diff --git a/docs/manage-sandboxes/uninstall-nemoclaw.mdx b/docs/manage-sandboxes/uninstall-nemoclaw.mdx index 518363880ae..dbdc5bdd7f6 100644 --- a/docs/manage-sandboxes/uninstall-nemoclaw.mdx +++ b/docs/manage-sandboxes/uninstall-nemoclaw.mdx @@ -45,6 +45,38 @@ Make `brew` available through `PATH` or inspect the formula before you remove Op For example, `NEMOCLAW_GATEWAY_PORT=9123 $$nemoclaw uninstall` selects `nemoclaw-9123` and its port-scoped state. Do not use `--gateway` to select another instance; when supplied for compatibility, its value must match the derived name or uninstall stops before cleanup. +## Stop the Amazon Bedrock Runtime Adapter + +The selected gateway can use a host-local Amazon Bedrock Runtime adapter. +Before it removes the selected state root, uninstall stops only the adapter bound to that state. + +Before each signal, uninstall revalidates the canonical PID, current user, stable process start identity, lifecycle generation, executable path, launcher path, and adapter port. +Before it deletes lifecycle evidence, uninstall revalidates process absence, the state generation, the PID, and the local bearer-token hash. +If the adapter remains after `SIGTERM` and `SIGKILL`, uninstall exits nonzero before state-root cleanup. +It preserves the selected gateway's PID, bearer token, any lifecycle state that was published, and prepared uninstall journal for a retry. +If required evidence conflicts before journal preparation, uninstall preserves that evidence and does not signal a process. + +The lifecycle evidence is `/bedrock-runtime-adapter.pid`, `/bedrock-runtime-adapter-token`, and `/bedrock-runtime-adapter.json`. +If startup leaves only a private PID file containing one canonical positive PID, uninstall does not signal that PID. +Under the adapter lifecycle lock, uninstall removes only the unchanged PID file after it observes that the PID is absent twice. +It also confirms that no bearer token, lifecycle state, or uninstall journal appeared between those checks. +A live or uninspectable PID, malformed or changed PID file, or newly published evidence makes uninstall exit nonzero. +Uninstall preserves the PID file and any new lifecycle evidence in those cases. +Keep those files intact while you resolve the reported process or state conflict. +Rerun uninstall with the same `NEMOCLAW_GATEWAY_PORT` value afterward. +The journal is `~/.local/state/nemoclaw-bedrock-runtime-adapter//uninstall.json`. +Onboarding refuses to start another Amazon Bedrock adapter generation while that journal or non-reusable lifecycle evidence remains. +If an older lifecycle record cannot prove the live process generation, NemoClaw does not signal that process. +Do not signal a process from the saved PID alone; independently verify the current user, process start, executable path, launcher path, and listening port before resolving it, then rerun uninstall. + +While an adapter remains alive, its process retains any forwarded AWS credential until the process exits. +After you resolve a failed stop, rerunning uninstall retires the local bearer token and lifecycle evidence. +Remove or rotate the upstream AWS credential through its owning AWS credential source when required. + +Only full uninstall checks the configured adapter port when a recorded adapter PID file is absent. +It never signals an unbound listener without matching lifecycle state. +A selected-gateway uninstall uses only the selected state root and does not scan for a sibling gateway's adapter. + ## Delete Host Models The `--delete-models` flag is an explicit opt-in for deleting host model files. diff --git a/docs/reference/host-files-and-state.mdx b/docs/reference/host-files-and-state.mdx index 6ed91d2314f..2d218c6283c 100644 --- a/docs/reference/host-files-and-state.mdx +++ b/docs/reference/host-files-and-state.mdx @@ -9,12 +9,14 @@ keywords: ["nemoclaw host files", "nemoclaw state directory", "nemoclaw sandboxe content: type: "reference" --- -NemoClaw stores host-side configuration, registry metadata, operational state, transient install state, and local backups under `~/.nemoclaw/`. +NemoClaw stores most host-side configuration, registry metadata, operational state, transient install state, and local backups under `~/.nemoclaw/`. +Some lifecycle journals live under `~/.local/state/` so they remain available when an operation removes a selected state root. Managed local inference profiles also use the cache paths listed on this page. Use this page when you need to identify what a file does before deleting, backing up, or sharing diagnostics. -The default OpenShell gateway stores managed llama.cpp state under `~/.nemoclaw/managed-llama-cpp/`. +The default gateway stores managed llama.cpp state under `~/.nemoclaw/managed-llama-cpp/`. A non-default gateway port stores the same files under `~/.nemoclaw/gateways//managed-llama-cpp/`. +For the Amazon Bedrock adapter rows below, `` is `~/.nemoclaw/` for port `8080` or `~/.nemoclaw/gateways//` for another port. The `nemo-deepagents` alias uses the same host-side `~/.nemoclaw/` configuration, sandbox registry, operational state, backup, and mount directories as the default NemoClaw CLI. @@ -37,6 +39,10 @@ Unless a row says otherwise, full-uninstall removal behavior in this table appli | `~/.nemoclaw/portable-uninstall-retirement.json` | Current-user-owned portable cleanup recovery authority, written at mode `0600` under the current-user-owned, mode-`0700` `~/.nemoclaw/` directory. It binds exact cleanup targets and remains after cleanup until a later completed onboarding durably supersedes it. Its hashes are dictionary-testable pseudonymous fingerprints, not secrets. | No while cleanup, retry, or supersession recovery may be needed. Do not remove it manually; later completed onboarding retires it. | | `~/.nemoclaw/onboard-session.json` | Resume marker for an onboarding attempt that failed before completion. | Yes, when you intentionally want to discard the failed session and start over. Prefer `$$nemoclaw onboard --fresh` when available. | | `~/.nemoclaw/usage-notice.json` | Records the third-party software notice version in `acceptedVersion` and the acceptance time in `acceptedAt`. Install, onboarding, and rebuild flows consult this file and prompt again when its recorded version differs from the current notice or the file is absent. | Yes; deleting it makes the next applicable install, onboarding, or rebuild flow prompt for acceptance again. | +| `/bedrock-runtime-adapter.pid` | Mode-`0600` canonical PID for the selected gateway's host-local Amazon Bedrock Runtime adapter. Uninstall correlates it with the lifecycle state and journal before it signals a process. | No while the adapter or an unfinished uninstall journal exists. Uninstall retires it only after it proves the recorded process is absent. | +| `/bedrock-runtime-adapter-token` | Mode-`0600` local bearer token that authenticates requests to the selected gateway's Amazon Bedrock Runtime adapter. This token is separate from the upstream AWS credential held by the adapter process. | No while the adapter or an unfinished uninstall journal exists. Uninstall removes it only after process absence and lifecycle generation match the journal. | +| `/bedrock-runtime-adapter.json` | Mode-`0600` lifecycle state that binds the adapter generation, canonical PID, process start identity, current user, executable and launcher paths, adapter port, and token hash. It does not contain the bearer token. | No while the adapter or an unfinished uninstall journal exists. Keep it for fail-closed uninstall recovery. | +| `~/.local/state/nemoclaw-bedrock-runtime-adapter//uninstall.json` | Mode-`0600` per-gateway phase journal for Amazon Bedrock adapter cleanup. It remains outside the selected state root so an interrupted uninstall can resume the exact generation. Onboarding refuses to start another generation while this journal remains unfinished. | No. Rerun uninstall with the same gateway port and let successful cleanup retire the journal. | | `~/.nemoclaw/ollama-proxy-token` | Host-global auth token used by the host-side Ollama auth proxy. Every gateway port on the host uses this one file. | Yes, but rerun onboarding for every gateway port that uses Local Ollama afterward, because a new token invalidates the shared proxy for all of them. | | `~/.nemoclaw/ollama-backend` | Host-global legacy route URL used to restart the Ollama auth proxy and retained for compatibility with earlier releases. | No while any gateway uses the shared proxy. Rerun onboarding if this file is missing or damaged. | | `~/.nemoclaw/ollama-backend.json` | Mode-`0600`, versioned descriptor that identifies whether the matching legacy route fronts Ollama or a compatible endpoint. Recovery trusts its kind only when both files contain the same URL. | Yes, but recovery uses neutral remediation until onboarding recreates the descriptor. | @@ -138,6 +144,12 @@ It names the environments it left behind and prints the command that removes one Pass `--all-gateway-ports`, or set `NEMOCLAW_UNINSTALL_ALL_GATEWAY_PORTS=1`, to remove every gateway port in one run. Outside portable cleanup, the shared host state is eligible for removal only when `--keep-openshell` is absent, no port fails or survives, and the selected gateway is not externally supervised. +Before it removes a selected state root, uninstall must prove that its state-bound Amazon Bedrock adapter process is absent. +It revalidates the process identity and lifecycle generation before each signal and revalidates the evidence before deletion. +If a stop remains unresolved after journal preparation, uninstall exits nonzero and preserves the PID, token, any lifecycle state that was published, and per-gateway journal. +An earlier evidence conflict also exits nonzero and preserves every existing lifecycle file. +Only full uninstall performs adapter-port orphan discovery; selected-gateway cleanup does not inspect sibling gateway state. + Portable cleanup instead retires only exact receipt-owned portable resources. It preserves model stores, Podman images, shared OpenShell providers and gateway registrations, the gateway service and process, and shared OpenShell binaries and configuration. It retains `~/.nemoclaw/portable-uninstall-retirement.json` even with `--destroy-user-data` so a retry or later completed onboarding can finish recovery. Before full uninstall deletes shared state, it removes only an exact authenticated host-local vLLM container and exact NemoClaw-owned llama.cpp container and network. diff --git a/src/lib/actions/uninstall/bedrock-runtime-adapter-cleanup.test.ts b/src/lib/actions/uninstall/bedrock-runtime-adapter-cleanup.test.ts new file mode 100644 index 00000000000..4106aecab0a --- /dev/null +++ b/src/lib/actions/uninstall/bedrock-runtime-adapter-cleanup.test.ts @@ -0,0 +1,782 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import crypto from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { describe, expect, it, vi } from "vitest"; + +import { stopBedrockRuntimeAdapter } from "./openrouter-runtime-adapter-cleanup"; + +const PID = 43_210; +const REPLACEMENT_PID = 43_211; +const GENERATION = "11111111111111111111111111111111"; +const REPLACEMENT_GENERATION = "22222222222222222222222222222222"; +const PROCESS_START = "linux:test-boot:100"; +const REPLACEMENT_PROCESS_START = "linux:test-boot:200"; +const SCRIPT_PATH = "/opt/nemoclaw/scripts/bedrock-runtime-adapter.mts"; +const EXECUTABLE_PATH = "/usr/bin/node"; +const TOKEN = "bedrock-local-token"; +const CURRENT_UID = process.getuid?.() ?? 501; +const CURRENT_USER = os.userInfo().username; + +interface AdapterProcess { + argv: readonly string[]; + executablePath: string; + generation: string | null; + processStart: string; + uid: number; + user: string; +} + +function lifecyclePaths(home: string) { + const root = path.join(home, ".local", "state", "nemoclaw-bedrock-runtime-adapter", "8080"); + return { + journalPath: path.join(root, "uninstall.json"), + lockPath: path.join(root, "lifecycle.lock"), + }; +} + +function adapterPaths(home: string) { + const stateDir = path.join(home, ".nemoclaw"); + return { + pidPath: path.join(stateDir, "bedrock-runtime-adapter.pid"), + stateDir, + statePath: path.join(stateDir, "bedrock-runtime-adapter.json"), + tokenPath: path.join(stateDir, "bedrock-runtime-adapter-token"), + }; +} + +function adapterState(pid = PID, generation = GENERATION, processStart = PROCESS_START) { + return { + version: 2, + generation, + pid, + processStart, + user: CURRENT_USER, + uid: CURRENT_UID, + executablePath: EXECUTABLE_PATH, + scriptPath: SCRIPT_PATH, + adapterPort: 11_436, + tokenHash: crypto.createHash("sha256").update(TOKEN).digest("hex"), + endpointUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + region: "us-east-1", + credentialHash: "a".repeat(64), + updatedAt: "2026-08-20T00:00:00.000Z", + }; +} + +function writeEvidence( + home: string, + state: { pid: number; [key: string]: unknown } = adapterState(), + options: { pidText?: string; token?: string } = {}, +): void { + const paths = adapterPaths(home); + fs.mkdirSync(paths.stateDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync(paths.pidPath, options.pidText ?? `${String(state.pid)}\n`, { mode: 0o600 }); + fs.writeFileSync(paths.tokenPath, `${options.token ?? TOKEN}\n`, { mode: 0o600 }); + fs.writeFileSync(paths.statePath, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 }); +} + +function writeLegacyEvidence(home: string): void { + writeEvidence(home, { + pid: PID, + endpointUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + region: "us-east-1", + credentialHash: "a".repeat(64), + updatedAt: "2026-08-20T00:00:00.000Z", + }); +} + +function writeFailedStartupEvidence(home: string): void { + const paths = adapterPaths(home); + fs.mkdirSync(paths.stateDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync(paths.pidPath, `${String(PID)}\n`, { mode: 0o600 }); + fs.writeFileSync(paths.tokenPath, `${TOKEN}\n`, { mode: 0o600 }); +} + +function writePidOnlyEvidence(home: string): void { + const paths = adapterPaths(home); + fs.mkdirSync(paths.stateDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync(paths.pidPath, `${String(PID)}\n`, { mode: 0o600 }); +} + +function writeJournal( + home: string, + phase: + | "prepared" + | "term-sent" + | "kill-sent" + | "process-absent" + | "evidence-retiring" + | "evidence-retired", +): void { + const { journalPath } = lifecyclePaths(home); + fs.mkdirSync(path.dirname(journalPath), { recursive: true, mode: 0o700 }); + fs.writeFileSync( + journalPath, + `${JSON.stringify( + { + version: 1, + phase, + gatewayPort: 8080, + generation: GENERATION, + pid: PID, + processStart: PROCESS_START, + user: CURRENT_USER, + uid: CURRENT_UID, + executablePath: EXECUTABLE_PATH, + scriptPath: SCRIPT_PATH, + adapterPort: 11_436, + tokenHash: crypto.createHash("sha256").update(TOKEN).digest("hex"), + createdAt: "2026-08-20T00:00:00.000Z", + updatedAt: "2026-08-20T00:00:00.000Z", + }, + null, + 2, + )}\n`, + { mode: 0o600 }, + ); +} + +function managedProcess(overrides: Partial = {}): AdapterProcess { + return { + argv: [EXECUTABLE_PATH, "--experimental-strip-types", "--no-warnings", SCRIPT_PATH], + executablePath: EXECUTABLE_PATH, + generation: GENERATION, + processStart: PROCESS_START, + uid: CURRENT_UID, + user: CURRENT_USER, + ...overrides, + }; +} + +function cleanupHost( + home: string, + processes: Map, + options: { + lsofPids?: readonly number[]; + lsofStatus?: number; + onKill?: (pid: number, signal: NodeJS.Signals | number | undefined) => void; + onRun?: (command: string, args: readonly string[]) => void; + } = {}, +) { + const kills: Array<{ pid: number; signal: NodeJS.Signals | number | undefined }> = []; + const lsofPorts: string[] = []; + const logs: string[] = []; + const warnings: string[] = []; + return { + host: { + commandExists: (command: string) => command === "lsof", + env: { HOME: home, LOGNAME: CURRENT_USER } as NodeJS.ProcessEnv, + existsSync: fs.existsSync, + kill: (pid: number, signal?: NodeJS.Signals | number) => { + kills.push({ pid, signal }); + options.onKill?.(pid, signal); + return true; + }, + log: (message: string) => logs.push(message), + readProcessArgv: (pid: number) => processes.get(pid)?.argv ?? null, + readProcessExecutable: (pid: number) => processes.get(pid)?.executablePath ?? null, + readProcessEnvironment: (pid: number): Record | null => { + const generation = processes.get(pid)?.generation; + return generation + ? { + NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_GENERATION: generation, + NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_PORT: "11436", + } + : generation === null + ? { NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_PORT: "11436" } + : null; + }, + readProcessIdentity: (pid: number) => processes.get(pid)?.processStart ?? null, + run: (command: string, args: readonly string[]) => { + options.onRun?.(command, args); + switch (command) { + case "lsof": + lsofPorts.push(args[1] ?? ""); + return { + status: options.lsofStatus ?? 0, + stdout: `${(options.lsofPids ?? []).map(String).join("\n")}${options.lsofPids?.length ? "\n" : ""}`, + stderr: "", + }; + case "ps": + break; + default: + return { status: 0, stdout: "", stderr: "" }; + } + const pid = Number(args[1]); + const observed = processes.get(pid); + switch (observed) { + case undefined: + return { status: 1, stdout: "", stderr: "" }; + } + const field = args.at(-1); + switch (field) { + case "pid=": + return { status: 0, stdout: `${String(pid)}\n`, stderr: "" }; + case "uid=": + return { status: 0, stdout: `${String(observed.uid)}\n`, stderr: "" }; + case "user=": + return { status: 0, stdout: `${observed.user}\n`, stderr: "" }; + case "args=": + return { status: 0, stdout: `${observed.argv.join(" ")}\n`, stderr: "" }; + default: + return { status: 1, stdout: "", stderr: "" }; + } + }, + sleep: vi.fn(), + warn: (message: string) => warnings.push(message), + }, + kills, + lsofPorts, + logs, + warnings, + }; +} + +function stop(home: string, host: ReturnType["host"], scanOrphans = true) { + return stopBedrockRuntimeAdapter({ nemoclawStateDir: adapterPaths(home).stateDir }, host, { + gatewayPort: 8080, + scanOrphans, + }); +} + +describe("Bedrock Runtime adapter fail-closed uninstall cleanup (#9552)", () => { + it("retires PID-only evidence after the startup child exits before identity capture", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-pid-only-")); + writePidOnlyEvidence(home); + const { host, kills, lsofPorts } = cleanupHost(home, new Map()); + + try { + expect(stop(home, host)).toMatchObject({ ok: true, status: "stopped", pid: PID }); + expect(kills).toEqual([]); + expect(fs.existsSync(adapterPaths(home).pidPath)).toBe(false); + + expect(stop(home, host)).toMatchObject({ ok: true, status: "absent" }); + expect(kills).toEqual([]); + expect(lsofPorts).toEqual([":11436"]); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("does not signal a live process from PID-only evidence", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-pid-only-live-")); + writePidOnlyEvidence(home); + const { host, kills } = cleanupHost(home, new Map([[PID, managedProcess()]])); + + try { + expect(stop(home, host)).toMatchObject({ + ok: false, + fatal: true, + pid: PID, + message: expect.stringContaining("cannot authorize a process signal"), + }); + expect(kills).toEqual([]); + expect(fs.existsSync(adapterPaths(home).pidPath)).toBe(true); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("preserves PID-only evidence when the recorded PID appears before deletion", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-pid-only-race-")); + const processes = new Map(); + writePidOnlyEvidence(home); + const presenceProbeEffects = new Map([ + ["ps:pid=", [vi.fn(), vi.fn(() => processes.set(PID, managedProcess()))]], + ]); + const { host, kills } = cleanupHost(home, processes, { + onRun: (command, args) => { + presenceProbeEffects.get(`${command}:${args.at(-1) ?? ""}`)?.shift()?.(); + }, + }); + + try { + expect(stop(home, host)).toMatchObject({ ok: false, fatal: true, pid: PID }); + expect(kills).toEqual([]); + expect(fs.existsSync(adapterPaths(home).pidPath)).toBe(true); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("retires failed-startup PID and token evidence after proving process exit", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-startup-journal-")); + const processes = new Map([[PID, managedProcess()]]); + writeFailedStartupEvidence(home); + writeJournal(home, "prepared"); + const { host, kills } = cleanupHost(home, processes, { + onKill: (pid) => processes.delete(pid), + }); + + try { + expect(stop(home, host)).toMatchObject({ ok: true, status: "stopped", pid: PID }); + expect(kills).toEqual([{ pid: PID, signal: "SIGTERM" }]); + expect(fs.existsSync(adapterPaths(home).pidPath)).toBe(false); + expect(fs.existsSync(adapterPaths(home).tokenPath)).toBe(false); + expect(fs.existsSync(adapterPaths(home).statePath)).toBe(false); + expect(fs.existsSync(lifecyclePaths(home).journalPath)).toBe(false); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("preserves failed-startup evidence when TERM and KILL cannot prove exit", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-startup-failure-")); + const processes = new Map([[PID, managedProcess()]]); + writeFailedStartupEvidence(home); + writeJournal(home, "prepared"); + const { host, kills } = cleanupHost(home, processes); + + try { + expect(stop(home, host)).toMatchObject({ ok: false, fatal: true, pid: PID }); + expect(kills).toEqual([ + { pid: PID, signal: "SIGTERM" }, + { pid: PID, signal: "SIGKILL" }, + ]); + expect(fs.existsSync(adapterPaths(home).pidPath)).toBe(true); + expect(fs.existsSync(adapterPaths(home).tokenPath)).toBe(true); + expect(fs.existsSync(adapterPaths(home).statePath)).toBe(false); + expect(fs.existsSync(lifecyclePaths(home).journalPath)).toBe(true); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("returns a fatal result and preserves lifecycle evidence after TERM and KILL exhaustion", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-exhaustion-")); + const processes = new Map([[PID, managedProcess()]]); + writeEvidence(home); + const { host, kills } = cleanupHost(home, processes); + + try { + const result = stop(home, host); + + expect(result).toMatchObject({ ok: false, fatal: true, pid: PID }); + expect(kills).toEqual([ + { pid: PID, signal: "SIGTERM" }, + { pid: PID, signal: "SIGKILL" }, + ]); + expect(fs.existsSync(adapterPaths(home).pidPath)).toBe(true); + expect(fs.existsSync(adapterPaths(home).tokenPath)).toBe(true); + expect(fs.existsSync(adapterPaths(home).statePath)).toBe(true); + expect(fs.existsSync(lifecyclePaths(home).journalPath)).toBe(true); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("does not signal when the canonical PID file and lifecycle state disagree", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-pid-mismatch-")); + writeEvidence(home, adapterState(REPLACEMENT_PID), { pidText: `${String(PID)}\n` }); + const { host, kills } = cleanupHost(home, new Map([[PID, managedProcess()]])); + + try { + expect(stop(home, host)).toMatchObject({ ok: false, fatal: true }); + expect(kills).toEqual([]); + expect(fs.existsSync(adapterPaths(home).statePath)).toBe(true); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("preserves absent lifecycle evidence whose adapter port differs from configuration", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-port-mismatch-")); + writeEvidence(home, { ...adapterState(), adapterPort: 11_437 }); + const { host, kills } = cleanupHost(home, new Map()); + + try { + expect(stop(home, host)).toMatchObject({ + ok: false, + fatal: true, + pid: PID, + message: expect.stringContaining("configured adapter port"), + }); + expect(kills).toEqual([]); + expect(fs.existsSync(adapterPaths(home).pidPath)).toBe(true); + expect(fs.existsSync(adapterPaths(home).tokenPath)).toBe(true); + expect(fs.existsSync(adapterPaths(home).statePath)).toBe(true); + expect(fs.existsSync(lifecyclePaths(home).journalPath)).toBe(false); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("rejects a PID file with a numeric prefix and trailing data", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-pid-format-")); + writeEvidence(home, adapterState(), { pidText: `${String(PID)}-replacement\n` }); + const { host, kills } = cleanupHost(home, new Map([[PID, managedProcess()]])); + + try { + expect(stop(home, host)).toMatchObject({ ok: false, fatal: true }); + expect(kills).toEqual([]); + expect(fs.readFileSync(adapterPaths(home).pidPath, "utf8")).toBe( + `${String(PID)}-replacement\n`, + ); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it.each([ + { + expectedWarning: false, + label: "another user", + process: managedProcess({ uid: CURRENT_UID + 1, user: "foreignuser" }), + }, + { + expectedWarning: true, + label: "another canonical launcher path", + process: managedProcess({ + argv: [ + EXECUTABLE_PATH, + "--experimental-strip-types", + "--no-warnings", + "/tmp/foreign/bedrock-runtime-adapter.mts", + ], + }), + }, + ])( + "does not signal an exact-basename listener owned by $label", + ({ expectedWarning, process }) => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-foreign-")); + const { host, kills, logs, warnings } = cleanupHost(home, new Map([[PID, process]]), { + lsofPids: [PID], + }); + + try { + expect(stop(home, host)).toMatchObject({ ok: true }); + expect(kills).toEqual([]); + expect(warnings.some((message) => message.includes("unbound Bedrock"))).toBe( + expectedWarning, + ); + expect(logs.includes("No Bedrock Runtime adapter processes found")).toBe(!expectedWarning); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }, + ); + + it("reports an unavailable full-uninstall orphan scan without claiming absence", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-lsof-error-")); + const { host, kills, logs, warnings } = cleanupHost(home, new Map(), { lsofStatus: 2 }); + + try { + expect(stop(home, host)).toMatchObject({ ok: true, status: "absent" }); + expect(kills).toEqual([]); + expect(warnings).toContain( + "Bedrock Runtime adapter orphan scan could not inspect the configured port; no process was signaled.", + ); + expect(logs).not.toContain("No Bedrock Runtime adapter processes found"); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("does not send KILL to a replacement that reuses the recorded PID", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-reused-pid-")); + const processes = new Map([[PID, managedProcess()]]); + writeEvidence(home); + const { host, kills } = cleanupHost(home, processes, { + onKill: (_pid, signal) => { + switch (signal) { + case "SIGTERM": + processes.set( + PID, + managedProcess({ + generation: REPLACEMENT_GENERATION, + processStart: REPLACEMENT_PROCESS_START, + }), + ); + break; + } + }, + }); + + try { + expect(stop(home, host)).toMatchObject({ ok: false, fatal: true }); + expect(kills).toEqual([{ pid: PID, signal: "SIGTERM" }]); + expect(fs.existsSync(adapterPaths(home).statePath)).toBe(true); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("does not signal a live adapter whose legacy state lacks generation identity", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-legacy-")); + const processes = new Map([[PID, managedProcess({ generation: null })]]); + writeLegacyEvidence(home); + const { host, kills } = cleanupHost(home, processes); + + try { + expect(stop(home, host)).toMatchObject({ ok: false, fatal: true, pid: PID }); + expect(kills).toEqual([]); + expect(fs.existsSync(lifecyclePaths(home).journalPath)).toBe(true); + + processes.delete(PID); + expect(stop(home, host)).toMatchObject({ ok: true, status: "stopped", pid: PID }); + expect(fs.existsSync(adapterPaths(home).statePath)).toBe(false); + expect(fs.existsSync(lifecyclePaths(home).journalPath)).toBe(false); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("retires legacy evidence when its recorded process is already absent", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-legacy-absent-")); + writeLegacyEvidence(home); + const { host, kills } = cleanupHost(home, new Map()); + + try { + expect(stop(home, host)).toMatchObject({ ok: true, status: "stopped", pid: PID }); + expect(kills).toEqual([]); + expect(fs.existsSync(adapterPaths(home).pidPath)).toBe(false); + expect(fs.existsSync(adapterPaths(home).tokenPath)).toBe(false); + expect(fs.existsSync(adapterPaths(home).statePath)).toBe(false); + expect(fs.existsSync(lifecyclePaths(home).journalPath)).toBe(false); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("uses full-uninstall discovery to stop an owned listener whose PID file is absent", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-orphan-")); + const processes = new Map([[PID, managedProcess()]]); + writeEvidence(home); + fs.unlinkSync(adapterPaths(home).pidPath); + const { host, kills, lsofPorts } = cleanupHost(home, processes, { + lsofPids: [PID], + onKill: (pid) => processes.delete(pid), + }); + + try { + expect(stop(home, host)).toMatchObject({ ok: true, status: "stopped", pid: PID }); + expect(kills).toEqual([{ pid: PID, signal: "SIGTERM" }]); + expect(lsofPorts).toEqual([":11436"]); + expect(fs.existsSync(adapterPaths(home).statePath)).toBe(false); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("retires state for an already-absent process without requiring orphan discovery", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-absent-orphan-")); + writeEvidence(home); + fs.unlinkSync(adapterPaths(home).pidPath); + const { host, kills, lsofPorts } = cleanupHost(home, new Map()); + + try { + expect(stop(home, host)).toMatchObject({ ok: true, status: "stopped", pid: PID }); + expect(kills).toEqual([]); + expect(lsofPorts).toEqual([]); + expect(fs.existsSync(adapterPaths(home).statePath)).toBe(false); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("preserves a concurrent new generation before lifecycle evidence deletion", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-new-generation-")); + const processes = new Map([[PID, managedProcess()]]); + writeEvidence(home); + const { host } = cleanupHost(home, processes, { + onKill: (_pid, signal) => { + switch (signal) { + case "SIGTERM": + processes.delete(PID); + writeEvidence( + home, + adapterState(REPLACEMENT_PID, REPLACEMENT_GENERATION, REPLACEMENT_PROCESS_START), + ); + break; + } + }, + }); + + try { + expect(stop(home, host)).toMatchObject({ ok: false, fatal: true }); + const current = JSON.parse(fs.readFileSync(adapterPaths(home).statePath, "utf8")); + expect(current.generation).toBe(REPLACEMENT_GENERATION); + expect(fs.existsSync(adapterPaths(home).tokenPath)).toBe(true); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("preserves a resumed journal after the configured adapter port drifts", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-resume-port-")); + writeEvidence(home); + writeJournal(home, "term-sent"); + const journalBefore = fs.readFileSync(lifecyclePaths(home).journalPath, "utf8"); + const { host, kills } = cleanupHost(home, new Map([[PID, managedProcess()]])); + host.env.NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_PORT = "11437"; + + try { + expect(stop(home, host)).toMatchObject({ + ok: false, + fatal: true, + message: expect.stringContaining("configured adapter port"), + }); + expect(kills).toEqual([]); + expect(fs.existsSync(adapterPaths(home).pidPath)).toBe(true); + expect(fs.existsSync(adapterPaths(home).tokenPath)).toBe(true); + expect(fs.existsSync(adapterPaths(home).statePath)).toBe(true); + expect(fs.readFileSync(lifecyclePaths(home).journalPath, "utf8")).toBe(journalBefore); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it.each([ + ["prepared", "SIGTERM", true], + ["term-sent", "SIGTERM", true], + ["kill-sent", "SIGKILL", true], + ["process-absent", null, false], + ["evidence-retiring", null, false], + ["evidence-retired", null, false], + ] as const)("resumes an interrupted %s phase", (phase, expectedSignal, processInitiallyLive) => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-resume-")); + const processes = new Map(); + processInitiallyLive ? processes.set(PID, managedProcess()) : undefined; + phase !== "evidence-retired" ? writeEvidence(home) : undefined; + writeJournal(home, phase); + const { host, kills } = cleanupHost(home, processes, { + onKill: (pid) => processes.delete(pid), + }); + + try { + expect(stop(home, host)).toMatchObject({ ok: true }); + expect(kills.map(({ signal }) => signal)).toEqual(expectedSignal ? [expectedSignal] : []); + expect(fs.existsSync(adapterPaths(home).pidPath)).toBe(false); + expect(fs.existsSync(adapterPaths(home).tokenPath)).toBe(false); + expect(fs.existsSync(adapterPaths(home).statePath)).toBe(false); + expect(fs.existsSync(lifecyclePaths(home).journalPath)).toBe(false); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("preserves evidence that reappears after the journal recorded retirement", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-retired-race-")); + writeEvidence(home); + writeJournal(home, "evidence-retired"); + const { host, kills } = cleanupHost(home, new Map()); + + try { + expect(stop(home, host)).toMatchObject({ ok: false, fatal: true }); + expect(kills).toEqual([]); + expect(fs.existsSync(adapterPaths(home).pidPath)).toBe(true); + expect(fs.existsSync(adapterPaths(home).tokenPath)).toBe(true); + expect(fs.existsSync(adapterPaths(home).statePath)).toBe(true); + expect(fs.existsSync(lifecyclePaths(home).journalPath)).toBe(true); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("preserves remaining evidence when the PID is reused during retirement", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-retire-reuse-")); + writeEvidence(home); + writeJournal(home, "process-absent"); + const processes = new Map(); + const cleanup = cleanupHost(home, processes); + const originalExistsSync = cleanup.host.existsSync; + cleanup.host.existsSync = (target) => { + switch ( + target === adapterPaths(home).tokenPath && + !fs.existsSync(adapterPaths(home).pidPath) + ) { + case true: + processes.set( + PID, + managedProcess({ + generation: REPLACEMENT_GENERATION, + processStart: REPLACEMENT_PROCESS_START, + }), + ); + break; + } + return originalExistsSync(target); + }; + + try { + expect(stop(home, cleanup.host)).toMatchObject({ ok: false, fatal: true, pid: PID }); + expect(cleanup.kills).toEqual([]); + expect(fs.existsSync(adapterPaths(home).pidPath)).toBe(false); + expect(fs.existsSync(adapterPaths(home).tokenPath)).toBe(true); + expect(fs.existsSync(adapterPaths(home).statePath)).toBe(true); + expect(fs.existsSync(lifecyclePaths(home).journalPath)).toBe(true); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("makes a completed second uninstall a no-mutation success", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-second-")); + const processes = new Map([[PID, managedProcess()]]); + writeEvidence(home); + const { host, kills } = cleanupHost(home, processes, { + onKill: (pid) => processes.delete(pid), + }); + + try { + expect(stop(home, host)).toMatchObject({ ok: true }); + const firstKillCount = kills.length; + expect(stop(home, host)).toMatchObject({ ok: true, status: "absent" }); + expect(kills).toHaveLength(firstKillCount); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("keeps orphan discovery and sibling evidence outside selected-gateway cleanup", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-stop-selected-")); + const processes = new Map([[PID, managedProcess()]]); + writeEvidence(home); + const siblingDir = path.join(adapterPaths(home).stateDir, "gateways", "8091"); + fs.mkdirSync(siblingDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync( + path.join(siblingDir, "bedrock-runtime-adapter.pid"), + `${String(REPLACEMENT_PID)}\n`, + { + mode: 0o600, + }, + ); + fs.writeFileSync(path.join(siblingDir, "bedrock-runtime-adapter-token"), `${TOKEN}\n`, { + mode: 0o600, + }); + fs.writeFileSync( + path.join(siblingDir, "bedrock-runtime-adapter.json"), + `${JSON.stringify( + adapterState(REPLACEMENT_PID, REPLACEMENT_GENERATION, REPLACEMENT_PROCESS_START), + null, + 2, + )}\n`, + { mode: 0o600 }, + ); + const { host, kills, lsofPorts } = cleanupHost(home, processes, { + lsofPids: [REPLACEMENT_PID], + onKill: (pid) => processes.delete(pid), + }); + let siblingInspected = false; + const originalExistsSync = host.existsSync; + host.existsSync = (target) => { + siblingInspected ||= String(target).startsWith(siblingDir); + return originalExistsSync(target); + }; + + try { + expect(stop(home, host, false)).toMatchObject({ ok: true, status: "stopped", pid: PID }); + expect(kills).toEqual([{ pid: PID, signal: "SIGTERM" }]); + expect(lsofPorts).toEqual([]); + expect(siblingInspected).toBe(false); + expect(fs.existsSync(path.join(siblingDir, "bedrock-runtime-adapter.json"))).toBe(true); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); +}); diff --git a/src/lib/actions/uninstall/openrouter-runtime-adapter-cleanup.test.ts b/src/lib/actions/uninstall/openrouter-runtime-adapter-cleanup.test.ts index 217a5fe4e2b..4f7163acaf5 100644 --- a/src/lib/actions/uninstall/openrouter-runtime-adapter-cleanup.test.ts +++ b/src/lib/actions/uninstall/openrouter-runtime-adapter-cleanup.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import crypto from "node:crypto"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -44,6 +45,9 @@ const OPENROUTER_RUNTIME_ADAPTER_CMDLINE = "/usr/bin/node /home/test/NemoClaw/dist/lib/inference/openrouter-runtime-adapter-entry.js\n"; const HTTPS_PIN_RUNTIME_ADAPTER_CMDLINE = "/usr/bin/node /home/test/NemoClaw/dist/lib/inference/https-pin-runtime-adapter.js\n"; +const BEDROCK_TEST_GENERATION = "33333333333333333333333333333333"; +const BEDROCK_TEST_PROCESS_START = "linux:test-boot:300"; +const BEDROCK_TEST_TOKEN = "bedrock-test-token"; const RUNTIME_ADAPTERS = [ { @@ -94,6 +98,7 @@ function psStub(pidStr: string, opts: { exited: Set; cmdline?: string; o () => (opts.exited.has(pid) ? notFound() : ok(`${pidStr}\n`)), ], [["-p", pidStr, "-o", "user="].join("\0"), () => ok(`${opts.owner ?? "testuser"}\n`)], + [["-p", pidStr, "-o", "uid="].join("\0"), () => ok(`${String(process.getuid?.() ?? 501)}\n`)], [ ["-p", pidStr, "-o", "args="].join("\0"), () => ok(opts.cmdline ?? OPENROUTER_RUNTIME_ADAPTER_CMDLINE), @@ -105,6 +110,41 @@ function psStub(pidStr: string, opts: { exited: Set; cmdline?: string; o }; } +function writeBedrockEvidence(home: string, pid: number, cmdline: string): void { + const stateDir = path.join(home, ".nemoclaw"); + const scriptPath = cmdline.trim().split(/\s+/u).at(-1)!; + fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync(path.join(stateDir, "bedrock-runtime-adapter.pid"), `${String(pid)}\n`, { + mode: 0o600, + }); + fs.chmodSync(path.join(stateDir, "bedrock-runtime-adapter.pid"), 0o600); + fs.writeFileSync( + path.join(stateDir, "bedrock-runtime-adapter-token"), + `${BEDROCK_TEST_TOKEN}\n`, + { mode: 0o600 }, + ); + fs.writeFileSync( + path.join(stateDir, "bedrock-runtime-adapter.json"), + `${JSON.stringify({ + version: 2, + generation: BEDROCK_TEST_GENERATION, + pid, + processStart: BEDROCK_TEST_PROCESS_START, + user: os.userInfo().username, + uid: process.getuid?.() ?? 501, + executablePath: "/usr/bin/node", + scriptPath, + adapterPort: 11_436, + tokenHash: crypto.createHash("sha256").update(BEDROCK_TEST_TOKEN).digest("hex"), + endpointUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + region: "us-east-1", + credentialHash: "a".repeat(64), + updatedAt: "2026-08-20T00:00:00.000Z", + })}\n`, + { mode: 0o600 }, + ); +} + function defaultRun(command: string, args: readonly string[]): RunResult { switch (command) { case "openshell": @@ -150,6 +190,11 @@ describe("runtime adapter uninstall cleanup", () => { const pidFile = path.join(tmpHome, ".nemoclaw", pidFilename); fs.mkdirSync(path.dirname(pidFile), { recursive: true }); fs.writeFileSync(pidFile, `${String(persistedPid)}\n`); + switch (pidFilename) { + case "bedrock-runtime-adapter.pid": + writeBedrockEvidence(tmpHome, persistedPid, cmdline); + break; + } try { const result = runUninstallPlan( @@ -165,9 +210,22 @@ describe("runtime adapter uninstall cleanup", () => { return true; }, log: (line) => logs.push(line), + readProcessArgv: () => cmdline.trim().split(/\s+/u), + readProcessExecutable: () => "/usr/bin/node", + readProcessEnvironment: () => ({ + NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_GENERATION: BEDROCK_TEST_GENERATION, + NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_PORT: "11436", + }), + readProcessIdentity: () => BEDROCK_TEST_PROCESS_START, rmSync: fs.rmSync, run: runStub({ - ps: psStub(String(persistedPid), { cmdline, exited }), + ps: psStub(String(persistedPid), { + cmdline, + exited, + ...(pidFilename === "bedrock-runtime-adapter.pid" + ? { owner: os.userInfo().username } + : {}), + }), }), runDocker: () => ok(""), }, @@ -183,7 +241,71 @@ describe("runtime adapter uninstall cleanup", () => { }, ); - it.each(RUNTIME_ADAPTERS)( + it("stops the uninstall plan before State cleanup when Bedrock TERM and KILL do not exit (#9552)", () => { + const tmpHome = fs.mkdtempSync( + path.join(os.tmpdir(), "nemoclaw-uninstall-bedrock-exhaustion-"), + ); + const logs: string[] = []; + const signals: Array = []; + const scannedPorts: string[] = []; + writeBedrockEvidence(tmpHome, 45_552, BEDROCK_RUNTIME_ADAPTER_CMDLINE); + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: true }, + { + commandExists: () => true, + env: { HOME: tmpHome, LOGNAME: "testuser" } as NodeJS.ProcessEnv, + existsSync: (target) => target.startsWith(tmpHome) && fs.existsSync(target), + isTty: false, + kill: (_pid, signal) => { + signals.push(signal); + return true; + }, + log: (line) => logs.push(line), + readProcessArgv: () => BEDROCK_RUNTIME_ADAPTER_CMDLINE.trim().split(/\s+/u), + readProcessExecutable: () => "/usr/bin/node", + readProcessEnvironment: () => ({ + NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_GENERATION: BEDROCK_TEST_GENERATION, + NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_PORT: "11436", + }), + readProcessIdentity: () => BEDROCK_TEST_PROCESS_START, + rmSync: fs.rmSync, + run: runStub({ + lsof: (args) => { + scannedPorts.push(args[1] ?? ""); + return ok(); + }, + ps: psStub("45552", { + cmdline: BEDROCK_RUNTIME_ADAPTER_CMDLINE, + exited: new Set(), + owner: os.userInfo().username, + }), + }), + runDocker: () => ok(""), + sleep: vi.fn(), + }, + ); + + expect(result.exitCode).toBe(1); + expect(signals).toEqual(["SIGTERM", "SIGKILL"]); + expect(scannedPorts).toEqual([":11435", ":11437", ":11438", ":4000"]); + expect(logs.some((line) => line.endsWith("State and binaries"))).toBe(false); + expect(fs.existsSync(path.join(tmpHome, ".nemoclaw", "bedrock-runtime-adapter.pid"))).toBe( + true, + ); + expect(fs.existsSync(path.join(tmpHome, ".nemoclaw", "bedrock-runtime-adapter-token"))).toBe( + true, + ); + expect(fs.existsSync(path.join(tmpHome, ".nemoclaw", "bedrock-runtime-adapter.json"))).toBe( + true, + ); + } finally { + fs.rmSync(tmpHome, { recursive: true, force: true }); + } + }); + + it.each(RUNTIME_ADAPTERS.filter(({ pidFile }) => pidFile !== "bedrock-runtime-adapter.pid"))( "stops an owned $label orphan on its configured port$issueSuffix", ({ cmdline, customPort, defaultPort, envPort, label, orphanPid }) => { const logs: string[] = []; @@ -271,7 +393,7 @@ describe("runtime adapter uninstall cleanup", () => { }, ); - it("does not signal a Bedrock marker lookalike from persisted state or port discovery (#9552)", () => { + it("fails closed on incomplete Bedrock PID evidence before process or port discovery (#9552)", () => { const foreignPid = 99995; const killed: number[] = []; const lsofPorts: string[] = []; @@ -312,11 +434,11 @@ describe("runtime adapter uninstall cleanup", () => { }, ); - expect(result.exitCode).toBe(0); - expect(commandLineProbeCount).toBe(2); - expect(lsofPorts).toContain(":11436"); + expect(result.exitCode).toBe(1); + expect(commandLineProbeCount).toBe(0); + expect(lsofPorts).not.toContain(":11436"); expect(killed).not.toContain(foreignPid); - expect(fs.existsSync(pidFile)).toBe(false); + expect(fs.existsSync(pidFile)).toBe(true); } finally { fs.rmSync(tmpHome, { recursive: true, force: true }); } diff --git a/src/lib/actions/uninstall/openrouter-runtime-adapter-cleanup.ts b/src/lib/actions/uninstall/openrouter-runtime-adapter-cleanup.ts index 2b2208515e7..7762fdfefd3 100644 --- a/src/lib/actions/uninstall/openrouter-runtime-adapter-cleanup.ts +++ b/src/lib/actions/uninstall/openrouter-runtime-adapter-cleanup.ts @@ -1,31 +1,45 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import type { SpawnSyncOptions } from "node:child_process"; +import crypto from "node:crypto"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { sleepMs } from "../../core/wait"; import type { UninstallPaths } from "../../domain/uninstall/paths"; +import { + type BedrockRuntimeAdapterProcessRuntime, + type BedrockRuntimeAdapterState, + type BedrockRuntimeAdapterUninstallJournal, + type BedrockRuntimeAdapterUninstallPhase, + type ObservedBedrockRuntimeAdapterProcess, + bedrockRuntimeAdapterProcessPresence, + canonicalPath, + canonicalPid, + isBedrockRuntimeAdapterState, + legacyBedrockRuntimeGeneration, + observeBedrockRuntimeAdapterProcess, + readBedrockRuntimeAdapterUninstallJournal, + readPrivateBedrockRuntimeFile, + removeDurableBedrockRuntimeFile, + resolveBedrockRuntimeAdapterLifecyclePaths, + withBedrockRuntimeAdapterLifecycleLock, + writeDurablePrivateBedrockRuntimeJson, +} from "../../inference/bedrock-runtime/lifecycle"; import { BEDROCK_RUNTIME_ADAPTER_PROCESS_MATCHER } from "../../inference/bedrock-runtime"; -interface RunResult { - status: number | null; - stdout: string; - stderr: string; -} - -interface RuntimeAdapterCleanupRuntime { +interface RuntimeAdapterCleanupRuntime extends BedrockRuntimeAdapterProcessRuntime { commandExists: (command: string) => boolean; - env: NodeJS.ProcessEnv; existsSync: (target: string) => boolean; - kill: (pid: number, signal?: NodeJS.Signals | number) => boolean; log: (message: string) => void; - run: (command: string, args: string[], options?: SpawnSyncOptions) => RunResult; warn: (message: string) => void; } +export type BedrockRuntimeAdapterStopResult = + | { ok: true; status: "absent" | "stopped"; pid?: number } + | { ok: false; fatal: true; message: string; pid?: number }; + type RuntimeAdapterDescriptor = { cmdlineMatcher: string | RegExp; defaultPort: number; @@ -42,6 +56,11 @@ const BEDROCK_RUNTIME_ADAPTER: RuntimeAdapterDescriptor = { pidFile: "bedrock-runtime-adapter.pid", }; +const BEDROCK_STATE_FILE = "bedrock-runtime-adapter.json"; +const BEDROCK_TOKEN_FILE = "bedrock-runtime-adapter-token"; +const PROCESS_EXIT_TIMEOUT_MS = 1_000; +const PROCESS_EXIT_POLL_MS = 50; + const OPENROUTER_RUNTIME_ADAPTER: RuntimeAdapterDescriptor = { cmdlineMatcher: "openrouter-runtime-adapter", defaultPort: 11437, @@ -180,12 +199,700 @@ function stopRuntimeAdapter( if (stopped.size === 0) runtime.log(`No ${descriptor.label} processes found`); } +interface BedrockEvidencePaths { + pidPath: string; + statePath: string; + tokenPath: string; +} + +interface BedrockEvidence { + generation: string; + pid: number; + pidFilePresent: boolean; + state: BedrockRuntimeAdapterState | null; + stateText: string; + tokenHash: string; +} + +function bedrockEvidencePaths(stateDir: string): BedrockEvidencePaths { + return { + pidPath: path.join(stateDir, BEDROCK_RUNTIME_ADAPTER.pidFile), + statePath: path.join(stateDir, BEDROCK_STATE_FILE), + tokenPath: path.join(stateDir, BEDROCK_TOKEN_FILE), + }; +} + +function parseJsonObject(raw: string): Record | null { + try { + const value: unknown = JSON.parse(raw); + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : null; + } catch { + return null; + } +} + +function isLegacyBedrockRuntimeAdapterState(value: Record): boolean { + return ( + value.version === undefined && + canonicalPid(`${String(value.pid)}\n`) !== null && + typeof value.endpointUrl === "string" && + value.endpointUrl.length > 0 && + typeof value.region === "string" && + value.region.length > 0 && + typeof value.credentialHash === "string" && + /^[a-f0-9]{64}$/u.test(value.credentialHash) && + typeof value.updatedAt === "string" && + !Number.isNaN(Date.parse(value.updatedAt)) + ); +} + +function readBedrockEvidence( + evidencePaths: BedrockEvidencePaths, + runtime: RuntimeAdapterCleanupRuntime, +): + | { kind: "absent" } + | { kind: "invalid"; message: string } + | { kind: "pid-only"; pid: number } + | { kind: "present"; evidence: BedrockEvidence } { + const present = { + pid: runtime.existsSync(evidencePaths.pidPath), + state: runtime.existsSync(evidencePaths.statePath), + token: runtime.existsSync(evidencePaths.tokenPath), + }; + if (!present.pid && !present.state && !present.token) return { kind: "absent" }; + if (present.pid && !present.state && !present.token) { + const pidText = readPrivateBedrockRuntimeFile(evidencePaths.pidPath); + const pid = pidText === null ? null : canonicalPid(pidText); + return pid === null + ? { + kind: "invalid", + message: + "Bedrock Runtime adapter PID-only evidence is unsafe or malformed; no files were removed.", + } + : { kind: "pid-only", pid }; + } + if (!present.state || !present.token) { + return { + kind: "invalid", + message: "Bedrock Runtime adapter lifecycle evidence is incomplete; no files were removed.", + }; + } + + const stateText = readPrivateBedrockRuntimeFile(evidencePaths.statePath); + const tokenText = readPrivateBedrockRuntimeFile(evidencePaths.tokenPath); + const pidText = present.pid ? readPrivateBedrockRuntimeFile(evidencePaths.pidPath) : null; + if ( + stateText === null || + tokenText === null || + (present.pid && pidText === null) || + !/^[^\s\u0000]{1,512}\n?$/u.test(tokenText) + ) { + return { + kind: "invalid", + message: + "Bedrock Runtime adapter lifecycle evidence is unsafe or malformed; no files were removed.", + }; + } + + const stateValue = parseJsonObject(stateText); + const statePid = stateValue && canonicalPid(`${String(stateValue.pid)}\n`); + const persistedPid = pidText === null ? statePid : canonicalPid(pidText); + if ( + stateValue === null || + statePid === null || + persistedPid === null || + statePid !== persistedPid + ) { + return { + kind: "invalid", + message: + "Bedrock Runtime adapter PID and lifecycle state do not match; no process was signaled.", + }; + } + + const tokenHash = crypto.createHash("sha256").update(tokenText.trim()).digest("hex"); + const state = isBedrockRuntimeAdapterState(stateValue) ? stateValue : null; + if (!state && !isLegacyBedrockRuntimeAdapterState(stateValue)) { + return { + kind: "invalid", + message: "Bedrock Runtime adapter lifecycle state is malformed; no process was signaled.", + }; + } + if (state && state.tokenHash !== tokenHash) { + return { + kind: "invalid", + message: + "Bedrock Runtime adapter token and lifecycle state do not match; no process was signaled.", + }; + } + return { + kind: "present", + evidence: { + generation: state + ? state.generation + : legacyBedrockRuntimeGeneration(stateText, persistedPid, tokenHash), + pid: persistedPid, + pidFilePresent: present.pid, + state, + stateText, + tokenHash, + }, + }; +} + +function currentProcessOwner(): { uid: number; user: string } | null { + const uid = process.getuid?.(); + const user = os.userInfo().username; + return Number.isSafeInteger(uid) && uid! >= 0 && user ? { uid: uid!, user } : null; +} + +function journalFromEvidence( + evidence: BedrockEvidence, + observed: ObservedBedrockRuntimeAdapterProcess | null, + gatewayPort: number, + adapterPort: number, +): BedrockRuntimeAdapterUninstallJournal | null { + const owner = currentProcessOwner(); + if (!owner) return null; + if (evidence.state) { + const state = evidence.state; + if ( + state.uid !== owner.uid || + state.user !== owner.user || + state.adapterPort !== adapterPort || + (observed !== null && + (observed.adapterPort !== state.adapterPort || + observed.executablePath !== canonicalPath(state.executablePath) || + observed.generation !== state.generation || + observed.processStart !== state.processStart || + observed.scriptPath !== canonicalPath(state.scriptPath) || + observed.uid !== state.uid || + observed.user !== state.user)) + ) { + return null; + } + } else if ( + observed !== null && + (observed.adapterPort !== adapterPort || + observed.generation !== null || + observed.uid !== owner.uid || + observed.user !== owner.user) + ) { + return null; + } + + const processAuthority = + evidence.state ?? + observed ?? + (evidence.generation.startsWith("legacy:") + ? { + processStart: "legacy-unbound", + user: owner.user, + uid: owner.uid, + executablePath: canonicalPath(process.execPath), + scriptPath: canonicalPath(path.resolve("bedrock-runtime-adapter.mts")), + } + : null); + if (!processAuthority) return null; + const now = new Date().toISOString(); + return { + version: 1, + phase: "prepared", + gatewayPort, + generation: evidence.generation, + pid: evidence.pid, + processStart: processAuthority.processStart, + user: processAuthority.user, + uid: processAuthority.uid, + executablePath: canonicalPath(processAuthority.executablePath), + scriptPath: canonicalPath(processAuthority.scriptPath), + adapterPort, + tokenHash: evidence.tokenHash, + createdAt: now, + updatedAt: now, + }; +} + +function advanceBedrockJournal( + journalPath: string, + journal: BedrockRuntimeAdapterUninstallJournal, + phase: BedrockRuntimeAdapterUninstallPhase, +): BedrockRuntimeAdapterUninstallJournal { + const next = { ...journal, phase, updatedAt: new Date().toISOString() }; + writeDurablePrivateBedrockRuntimeJson(journalPath, next); + return next; +} + +function stopFailure( + _runtime: RuntimeAdapterCleanupRuntime, + message: string, + pid?: number, +): BedrockRuntimeAdapterStopResult { + return { ok: false, fatal: true, message, ...(pid === undefined ? {} : { pid }) }; +} + +function pidOnlyEvidenceMatches( + evidencePaths: BedrockEvidencePaths, + journalPath: string, + pid: number, + runtime: RuntimeAdapterCleanupRuntime, +): boolean { + if ( + !runtime.existsSync(evidencePaths.pidPath) || + runtime.existsSync(evidencePaths.statePath) || + runtime.existsSync(evidencePaths.tokenPath) || + runtime.existsSync(journalPath) + ) { + return false; + } + const pidText = readPrivateBedrockRuntimeFile(evidencePaths.pidPath); + return pidText !== null && canonicalPid(pidText) === pid; +} + +function retireAbsentPidOnlyEvidence( + evidencePaths: BedrockEvidencePaths, + journalPath: string, + pid: number, + runtime: RuntimeAdapterCleanupRuntime, +): BedrockRuntimeAdapterStopResult { + const presence = bedrockRuntimeAdapterProcessPresence(pid, runtime); + if (presence === "unknown") { + return stopFailure( + runtime, + "Bedrock Runtime adapter PID-only process state is unavailable; PID evidence was preserved.", + pid, + ); + } + if (presence === "present") { + return stopFailure( + runtime, + "Bedrock Runtime adapter PID-only evidence cannot authorize a process signal; PID evidence was preserved.", + pid, + ); + } + if (!pidOnlyEvidenceMatches(evidencePaths, journalPath, pid, runtime)) { + return stopFailure( + runtime, + "Bedrock Runtime adapter PID-only evidence changed before cleanup; no files were removed.", + pid, + ); + } + if ( + bedrockRuntimeAdapterProcessPresence(pid, runtime) !== "absent" || + !pidOnlyEvidenceMatches(evidencePaths, journalPath, pid, runtime) + ) { + return stopFailure( + runtime, + "Bedrock Runtime adapter process absence or PID-only evidence could not be revalidated before deletion; PID evidence was preserved.", + pid, + ); + } + removeDurableBedrockRuntimeFile(evidencePaths.pidPath); + runtime.log(`Removed stale Bedrock Runtime adapter PID evidence ${String(pid)}`); + return { ok: true, status: "stopped", pid }; +} + +function waitForRecordedProcessExit( + journal: BedrockRuntimeAdapterUninstallJournal, + runtime: RuntimeAdapterCleanupRuntime, +): boolean | null { + const deadline = Date.now() + PROCESS_EXIT_TIMEOUT_MS; + while (Date.now() < deadline) { + const presence = bedrockRuntimeAdapterProcessPresence(journal.pid, runtime); + if (presence === "absent") return true; + if (presence === "unknown") return null; + (runtime.sleep ?? sleepMs)(PROCESS_EXIT_POLL_MS); + } + const presence = bedrockRuntimeAdapterProcessPresence(journal.pid, runtime); + return presence === "unknown" ? null : presence === "absent"; +} + +function signalRecordedProcess( + journalPath: string, + journal: BedrockRuntimeAdapterUninstallJournal, + phase: "term-sent" | "kill-sent", + signal: "SIGTERM" | "SIGKILL", + runtime: RuntimeAdapterCleanupRuntime, +): { journal: BedrockRuntimeAdapterUninstallJournal; exited: boolean | null } | null { + const next = advanceBedrockJournal(journalPath, journal, phase); + if (!observeBedrockRuntimeAdapterProcess(next.pid, runtime, next)) return null; + runtime.kill(next.pid, signal); + return { journal: next, exited: waitForRecordedProcessExit(next, runtime) }; +} + +function runBedrockStopPhases( + journalPath: string, + initial: BedrockRuntimeAdapterUninstallJournal, + runtime: RuntimeAdapterCleanupRuntime, +): + | { kind: "failure"; message: string; journal: BedrockRuntimeAdapterUninstallJournal } + | { kind: "ready"; journal: BedrockRuntimeAdapterUninstallJournal } { + let journal = initial; + const initialPresence = bedrockRuntimeAdapterProcessPresence(journal.pid, runtime); + if (initialPresence === "unknown") { + return { + kind: "failure", + message: "Bedrock Runtime adapter process state is unavailable.", + journal, + }; + } + if (initialPresence === "absent") { + journal = advanceBedrockJournal(journalPath, journal, "process-absent"); + return { kind: "ready", journal }; + } + + if (journal.generation.startsWith("legacy:")) { + return { + kind: "failure", + message: + "Bedrock Runtime adapter legacy state cannot prove the live process generation; no signal was sent. Resolve the unverified live process outside this command, then rerun uninstall.", + journal, + }; + } + + if (journal.phase === "prepared" || journal.phase === "term-sent") { + const term = signalRecordedProcess(journalPath, journal, "term-sent", "SIGTERM", runtime); + if (!term) { + return { + kind: "failure", + message: "Bedrock Runtime adapter process identity could not be revalidated before TERM.", + journal, + }; + } + journal = term.journal; + if (term.exited === null) { + return { + kind: "failure", + message: "Bedrock Runtime adapter process state became unavailable after TERM.", + journal, + }; + } + if (term.exited) { + journal = advanceBedrockJournal(journalPath, journal, "process-absent"); + return { kind: "ready", journal }; + } + } + + if (journal.phase === "term-sent" || journal.phase === "kill-sent") { + const kill = signalRecordedProcess(journalPath, journal, "kill-sent", "SIGKILL", runtime); + if (!kill) { + return { + kind: "failure", + message: "Bedrock Runtime adapter process identity could not be revalidated before KILL.", + journal, + }; + } + journal = kill.journal; + if (kill.exited === null) { + return { + kind: "failure", + message: "Bedrock Runtime adapter process state became unavailable after KILL.", + journal, + }; + } + if (!kill.exited) { + return { + kind: "failure", + message: "Failed to stop Bedrock Runtime adapter after TERM and KILL.", + journal, + }; + } + journal = advanceBedrockJournal(journalPath, journal, "process-absent"); + } + return { kind: "ready", journal }; +} + +function stateMatchesJournal( + stateText: string, + journal: BedrockRuntimeAdapterUninstallJournal, +): boolean { + const stateValue = parseJsonObject(stateText); + if (!stateValue) return false; + const statePid = canonicalPid(`${String(stateValue.pid)}\n`); + if (statePid !== journal.pid) return false; + if (isBedrockRuntimeAdapterState(stateValue)) { + return ( + stateValue.generation === journal.generation && + stateValue.processStart === journal.processStart && + stateValue.user === journal.user && + stateValue.uid === journal.uid && + canonicalPath(stateValue.executablePath) === canonicalPath(journal.executablePath) && + canonicalPath(stateValue.scriptPath) === canonicalPath(journal.scriptPath) && + stateValue.adapterPort === journal.adapterPort && + stateValue.tokenHash === journal.tokenHash + ); + } + return ( + legacyBedrockRuntimeGeneration(stateText, journal.pid, journal.tokenHash) === journal.generation + ); +} + +function evidenceFileMatchesJournal( + target: keyof BedrockEvidencePaths, + evidencePaths: BedrockEvidencePaths, + journal: BedrockRuntimeAdapterUninstallJournal, +): boolean { + const raw = readPrivateBedrockRuntimeFile(evidencePaths[target]); + if (raw === null) return false; + if (target === "pidPath") return canonicalPid(raw) === journal.pid; + if (target === "tokenPath") { + return crypto.createHash("sha256").update(raw.trim()).digest("hex") === journal.tokenHash; + } + return stateMatchesJournal(raw, journal); +} + +function validateRetirementEvidence( + evidencePaths: BedrockEvidencePaths, + journal: BedrockRuntimeAdapterUninstallJournal, + allowAbsent: boolean, + runtime: RuntimeAdapterCleanupRuntime, +): boolean { + return (["pidPath", "tokenPath", "statePath"] as const).every((target) => { + if (!runtime.existsSync(evidencePaths[target])) return allowAbsent; + return evidenceFileMatchesJournal(target, evidencePaths, journal); + }); +} + +function retireBedrockEvidence( + journalPath: string, + initial: BedrockRuntimeAdapterUninstallJournal, + evidencePaths: BedrockEvidencePaths, + runtime: RuntimeAdapterCleanupRuntime, +): BedrockRuntimeAdapterStopResult { + if (bedrockRuntimeAdapterProcessPresence(initial.pid, runtime) !== "absent") { + return stopFailure( + runtime, + "Bedrock Runtime adapter process absence could not be revalidated before evidence deletion.", + initial.pid, + ); + } + if (!validateRetirementEvidence(evidencePaths, initial, true, runtime)) { + return stopFailure( + runtime, + "Bedrock Runtime adapter lifecycle generation could not be revalidated before evidence deletion; current evidence was preserved.", + initial.pid, + ); + } + if (initial.phase === "evidence-retired") { + if ( + runtime.existsSync(evidencePaths.pidPath) || + runtime.existsSync(evidencePaths.tokenPath) || + runtime.existsSync(evidencePaths.statePath) + ) { + return stopFailure( + runtime, + "Bedrock Runtime adapter lifecycle evidence reappeared after retirement; current evidence and journal were preserved.", + initial.pid, + ); + } + removeDurableBedrockRuntimeFile(journalPath); + return { ok: true, status: "stopped", pid: initial.pid }; + } + + let journal = advanceBedrockJournal(journalPath, initial, "evidence-retiring"); + for (const target of ["pidPath", "tokenPath", "statePath"] as const) { + if (!runtime.existsSync(evidencePaths[target])) continue; + if (bedrockRuntimeAdapterProcessPresence(journal.pid, runtime) !== "absent") { + return stopFailure( + runtime, + "Bedrock Runtime adapter PID was reused during evidence deletion; remaining evidence and journal were preserved.", + journal.pid, + ); + } + if (!evidenceFileMatchesJournal(target, evidencePaths, journal)) { + return stopFailure( + runtime, + "Bedrock Runtime adapter lifecycle generation could not be revalidated during evidence deletion; remaining evidence was preserved.", + journal.pid, + ); + } + removeDurableBedrockRuntimeFile(evidencePaths[target]); + } + journal = advanceBedrockJournal(journalPath, journal, "evidence-retired"); + removeDurableBedrockRuntimeFile(journalPath); + runtime.log(`Stopped Bedrock Runtime adapter ${String(journal.pid)}`); + return { ok: true, status: "stopped", pid: journal.pid }; +} + +function discoverUnboundBedrockListeners( + runtime: RuntimeAdapterCleanupRuntime, + adapterPort: number, +): void { + if (!runtime.commandExists("lsof")) { + runtime.warn("lsof not found; skipping orphan Bedrock Runtime adapter scan."); + return; + } + const lsof = runtime.run("lsof", ["-ti", `:${String(adapterPort)}`], { env: runtime.env }); + if (lsof.status !== 0 && lsof.status !== 1) { + runtime.warn( + "Bedrock Runtime adapter orphan scan could not inspect the configured port; no process was signaled.", + ); + return; + } + const pids = splitNonEmptyLines(lsof.stdout) + .map((raw) => canonicalPid(`${raw}\n`)) + .filter((pid): pid is number => pid !== null); + const owner = currentProcessOwner(); + const candidates = owner + ? pids.filter((pid) => { + const observed = observeBedrockRuntimeAdapterProcess(pid, runtime); + return ( + observed?.uid === owner.uid && + observed.user === owner.user && + observed.adapterPort === adapterPort + ); + }) + : []; + if (candidates.length > 0) { + runtime.warn( + "Found an unbound Bedrock Runtime adapter listener; no process was signaled without matching lifecycle state.", + ); + } else { + runtime.log("No Bedrock Runtime adapter processes found"); + } +} + +function discoverBedrockListenerPids( + runtime: RuntimeAdapterCleanupRuntime, + adapterPort: number, +): number[] | null { + if (!runtime.commandExists("lsof")) return null; + const lsof = runtime.run("lsof", ["-ti", `:${String(adapterPort)}`], { env: runtime.env }); + if (lsof.status !== 0 && lsof.status !== 1) return null; + return splitNonEmptyLines(lsof.stdout) + .map((raw) => canonicalPid(`${raw}\n`)) + .filter((pid): pid is number => pid !== null); +} + +function stopBedrockRuntimeAdapterLocked( + paths: Pick, + runtime: RuntimeAdapterCleanupRuntime, + journalPath: string, + gatewayPort: number, + scanOrphans: boolean, +): BedrockRuntimeAdapterStopResult { + const evidencePaths = bedrockEvidencePaths(paths.nemoclawStateDir); + const adapterPort = resolveRuntimeAdapterPort(runtime, BEDROCK_RUNTIME_ADAPTER); + const journalExists = runtime.existsSync(journalPath); + let journal = journalExists ? readBedrockRuntimeAdapterUninstallJournal(journalPath) : null; + if ( + journalExists && + (!journal || journal.gatewayPort !== gatewayPort || journal.adapterPort !== adapterPort) + ) { + return stopFailure( + runtime, + "Bedrock Runtime adapter uninstall journal is unsafe, malformed, or does not match the selected gateway and configured adapter port; lifecycle evidence was preserved.", + ); + } + + if (!journal) { + const evidenceResult = readBedrockEvidence(evidencePaths, runtime); + if (evidenceResult.kind === "invalid") { + return stopFailure(runtime, evidenceResult.message); + } + if (evidenceResult.kind === "pid-only") { + return retireAbsentPidOnlyEvidence( + evidencePaths, + journalPath, + evidenceResult.pid, + runtime, + ); + } + if (evidenceResult.kind === "absent") { + if (scanOrphans) { + discoverUnboundBedrockListeners( + runtime, + resolveRuntimeAdapterPort(runtime, BEDROCK_RUNTIME_ADAPTER), + ); + } else { + runtime.log("No selected-gateway Bedrock Runtime adapter found"); + } + return { ok: true, status: "absent" }; + } + + const { evidence } = evidenceResult; + const presence = bedrockRuntimeAdapterProcessPresence(evidence.pid, runtime); + if (presence === "unknown") { + return stopFailure( + runtime, + "Bedrock Runtime adapter process state is unavailable; lifecycle evidence was preserved.", + evidence.pid, + ); + } + if (scanOrphans && !evidence.pidFilePresent && presence === "present") { + const discovered = discoverBedrockListenerPids(runtime, adapterPort); + if (!discovered || !discovered.includes(evidence.pid)) { + return stopFailure( + runtime, + "Bedrock Runtime adapter orphan discovery did not confirm the state-bound listener; lifecycle evidence was preserved.", + evidence.pid, + ); + } + } + const observed = + presence === "present" ? observeBedrockRuntimeAdapterProcess(evidence.pid, runtime) : null; + if (presence === "present" && !observed) { + return stopFailure( + runtime, + "Bedrock Runtime adapter process ownership could not be proven; no process was signaled.", + evidence.pid, + ); + } + journal = journalFromEvidence(evidence, observed, gatewayPort, adapterPort); + if (!journal) { + return stopFailure( + runtime, + "Bedrock Runtime adapter lifecycle state does not match the configured adapter port, current user, process identity, or generation; no process was signaled.", + evidence.pid, + ); + } + writeDurablePrivateBedrockRuntimeJson(journalPath, journal); + if (presence === "absent") { + journal = advanceBedrockJournal(journalPath, journal, "process-absent"); + } + } + + if ( + journal.phase === "process-absent" || + journal.phase === "evidence-retiring" || + journal.phase === "evidence-retired" + ) { + return retireBedrockEvidence(journalPath, journal, evidencePaths, runtime); + } + const stopped = runBedrockStopPhases(journalPath, journal, runtime); + if (stopped.kind === "failure") { + return stopFailure(runtime, stopped.message, stopped.journal.pid); + } + return retireBedrockEvidence(journalPath, stopped.journal, evidencePaths, runtime); +} + export function stopBedrockRuntimeAdapter( paths: Pick, runtime: RuntimeAdapterCleanupRuntime, - options: { scanOrphans?: boolean } = {}, -): void { - stopRuntimeAdapter(paths, runtime, BEDROCK_RUNTIME_ADAPTER, options); + options: { gatewayPort: number; scanOrphans?: boolean }, +): BedrockRuntimeAdapterStopResult { + const home = runtime.env.HOME || os.homedir(); + const lifecycle = resolveBedrockRuntimeAdapterLifecyclePaths(home, options.gatewayPort); + try { + return withBedrockRuntimeAdapterLifecycleLock(lifecycle, () => + stopBedrockRuntimeAdapterLocked( + paths, + runtime, + lifecycle.journalPath, + options.gatewayPort, + options.scanOrphans !== false, + ), + ); + } catch (error) { + return stopFailure( + runtime, + `Bedrock Runtime adapter cleanup could not preserve its lifecycle journal: ${ + error instanceof Error ? error.message : String(error) + }`, + ); + } } export function stopOpenRouterRuntimeAdapter( diff --git a/src/lib/actions/uninstall/run-plan-gateway-segregation.test.ts b/src/lib/actions/uninstall/run-plan-gateway-segregation.test.ts index 05c5e23847b..72ba666fa59 100644 --- a/src/lib/actions/uninstall/run-plan-gateway-segregation.test.ts +++ b/src/lib/actions/uninstall/run-plan-gateway-segregation.test.ts @@ -5,7 +5,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterAll, afterEach, describe, expect, it, vi } from "vitest"; import { withProvenManagedGatewayProcess, writeManagedGatewayRuntimeProof, @@ -27,6 +27,14 @@ import { type UninstallRunOptions, } from "./run-plan"; +const STATIC_TEST_HOME = fs.mkdtempSync( + path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-segregation-static-"), +); + +afterAll(() => { + fs.rmSync(STATIC_TEST_HOME, { recursive: true, force: true }); +}); + function ok(stdout = ""): RunResult { return { status: 0, stdout, stderr: "" }; } @@ -216,7 +224,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command === "openshell", - env: { HOME: "/home/test" } as NodeJS.ProcessEnv, + env: { HOME: STATIC_TEST_HOME } as NodeJS.ProcessEnv, existsSync: () => false, isTty: false, resolveGatewayTeardownAuthority: ({ gatewayName, gatewayPort }) => ({ @@ -258,7 +266,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { const result = runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { - env: { HOME: "/home/test" } as NodeJS.ProcessEnv, + env: { HOME: STATIC_TEST_HOME } as NodeJS.ProcessEnv, error: vi.fn(), existsSync: () => false, resolveGatewayTeardownAuthority: () => { @@ -289,7 +297,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command !== "docker" && command !== "pgrep", - env: { HOME: "/home/test", TMPDIR: "/tmp/test" } as NodeJS.ProcessEnv, + env: { HOME: STATIC_TEST_HOME, TMPDIR: "/tmp/test" } as NodeJS.ProcessEnv, existsSync: () => false, isTty: false, rmSync: vi.fn(), @@ -320,7 +328,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command !== "docker" && command !== "pgrep", - env: { HOME: "/home/test", TMPDIR: "/tmp/test" } as NodeJS.ProcessEnv, + env: { HOME: STATIC_TEST_HOME, TMPDIR: "/tmp/test" } as NodeJS.ProcessEnv, existsSync: () => false, isTty: false, rmSync: vi.fn(), diff --git a/src/lib/actions/uninstall/run-plan-preserved-registry.test.ts b/src/lib/actions/uninstall/run-plan-preserved-registry.test.ts index 8622808ab7c..10447025f2b 100644 --- a/src/lib/actions/uninstall/run-plan-preserved-registry.test.ts +++ b/src/lib/actions/uninstall/run-plan-preserved-registry.test.ts @@ -5,7 +5,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { describe, expect, it, vi } from "vitest"; +import { afterAll, describe, expect, it, vi } from "vitest"; import { type RunResult, @@ -14,6 +14,14 @@ import { runUninstallPlan as runUninstallPlanBase, } from "./run-plan"; +const STATIC_TEST_HOME = fs.mkdtempSync( + path.join(os.tmpdir(), "nemoclaw-uninstall-preserved-registry-static-"), +); + +afterAll(() => { + fs.rmSync(STATIC_TEST_HOME, { recursive: true, force: true }); +}); + function ok(stdout = ""): RunResult { return { status: 0, stdout, stderr: "" }; } @@ -94,7 +102,7 @@ describe("uninstall messaging for a preserved-but-orphaned sandbox registry (#65 { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command !== "docker" && command !== "pgrep", - env: { HOME: "/home/test", TMPDIR: "/tmp/test" } as NodeJS.ProcessEnv, + env: { HOME: STATIC_TEST_HOME, TMPDIR: "/tmp/test" } as NodeJS.ProcessEnv, error: (line) => warnings.push(line), existsSync: () => false, isTty: false, diff --git a/src/lib/actions/uninstall/run-plan.test.ts b/src/lib/actions/uninstall/run-plan.test.ts index 19b8bdedd5f..b69cd2c7955 100644 --- a/src/lib/actions/uninstall/run-plan.test.ts +++ b/src/lib/actions/uninstall/run-plan.test.ts @@ -5,7 +5,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { describe, expect, it, vi } from "vitest"; +import { afterAll, describe, expect, it, vi } from "vitest"; import { buildRunPlan, @@ -15,6 +15,12 @@ import { type UninstallRunOptions, } from "./run-plan"; +const STATIC_TEST_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-static-")); + +afterAll(() => { + fs.rmSync(STATIC_TEST_HOME, { recursive: true, force: true }); +}); + function ok(stdout = ""): RunResult { return { status: 0, stdout, stderr: "" }; } @@ -912,13 +918,14 @@ describe("uninstall run plan", () => { // process.env, so a developer shell exporting it would silently flip // this interactive scenario onto the non-interactive path. env: { - HOME: "/home/test", + HOME: STATIC_TEST_HOME, NEMOCLAW_NON_INTERACTIVE: "", TMPDIR: "/tmp/test", } as NodeJS.ProcessEnv, error: (line) => warnings.push(line), existsSync: (target) => - target === "/swapfile" || target === "/home/test/.nemoclaw/managed_swap", + target === "/swapfile" || + target === path.join(STATIC_TEST_HOME, ".nemoclaw/managed_swap"), isTty: true, log: (line) => logs.push(line), rmSync: vi.fn(), @@ -942,7 +949,7 @@ describe("uninstall run plan", () => { { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command !== "docker" && command !== "pgrep", - env: { HOME: "/home/test", TMPDIR: "/tmp/test" } as NodeJS.ProcessEnv, + env: { HOME: STATIC_TEST_HOME, TMPDIR: "/tmp/test" } as NodeJS.ProcessEnv, error: (line) => warnings.push(line), existsSync: () => false, isTty: false, diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index c503b7d667d..aea143e0915 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -126,6 +126,7 @@ export interface UninstallRunDeps { readProcessArgv?: (pid: number) => readonly string[] | null; readProcessExecutable?: (pid: number) => string | null; readProcessEnvironment?: (pid: number) => Record | null; + readProcessIdentity?: (pid: number, fresh?: boolean) => string | null; readLine?: () => string | null; requireCompleteGatewayProcessCleanup?: boolean; resolveGatewayTeardownAuthority?: GatewayTeardownAuthorityResolver; @@ -485,6 +486,7 @@ interface UninstallRuntime { readProcessArgv: ((pid: number) => readonly string[] | null) | undefined; readProcessExecutable: ((pid: number) => string | null) | undefined; readProcessEnvironment: ((pid: number) => Record | null) | undefined; + readProcessIdentity: ((pid: number, fresh?: boolean) => string | null) | undefined; readLine: () => string | null; requireCompleteGatewayProcessCleanup: boolean; resolveGatewayTeardownAuthority: GatewayTeardownAuthorityResolver; @@ -538,6 +540,7 @@ function buildRuntime(deps: UninstallRunDeps): UninstallRuntime { readProcessArgv: deps.readProcessArgv, readProcessExecutable: deps.readProcessExecutable, readProcessEnvironment: deps.readProcessEnvironment, + readProcessIdentity: deps.readProcessIdentity, readLine: deps.readLine ?? readLineFromStdin, requireCompleteGatewayProcessCleanup: deps.requireCompleteGatewayProcessCleanup ?? false, resolveGatewayTeardownAuthority: @@ -1724,8 +1727,7 @@ function removeNvmLeftovers(paths: UninstallPaths, runtime: UninstallRuntime): v const versionDir = path.join(nodeVersionsDir, version.name); const modulesDir = path.join(versionDir, "lib", "node_modules"); const packageEntry = dirEntries(modulesDir).find( - (entry) => - (entry.isDirectory() || entry.isSymbolicLink()) && entry.name === "nemoclaw", + (entry) => (entry.isDirectory() || entry.isSymbolicLink()) && entry.name === "nemoclaw", ); const packageDir = packageEntry ? path.join(modulesDir, packageEntry.name) : null; const packageBins = packageDir ? nvmPackageBinTargets(packageDir) : new Map(); @@ -2110,6 +2112,20 @@ function recordManagedModelCleanup( return result.ok; } +function stopBedrockRuntimeAdapterForUninstall( + paths: UninstallPaths, + runtime: UninstallRuntime, + scopedToSelectedGateway: boolean, +): void { + const result = stopBedrockRuntimeAdapter(paths, runtime, { + gatewayPort: GATEWAY_PORT, + scanOrphans: !scopedToSelectedGateway, + }); + if (result.ok) return; + runtime.error(result.message); + throw new IncompleteBedrockRuntimeAdapterCleanupError(); +} + function removeDockerContainers(runtime: UninstallRuntime, gatewayName?: string): void { const result = runtime.runDocker(["ps", "-a", "--format", "{{.ID}} {{.Image}} {{.Names}}"], { env: runtime.env, @@ -2302,7 +2318,9 @@ function removeHostModelStores( preserveForFailedLlamaCleanup: boolean, ): boolean { if (preserveForFailedLlamaCleanup) { - runtime.log("Managed llama.cpp cleanup did not complete. NemoClaw kept model stores for retry."); + runtime.log( + "Managed llama.cpp cleanup did not complete. NemoClaw kept model stores for retry.", + ); return true; } if (scopedToSelectedGateway) { @@ -2888,15 +2906,13 @@ function executePlan( stopOpenRouterRuntimeAdapter(paths, runtime, { scanOrphans: !scopedToSelectedGateway, }); - stopBedrockRuntimeAdapter(paths, runtime, { - scanOrphans: !scopedToSelectedGateway, - }); if (scopedToSelectedGateway) { runtime.log("Sibling gateways remain; kept the shared HTTPS Pin Runtime adapter."); } else { stopHttpsPinRuntimeAdapter(paths, runtime); } stopModelRouter(paths, runtime, !scopedToSelectedGateway); + stopBedrockRuntimeAdapterForUninstall(paths, runtime, scopedToSelectedGateway); } else if (step.name === "OpenShell resources") { if ( !executeOpenShellResourceCleanup( @@ -3089,6 +3105,7 @@ function completePortablePlan( } class IncompleteHostGatewayCleanupError extends Error {} +class IncompleteBedrockRuntimeAdapterCleanupError extends Error {} function stopHostGatewayProcessesForUninstall( runtime: UninstallRuntime, @@ -3249,7 +3266,12 @@ export function runUninstallPlan( portableRetirementEntries, )); } catch (error) { - if (!(error instanceof IncompleteHostGatewayCleanupError)) throw error; + if ( + !(error instanceof IncompleteHostGatewayCleanupError) && + !(error instanceof IncompleteBedrockRuntimeAdapterCleanupError) + ) { + throw error; + } } if (ok) { printBye(runtime); diff --git a/src/lib/inference/bedrock-runtime-adapter.test.ts b/src/lib/inference/bedrock-runtime-adapter.test.ts index bc1eb7a5087..690d964d4e4 100644 --- a/src/lib/inference/bedrock-runtime-adapter.test.ts +++ b/src/lib/inference/bedrock-runtime-adapter.test.ts @@ -1,22 +1,58 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import crypto from "node:crypto"; +import fs from "node:fs"; import http from "node:http"; +import os from "node:os"; import { afterEach, describe, expect, it, vi } from "vitest"; +const runCaptureMock = vi.hoisted(() => vi.fn(() => "")); + // Only the process- and disk-touching helpers are replaced; every pure helper this file also // exercises keeps its real implementation. vi.mock("./local-adapter-lifecycle", async (importOriginal) => ({ ...(await importOriginal()), - cleanupFailedLocalAdapterStartup: vi.fn(), killLocalAdapterPid: vi.fn(), loadLocalAdapterPid: vi.fn(() => null), persistLocalAdapterPid: vi.fn(), + probeLocalAdapterHealth: vi.fn(async () => false), readLocalAdapterJsonFile: vi.fn(() => null), readLocalAdapterTextFile: vi.fn(() => null), spawnDetachedNodeAdapter: vi.fn(() => ({ pid: 4242 })), waitForLocalAdapterHealth: vi.fn(async () => false), + writeLocalAdapterSecretFile: vi.fn(), +})); + +vi.mock("./bedrock-runtime/lifecycle", async (importOriginal) => ({ + ...(await importOriginal()), + bedrockRuntimeAdapterProcessPresence: vi.fn(() => "absent"), + observeBedrockRuntimeAdapterProcess: vi.fn((_pid, _runtime, expected) => + expected ? { ...expected } : null, + ), + removeDurableBedrockRuntimeFile: vi.fn(), + resolveBedrockRuntimeAdapterLifecyclePaths: vi.fn(() => ({ + directory: "/__nemoclaw_test__/bedrock-runtime-adapter/8080", + journalPath: "/__nemoclaw_test__/bedrock-runtime-adapter/8080/uninstall.json", + lockName: "bedrock-runtime-adapter-test-8080", + lockPath: "/__nemoclaw_test__/bedrock-runtime-adapter/8080/lifecycle.lock", + lockStateDir: "/__nemoclaw_test__/bedrock-runtime-adapter-locks", + })), + withBedrockRuntimeAdapterLifecycleLockAsync: vi.fn(async (_lifecycle, operation) => operation()), + stopExactBedrockRuntimeAdapterProcess: vi.fn(() => ({ ok: true, status: "stopped" })), + writeDurablePrivateBedrockRuntimeJson: vi.fn(), +})); + +vi.mock("../runner", async (importOriginal) => ({ + ...(await importOriginal()), + run: vi.fn(), + runCapture: runCaptureMock, +})); + +vi.mock("../state/mcp-lifecycle-lock-identity", async (importOriginal) => ({ + ...(await importOriginal()), + readMcpLockProcessIdentity: vi.fn(() => "linux:test-boot:4242"), })); import { @@ -28,10 +64,22 @@ import { streamOpenAiChatCompletion, } from "./bedrock-runtime-adapter"; import { - cleanupFailedLocalAdapterStartup, + BEDROCK_RUNTIME_ADAPTER_GENERATION_ENV, + observeBedrockRuntimeAdapterProcess, + removeDurableBedrockRuntimeFile, + stopExactBedrockRuntimeAdapterProcess, + writeDurablePrivateBedrockRuntimeJson, +} from "./bedrock-runtime/lifecycle"; +import { isLocalAdapterProcess, killLocalAdapterPid, persistLocalAdapterPid, + probeLocalAdapterHealth, + readLocalAdapterJsonFile, + readLocalAdapterTextFile, + spawnDetachedNodeAdapter, + waitForLocalAdapterHealth, + writeLocalAdapterSecretFile, } from "./local-adapter-lifecycle"; const US_EAST_1_CLASSIFICATION = { @@ -54,6 +102,7 @@ afterEach(async () => { ), ); servers.length = 0; + vi.clearAllMocks(); }); function listen(server: http.Server): Promise { @@ -411,26 +460,25 @@ describe("Bedrock Runtime OpenAI adapter", () => { expect(body.error.message).toContain("Could not load credentials"); }); - it("kills the spawned child and clears adapter state when startup never becomes healthy", async () => { + it("stops the exact spawned generation when startup never becomes healthy", async () => { vi.mocked(killLocalAdapterPid).mockClear(); - vi.mocked(cleanupFailedLocalAdapterStartup).mockClear(); await expect( ensureBedrockRuntimeAdapter({ classification: US_EAST_1_CLASSIFICATION }), ).rejects.toThrow("did not become healthy"); - // The single direct kill is the pre-spawn one that clears any prior adapter; tearing the new - // child down is the shared cleanup's job, and it must target this adapter's own files and the - // pid of the child this call spawned. - expect(vi.mocked(killLocalAdapterPid).mock.calls).toHaveLength(1); - const [cleanup] = vi.mocked(cleanupFailedLocalAdapterStartup).mock.calls; - expect(cleanup?.[0].pidPath.endsWith("bedrock-runtime-adapter.pid")).toBe(true); - expect(cleanup?.[0].statePath.endsWith("bedrock-runtime-adapter.json")).toBe(true); - expect(cleanup?.[1]).toBe(4242); + expect(vi.mocked(killLocalAdapterPid).mock.calls).toHaveLength(0); + expect(stopExactBedrockRuntimeAdapterProcess).toHaveBeenCalledWith( + expect.objectContaining({ + pid: 4242, + processStart: "linux:test-boot:4242", + generation: expect.stringMatching(/^[a-f0-9]{32}$/u), + }), + expect.any(Object), + ); }); - it("hands the spawned child to cleanup when its pid file cannot be persisted", async () => { - vi.mocked(cleanupFailedLocalAdapterStartup).mockClear(); + it("uses the in-memory process identity when its PID file cannot be persisted", async () => { vi.mocked(persistLocalAdapterPid).mockImplementationOnce(() => { throw new Error("ENOSPC: no space left on device"); }); @@ -439,11 +487,294 @@ describe("Bedrock Runtime OpenAI adapter", () => { ensureBedrockRuntimeAdapter({ classification: US_EAST_1_CLASSIFICATION }), ).rejects.toThrow("ENOSPC"); - // The pid file the cleanup would otherwise reload was never written, so 4242 — the pid the - // mocked spawn returned — is the only remaining handle on the orphaned child. - const [cleanup] = vi.mocked(cleanupFailedLocalAdapterStartup).mock.calls; - expect(cleanup?.[0].pidPath.endsWith("bedrock-runtime-adapter.pid")).toBe(true); - expect(cleanup?.[1]).toBe(4242); + expect(stopExactBedrockRuntimeAdapterProcess).toHaveBeenCalledWith( + expect.objectContaining({ pid: 4242, processStart: "linux:test-boot:4242" }), + expect.any(Object), + ); + }); + + it("persists the exact Bedrock process generation after startup becomes healthy", async () => { + vi.mocked(waitForLocalAdapterHealth).mockResolvedValueOnce(true); + + const result = await ensureBedrockRuntimeAdapter({ + classification: US_EAST_1_CLASSIFICATION, + }); + + expect(result.token).toMatch(/^[a-f0-9]{48}$/u); + const spawnOptions = vi.mocked(spawnDetachedNodeAdapter).mock.calls.at(-1)?.[0]; + const generation = spawnOptions?.env[BEDROCK_RUNTIME_ADAPTER_GENERATION_ENV]; + expect(generation).toMatch(/^[a-f0-9]{32}$/u); + const persisted = vi.mocked(writeDurablePrivateBedrockRuntimeJson).mock.calls.at(-1)?.[1]; + expect(persisted).toMatchObject({ + version: 2, + generation, + pid: 4242, + processStart: "linux:test-boot:4242", + executablePath: expect.any(String), + scriptPath: expect.stringMatching(/bedrock-runtime-adapter\.mts$/u), + adapterPort: 11_436, + tokenHash: expect.stringMatching(/^[a-f0-9]{64}$/u), + }); + }); + + it("preserves exact lifecycle evidence when durable state publication fails", async () => { + const journalPath = "/__nemoclaw_test__/bedrock-runtime-adapter/8080/uninstall.json"; + let journalPublished = false; + const existsSync = vi + .spyOn(fs, "existsSync") + .mockImplementation((target) => (String(target) === journalPath ? journalPublished : false)); + vi.mocked(writeDurablePrivateBedrockRuntimeJson) + .mockImplementationOnce(() => { + throw new Error("EIO: lifecycle state write failed"); + }) + .mockImplementationOnce(() => { + journalPublished = true; + }); + + try { + await expect( + ensureBedrockRuntimeAdapter({ classification: US_EAST_1_CLASSIFICATION }), + ).rejects.toThrow("PID and token evidence were preserved"); + + const [tokenPath, token] = vi.mocked(writeLocalAdapterSecretFile).mock.calls.at(-1) ?? []; + expect(tokenPath).toMatch(/bedrock-runtime-adapter-token$/u); + expect(token).toMatch(/^[a-f0-9]{48}$/u); + expect(stopExactBedrockRuntimeAdapterProcess).not.toHaveBeenCalled(); + expect(vi.mocked(writeDurablePrivateBedrockRuntimeJson).mock.calls).toEqual([ + [ + expect.stringMatching(/bedrock-runtime-adapter\.json$/u), + expect.objectContaining({ + version: 2, + generation: expect.stringMatching(/^[a-f0-9]{32}$/u), + pid: 4242, + processStart: "linux:test-boot:4242", + tokenHash: expect.stringMatching(/^[a-f0-9]{64}$/u), + }), + ], + [ + journalPath, + expect.objectContaining({ + version: 1, + phase: "prepared", + gatewayPort: 8080, + generation: expect.stringMatching(/^[a-f0-9]{32}$/u), + pid: 4242, + processStart: "linux:test-boot:4242", + tokenHash: expect.stringMatching(/^[a-f0-9]{64}$/u), + }), + ], + ]); + + await expect( + ensureBedrockRuntimeAdapter({ classification: US_EAST_1_CLASSIFICATION }), + ).rejects.toThrow("uninstall cleanup is incomplete"); + expect(spawnDetachedNodeAdapter).toHaveBeenCalledTimes(1); + } finally { + existsSync.mockRestore(); + } + }); + + it("stops and retires the exact generation when state and journal publication both fail", async () => { + vi.mocked(writeDurablePrivateBedrockRuntimeJson) + .mockImplementationOnce(() => { + throw new Error("EIO: lifecycle state write failed"); + }) + .mockImplementationOnce(() => { + throw new Error("EIO: uninstall journal write failed"); + }); + + await expect( + ensureBedrockRuntimeAdapter({ classification: US_EAST_1_CLASSIFICATION }), + ).rejects.toThrow("state and uninstall journal could not be published"); + + expect(stopExactBedrockRuntimeAdapterProcess).toHaveBeenCalledWith( + expect.objectContaining({ + pid: 4242, + processStart: "linux:test-boot:4242", + generation: expect.stringMatching(/^[a-f0-9]{32}$/u), + executablePath: process.execPath, + adapterPort: 11_436, + }), + expect.any(Object), + ); + expect(removeDurableBedrockRuntimeFile).not.toHaveBeenCalled(); + + vi.mocked(writeDurablePrivateBedrockRuntimeJson).mockReset(); + vi.mocked(waitForLocalAdapterHealth).mockResolvedValueOnce(true); + await expect( + ensureBedrockRuntimeAdapter({ classification: US_EAST_1_CLASSIFICATION }), + ).resolves.toMatchObject({ region: "us-east-1" }); + }); + + it("preserves available evidence when publication and exact stop both fail", async () => { + vi.mocked(writeDurablePrivateBedrockRuntimeJson) + .mockImplementationOnce(() => { + throw new Error("EIO: lifecycle state write failed"); + }) + .mockImplementationOnce(() => { + throw new Error("EIO: uninstall journal write failed"); + }); + vi.mocked(stopExactBedrockRuntimeAdapterProcess).mockReturnValueOnce({ + ok: false, + reason: "unresolved", + }); + + await expect( + ensureBedrockRuntimeAdapter({ classification: US_EAST_1_CLASSIFICATION }), + ).rejects.toThrow( + "exact spawned process could not be stopped; lifecycle evidence was preserved", + ); + + expect(removeDurableBedrockRuntimeFile).not.toHaveBeenCalled(); + }); + + it("does not replace a running PID whose stable identity disagrees with lifecycle state", async () => { + const token = "prior-token"; + vi.mocked(readLocalAdapterJsonFile).mockReturnValueOnce({ + version: 2, + generation: "11111111111111111111111111111111", + pid: 4242, + processStart: "linux:test-boot:prior", + user: os.userInfo().username, + uid: process.getuid?.() ?? 501, + executablePath: process.execPath, + scriptPath: __test.getAdapterScriptPath(), + adapterPort: 11_436, + tokenHash: crypto.createHash("sha256").update(token).digest("hex"), + endpointUrl: US_EAST_1_CLASSIFICATION.endpointUrl, + region: US_EAST_1_CLASSIFICATION.region, + credentialHash: "a".repeat(64), + updatedAt: "2026-08-20T00:00:00.000Z", + }); + vi.mocked(readLocalAdapterTextFile).mockReturnValueOnce(token).mockReturnValueOnce("4242"); + runCaptureMock.mockReturnValueOnce( + `${process.execPath} --experimental-strip-types --no-warnings ${__test.getAdapterScriptPath()}`, + ); + + await expect( + ensureBedrockRuntimeAdapter({ classification: US_EAST_1_CLASSIFICATION }), + ).rejects.toThrow("lifecycle state does not match the running process"); + + expect(killLocalAdapterPid).not.toHaveBeenCalled(); + expect(spawnDetachedNodeAdapter).not.toHaveBeenCalled(); + }); + + it("does not signal a prior generation when a failed health check requires replacement", async () => { + const token = "prior-token"; + vi.mocked(readLocalAdapterJsonFile).mockReturnValueOnce({ + version: 2, + generation: "11111111111111111111111111111111", + pid: 4242, + processStart: "linux:test-boot:4242", + user: os.userInfo().username, + uid: process.getuid?.() ?? 501, + executablePath: process.execPath, + scriptPath: __test.getAdapterScriptPath(), + adapterPort: 11_436, + tokenHash: crypto.createHash("sha256").update(token).digest("hex"), + endpointUrl: US_EAST_1_CLASSIFICATION.endpointUrl, + region: US_EAST_1_CLASSIFICATION.region, + credentialHash: __test.adapterCredentialHash({ + endpointUrl: US_EAST_1_CLASSIFICATION.endpointUrl, + region: US_EAST_1_CLASSIFICATION.region, + compatibleCredential: null, + }), + updatedAt: "2026-08-20T00:00:00.000Z", + }); + vi.mocked(readLocalAdapterTextFile).mockReturnValueOnce(token).mockReturnValueOnce("4242"); + runCaptureMock.mockReturnValueOnce( + `${process.execPath} --experimental-strip-types --no-warnings ${__test.getAdapterScriptPath()}`, + ); + + await expect( + ensureBedrockRuntimeAdapter({ classification: US_EAST_1_CLASSIFICATION }), + ).rejects.toThrow("running generation cannot be reused"); + + expect(killLocalAdapterPid).not.toHaveBeenCalled(); + expect(spawnDetachedNodeAdapter).not.toHaveBeenCalled(); + }); + + it("retries a transient reuse probe and revalidates identity before returning", async () => { + const token = "prior-token"; + const priorState = { + version: 2, + generation: "11111111111111111111111111111111", + pid: 4242, + processStart: "linux:test-boot:4242", + user: os.userInfo().username, + uid: process.getuid?.() ?? 501, + executablePath: process.execPath, + scriptPath: __test.getAdapterScriptPath(), + adapterPort: 11_436, + tokenHash: crypto.createHash("sha256").update(token).digest("hex"), + endpointUrl: US_EAST_1_CLASSIFICATION.endpointUrl, + region: US_EAST_1_CLASSIFICATION.region, + credentialHash: __test.adapterCredentialHash({ + endpointUrl: US_EAST_1_CLASSIFICATION.endpointUrl, + region: US_EAST_1_CLASSIFICATION.region, + compatibleCredential: null, + }), + updatedAt: "2026-08-20T00:00:00.000Z", + }; + vi.mocked(readLocalAdapterJsonFile).mockReturnValueOnce(priorState); + vi.mocked(readLocalAdapterTextFile).mockReturnValueOnce(token).mockReturnValueOnce("4242"); + runCaptureMock.mockReturnValueOnce( + `${process.execPath} --experimental-strip-types --no-warnings ${__test.getAdapterScriptPath()}`, + ); + vi.mocked(probeLocalAdapterHealth).mockResolvedValueOnce(false).mockResolvedValueOnce(true); + vi.mocked(waitForLocalAdapterHealth).mockImplementationOnce(async (probe, options) => { + expect(options).toEqual({ attempts: 3, intervalMs: 100 }); + expect(await probe()).toBe(false); + return probe(); + }); + + await expect( + ensureBedrockRuntimeAdapter({ classification: US_EAST_1_CLASSIFICATION }), + ).resolves.toMatchObject({ token, region: "us-east-1" }); + + expect(observeBedrockRuntimeAdapterProcess).toHaveBeenCalledWith( + 4242, + expect.any(Object), + priorState, + ); + expect(spawnDetachedNodeAdapter).not.toHaveBeenCalled(); + }); + + it("does not reuse a process replaced after the health probe", async () => { + const token = "prior-token"; + vi.mocked(readLocalAdapterJsonFile).mockReturnValueOnce({ + version: 2, + generation: "11111111111111111111111111111111", + pid: 4242, + processStart: "linux:test-boot:4242", + user: os.userInfo().username, + uid: process.getuid?.() ?? 501, + executablePath: process.execPath, + scriptPath: __test.getAdapterScriptPath(), + adapterPort: 11_436, + tokenHash: crypto.createHash("sha256").update(token).digest("hex"), + endpointUrl: US_EAST_1_CLASSIFICATION.endpointUrl, + region: US_EAST_1_CLASSIFICATION.region, + credentialHash: __test.adapterCredentialHash({ + endpointUrl: US_EAST_1_CLASSIFICATION.endpointUrl, + region: US_EAST_1_CLASSIFICATION.region, + compatibleCredential: null, + }), + updatedAt: "2026-08-20T00:00:00.000Z", + }); + vi.mocked(readLocalAdapterTextFile).mockReturnValueOnce(token).mockReturnValueOnce("4242"); + runCaptureMock.mockReturnValueOnce( + `${process.execPath} --experimental-strip-types --no-warnings ${__test.getAdapterScriptPath()}`, + ); + vi.mocked(waitForLocalAdapterHealth).mockResolvedValueOnce(true); + vi.mocked(observeBedrockRuntimeAdapterProcess).mockReturnValueOnce(null); + + await expect( + ensureBedrockRuntimeAdapter({ classification: US_EAST_1_CLASSIFICATION }), + ).rejects.toThrow("running generation cannot be reused"); + + expect(spawnDetachedNodeAdapter).not.toHaveBeenCalled(); + expect(stopExactBedrockRuntimeAdapterProcess).not.toHaveBeenCalled(); }); it("spawns the typed .mts launcher entrypoint", () => { diff --git a/src/lib/inference/bedrock-runtime-adapter.ts b/src/lib/inference/bedrock-runtime-adapter.ts index c885df7fc03..0ff6e91fb27 100644 --- a/src/lib/inference/bedrock-runtime-adapter.ts +++ b/src/lib/inference/bedrock-runtime-adapter.ts @@ -2,14 +2,20 @@ // SPDX-License-Identifier: Apache-2.0 import crypto from "node:crypto"; +import fs from "node:fs"; import http from "node:http"; +import os from "node:os"; import path from "node:path"; import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime"; -import { BEDROCK_RUNTIME_ADAPTER_PORT, validateRuntimeAdapterPort } from "../core/ports"; +import { + BEDROCK_RUNTIME_ADAPTER_PORT, + GATEWAY_PORT, + validateRuntimeAdapterPort, +} from "../core/ports"; import { compactText, isLoopbackRemoteAddress } from "../core/url-utils"; -import { run, runCapture, SCRIPTS } from "../runner"; +import { runCapture, runCaptureEx, SCRIPTS } from "../runner"; import { buildSubprocessEnv } from "../subprocess-env"; import { BEDROCK_RUNTIME_ADAPTER_BIND_HOST, @@ -32,13 +38,29 @@ import { streamOpenAiChatCompletion, } from "./bedrock-runtime-translation"; import { - cleanupFailedLocalAdapterStartup, + BEDROCK_RUNTIME_ADAPTER_GENERATION_ENV, + BEDROCK_RUNTIME_ADAPTER_STATE_VERSION, + BEDROCK_RUNTIME_ADAPTER_UNINSTALL_JOURNAL_VERSION, + type BedrockRuntimeAdapterLifecyclePaths, + type BedrockRuntimeAdapterProcessIdentity, + type BedrockRuntimeAdapterProcessRuntime, + bedrockRuntimeAdapterProcessPresence, + canonicalPath, + canonicalPid, + isBedrockRuntimeAdapterState, + isBedrockRuntimeAdapterUninstallJournal, + observeBedrockRuntimeAdapterProcess, + readPrivateBedrockRuntimeFile, + removeDurableBedrockRuntimeFile, + resolveBedrockRuntimeAdapterLifecyclePaths, + stopExactBedrockRuntimeAdapterProcess, + withBedrockRuntimeAdapterLifecycleLockAsync, + writeDurablePrivateBedrockRuntimeJson, +} from "./bedrock-runtime/lifecycle"; +import { DEFAULT_LOCAL_ADAPTER_STATE_DIR, isLocalAdapterProcess, type JsonObject, - killLocalAdapterPid, - type LocalAdapterProcessOptions, - loadLocalAdapterPid, localAdapterTokenHash, persistLocalAdapterPid, probeLocalAdapterHealth, @@ -46,10 +68,10 @@ import { readLocalAdapterTextFile, spawnDetachedNodeAdapter, waitForLocalAdapterHealth, - writeLocalAdapterJsonFile, writeLocalAdapterSecretFile, } from "./local-adapter-lifecycle"; import { type AdapterLogger, createLocalAdapterLogger } from "./runtime-adapter/logger"; +import { readMcpLockProcessIdentity } from "../state/mcp-lifecycle-lock-identity"; export { AdapterHttpError, @@ -289,19 +311,132 @@ export function startBedrockRuntimeAdapterFromEnv(): http.Server { return server; } -const ADAPTER_PROCESS: LocalAdapterProcessOptions & { statePath: string } = { - pidPath: PID_PATH, - statePath: STATE_PATH, - processMatcher: BEDROCK_RUNTIME_ADAPTER_PROCESS_MATCHER, - run, - runCapture, -}; - function getAdapterScriptPath(): string { const scriptsDir = typeof SCRIPTS === "string" ? SCRIPTS : path.join(process.cwd(), "scripts"); return path.join(scriptsDir, "bedrock-runtime-adapter.mts"); } +function bedrockRuntimeAdapterProcessRuntime(): BedrockRuntimeAdapterProcessRuntime { + return { + env: process.env, + kill: (pid, signal) => { + try { + return process.kill(pid, signal); + } catch { + return false; + } + }, + run: (command, args, options) => { + const result = runCaptureEx([command, ...args], { env: options?.env }); + return { + status: result.exitCode, + stdout: result.stdout, + stderr: result.stderr ?? "", + }; + }, + }; +} + +function captureSpawnedBedrockRuntimeAdapterIdentity( + pid: number | null | undefined, + generation: string, + tokenHash: string, +): BedrockRuntimeAdapterProcessIdentity | null { + const processStart = Number.isSafeInteger(pid) ? readMcpLockProcessIdentity(pid!, true) : null; + const uid = process.getuid?.(); + if (!Number.isSafeInteger(pid) || !pid || pid <= 0 || !processStart) return null; + if (!Number.isSafeInteger(uid) || uid! < 0) return null; + return { + generation, + pid, + processStart, + user: os.userInfo().username, + uid: uid!, + executablePath: canonicalPath(process.execPath), + scriptPath: canonicalPath(getAdapterScriptPath()), + adapterPort: BEDROCK_RUNTIME_ADAPTER_PORT, + tokenHash, + }; +} + +function matchesBedrockRuntimeAdapterIdentity( + value: BedrockRuntimeAdapterProcessIdentity, + expected: BedrockRuntimeAdapterProcessIdentity, +): boolean { + return ( + value.generation === expected.generation && + value.pid === expected.pid && + value.processStart === expected.processStart && + value.user === expected.user && + value.uid === expected.uid && + canonicalPath(value.executablePath) === canonicalPath(expected.executablePath) && + canonicalPath(value.scriptPath) === canonicalPath(expected.scriptPath) && + value.adapterPort === expected.adapterPort && + value.tokenHash === expected.tokenHash + ); +} + +function failedStartupEvidenceMatches( + target: "journal" | "pid" | "state" | "token", + filePath: string, + expected: BedrockRuntimeAdapterProcessIdentity, + gatewayPort: number, +): boolean { + const raw = readPrivateBedrockRuntimeFile(filePath); + if (raw === null) return false; + if (target === "pid") return canonicalPid(raw) === expected.pid; + if (target === "token") return adapterTokenHash(raw.trim()) === expected.tokenHash; + try { + const value: unknown = JSON.parse(raw); + if (target === "state") { + return ( + isBedrockRuntimeAdapterState(value) && matchesBedrockRuntimeAdapterIdentity(value, expected) + ); + } + return ( + isBedrockRuntimeAdapterUninstallJournal(value) && + value.gatewayPort === gatewayPort && + matchesBedrockRuntimeAdapterIdentity(value, expected) + ); + } catch { + return false; + } +} + +function retireFailedStartupEvidence( + expected: BedrockRuntimeAdapterProcessIdentity, + lifecycle: BedrockRuntimeAdapterLifecyclePaths, + gatewayPort: number, + runtime: BedrockRuntimeAdapterProcessRuntime, +): boolean { + const evidence = [ + ["pid", PID_PATH], + ["token", TOKEN_PATH], + ["state", STATE_PATH], + ["journal", lifecycle.journalPath], + ] as const; + if (bedrockRuntimeAdapterProcessPresence(expected.pid, runtime) !== "absent") return false; + if ( + evidence.some( + ([kind, target]) => + fs.existsSync(target) && !failedStartupEvidenceMatches(kind, target, expected, gatewayPort), + ) + ) { + return false; + } + for (const [kind, target] of evidence) { + if (!fs.existsSync(target)) continue; + if ( + bedrockRuntimeAdapterProcessPresence(expected.pid, runtime) !== "absent" || + !failedStartupEvidenceMatches(kind, target, expected, gatewayPort) + ) { + return false; + } + removeDurableBedrockRuntimeFile(target); + } + return true; +} + function copyAwsEnv(extra: Record): void { for (const [key, value] of Object.entries(process.env)) { if (value !== undefined && key.startsWith("AWS_")) { @@ -355,9 +490,11 @@ async function waitForAdapterHealth( }); } -export async function ensureBedrockRuntimeAdapter(options: { +async function ensureBedrockRuntimeAdapterLocked(options: { classification: Extract; compatibleCredential?: string | null; + lifecycle: BedrockRuntimeAdapterLifecyclePaths; + gatewayPort: number; }): Promise<{ baseUrl: string; localBaseUrl: string; @@ -373,15 +510,52 @@ export async function ensureBedrockRuntimeAdapter(options: { const credentialHash = adapterCredentialHash({ endpointUrl, region, compatibleCredential }); const priorState = readLocalAdapterJsonFile(STATE_PATH); const priorToken = readLocalAdapterTextFile(TOKEN_PATH); - const priorPid = loadLocalAdapterPid(PID_PATH); + const priorPidText = readLocalAdapterTextFile(PID_PATH); + const priorEvidenceExists = + priorState !== null || + priorToken !== null || + priorPidText !== null || + [STATE_PATH, TOKEN_PATH, PID_PATH].some((target) => fs.existsSync(target)); + const priorPid = priorPidText ? canonicalPid(priorPidText) : null; + const priorProcessIsRunning = isLocalAdapterProcess( + priorPid, + BEDROCK_RUNTIME_ADAPTER_PROCESS_MATCHER, + runCapture, + ); + const priorStateProcessMatches = + isBedrockRuntimeAdapterState(priorState) && + priorPid !== null && + priorState.pid === priorPid && + priorState.uid === process.getuid?.() && + priorState.user === os.userInfo().username && + canonicalPath(priorState.executablePath) === canonicalPath(process.execPath) && + canonicalPath(priorState.scriptPath) === canonicalPath(getAdapterScriptPath()) && + priorState.adapterPort === BEDROCK_RUNTIME_ADAPTER_PORT && + priorToken !== null && + priorState.tokenHash === adapterTokenHash(priorToken) && + readMcpLockProcessIdentity(priorPid, true) === priorState.processStart; + let reusableProcessValidated = false; if ( priorToken && - isLocalAdapterProcess(priorPid, BEDROCK_RUNTIME_ADAPTER_PROCESS_MATCHER, runCapture) && + priorStateProcessMatches && + priorProcessIsRunning && priorState?.endpointUrl === endpointUrl && priorState?.region === region && - priorState?.credentialHash === credentialHash && - (await probeAdapterHealth({ tokenHash: adapterTokenHash(priorToken) })) + priorState?.credentialHash === credentialHash ) { + const healthy = await waitForLocalAdapterHealth( + () => probeAdapterHealth({ tokenHash: adapterTokenHash(priorToken) }), + { attempts: 3, intervalMs: 100 }, + ); + reusableProcessValidated = + healthy && + observeBedrockRuntimeAdapterProcess( + priorState.pid, + bedrockRuntimeAdapterProcessRuntime(), + priorState, + ) !== null; + } + if (priorToken && reusableProcessValidated) { process.env[BEDROCK_RUNTIME_ADAPTER_PROVIDER_CREDENTIAL_ENV] = priorToken; return { baseUrl: BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL, @@ -393,12 +567,21 @@ export async function ensureBedrockRuntimeAdapter(options: { }; } - killLocalAdapterPid(ADAPTER_PROCESS); + if (priorEvidenceExists) { + const reason = priorProcessIsRunning + ? priorStateProcessMatches + ? "the running generation cannot be reused" + : "lifecycle state does not match the running process" + : "lifecycle evidence remains for a generation that cannot be reused"; + throw new Error(`Bedrock Runtime adapter ${reason}; rerun uninstall before onboarding.`); + } const token = crypto.randomBytes(24).toString("hex"); + const generation = crypto.randomBytes(16).toString("hex"); const childEnv: Record = { NEMOCLAW_BEDROCK_RUNTIME_ENDPOINT_URL: endpointUrl, NEMOCLAW_BEDROCK_RUNTIME_REGION: region, NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_PORT: String(BEDROCK_RUNTIME_ADAPTER_PORT), + [BEDROCK_RUNTIME_ADAPTER_GENERATION_ENV]: generation, [BEDROCK_RUNTIME_ADAPTER_PROVIDER_CREDENTIAL_ENV]: token, AWS_REGION: process.env.AWS_REGION || region, AWS_DEFAULT_REGION: process.env.AWS_DEFAULT_REGION || region, @@ -413,25 +596,91 @@ export async function ensureBedrockRuntimeAdapter(options: { env: childEnv, buildEnv: buildSubprocessEnv, }); + const processRuntime = bedrockRuntimeAdapterProcessRuntime(); + const tokenHash = adapterTokenHash(token); + let lifecycleIdentity: BedrockRuntimeAdapterProcessIdentity | null = null; + let durableUninstallAuthorityPublished = false; try { persistLocalAdapterPid(PID_PATH, child.pid); - + lifecycleIdentity = captureSpawnedBedrockRuntimeAdapterIdentity( + child.pid, + generation, + tokenHash, + ); + if (!lifecycleIdentity) { + throw new Error("Bedrock Runtime adapter process identity could not be recorded"); + } + const updatedAt = new Date().toISOString(); + writeLocalAdapterSecretFile(TOKEN_PATH, token); + try { + writeDurablePrivateBedrockRuntimeJson(STATE_PATH, { + version: BEDROCK_RUNTIME_ADAPTER_STATE_VERSION, + ...lifecycleIdentity, + endpointUrl, + region, + credentialHash, + updatedAt, + }); + } catch (stateError) { + try { + writeDurablePrivateBedrockRuntimeJson(options.lifecycle.journalPath, { + version: BEDROCK_RUNTIME_ADAPTER_UNINSTALL_JOURNAL_VERSION, + phase: "prepared", + gatewayPort: options.gatewayPort, + ...lifecycleIdentity, + createdAt: updatedAt, + updatedAt, + }); + durableUninstallAuthorityPublished = true; + } catch (journalError) { + throw new AggregateError( + [stateError, journalError], + "Bedrock Runtime adapter lifecycle state and uninstall journal could not be published.", + ); + } + throw new Error( + "Bedrock Runtime adapter lifecycle state could not be published; PID and token evidence were preserved. Rerun uninstall before onboarding.", + { cause: stateError }, + ); + } if (!(await waitForAdapterHealth(token))) { throw new Error( `Bedrock Runtime adapter did not become healthy on ${BEDROCK_RUNTIME_ADAPTER_LOOPBACK_OPENAI_BASE_URL}`, ); } - - writeLocalAdapterSecretFile(TOKEN_PATH, token); - writeLocalAdapterJsonFile(STATE_PATH, { - endpointUrl, - region, - credentialHash, - pid: child.pid ?? null, - updatedAt: new Date().toISOString(), - }); } catch (err) { - cleanupFailedLocalAdapterStartup(ADAPTER_PROCESS, child.pid); + if (durableUninstallAuthorityPublished) throw err; + lifecycleIdentity ??= captureSpawnedBedrockRuntimeAdapterIdentity( + child.pid, + generation, + tokenHash, + ); + if (!lifecycleIdentity) { + throw new Error( + "Bedrock Runtime adapter startup failed before its process identity could be proven; available PID evidence was preserved.", + { cause: err }, + ); + } + const stopped = stopExactBedrockRuntimeAdapterProcess(lifecycleIdentity, processRuntime); + if (!stopped.ok) { + throw new Error( + "Bedrock Runtime adapter startup failed and the exact spawned process could not be stopped; lifecycle evidence was preserved.", + { cause: err }, + ); + } + if ( + !retireFailedStartupEvidence( + lifecycleIdentity, + options.lifecycle, + options.gatewayPort, + processRuntime, + ) + ) { + throw new Error( + "Bedrock Runtime adapter startup failed; the process stopped, but lifecycle evidence could not be safely retired.", + { cause: err }, + ); + } throw err; } process.env[BEDROCK_RUNTIME_ADAPTER_PROVIDER_CREDENTIAL_ENV] = token; @@ -446,6 +695,33 @@ export async function ensureBedrockRuntimeAdapter(options: { }; } +export async function ensureBedrockRuntimeAdapter(options: { + classification: Extract; + compatibleCredential?: string | null; +}): Promise<{ + baseUrl: string; + localBaseUrl: string; + logPath: string; + credentialEnv: string; + token: string; + region: string; +}> { + const home = process.env.HOME || os.homedir(); + const lifecycle = resolveBedrockRuntimeAdapterLifecyclePaths(home, GATEWAY_PORT); + return withBedrockRuntimeAdapterLifecycleLockAsync(lifecycle, async () => { + if (fs.existsSync(lifecycle.journalPath)) { + throw new Error( + "Bedrock Runtime adapter uninstall cleanup is incomplete; rerun uninstall before onboarding.", + ); + } + return ensureBedrockRuntimeAdapterLocked({ + ...options, + lifecycle, + gatewayPort: GATEWAY_PORT, + }); + }); +} + export function getCompatibleAnthropicCredentialForBedrock(): string | null { return process.env[BEDROCK_RUNTIME_COMPATIBLE_CREDENTIAL_ENV]?.trim() || null; } diff --git a/src/lib/inference/bedrock-runtime/lifecycle.test.ts b/src/lib/inference/bedrock-runtime/lifecycle.test.ts new file mode 100644 index 00000000000..b993c57cbaa --- /dev/null +++ b/src/lib/inference/bedrock-runtime/lifecycle.test.ts @@ -0,0 +1,296 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + BEDROCK_RUNTIME_ADAPTER_STATE_VERSION, + canonicalPid, + isBedrockRuntimeAdapterState, + readPrivateBedrockRuntimeFile, + resolveBedrockRuntimeAdapterLifecyclePaths, + stopExactBedrockRuntimeAdapterProcess, + withBedrockRuntimeAdapterLifecycleLock, + writeDurablePrivateBedrockRuntimeJson, +} from "./lifecycle"; +import { readMcpLockProcessIdentity } from "../../state/mcp-lifecycle-lock-identity"; + +describe("Bedrock Runtime adapter lifecycle", () => { + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it("records stable owner identity so a live lock cannot be reclaimed by age", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-lifecycle-lock-")); + const lifecycle = resolveBedrockRuntimeAdapterLifecyclePaths(home, 8080); + const expectedIdentity = readMcpLockProcessIdentity(process.pid, true); + + try { + expect(expectedIdentity).not.toBeNull(); + withBedrockRuntimeAdapterLifecycleLock(lifecycle, () => { + const owner = JSON.parse(fs.readFileSync(lifecycle.lockPath, "utf8")); + expect(owner).toMatchObject({ + pid: process.pid, + processIdentity: expectedIdentity, + }); + }); + expect(fs.existsSync(lifecycle.lockPath)).toBe(false); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("keeps process-bound locks in the owner-private lifecycle tree", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-lifecycle-path-")); + const lifecycle = resolveBedrockRuntimeAdapterLifecyclePaths(home, 8080); + + try { + expect(lifecycle.lockStateDir).toBe( + path.join(home, ".local", "state", "nemoclaw-bedrock-runtime-adapter", "locks"), + ); + withBedrockRuntimeAdapterLifecycleLock(lifecycle, () => undefined); + const stat = fs.lstatSync(lifecycle.lockStateDir); + expect(stat.mode & 0o777).toBe(0o700); + expect(stat.uid).toBe(process.getuid?.()); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("rejects unsafe private-file shapes and noncanonical PIDs", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-private-file-")); + const target = path.join(home, "state.json"); + + try { + fs.writeFileSync(target, "{}\n", { mode: 0o644 }); + expect(readPrivateBedrockRuntimeFile(target)).toBeNull(); + expect(canonicalPid("42\n")).toBe(42); + expect(canonicalPid("42 trailing\n")).toBeNull(); + expect(canonicalPid("042\n")).toBeNull(); + expect(isBedrockRuntimeAdapterState({ version: BEDROCK_RUNTIME_ADAPTER_STATE_VERSION })).toBe( + false, + ); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("writes owner-only durable files and rejects symlink and hard-link reads", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-durable-file-")); + const target = path.join(home, "private", "state.json"); + const symlink = path.join(home, "state-link.json"); + const hardLink = path.join(home, "state-hard-link.json"); + + try { + writeDurablePrivateBedrockRuntimeJson(target, { ok: true }); + expect(fs.lstatSync(target).mode & 0o777).toBe(0o600); + expect(readPrivateBedrockRuntimeFile(target)).toContain('"ok": true'); + fs.symlinkSync(target, symlink); + fs.linkSync(target, hardLink); + expect(readPrivateBedrockRuntimeFile(symlink)).toBeNull(); + expect(readPrivateBedrockRuntimeFile(target)).toBeNull(); + expect(readPrivateBedrockRuntimeFile(hardLink)).toBeNull(); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("rejects a lifecycle lock directory owned by another user", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-foreign-lock-")); + const lifecycle = resolveBedrockRuntimeAdapterLifecyclePaths(home, 8080); + fs.mkdirSync(lifecycle.lockStateDir, { recursive: true, mode: 0o700 }); + const originalLstat = fs.lstatSync; + const current = originalLstat(lifecycle.lockStateDir); + vi.spyOn(fs, "lstatSync").mockImplementation(((target: fs.PathLike) => { + const stat = originalLstat(target); + return String(target) === lifecycle.lockStateDir + ? new Proxy(stat, { + get(value, property) { + const result = Reflect.get(value, property, value); + return property === "uid" + ? current.uid + 1 + : typeof result === "function" + ? result.bind(value) + : result; + }, + }) + : stat; + }) as typeof fs.lstatSync); + + try { + expect(() => withBedrockRuntimeAdapterLifecycleLock(lifecycle, () => undefined)).toThrow( + "owned by another user", + ); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("keeps the synchronous lock wrapper synchronous at compile time", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-bedrock-sync-lock-")); + const lifecycle = resolveBedrockRuntimeAdapterLifecyclePaths(home, 8080); + + try { + const rejectsPromiseCallback = () => { + // @ts-expect-error The synchronous lifecycle lock must reject Promise callbacks. + withBedrockRuntimeAdapterLifecycleLock(lifecycle, async () => undefined); + }; + expect(rejectsPromiseCallback).toBeTypeOf("function"); + expect(withBedrockRuntimeAdapterLifecycleLock(lifecycle, () => "done")).toBe("done"); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("revalidates the exact generation before TERM and KILL", () => { + vi.useFakeTimers(); + const expected = { + generation: "1".repeat(32), + pid: 4242, + processStart: "linux:test-boot:42", + user: "testuser", + uid: 501, + executablePath: "/usr/bin/node", + scriptPath: "/opt/nemoclaw/bedrock-runtime-adapter.mts", + adapterPort: 11_436, + tokenHash: "a".repeat(64), + }; + let generation = expected.generation; + const kills: NodeJS.Signals[] = []; + const runtime = { + env: {} as NodeJS.ProcessEnv, + kill: (_pid: number, signal?: NodeJS.Signals | number) => { + kills.push(signal as NodeJS.Signals); + generation = signal === "SIGTERM" ? "2".repeat(32) : generation; + return true; + }, + readProcessArgv: () => [expected.executablePath, expected.scriptPath], + readProcessExecutable: () => expected.executablePath, + readProcessEnvironment: () => ({ + NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_GENERATION: generation, + NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_PORT: String(expected.adapterPort), + }), + readProcessIdentity: () => expected.processStart, + run: (_command: string, args: readonly string[]) => { + const field = args.at(-1); + return { + status: 0, + stdout: + field === "pid=" + ? `${String(expected.pid)}\n` + : field === "uid=" + ? `${String(expected.uid)}\n` + : field === "user=" + ? `${expected.user}\n` + : "", + stderr: "", + }; + }, + sleep: (milliseconds: number) => vi.advanceTimersByTime(milliseconds), + }; + + expect(stopExactBedrockRuntimeAdapterProcess(expected, runtime)).toEqual({ + ok: false, + reason: "authority-drift", + }); + expect(kills).toEqual(["SIGTERM"]); + }); + + it("returns unresolved after exact TERM and KILL exhaustion", () => { + vi.useFakeTimers(); + const expected = { + generation: "1".repeat(32), + pid: 4242, + processStart: "linux:test-boot:42", + user: "testuser", + uid: 501, + executablePath: "/usr/bin/node", + scriptPath: "/opt/nemoclaw/bedrock-runtime-adapter.mts", + adapterPort: 11_436, + tokenHash: "a".repeat(64), + }; + const kills: NodeJS.Signals[] = []; + const runtime = { + env: {} as NodeJS.ProcessEnv, + kill: (_pid: number, signal?: NodeJS.Signals | number) => { + kills.push(signal as NodeJS.Signals); + return true; + }, + readProcessArgv: () => [expected.executablePath, expected.scriptPath], + readProcessExecutable: () => expected.executablePath, + readProcessEnvironment: () => ({ + NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_GENERATION: expected.generation, + NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_PORT: String(expected.adapterPort), + }), + readProcessIdentity: () => expected.processStart, + run: (_command: string, args: readonly string[]) => ({ + status: 0, + stdout: + args.at(-1) === "pid=" + ? `${String(expected.pid)}\n` + : args.at(-1) === "uid=" + ? `${String(expected.uid)}\n` + : args.at(-1) === "user=" + ? `${expected.user}\n` + : "", + stderr: "", + }), + sleep: (milliseconds: number) => vi.advanceTimersByTime(milliseconds), + }; + + expect(stopExactBedrockRuntimeAdapterProcess(expected, runtime)).toEqual({ + ok: false, + reason: "unresolved", + }); + expect(kills).toEqual(["SIGTERM", "SIGKILL"]); + }); + + it("does not signal when the live adapter port differs from authority", () => { + const expected = { + generation: "1".repeat(32), + pid: 4242, + processStart: "linux:test-boot:42", + user: "testuser", + uid: 501, + executablePath: "/usr/bin/node", + scriptPath: "/opt/nemoclaw/bedrock-runtime-adapter.mts", + adapterPort: 11_436, + tokenHash: "a".repeat(64), + }; + const kill = vi.fn(() => true); + const runtime = { + env: {} as NodeJS.ProcessEnv, + kill, + readProcessArgv: () => [expected.executablePath, expected.scriptPath], + readProcessExecutable: () => expected.executablePath, + readProcessEnvironment: () => ({ + NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_GENERATION: expected.generation, + NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_PORT: "11437", + }), + readProcessIdentity: () => expected.processStart, + run: (_command: string, args: readonly string[]) => ({ + status: 0, + stdout: + args.at(-1) === "pid=" + ? `${String(expected.pid)}\n` + : args.at(-1) === "uid=" + ? `${String(expected.uid)}\n` + : args.at(-1) === "user=" + ? `${expected.user}\n` + : "", + stderr: "", + }), + }; + + expect(stopExactBedrockRuntimeAdapterProcess(expected, runtime)).toEqual({ + ok: false, + reason: "authority-drift", + }); + expect(kill).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/inference/bedrock-runtime/lifecycle.ts b/src/lib/inference/bedrock-runtime/lifecycle.ts new file mode 100644 index 00000000000..b027c947cec --- /dev/null +++ b/src/lib/inference/bedrock-runtime/lifecycle.ts @@ -0,0 +1,615 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import crypto from "node:crypto"; +import type { SpawnSyncOptions } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; + +import { ensureLocalAdapterStateDir } from "../local-adapter-lifecycle"; +import { + withMcpLifecycleLock, + withMcpLifecycleLockSync, +} from "../../state/mcp-lifecycle-lock-acquisition"; +import { getMcpLifecycleLockPath } from "../../state/mcp-lifecycle-lock-storage"; +import { readMcpLockProcessIdentity } from "../../state/mcp-lifecycle-lock-identity"; + +export const BEDROCK_RUNTIME_ADAPTER_STATE_VERSION = 2; +export const BEDROCK_RUNTIME_ADAPTER_UNINSTALL_JOURNAL_VERSION = 1; +export const BEDROCK_RUNTIME_ADAPTER_GENERATION_ENV = "NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_GENERATION"; + +export type BedrockRuntimeAdapterUninstallPhase = + | "prepared" + | "term-sent" + | "kill-sent" + | "process-absent" + | "evidence-retiring" + | "evidence-retired"; + +export interface BedrockRuntimeAdapterState { + version: typeof BEDROCK_RUNTIME_ADAPTER_STATE_VERSION; + generation: string; + pid: number; + processStart: string; + user: string; + uid: number; + executablePath: string; + scriptPath: string; + adapterPort: number; + tokenHash: string; + endpointUrl: string; + region: string; + credentialHash: string; + updatedAt: string; +} + +export interface BedrockRuntimeAdapterUninstallJournal { + version: typeof BEDROCK_RUNTIME_ADAPTER_UNINSTALL_JOURNAL_VERSION; + phase: BedrockRuntimeAdapterUninstallPhase; + gatewayPort: number; + generation: string; + pid: number; + processStart: string; + user: string; + uid: number; + executablePath: string; + scriptPath: string; + adapterPort: number; + tokenHash: string; + createdAt: string; + updatedAt: string; +} + +export interface BedrockRuntimeAdapterLifecyclePaths { + directory: string; + journalPath: string; + lockName: string; + lockPath: string; + lockStateDir: string; +} + +export interface BedrockRuntimeAdapterProcessIdentity { + generation: string; + pid: number; + processStart: string; + user: string; + uid: number; + executablePath: string; + scriptPath: string; + adapterPort: number; + tokenHash: string; +} + +export interface BedrockRuntimeAdapterProcessRuntime { + env: NodeJS.ProcessEnv; + kill: (pid: number, signal?: NodeJS.Signals | number) => boolean; + readProcessArgv?: (pid: number) => readonly string[] | null; + readProcessExecutable?: (pid: number) => string | null; + readProcessEnvironment?: (pid: number) => Record | null; + readProcessIdentity?: (pid: number, fresh?: boolean) => string | null; + run: ( + command: string, + args: string[], + options?: SpawnSyncOptions, + ) => { status: number | null; stdout: string; stderr: string }; + sleep?: (milliseconds: number) => void; +} + +export type BedrockRuntimeAdapterProcessPresence = "absent" | "present" | "unknown"; + +export interface ObservedBedrockRuntimeAdapterProcess { + adapterPort: number | null; + executablePath: string; + generation: string | null; + processStart: string; + scriptPath: string; + uid: number; + user: string; +} + +export type BedrockRuntimeAdapterProcessStopResult = + | { ok: true; status: "absent" | "stopped" } + | { ok: false; reason: "authority-drift" | "unresolved" }; + +const GENERATION = /^[a-f0-9]{32}$/u; +const LEGACY_GENERATION = /^legacy:[a-f0-9]{64}$/u; +const PROCESS_START = /^[^\u0000\r\n]{1,512}$/u; +const SHA256 = /^[a-f0-9]{64}$/u; +const USER = /^[^\s\u0000]{1,256}$/u; +const MAX_PRIVATE_FILE_BYTES = 16 * 1024; +const PROCESS_EXIT_TIMEOUT_MS = 1_000; +const PROCESS_EXIT_POLL_MS = 50; +const PROCESS_EXIT_WAIT_BUFFER = new Int32Array( + new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT), +); + +function sleepForProcessExit(milliseconds: number): void { + Atomics.wait(PROCESS_EXIT_WAIT_BUFFER, 0, 0, milliseconds); +} + +function isSafePort(value: unknown): value is number { + return Number.isSafeInteger(value) && (value as number) >= 1 && (value as number) <= 65_535; +} + +function isSafePid(value: unknown): value is number { + return Number.isSafeInteger(value) && (value as number) > 0; +} + +function isCanonicalAbsolutePath(value: unknown): value is string { + return ( + typeof value === "string" && + value.length > 1 && + value.length <= 4096 && + !value.includes("\0") && + path.isAbsolute(value) && + path.normalize(value) === value + ); +} + +export function isBedrockRuntimeAdapterState(value: unknown): value is BedrockRuntimeAdapterState { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const state = value as Record; + return ( + state.version === BEDROCK_RUNTIME_ADAPTER_STATE_VERSION && + typeof state.generation === "string" && + GENERATION.test(state.generation) && + isSafePid(state.pid) && + typeof state.processStart === "string" && + PROCESS_START.test(state.processStart) && + typeof state.user === "string" && + USER.test(state.user) && + Number.isSafeInteger(state.uid) && + (state.uid as number) >= 0 && + isCanonicalAbsolutePath(state.executablePath) && + isCanonicalAbsolutePath(state.scriptPath) && + isSafePort(state.adapterPort) && + typeof state.tokenHash === "string" && + SHA256.test(state.tokenHash) && + typeof state.endpointUrl === "string" && + state.endpointUrl.length > 0 && + typeof state.region === "string" && + state.region.length > 0 && + typeof state.credentialHash === "string" && + SHA256.test(state.credentialHash) && + typeof state.updatedAt === "string" && + !Number.isNaN(Date.parse(state.updatedAt)) + ); +} + +export function isBedrockRuntimeAdapterUninstallJournal( + value: unknown, +): value is BedrockRuntimeAdapterUninstallJournal { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const journal = value as Record; + return ( + journal.version === BEDROCK_RUNTIME_ADAPTER_UNINSTALL_JOURNAL_VERSION && + [ + "prepared", + "term-sent", + "kill-sent", + "process-absent", + "evidence-retiring", + "evidence-retired", + ].includes(String(journal.phase)) && + isSafePort(journal.gatewayPort) && + typeof journal.generation === "string" && + (GENERATION.test(journal.generation) || LEGACY_GENERATION.test(journal.generation)) && + isSafePid(journal.pid) && + typeof journal.processStart === "string" && + PROCESS_START.test(journal.processStart) && + typeof journal.user === "string" && + USER.test(journal.user) && + Number.isSafeInteger(journal.uid) && + (journal.uid as number) >= 0 && + isCanonicalAbsolutePath(journal.executablePath) && + isCanonicalAbsolutePath(journal.scriptPath) && + isSafePort(journal.adapterPort) && + typeof journal.tokenHash === "string" && + SHA256.test(journal.tokenHash) && + typeof journal.createdAt === "string" && + !Number.isNaN(Date.parse(journal.createdAt)) && + typeof journal.updatedAt === "string" && + !Number.isNaN(Date.parse(journal.updatedAt)) + ); +} + +export function canonicalPid(raw: string): number | null { + if (!/^[1-9][0-9]{0,15}\n?$/u.test(raw)) return null; + const value = Number(raw.trim()); + return Number.isSafeInteger(value) ? value : null; +} + +export function canonicalPath(target: string): string { + try { + return fs.realpathSync.native(target); + } catch { + return path.resolve(target); + } +} + +export function bedrockRuntimeAdapterProcessPresence( + pid: number, + runtime: BedrockRuntimeAdapterProcessRuntime, +): BedrockRuntimeAdapterProcessPresence { + const result = runtime.run("ps", ["-p", String(pid), "-o", "pid="], { env: runtime.env }); + if (result.status === 1) return "absent"; + if (result.status !== 0 || result.stdout.trim() !== String(pid)) return "unknown"; + return "present"; +} + +function readProcArgv(pid: number): readonly string[] | null { + try { + const argv = fs + .readFileSync(`/proc/${String(pid)}/cmdline`) + .toString("utf8") + .split("\0"); + if (argv.at(-1) === "") argv.pop(); + return argv.length > 0 ? argv : null; + } catch { + return null; + } +} + +function readProcessArgv( + pid: number, + runtime: BedrockRuntimeAdapterProcessRuntime, +): readonly string[] | null { + if (runtime.readProcessArgv) return runtime.readProcessArgv(pid); + const procArgv = readProcArgv(pid); + if (procArgv) return procArgv; + const result = runtime.run("ps", ["-ww", "-p", String(pid), "-o", "args="], { + env: runtime.env, + }); + const commandLine = result.status === 0 ? result.stdout.trim() : ""; + return commandLine ? commandLine.split(/\s+/u) : null; +} + +function isBedrockLauncherPath(target: string): boolean { + return ( + path.basename(target) === "bedrock-runtime-adapter.mts" || + path.basename(target) === "bedrock-runtime-adapter.js" + ); +} + +function observedScriptPath(argv: readonly string[], expectedPath?: string): string | null { + const candidates = argv.filter((argument) => path.isAbsolute(argument)); + if (expectedPath) { + const expected = canonicalPath(expectedPath); + return candidates.some((candidate) => canonicalPath(candidate) === expected) ? expected : null; + } + const launchers = candidates.filter(isBedrockLauncherPath).map(canonicalPath); + return launchers.length === 1 ? launchers[0]! : null; +} + +function observedExecutablePath( + pid: number, + argv: readonly string[], + runtime: BedrockRuntimeAdapterProcessRuntime, +): string | null { + const injected = runtime.readProcessExecutable?.(pid); + if (injected) return canonicalPath(injected); + try { + return fs.realpathSync.native(`/proc/${String(pid)}/exe`); + } catch { + const first = argv[0]; + return first && path.isAbsolute(first) ? canonicalPath(first) : null; + } +} + +function readProcessEnvironment( + pid: number, + runtime: BedrockRuntimeAdapterProcessRuntime, +): Record | null | undefined { + if (runtime.readProcessEnvironment) return runtime.readProcessEnvironment(pid); + try { + return Object.fromEntries( + fs + .readFileSync(`/proc/${String(pid)}/environ`, "utf8") + .split("\0") + .filter(Boolean) + .map((entry) => { + const separator = entry.indexOf("="); + return [entry.slice(0, separator), entry.slice(separator + 1)]; + }), + ); + } catch { + const result = runtime.run("ps", ["eww", "-p", String(pid), "-o", "command="], { + env: runtime.env, + }); + if (result.status !== 0) return undefined; + const environment: Record = {}; + for (const name of [ + BEDROCK_RUNTIME_ADAPTER_GENERATION_ENV, + "NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_PORT", + ]) { + const match = new RegExp(`(?:^|\\s)${name}=([^\\s]+)(?:\\s|$)`, "u").exec(result.stdout); + if (match?.[1]) environment[name] = match[1]; + } + return environment; + } +} + +function observedProcessOwner( + pid: number, + runtime: BedrockRuntimeAdapterProcessRuntime, +): { uid: number; user: string } | null { + const uidResult = runtime.run("ps", ["-p", String(pid), "-o", "uid="], { env: runtime.env }); + const userResult = runtime.run("ps", ["-p", String(pid), "-o", "user="], { + env: runtime.env, + }); + const uidText = uidResult.status === 0 ? uidResult.stdout.trim() : ""; + const uid = /^[0-9]{1,15}$/u.test(uidText) ? Number(uidText) : Number.NaN; + const user = userResult.status === 0 ? userResult.stdout.trim() : ""; + return Number.isSafeInteger(uid) && uid >= 0 && user ? { uid, user } : null; +} + +export function observeBedrockRuntimeAdapterProcess( + pid: number, + runtime: BedrockRuntimeAdapterProcessRuntime, + expected?: Pick< + BedrockRuntimeAdapterProcessIdentity, + "adapterPort" | "executablePath" | "generation" | "processStart" | "scriptPath" | "uid" | "user" + >, +): ObservedBedrockRuntimeAdapterProcess | null { + if (bedrockRuntimeAdapterProcessPresence(pid, runtime) !== "present") return null; + const readIdentity = runtime.readProcessIdentity ?? readMcpLockProcessIdentity; + const firstIdentity = readIdentity(pid, true); + const argv = readProcessArgv(pid, runtime); + const owner = observedProcessOwner(pid, runtime); + if (!firstIdentity || !argv || !owner) return null; + const scriptPath = observedScriptPath(argv, expected?.scriptPath); + const executablePath = observedExecutablePath(pid, argv, runtime); + const environment = readProcessEnvironment(pid, runtime); + const generation = environment?.[BEDROCK_RUNTIME_ADAPTER_GENERATION_ENV] ?? null; + const portText = environment?.NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_PORT; + const adapterPort = portText && /^[0-9]{1,5}$/u.test(portText) ? Number(portText) : null; + const secondIdentity = readIdentity(pid, true); + if ( + !scriptPath || + !executablePath || + environment === undefined || + secondIdentity !== firstIdentity || + bedrockRuntimeAdapterProcessPresence(pid, runtime) !== "present" + ) { + return null; + } + const observed = { + adapterPort, + executablePath, + generation, + processStart: firstIdentity, + scriptPath, + uid: owner.uid, + user: owner.user, + }; + if (!expected) return observed; + return observed.adapterPort === expected.adapterPort && + observed.executablePath === canonicalPath(expected.executablePath) && + observed.generation === expected.generation && + observed.processStart === expected.processStart && + observed.scriptPath === canonicalPath(expected.scriptPath) && + observed.uid === expected.uid && + observed.user === expected.user + ? observed + : null; +} + +function waitForBedrockRuntimeAdapterExit( + pid: number, + runtime: BedrockRuntimeAdapterProcessRuntime, +): boolean | null { + const deadline = Date.now() + PROCESS_EXIT_TIMEOUT_MS; + while (Date.now() < deadline) { + const presence = bedrockRuntimeAdapterProcessPresence(pid, runtime); + if (presence === "absent") return true; + if (presence === "unknown") return null; + (runtime.sleep ?? sleepForProcessExit)(PROCESS_EXIT_POLL_MS); + } + const presence = bedrockRuntimeAdapterProcessPresence(pid, runtime); + return presence === "unknown" ? null : presence === "absent"; +} + +export function stopExactBedrockRuntimeAdapterProcess( + expected: BedrockRuntimeAdapterProcessIdentity, + runtime: BedrockRuntimeAdapterProcessRuntime, +): BedrockRuntimeAdapterProcessStopResult { + const initialPresence = bedrockRuntimeAdapterProcessPresence(expected.pid, runtime); + if (initialPresence === "absent") return { ok: true, status: "absent" }; + if ( + initialPresence !== "present" || + !observeBedrockRuntimeAdapterProcess(expected.pid, runtime, expected) + ) { + return { ok: false, reason: "authority-drift" }; + } + runtime.kill(expected.pid, "SIGTERM"); + const termExit = waitForBedrockRuntimeAdapterExit(expected.pid, runtime); + if (termExit) return { ok: true, status: "stopped" }; + if (termExit === null || !observeBedrockRuntimeAdapterProcess(expected.pid, runtime, expected)) { + return { ok: false, reason: "authority-drift" }; + } + runtime.kill(expected.pid, "SIGKILL"); + return waitForBedrockRuntimeAdapterExit(expected.pid, runtime) + ? { ok: true, status: "stopped" } + : { ok: false, reason: "unresolved" }; +} + +export function legacyBedrockRuntimeGeneration( + stateText: string, + pid: number, + tokenHash: string, +): string { + return `legacy:${crypto + .createHash("sha256") + .update(stateText) + .update("\0") + .update(String(pid)) + .update("\0") + .update(tokenHash) + .digest("hex")}`; +} + +export function resolveBedrockRuntimeAdapterLifecyclePaths( + home: string, + gatewayPort: number, +): BedrockRuntimeAdapterLifecyclePaths { + if (!isSafePort(gatewayPort)) { + throw new Error("Bedrock Runtime adapter lifecycle gateway port is invalid."); + } + const lifecycleRoot = path.join(home, ".local", "state", "nemoclaw-bedrock-runtime-adapter"); + const directory = path.join(lifecycleRoot, String(gatewayPort)); + const homeIdentity = crypto.createHash("sha256").update(path.resolve(home)).digest("hex"); + const lockRoot = path.join(lifecycleRoot, "locks"); + const lockName = `bedrock-runtime-adapter-${homeIdentity}-${String(gatewayPort)}`; + return { + directory, + journalPath: path.join(directory, "uninstall.json"), + lockName, + lockPath: getMcpLifecycleLockPath(lockName, lockRoot), + lockStateDir: lockRoot, + }; +} + +function ensureOwnedPrivateBedrockRuntimeDirectory(directory: string): void { + ensureLocalAdapterStateDir(directory); + const stat = fs.lstatSync(directory); + const uid = process.getuid?.(); + if (uid !== undefined && stat.uid !== uid) { + throw new Error( + `Refusing to use Bedrock Runtime adapter lifecycle directory owned by another user: ${directory}`, + ); + } +} + +export function readPrivateBedrockRuntimeFile(target: string): string | null { + let descriptor: number | null = null; + try { + const noFollow = fs.constants.O_NOFOLLOW ?? 0; + descriptor = fs.openSync(target, fs.constants.O_RDONLY | noFollow); + const before = fs.fstatSync(descriptor, { bigint: true }); + const linked = fs.lstatSync(target, { bigint: true }); + const uid = process.getuid?.(); + if ( + !before.isFile() || + !linked.isFile() || + linked.isSymbolicLink() || + before.dev !== linked.dev || + before.ino !== linked.ino || + before.nlink !== 1n || + before.size < 1n || + before.size > BigInt(MAX_PRIVATE_FILE_BYTES) || + (before.mode & 0o077n) !== 0n || + (uid !== undefined && before.uid !== BigInt(uid)) + ) { + return null; + } + const buffer = Buffer.alloc(Number(before.size)); + const bytesRead = fs.readSync(descriptor, buffer, 0, buffer.length, 0); + const after = fs.fstatSync(descriptor, { bigint: true }); + const linkedAfter = fs.lstatSync(target, { bigint: true }); + if ( + bytesRead !== buffer.length || + before.dev !== after.dev || + before.ino !== after.ino || + before.size !== after.size || + before.mtimeNs !== after.mtimeNs || + before.ctimeNs !== after.ctimeNs || + before.dev !== linkedAfter.dev || + before.ino !== linkedAfter.ino + ) { + return null; + } + return buffer.toString("utf8"); + } catch { + return null; + } finally { + if (descriptor !== null) fs.closeSync(descriptor); + } +} + +export function readBedrockRuntimeAdapterUninstallJournal( + journalPath: string, +): BedrockRuntimeAdapterUninstallJournal | null { + const raw = readPrivateBedrockRuntimeFile(journalPath); + if (raw === null) return null; + try { + const parsed: unknown = JSON.parse(raw); + return isBedrockRuntimeAdapterUninstallJournal(parsed) ? parsed : null; + } catch { + return null; + } +} + +function fsyncDirectory(directory: string): void { + let descriptor: number | null = null; + try { + descriptor = fs.openSync(directory, fs.constants.O_RDONLY); + fs.fsyncSync(descriptor); + } finally { + if (descriptor !== null) fs.closeSync(descriptor); + } +} + +export function writeDurablePrivateBedrockRuntimeJson(target: string, value: unknown): void { + const directory = path.dirname(target); + ensureOwnedPrivateBedrockRuntimeDirectory(directory); + const temporary = path.join( + directory, + `.${path.basename(target)}.tmp.${String(process.pid)}.${crypto.randomUUID()}`, + ); + let descriptor: number | null = null; + try { + descriptor = fs.openSync( + temporary, + fs.constants.O_WRONLY | + fs.constants.O_CREAT | + fs.constants.O_EXCL | + (fs.constants.O_NOFOLLOW ?? 0), + 0o600, + ); + fs.writeFileSync(descriptor, `${JSON.stringify(value, null, 2)}\n`, "utf8"); + fs.fchmodSync(descriptor, 0o600); + fs.fsyncSync(descriptor); + fs.closeSync(descriptor); + descriptor = null; + fs.renameSync(temporary, target); + fsyncDirectory(directory); + } catch (error) { + try { + fs.unlinkSync(temporary); + } catch { + // The temporary file was never created or was already renamed. + } + throw error; + } finally { + if (descriptor !== null) fs.closeSync(descriptor); + } +} + +export function removeDurableBedrockRuntimeFile(target: string): void { + try { + fs.unlinkSync(target); + fsyncDirectory(path.dirname(target)); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } +} + +export function withBedrockRuntimeAdapterLifecycleLock( + lifecycle: BedrockRuntimeAdapterLifecyclePaths, + operation: () => T & (T extends PromiseLike ? never : unknown), +): T { + ensureOwnedPrivateBedrockRuntimeDirectory(lifecycle.lockStateDir); + return withMcpLifecycleLockSync(lifecycle.lockName, operation, { + stateDir: lifecycle.lockStateDir, + }); +} + +export async function withBedrockRuntimeAdapterLifecycleLockAsync( + lifecycle: BedrockRuntimeAdapterLifecyclePaths, + operation: () => Promise, +): Promise { + ensureOwnedPrivateBedrockRuntimeDirectory(lifecycle.lockStateDir); + return withMcpLifecycleLock(lifecycle.lockName, operation, { + stateDir: lifecycle.lockStateDir, + }); +}