From 2447b71e031ea61ebc1de6e07aacc974fd801216 Mon Sep 17 00:00:00 2001 From: Senthil Ravichandran Date: Fri, 31 Jul 2026 19:19:37 -0700 Subject: [PATCH 1/8] fix(cli): clean up headless gateway fallback Signed-off-by: Senthil Ravichandran --- docs/reference/commands.mdx | 5 +- .../actions/sandbox/destroy-gateway.test.ts | 93 ++++++++++++++++++- src/lib/actions/sandbox/destroy-gateway.ts | 72 +++++++++++++- .../docker-driver-gateway-service.test.ts | 25 +++++ .../onboard/docker-driver-gateway-service.ts | 19 +++- 5 files changed, 206 insertions(+), 8 deletions(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index b3e80cdce8e..607696ae229 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1779,7 +1779,10 @@ NemoClaw preserves the per-gateway PID file and runtime marker so you can inspec Stop only the listener that matches the target gateway, then rerun `destroy` to converge cleanup. When the default-port gateway runs under the packaged OpenShell gateway service, gateway cleanup stops that service before it reaps host processes, so the gateway port is released instead of being rebound by the service manager. The service is stopped, not disabled or removed, and the next onboarding run starts it again. -If the service cannot be stopped, `destroy` exits non-zero after sandbox and registry deletion, prints the status command for the service, and skips gateway and volume removal. +On headless Linux, the packaged service can exist while its `systemd` user manager is unavailable and the gateway runs through the standalone fallback. +For this recognized manager-unavailable failure only, `destroy` stops the exact gateway process recorded in the per-gateway PID file and verifies that the gateway port is free before it continues gateway and shared volume removal. +If the recorded PID does not prove gateway ownership or the port remains occupied, `destroy` exits non-zero and preserves the runtime evidence for inspection. +For any other service stop failure, `destroy` exits non-zero after sandbox and registry deletion, prints the status command for the service, and skips gateway and volume removal. If the OpenShell gateway is unreachable and the sandbox has no managed MCP ownership state, `--force` removes only NemoClaw's local registry entry and local artifacts. Gateway-side deletion remains unconfirmed, shared host-service and gateway teardown are skipped, and the sandbox and retained volume may still exist if the gateway returns. Start the gateway with `$$nemoclaw status` and retry destroy when you need a confirmed deletion. diff --git a/src/lib/actions/sandbox/destroy-gateway.test.ts b/src/lib/actions/sandbox/destroy-gateway.test.ts index 1560ac89951..07523332d1f 100644 --- a/src/lib/actions/sandbox/destroy-gateway.test.ts +++ b/src/lib/actions/sandbox/destroy-gateway.test.ts @@ -47,9 +47,10 @@ function packagedServiceOwner({ }; } -function serviceStopResult(stopped: boolean, reason?: string) { +function serviceStopResult(stopped: boolean, reason?: string, standaloneFallbackAllowed = false) { return { attempted: true, + standaloneFallbackAllowed, manager: "systemd" as const, serviceName: "nemoclaw-openshell-gateway", statusCommand: "systemctl --user status nemoclaw-openshell-gateway", @@ -344,6 +345,96 @@ describe("cleanupGatewayAfterLastSandbox", () => { expect(mocks.dockerRemoveVolumesByPrefix).not.toHaveBeenCalled(); }); + it("stops the recorded standalone gateway when the systemd user manager is unavailable", () => { + vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + vi.spyOn(os, "homedir").mockReturnValue("/home/tester"); + mocks.resolveGatewayTeardownAuthority.mockImplementationOnce(packagedServiceOwner); + mocks.stopHostGatewayProcesses.mockReturnValueOnce({ + ...idleHostReaperResult(), + stopped: [4242], + }); + const clearGatewayRuntimeFiles = vi.fn(); + const isGatewayPortFree = vi.fn(() => true); + const runOpenshell = vi.fn(() => ({ status: 0, stdout: "", stderr: "" })); + + cleanupGatewayAfterLastSandbox("nemoclaw", runOpenshell, { + clearGatewayRuntimeFiles, + isGatewayPortFree, + stopOpenShellGatewayUserService: () => + serviceStopResult( + false, + "systemctl --user stop failed: Failed to connect to bus: No medium found", + true, + ), + }); + + expect(mocks.stopHostGatewayProcesses).toHaveBeenCalledWith( + {}, + expect.objectContaining({ + clearRuntimeFiles: false, + openShellGatewayName: "nemoclaw", + openShellGatewayPort: 8080, + usePgrepFallback: false, + }), + ); + expect(isGatewayPortFree).toHaveBeenCalledWith(8080); + expect(clearGatewayRuntimeFiles).toHaveBeenCalledWith( + "/home/tester/.local/state/nemoclaw/openshell-docker-gateway", + "/home/tester/.local/state/nemoclaw/openshell-docker-gateway/openshell-gateway.pid", + ); + expect(runOpenshell).toHaveBeenCalledWith(["gateway", "remove", "nemoclaw"], { + ignoreError: true, + stdio: ["ignore", "pipe", "pipe"], + }); + }); + + it("fails closed when a headless service stop has no recorded standalone owner", () => { + vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + vi.spyOn(os, "homedir").mockReturnValue("/home/tester"); + mocks.resolveGatewayTeardownAuthority.mockImplementationOnce(packagedServiceOwner); + const isGatewayPortFree = vi.fn(() => true); + const runOpenshell = vi.fn(() => ({ status: 0, stdout: "", stderr: "" })); + + expect(() => + cleanupGatewayAfterLastSandbox("nemoclaw", runOpenshell, { + isGatewayPortFree, + stopOpenShellGatewayUserService: () => + serviceStopResult(false, "Failed to connect to bus: No medium found", true), + }), + ).toThrow(/no recorded standalone gateway process proved ownership/); + expect(isGatewayPortFree).not.toHaveBeenCalled(); + expect(runOpenshell).not.toHaveBeenCalledWith( + ["gateway", "remove", "nemoclaw"], + expect.anything(), + ); + }); + + it("fails closed when the gateway port stays occupied after headless fallback cleanup", () => { + vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + vi.spyOn(os, "homedir").mockReturnValue("/home/tester"); + mocks.resolveGatewayTeardownAuthority.mockImplementationOnce(packagedServiceOwner); + mocks.stopHostGatewayProcesses.mockReturnValueOnce({ + ...idleHostReaperResult(), + stopped: [4242], + }); + const clearGatewayRuntimeFiles = vi.fn(); + const runOpenshell = vi.fn(() => ({ status: 0, stdout: "", stderr: "" })); + + expect(() => + cleanupGatewayAfterLastSandbox("nemoclaw", runOpenshell, { + clearGatewayRuntimeFiles, + isGatewayPortFree: () => false, + stopOpenShellGatewayUserService: () => + serviceStopResult(false, "Failed to connect to bus: No medium found", true), + }), + ).toThrow(/gateway port 8080 remains occupied/); + expect(clearGatewayRuntimeFiles).not.toHaveBeenCalled(); + expect(runOpenshell).not.toHaveBeenCalledWith( + ["gateway", "remove", "nemoclaw"], + expect.anything(), + ); + }); + it("leaves the service manager alone for a standalone NemoClaw gateway (#7904)", () => { vi.spyOn(process, "platform", "get").mockReturnValue("linux"); vi.spyOn(os, "homedir").mockReturnValue("/home/tester"); diff --git a/src/lib/actions/sandbox/destroy-gateway.ts b/src/lib/actions/sandbox/destroy-gateway.ts index dc1823dc724..751d0ac596a 100644 --- a/src/lib/actions/sandbox/destroy-gateway.ts +++ b/src/lib/actions/sandbox/destroy-gateway.ts @@ -1,12 +1,15 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { dockerRemoveVolumesByPrefix } from "../../adapters/docker/volume"; import { OPENSHELL_OPERATION_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; import { DASHBOARD_PORT } from "../../core/ports"; +import { clearDockerDriverGatewayRuntimeMarker } from "../../onboard/docker-driver-gateway-runtime-marker"; import { stopOpenShellGatewayUserService } from "../../onboard/docker-driver-gateway-service"; import { resolveGatewayPortFromName, @@ -28,10 +31,34 @@ export type DestroyRunOpenshell = ( const DASHBOARD_FORWARD_PORT = String(DASHBOARD_PORT); export interface CleanupGatewayDeps { + clearGatewayRuntimeFiles?: (stateDir: string, pidFile: string) => void; + isGatewayPortFree?: (port: number) => boolean; resolveGatewayTeardownAuthority?: GatewayTeardownAuthorityResolver; stopOpenShellGatewayUserService?: typeof stopOpenShellGatewayUserService; } +function isGatewayPortFree(port: number): boolean { + const script = + "const net = require('node:net');" + + "const server = net.createServer();" + + "let done = false;" + + "const finish = (code) => { if (!done) { done = true; process.exit(code); } };" + + "server.once('error', () => finish(1));" + + `server.listen(${String(port)}, '127.0.0.1', () => server.close(() => finish(0)));`; + try { + return ( + spawnSync(process.execPath, ["-e", script], { stdio: "ignore", timeout: 2_000 }).status === 0 + ); + } catch { + return false; + } +} + +function clearGatewayRuntimeFiles(stateDir: string, pidFile: string): void { + fs.rmSync(pidFile, { force: true }); + clearDockerDriverGatewayRuntimeMarker(stateDir); +} + // Compute the Docker-driver gateway state directory that belongs to // `gatewayName`. `stopHostGatewayProcesses` defaults to the bare leaf // `openshell-docker-gateway`, so without this override a destroy of a @@ -107,14 +134,19 @@ export function cleanupGatewayAfterLastSandbox( // ports the live openshell tracks; this catches orphans whose openshell // record was lost across upgrades or failed onboards. stopStaleDashboardListeners(); + let packagedServiceFallbackReason: string | null = null; if (!externallySupervised && owner.source === "packaged-service") { const stopService = deps.stopOpenShellGatewayUserService ?? stopOpenShellGatewayUserService; const serviceStop = stopService(); if (serviceStop.attempted && !serviceStop.stopped) { - throw new Error( - `Failed to stop the packaged OpenShell gateway service '${serviceStop.serviceName}' that owns gateway '${gatewayName}': ${serviceStop.reason}. ` + - `Check: ${serviceStop.statusCommand}. Stop the service, then rerun destroy.`, - ); + if (serviceStop.standaloneFallbackAllowed) { + packagedServiceFallbackReason = serviceStop.reason ?? "user service manager unavailable"; + } else { + throw new Error( + `Failed to stop the packaged OpenShell gateway service '${serviceStop.serviceName}' that owns gateway '${gatewayName}': ${serviceStop.reason}. ` + + `Check: ${serviceStop.statusCommand}. Stop the service, then rerun destroy.`, + ); + } } } if (!externallySupervised && (process.platform === "linux" || process.platform === "darwin")) { @@ -132,6 +164,7 @@ export function cleanupGatewayAfterLastSandbox( openShellGatewayPort?: number; preserveRuntimeFilesOnNonMatching: true; usePgrepFallback: false; + clearRuntimeFiles?: boolean; stateDir?: string; pidFile?: string; } = { @@ -142,6 +175,13 @@ export function cleanupGatewayAfterLastSandbox( stopOptions.pidFile = path.join(perGatewayState.stateDir, "openshell-gateway.pid"); stopOptions.openShellGatewayName = gatewayName; stopOptions.openShellGatewayPort = perGatewayState.port; + if (packagedServiceFallbackReason !== null) { + // A package can be installed even when its user manager is unavailable. + // In that exact start fallback, the standalone launcher wrote this + // per-gateway PID evidence. Preserve it until every later cleanup step + // succeeds so a retry can prove the same ownership again. + stopOptions.clearRuntimeFiles = false; + } const stopResult = stopHostGatewayProcesses({}, stopOptions); const unverifiablePids = [...new Set(stopResult.skippedNonMatchingPids)]; if (unverifiablePids.length > 0) { @@ -159,6 +199,23 @@ export function cleanupGatewayAfterLastSandbox( `Failed to stop the owned host gateway process(es) for '${gatewayName}': ${failedPids.join(", ")}.${remediation}`, ); } + if (packagedServiceFallbackReason !== null) { + const ownedStandalonePidProven = + stopResult.stopped.length > 0 || stopResult.skippedDeadPids.length > 0; + if (!ownedStandalonePidProven) { + throw new Error( + `Failed to stop the packaged OpenShell gateway service for '${gatewayName}' because ${packagedServiceFallbackReason}, and no recorded standalone gateway process proved ownership. ` + + "Restore the user service manager or stop the verified gateway listener, then rerun destroy.", + ); + } + const portFree = deps.isGatewayPortFree ?? isGatewayPortFree; + if (!portFree(perGatewayState.port)) { + throw new Error( + `Refusing cleanup because gateway port ${String(perGatewayState.port)} remains occupied after the recorded standalone gateway process for '${gatewayName}' was stopped. ` + + "Inspect the remaining listener, stop only the matching gateway process, then rerun destroy.", + ); + } + } } /** * SOURCE_OF_TRUTH @@ -206,4 +263,11 @@ export function cleanupGatewayAfterLastSandbox( dockerRemoveVolumesByPrefix(`openshell-cluster-${gatewayName}`, { ignoreError: true, }); + if (packagedServiceFallbackReason !== null) { + const clearRuntimeFiles = deps.clearGatewayRuntimeFiles ?? clearGatewayRuntimeFiles; + clearRuntimeFiles( + perGatewayState.stateDir, + path.join(perGatewayState.stateDir, "openshell-gateway.pid"), + ); + } } diff --git a/src/lib/onboard/docker-driver-gateway-service.test.ts b/src/lib/onboard/docker-driver-gateway-service.test.ts index 0e9b7f66f41..963eb4987ca 100644 --- a/src/lib/onboard/docker-driver-gateway-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-service.test.ts @@ -573,6 +573,7 @@ describe("docker-driver-gateway-service", () => { expect(result).toEqual({ attempted: true, + standaloneFallbackAllowed: false, manager: "systemd", serviceName: "nemoclaw-openshell-gateway", statusCommand: "systemctl --user status nemoclaw-openshell-gateway", @@ -626,6 +627,7 @@ describe("docker-driver-gateway-service", () => { expect(result).toEqual({ attempted: true, + standaloneFallbackAllowed: false, manager: "homebrew", serviceName: "openshell", statusCommand: "brew services info openshell", @@ -674,8 +676,31 @@ describe("docker-driver-gateway-service", () => { ])("reports nothing to stop when %s (#7904)", (_case, opts, reason) => { expect(stopOpenShellGatewayUserService({ commandExists: () => true, ...opts })).toEqual({ attempted: false, + standaloneFallbackAllowed: false, reason, stopped: false, }); }); + + it("allows only an owned standalone fallback when the systemd user manager is unavailable", () => { + const home = "/home/nvidia"; + const servicePath = `${home}/.config/systemd/user/nemoclaw-openshell-gateway.service`; + + const result = stopOpenShellGatewayUserService({ + commandExists: (command) => command === "systemctl", + env: { HOME: home }, + existsSync: (candidate) => candidate === servicePath, + home, + lstatSync: nonSymlinkStat, + platform: "linux", + readFileSync: () => `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}\n`, + spawnSyncImpl: vi.fn(() => spawnResult(1, "Failed to connect to bus: No medium found")), + }); + + expect(result).toMatchObject({ + attempted: true, + standaloneFallbackAllowed: true, + stopped: false, + }); + }); }); diff --git a/src/lib/onboard/docker-driver-gateway-service.ts b/src/lib/onboard/docker-driver-gateway-service.ts index 7e41084336b..e54a30b1ed8 100644 --- a/src/lib/onboard/docker-driver-gateway-service.ts +++ b/src/lib/onboard/docker-driver-gateway-service.ts @@ -50,6 +50,7 @@ export interface OpenShellGatewayUserServiceStartResult { export interface OpenShellGatewayUserServiceStopResult { attempted: boolean; + standaloneFallbackAllowed: boolean; manager?: "homebrew" | "systemd"; reason?: string; serviceName?: string; @@ -666,17 +667,31 @@ export function stopOpenShellGatewayUserService( ): OpenShellGatewayUserServiceStopResult { const platform = opts.platform ?? process.platform; if (platform !== "linux" && platform !== "darwin") { - return { attempted: false, stopped: false, reason: "unsupported platform" }; + return { + attempted: false, + standaloneFallbackAllowed: false, + stopped: false, + reason: "unsupported platform", + }; } const env = opts.env ?? process.env; const home = effectiveHome(opts.home, opts.env); const commandExists = opts.commandExists ?? ((command) => defaultCommandExists(command, env)); const spawnSyncImpl = opts.spawnSyncImpl ?? spawnSync; const service = resolveOpenShellGatewayUserService({ ...opts, env, home }); - if (!service) return { attempted: false, stopped: false, reason: "service not installed" }; + if (!service) { + return { + attempted: false, + standaloneFallbackAllowed: false, + stopped: false, + reason: "service not installed", + }; + } const describe = (stopped: boolean, reason?: string): OpenShellGatewayUserServiceStopResult => ({ attempted: true, + standaloneFallbackAllowed: + !stopped && service.manager === "systemd" && userManagerLooksUnavailable(reason ?? ""), manager: service.manager, serviceName: service.serviceName, statusCommand: service.statusCommand, From 494b2a51bd5a4271ee847d98e7fd758ab332ee17 Mon Sep 17 00:00:00 2001 From: Senthil Ravichandran Date: Fri, 31 Jul 2026 19:31:14 -0700 Subject: [PATCH 2/8] refactor(cli): keep gateway host cleanup in adapter Signed-off-by: Senthil Ravichandran --- src/lib/actions/sandbox/destroy-gateway.ts | 39 +++++--------------- src/lib/onboard/host-gateway-process.test.ts | 34 +++++++++++++++++ src/lib/onboard/host-gateway-process.ts | 32 +++++++++++++--- 3 files changed, 69 insertions(+), 36 deletions(-) diff --git a/src/lib/actions/sandbox/destroy-gateway.ts b/src/lib/actions/sandbox/destroy-gateway.ts index 751d0ac596a..4936649d961 100644 --- a/src/lib/actions/sandbox/destroy-gateway.ts +++ b/src/lib/actions/sandbox/destroy-gateway.ts @@ -1,15 +1,12 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "node:child_process"; -import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { dockerRemoveVolumesByPrefix } from "../../adapters/docker/volume"; import { OPENSHELL_OPERATION_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; import { DASHBOARD_PORT } from "../../core/ports"; -import { clearDockerDriverGatewayRuntimeMarker } from "../../onboard/docker-driver-gateway-runtime-marker"; import { stopOpenShellGatewayUserService } from "../../onboard/docker-driver-gateway-service"; import { resolveGatewayPortFromName, @@ -20,7 +17,11 @@ import { type GatewayTeardownAuthorityResolver, resolveGatewayTeardownAuthority, } from "../../onboard/gateway-teardown-authority"; -import { stopHostGatewayProcesses } from "../../onboard/host-gateway-process"; +import { + clearHostGatewayRuntimeFiles, + isHostPortFree, + stopHostGatewayProcesses, +} from "../../onboard/host-gateway-process"; import { stopStaleDashboardListeners } from "../../onboard/stale-gateway-cleanup"; export type DestroyRunOpenshell = ( @@ -31,34 +32,12 @@ export type DestroyRunOpenshell = ( const DASHBOARD_FORWARD_PORT = String(DASHBOARD_PORT); export interface CleanupGatewayDeps { - clearGatewayRuntimeFiles?: (stateDir: string, pidFile: string) => void; - isGatewayPortFree?: (port: number) => boolean; + clearGatewayRuntimeFiles?: typeof clearHostGatewayRuntimeFiles; + isGatewayPortFree?: typeof isHostPortFree; resolveGatewayTeardownAuthority?: GatewayTeardownAuthorityResolver; stopOpenShellGatewayUserService?: typeof stopOpenShellGatewayUserService; } -function isGatewayPortFree(port: number): boolean { - const script = - "const net = require('node:net');" + - "const server = net.createServer();" + - "let done = false;" + - "const finish = (code) => { if (!done) { done = true; process.exit(code); } };" + - "server.once('error', () => finish(1));" + - `server.listen(${String(port)}, '127.0.0.1', () => server.close(() => finish(0)));`; - try { - return ( - spawnSync(process.execPath, ["-e", script], { stdio: "ignore", timeout: 2_000 }).status === 0 - ); - } catch { - return false; - } -} - -function clearGatewayRuntimeFiles(stateDir: string, pidFile: string): void { - fs.rmSync(pidFile, { force: true }); - clearDockerDriverGatewayRuntimeMarker(stateDir); -} - // Compute the Docker-driver gateway state directory that belongs to // `gatewayName`. `stopHostGatewayProcesses` defaults to the bare leaf // `openshell-docker-gateway`, so without this override a destroy of a @@ -208,7 +187,7 @@ export function cleanupGatewayAfterLastSandbox( "Restore the user service manager or stop the verified gateway listener, then rerun destroy.", ); } - const portFree = deps.isGatewayPortFree ?? isGatewayPortFree; + const portFree = deps.isGatewayPortFree ?? isHostPortFree; if (!portFree(perGatewayState.port)) { throw new Error( `Refusing cleanup because gateway port ${String(perGatewayState.port)} remains occupied after the recorded standalone gateway process for '${gatewayName}' was stopped. ` + @@ -264,7 +243,7 @@ export function cleanupGatewayAfterLastSandbox( ignoreError: true, }); if (packagedServiceFallbackReason !== null) { - const clearRuntimeFiles = deps.clearGatewayRuntimeFiles ?? clearGatewayRuntimeFiles; + const clearRuntimeFiles = deps.clearGatewayRuntimeFiles ?? clearHostGatewayRuntimeFiles; clearRuntimeFiles( perGatewayState.stateDir, path.join(perGatewayState.stateDir, "openshell-gateway.pid"), diff --git a/src/lib/onboard/host-gateway-process.test.ts b/src/lib/onboard/host-gateway-process.test.ts index 29c87ca9ffd..f546950decd 100644 --- a/src/lib/onboard/host-gateway-process.test.ts +++ b/src/lib/onboard/host-gateway-process.test.ts @@ -8,8 +8,10 @@ import path from "node:path"; import { describe, expect, it, vi } from "vitest"; import { + clearHostGatewayRuntimeFiles, HOST_GATEWAY_PGREP_PATTERN, type HostGatewayProcessDeps, + isHostPortFree, type RunResult, stopHostGatewayProcesses, } from "./host-gateway-process"; @@ -66,6 +68,38 @@ function psResponses( ]; } +describe("host gateway cleanup boundaries", () => { + it.each([ + ["free", 0, true], + ["occupied", 1, false], + ["inconclusive", null, false], + ] as const)("reports a host port as %s from the bind probe", (_case, status, expected) => { + const spawnSyncImpl = vi.fn(() => ({ + status, + })) as unknown as typeof import("node:child_process").spawnSync; + + expect(isHostPortFree(8080, spawnSyncImpl)).toBe(expected); + expect(spawnSyncImpl).toHaveBeenCalledWith( + process.execPath, + ["-e", expect.stringContaining("server.listen(8080, '127.0.0.1'")], + { stdio: "ignore", timeout: 2_000 }, + ); + }); + + it("clears the exact gateway PID file and runtime marker", () => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-host-gateway-clear-")); + const pidFile = path.join(stateDir, "openshell-gateway.pid"); + const markerFile = path.join(stateDir, "runtime.json"); + fs.writeFileSync(pidFile, "4242\n"); + fs.writeFileSync(markerFile, "{}\n"); + + clearHostGatewayRuntimeFiles(stateDir, pidFile); + + expect(fs.existsSync(pidFile)).toBe(false); + expect(fs.existsSync(markerFile)).toBe(false); + }); +}); + describe("stopHostGatewayProcesses", () => { it("uses pgrep fallback when the Docker-driver gateway PID file is missing", () => { const exited = new Set(); diff --git a/src/lib/onboard/host-gateway-process.ts b/src/lib/onboard/host-gateway-process.ts index af72f53fdde..9c527ad3582 100644 --- a/src/lib/onboard/host-gateway-process.ts +++ b/src/lib/onboard/host-gateway-process.ts @@ -9,8 +9,8 @@ import path from "node:path"; import { waitUntil } from "../core/wait"; import { clearDockerDriverGatewayRuntimeMarker } from "./docker-driver-gateway-runtime-marker"; import { - hostGatewayCmdlineMatches as sharedHostGatewayCmdlineMatches, type OpenShellGatewayProcessTarget, + hostGatewayCmdlineMatches as sharedHostGatewayCmdlineMatches, } from "./gateway-process-identity"; export interface RunResult { @@ -194,11 +194,31 @@ function waitForExit( ); } -function clearRuntimeFiles(pidFile: string, stateDir: string): void { +export function clearHostGatewayRuntimeFiles(stateDir: string, pidFile: string): void { fs.rmSync(pidFile, { force: true }); clearDockerDriverGatewayRuntimeMarker(stateDir); } +export function isHostPortFree(port: number, spawnSyncImpl: typeof spawnSync = spawnSync): boolean { + const script = + "const net = require('node:net');" + + "const server = net.createServer();" + + "let done = false;" + + "const finish = (code) => { if (!done) { done = true; process.exit(code); } };" + + "server.once('error', () => finish(1));" + + `server.listen(${String(port)}, '127.0.0.1', () => server.close(() => finish(0)));`; + try { + return ( + spawnSyncImpl(process.execPath, ["-e", script], { + stdio: "ignore", + timeout: 2_000, + }).status === 0 + ); + } catch { + return false; + } +} + function addPid(candidates: Map>, pid: number, source: string): void { const sources = candidates.get(pid) ?? new Set(); sources.add(source); @@ -274,7 +294,7 @@ export function stopHostGatewayProcesses( if (pidFromFile !== null) { addPid(candidates, pidFromFile, "pid-file"); } else if (clearRuntimeState && fs.existsSync(pidFile)) { - clearRuntimeFiles(pidFile, stateDir); + clearHostGatewayRuntimeFiles(stateDir, pidFile); } } @@ -313,7 +333,7 @@ export function stopHostGatewayProcesses( if (!pidExists(pid, deps)) { result.skippedDeadPids.push(pid); if (clearRuntimeState && sources.has("pid-file") && !clearedRuntimeFiles) { - clearRuntimeFiles(pidFile, stateDir); + clearHostGatewayRuntimeFiles(stateDir, pidFile); clearedRuntimeFiles = true; } continue; @@ -332,7 +352,7 @@ export function stopHostGatewayProcesses( sources.has("pid-file") && !clearedRuntimeFiles ) { - clearRuntimeFiles(pidFile, stateDir); + clearHostGatewayRuntimeFiles(stateDir, pidFile); clearedRuntimeFiles = true; } continue; @@ -341,7 +361,7 @@ export function stopHostGatewayProcesses( if (tryStopPid(pid, deps, waitOptions) === "stopped") { result.stopped.push(pid); if (clearRuntimeState && !clearedRuntimeFiles) { - clearRuntimeFiles(pidFile, stateDir); + clearHostGatewayRuntimeFiles(stateDir, pidFile); clearedRuntimeFiles = true; } } else { From 5983889d62ad35050984fc3294adbae2d07cac1c Mon Sep 17 00:00:00 2001 From: Senthil Ravichandran Date: Fri, 31 Jul 2026 19:51:17 -0700 Subject: [PATCH 3/8] fix(cli): preserve gateway cleanup evidence --- src/lib/onboard/host-gateway-process.test.ts | 34 +++++++++++++++++--- src/lib/onboard/host-gateway-process.ts | 2 +- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/src/lib/onboard/host-gateway-process.test.ts b/src/lib/onboard/host-gateway-process.test.ts index f546950decd..14b62e2b61f 100644 --- a/src/lib/onboard/host-gateway-process.test.ts +++ b/src/lib/onboard/host-gateway-process.test.ts @@ -87,16 +87,42 @@ describe("host gateway cleanup boundaries", () => { }); it("clears the exact gateway PID file and runtime marker", () => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-host-gateway-clear-")); + try { + const pidFile = path.join(stateDir, "openshell-gateway.pid"); + const markerFile = path.join(stateDir, "runtime.json"); + fs.writeFileSync(pidFile, "4242\n"); + fs.writeFileSync(markerFile, "{}\n"); + + clearHostGatewayRuntimeFiles(stateDir, pidFile); + + expect(fs.existsSync(pidFile)).toBe(false); + expect(fs.existsSync(markerFile)).toBe(false); + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }); + } + }); + + it("preserves the gateway PID file when runtime marker removal fails", () => { const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-host-gateway-clear-")); const pidFile = path.join(stateDir, "openshell-gateway.pid"); const markerFile = path.join(stateDir, "runtime.json"); fs.writeFileSync(pidFile, "4242\n"); fs.writeFileSync(markerFile, "{}\n"); + const rmSync = vi.spyOn(fs, "rmSync").mockImplementation((candidate, options) => { + if (candidate === markerFile) throw new Error("marker cleanup failed"); + return fs.rmSync(candidate, options); + }); - clearHostGatewayRuntimeFiles(stateDir, pidFile); - - expect(fs.existsSync(pidFile)).toBe(false); - expect(fs.existsSync(markerFile)).toBe(false); + try { + expect(() => clearHostGatewayRuntimeFiles(stateDir, pidFile)).toThrow( + "marker cleanup failed", + ); + expect(fs.existsSync(pidFile)).toBe(true); + } finally { + rmSync.mockRestore(); + fs.rmSync(stateDir, { recursive: true, force: true }); + } }); }); diff --git a/src/lib/onboard/host-gateway-process.ts b/src/lib/onboard/host-gateway-process.ts index 9c527ad3582..eada983ec78 100644 --- a/src/lib/onboard/host-gateway-process.ts +++ b/src/lib/onboard/host-gateway-process.ts @@ -195,8 +195,8 @@ function waitForExit( } export function clearHostGatewayRuntimeFiles(stateDir: string, pidFile: string): void { - fs.rmSync(pidFile, { force: true }); clearDockerDriverGatewayRuntimeMarker(stateDir); + fs.rmSync(pidFile, { force: true }); } export function isHostPortFree(port: number, spawnSyncImpl: typeof spawnSync = spawnSync): boolean { From 189016a2a74c96fe06c630efc414cd97e432a258 Mon Sep 17 00:00:00 2001 From: Senthil Ravichandran Date: Fri, 31 Jul 2026 19:53:51 -0700 Subject: [PATCH 4/8] docs(cli): clarify headless cleanup evidence --- docs/reference/commands.mdx | 6 ++++-- src/lib/onboard/docker-driver-gateway-service.test.ts | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 607696ae229..cf0bd97c079 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1780,8 +1780,10 @@ Stop only the listener that matches the target gateway, then rerun `destroy` to When the default-port gateway runs under the packaged OpenShell gateway service, gateway cleanup stops that service before it reaps host processes, so the gateway port is released instead of being rebound by the service manager. The service is stopped, not disabled or removed, and the next onboarding run starts it again. On headless Linux, the packaged service can exist while its `systemd` user manager is unavailable and the gateway runs through the standalone fallback. -For this recognized manager-unavailable failure only, `destroy` stops the exact gateway process recorded in the per-gateway PID file and verifies that the gateway port is free before it continues gateway and shared volume removal. -If the recorded PID does not prove gateway ownership or the port remains occupied, `destroy` exits non-zero and preserves the runtime evidence for inspection. +For this recognized manager-unavailable failure only, `destroy` uses the per-gateway PID file before it continues gateway and shared volume removal. +If the recorded PID is live, its command line must match the exact gateway name and port before `destroy` stops it. +If the recorded process has exited, `destroy` continues only after it verifies that the gateway port is free. +If a live PID does not prove gateway ownership or the port remains occupied, `destroy` exits non-zero and preserves the runtime evidence for inspection. For any other service stop failure, `destroy` exits non-zero after sandbox and registry deletion, prints the status command for the service, and skips gateway and volume removal. If the OpenShell gateway is unreachable and the sandbox has no managed MCP ownership state, `--force` removes only NemoClaw's local registry entry and local artifacts. Gateway-side deletion remains unconfirmed, shared host-service and gateway teardown are skipped, and the sandbox and retained volume may still exist if the gateway returns. diff --git a/src/lib/onboard/docker-driver-gateway-service.test.ts b/src/lib/onboard/docker-driver-gateway-service.test.ts index 963eb4987ca..73be59e947b 100644 --- a/src/lib/onboard/docker-driver-gateway-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-service.test.ts @@ -682,7 +682,7 @@ describe("docker-driver-gateway-service", () => { }); }); - it("allows only an owned standalone fallback when the systemd user manager is unavailable", () => { + it("reports standalone fallback eligibility when the systemd user manager is unavailable", () => { const home = "/home/nvidia"; const servicePath = `${home}/.config/systemd/user/nemoclaw-openshell-gateway.service`; From b9c4a40b274792091d1c5b0f269f08400b7a670c Mon Sep 17 00:00:00 2001 From: Senthil Ravichandran Date: Fri, 31 Jul 2026 19:58:21 -0700 Subject: [PATCH 5/8] fix(cli): block automatic gateway reactivation --- docs/reference/commands.mdx | 2 +- .../actions/sandbox/destroy-gateway.test.ts | 38 +++++++++++++++++++ src/lib/actions/sandbox/destroy-gateway.ts | 3 ++ .../docker-driver-gateway-service.test.ts | 23 +++++++++++ .../onboard/docker-driver-gateway-service.ts | 24 +++++++++++- 5 files changed, 88 insertions(+), 2 deletions(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index cf0bd97c079..4ca95a53561 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1780,7 +1780,7 @@ Stop only the listener that matches the target gateway, then rerun `destroy` to When the default-port gateway runs under the packaged OpenShell gateway service, gateway cleanup stops that service before it reaps host processes, so the gateway port is released instead of being rebound by the service manager. The service is stopped, not disabled or removed, and the next onboarding run starts it again. On headless Linux, the packaged service can exist while its `systemd` user manager is unavailable and the gateway runs through the standalone fallback. -For this recognized manager-unavailable failure only, `destroy` uses the per-gateway PID file before it continues gateway and shared volume removal. +For this recognized manager-unavailable failure only, `destroy` uses the per-gateway PID file when the service is not enabled for automatic activation. If the recorded PID is live, its command line must match the exact gateway name and port before `destroy` stops it. If the recorded process has exited, `destroy` continues only after it verifies that the gateway port is free. If a live PID does not prove gateway ownership or the port remains occupied, `destroy` exits non-zero and preserves the runtime evidence for inspection. diff --git a/src/lib/actions/sandbox/destroy-gateway.test.ts b/src/lib/actions/sandbox/destroy-gateway.test.ts index 07523332d1f..1d72c56cf14 100644 --- a/src/lib/actions/sandbox/destroy-gateway.test.ts +++ b/src/lib/actions/sandbox/destroy-gateway.test.ts @@ -435,6 +435,44 @@ describe("cleanupGatewayAfterLastSandbox", () => { ); }); + it("retries headless fallback cleanup after volume removal fails", () => { + vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + vi.spyOn(os, "homedir").mockReturnValue("/home/tester"); + mocks.resolveGatewayTeardownAuthority.mockImplementation(packagedServiceOwner); + mocks.stopHostGatewayProcesses + .mockReturnValueOnce({ + ...idleHostReaperResult(), + stopped: [4242], + }) + .mockReturnValueOnce({ + ...idleHostReaperResult(), + skippedDeadPids: [4242], + }); + mocks.dockerRemoveVolumesByPrefix.mockImplementationOnce(() => { + throw new Error("injected volume cleanup failure"); + }); + const clearGatewayRuntimeFiles = vi.fn(); + const isGatewayPortFree = vi.fn(() => true); + const runOpenshell = vi.fn(() => ({ status: 0, stdout: "", stderr: "" })); + const deps = { + clearGatewayRuntimeFiles, + isGatewayPortFree, + stopOpenShellGatewayUserService: () => + serviceStopResult(false, "Failed to connect to bus: No medium found", true), + }; + + expect(() => cleanupGatewayAfterLastSandbox("nemoclaw", runOpenshell, deps)).toThrow( + "injected volume cleanup failure", + ); + expect(clearGatewayRuntimeFiles).not.toHaveBeenCalled(); + + expect(() => cleanupGatewayAfterLastSandbox("nemoclaw", runOpenshell, deps)).not.toThrow(); + expect(mocks.stopHostGatewayProcesses).toHaveBeenCalledTimes(2); + expect(isGatewayPortFree).toHaveBeenCalledTimes(2); + expect(clearGatewayRuntimeFiles).toHaveBeenCalledOnce(); + expect(mocks.dockerRemoveVolumesByPrefix).toHaveBeenCalledTimes(2); + }); + it("leaves the service manager alone for a standalone NemoClaw gateway (#7904)", () => { vi.spyOn(process, "platform", "get").mockReturnValue("linux"); vi.spyOn(os, "homedir").mockReturnValue("/home/tester"); diff --git a/src/lib/actions/sandbox/destroy-gateway.ts b/src/lib/actions/sandbox/destroy-gateway.ts index 4936649d961..d51a02f7daf 100644 --- a/src/lib/actions/sandbox/destroy-gateway.ts +++ b/src/lib/actions/sandbox/destroy-gateway.ts @@ -156,6 +156,9 @@ export function cleanupGatewayAfterLastSandbox( stopOptions.openShellGatewayPort = perGatewayState.port; if (packagedServiceFallbackReason !== null) { // A package can be installed even when its user manager is unavailable. + // Destroy cannot repair the missing systemd user session. Remove this + // branch when supported onboarding no longer starts a standalone gateway + // after this service-manager failure. // In that exact start fallback, the standalone launcher wrote this // per-gateway PID evidence. Preserve it until every later cleanup step // succeeds so a retry can prove the same ownership again. diff --git a/src/lib/onboard/docker-driver-gateway-service.test.ts b/src/lib/onboard/docker-driver-gateway-service.test.ts index 73be59e947b..505a2398e33 100644 --- a/src/lib/onboard/docker-driver-gateway-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-service.test.ts @@ -703,4 +703,27 @@ describe("docker-driver-gateway-service", () => { stopped: false, }); }); + + it("refuses standalone fallback when the systemd service can activate automatically", () => { + const home = "/home/nvidia"; + const servicePath = `${home}/.config/systemd/user/nemoclaw-openshell-gateway.service`; + const activationPath = `${home}/.config/systemd/user/default.target.wants/nemoclaw-openshell-gateway.service`; + + const result = stopOpenShellGatewayUserService({ + commandExists: (command) => command === "systemctl", + env: { HOME: home }, + existsSync: (candidate) => candidate === servicePath || candidate === activationPath, + home, + lstatSync: nonSymlinkStat, + platform: "linux", + readFileSync: () => `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}\n`, + spawnSyncImpl: vi.fn(() => spawnResult(1, "Failed to connect to bus: No medium found")), + }); + + expect(result).toMatchObject({ + attempted: true, + standaloneFallbackAllowed: false, + stopped: false, + }); + }); }); diff --git a/src/lib/onboard/docker-driver-gateway-service.ts b/src/lib/onboard/docker-driver-gateway-service.ts index e54a30b1ed8..197855dcd60 100644 --- a/src/lib/onboard/docker-driver-gateway-service.ts +++ b/src/lib/onboard/docker-driver-gateway-service.ts @@ -361,6 +361,24 @@ function userManagerLooksUnavailable(reason: string): boolean { ); } +function hasSystemdUserServiceActivationLink( + service: OpenShellGatewayUserServiceTarget, + home: string, + env: NodeJS.ProcessEnv, + existsSync: typeof fs.existsSync, +): boolean { + if (service.manager !== "systemd") return false; + return existsSync( + path.join( + getOpenShellUserConfigHome(home, env), + "systemd", + "user", + "default.target.wants", + `${service.serviceName}.service`, + ), + ); +} + function parseSystemctlShow(output: string): Record { return Object.fromEntries( output @@ -676,6 +694,7 @@ export function stopOpenShellGatewayUserService( } const env = opts.env ?? process.env; const home = effectiveHome(opts.home, opts.env); + const existsSync = opts.existsSync ?? fs.existsSync; const commandExists = opts.commandExists ?? ((command) => defaultCommandExists(command, env)); const spawnSyncImpl = opts.spawnSyncImpl ?? spawnSync; const service = resolveOpenShellGatewayUserService({ ...opts, env, home }); @@ -691,7 +710,10 @@ export function stopOpenShellGatewayUserService( const describe = (stopped: boolean, reason?: string): OpenShellGatewayUserServiceStopResult => ({ attempted: true, standaloneFallbackAllowed: - !stopped && service.manager === "systemd" && userManagerLooksUnavailable(reason ?? ""), + !stopped && + service.manager === "systemd" && + userManagerLooksUnavailable(reason ?? "") && + !hasSystemdUserServiceActivationLink(service, home, env, existsSync), manager: service.manager, serviceName: service.serviceName, statusCommand: service.statusCommand, From 0ffb711ba15c58098e675b977071bcecb9a59067 Mon Sep 17 00:00:00 2001 From: Senthil Ravichandran Date: Fri, 31 Jul 2026 20:00:53 -0700 Subject: [PATCH 6/8] fix(cli): align headless cleanup diagnostics --- src/lib/actions/sandbox/destroy-gateway.ts | 2 +- src/lib/onboard/docker-driver-gateway-service.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/actions/sandbox/destroy-gateway.ts b/src/lib/actions/sandbox/destroy-gateway.ts index d51a02f7daf..48ce8809bc2 100644 --- a/src/lib/actions/sandbox/destroy-gateway.ts +++ b/src/lib/actions/sandbox/destroy-gateway.ts @@ -193,7 +193,7 @@ export function cleanupGatewayAfterLastSandbox( const portFree = deps.isGatewayPortFree ?? isHostPortFree; if (!portFree(perGatewayState.port)) { throw new Error( - `Refusing cleanup because gateway port ${String(perGatewayState.port)} remains occupied after the recorded standalone gateway process for '${gatewayName}' was stopped. ` + + `Refusing cleanup because gateway port ${String(perGatewayState.port)} remains occupied after the recorded standalone gateway process for '${gatewayName}' exited or was stopped. ` + "Inspect the remaining listener, stop only the matching gateway process, then rerun destroy.", ); } diff --git a/src/lib/onboard/docker-driver-gateway-service.ts b/src/lib/onboard/docker-driver-gateway-service.ts index 197855dcd60..96026ca3bdf 100644 --- a/src/lib/onboard/docker-driver-gateway-service.ts +++ b/src/lib/onboard/docker-driver-gateway-service.ts @@ -365,7 +365,7 @@ function hasSystemdUserServiceActivationLink( service: OpenShellGatewayUserServiceTarget, home: string, env: NodeJS.ProcessEnv, - existsSync: typeof fs.existsSync, + existsSync: (filePath: string) => boolean, ): boolean { if (service.manager !== "systemd") return false; return existsSync( From c462f544b9b4dfe74fca6788d9c3376d670c9ec5 Mon Sep 17 00:00:00 2001 From: Senthil Ravichandran Date: Fri, 31 Jul 2026 20:06:03 -0700 Subject: [PATCH 7/8] test(cli): preserve unrelated gateway state --- src/lib/onboard/host-gateway-process.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/lib/onboard/host-gateway-process.test.ts b/src/lib/onboard/host-gateway-process.test.ts index 14b62e2b61f..02c48d60ef1 100644 --- a/src/lib/onboard/host-gateway-process.test.ts +++ b/src/lib/onboard/host-gateway-process.test.ts @@ -91,13 +91,16 @@ describe("host gateway cleanup boundaries", () => { try { const pidFile = path.join(stateDir, "openshell-gateway.pid"); const markerFile = path.join(stateDir, "runtime.json"); + const unrelatedFile = path.join(stateDir, "unrelated.txt"); fs.writeFileSync(pidFile, "4242\n"); fs.writeFileSync(markerFile, "{}\n"); + fs.writeFileSync(unrelatedFile, "keep\n"); clearHostGatewayRuntimeFiles(stateDir, pidFile); expect(fs.existsSync(pidFile)).toBe(false); expect(fs.existsSync(markerFile)).toBe(false); + expect(fs.existsSync(unrelatedFile)).toBe(true); } finally { fs.rmSync(stateDir, { recursive: true, force: true }); } From c14826163d08d98031a583c49407783355b24592 Mon Sep 17 00:00:00 2001 From: Senthil Ravichandran Date: Fri, 31 Jul 2026 20:11:09 -0700 Subject: [PATCH 8/8] test(cli): keep cleanup failure path linear --- src/lib/onboard/host-gateway-process.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/lib/onboard/host-gateway-process.test.ts b/src/lib/onboard/host-gateway-process.test.ts index 02c48d60ef1..c07b4938548 100644 --- a/src/lib/onboard/host-gateway-process.test.ts +++ b/src/lib/onboard/host-gateway-process.test.ts @@ -112,9 +112,9 @@ describe("host gateway cleanup boundaries", () => { const markerFile = path.join(stateDir, "runtime.json"); fs.writeFileSync(pidFile, "4242\n"); fs.writeFileSync(markerFile, "{}\n"); - const rmSync = vi.spyOn(fs, "rmSync").mockImplementation((candidate, options) => { - if (candidate === markerFile) throw new Error("marker cleanup failed"); - return fs.rmSync(candidate, options); + const rmSync = vi.spyOn(fs, "rmSync").mockImplementation((candidate) => { + expect(candidate).toBe(markerFile); + throw new Error("marker cleanup failed"); }); try {