Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion ci/source-architecture-budget.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"src/lib/cli/terminal-style.ts": 43,
"src/lib/core/json-types.ts": 37,
"src/lib/core/ports.ts": 89,
"src/lib/core/shell-quote.ts": 28,
"src/lib/core/shell-quote.ts": 29,
"src/lib/core/url-utils.ts": 30,
"src/lib/core/wait.ts": 37,
"src/lib/credentials/store.ts": 46,
Expand All @@ -27,6 +27,7 @@
"src/lib/runner.ts": 86,
"src/lib/security/redact.ts": 54,
"src/lib/state/onboard-session.ts": 36,
"src/lib/state/paths.ts": 22,
"src/lib/state/registry.ts": 101,
"src/lib/state/state-root.ts": 21,
"src/lib/subprocess-env.ts": 24,
Expand Down
36 changes: 36 additions & 0 deletions docs/reference/troubleshooting.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -5313,6 +5313,42 @@ An HTTP status of `200` or `401` means the host port forward is reachable.
Any other status, `000`, or connection failure requires fresh diagnostics.
Rerun `$$nemoclaw onboard` and follow the reported `gateway` or `api` failure.

### Onboarding Reports That a Hermes Forward Watcher Is Still Running

The installer starts a background forward watcher after it onboards a Hermes sandbox.
The watcher probes the sandbox's API port every 10 seconds and restarts the port forward when the probe fails.

Onboarding stops the watcher recorded for a sandbox and port before it starts that port's forward.
Sandbox destroy stops every watcher recorded for a sandbox once its delete succeeds or it was already gone; a failed delete leaves the watcher running, because the sandbox is still live and needs its self-healing forward.
Both stop a process only after confirming that it runs as the current user and that its command line is exactly the watcher NemoClaw recorded.

Running `$$nemoclaw onboard` directly on a sandbox that already has a watcher also stops that watcher.
Only the installer plants a replacement; onboarding and destroy never do, including a `destroy` followed by a fresh `onboard`.
The sandbox keeps working, but its forward stops auto-recovering from a dropped listener until you reinstall.

When a watcher survives that check and the forward still fails to open its listener, onboarding names the surviving process:

```text
! Port 8642 forward did not start: local forward listener did not open on 127.0.0.1:8642 within 10000ms
A managed Hermes forward watcher is still running for 'hermes' on port 8642: pid 60642 (/home/user/.nemoclaw/state/hermes-hermes-8642.forward.pid.js). Stop it before retrying.
```

A surviving watcher restarts the same forward while onboarding is establishing it, and each side can stop the other's listener.
Confirm the reported process before you stop it:

```bash
ps -p <pid> -o user=,args=
```

That command reporting your own user and a command line that *contains* the watcher script path from the diagnostic is not enough — NemoClaw only ever names a watcher here after confirming its command line matches exactly (`node <script> <openshell> <port> <sandbox>`), not merely that it contains that script path.
Stop it only when the full command line matches that exact form:

```bash
kill <pid>
```

Then rerun `$$nemoclaw onboard`.

### `docker port` shows no mapping for 8642 even though forwarding works

OpenShell port forwards are host-side relays managed by the OpenShell gateway process, not Docker `-p` publish mappings on the sandbox container.
Expand Down
24 changes: 24 additions & 0 deletions src/lib/actions/sandbox/destroy-flow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,30 @@ describe("destroySandbox flow", () => {
);
});

it("reaps the sandbox's Hermes forward watcher even when state-volume cleanup fails and exits (#10385)", async () => {
// OpenShell has already deleted the sandbox by this point; the watcher
// this call stops is an orphan's, not a live sandbox's self-healing, so
// it must not outlive the confirmed delete just because an unrelated,
// independently-retryable cleanup step failed afterward.
const harness = createDestroyHarness({
agent: "hermes",
openshellDriver: "docker",
workload: managedHermesWorkload,
managedHermesStateVolumeCleanupResult: {
status: "failed",
detail: "volume is still in use",
volumeName: "nemoclaw-hermes-state-v1-alpha",
},
});

await expect(harness.destroySandbox("alpha", { yes: true })).rejects.toThrow("process.exit(1)");

expect(harness.stopHermesForwardWatchersForDestroyedSandboxSpy).toHaveBeenCalledWith("alpha");
expect(
harness.stopHermesForwardWatchersForDestroyedSandboxSpy.mock.invocationCallOrder[0],
).toBeLessThan(harness.removeManagedHermesStateVolumeSpy.mock.invocationCallOrder[0]);
});

it("leaves a foreign same-name Hermes volume untouched and completes registry cleanup", async () => {
const harness = createDestroyHarness({
agent: "hermes",
Expand Down
97 changes: 97 additions & 0 deletions src/lib/actions/sandbox/destroy-hermes-forward-watcher.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import path from "node:path";

import { describe, expect, it, vi } from "vitest";

import type { HermesForwardWatcherHost } from "../../adapters/openshell/hermes-forward-watcher";
import {
createWatcherHost,
managedCommandLine,
seedWatcherPidFile,
stateDirFor,
withTempHome,
} from "../../../../test/helpers/hermes-forward-watcher-test-fixture";
import { cleanupSandboxServices } from "./destroy";

const SANDBOX = "hermes";
const PORT = "8642";

function destroyCleanup(
hermesForwardWatcherHost: HermesForwardWatcherHost,
hermesForwardWatcherStateDir: string,
sandboxConfirmedDestroyed = true,
): void {
cleanupSandboxServices(
SANDBOX,
{ stopHostServices: false, sandboxConfirmedDestroyed },
{
getSandbox: vi.fn(() => null),
googlechatWebhookTunnelPidDir: (servicePidDir: string) =>
path.join(servicePidDir, "googlechat"),
hermesForwardWatcherHost,
hermesForwardWatcherStateDir,
rmSync: vi.fn(),
runOpenshell: vi.fn(() => ({ status: 0 })),
stopAll: vi.fn(),
stopGooglechatWebhookTunnel: vi.fn(() => ""),
unloadOllamaModels: vi.fn(),
},
);
}

describe("destroy reaps the sandbox's Hermes forward watcher (#10385)", () => {
it("stops the owned watcher a destroyed sandbox would otherwise leave running", () => {
withTempHome("destroy-reap", (home) => {
const watcher = seedWatcherPidFile(home, 60643, SANDBOX, PORT);
const { host, killed } = createWatcherHost(home, watcher, { pid: 60643 });

destroyCleanup(host, stateDirFor(home));

expect(killed).toContain(60643);
});
});

it("never signals a foreign-owned process holding the watcher PID file", () => {
withTempHome("destroy-foreign", (home) => {
const watcher = seedWatcherPidFile(home, 70643, SANDBOX, PORT);
const { host, killed } = createWatcherHost(home, watcher, {
owner: "someone-else",
pid: 70643,
});

destroyCleanup(host, stateDirFor(home));

expect(killed).toHaveLength(0);
});
});

it("never signals an unrelated command line reusing the watcher PID", () => {
withTempHome("destroy-unrelated", (home) => {
const watcher = seedWatcherPidFile(home, 71643, SANDBOX, PORT);
const { host, killed } = createWatcherHost(home, watcher, {
commandLine: `/bin/sh -c ${managedCommandLine(watcher)}`,
pid: 71643,
});

destroyCleanup(host, stateDirFor(home));

expect(killed).toHaveLength(0);
});
});

it("never reaps a still-registered sandbox's watcher when the delete was not confirmed", () => {
// A failed delete leaves the sandbox registered and still running; the
// watcher this call would otherwise stop is that live sandbox's own
// forward self-healing, not an orphan's (#10385).
withTempHome("destroy-unconfirmed", (home) => {
const watcher = seedWatcherPidFile(home, 72643, SANDBOX, PORT);
const { host, killed } = createWatcherHost(home, watcher, { pid: 72643 });

destroyCleanup(host, stateDirFor(home), false);

expect(killed).toHaveLength(0);
});
});
});
31 changes: 31 additions & 0 deletions src/lib/actions/sandbox/destroy-preflight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@

import os from "node:os";

import {
defaultHermesForwardWatcherHost,
type HermesForwardWatcherHost,
reapManagedHermesForwardWatchers,
} from "../../adapters/openshell/hermes-forward-watcher";
import { OPENSHELL_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts";
import { withModelRouterPortLifecycleLock } from "../../inference/gateway-route-mutation-lock";
import { DEFAULT_MODEL_ROUTER_PORT, isRoutedInferenceProvider } from "../../onboard/model-router";
Expand All @@ -19,6 +24,7 @@ import type {
releaseOnboardLock,
Session,
} from "../../state/onboard-session";
import { resolveNemoclawStateDir } from "../../state/paths";
import type { SandboxEntry } from "../../state/registry";
import * as registry from "../../state/registry";
import { type DestroyRunOpenshell, selectGatewayForSandboxDestroy } from "./destroy-gateway";
Expand All @@ -33,6 +39,31 @@ export type SandboxDestroyPreflight = {
sandboxConfirmedAbsent: boolean;
};

/**
* Stop the managed Hermes forward watcher `install.sh` planted for this
* sandbox. The watcher restarts the sandbox's API forward every 10 seconds, and
* destroy never reaped it, so a destroyed sandbox left one running against a
* name the next onboard reuses (#10385).
*
* `stateDir` defaults from `resolveNemoclawStateDir()` (test-isolation-aware)
* rather than being resolved from `$HOME` inside the reap call, so a test that
* forgets to inject it reads an empty/wrong directory instead of this
* function silently reading — and, through the reap's signal path,
* potentially killing a process under — the invoking user's real
* `~/.nemoclaw` state.
*/
export function stopHermesForwardWatchersForDestroyedSandbox(
sandboxName: string,
host?: HermesForwardWatcherHost,
stateDir?: string,
): void {
reapManagedHermesForwardWatchers(
stateDir ?? resolveNemoclawStateDir(),
{ sandbox: sandboxName },
host ?? defaultHermesForwardWatcherHost(),
);
}

export function stopSandboxInferenceResources(
sandboxName: string,
sandbox: SandboxEntry | null,
Expand Down
40 changes: 39 additions & 1 deletion src/lib/actions/sandbox/destroy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import fs from "node:fs";
import path from "node:path";

import type { HermesForwardWatcherHost } from "../../adapters/openshell/hermes-forward-watcher";
import { CLI_NAME } from "../../cli/branding";
import { G, R, YW } from "../../cli/terminal-style";
import { isNonInteractiveEnv } from "../../core/non-interactive";
Expand Down Expand Up @@ -59,6 +60,7 @@ import {
} from "./destroy-presence";
import {
prepareSandboxDestroy,
stopHermesForwardWatchersForDestroyedSandbox,
stopModelRouterForDestroyedSandbox,
stopSandboxInferenceResources,
} from "./destroy-preflight";
Expand Down Expand Up @@ -109,6 +111,10 @@ export function requireSandboxDestructiveCleanupAuthority(
type RunOpenshell = (args: string[], opts?: Record<string, unknown>) => { status: number | null };

export type CleanupSandboxServicesDeps = {
/** Process host for the Hermes forward-watcher reap; tests inject a fake process table. */
hermesForwardWatcherHost?: HermesForwardWatcherHost;
/** State directory the watcher reap reads; defaults to `resolveNemoclawStateDir()`. */
hermesForwardWatcherStateDir?: string;
getSandbox?: typeof registry.getSandbox;
stopAll?: (opts: { sandboxName: string }) => void;
unloadOllamaModels?: () => void;
Expand Down Expand Up @@ -156,7 +162,10 @@ async function resolveCleanupGatewayDecision(options: DestroySandboxOptions): Pr

export function cleanupSandboxServices(
sandboxName: string,
{ stopHostServices = false }: { stopHostServices?: boolean } = {},
{
stopHostServices = false,
sandboxConfirmedDestroyed = false,
}: { stopHostServices?: boolean; sandboxConfirmedDestroyed?: boolean } = {},
deps: CleanupSandboxServicesDeps = {},
): void {
// Source boundary: this exported helper can be called independently of CLI
Expand All @@ -168,6 +177,23 @@ export function cleanupSandboxServices(
const validatedSandboxName = validateName(sandboxName, "sandbox name");
const servicesPidDir = path.resolve("/tmp", `nemoclaw-services-${validatedSandboxName}`);
const getSandbox = deps.getSandbox ?? registry.getSandbox;
// Reap only when the caller has confirmed the delete succeeded or the
// sandbox was already gone, not merely because this cleanup pass started: a
// failed delete leaves the sandbox registered and still running, and the
// watcher this call stops is that live sandbox's own forward self-healing
// (#10385). The registry entry itself is not removed until after this
// function returns, so it cannot be used here to infer that; the caller
// passes its own already-computed `deleteSucceededOrAlreadyGone`. The
// watcher restarts this sandbox's forwards every 10 seconds, so once the
// sandbox truly is gone it must not outlive that fact or the tunnel-stop
// failure below.
if (sandboxConfirmedDestroyed) {
stopHermesForwardWatchersForDestroyedSandbox(
validatedSandboxName,
deps.hermesForwardWatcherHost,
deps.hermesForwardWatcherStateDir,
);
}
const stopAll =
deps.stopAll ??
((opts: { sandboxName: string }) => {
Expand Down Expand Up @@ -766,6 +792,17 @@ async function destroySandboxUnlocked(
if (!deleteSucceededOrAlreadyGone) {
preparedManagedLlamaCppCleanup?.abort();
}
// Reap the sandbox's Hermes forward watcher as soon as the delete is
// confirmed, before any later step in this function can exit early: the
// managed Hermes state-volume cleanup below calls
// `requestSandboxDestroyExit(1)` on failure, which throws and unwinds past
// the later `cleanupSandboxServices()` call, leaving the watcher live and
// restarting a forward for a sandbox that OpenShell has already deleted
// (#10385). `cleanupSandboxServices()` still reaps its own gated copy for
// any caller that reaches it independently of this function.
if (deleteSucceededOrAlreadyGone) {
stopHermesForwardWatchersForDestroyedSandbox(sandboxName);
}
if (deleteSucceededOrAlreadyGone && sandbox) {
const stateVolumeCleanup = abortPreparedCleanupOnError(() =>
removeManagedHermesStateVolume({
Expand Down Expand Up @@ -799,6 +836,7 @@ async function destroySandboxUnlocked(
});
cleanupSandboxServices(sandboxName, {
stopHostServices: shouldStopHostServices,
sandboxConfirmedDestroyed: deleteSucceededOrAlreadyGone,
});
});
if (deleteSucceededOrAlreadyGone && commonLlamaCppAuthorityRetired === true) {
Expand Down
7 changes: 5 additions & 2 deletions src/lib/actions/uninstall/hermes-forward-watcher-cleanup.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import path from "node:path";

import {
type HermesForwardWatcherHost,
stopHermesForwardWatcherProcess,
Expand All @@ -12,9 +14,10 @@ export function stopHermesForwardWatchers(
nemoclawStateDir: string,
host: HermesForwardWatcherHost,
): boolean {
const state = readHermesForwardWatcherState(nemoclawStateDir);
const stateDir = path.join(nemoclawStateDir, "state");
const state = readHermesForwardWatcherState(stateDir);
if (!state.readable) {
host.warn(`Failed to inspect Hermes forward watcher state under ${nemoclawStateDir}.`);
host.warn(`Failed to inspect Hermes forward watcher state under ${stateDir}.`);
return false;
}
if (state.watchers.length === 0) {
Expand Down
Loading