UNPKG

@bitkyc08/opencodex

Version:

Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code

1,679 lines • 93.2 kB
#!/usr/bin/env node
import { guardedRun, guardedSpawn, guardedSpawnSync, guardedExit, probeProcessAlive, relayOwnSignal } from "../src/update/mutation-guard.mjs";
/**
 * opencodex published-package bin launcher.
 *
 * The package source is TypeScript that runs on the Bun runtime. To let
 * global npm and pnpm installs of `@bitkyc08/opencodex` work without a separately-installed Bun,
 * we bundle the runtime via the `bun` npm dependency and exec it from this
 * Node shim. (Dev still runs `bun run src/cli/index.ts` directly via the shebang on
 * src/cli/index.ts — only the published npm/pnpm `bin` routes through here.)
 */
import { probeSpawn, probeSpawnSync } from "../src/update/mutation-guard.mjs";
import { createSupervisionLatch, inspectDesktopSupervision } from "../src/service/desktop-supervision.mjs";
import { planDesktopCliHandoff, runDesktopCliHandoff } from "../src/lib/desktop-cli-handoff.mjs";
import { forwardLauncherSignals } from "../src/lib/launcher-signal-forwarding.mjs";
import { acquireSyncGuard, staleUpdateMarkerHint } from "../src/update/sync-update-mutex.mjs";
import { desktopCliRecordPath } from "../src/lib/desktop-cli-record.mjs";
import { STOP_HISTORY_INCOMPLETE_EXIT_CODE } from "../src/update/stop-contract.mjs";
import { probeProxyLiveness } from "../src/update/proxy-liveness-probe.mjs";
import { decidePostStopUpdate } from "../src/update/stop-decision.mjs";
import { createUpdateServiceHomePolicy, isUpdateHomeProbe, parseUpdateWorkerHome, UPDATE_HOME_LAUNCHER_PROTOCOL, UPDATE_PACKAGE_ONLY_EXIT_CODE, UPDATE_PACKAGE_ONLY_PROTOCOL_VERSION } from "../src/update/service-home-policy.mjs";
import { probeUpdateServiceHome, supportsUpdateHomeProbe, updateHomeProbeEnvironment } from "../src/update/service-home-probe.mjs";
import {
  inspectPackageRuntimeLiveness,
  planStoppedRuntimeRecovery,
  planUpdateRuntimeHandling,
} from "../src/update/runtime-ownership.mjs";
import {
  inspectInstallStateBytes,
  selectAuthoritativeServiceState,
  serviceStateFilesFor,
} from "../src/service/install-state-contract.mjs";
import {
  acquireOwnershipMutationLease,
  ownershipMutationLeaseChildEnvironment,
  unprivilegedOwnershipMutationEnvironment,
} from "../src/service/ownership-mutation-lease.mjs";
import { randomBytes } from "node:crypto";
import { createRequire } from "node:module";
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { isRealBunBinary } from "../src/lib/bun-binary-validator.mjs";
import { scopeTranspilerCacheToRuntime } from "../src/lib/bun-transpiler-cache-scope.mjs";
import { findDesktopCli, findPathBun } from "../src/lib/bun-path-runtime.mjs";
import { npmInvocation } from "../src/update/npm-invocation.mjs";
import { runNpmInstall, runWindowsInstallerSync } from "../src/update/npm-install.mjs";
import { runPosixInstallerSync } from "../src/update/posix-install-supervisor.mjs";
import { pnpmInvocationForPath, resolvePnpmCommands } from "../src/update/pnpm-invocation.mjs";
import { detectInstallOwnershipFromPath } from "../src/update/install-detection.mjs";
import { isOrchestratedUpdateArgv, parseOrchestratedUpdateArgs, parseOrchestratedChildArgs } from "../src/update/orchestrated-arguments.mjs";
import { createLegacyUpdateSession, createOrchestratedChildSession, decodeOrchestratedExpect } from "../src/update/orchestrated-session.mjs";
import { matchesOrchestratedPnpmOwner } from "../src/update/orchestrated-pnpm.mjs";
import { createUpdatePlanToken } from "../src/update/orchestrated-token.mjs";
import { applyNodeOrchestratedUpdate } from "../src/update/orchestrated-node-driver.mjs";
import {
  pnpmOwnerInvocation,
  resolvePnpmGlobalOwner,
  runPnpmGlobalUpdate,
} from "../src/update/pnpm-global-install.mjs";
import { PNPM_READ_CWD, withPnpmCommandCwd, pnpmReadEnvironment } from "../src/update/pnpm-read-policy.mjs";
import { checkRegistryPackageIntegrity } from "../src/update/registry-integrity.mjs";
import { hasPendingTeardownIn } from "../src/config/pending-teardown-names.mjs";
import {
  npmCachePreflightFailureMessage,
  resolveNpmCachePath,
  runNpmCachePreflight,
} from "../src/update/npm-cache-preflight.mjs";
import { handoffWindowsTrayForUpdate, planWindowsTrayUpdate } from "../src/update/tray-update-plan.mjs";
import { bootRestoreProbe, launcherUsableAfterNpmUpdate, transactionalNpmUpdate as transactionalNpmUpdateSync, transactionalNpmUpdateAsync } from "../src/update/transactional-install.mjs";
import { manualUpdateFailureGuidance, npmUpdateFailureGuidance } from "../src/update/update-failure-guidance.mjs";
import {
  captureCodexCliTransportEnv,
  CODEX_CLI_TRANSPORT_ENV_KEYS,
  CODEX_CLI_VERSION_MANAGER_ROOT_ENV_SLOTS,
  codexCliInspectionLookupSeeds,
  carriesCodexCliUpdateInspectionContext,
  isCodexCliUpdateInspectionArgv,
} from "../src/update/codex-cli-update-launch-policy.mjs";
import {
  freshServingPid, hasRestartableServiceManager, readParentPid, readServiceManagerPid, restartServiceManagerJob,
  supervisionVerdict, unsettledManagerWarning, unsupervisedRuntimeWarning,
} from "../src/update/supervised-recovery.mjs";

const PKG = "@bitkyc08/opencodex";
const UPDATE_RECOVERY_READY_MS = 30_000;
const UPDATE_RECOVERY_POLL_MS = 100;
const UPDATE_RECOVERY_SLEEP = new Int32Array(new SharedArrayBuffer(4));
try {
  process.cwd();
} catch {
  try {
    process.chdir(homedir());
  } catch {
    /* best-effort */
  }
}
const here = dirname(fileURLToPath(import.meta.url));
const installOwnership = detectInstallOwnershipFromPath(here, { exists: existsSync });
const installMethod = installOwnership.installer;
const cliPath = join(here, "..", "src", "cli", "index.ts");
const NODE_LAUNCH_CONTEXT_ENV = "OCX_NODE_LAUNCH_CONTEXT";
const NODE_LAUNCH_PROOF_PREFIX = "--ocx-internal-launch-proof=";

function isNodeModulesInstall() {
  return here.split(/[\\/]/).includes("node_modules");
}

function isBunGlobalInstall() {
  return installMethod === "bun";
}

function currentPackageVersion() {
  try {
    return JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8")).version ?? "?";
  } catch {
    return "?";
  }
}

function pinnedBunVersion(launcherPath) {
  try {
    const pkg = JSON.parse(readFileSync(join(launcherPath ? dirname(launcherPath) : here, "..", "package.json"), "utf8"));
    return typeof pkg.dependencies?.bun === "string" ? pkg.dependencies.bun : "";
  } catch {
    return "";
  }
}

function updateTag(currentVersion) {
  // Allowlist the tag: the value is argv-controlled and (on Windows) flows into a
  // shell-joined spawnSync — never forward arbitrary strings.
  const tagIndex = process.argv.indexOf("--tag");
  const explicit = tagIndex !== -1 ? process.argv[tagIndex + 1] : undefined;
  if (explicit === "preview" || explicit === "latest") return explicit;
  return String(currentVersion).includes("-preview.") ? "preview" : "latest";
}

function expandUserPath(raw) {
  // Mirror src/config.ts expandUserPath — the Bun proxy expands `~`, so this launcher's
  // pid/state gates must resolve the same directory or they silently check the wrong path.
  if (raw === "~") return homedir();
  if (raw.startsWith("~/") || raw.startsWith("~\\")) return join(homedir(), raw.slice(2));
  return raw;
}

function configDir() {
  const raw = process.env.OPENCODEX_HOME?.trim();
  return resolve(raw ? expandUserPath(raw) : join(homedir(), ".opencodex"));
}

// Direct Bun entry only: never recurse through another Node launcher or ordinary CLI startup.
function readNodeUpdateHome(launcherPath) {
  if (!supportsUpdateHomeProbe(launcherPath)) return { kind: "unknown" };
  const bun = resolveBun({ allowInstall: false, launcherPath, allowMissing: true });
  if (!bun) return { kind: "unknown" };
  const env = updateHomeProbeEnvironment(process.env, {
    codexHome: process.env.CODEX_HOME ?? "", opencodexHome: configDir(),
  });
  return probeUpdateServiceHome(probeSpawnSync, bun.path,
    ["--no-env-file", join(dirname(launcherPath), "..", "src", "update", "service-home-probe-entry.ts")], { env });
}


function shouldRepairCodexShim() {
  return existsSync(join(configDir(), "codex-shim.json"));
}

function historyRestoreIncomplete() {
  // Mirror src/update/index.ts historyRestoreIncomplete — a codex-history-backup-*.json surviving
  // a stop means the native-history restore was skipped (locked state DB).
  try {
    return readdirSync(configDir()).some(
      name => name.startsWith("codex-history-backup-") && name.endsWith(".json"),
    );
  } catch {
    return false;
  }
}

function repairCodexShimIfNeeded(launcherPath, authorizeMutation) {
  if (!shouldRepairCodexShim()) return;
  if (!authorizeMutation("shim")) return false;
  const res = guardedSpawnSync(authorizeMutation, "shim", process.execPath, [launcherPath, "codex-shim", "install"], {
    stdio: "inherit",
    windowsHide: true,
  });
  if (res.status !== 0) {
    console.warn(`opencodex: Codex shim repair failed (${res.status ?? "unknown exit"}). Try: ocx codex-shim install`);
  }
}

function trayInstallState() {
  const statePath = join(configDir(), "tray-state.json");
  if (!existsSync(statePath)) return { installed: false, running: false };
  let running = false;
  try {
    const heartbeat = JSON.parse(readFileSync(join(configDir(), "tray-heartbeat.json"), "utf8"));
    if (Number.isSafeInteger(heartbeat.pid) && Date.now() - Number(heartbeat.timestamp) < 15_000) {
      probeProcessAlive(heartbeat.pid);
      running = true;
    }
  } catch { /* installed but not running */ }
  return { installed: true, running };
}

function runTrayLifecycle(launcher, action, authorizeMutation) {
  if (!authorizeMutation(action === "start" ? "own-tray" : "tray")) return { status: 1 };
  return guardedSpawnSync(authorizeMutation, action === "start" ? "own-tray" : "tray", process.execPath, [launcher, "tray", action], {
    stdio: "inherit",
    windowsHide: true,
  });
}

function shellQuote(value) {
  if (process.platform === "win32") return `"${value.replaceAll("\"", "\\\"")}"`;
  return `'${value.replaceAll("'", "'\\''")}'`;
}

function launcherStartHint(launcher, port) {
  return `${shellQuote(process.execPath)} ${shellQuote(launcher)} start --port ${Math.trunc(port)}`;
}

function runNpmSelfUpdate() {
  return runPackageManagerSelfUpdate("npm");
}

function runPnpmSelfUpdate() {
  return runPackageManagerSelfUpdate("pnpm");
}

function runningPnpmShimPath() {
  const invoked = process.argv[1];
  if (!invoked) return undefined;
  const name = invoked.replaceAll("\\", "/").split("/").at(-1)?.toLowerCase();
  if (!new Set(["ocx", "opencodex", "ocx.cmd", "opencodex.cmd", "ocx.ps1", "opencodex.ps1"]).has(name ?? "")) {
    return undefined;
  }
  return resolve(invoked);
}

async function runPackageManagerSelfUpdate(manager, child) {
  let session, enteredMutation = false, owner, resolveOwner;
  let childOutcome = { phase: "failed", rollbackPerformed: false };
  if (child) {
    try {
      const expected = decodeOrchestratedExpect(child.expect);
      session = createOrchestratedChildSession({ home: configDir(), resultPath: child.resultPath, resultCapability: child.resultCapability, expect: expected,
        notAfter: child.notAfter, verifyIdentity: () => {
          if (manager === "pnpm") {
            if (!matchesOrchestratedPnpmOwner(expected.pnpmOwner, owner)) return false;
            const currentOwner = resolveOwner([owner.commandPath]);
            if (!currentOwner.ok || !matchesOrchestratedPnpmOwner(expected.pnpmOwner, currentOwner.owner)) return false;
          } else if (expected.pnpmOwner !== undefined) return false;
          const bun = resolveBun({ allowInstall: false, allowMissing: true });
          if (!bun) return false;
          const probe = probeSpawnSync(bun.path, ["--no-env-file", join(here, "../src/update/orchestrated-identity-probe-entry.ts"), "__update-orchestrated-identity"], {
            encoding: "utf8", timeout: 8000, maxBuffer: 8192, windowsHide: true, stdio: ["ignore", "pipe", "ignore"],
            env: { ...updateHomeProbeEnvironment(process.env, { codexHome: process.env.CODEX_HOME ?? "", opencodexHome: configDir() }),
              OCX_IDENTITY_CLI_ROOT: resolve(here, ".."), OCX_IDENTITY_INSTALLER: manager, OCX_IDENTITY_TARGET: child.version },
          });
          if (probe.status !== 0 || probe.error || probe.signal || typeof probe.stdout !== "string") return false;
          const observed = JSON.parse(probe.stdout);
          return observed.permits === true && observed.cliRoot === expected.cliRoot && observed.planToken === expected.planToken
            && (observed.kind === "absent" ? expected.servingRoot === null && expected.runtimePid === null
              : observed.kind === "live" && observed.servingRoot === expected.servingRoot && observed.runtime?.pid === expected.runtimePid);
        } });
      if (!session.start().ok) process.exit(10);
      // The parent may forward a signal while a synchronous installer is running. Keep the
      // owner alive through its transaction and recovery so the mutex cannot outlive us.
      for (const signal of ["SIGINT", "SIGTERM", ...(process.platform === "win32" ? [] : ["SIGHUP"])]) process.on(signal, () => {});
      process.once("exit", () => {
        try { if (enteredMutation) session.finish(childOutcome); else session.finishPreflight(); }
        catch (error) { console.error(`Orchestrated outcome write failed: ${error?.message ?? error}`); process.exitCode = 1; }
      });
    } catch (error) {
      console.error(`Orchestrated update preflight failed: ${error?.message ?? error}`);
      process.exit(1);
    }
  } else {
    session = createLegacyUpdateSession({ home: configDir() });
    const started = session.start();
    if (!started.ok) {
      console.error(`opencodex: ${started.error}`);
      if (started.staleMarker) for (const line of staleUpdateMarkerHint(configDir())) console.error(line);
      process.exit(1);
    }
    process.once("exit", () => {
      try { if (enteredMutation) session.finish(childOutcome); else session.finishPreflight(); }
      catch (error) { console.error(`Update outcome write failed: ${error?.message ?? error}`); process.exitCode = 1; }
    });
  }
  const current = currentPackageVersion();
  const tag = updateTag(current);
  if (manager === "pnpm") {
    resolveOwner = commandPaths => resolvePnpmGlobalOwner({
      packageName: PKG,
      packagePath: resolve(here, ".."),
      commandPaths,
      runningShimPath: runningPnpmShimPath(),
      runPnpm: (commandPath, args, capture = false, owner) => {
        const invocation = owner ? pnpmOwnerInvocation(owner, args) : pnpmInvocationForPath(commandPath, args);
        if (!invocation) return { status: 1 };
        return withPnpmCommandCwd(args, cwd => probeSpawnSync(invocation.file, invocation.args, {
          stdio: capture ? "pipe" : "ignore",
          encoding: "utf8",
          timeout: 20_000,
          windowsHide: true,
          cwd,
          env: pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(invocation.env ?? process.env)),
          ...invocation.options,
        }));
      },
    });
    const ownerResult = resolveOwner(resolvePnpmCommands());
    if (!ownerResult.ok) {
      console.error(`opencodex: ${ownerResult.reason}; aborting before stopping the proxy.`);
      process.exit(1);
    }
    owner = ownerResult.owner;
  }
  const managerInvocation = args => manager === "pnpm"
    ? pnpmOwnerInvocation(owner, args)
    : npmInvocation(args);
  // Read-only pnpm probes run from the installed package directory with project pnpmfiles
  // disabled, so an attacker-controlled cwd cannot execute hooks during the update check.
  const readProbeOptions = invocation => ({
    encoding: "utf8",
    timeout: 12000,
    windowsHide: true,
    ...(manager === "pnpm"
      ? {
        cwd: PNPM_READ_CWD,
        env: pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(invocation.env ?? process.env)),
      }
      : invocation.env ? { env: invocation.env } : {}),
    ...invocation.options,
  });
  const selector = child?.version ?? tag;
  const latestInvocation = managerInvocation(["view", `${PKG}@${selector}`, "version"]);
  const installArgs = manager === "pnpm"
    ? ["add", "-g", "--allow-build=bun", `${PKG}@${selector}`]
    : ["install", "-g", "--allow-scripts=bun", `${PKG}@${selector}`];
  const installInvocation = managerInvocation(installArgs);
  if (!latestInvocation || !installInvocation) {
    console.error(`opencodex: could not resolve ${manager} from a trusted absolute PATH entry; aborting before stopping the proxy.`);
    process.exit(1);
  }
  const latestResult = probeSpawnSync(latestInvocation.file, latestInvocation.args, readProbeOptions(latestInvocation));
  const latest = child?.version ?? (latestResult.status === 0 && typeof latestResult.stdout === "string" ? latestResult.stdout.trim() : "");

  console.log(`opencodex v${current} (installed via ${manager}, tag ${tag})`);
  if (latest && latest === current) {
    console.log(`Already on the latest ${tag} version (v${latest}).`);
    process.exit(0);
  }

  const integrity = checkRegistryPackageIntegrity(PKG, latest || null, args => {
    const invocation = managerInvocation(args);
    if (!invocation) return { status: 1 };
    return probeSpawnSync(invocation.file, invocation.args, readProbeOptions(invocation));
  });
  if (integrity.ok === false) {
    console.error(`opencodex: ${integrity.reason}; aborting before stopping the proxy.`);
    process.exit(1);
  }
  if (integrity.ok === "skipped") {
    console.warn(`opencodex: integrity pre-flight skipped: ${integrity.reason}. Proceeding best-effort.`);
  } else {
    console.log(`Verified ${PKG}@${latest} integrity metadata ${integrity.integrity.slice(0, 24)}…`);
  }

  // The cache root is resolved once, with the environment staging uses, then checked and pinned:
  // the stage installs with exactly the root this pre-flight inspected (#6288).
  let npmCachePath;
  if (manager === "npm") {
    const npmCache = resolveNpmCachePath({ env: unprivilegedOwnershipMutationEnvironment(process.env) });
    // Windows skipped this gate before #6288: an unresolvable npm cache path keeps that behavior
    // there (no check, no pin) and only a confirmed broken root aborts the update.
    const cachePreflight = npmCache.ok
      ? runNpmCachePreflight({ cachePath: npmCache.path })
      : process.platform === "win32" ? { ok: true, reason: "windows_skip" } : npmCache;
    if (!cachePreflight.ok) {
      console.error(`opencodex: ${npmCachePreflightFailureMessage(cachePreflight.reason)}. Aborting before stopping the proxy.`);
      process.exit(1);
    }
    npmCachePath = npmCache.path;
  }

  // Remember whether a background service manages the proxy BEFORE stopping — `ocx stop`
  // unloads it, so a successful update must refresh and restart it afterwards.
  const allServiceStatePaths = serviceStateFilesFor(configDir(), join(homedir(), ".opencodex"));
  // The test guard's legacy path is the developer's real home. Production always reads the
  // same active-home + default-home observations as the Bun resolver.
  const serviceStatePaths = process.env.OCX_TEST_HOME_GUARD === "1"
    ? allServiceStatePaths.slice(0, 1)
    : allServiceStatePaths;
  let authorityLauncher = fileURLToPath(import.meta.url);
  const homePolicy = createUpdateServiceHomePolicy(() => readNodeUpdateHome(authorityLauncher), message => console.warn(message), process.argv.includes("--update-package-only"), parseUpdateWorkerHome(process.argv));
  if (!homePolicy.authorizeMutation("package")) process.exit(1);
  const serviceWasInstalled = homePolicy.serviceAllowed && serviceStatePaths.some(path => existsSync(path));
  // What this update may do to the runtime. The same rule the Bun updater applies, from the
  // same module: a desktop takeover vetoes both the stop and the service refresh below.
  const readServiceState = () => selectAuthoritativeServiceState(
    serviceStatePaths.map(path => inspectInstallStateBytes(path, at => readFileSync(at, "utf8"))),
  );
  const readOwnership = () => {
    const selected = readServiceState();
    if (selected.kind === "unknown") return { ownership: null, ownershipUnknown: true, subjectToken: "unknown" };
    if (selected.kind === "none") return {
      ownership: null, ownershipUnknown: false, subjectToken: JSON.stringify(["none", selected.revision]),
    };
    const ownership = selected.state.ownership ?? null;
    return {
      ownership,
      ownershipUnknown: false,
      subjectToken: JSON.stringify(ownership
        ? ["owned", selected.revision, ownership]
        : ["none", selected.revision]),
    };
  };
  const ownershipIdentity = observation => observation.ownershipUnknown
    ? null
    : JSON.stringify(observation.ownership
      ? ["owned", observation.ownership.owner, observation.ownership.installId, observation.ownership.consentGeneration]
      : ["none"]);
  const supervisionLatch = createSupervisionLatch();
  const observeSupervision = () => supervisionLatch.observe(inspectDesktopSupervision());
  const initialOwnership = readOwnership();
  let runtimePlan = planUpdateRuntimeHandling({ ...initialOwnership, serviceInstalled: serviceWasInstalled, supervision: observeSupervision() });
  if (runtimePlan.notice) console.log(runtimePlan.notice);
  if (!runtimePlan.mayReplacePackage) {
    console.error("opencodex: update stopped before tray handoff, runtime stop, or package replacement because runtime authority does not permit it.");
    process.exit(1);
  }
  const trayBeforeUpdate = planWindowsTrayUpdate(
    !homePolicy.packageOnly && process.platform === "win32" ? trayInstallState() : { installed: false, running: false },
  );
  /**
   * Refresh the existing service in place. `service repair` discovers the installed backend;
   * healthy Windows scheduler registrations avoid `schtasks /create`, while stale definitions
   * may be re-registered and require elevation.
   */
  function serviceRefreshArgs() {
    return [postUpdateLauncher, "service", "repair"];
  }
  /** Register from scratch, preserving the recorded backend. Only for a genuinely absent service. */
  function serviceInstallArgs() {
    const selected = readServiceState();
    if (selected.kind === "unknown") throw new Error(`service backend is unknown: ${selected.reason}`);
    if (selected.kind === "state" && selected.state.backend === "native") {
      return [postUpdateLauncher, "service", "install", "--native"];
    }
    return [postUpdateLauncher, "service", "install"];
  }
  /**
   * Structured "is a service actually registered?" answer.
   *
   * This file is plain Node ESM and cannot import `diagnoseService()` from the
   * TypeScript runtime, so it asks the freshly-installed launcher — which runs that
   * diagnostic under Bun — and reads `startup.serviceInstalled`.
   *
   * Returns `null` when the probe itself could not answer, which callers must treat as
   * "unknown" rather than "absent": failing closed here means NOT re-registering.
   */
  function readServiceInstalledFromStatus(launcherPath) {
    try {
      const st = probeSpawnSync(process.execPath, [launcherPath, "status", "--json"], {
        encoding: "utf8",
        timeout: 20_000,
        windowsHide: true,
      });
      if (st.status !== 0 || typeof st.stdout !== "string" || !st.stdout.trim()) return null;
      const installed = JSON.parse(st.stdout)?.startup?.serviceInstalled;
      return typeof installed === "boolean" ? installed : null;
    } catch {
      return null;
    }
  }

  function readCurrentRuntimeTarget() {
    let raw;
    try {
      raw = readFileSync(join(configDir(), "runtime-port.json"), "utf8");
    } catch (error) {
      return error && typeof error === "object" && "code" in error && error.code === "ENOENT"
        ? { kind: "absent" }
        : { kind: "unknown" };
    }
    try {
      const rt = JSON.parse(raw);
      const pid = Number(rt?.pid);
      if (!Number.isFinite(rt?.port) || rt.port <= 0 || rt.port > 65535
        || !Number.isSafeInteger(pid) || pid <= 0) return { kind: "unknown" };
      return { kind: "target", target: {
        pid,
        port: Math.trunc(rt.port),
        hostname: typeof rt.hostname === "string" && rt.hostname.trim() !== ""
          ? rt.hostname.trim()
          : null,
      } };
    } catch { return { kind: "unknown" }; }
  }

  // Capture the recovery target before stop clears runtime-port.json. Replacement safety
  // re-reads this record under the mutation lease instead of trusting this snapshot.
  let bakePort = 10100;
  // The hostname travels with the port: a proxy bound to ::1 or a specific interface is
  // invisible to a probe that assumes 127.0.0.1, and "no answer" would then read as
  // "stopped" for exactly the proxy the probe exists to find.
  let bakeHostname = "127.0.0.1";
  const initialRuntimeObservation = readCurrentRuntimeTarget();
  const initialRuntimeTarget = initialRuntimeObservation.kind === "target" ? initialRuntimeObservation.target : null;
  let sawRuntimePort = initialRuntimeTarget !== null;
  let sawRuntimeHostname = initialRuntimeTarget?.hostname !== null && initialRuntimeTarget?.hostname !== undefined;
  if (initialRuntimeTarget) {
    bakePort = initialRuntimeTarget.port;
    if (initialRuntimeTarget.hostname) bakeHostname = initialRuntimeTarget.hostname;
  }
  // Port and hostname resolve INDEPENDENTLY: a legacy runtime record carries a port and no
  // hostname, and skipping config in that case probed 127.0.0.1 for a proxy bound to ::1.
  if (!sawRuntimePort || bakeHostname === "127.0.0.1") {
    try {
      const cfg = JSON.parse(readFileSync(join(configDir(), "config.json"), "utf8"));
      if (!sawRuntimePort && Number.isFinite(cfg?.port) && cfg.port > 0 && cfg.port <= 65535) {
        bakePort = Math.trunc(cfg.port);
      }
      if (!sawRuntimeHostname && typeof cfg?.hostname === "string" && cfg.hostname.trim() !== "") {
        bakeHostname = cfg.hostname.trim();
      }
    } catch { /* keep default */ }
  }
  // Wildcard and bracketed-IPv6 normalization lives in probeProxyLiveness, so both lanes
  // get it from one place.
  function currentPackageRuntimeLiveness() {
    return inspectPackageRuntimeLiveness({
      capturedTarget: { port: bakePort, hostname: bakeHostname },
      readCurrentTarget: () => {
        const current = readCurrentRuntimeTarget();
        return current.kind === "target"
          ? { kind: "target", target: { port: current.target.port, hostname: current.target.hostname ?? bakeHostname } }
          : current;
      },
      probe: target => probeProxyLiveness(target.port, target.hostname),
    }).overall;
  }

  const launcher = fileURLToPath(import.meta.url);
  // The pnpm owner preflight has verified this package tree and global group. Keep that exact
  // package path as the recovery starting point; a path returned by the pnpm transaction
  // replaces it only after the new tree and shims have been verified.
  let postUpdateLauncher = manager === "pnpm" && owner
    ? join(owner.packagePath, "bin", "ocx.mjs")
    : launcher;
  let postUpdateLauncherUsable = true;
  let delegatedOwnershipMutationToken = null;
  const mutationChildEnvironment = () => delegatedOwnershipMutationToken
    ? ownershipMutationLeaseChildEnvironment(process.env, delegatedOwnershipMutationToken)
    : unprivilegedOwnershipMutationEnvironment(process.env);

  /** Returns true, false, or "vetoed" when another owner holds the runtime (not a failure). */
  function startProxyDirectly() {
    try { reacquireUpdateLease(); } catch {
      console.warn("opencodex: recovery could not acquire runtime ownership; run 'ocx service repair' or 'ocx start' manually after the other operation finishes.");
      return false;
    }
    if (!homePolicy.authorizeMutation("runtime")) return "refused";
    const currentOwnership = readOwnership();
    const supervision = observeSupervision();
    const plan = planUpdateRuntimeHandling({ ...currentOwnership, serviceInstalled: false, supervision });
    if (!homePolicy.authorizeMutation("runtime")) return "refused";
    if (ownershipIdentity(currentOwnership) !== ownershipIdentity(initialOwnership) || !plan.mayStopRuntime) {
      console.warn(supervision
        ? "OpenCodex Desktop supervises the proxy; no CLI runtime was restored."
        : plan.notice);
      return homePolicy.authorizeMutation("publish") ? "vetoed" : "refused";
    }
    if (!postUpdateLauncherUsable || !existsSync(postUpdateLauncher)) {
      console.error("opencodex: cannot restart the proxy because the launcher is missing; reinstall opencodex manually.");
      return false;
    }
    const env = mutationChildEnvironment();
    delete env.OCX_SERVICE;
    // Not launched by a supervisor: none of its markers (src/lib/supervisor-markers.ts) may ride along.
    for (const name of ["OCX_DESKTOP_SUPERVISED", "OCX_SERVICE_MANAGED", "OCX_WINDOWS_WRAPPER_PROTOCOL"]) delete env[name];
    // The restarted proxy is an ordinary owner; only a sibling's own replacement carries this.
    delete env.OCX_SIBLING_OF_PORT;
    delete env.OCX_SIBLING_HANDOFF_NONCE;
    console.log(`Attempting to restart the proxy on port ${bakePort}.`);
    if (!homePolicy.authorizeMutation("runtime")) return "refused";
    const child = guardedSpawn(homePolicy.authorizeMutation, "runtime", process.execPath, [postUpdateLauncher, "start", "--port", String(bakePort)], {
      detached: true,
      stdio: "ignore",
      windowsHide: true,
      env,
    });
    child.on("error", error => {
      console.error(`opencodex: direct proxy restart failed: ${error.message}`);
    });
    child.unref();
    const deadline = Date.now() + UPDATE_RECOVERY_READY_MS;
    while (Date.now() < deadline) {
      const current = readCurrentRuntimeTarget();
      if (current.kind === "target"
        && probeProxyLiveness(current.target.port, current.target.hostname ?? bakeHostname) === "live") return homePolicy.authorizeMutation("publish") ? true : "refused";
      Atomics.wait(UPDATE_RECOVERY_SLEEP, 0, 0, UPDATE_RECOVERY_POLL_MS);
    }
    console.error("opencodex: the recovery proxy did not publish a healthy runtime before the recovery deadline.");
    return false;
  }

  // #7043: before any detached start, ask launchd/systemd to restart the job it already holds,
  // and count it only when the serving proxy is that job (or its launcher's child). Returns
  // "supervised", "failed", or "unsettled" when the manager may still finish the restart.
  function restartThroughServiceManager() {
    if (!hasRestartableServiceManager()) return "failed";
    releaseUpdateLease();
    if (!homePolicy.authorizeMutation("runtime")) return "refused";
    if (!homePolicy.serviceAllowed) return "failed";
    const owner = readOwnership();
    if (!homePolicy.authorizeMutation("runtime")) return "refused";
    if (ownershipIdentity(owner) !== ownershipIdentity(initialOwnership)
      || !planUpdateRuntimeHandling({ ...owner, serviceInstalled: true, supervision: observeSupervision() }).mayRestoreService) return homePolicy.authorizeMutation("publish") ? "vetoed" : "refused";
    console.log("opencodex: asking the service manager to restart the background service.");
    const before = readCurrentRuntimeTarget();
    const staleRecordPid = before.kind === "target" ? before.target.pid : null;
    if (!homePolicy.authorizeMutation("service")) return homePolicy.authorizeMutation("runtime") ? "failed" : "refused";
    const restarted = restartServiceManagerJob({}, homePolicy.authorizeMutation);
    if (!restarted.ok && restarted.refused) return "refused";
    const unsettled = !restarted.ok && restarted.unsettled === true;
    let verdict;
    if (!restarted.ok && !unsettled) {
      verdict = { kind: "failed", reason: restarted.reason };
    } else {
      let servingPid = null;
      const deadline = Date.now() + UPDATE_RECOVERY_READY_MS;
      while (servingPid === null && Date.now() < deadline) {
        const current = readCurrentRuntimeTarget();
        if (current.kind === "target" && current.target.port === bakePort
          && freshServingPid(current.target.pid, staleRecordPid) !== null
          && probeProxyLiveness(current.target.port, current.target.hostname ?? bakeHostname) === "live") {
          servingPid = current.target.pid;
        } else {
          Atomics.wait(UPDATE_RECOVERY_SLEEP, 0, 0, UPDATE_RECOVERY_POLL_MS);
        }
      }
      verdict = supervisionVerdict({ servingPid, managerPid: readServiceManagerPid(), parentPid: pid => readParentPid(pid) });
    }
    if (verdict.kind === "supervised") {
      if (!homePolicy.authorizeMutation("publish")) return "refused";
      guardedRun(homePolicy.authorizeMutation, "publish", console.log, [`opencodex: the proxy is healthy on port ${bakePort} under the service manager (pid ${verdict.managerPid}).`]);
      return "supervised";
    }
    if (unsettled) {
      console.warn(unsettledManagerWarning(bakePort));
      return "unsettled";
    }
    console.warn(`opencodex: the service manager did not recover a supervised proxy: ${verdict.reason}.`);
    return "failed";
  }

  /**
   * Returns "unsupervised" when only a detached fallback was attempted, or "unsettled" when the
   * manager may still finish its restart; callers exit non-zero for both.
   */
  function refreshBackgroundServiceOrStartDirect() {
    authorityLauncher = postUpdateLauncher;
    if (!homePolicy.authorizeMutation("runtime")) return "refused";
    if (!homePolicy.serviceAllowed) return [true, "vetoed"].includes(startProxyDirectly()) ? undefined : "refused";
    let homeRefused = false;
    const mayRefresh = () => {
      if (!homePolicy.authorizeMutation("runtime")) { homeRefused = true; return false; }
      const supervision = observeSupervision();
      const plan = planUpdateRuntimeHandling({ ...readOwnership(), serviceInstalled: true, supervision });
      if (!homePolicy.authorizeMutation("runtime")) { homeRefused = true; return false; }
      if (!plan.mayRestoreService) console.warn(supervision
        ? "OpenCodex Desktop supervises the proxy; CLI recovery was skipped. Use the app's updater (tray → Check for Updates)."
        : plan.notice);
      return plan.mayRestoreService && homePolicy.serviceAllowed;
    };
    if (!mayRefresh()) {
      if (homeRefused) return "refused";
      if (!homePolicy.serviceAllowed) return [true, "vetoed"].includes(startProxyDirectly()) ? undefined : "refused";
      return;
    }
    const prevBake = process.env.OCX_BAKE_PORT;
    process.env.OCX_BAKE_PORT = String(bakePort);
    try {
      if (!homePolicy.authorizeMutation("service")) return homePolicy.authorizeMutation("runtime") && [true, "vetoed"].includes(startProxyDirectly()) ? undefined : "refused";
      let svc = guardedSpawnSync(homePolicy.authorizeMutation, "service", process.execPath, serviceRefreshArgs(), {
        stdio: "inherit", windowsHide: true, env: mutationChildEnvironment(),
      });
      if (!homePolicy.authorizeMutation("runtime")) return "refused";
      if (!homePolicy.serviceAllowed) return [true, "vetoed"].includes(startProxyDirectly()) ? undefined : "refused";
      // `serviceWasInstalled` is inferred from service-state.json alone, which can be
      // STALE — present while the registration is gone. Repair refuses that case by
      // design, and its thrown Error is indistinguishable from any other failure at
      // this layer (plain Error, inherited stdio, generic exit status). So ask for
      // structured state instead of parsing the failure: install only when the
      // diagnostic says the service is genuinely absent. Installing after ANY repair
      // failure would resurrect the elevation prompt this change exists to avoid, and
      // could re-register a service the user just uninstalled.
      if (svc.status !== 0 && readServiceInstalledFromStatus(postUpdateLauncher) === false) {
        if (!mayRefresh()) {
          if (homeRefused) return "refused";
          if (!homePolicy.serviceAllowed) return [true, "vetoed"].includes(startProxyDirectly()) ? undefined : "refused";
          return;
        }
        console.log("No registered service found — installing it instead.");
        const serviceInstallArgsForSpawn = serviceInstallArgs();
        if (!homePolicy.authorizeMutation("service")) return homePolicy.authorizeMutation("runtime") && [true, "vetoed"].includes(startProxyDirectly()) ? undefined : "refused";
        svc = guardedSpawnSync(homePolicy.authorizeMutation, "service", process.execPath, serviceInstallArgsForSpawn, {
          stdio: "inherit", windowsHide: true, env: mutationChildEnvironment(),
        });
        if (!homePolicy.authorizeMutation("runtime")) return "refused";
      }
      let needDirectStart = svc.status !== 0;
      if (!needDirectStart) {
        // Exit 0 can still leave stale/missing assets that never bring the proxy
        // back — match the GUI/CLI fallthrough so /healthz is not left dead.
        try {
          const st = probeSpawnSync(process.execPath, [postUpdateLauncher, "status", "--json"], {
            encoding: "utf8",
            timeout: 20_000,
            windowsHide: true,
          });
          if (st.status === 0 && typeof st.stdout === "string" && st.stdout.trim()) {
            const parsed = JSON.parse(st.stdout);
            const proxyUp = parsed?.proxy?.running === true || parsed?.proxy?.health?.ok === true;
            const viable = parsed?.startup?.serviceViable === true;
            if (!proxyUp && !viable) needDirectStart = true;
          } else {
            // status failed or empty — fail closed to direct start (match CLI).
            needDirectStart = true;
          }
        } catch {
          needDirectStart = true;
        }
      }
      if (needDirectStart) {
        // Re-read rather than reuse the plan from before the package install: the app can
        // claim the runtime during an update that takes minutes, and the refusal that repair
        // just returned is indistinguishable from any other failure at this layer.
        const supervision = observeSupervision();
        const nowOwned = planUpdateRuntimeHandling({ ...readOwnership(), serviceInstalled: true, supervision });
        if (!homePolicy.authorizeMutation("runtime")) return "refused";
        if (!nowOwned.mayStopRuntime) {
          console.warn(supervision
            ? "OpenCodex Desktop supervises the proxy; CLI recovery was skipped. Use the app's updater (tray → Check for Updates)."
            : nowOwned.notice ?? "opencodex: the background runtime is owned elsewhere; not starting a second proxy.");
          return;
        }
        // #7043: the manager first. Only a proxy it owns counts as recovered.
        if (!homePolicy.authorizeMutation("runtime")) return "refused";
        const managed = restartThroughServiceManager();
        if (managed === "supervised" || managed === "vetoed") return;
        if (managed === "unsettled") return "unsettled";
        if (managed === "refused") return "refused";
        // Repair normally avoids elevation for a healthy registration, but a stale Windows
        // scheduler definition can require it. It can also fail — or exit 0 while leaving
        // a non-viable manager. Fall back to a direct detached proxy start so the
        // update never leaves the user without a running proxy.
        console.warn(
          svc.status === 0
            ? "opencodex: service refresh left a non-viable manager — starting the proxy directly instead."
            : "opencodex: service refresh failed — starting the proxy directly instead.",
        );
        console.warn("  Run 'ocx service repair' to see why the background service could not restart.");
        const started = startProxyDirectly();
        // An ownership veto is the correct outcome, not a degraded one.
        if (started === "vetoed") return;
        if (started === "refused") return "refused";
        if (started) console.warn(unsupervisedRuntimeWarning(bakePort));
        return "unsupervised";
      }
    } finally {
      if (prevBake === undefined) delete process.env.OCX_BAKE_PORT;
      else process.env.OCX_BAKE_PORT = prevBake;
    }
  }

  let updateLease = acquireOwnershipMutationLease(serviceStatePaths);
  delegatedOwnershipMutationToken = updateLease.token;
  let updateLeaseReleased = false;
  const releaseUpdateLease = () => {
    if (updateLeaseReleased) return;
    updateLeaseReleased = true;
    delegatedOwnershipMutationToken = null;
    updateLease.release();
  };
  const reacquireUpdateLease = () => {
    if (!updateLeaseReleased) return;
    updateLease = acquireOwnershipMutationLease(serviceStatePaths);
    updateLeaseReleased = false;
    delegatedOwnershipMutationToken = updateLease.token;
  };

  let res;
  let stopAttempted = false;
  let npmFailure = null;
  try {
    // Stop authority is decided under the same lease the child joins. A takeover between the
    // earlier preflight and this boundary therefore blocks stop before it is sent.
    const lockedOwnership = readOwnership();
    const lockedPlan = planUpdateRuntimeHandling({ ...lockedOwnership, serviceInstalled: serviceWasInstalled, supervision: observeSupervision() });
    if (!homePolicy.authorizeMutation("package") || lockedOwnership.subjectToken !== initialOwnership.subjectToken || !lockedPlan.mayReplacePackage) {
      releaseUpdateLease();
      console.error(lockedPlan.notice
        ?? "opencodex: update stopped because runtime ownership changed before stop authorization; rerun from the beginning.");
      process.exit(1);
    }
    runtimePlan = lockedPlan;
    const stoppedOwnershipIdentity = ownershipIdentity(lockedOwnership);

    if (session) {
      const entered = await session.enterMutation();
      if (!entered.ok) { releaseUpdateLease(); process.exit(10); }
      enteredMutation = true;
    }

    // Never replace package files under a live proxy — stop it first (full `ocx stop`
    // semantics: graceful drain, service stop, native Codex restore). Gate on the service
    // and the runtime-port record too: a service-managed or orphaned proxy can be live
    // while ocx.pid is stale/missing.
    if (!homePolicy.packageOnly && trayBeforeUpdate.stopBeforeReplacement) {
      console.log("⏹  Handing off the Windows tray before updating...");
      try {
        if (!homePolicy.authorizeMutation("tray")) { releaseUpdateLease(); process.exit(1); }
        let stopAttempted = false;
        handoffWindowsTrayForUpdate(trayBeforeUpdate, {
          stop: () => {
            if (!homePolicy.authorizeMutation("tray")) throw new Error("Automatic update tray handoff refused.");
            stopAttempted = true;
            const stopped = runTrayLifecycle(launcher, "stop", homePolicy.authorizeMutation);
            return { exitStatus: stopped.status, running: trayInstallState().running };
          },
          start: () => { if (stopAttempted && homePolicy.authorizeMutation("own-tray")) return runTrayLifecycle(launcher, "start", homePolicy.authorizeMutation); },
        });
      } catch {
        releaseUpdateLease();
        console.error("opencodex: could not stop the Windows tray; aborting before package replacement.");
        process.exit(1);
      }
    }
    const hasRuntimeState =
      existsSync(join(configDir(), "ocx.pid")) || existsSync(join(configDir(), "runtime-port.json"));

    function recoverStoppedRuntimeAfterFailure(reason) {
      authorityLauncher = postUpdateLauncher;
      if (!homePolicy.authorizeMutation("runtime")) return;
      const planRecovery = () => {
        const recoveryOwnership = readOwnership();
        const liveness = currentPackageRuntimeLiveness();
        return {
          liveness,
          plan: planStoppedRuntimeRecovery({
            stopAttempted,
            supervision: observeSupervision(),
            ...recoveryOwnership,
            sameOwner: ownershipIdentity(recoveryOwnership) === stoppedOwnershipIdentity,
            liveness,
            serviceInstalled: serviceWasInstalled,
            launcherUsable: postUpdateLauncherUsable,
            hadRuntimeState: hasRuntimeState,
          }),
        };
      };
      let { liveness: recoveryLiveness, plan: recovery } = planRecovery();
      if (recovery.action === "service") {
        // The service manager starts the proxy outside this process tree, so it cannot join this
        // lease, and holding the lease through the repair's health wait keeps that proxy from
        // starting (#5760). Release it as the successful path does, then decide again.
        releaseUpdateLease();
        if (!homePolicy.authorizeMutation("runtime")) return;
        ({ liveness: recoveryLiveness, plan: recovery } = planRecovery());
      }
      if (recovery.reason === "desktop-supervised") {
        console.log("OpenCodex Desktop supervises the proxy; no CLI runtime was restored.");
      } else if (recovery.reason === "ownership-unknown") {
        console.error(`opencodex: ${reason}; runtime ownership is unknown, so automatic recovery was refused. Run 'ocx status --json' and repair the service-state record before retrying.`);
      } else if (recovery.reason === "ownership-transferred") {
        console.log("opencodex: runtime ownership moved to another installation; the stopped CLI runtime was not revived.");
      } else if (recovery.reason.startsWith("runtime-")) {
        console.error(`opencodex: ${reason}; package runtime liveness is ${recoveryLiveness}, so automatic recovery was refused.`);
      } else if (recovery.reason === "launcher-unavailable") {
        console.error("opencodex: no verified active launcher remains for automatic recovery; reinstall opencodex manually.");
      } else if (recovery.action === "service") {
        console.warn(`opencodex: ${reason} after stopping the proxy — restoring the previous background service.`);
        refreshBackgroundServiceOrStartDirect();
      } else if (recovery.action === "direct") {
        console.warn(`opencodex: ${reason} after stopping the proxy — restarting the previous version directly.`);
        startProxyDirectly();
      }
      return recovery;
    }

    // An outstanding pending-teardown receipt is a fourth reason to run the stop. After a
    // parent crashed mid-deferral the service, pid and runtime records can all be absent
    // while the shared client config still points at a proxy that is gone; installing over
    // that silently skips the recovery the receipt was written to trigger (#3008). Presence
    // is the whole test here — the launcher cannot parse it, and `ocx stop` is what decides
    // whether the obligation is safe to finish.
    const hasPendingTeardown = hasPendingTeardownIn(readdirSync, configDir());
    if (homePolicy.packageOnly && hasPendingTeardown) {
      releaseUpdateLease();
      console.error("opencodex: pending teardown requires manual recovery before package replacement; run 'ocx stop' from the owning installation.");
      process.exit(1);
    }
    const stopNeeded = !homePolicy.packageOnly && (serviceWasInstalled || hasRuntimeState || hasPendingTeardown);
    if (stopNeeded && !runtimePlan.mayStopRuntime) {
      releaseUpdateLease();
      console.error(runtimePlan.notice
        ?? "opencodex: update stopped because this installation may not stop the current runtime.");
      process.exit(1);
    }
    if (stopNeeded) {
      if (!homePolicy.authorizeMutation("runtime")) { releaseUpdateLease(); process.exit(1); }
      const preStopPlan = planUpdateRuntimeHandling({
        ...readOwnership(), serviceInstalled: serviceWasInstalled, supervision: observeSupervision(),
      });
      if (!preStopPlan.mayStopRuntime) {
        console.error(preStopPlan.notice);
        releaseUpdateLease();
        process.exit(1);
      }
      if (!homePolicy.authorizeMutation("runtime")) { releaseUpdateLease(); process.exit(1); }
      if (serviceWasInstalled && !homePolicy.serviceAllowed) {
        console.warn("Service authority changed before proxy stop; check 'ocx service status' before retrying the update.");
        releaseUpdateLease();
        process.exit(1);
      }
      stopAttempted = true;
      console.log("⏹  Stopping the running proxy before updating...");
      if (!homePolicy.authorizeMutation(serviceWasInstalled ? "service" : "runtime")) { releaseUpdateLease(); process.exit(1); }
      const stopRes = guardedSpawnSync(homePolicy.authorizeMutation, serviceWasInstalled ? "service" : "runtime", process.execPath, [launcher, "stop"], {
        stdio: "inherit", windowsHide: true, env: mutationChildEnvironment(),
      });
      const stillHasRuntimeState =
        existsSync(join(configDir(), "ocx.pid")) || existsSync(join(configDir(), "runtime-port.json"));
      // A history-only failure means teardown succeeded and a backup manifest is waiting for
      // review: the proxy is down and replacing package files is safe. Every other nonzero
      // status is a stop that did not finish, and a signal kill (status null) says nothing
      // about whether it did - both abort, because replacing files under a live server
      // leaves it running mixed old and new modules (#3008).
      // The same decision the Bun updater makes, from the same module (#3008). Absent PID and
      // runtime files are weak evidence, so the captured endpoint is asked; "unknown" aborts
      // because a silent listener is exactly the state where replacing files is dangerous.
      const decision = decidePostStopUpdate({
        status: stopRes.status,
        hasRuntimeState: stillHasRuntimeState,
        // Re-checked AFTER the stop: a quarantined receipt lets the stop itself succeed
        // (there is nothing left to stop), so a pre-stop check alone let the retry install
        // over a teardown that never ran.
        teardownOutstanding: hasPendingTeardownIn(readdirSync, configDir()),
        liveness: probeProxyLiveness(bakePort, bakeHostname),
      });
      const historyOnlyStop = decision.reason === "history-only";
      if (!decision.proceed) {
        if (trayBeforeUpdate.restoreOnFailure && homePolicy.authorizeMutation("own-tray")) runTrayLifecycle(launcher, "start", homePolicy.authorizeMutation);
        if (decision.reason === "teardown-outstanding") {
          console.error("opencodex: a shared teardown from an earlier stop is still outstanding and needs manual review; aborting the update.");
          console.error("opencodex: confirm no proxy is running, run 'ocx restore', then remove the pending-teardown file in the opencodex home.");
        } else console.error(decision.reason === "proxy-unknown"
          ? `opencodex: could not confirm the proxy on ${bakeHostname}:${bakePort} is stopped; aborting the update. Run 'ocx stop' and retry.`
          : "opencodex: could not stop the running proxy; aborting the update. Run 'ocx stop' and retry.");
        releaseUpdateLease();
        process.exit(1);
      }
      if (historyOnlyStop || historyRestoreIncomplete()) {
        console.warn(
          "opencodex: WARNING — Codex resume-history metadata restore is incomplete (a backup manifest remains).\n" +
          "  The DB may be busy or the manifest/target may need review; untracked routed history is intentionally unchanged.\n" +
          "  After the update: close the Codex app, run 'ocx doctor', then run 'ocx stop' once to retry.",
        );
      }
      if (decision.reason === "history-deferred") {
        // The reported #4718 path is this lane. Nothing was restored, so this is a different
        // sentence from the manifest warning above: an operator told "history metadata is
        // incomplete" would assume config and catalog already came back.
        console.warn(
          "opencodex: WARNING — the shared teardown was refused by the Codex history preflight and restored nothing.\n" +
          "  Config, catalog, history and provenance were preserved, and the teardown receipt was kept.\n" +
          "  The proxy is down, so the update continues; close the Codex app and run 'ocx stop' once afterwards to finish the restore.",
        );
      }
    }

    const replacementOwnership = readOwnership();
    const replacementPlan = planUpdateRuntimeHandling({ ...replacementOwnership, serviceInstalled: serviceWasInstalled, supervision: observeSupervision() });
    const replacementLiveness = currentPackageRuntimeLiveness();
    if (!homePolicy.authorizeMutation("package") || replacementOwnership.subjectToken !== initialOwnership.subjectToken
      || !replacementPlan.mayReplacePackage
      || replacementLiveness !== "dead") {
      recoverStoppedRuntimeAfterFailure("replacement was refused");
      releaseUpdateLease();
      if (trayBeforeUpdate.restoreOnFailure && homePolicy.authorizeMutation("own-tray")) runTrayLifecycle(launcher, "start", homePolicy.authorizeMutation);
      console.error(replacementPlan.notice
        ?? "opencodex: update stopped because runtime ownership or liveness changed after the stop decision; rerun from the beginning.");
      process.exit(1);
    }

    // npm keeps the existing stage -> verify -> swap -> rollback flow. pnpm owns a
    // content-addressable store and generated global shims, so its path uses pnpm's own
    // global update operation and verifies the active group instead of renaming files.
    console.log(`Updating${latest ? ` to v${latest}` : ""} (${manager === "npm" ? "transactional" : "pnpm-managed"})...`);
    try {
      if (manager === "npm") {
        const packageDir = resolve(here, "..");
        const transactionalNpmUpdate = session ? transactionalNpmUpdateAsync : transactionalNpmUpdateSync;
        if (!homePolicy.authorizeMutation("package")) throw new Error("Automatic package update refused.");
        const tx = await transactionalNpmUpdate({
          packageDir,
          pkgName: PKG,
          targetVersion: latest || undefined,
          tag,
          cachePath: npmCachePath,
          mayReplacePackage: () => {
            const ownership = readOwnership();
            const plan = planUpdateRuntimeHandling({ ...ownership, serviceInstalled: serviceWasInstalled, supervision: observeSupervision() });
            const liveness = currentPackageRuntimeLiveness();
            return homePolicy.authorizeMutation("package") && ownership.subjectToken === initialOwnership.subjectToken
              && plan.mayReplacePackage && liveness === "dead";
          },
          runNpm: (args) => {
            const invocation = npmInvocation(args);
            if (!homePolicy.authorizeMutation("package")) return { status: 1 };
            if (process.platform === "win32") {
              if (session) session.noteUntrackedInstaller();
              return runNpmInstall(invocation, {
                authorizeMutation: homePolicy.authorizeMutation,
                ...(session ? { markerPath: join(configDir(), "update-orchestrated.json") } : {}),
                env: unprivilegedOwnershipMutationEnvironment(invocation?.options?.env ?? process.env),
              }).then(result => {
                if (session && result.processTreeExited === true && Number.isInteger(result.status)) session.confirmInstallerExit();
                else if (session) { session.retainInstallerFence(); return { ...result, processTreeExited: false }; }
                return result;
              });
            }
            if (!invocation) return { status: 1 };
            if (!homePolicy.authorizeMutation("package")) return { status: 1 };
            if (session) {
              try {
              const result = runPosixInstallerSync({ file: invocation.file, args: invocation.args,
                markerPath: join(configDir(), "update-orchestrated.json"), authorizeMutation: homePolicy.authorizeMutation,
                env: unprivilegedOwnershipMutationEnvironment(invocation.options?.env ?? process.env) });
              if (!Number.isInteger(result.status) || result.signal || !result.groupExited || result.groupKilled !== false || result.processTreeExited === false) {
                session.retainInstallerFence();
                return { ...result, processTreeExited: false };
              }
              return { ...result, processTreeExited: true };
              } catch (error) { session.retainInstallerFence(); throw error; }
            }
            return guardedSpawnSync(homePolicy.authorizeMutation, "package", invocation.file, invocation.args, {
              ...invocation.options,
              stdio: "inherit",
              timeout: 180000,
              windowsHide: true,
              env: unprivilegedOwnershipMutationEnvironment(invocation.options?.env ?? process.env),
            });
          },
          log: (line) => console.log(line),
        });
        if (session) childOutcome = tx.ok ? { phase: "installed", activeRoot: packageDir }
          : { phase: "failed", rollbackPerformed: tx.rolledBack === true,
            ...(tx.processTreeExited === false ? { error: "installer-termination-unconfirmed", terminationConfirmed: false } : {}) };
        postUpdateLauncherUsable = launcherUsableAfterNpmUpdate(tx);
        if (!tx.ok) npmFailure = tx;
        if (tx.ok) {
          res = { status: 0 };
        } else if (tx.phase === "stage" || tx.phase === "verify" || tx.phase === "authorize") {
          // Live tree untouched: report and stop. Nothing to roll back.
          console.error(`opencodex: update aborted before touching the live install (${tx.phase}): ${tx.error}`);
          res = { status: 1 };
        } else {
          console.error(`opencodex: update failed (${tx.phase}): ${tx.error}${tx.rolledBack ? " — previous version restored." : ""}`);
          res = { status: 1 };
        }
      } else {
        if (!homePolicy.authorizeMutation("package")) throw new Error("Automatic package update refused.");
        const update = runPnpmGlobalUpdate({
          packageName: PKG,
          currentVersion: current,
          targetVersion: latest || undefined,
          tag,
          owner,
          runningPackagePath: resolve(here, ".."),
          runPnpm: (args, capture = false) => {
            const invocation = pnpmOwnerInvocation(owner, args);
            if (!invocation) return { status: 1 };
            if (session && !capture) return withPnpmCommandCwd(args, cwd => {
              const env = pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(invocation.env ?? process.env));
              if (process.platform === "win32") {
                session.noteUntrackedInstaller();
                const result = runWindowsInstallerSync(invocation, { cwd, env, authorizeMutation: homePolicy.authorizeMutation,
                  markerPath: join(configDir(), "update-orchestrated.json") });
                if (result.processTreeExited === true && Number.isInteger(result.status)) session.confirmInstallerExit();
                else { session.retainInstallerFence(); return { ...result, processTreeExited: false }; }
                return result;
              }
              try {
              const result = runPosixInstallerSync({ file: invocation.file, args: invocation.args, cwd, markerPath: join(configDir(), "update-orchestrated.json"),
                authorizeMutation: homePolicy.authorizeMutation, env });
              if (!Number.isInteger(result.status) || result.signal || !result.groupExited || result.groupKilled !== false || result.processTreeExited === false) {
                session.retainInstallerFence();
                return { ...result, processTreeExited: false };
              }
              return { ...result, processTreeExited: true };
              } catch (error) { session.retainInstallerFence(); throw error; }
            });
            return withPnpmCommandCwd(args, cwd => homePolicy.authorizeMutation("package") ? guardedSpawnSync(homePolicy.authorizeMutation, "package", invocation.file, invocation.args, {
              ...invocation.options,
              stdio: capture ? "pipe" : "inherit",
              encoding: "utf8",
              timeout: 180000,
              windowsHide: true,
              // Reads probe from the package dir; mutations (add -g, rollback) must not
              // keep a cwd handle inside the package Windows is replacing.
              cwd,
              env: pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(invocation.env ?? process.env)),
            }) : { status: 1 });
          },
          log: line => console.log(line),
        });
        if (session) childOutcome = update.ok ? { phase: "installed", activeRoot: update.path }
          : { phase: "failed", rollbackPerformed: update.rollbackPerformed === true,
            ...(update.processTreeExited === false ? { error: "installer-termination-unconfirmed", terminationConfirmed: false } : {}) };
        if (update.ok) {
          // pnpm switches the active global group and updates its shim. Continue recovery
          // through that fresh package tree, not the old group whose launcher is still
          // executing this update.
          postUpdateLauncher = join(update.path, "bin", "ocx.mjs");
          res = { status: 0 };
        } else {
          console.error(`opencodex: ${update.error}${update.rolledBack ? "." : " Manual recovery may be required."}`);
          postUpdateLauncherUsable = Boolean(update.activePath);
          if (update.activePath) postUpdateLauncher = join(update.activePath, "bin", "ocx.mjs");
          res = { status: 1 };
        }
      }
    } catch (error) {
      // An unexpected throw means we cannot prove the live tree is untouched, so the
      // legacy in-place install (which deletes live first) is exactly the wrong rescue —
      // it recreates the #1849 destruction path. Report and stop; the boot probe and the
      // recovery marker cover the swap-window states.
      // An unexpected exception leaves the active package path unproven for either manager.
      // Do not run service/tray/proxy recovery through a possibly half-swapped tree.
      postUpdateLauncherUsable = false;
      console.error(`opencodex: ${manager} update failed unexpectedly (${error?.message ?? error}). ` +
        `Run 'ocx update' again or follow the manual recovery steps below.`);
      res = { status: 1 };
    }
    if (res.status !== 0 && childOutcome.error !== "installer-termination-unconfirmed") recoverStoppedRuntimeAfterFailure("update failed");
  } finally {
    // Expected aborts release before process.exit(); this covers every thrown or newly-added
    // path and keeps token restoration coupled to the lease itself.
    releaseUpdateLease();
  }
  if (childOutcome.error === "installer-termination-unconfirmed") process.exit(1);
  const postInstallPlan = planUpdateRuntimeHandling({ ...readOwnership(), serviceInstalled: serviceWasInstalled, supervision: observeSupervision() });
  if (res.status === 0) {
    authorityLauncher = postUpdateLauncher;
    if (homePolicy.packageOnly) {
      if (!homePolicy.authorizeMutation("package-publish")) process.exit(1);
      guardedRun(homePolicy.authorizeMutation, "package-publish", console.log, [`\nUpdated${latest ? ` to v${latest}` : ""}.`]);
      homePolicy.check(homePolicy.initial);
      console.log(`Restart the proxy:  ${launcherStartHint(postUpdateLauncher, bakePort)}`);
      if (!homePolicy.authorizeMutation("package-publish")) process.exit(1);
      guardedExit(homePolicy.authorizeMutation, "package-publish", process.argv.includes("--update-worker-result") ? UPDATE_PACKAGE_ONLY_EXIT_CODE : 0);
    }
    const restoreOwnStoppedTray = () => {
      if (trayBeforeUpdate.restoreOnFailure && postUpdateLauncherUsable && existsSync(postUpdateLauncher)) {
        try { if (homePolicy.authorizeMutation("own-tray")) runTrayLifecycle(postUpdateLauncher, "start", homePolicy.authorizeMutation); } catch { /* preserve the authority refusal */ }
      }
    };
    if (!homePolicy.authorizeMutation("publish")) {
      restoreOwnStoppedTray();
      process.exit(1);
    }
    guardedRun(homePolicy.authorizeMutation, "publish", console.log, [`\nUpdated${latest ? ` to v${latest}` : ""}.`]);
    if (!postInstallPlan.mayStopRuntime) console.warn("Runtime authority does not permit CLI recovery; no service was refreshed or proxy started.");
    if (!homePolicy.authorizeMutation("shim") || repairCodexShimIfNeeded(postUpdateLauncher, homePolicy.authorizeMutation) === false) { restoreOwnStoppedTray(); process.exit(1); }
    if (trayBeforeUpdate.refreshAfterReplacement) {
      if (!homePolicy.authorizeMutation("tray")) {
        restoreOwnStoppedTray();
        process.exit(1);
      }
      const tray = guardedSpawnSync(homePolicy.authorizeMutation, "tray", process.execPath, [postUpdateLauncher, ...trayBeforeUpdate.installArgs], {
        stdio: "inherit",
        windowsHide: true,
      });
      if (tray.status !== 0) {
        console.warn("opencodex: Windows tray refresh failed. Run: ocx tray install");
        if (trayBeforeUpdate.restoreOnFailure && postUpdateLauncherUsable && homePolicy.authorizeMutation("own-tray")) runTrayLifecycle(postUpdateLauncher, "start", homePolicy.authorizeMutation);
      }
    }
    // The stop above unloaded any managed service; refresh via the freshly-installed
    // launcher so the new files write the baked paths and the service restarts.
    if (postInstallPlan.mayRestoreService) {
      console.log("Refreshing the background service with the updated files...");
      let refreshed;
      try { refreshed = refreshBackgroundServiceOrStartDirect(); }
      finally { releaseUpdateLease(); }
      if (refreshed === "unsupervised" || refreshed === "unsettled" || refreshed === "refused") process.exit(1);
    } else if (postInstallPlan.mayStopRuntime) {
      if (!homePolicy.authorizeMutation("runtime")) process.exit(1);
      authorityLauncher = postUpdateLauncher;
      if (stopAttempted) {
        let started;
        try { started = startProxyDirectly(); }
        finally { releaseUpdateLease(); }
        if (started !== true && started !== "vetoed") process.exit(1);
      } else console.log(`Restart the proxy:  ${launcherStartHint(postUpdateLauncher, bakePort)}`);
    }
    if (!homePolicy.authorizeMutation("publish")) process.exit(1);
    guardedExit(homePolicy.authorizeMutation, "publish", 0);
  }
  if (trayBeforeUpdate.restoreOnFailure && postUpdateLauncherUsable && homePolicy.authorizeMutation("own-tray")) runTrayLifecycle(postUpdateLauncher, "start", homePolicy.authorizeMutation);
  if (npmFailure) {
    // Phase-specific next step (#5624): whether the previous version is still in place decides
    // between "retry" and "restore", and a bare reinstall must follow a stop (#5496).
    const guidance = npmUpdateFailureGuidance({ ...npmFailure, pkgName: PKG, version: latest || undefined, tag });
    console.error(`\nUpdate failed (npm ${npmFailure.phase}). ${guidance.lines.join("\n")}`);
    process.exit(1);
  }
  const guidance = manualUpdateFailureGuidance({
    bin: manager,
    args: manager === "pnpm"
      ? ["add", "-g", "--allow-build=bun", `${PKG}@${latest || tag}`]
      : ["install", "-g", "--allow-scripts=bun", `${PKG}@${latest || tag}`],
    owner,
  });
  console.error(`\nUpdate failed (${manager} exit ${res.status ?? "?"}). ${guidance.join("\n")}`);
  process.exit(1);
}

function bunBinDir(launcherPath) {
  // Resolve the `bun` dependency's directory without hardcoding the platform
  // package — the package manager's os/cpu/libc resolution already picked the right @oven/bun-*.
  const resolver = createRequire(launcherPath || import.meta.url);
  return dirname(resolver.resolve("bun/package.json"));
}

const BUN_OVERRIDE_ENV = "OPENCODEX_BUN_PATH";
// Mirrors BUN_RUNTIME_SOURCE_ENV in src/lib/bun-runtime.ts. This launcher is plain
// Node and runs before any TypeScript is loaded, so the name is repeated rather than
// imported; tests/cli/ocx-launcher-source.test.ts pins the two together.
const BUN_RUNTIME_SOURCE_ENV = "OCX_BUN_RUNTIME_SOURCE";
const BUN_RUNTIME_PATH_ENV = "OCX_BUN_RUNTIME_PATH";
/** Total budget for validating a PATH Bun fallback (both probes together). */
const PATH_BUN_PROBE_BUDGET_MS = 5_000;

function findBunBinary(bunDir) {
  // The bundled `bun` package ships the binary as bin/bun.exe on every platform;
  // probe bin/bun too for forward compatibility.
  for (const name of ["bun.exe", "bun"]) {
    const p = join(bunDir, "bin", name);
    if (isRealBunBinary(p)) return p;
  }
  return null;
}

function bundledBunVersion(bunDir) {
  try {
    const version = JSON.parse(readFileSync(join(bunDir, "package.json"), "utf8")).version;
    return typeof version === "string" ? version : null;
  } catch {
    return null;
  }
}

function fail(msg) {
  const reinstall = installMethod === "pnpm"
    ? "pnpm add -g --allow-build=bun @bitkyc08/opencodex"
    : "npm install -g --allow-scripts=bun @bitkyc08/opencodex";
  const desktopCli = findDesktopCli();
  console.error(
    `opencodex: ${msg}\n` +
      "The bundled Bun runtime could not be prepared. This usually means the\n" +
      "install skipped lifecycle scripts (for example npm blocked bun's postinstall\n" +
      "or pnpm did not approve bun's build) or optional dependencies. Reinstall with:\n" +
      `  ${reinstall}\n` +
      "(use sudo if the original install used sudo; without --ignore-scripts\n" +
      "and without --omit=optional / optional=false)" +
      (desktopCli ? `\nAn installed Desktop CLI is available: "${desktopCli}"` : "")
  );
  process.exit(1);
}

function resolveBun({ allowInstall = true, launcherPath, allowMissing = false } = {}) {
  // Keep direct package-launcher starts aligned with durable service/shim installs:
  // a valid explicit runtime must win even when the bundled dependency exists.
  const override = process.env[BUN_OVERRIDE_ENV]?.trim();
  if (override) {
    const overridePath = resolve(override);
    if (isRealBunBinary(overridePath)) return { path: overridePath, source: "override" };
    console.error(
      `opencodex: ${BUN_OVERRIDE_ENV} is missing, unreadable, or not a complete Bun binary; falling back to the bundled runtime.`,
    );
  }

  let bunDir = null;
  try {
    bunDir = bunBinDir(launcherPath);
  } catch { /* Missing dependency can still fall back to a validated PATH Bun. */ }

  let bin = bunDir ? findBunBinary(bunDir) : null;
  if (bin) return { path: bin, source: "bundled", version: bundledBunVersion(bunDir) };

  // Lazy fallback: --ignore-scripts (or a failed postinstall) leaves the
  // ~450-byte placeholder stub. Run the bun package's own installer once.
  const installJs = bunDir ? join(bunDir, "install.js") : null;
  if (allowInstall && installJs && existsSync(installJs)) {
    const r = probeSpawnSync(process.execPath, [installJs], { stdio: "inherit" });
    if (r.status === 0) bin = findBunBinary(bunDir);
  }
  if (bin) return { path: bin, source: "bundled", version: bundledBunVersion(bunDir) };

  // Reached only when the bundled runtime is unusable. The two probes start the candidate Bun
  // cold, and on Windows a first run of a copied bun.exe is often held by an on-access scan for
  // well over a second, so the total budget is generous rather than interactive-tight.
  const pathBun = findPathBun({ pinnedVersion: pinnedBunVersion(launcherPath), deadlineMs: PATH_BUN_PROBE_BUDGET_MS });
  if (pathBun) {
    console.error(`opencodex: using PATH Bun ${pathBun.version}.`);
    return { path: pathBun.path, source: "process", version: pathBun.version };
  }
  if (allowMissing) return null;
  fail(bunDir ? "Bun binary missing after install attempt." : "the `bun` dependency is not installed.");
}

// `ocx update --help` prints usage and exits WITHOUT side effects. The Node launcher
// intercepts `update` before the Bun CLI starts, so the help short-circuit must live
// here too — otherwise --help runs the real self-update, stops the proxy, and drops
// in-flight routed streams (issue #168).
const updateHelpRequested = process.argv[2] === "update" && !isOrchestratedUpdateArgv(process.argv.slice(3)) &&
  process.argv.slice(3).some(a => a === "--help" || a === "-h" || a === "help");
if (updateHelpRequested) {
  console.log("Usage: ocx update [--tag latest|preview]\n       ocx update --plan --json [--tag latest|preview | --version <version>]\n       ocx update --yes --json [--tag latest|preview | --version <version>] [--expect-plan <token>] [--not-after <unix-ms>]\n       ocx update --desktop [--check] [--json]   (Windows OpenCodex Desktop installation only)\n\nPreview with --plan; apply with --yes. --expect-plan binds apply to the planToken; --not-after sets a Unix millisecond mutation deadline.\nOrchestrated exit codes: 0 verified or up-to-date; 10 refused; 11 failed with previous version verified; 12 unverified or still running; 64 invalid usage.\nPreview installs stay on the preview tag unless overridden.");
  process.exit(0);
}

// `ocx update --desktop` updates a Windows Desktop installation through its bundled ocx.exe (#8246).
// This launcher only ever runs a package installation, so it refuses before any package update.
if (process.argv[2] === "update" && process.argv.slice(3).includes("--desktop")) {
  console.error("opencodex: 'ocx update --desktop' updates a Windows OpenCodex Desktop installation and must be run with that installation's ocx.exe. This ocx is a package installation; update it with 'ocx update'.");
  process.exit(64);
}

// This intercept precedes Desktop handoff, boot restore and install-capable Bun resolution.
// Capability only: no Bun lookup, home inspection, dotenv or ordinary bootstrap.
if (process.argv[2] === "__update-package-only-probe") {
  if (process.argv.length !== 3) process.exit(2);
  console.log(JSON.stringify({ schemaVersion: 1, packageOnlyProtocolVersion: UPDATE_PACKAGE_ONLY_PROTOCOL_VERSION }));
  process.exit(0);
}
if (process.argv[2] === "__update-home-probe") {
  if (!isUpdateHomeProbe(process.argv.slice(2))) process.exit(1);
  console.log(JSON.stringify({ schemaVersion: 1, ...readNodeUpdateHome(fileURLToPath(import.meta.url)), launcherProtocolVersion: UPDATE_HOME_LAUNCHER_PROTOCOL }));
  process.exit(0);
}
if (process.argv[2] === "__update-orchestrated-identity") {
  if (process.argv.length !== 3) process.exit(1);
  const bun = resolveBun({ allowInstall: false, allowMissing: true });
  if (!bun) process.exit(1);
  const result = probeSpawnSync(bun.path, ["--no-env-file", join(here, "../src/update/orchestrated-identity-probe-entry.ts"), process.argv[2]], {
    stdio: "inherit", timeout: 8000, windowsHide: true, env: { ...process.env, OCX_IDENTITY_CLI_ROOT: resolve(here, ".."), OCX_IDENTITY_INSTALLER: "", OCX_IDENTITY_TARGET: "" },
  });
  process.exit(result.status ?? 1);
}

const orchestratedUpdate = process.argv[2] === "update" && isOrchestratedUpdateArgv(process.argv.slice(3));
const childArgs = orchestratedUpdate && process.env.OCX_UPDATE_ORCHESTRATED_CHILD === "1"
  ? parseOrchestratedChildArgs(process.argv.slice(3), process.env) : null;
const orchestratedArgs = orchestratedUpdate && !childArgs?.ok ? parseOrchestratedUpdateArgs(process.argv.slice(3)) : null;
if (orchestratedArgs && !orchestratedArgs.ok) {
  console.log(JSON.stringify({ error: "usage" }));
  console.error("Usage: ocx update (--plan | --yes) --json [--tag latest|preview | --version <version>]");
  process.exit(64);
}
if (childArgs?.ok && isNodeModulesInstall() && !isBunGlobalInstall() && (installMethod === "npm" || installMethod === "pnpm")) {
  await runPackageManagerSelfUpdate(installMethod, childArgs);
}
if (orchestratedArgs?.ok && orchestratedArgs.mode === "apply" && process.env.OCX_UPDATE_ORCHESTRATED_CHILD !== "1"
  && isNodeModulesInstall() && !isBunGlobalInstall() && (installMethod === "npm" || installMethod === "pnpm")) {
  const result = await applyNodeOrchestratedUpdate(orchestratedArgs, {
    installer: installMethod, currentVersion: String(currentPackageVersion()), cliRoot: resolve(here, ".."),
    home: configDir(), launcher: fileURLToPath(import.meta.url), resolveBun: () => resolveBun({ allowInstall: false, allowMissing: true }),
    plan: (bun, version, tag) => probeSpawnSync(bun.path, ["--no-env-file", cliPath, "update", "--plan", "--json",
      ...(version ? ["--version", version] : tag ? ["--tag", tag] : [])], { encoding: "utf8", maxBuffer: 65536, timeout: 60000, windowsHide: true,
      stdio: ["ignore", "pipe", 2], env: process.env }),
    identity: bun => {
      const probe = probeSpawnSync(bun.path, ["--no-env-file", join(here, "../src/update/orchestrated-identity-probe-entry.ts"), "__update-orchestrated-identity"], {
        encoding: "utf8", maxBuffer: 8192, timeout: 8000, windowsHide: true, stdio: ["ignore", "pipe", 2],
        env: { ...updateHomeProbeEnvironment(process.env, { codexHome: process.env.CODEX_HOME ?? "", opencodexHome: configDir() }),
          OCX_IDENTITY_CLI_ROOT: resolve(here, ".."), OCX_IDENTITY_INSTALLER: "", OCX_IDENTITY_TARGET: "" },
      });
      if (probe.status !== 0 || probe.error || probe.signal) throw Error("identity unavailable");
      return JSON.parse(probe.stdout);
    },
    pnpmCommands: resolvePnpmCommands(), runningShimPath: runningPnpmShimPath(),
    runPnpm: (commandPath, args, capture = false, owner) => {
      const invocation = owner ? pnpmOwnerInvocation(owner, args) : pnpmInvocationForPath(commandPath, args);
      if (!invocation) return { status: 1 };
      return withPnpmCommandCwd(args, cwd => probeSpawnSync(invocation.file, invocation.args, { stdio: capture ? "pipe" : "ignore", encoding: "utf8",
        timeout: 20000, windowsHide: true, cwd,
        env: pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(invocation.env ?? process.env)), ...invocation.options }));
    },
    spawn: probeSpawn,
  });
  await new Promise(resolveOutput => process.stdout.write(`${JSON.stringify(result.result)}\n`, resolveOutput));
  process.exit(result.exitCode);
}
const passiveCapabilities = process.argv[2] === "capabilities";
const codexCliUpdateInspection = isCodexCliUpdateInspectionArgv(process.argv);
// Windows inspection currently refuses before candidate I/O, so a long-lived
// Windows server does not duplicate PATH into its inherited environment block.
const codexCliUpdateInspectionContext = codexCliUpdateInspection
  || (process.platform !== "win32" && carriesCodexCliUpdateInspectionContext(process.argv));
if (codexCliUpdateInspection && typeof process.versions.bun === "string") {
  console.error("opencodex: codex-cli-update inspection must use the published Node launcher.");
  process.exit(1);
}

const { launchProof, launchContext, inheritedEnv } = createNodeLaunchContext();
delete inheritedEnv.OCX_SYNC_MUTEX_HELD_BY;
// The parsed child capability was removed from process.env; only the Bun CLI handoff of this same child receives it.
if (childArgs?.ok) inheritedEnv.OCX_UPDATE_RESULT_CAPABILITY = childArgs.resultCapability;
const desktopPlan = planDesktopCliHandoff({ selfPaths: [fileURLToPath(import.meta.url), process.execPath] });
if (desktopPlan.kind === "error") {
  if (desktopPlan.issue.startsWith("record-")) {
    console.error(`opencodex: OpenCodex Desktop's terminal-command record at ${desktopCliRecordPath()} could not be used (${desktopPlan.issue}). Open OpenCodex Desktop to repair the terminal command, or run with OCX_NO_DESKTOP_HANDOFF=1.`);
  } else {
    console.error(`opencodex: Desktop CLI handoff refused (${desktopPlan.issue}). Repair the terminal command in OpenCodex Desktop, or run with OCX_NO_DESKTOP_HANDOFF=1.`);
  }
  process.exit(1);
}
let releaseSyncLease = () => {};
let addSyncDelegate = () => {};
if (process.argv[2] === "sync") {
  const syncLease = acquireSyncGuard(configDir(), process.argv.slice(2));
  if (syncLease.kind === "refused") process.exit(syncLease.exit);
  addSyncDelegate = pid => syncLease.addDelegate(pid);
  inheritedEnv.OCX_SYNC_MUTEX_HELD_BY = String(process.pid);
  let released = false;
  releaseSyncLease = () => {
    if (released) return;
    try { syncLease.release(); released = true; } catch (error) { console.error(`opencodex: sync mutex release failed: ${error.message}`); }
  };
  process.once("exit", releaseSyncLease);
}
if (desktopPlan.kind === "handoff") {
  const result = await runDesktopCliHandoff(desktopPlan, {
    argv: process.argv.slice(2), env: inheritedEnv, proof: launchProof, context: launchContext, onSpawn: addSyncDelegate,
  });
  if (result.kind === "error") {
    console.error(`opencodex: Desktop CLI handoff failed (${result.issue}). Repair the terminal command in OpenCodex Desktop, or run with OCX_NO_DESKTOP_HANDOFF=1.`);
    process.exit(127);
  }
  if (result.kind === "exit") {
    releaseSyncLease();
    if (result.signal) {
      relayOwnSignal(result.signal);
    } else {
      process.exit(result.code);
    }
    // Signal delivery is asynchronous; never resume package repair or Bun lookup.
    await new Promise(() => {});
  }
  // A selected Desktop never falls back to the package after a launch failure.
}

if (!orchestratedUpdate && process.argv[2] === "update" && installMethod === "mise") {
  if (installOwnership.owner) {
    console.error(
      `opencodex: this installation is externally managed by mise; update it with: mise upgrade ${installOwnership.owner.tool}`,
    );
  } else {
    console.error(
      "opencodex: this installation appears to be managed by mise, but its ownership metadata is unreadable or inconsistent; repair the mise installation metadata before updating.",
    );
  }
  process.exit(1);
}

if (!orchestratedUpdate && process.argv[2] === "update" && isNodeModulesInstall() && !isBunGlobalInstall()) {
  if (installMethod === "npm") await runNpmSelfUpdate();
  if (installMethod === "pnpm") await runPnpmSelfUpdate();
}

// #1849 boot probe: a prior update that lost power (or double-faulted) mid-swap leaves a
// backup sibling and a broken live tree. Restore before anything tries to run from the
// broken tree; reap stale backups once the live tree verifies healthy.
if (process.argv[2] !== "sync" && !orchestratedUpdate && !passiveCapabilities && !codexCliUpdateInspection && installMethod === "npm" && isNodeModulesInstall() && !isBunGlobalInstall()) {
  try {
    const probe = bootRestoreProbe(resolve(here, ".."));
    if (probe.action === "restored") {
      console.warn(`opencodex: previous update left a broken install — restored the backup from ${probe.from}.`);
    } else if (probe.action === "failed") {
      console.warn(`opencodex: a backup from a failed update exists but could not be restored automatically: ${probe.error}`);
    }
  } catch { /* the probe must never block launch */ }
}

const passiveSync = process.argv[2] === "sync";
const bunRuntime = resolveBun({ allowInstall: !passiveSync && !orchestratedUpdate && !passiveCapabilities && !codexCliUpdateInspection, allowMissing: orchestratedUpdate || passiveSync });
if (!bunRuntime && passiveSync) fail("Bun is unavailable; install Bun before running sync.");
if (!bunRuntime && orchestratedArgs?.ok) {
  const currentVersion = String(currentPackageVersion()), cliRoot = resolve(here, "..");
  if (orchestratedArgs.mode === "plan") {
    const identity = { currentVersion, targetVersion: null, installer: installMethod, cliRoot, servingRoot: null, runtimeOwner: "unknown", runtime: null };
    console.log(JSON.stringify({ schema: "ocx.update.plan/1", currentVersion, targetVersion: null, installer: installMethod,
      runtimeOwner: "unknown", servingPath: null, cliPath: cliRoot, canApply: false, reason: "plan-unavailable", restartRequired: false,
      planToken: createUpdatePlanToken(identity), updateInFlight: true, mutationBoundMs: 900000 }));
    process.exit(0);
  }
  console.log(JSON.stringify({ schema: "ocx.update.result/1", applied: false, fromVersion: currentVersion, toVersion: null,
    installer: installMethod, restarted: false, healthy: false, rolledBack: false, error: "plan-unavailable" }));
  process.exit(10);
}
const bun = bunRuntime.path;

// Run the Bun child asynchronously and FORWARD termination signals to it, then wait
// for its graceful shutdown before this launcher exits. The previous blocking
// spawnSync() could not run JS signal handlers and did not forward signals, so a
// signal delivered only to this launcher (Codex app, IDE terminal, service wrapper,
// or `kill -INT <launcherPid>`) killed the launcher and ORPHANED the Bun proxy —
// port left bound, pid/runtime-port files left behind, Codex config not restored.
//
// Provenance seam for issue #701: THIS launcher runs under Node, which does not
// auto-load a project `.env`/`.env.local`; the Bun child does, before any opencodex
// code evaluates. So this is the last point that can still tell a real shell export
// from a working-directory dotenv value, and we record which Anthropic credential or
// destination slots already existed. The context is paired with a random proof carried
// in argv, which project dotenv cannot modify during an ordinary `ocx` invocation.
// `src/cli/claude.ts` treats anything present in the Bun child but missing from this
// list as ambient project pollution rather than user auth or destination,
// which stopped a project dotenv from silently moving a claude.ai subscriber onto API
// billing and prevents it from redirecting the subscriber's OAuth bearer.
// Disabling Bun's dotenv wholesale with --no-env-file is NOT an option: config
// interpolation and provider settings legitimately read the project environment.
function createNodeLaunchContext() {
  const preBunAnthropicSlots = ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL"]
    .filter(name => typeof process.env[name] === "string" && process.env[name] !== "");
  // A configured CODEX_CLI_PATH may legitimately be cwd-relative (`./tools/codex`), which the
  // ordinary runtime resolver accepts. Inspection only trusts absolute local paths, so capture
  // the absolute form here, in the launcher, while the original cwd is still authoritative;
  // resolving it later would silently reinterpret it against a different working directory.
  //
  // A bare command with no separator (`codex`) is NOT a relative path: the runtime resolver
  // deliberately hands those to executable lookup along PATH. Rewriting it to `<cwd>/codex`
  // would make the inspector treat it as an explicit path and stop searching PATH entirely.
  const configuredCodexCliPath = typeof process.env.CODEX_CLI_PATH === "string" && process.env.CODEX_CLI_PATH !== ""
    ? process.env.CODEX_CLI_PATH
    : null;
  const preBunCodexCliPath = configuredCodexCliPath !== null
      && (configuredCodexCliPath.includes("/") || configuredCodexCliPath.includes("\\") || /^[A-Za-z]:/.test(configuredCodexCliPath))
    ? resolve(configuredCodexCliPath)
    : configuredCodexCliPath;
  const preBunPath = typeof process.env.PATH === "string" ? process.env.PATH : null;
  const preBunPathExt = typeof process.env.PATHEXT === "string" ? process.env.PATHEXT : null;
  // HOME and NODE_PATH seed the candidate Node module lookup the update
  // inspection models, so they are proof-bound here for the same reason as
  // PATH: the live environment could have been rewritten after selection. They
  // stay in the inherited environment regardless — the child may need them for
  // its own work; only the snapshot copy is optional.
  const preBunHome = typeof process.env.HOME === "string" ? process.env.HOME : null;
  const preBunNodePath = typeof process.env.NODE_PATH === "string" ? process.env.NODE_PATH : null;
  const preBunCodexCliManagerRoots = Object.fromEntries(
    CODEX_CLI_VERSION_MANAGER_ROOT_ENV_SLOTS.flatMap(name => {
      const value = process.env[name];
      return typeof value === "string" && value !== "" ? [[name, value]] : [];
    }),
  );
  // Proxy/CA settings are captured once, here, before Bun can add project dotenv
  // values. They are part of the required selection snapshot, so they count
  // against the context budget below before any optional lookup seed does.
  const preBunTransportEnv = captureCodexCliTransportEnv(process.env);
  const launchProof = randomBytes(32).toString("base64url");
  const serializeContext = lookupSeeds => JSON.stringify({
    version: 1,
    proof: launchProof,
    anthropicEnvSlots: preBunAnthropicSlots,
    // Running this shim under Bun can already have loaded project dotenv.
    managedRelease: process.versions.bun === undefined && process.env.OCX_MANAGED_RELEASE === "1",
    codexCliInspectionEnv: codexCliUpdateInspectionContext ? {
      codexCliPath: preBunCodexCliPath,
      path: preBunPath,
      pathExt: preBunPathExt,
      home: lookupSeeds.home,
      nodePath: lookupSeeds.nodePath,
      managerRoots: preBunCodexCliManagerRoots,
      transportEnv: preBunTransportEnv,
      // The published Codex entrypoint selects its native backing by the arch of
      // the Node that runs it; a Bun override or PATH fallback can run another
      // arch under Rosetta, so this Node launcher's arch is the bound value.
      arch: process.arch,
      configDir: configDir(),
    } : null,
  });
  let launchContext = serializeContext({ home: preBunHome, nodePath: preBunNodePath });
  // The lookup seeds are optional: a Windows inspection never models the global
  // Node lookup, and an oversized NODE_PATH must not push the serialized
  // context past the reader's limit — that would discard the whole selection
  // snapshot, while dropped seeds merely leave the fallback lane unverifiable
  // and fail only the content observation closed.
  const lookupSeeds = codexCliInspectionLookupSeeds(
    process.platform, preBunHome, preBunNodePath, launchContext.length,
  );
  if (lookupSeeds.home !== preBunHome || lookupSeeds.nodePath !== preBunNodePath) {
    launchContext = serializeContext(lookupSeeds);
  }
  // The inspection snapshot above already carries PATH, PATHEXT, manager roots and proxy/CA settings as
  // proof-bound values, and `inspectCodexCliInstall` reads them from that snapshot rather than
  // from the live environment. Inheriting them again would spend the 32,767-character Windows
  // environment block twice, so a large-but-valid shell environment could stop the Bun child
  // from spawning and fail the command before it reports anything. Drop the duplicates for the
  // one-shot inspection launch only; every other launch inherits the environment unchanged.
  // Windows environment names are case-insensitive, but this spread produces an ordinary
  // case-sensitive object, and a real Windows environment commonly spells the variable `Path`.
  // Deleting only the canonical upper-case spelling would silently leave that copy behind and
  // reintroduce the duplication this block exists to prevent, so match on the lowercase form.
  const inheritedEnv = { ...process.env };
  if (codexCliUpdateInspection) {
    const snapshotted = new Set(
      ["PATH", "PATHEXT", ...CODEX_CLI_VERSION_MANAGER_ROOT_ENV_SLOTS,
        ...CODEX_CLI_TRANSPORT_ENV_KEYS].map(name => name.toLowerCase()),
    );
    for (const name of Object.keys(inheritedEnv)) {
      if (snapshotted.has(name.toLowerCase())) delete inheritedEnv[name];
    }
  }
  return { launchProof, launchContext, inheritedEnv };
}

// Forwarders precede the spawn so no signal can kill this launcher by default action while the child runs.
const forwarding = forwardLauncherSignals();
const child = probeSpawn(bun, [cliPath, `${NODE_LAUNCH_PROOF_PREFIX}${launchProof}`, ...process.argv.slice(2).filter(arg => !arg.startsWith(NODE_LAUNCH_PROOF_PREFIX))], {
  stdio: "inherit",
  // A headless Windows parent (Task Scheduler, dashboard restart, shortcut) has no
  // console to inherit. Without this flag Windows allocates a visible console for
  // the long-running Bun child, and closing that window kills the proxy (#1236).
  windowsHide: true,
  env: {
    // A cache shared with another Bun version (the CI test runner's) is evicted on every start.
    ...scopeTranspilerCacheToRuntime(inheritedEnv, bunRuntime.version, join),
    [NODE_LAUNCH_CONTEXT_ENV]: launchContext,
    [BUN_RUNTIME_SOURCE_ENV]: bunRuntime.source,
    [BUN_RUNTIME_PATH_ENV]: bunRuntime.path,
  },
});
forwarding.attach(child);
let delegateError = false;
if (child.pid) {
  try { addSyncDelegate(child.pid); }
  catch (error) {
    delegateError = true;
    console.error(`opencodex: sync mutex delegate publication failed: ${error.message}`);
    try { child.kill(); } catch (killError) { console.error(`opencodex: failed to stop sync child: ${killError.message}`); }
  }
}

child.on("error", err => {
  forwarding.clear();
  console.error(`opencodex: failed to launch Bun runtime: ${err.message}`);
  process.exit(1);
});

child.on("exit", (code, signal) => {
  forwarding.clear();
  releaseSyncLease();
  if (delegateError) process.exit(1);
  // Mirror the child's terminating signal/exit code so this launcher's status matches.
  if (signal) {
    relayOwnSignal(signal);
    return;
  }
  process.exit(code ?? 1);
});