From 83004ba7f542b266f1122473a8042bcd9d163cdb Mon Sep 17 00:00:00 2001 From: Josh Winters Date: Mon, 16 Nov 2026 01:50:51 -0500 Subject: [PATCH 1/3] Defer host launch when runtime update lock is unavailable --- README.md | 4 +++- docs/SECURITY-REVIEW.md | 3 ++- package-lock.json | 4 ++-- package.json | 2 +- src/runtime/claude-code-adapter.ts | 11 ++++++++++- src/runtime/cli.ts | 8 ++++++-- src/runtime/codex-adapter.ts | 11 ++++++++++- tests/runtime/adapter-utils.test.ts | 23 ++++++++++++++++++++++- tests/runtime/runtime-auto-update.test.ts | 9 +++++++++ 9 files changed, 65 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index e080414..242d008 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,9 @@ disabled, and writes the wrappers into `~/.crosshead/bin`. (the default), checking for a new release about once an hour and retrying failed checks after 30 minutes. Before installing, Crosshead verifies GitHub's signed build attestation for the exact archive digest and this repository's release workflow. If verification or download fails, the host still launches and the -update is retried later. `crosshead update --manual` disables automatic +update is retried later. If another install still holds the update lock and +the launch check times out, launch is deferred; retry after the install +finishes. `crosshead update --manual` disables automatic updates. `crosshead update --policy` shows the current setting. The older `--pin` option remains an alias for `--manual`. diff --git a/docs/SECURITY-REVIEW.md b/docs/SECURITY-REVIEW.md index a28db28..e2e735a 100644 --- a/docs/SECURITY-REVIEW.md +++ b/docs/SECURITY-REVIEW.md @@ -70,7 +70,8 @@ from it is in scope. workflow and tag before installing. In `manual` mode, the operator supplies a trusted SHA-256 from an independent channel. Both paths validate archive entries and run `npm ci --omit=dev --ignore-scripts` with install scripts - disabled. A failed update check does not prevent the host from launching. + disabled. Remote verification and download failures do not prevent host + launch; a failure to establish the update lock and host lease defers it. See `src/runtime/release-attestation.ts`, `runtime-auto-update.ts`, and `validateRuntimeReleaseArchive`. 2. **Local daemon HTTP API.** It binds `127.0.0.1` on a configurable port diff --git a/package-lock.json b/package-lock.json index 11c1c88..cd59136 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@crosshead/runtime", - "version": "0.5.0-alpha.14", + "version": "0.5.0-alpha.15", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@crosshead/runtime", - "version": "0.5.0-alpha.14", + "version": "0.5.0-alpha.15", "license": "Apache-2.0", "dependencies": { "@noble/curves": "^1.9.7", diff --git a/package.json b/package.json index da456db..55d5991 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@crosshead/runtime", - "version": "0.5.0-alpha.14", + "version": "0.5.0-alpha.15", "description": "Crosshead local runtime: persistent memory for Claude Code, Codex, Pi, Hermes and OpenCode. CLI, daemon, host adapters and hooks.", "license": "Apache-2.0", "private": true, diff --git a/src/runtime/claude-code-adapter.ts b/src/runtime/claude-code-adapter.ts index 0b21622..1e9d75c 100644 --- a/src/runtime/claude-code-adapter.ts +++ b/src/runtime/claude-code-adapter.ts @@ -475,7 +475,16 @@ export CROSSHEAD_HOME="$ONLYBOTS_HOME" export ONLYBOTS_RUNTIME_HOME=${shellQuote(config.runtimeHome)} if [[ -x ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} ]]; then - ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} update --check-on-launch --host-pid "$$" >&2 || printf 'Crosshead update check failed; continuing host launch.\n' >&2 + if ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} update --check-on-launch --host-pid "$$" >&2; then + : + else + update_status=$? + if [[ "$update_status" -eq 75 ]]; then + printf 'Crosshead could not safely check for updates; retry host launch after the update finishes.\n' >&2 + exit 75 + fi + printf 'Crosshead update check failed; continuing host launch.\n' >&2 + fi fi exec ${shellQuote(config.claudeBinary)} "$@" `; diff --git a/src/runtime/cli.ts b/src/runtime/cli.ts index a750d81..fa19b56 100644 --- a/src/runtime/cli.ts +++ b/src/runtime/cli.ts @@ -36,6 +36,10 @@ const renderOnlyBotsCtlCliError = ( error: unknown ): { stream: "stdout" | "stderr"; output: string; exitCode: number } => { const message = error instanceof Error ? error.message : String(error); + // Launchers may continue after ordinary update failures reported as text by + // maintainRuntimeBeforeLaunch, but an exception means the host lease may not + // have been recorded. Reserve 75 so wrappers defer the host launch. + const exitCode = argv[0] === "update" && argv.includes("--check-on-launch") ? 75 : 1; const hosted = error instanceof HostedOnlyBotsRequestError ? error : null; const remediation = hosted ? buildRuntimeBillingRemediation({ @@ -61,14 +65,14 @@ const renderOnlyBotsCtlCliError = ( null, 2 ), - exitCode: 1, + exitCode, }; } return { stream: "stderr", output: remediation ? `${message}\n${formatRuntimeBillingRemediation(remediation)}` : message, - exitCode: 1, + exitCode, }; }; diff --git a/src/runtime/codex-adapter.ts b/src/runtime/codex-adapter.ts index 0d2b51e..d2aa643 100644 --- a/src/runtime/codex-adapter.ts +++ b/src/runtime/codex-adapter.ts @@ -468,7 +468,16 @@ export CROSSHEAD_HOME="$ONLYBOTS_HOME" export ONLYBOTS_RUNTIME_HOME=${shellQuote(config.runtimeHome)} if [[ -x ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} ]]; then - ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} update --check-on-launch --host-pid "$$" >&2 || printf 'Crosshead update check failed; continuing host launch.\n' >&2 + if ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} update --check-on-launch --host-pid "$$" >&2; then + : + else + update_status=$? + if [[ "$update_status" -eq 75 ]]; then + printf 'Crosshead could not safely check for updates; retry host launch after the update finishes.\n' >&2 + exit 75 + fi + printf 'Crosshead update check failed; continuing host launch.\n' >&2 + fi fi exec ${shellQuote(config.codexBinary)} --enable hooks "$@" `; diff --git a/tests/runtime/adapter-utils.test.ts b/tests/runtime/adapter-utils.test.ts index a334bd2..da89dd5 100644 --- a/tests/runtime/adapter-utils.test.ts +++ b/tests/runtime/adapter-utils.test.ts @@ -3,7 +3,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, import os from "node:os"; import path from "node:path"; import { runInNewContext } from "node:vm"; -import { execFileSync } from "node:child_process"; +import { execFileSync, spawnSync } from "node:child_process"; import { buildWrapperScript, @@ -215,6 +215,27 @@ printf '%s\\n' "\${CODEX_HOME:-\${CLAUDE_CONFIG_DIR:-\${CLAUDE_CODE_HOME:-}}}" " } finally { rmSync(fixture, { recursive: true, force: true }); } }); + it.each(["codex", "claude"])("defers %s launch when update safety cannot be established", host => { + const fixture = mkdtempSync(path.join(os.tmpdir(), "crosshead-locked-launch-")); + try { + const runtimeHome = path.join(fixture, "runtime"); + const hostBinary = path.join(fixture, "host-stub"); + const wrapper = path.join(fixture, "launcher"); + mkdirSync(path.join(runtimeHome, "bin"), { recursive: true }); + writeFileSync(path.join(runtimeHome, "bin", "onlybotsctl"), "#!/bin/sh\nexit 75\n", { mode: 0o755 }); + writeFileSync(hostBinary, "#!/bin/sh\nprintf 'host launched\\n'\n", { mode: 0o755 }); + const common = { marker: "test", adapterVersion: "test", runtimeHome, hostHome: path.join(fixture, "host"), + profileName: "default", installedAt: "now", updatedAt: "now" }; + writeFileSync(wrapper, host === "codex" + ? renderCodexLaunchWrapper({ ...common, adapterName: "codex", codexBinary: hostBinary, skillName: "test" }) + : renderClaudeLaunchWrapper({ ...common, adapterName: "claude-code", claudeBinary: hostBinary, workspaceRoot: fixture })); + const result = spawnSync("bash", [wrapper], { encoding: "utf8", env: { PATH: process.env.PATH } }); + expect(result.status).toBe(75); + expect(result.stdout).not.toContain("host launched"); + expect(result.stderr).toContain("retry host launch"); + } finally { rmSync(fixture, { recursive: true, force: true }); } + }); + it("quotes every configured Codex and Claude path as a single shell word", () => { const hostile = `/tmp/host'$(touch /tmp/crosshead-shell-injection)`; const common = { marker: "test", adapterVersion: "test", runtimeHome: hostile, hostHome: hostile, diff --git a/tests/runtime/runtime-auto-update.test.ts b/tests/runtime/runtime-auto-update.test.ts index f04b4ae..025e64c 100644 --- a/tests/runtime/runtime-auto-update.test.ts +++ b/tests/runtime/runtime-auto-update.test.ts @@ -4,6 +4,7 @@ import path from "path"; import { describe, expect, it, vi } from "vitest"; import { maintainRuntimeBeforeLaunch, runtimeUpdatePolicy, nativeHostProcessesRunning } from "../../src/runtime/runtime-auto-update"; import { updateFromCli } from "../../src/runtime/cli/core"; +import { runOnlyBotsCtlCliEntrypoint } from "../../src/runtime/cli"; import { fetchRuntimeReleaseArtifact, inspectInstalledRuntimeRelease, isAllowedRuntimeReleaseUrl, parseWrapperScriptTarget, resolveReleaseUpdateBaseUrl, updateManagedRuntimeRelease, runRuntimeInstallCommand } from "../../src/runtime/local-runtime"; import { shellQuote } from "../../src/runtime/adapter-utils"; import { ensureRuntimeHomeLayout, writeJsonFile } from "../../src/runtime/runtime-persistence"; @@ -46,6 +47,14 @@ const autoSetup = () => { }; describe("published runtime automatic updates", () => { + it("returns a distinct failure when launch safety was not established", async () => { + const exit = vi.fn(); + const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true); + try { + await runOnlyBotsCtlCliEntrypoint(["update", "--check-on-launch", "--host-pid", "0"], exit); + expect(exit).toHaveBeenCalledExactlyOnceWith(75); + } finally { stderr.mockRestore(); } + }); it("detects the single-quoted wrapper emitted by the real installer", () => { const { home, p } = setup(); expect(inspectInstalledRuntimeRelease(p).releaseId).toBe("old"); From ff9180eacb42a876f5d8703cc8a74782740e2716 Mon Sep 17 00:00:00 2001 From: Josh Winters Date: Mon, 16 Nov 2026 01:52:45 -0500 Subject: [PATCH 2/3] Require successful maintenance check before managed host launch --- src/runtime/claude-code-adapter.ts | 18 +++++++----------- src/runtime/cli.ts | 8 ++------ src/runtime/codex-adapter.ts | 18 +++++++----------- tests/runtime/adapter-utils.test.ts | 15 ++++++++------- tests/runtime/runtime-auto-update.test.ts | 9 --------- 5 files changed, 24 insertions(+), 44 deletions(-) diff --git a/src/runtime/claude-code-adapter.ts b/src/runtime/claude-code-adapter.ts index 1e9d75c..3089f28 100644 --- a/src/runtime/claude-code-adapter.ts +++ b/src/runtime/claude-code-adapter.ts @@ -474,17 +474,13 @@ export ONLYBOTS_HOME=${shellQuote(config.runtimeHome)} export CROSSHEAD_HOME="$ONLYBOTS_HOME" export ONLYBOTS_RUNTIME_HOME=${shellQuote(config.runtimeHome)} -if [[ -x ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} ]]; then - if ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} update --check-on-launch --host-pid "$$" >&2; then - : - else - update_status=$? - if [[ "$update_status" -eq 75 ]]; then - printf 'Crosshead could not safely check for updates; retry host launch after the update finishes.\n' >&2 - exit 75 - fi - printf 'Crosshead update check failed; continuing host launch.\n' >&2 - fi +if [[ ! -x ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} ]]; then + printf 'Crosshead update check is unavailable; retry host launch after repairing the runtime.\n' >&2 + exit 1 +fi +if ! ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} update --check-on-launch --host-pid "$$" >&2; then + printf 'Crosshead could not safely check for updates; retry host launch after the update finishes.\n' >&2 + exit 1 fi exec ${shellQuote(config.claudeBinary)} "$@" `; diff --git a/src/runtime/cli.ts b/src/runtime/cli.ts index fa19b56..a750d81 100644 --- a/src/runtime/cli.ts +++ b/src/runtime/cli.ts @@ -36,10 +36,6 @@ const renderOnlyBotsCtlCliError = ( error: unknown ): { stream: "stdout" | "stderr"; output: string; exitCode: number } => { const message = error instanceof Error ? error.message : String(error); - // Launchers may continue after ordinary update failures reported as text by - // maintainRuntimeBeforeLaunch, but an exception means the host lease may not - // have been recorded. Reserve 75 so wrappers defer the host launch. - const exitCode = argv[0] === "update" && argv.includes("--check-on-launch") ? 75 : 1; const hosted = error instanceof HostedOnlyBotsRequestError ? error : null; const remediation = hosted ? buildRuntimeBillingRemediation({ @@ -65,14 +61,14 @@ const renderOnlyBotsCtlCliError = ( null, 2 ), - exitCode, + exitCode: 1, }; } return { stream: "stderr", output: remediation ? `${message}\n${formatRuntimeBillingRemediation(remediation)}` : message, - exitCode, + exitCode: 1, }; }; diff --git a/src/runtime/codex-adapter.ts b/src/runtime/codex-adapter.ts index d2aa643..ec893b2 100644 --- a/src/runtime/codex-adapter.ts +++ b/src/runtime/codex-adapter.ts @@ -467,17 +467,13 @@ export ONLYBOTS_HOME=${shellQuote(config.runtimeHome)} export CROSSHEAD_HOME="$ONLYBOTS_HOME" export ONLYBOTS_RUNTIME_HOME=${shellQuote(config.runtimeHome)} -if [[ -x ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} ]]; then - if ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} update --check-on-launch --host-pid "$$" >&2; then - : - else - update_status=$? - if [[ "$update_status" -eq 75 ]]; then - printf 'Crosshead could not safely check for updates; retry host launch after the update finishes.\n' >&2 - exit 75 - fi - printf 'Crosshead update check failed; continuing host launch.\n' >&2 - fi +if [[ ! -x ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} ]]; then + printf 'Crosshead update check is unavailable; retry host launch after repairing the runtime.\n' >&2 + exit 1 +fi +if ! ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} update --check-on-launch --host-pid "$$" >&2; then + printf 'Crosshead could not safely check for updates; retry host launch after the update finishes.\n' >&2 + exit 1 fi exec ${shellQuote(config.codexBinary)} --enable hooks "$@" `; diff --git a/tests/runtime/adapter-utils.test.ts b/tests/runtime/adapter-utils.test.ts index da89dd5..7a5bf87 100644 --- a/tests/runtime/adapter-utils.test.ts +++ b/tests/runtime/adapter-utils.test.ts @@ -196,7 +196,7 @@ printf '%s\\n' "\${CODEX_HOME:-\${CLAUDE_CONFIG_DIR:-\${CLAUDE_CODE_HOME:-}}}" " }, ); - it.each(["codex", "claude"])("launches %s when the update check fails", host => { + it.each(["codex", "claude"])("defers %s when the update check fails", host => { const fixture = mkdtempSync(path.join(os.tmpdir(), "crosshead-failed-update-check-")); try { const runtimeHome = path.join(fixture, "runtime"); @@ -210,19 +210,20 @@ printf '%s\\n' "\${CODEX_HOME:-\${CLAUDE_CONFIG_DIR:-\${CLAUDE_CODE_HOME:-}}}" " writeFileSync(wrapper, host === "codex" ? renderCodexLaunchWrapper({ ...common, adapterName: "codex", codexBinary: hostBinary, skillName: "test" }) : renderClaudeLaunchWrapper({ ...common, adapterName: "claude-code", claudeBinary: hostBinary, workspaceRoot: fixture })); - const output = execFileSync("bash", [wrapper], { encoding: "utf8", env: { PATH: process.env.PATH } }); - expect(output).toContain("host launched"); + const result = spawnSync("bash", [wrapper], { encoding: "utf8", env: { PATH: process.env.PATH } }); + expect(result.status).toBe(1); + expect(result.stdout).not.toContain("host launched"); + expect(result.stderr).toContain("retry host launch"); } finally { rmSync(fixture, { recursive: true, force: true }); } }); - it.each(["codex", "claude"])("defers %s launch when update safety cannot be established", host => { + it.each(["codex", "claude"])("defers %s launch when the update check is missing", host => { const fixture = mkdtempSync(path.join(os.tmpdir(), "crosshead-locked-launch-")); try { const runtimeHome = path.join(fixture, "runtime"); const hostBinary = path.join(fixture, "host-stub"); const wrapper = path.join(fixture, "launcher"); mkdirSync(path.join(runtimeHome, "bin"), { recursive: true }); - writeFileSync(path.join(runtimeHome, "bin", "onlybotsctl"), "#!/bin/sh\nexit 75\n", { mode: 0o755 }); writeFileSync(hostBinary, "#!/bin/sh\nprintf 'host launched\\n'\n", { mode: 0o755 }); const common = { marker: "test", adapterVersion: "test", runtimeHome, hostHome: path.join(fixture, "host"), profileName: "default", installedAt: "now", updatedAt: "now" }; @@ -230,9 +231,9 @@ printf '%s\\n' "\${CODEX_HOME:-\${CLAUDE_CONFIG_DIR:-\${CLAUDE_CODE_HOME:-}}}" " ? renderCodexLaunchWrapper({ ...common, adapterName: "codex", codexBinary: hostBinary, skillName: "test" }) : renderClaudeLaunchWrapper({ ...common, adapterName: "claude-code", claudeBinary: hostBinary, workspaceRoot: fixture })); const result = spawnSync("bash", [wrapper], { encoding: "utf8", env: { PATH: process.env.PATH } }); - expect(result.status).toBe(75); + expect(result.status).toBe(1); expect(result.stdout).not.toContain("host launched"); - expect(result.stderr).toContain("retry host launch"); + expect(result.stderr).toContain("update check is unavailable"); } finally { rmSync(fixture, { recursive: true, force: true }); } }); diff --git a/tests/runtime/runtime-auto-update.test.ts b/tests/runtime/runtime-auto-update.test.ts index 025e64c..f04b4ae 100644 --- a/tests/runtime/runtime-auto-update.test.ts +++ b/tests/runtime/runtime-auto-update.test.ts @@ -4,7 +4,6 @@ import path from "path"; import { describe, expect, it, vi } from "vitest"; import { maintainRuntimeBeforeLaunch, runtimeUpdatePolicy, nativeHostProcessesRunning } from "../../src/runtime/runtime-auto-update"; import { updateFromCli } from "../../src/runtime/cli/core"; -import { runOnlyBotsCtlCliEntrypoint } from "../../src/runtime/cli"; import { fetchRuntimeReleaseArtifact, inspectInstalledRuntimeRelease, isAllowedRuntimeReleaseUrl, parseWrapperScriptTarget, resolveReleaseUpdateBaseUrl, updateManagedRuntimeRelease, runRuntimeInstallCommand } from "../../src/runtime/local-runtime"; import { shellQuote } from "../../src/runtime/adapter-utils"; import { ensureRuntimeHomeLayout, writeJsonFile } from "../../src/runtime/runtime-persistence"; @@ -47,14 +46,6 @@ const autoSetup = () => { }; describe("published runtime automatic updates", () => { - it("returns a distinct failure when launch safety was not established", async () => { - const exit = vi.fn(); - const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true); - try { - await runOnlyBotsCtlCliEntrypoint(["update", "--check-on-launch", "--host-pid", "0"], exit); - expect(exit).toHaveBeenCalledExactlyOnceWith(75); - } finally { stderr.mockRestore(); } - }); it("detects the single-quoted wrapper emitted by the real installer", () => { const { home, p } = setup(); expect(inspectInstalledRuntimeRelease(p).releaseId).toBe("old"); From df9fe5e111249c8a7b3ca625dbd48182b7eae717 Mon Sep 17 00:00:00 2001 From: Josh Winters Date: Mon, 16 Nov 2026 02:01:12 -0500 Subject: [PATCH 3/3] Guard operator updates and staged release applies against live hosts --- README.md | 4 +++- docs/SECURITY-REVIEW.md | 3 +++ src/runtime/cli.ts | 6 ++--- src/runtime/cli/core.ts | 22 ++++++++++++----- src/runtime/local-runtime.ts | 8 +++++-- src/runtime/runtime-auto-update.ts | 29 ++++++++++++++++++++++- tests/runtime/runtime-auto-update.test.ts | 25 ++++++++++++++++--- 7 files changed, 81 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 242d008..ddd01d0 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,9 @@ updates. `crosshead update --policy` shows the current setting. The older `--pin` option remains an alias for `--manual`. For a manual install, obtain the digest from an independent release channel -and run `crosshead update --sha256 `. +and run `crosshead update --sha256 `. Operator updates and rollbacks +refuse to change runtime files while a host is running. Close host sessions +first, or use `--force` at the end of the command to update during a session. To check that a release matches this source, compare the installer's `RELEASE_SHA256` with `SHA256SUMS` on the matching GitHub release. Public diff --git a/docs/SECURITY-REVIEW.md b/docs/SECURITY-REVIEW.md index e2e735a..a0091c7 100644 --- a/docs/SECURITY-REVIEW.md +++ b/docs/SECURITY-REVIEW.md @@ -72,6 +72,9 @@ from it is in scope. entries and run `npm ci --omit=dev --ignore-scripts` with install scripts disabled. Remote verification and download failures do not prevent host launch; a failure to establish the update lock and host lease defers it. + Operator updates and rollbacks check live host leases and native processes + under the update lock. Staged release installs recheck immediately before + applying. `--force` explicitly bypasses the active-host guard. See `src/runtime/release-attestation.ts`, `runtime-auto-update.ts`, and `validateRuntimeReleaseArchive`. 2. **Local daemon HTTP API.** It binds `127.0.0.1` on a configurable port diff --git a/src/runtime/cli.ts b/src/runtime/cli.ts index a750d81..cbd335b 100644 --- a/src/runtime/cli.ts +++ b/src/runtime/cli.ts @@ -311,10 +311,10 @@ export const runOnlyBotsCtlCli = async ( "crosshead billing invoice (--invoice-id |--payment-hash ) [--home ] [--profile ] [--json]", "crosshead check-updates [--home ] [--channel stable|beta|canary] [--json]", "crosshead apply [--home ] [--manifest ]", - "crosshead update --sha256 [--home ] [--no-restart]", + "crosshead update --sha256 [--home ] [--no-restart] [--force]", "crosshead update --manual|--auto|--policy [--home ]", - "crosshead update [adapter] [--home ] [--channel stable|beta|canary] [--version ]", - "crosshead rollback [adapter] --to [--home ]", + "crosshead update [adapter] [--home ] [--channel stable|beta|canary] [--version ] [--force]", + "crosshead rollback [adapter] --to [--home ] [--force]", "crosshead doctor [--home ] [--workspace-root ] [--json]", "crosshead workspace add --workspace-root --adapter codex|claude-code|both --profile [--source-excerpts on|off] [--replace-user-hooks] [--dry-run] [--json]", "crosshead workspace remove --workspace-root [--adapter codex|claude-code|both] [--dry-run] [--json]", diff --git a/src/runtime/cli/core.ts b/src/runtime/cli/core.ts index 1dae2f4..5b38f2a 100644 --- a/src/runtime/cli/core.ts +++ b/src/runtime/cli/core.ts @@ -2,7 +2,7 @@ import { OnlyBotsLocalRuntimeDaemon, RuntimeAdapterName, RuntimeChannel, Runtime import path from "path"; import { RUNTIME_ADAPTER_NAMES, ensureRuntimeHomeLayout, loadAdapterRecord, loadRuntimeConfig, resolveRuntimeHome } from "../runtime-persistence"; import { billingFromCli } from "./billing"; -import { maintainRuntimeBeforeLaunch, runtimeUpdatePolicy, withRuntimeUpdateLock } from "../runtime-auto-update"; +import { assertNoLiveRuntimeHosts, maintainRuntimeBeforeLaunch, runtimeUpdatePolicy, withRuntimeUpdateLock } from "../runtime-auto-update"; import { DEFAULT_CHECKOUT_CREDIT_UNITS } from "../billing-remediation"; import { inspectHostHookRegistrations } from "../host-hook-doctor"; import { inspectWorkspaceHooks, workspaceBindingStatus } from "../workspace-hooks"; @@ -64,12 +64,16 @@ export const updateFromCli = async (argv: string[]): Promise => { const channel = typeof flags.channel === "string" ? (flags.channel as RuntimeChannel) : config.channel; const versionOverride = typeof flags.version === "string" ? flags.version : undefined; const target = positionals[0]; + const mutate = (action: () => Promise): Promise => withRuntimeUpdateLock(paths.home, () => { + assertNoLiveRuntimeHosts(paths.home, flags.force === true); + return action(); + }); if (target && RUNTIME_ADAPTER_NAMES.includes(target as RuntimeAdapterName)) { const adapterName = target as RuntimeAdapterName; const adapter = loadAdapterRecord(paths, adapterName); const targetVersion = resolveAdapterTargetVersion(adapterName, channel, versionOverride); - await updateRuntimeAdapterVersion(paths.home, adapterName, targetVersion); + await mutate(() => updateRuntimeAdapterVersion(paths.home, adapterName, targetVersion)); return [ `Updated ${adapterName}`, `channel: ${channel}`, @@ -78,11 +82,12 @@ export const updateFromCli = async (argv: string[]): Promise => { } if (typeof flags["base-url"] === "string" || typeof flags.baseUrl === "string" || (!versionOverride && typeof flags.channel !== "string")) { - const result = await withRuntimeUpdateLock(paths.home, async () => { + const result = await mutate(async () => { const updated = await updateManagedRuntimeRelease(paths.home, { baseUrl: typeof flags["base-url"] === "string" ? flags["base-url"] : typeof flags.baseUrl === "string" ? flags.baseUrl : undefined, trustedSha256: typeof flags.sha256 === "string" ? flags.sha256 : undefined, restart: !flags["no-restart"], + beforeApply: () => assertNoLiveRuntimeHosts(paths.home, flags.force === true), }); if (runtimeUpdatePolicy(paths.home).mode === "manual") runtimeUpdatePolicy(paths.home, "manual"); return updated; @@ -90,7 +95,7 @@ export const updateFromCli = async (argv: string[]): Promise => { return formatRuntimeReleaseUpdate(result); } - const updated = await updateRuntimeCatalogInstall(paths.home, channel, versionOverride); + const updated = await mutate(() => updateRuntimeCatalogInstall(paths.home, channel, versionOverride)); return [ "Updated runtime install metadata", `channel: ${channel}`, @@ -109,11 +114,16 @@ export const rollbackFromCli = async (argv: string[]): Promise => { throw new Error("rollback requires --to "); } const target = positionals[0]; + const runtimeHome = resolveRuntimeHome(home); + const mutate = (action: () => Promise): Promise => withRuntimeUpdateLock(runtimeHome, () => { + assertNoLiveRuntimeHosts(runtimeHome, flags.force === true); + return action(); + }); if (target && RUNTIME_ADAPTER_NAMES.includes(target as RuntimeAdapterName)) { - await rollbackRuntimeAdapterVersion(resolveRuntimeHome(home), target as RuntimeAdapterName, targetVersion); + await mutate(() => rollbackRuntimeAdapterVersion(runtimeHome, target as RuntimeAdapterName, targetVersion)); return `Rolled back ${target} to ${targetVersion}`; } - await rollbackRuntimeCoreVersion(resolveRuntimeHome(home), targetVersion); + await mutate(() => rollbackRuntimeCoreVersion(runtimeHome, targetVersion)); return `Rolled back runtime core to ${targetVersion}`; }; diff --git a/src/runtime/local-runtime.ts b/src/runtime/local-runtime.ts index bab6c51..7b8037c 100644 --- a/src/runtime/local-runtime.ts +++ b/src/runtime/local-runtime.ts @@ -1630,7 +1630,8 @@ const downloadRuntimeRelease = async ( explicitBaseUrl?: string, trustedSha256?: string, timeoutMs = 120_000, - expectedReleaseId?: string + expectedReleaseId?: string, + beforeApply?: () => void ): Promise => { const baseUrl = resolveReleaseUpdateBaseUrl(paths, explicitBaseUrl); if (!trustedSha256 || !/^[a-f0-9]{64}$/.test(trustedSha256)) { @@ -1702,6 +1703,7 @@ const downloadRuntimeRelease = async ( const npmExecutable = path.join(path.dirname(process.execPath), process.platform === "win32" ? "npm.cmd" : "npm"); if (!existsSync(npmExecutable)) throw new Error(`Runtime update cannot find npm beside ${process.execPath}`); await runRuntimeInstallCommand(npmExecutable, ["ci", "--omit=dev", "--ignore-scripts", "--no-audit", "--no-fund", "--fetch-timeout=15000", "--fetch-retries=1"], stageRoot, timeoutMs); + beforeApply?.(); rmSync(releaseRoot, { recursive: true, force: true }); renameSync(stageRoot, releaseRoot); } finally { @@ -1888,13 +1890,14 @@ export const updateManagedRuntimeRelease = async ( restart?: boolean; timeoutMs?: number; expectedReleaseId?: string; + beforeApply?: () => void; } = {} ): Promise => { readWorkspaceHookPolicy(resolveRuntimePaths(home)); const paths = ensureRuntimeHomeLayout(home); const previousRelease = inspectInstalledRuntimeRelease(paths); const specs = await collectManagedAdapterReinstallSpecs(paths); - const release = await downloadRuntimeRelease(paths, options.baseUrl, options.trustedSha256, options.timeoutMs, options.expectedReleaseId); + const release = await downloadRuntimeRelease(paths, options.baseUrl, options.trustedSha256, options.timeoutMs, options.expectedReleaseId, options.beforeApply); // A release must not leave launchers pointing at a half-applied installation. // Keep credentials, memory and queued writes outside this file-level rollback. const protectedFiles = new Set([ @@ -1920,6 +1923,7 @@ export const updateManagedRuntimeRelease = async ( const priorDaemon = loadDaemonState(paths); let restartAttempted = false; try { + options.beforeApply?.(); const reapplied = await reapplyManagedRuntimeRelease(paths, release, specs); restartAttempted = options.restart !== false && priorDaemon.status === "running"; const daemon = await restartRuntimeDaemonIfNeeded(paths, release, options.restart !== false); diff --git a/src/runtime/runtime-auto-update.ts b/src/runtime/runtime-auto-update.ts index 0dbcb12..92cdc6d 100644 --- a/src/runtime/runtime-auto-update.ts +++ b/src/runtime/runtime-auto-update.ts @@ -62,6 +62,28 @@ export const runtimeHasActiveWork = (home: string, hostRunning = () => true): bo return false; }; +/** Call while holding the update lock, before changing files used by a host. */ +export const assertNoLiveRuntimeHosts = ( + home: string, + force = false, + ownerAlive = alive, + nativeHostsRunning = () => nativeHostProcessesRunning(process.pid) +): void => { + if (force) return; + const leases = path.join(ensureRuntimeHomeLayout(home).state, "host-processes"); + for (const file of existsSync(leases) ? readdirSync(leases) : []) { + if (!/^\d+\.json$/.test(file)) continue; + const pid = Number(file.slice(0, -5)); + if (ownerAlive(pid)) { + throw new Error("A managed host is running; close it before updating, or use --force to update during its session"); + } + rmSync(path.join(leases, file)); + } + if (nativeHostsRunning()) { + throw new Error("A Codex or Claude host is running; close it before updating, or use --force to update during its session"); + } +}; + /** Serializes all release installs and update-policy writes across CLI processes. */ export const withRuntimeUpdateLock = async (home: string | undefined, action: () => Promise | T, ownerAlive = alive): Promise => { const paths = ensureRuntimeHomeLayout(home); @@ -141,7 +163,12 @@ export const maintainRuntimeBeforeLaunch = async (home: string | undefined, host if (deps.nativeHostsRunning(hostPid) || hasActiveWork()) return "Crosshead update available; deferred while another host is active."; await deps.verify(candidate[1], release.sha256); if (deps.nativeHostsRunning(hostPid) || hasActiveWork()) return "Crosshead verified update available; deferred while another host is active."; - const updated = await deps.update(paths.home, { trustedSha256: release.sha256, timeoutMs: 45_000, expectedReleaseId: release.available }); + const updated = await deps.update(paths.home, { + trustedSha256: release.sha256, timeoutMs: 45_000, expectedReleaseId: release.available, + beforeApply: () => { + if (deps.nativeHostsRunning(hostPid) || hasActiveWork()) throw new Error("A host became active during the update; retry after it exits"); + }, + }); if (updated.releaseId !== release.available) throw new Error("Installed release did not match the verified release"); writeJsonFile(stateFile, { checkedAtMs: deps.now(), installed: release.available, available: release.available, status: "updated" }); return `Crosshead automatically updated to ${candidate[1]} (signed release verified).`; diff --git a/tests/runtime/runtime-auto-update.test.ts b/tests/runtime/runtime-auto-update.test.ts index f04b4ae..f1b0da3 100644 --- a/tests/runtime/runtime-auto-update.test.ts +++ b/tests/runtime/runtime-auto-update.test.ts @@ -2,8 +2,8 @@ import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs" import os from "os"; import path from "path"; import { describe, expect, it, vi } from "vitest"; -import { maintainRuntimeBeforeLaunch, runtimeUpdatePolicy, nativeHostProcessesRunning } from "../../src/runtime/runtime-auto-update"; -import { updateFromCli } from "../../src/runtime/cli/core"; +import { assertNoLiveRuntimeHosts, maintainRuntimeBeforeLaunch, runtimeUpdatePolicy, nativeHostProcessesRunning } from "../../src/runtime/runtime-auto-update"; +import { rollbackFromCli, updateFromCli } from "../../src/runtime/cli/core"; import { fetchRuntimeReleaseArtifact, inspectInstalledRuntimeRelease, isAllowedRuntimeReleaseUrl, parseWrapperScriptTarget, resolveReleaseUpdateBaseUrl, updateManagedRuntimeRelease, runRuntimeInstallCommand } from "../../src/runtime/local-runtime"; import { shellQuote } from "../../src/runtime/adapter-utils"; import { ensureRuntimeHomeLayout, writeJsonFile } from "../../src/runtime/runtime-persistence"; @@ -193,7 +193,26 @@ describe("published runtime automatic updates", () => { await maintainRuntimeBeforeLaunch(home, 2000, deps); expect(deps.inspect).toHaveBeenCalledTimes(1); expect(deps.verify).toHaveBeenCalledExactlyOnceWith("0.5.0-alpha.14", newDigest); - expect(deps.update).toHaveBeenCalledExactlyOnceWith(home, { trustedSha256: newDigest, timeoutMs: 45_000, expectedReleaseId: newRelease }); + expect(deps.update).toHaveBeenCalledExactlyOnceWith(home, expect.objectContaining({ + trustedSha256: newDigest, timeoutMs: 45_000, expectedReleaseId: newRelease, beforeApply: expect.any(Function), + })); + deps.nativeHostsRunning.mockReturnValue(true); + expect(deps.update.mock.calls[0]![1].beforeApply).toThrow("A host became active"); + }); + it("blocks release, catalog and rollback changes while a managed host is live", async () => { + const { home, p } = autoSetup(); + const leases = path.join(p.state, "host-processes"); + mkdirSync(leases, { recursive: true }); + writeJsonFile(path.join(leases, `${process.pid}.json`), { pid: process.pid }); + await expect(updateFromCli(["--home", home, "--sha256", newDigest])).rejects.toThrow("managed host is running"); + await expect(updateFromCli(["--home", home, "--channel", "stable"])).rejects.toThrow("managed host is running"); + await expect(rollbackFromCli(["--home", home, "--to", "0.3.0"])).rejects.toThrow("managed host is running"); + await expect(updateFromCli(["--home", home, "--force"])).rejects.toThrow("requires --sha256"); + }); + it("checks direct native hosts even without a launcher lease", () => { + const { home } = setup(); + expect(() => assertNoLiveRuntimeHosts(home, false, () => false, () => true)).toThrow("Codex or Claude host is running"); + expect(() => assertNoLiveRuntimeHosts(home, true, () => false, () => true)).not.toThrow(); }); it("offers auto and manual CLI settings and migrates the legacy pinned mode", async () => { const { home, p, deps } = autoSetup();