diff --git a/docs/deployment/deploy-to-headless-server.mdx b/docs/deployment/deploy-to-headless-server.mdx index bf5983e5241..88f45439e1d 100644 --- a/docs/deployment/deploy-to-headless-server.mdx +++ b/docs/deployment/deploy-to-headless-server.mdx @@ -206,7 +206,9 @@ $$nemoclaw headless-agent status $$nemoclaw headless-agent connect --probe-only ``` -`$$nemoclaw headless-agent status` exits nonzero when the sandbox, gateway, local container, or authoritative inference route is not verified, except for a degraded native NVIDIA result. Its main `Inference` line probes the selected provider path from inside the sandbox. Shared providers use `https://inference.local/v1/models`, then send an inference request over the same route when that probe reports the route reachable. NVIDIA Endpoints, supported fixed hosted providers, new hosted compatible endpoints outside the Personal tier, and qualified new local selections verify the recorded sandbox-attached OpenShell provider with an inference request. A fresh Personal-tier hosted compatible selection verifies the shared route and has no native attachment. Status repeats inference requests up to three total attempts when they return a transient gateway status; refer to the [CLI commands reference](../reference/commands) for the retried statuses and their token cost. The line reports `healthy` when the route served the request, `unauthorized` when the route rejected it with HTTP `401` or `403`, and `unhealthy` after other final failures. A verified native NVIDIA route instead reports `degraded` and exits `0` after a final HTTP `429`, `500`, `502`, `503`, or `504` response or a confirmed request timeout. The model response remains unverified. +On a normal read, `$$nemoclaw headless-agent status` exits nonzero when the sandbox, gateway, local container, or authoritative inference route is not verified, except for a degraded native NVIDIA result. When gateway and sandbox state are verified and probes are not suppressed, its main `Inference` line checks an available selected provider path from inside the sandbox. Shared providers use `https://inference.local/v1/models`, then send an inference request over the same route when that probe reports the route reachable. NVIDIA Endpoints, supported fixed hosted providers, new hosted compatible endpoints outside the Personal tier, and qualified new local selections verify the recorded sandbox-attached OpenShell provider with an inference request. A fresh Personal-tier hosted compatible selection verifies the shared route and has no native attachment. Status repeats inference requests up to three total attempts when they return a transient gateway status; refer to the [CLI commands reference](../reference/commands) for the retried statuses and their token cost. The line reports `healthy` when the route served the request, `unauthorized` when the route rejected it with HTTP `401` or `403`, and `unhealthy` after other final failures. A verified native NVIDIA route instead reports `degraded` and exits `0` after a final HTTP `429`, `500`, `502`, `503`, or `504` response or a confirmed request timeout. The model response remains unverified. + +During an ordinary lifecycle operation, status can return a read-only snapshot only when receipt and registry checks confirm that no Portable authority exists before and after the read. The snapshot shows `Inference: not probed (another lifecycle operation is in progress)`; JSON output sets `inferenceProbeSuppressed: true`. The exit status still reflects the observed sandbox and gateway state and may be nonzero. If Portable authority exists, cannot be checked, or appears during the read, status rejects the snapshot and reports lifecycle contention. A snapshot is not inference or readiness evidence. Wait for the lifecycle operation to finish and rerun status before requiring an unsuppressed `healthy` inference result. diff --git a/docs/inference/set-up-ollama.mdx b/docs/inference/set-up-ollama.mdx index f815893f452..12b01e047b4 100644 --- a/docs/inference/set-up-ollama.mdx +++ b/docs/inference/set-up-ollama.mdx @@ -290,6 +290,8 @@ The host-side proxy liveness check treats any HTTP response, including `401`, as The `status` and `doctor` route probe runs inside the sandbox and reports HTTP `200` through `499` as reachable, HTTP `500` through `599` as `unhealthy`, and transport failures or unavailable probes as `unreachable` or `not probed`. `status` then sends an inference request over the reachable route and reports `healthy` when the route served it, or `unauthorized` when the proxy token is no longer accepted. +These checks apply to a normal status read when gateway and sandbox state are verified. If either state is not verified, status reports `Inference: not verified (gateway/sandbox state not verified)` and sends no inference request. If status reports `Inference: not probed (another lifecycle operation is in progress)`, it skips provider-health and inference-invocation probes but may still observe the shared route. JSON output sets `inferenceProbeSuppressed: true` for that unlocked read. Repeat status after the lifecycle operation completes before using it to verify the route or proxy token. + If Ollama is already bound to a non-loopback address, onboarding restarts it on `127.0.0.1:11434` so the proxy becomes the only network path. ## Allow the Docker Bridge Through a Firewall diff --git a/docs/inference/verify-inference-route.mdx b/docs/inference/verify-inference-route.mdx index 344d58461ae..7f551124c0f 100644 --- a/docs/inference/verify-inference-route.mdx +++ b/docs/inference/verify-inference-route.mdx @@ -34,6 +34,8 @@ Run the named sandbox status command. $$nemoclaw status ``` +The checks below apply to a normal status read when gateway and sandbox state are verified. If either state is not verified, status reports `Inference: not verified (gateway/sandbox state not verified)` and sends no inference request. If status reports `Inference: not probed (another lifecycle operation is in progress)`, it sends no inference request. For shared-route providers, it may still observe the live route without probing its health. JSON output sets `inferenceProbeSuppressed: true` for that unlocked read. Repeat status after the lifecycle operation completes before treating its result as inference evidence. + For NVIDIA Endpoints, the `Inference` row verifies the recorded sandbox attachment. It then sends a native Chat Completions request to `https://integrate.api.nvidia.com/v1`. It does not probe `https://inference.local/v1/models` for this provider. diff --git a/docs/monitoring/monitor-sandbox-activity.mdx b/docs/monitoring/monitor-sandbox-activity.mdx index a0124561494..e42083763f9 100644 --- a/docs/monitoring/monitor-sandbox-activity.mdx +++ b/docs/monitoring/monitor-sandbox-activity.mdx @@ -27,9 +27,11 @@ Run the status command to view sandbox state, gateway health, and the active inf $$nemoclaw status ``` -`$$nemoclaw status` probes the selected provider path from inside the sandbox as the authoritative inference check. Shared providers use `https://inference.local/v1/models`. NVIDIA Endpoints, supported fixed hosted providers, new hosted compatible endpoints outside the Personal tier, and qualified new local selections verify the recorded sandbox-attached OpenShell provider with an inference request to its native endpoint. A fresh Personal-tier hosted compatible selection verifies the shared route and has no native attachment. +On a normal read with verified gateway and sandbox state, `$$nemoclaw status` checks an available selected provider path from inside the sandbox as the authoritative inference check. Shared providers use `https://inference.local/v1/models`. NVIDIA Endpoints, supported fixed hosted providers, new hosted compatible endpoints outside the Personal tier, and qualified new local selections verify the recorded sandbox-attached OpenShell provider with an inference request to its native endpoint. A fresh Personal-tier hosted compatible selection verifies the shared route and has no native attachment. For local Ollama and local vLLM routes, it also prints labeled host-side backend diagnostics that help identify which hop failed. +During ordinary lifecycle contention, status may return a read-only snapshot only when receipt and registry checks confirm that no Portable authority exists before and after the read. The snapshot shows `Inference: not probed (another lifecycle operation is in progress)` and `inferenceProbeSuppressed: true` in JSON. If Portable authority exists, cannot be checked, or appears during the read, status rejects the snapshot and reports lifecycle contention. A snapshot may still observe a shared route, but it does not verify inference health. Wait for the lifecycle operation to finish and rerun status before using the result as inference evidence. + Review these output fields. - Sandbox details show the configured model, provider, GPU mode, and applied policy presets. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 29a91086c24..5b243e0627c 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1845,7 +1845,7 @@ $$nemoclaw my-assistant status --json $$nemoclaw sandbox status my-assistant --json ``` -The command probes the selected provider path from inside the sandbox, and when that probe reports the path reachable it sends an inference request over the same path. NVIDIA Endpoints, supported fixed hosted providers, new hosted compatible selections outside the Personal tier, and qualified new local selections use native endpoints through sandbox-attached OpenShell providers. Owned Local NVIDIA NIM, fresh Personal-tier hosted compatible selections, custom endpoints without an attachment, and retained shared routes use `inference.local`. The inference request verifies the selected provider path, and both checks exercise the path that agent traffic uses. For provider-path results, the main `Inference` line uses these states: +On a normal status read, the command probes the selected provider path from inside the sandbox, and when that probe reports the path reachable it sends an inference request over the same path. NVIDIA Endpoints, supported fixed hosted providers, new hosted compatible selections outside the Personal tier, and qualified new local selections use native endpoints through sandbox-attached OpenShell providers. Owned Local NVIDIA NIM, fresh Personal-tier hosted compatible selections, custom endpoints without an attachment, and retained shared routes use `inference.local`. The inference request verifies the selected provider path, and both checks exercise the path that agent traffic uses. For provider-path results, the main `Inference` line uses these states: | State | Meaning | | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -1858,6 +1858,13 @@ The command probes the selected provider path from inside the sandbox, and when | `not probed` | NemoClaw could not run the authoritative route probe from a reachable sandbox. | | `not verified` | NemoClaw could not verify the sandbox or gateway state, so it skips inference probing. | +When another lifecycle operation is in progress and NemoClaw confirms that no Portable authority exists, status returns a best-effort, read-only snapshot that can show transitional state. +It does not run inference health checks or send an inference request. +It does not repair the gateway, host forward, stop-intent record, or Hermes tool gateway broker. +JSON output sets `inferenceProbeSuppressed` to `true`. +If NemoClaw finds or cannot rule out Portable authority, status fails fast. +If Portable authority appears during the snapshot, status reports a lifecycle conflict after it finishes the snapshot. + An authentication response on a shared gateway route probe confirms that the route is reachable, not that provider credentials are valid. For those shared routes, `$$nemoclaw doctor` sends no inference request, so it reports an HTTP `401` or `403` route response as reachable and exits `0` where `status` reports `unauthorized`. Native hosted and Deep Agents Code, Hermes, and OpenClaw native local doctor checks verify the recorded provider identity and sandbox attachment, then require a successful inference request through the selected native endpoint. The native NVIDIA doctor probe verifies the sandbox-attached provider directly and requires a 2xx response. The command can also print direct host-side provider checks such as `Inference (upstream)` and provider-specific subprobes. For supported remote providers, this diagnostic sends an authenticated request to the configured model and accepts only a recognized Chat Completions, streaming Chat Completions, or Anthropic Messages response. It uses a 3-second connection timeout, a 5-second total timeout, and an 8-token output limit. If that host-side request reaches the time limit, `Inference (upstream)` reports `not probed` and leaves model health unverified. A confirmed timeout of the authoritative native NVIDIA request instead reports `degraded` after bounded retries. Host-side checks are diagnostic only and do not override the authoritative selected-provider result or determine the command exit status. The `Inference (upstream)` check authenticates with the host credential that NemoClaw resolves for the provider, such as `NVIDIA_INFERENCE_API_KEY`. OpenShell stores the credential that the sandbox's selected provider path uses. The CLI cannot read the stored value back, so the two credentials can hold different secrets. When the managed sandbox path has already served the inference request, an `unauthorized` result on `Inference (upstream)` describes the host credential. NemoClaw then reports that check as `not probed` and names both credential sources. An `Inference (upstream)` check that fails for another reason, such as `unreachable`, still reports its own state. Local backend and auth proxy checks, such as `Inference (auth proxy)`, always report their own state and their own repair step. For a shared route, `$$nemoclaw doctor` sends no inference request, so it reports the `Inference (upstream)` state that it measured. @@ -1871,7 +1878,7 @@ When the sandbox's recorded driver is `docker` and the host Docker daemon is not When the host Docker daemon is reachable but the per-sandbox container is stopped without a matching intentional-stop record, the initial preflight records the `sandbox_container_stopped` failure layer and suppresses the host-side `Inference` probe. A matching intentional-stop record instead produces the clean `Stopped` result described above. If the owning OpenShell gateway is healthy but no longer lists the registered sandbox, status preserves the local registration and reports the missing OpenShell state without directly starting, unpausing, renaming, or replacing a container. -If OpenShell already reports the registered Docker-driver sandbox as present and `Ready`, status verifies the OpenClaw gateway and host forward. +When lifecycle locks are available and OpenShell reports the registered Docker-driver sandbox as present and `Ready`, status verifies the OpenClaw gateway and host forward. It recovers either component when the verification reports it absent. When status finds a running sandbox but cannot clear its stale intentional-stop record, it exits non-zero and reports the `stop_intent_update_failed` state. diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index b69c22bf7fa..a4324d0ba7b 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -2104,7 +2104,9 @@ Verify that the inference provider endpoint is reachable from the host. Check th $$nemoclaw status ``` -The main `Inference` line checks the provider path from inside the sandbox and sends an inference request over the path the agent uses. For shared-route providers, including owned Local NVIDIA NIM, `status` probes `https://inference.local/v1/models` before it sends the request through `https://inference.local`. For NVIDIA Endpoints, fixed hosted selections, new hosted compatible selections outside the Personal tier, and qualified new local selections with a recorded native attachment, it verifies that attachment and sends the request to the selected native endpoint; it does not probe `inference.local`. When an inference request returns a transient gateway status, `status` makes up to three request attempts before it reports a failure. Shared-route retries repeat the route probe and request, while native providers retry only the native request. It prints the next attempt and two-second delay to stderr before each retry. Each inference request attempt has a 90-second request timeout. If a verified native NVIDIA attachment returns HTTP `429`, `500`, `502`, `503`, or `504`, or a confirmed timeout after bounded retries, `status` reports `degraded` and exits `0`. The model response remains unverified. Run `$$nemoclaw connect --probe-only` to require a successful inference request before accepting readiness. If the main line shows `unauthorized`, `unhealthy`, `unreachable`, or `not probed`, inspect the labeled diagnostic lines to identify the failing hop. An `unauthorized` line means the route answered but rejected the request, so refresh the provider credential rather than the route. +On a normal status read with verified gateway and sandbox state, the main `Inference` line checks the provider path from inside the sandbox and sends an inference request over the reachable path the agent uses. If gateway or sandbox state is not verified, status reports `Inference: not verified (gateway/sandbox state not verified)` and sends no inference request. For shared-route providers, including owned Local NVIDIA NIM, `status` probes `https://inference.local/v1/models` before it sends the request through `https://inference.local`. For NVIDIA Endpoints, fixed hosted selections, new hosted compatible selections outside the Personal tier, and qualified new local selections with a recorded native attachment, it verifies that attachment and sends the request to the selected native endpoint; it does not probe `inference.local`. When an inference request returns a transient gateway status, `status` makes up to three request attempts before it reports a failure. Shared-route retries repeat the route probe and request, while native providers retry only the native request. It prints the next attempt and two-second delay to stderr before each retry. Each inference request attempt has a 90-second request timeout. If a verified native NVIDIA attachment returns HTTP `429`, `500`, `502`, `503`, or `504`, or a confirmed timeout after bounded retries, `status` reports `degraded` and exits `0`. The model response remains unverified. Run `$$nemoclaw connect --probe-only` to require a successful inference request before accepting readiness. If the main line shows `unauthorized`, `unhealthy`, `unreachable`, or `not probed`, inspect the labeled diagnostic lines to identify the failing hop. An `unauthorized` line means the route answered but rejected the request, so refresh the provider credential rather than the route. + +If status reports `Inference: not probed (another lifecycle operation is in progress)`, the unlocked read skipped provider-path and inference probes; JSON output sets `inferenceProbeSuppressed: true`. Wait for the lifecycle operation to finish and run status again before diagnosing the route or credential. For Hermes native NVIDIA routes, status also checks the managed credential reference in the Hermes configuration. If this check reports an invalid or stale credential, run `$$nemoclaw rebuild --yes` to refresh it. Then rerun `$$nemoclaw status` and confirm inference is healthy. If status reports that the installed image lacks the credential verifier, rebuild to install it, then rerun status. For other unavailable-verification results, follow the printed sandbox health and access recovery guidance. diff --git a/docs/security/credential-rotation.mdx b/docs/security/credential-rotation.mdx index b5f599fb904..7fcac0525cc 100644 --- a/docs/security/credential-rotation.mdx +++ b/docs/security/credential-rotation.mdx @@ -304,7 +304,9 @@ Plan for recreation downtime when automating messaging or web search rotation. `$$nemoclaw credentials list` confirms that a provider exists, but it does not reveal or validate the stored value. `$$nemoclaw status` performs host-side reachability checks without sending cloud API keys, so even an HTTP `401` or `403` can count as reachable there. -`$$nemoclaw status` also sends an inference request through the stored provider credential and reports `unauthorized` when the route rejects it with HTTP `401` or `403`. It does not retry that rejection. +On a normal read with verified gateway and sandbox state, `$$nemoclaw status` checks the provider path and sends an inference request through the stored credential when the path is reachable. It reports `unauthorized` when the route rejects the request with HTTP `401` or `403` and does not retry that rejection. +If gateway or sandbox state is not verified, status reports `Inference: not verified (gateway/sandbox state not verified)` and sends no inference request. +If status reports `Inference: not probed (another lifecycle operation is in progress)`, the credential was not checked; JSON output sets `inferenceProbeSuppressed: true`. Repeat status after the lifecycle operation completes before accepting it as credential evidence. `$$nemoclaw inference get` reports the active route and does not authenticate a model request. Complete a real request through the rotated integration before declaring the rotation successful. diff --git a/src/commands/sandbox/oclif-command-adapters.test.ts b/src/commands/sandbox/oclif-command-adapters.test.ts index b418b871b91..b561c89d1d6 100644 --- a/src/commands/sandbox/oclif-command-adapters.test.ts +++ b/src/commands/sandbox/oclif-command-adapters.test.ts @@ -8,7 +8,10 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import * as portableAgentLifecycle from "../../lib/onboard/experimental/portable-agent-lifecycle"; import * as receiptAuthority from "../../lib/onboard/experimental/hermes-portable-receipt"; +import { isUnlockedSandboxStatusRead } from "../../lib/actions/sandbox/status-snapshot"; import { isMcpLifecycleLockHeld } from "../../lib/state/mcp-lifecycle-lock-acquisition"; +import { portableHostFencePath } from "../../lib/state/portable-uninstall-retirement"; +import { acquireProcessBoundLockAt, releaseProcessBoundLock } from "../../lib/state/registry/lock"; const mocks = vi.hoisted(() => { class SandboxConfigError extends Error { @@ -272,6 +275,49 @@ describe("sandbox oclif command adapters", () => { expect(process.exitCode).toBe(1); }); + it("routes the text status command through the unlocked read during ordinary host contention (#11903)", async () => { + vi.stubEnv("HOME", stateDir); + vi.stubEnv("NEMOCLAW_TEST_BASE_HOME", stateDir); + mocks.showSandboxStatus.mockImplementationOnce(async (name: string) => { + expect(name).toBe("alpha"); + expect(isUnlockedSandboxStatusRead()).toBe(true); + expect(isMcpLifecycleLockHeld(name)).toBe(false); + }); + const fence = acquireProcessBoundLockAt(portableHostFencePath(stateDir)); + try { + await SandboxStatusCommand.run(["alpha"], rootDir); + } finally { + releaseProcessBoundLock(fence); + } + + expect(mocks.showSandboxStatus).toHaveBeenCalledWith("alpha"); + }); + + it("routes the JSON status command through the unlocked read during ordinary host contention (#11903)", async () => { + vi.stubEnv("HOME", stateDir); + vi.stubEnv("NEMOCLAW_TEST_BASE_HOME", stateDir); + mocks.getSandboxStatusReport.mockImplementationOnce(async (name: string) => { + expect(name).toBe("alpha"); + expect(isUnlockedSandboxStatusRead()).toBe(true); + expect(isMcpLifecycleLockHeld(name)).toBe(false); + return { + schemaVersion: 1, + name, + found: true, + gatewayState: "present", + inferenceProbeSuppressed: true, + }; + }); + const fence = acquireProcessBoundLockAt(portableHostFencePath(stateDir)); + try { + await SandboxStatusCommand.run(["alpha", "--json"], rootDir); + } finally { + releaseProcessBoundLock(fence); + } + + expect(mocks.getSandboxStatusReport).toHaveBeenCalledWith("alpha"); + }); + it("keeps policy list pending until the asynchronous action completes", async () => { let finish!: () => void; mocks.listSandboxPolicies.mockImplementationOnce( diff --git a/src/lib/actions/sandbox/status-flow.test.ts b/src/lib/actions/sandbox/status-flow.test.ts index 46691c518db..844c0b29002 100644 --- a/src/lib/actions/sandbox/status-flow.test.ts +++ b/src/lib/actions/sandbox/status-flow.test.ts @@ -8,6 +8,7 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest"; import { + createRealMcpLifecycleLock, createStatusFlowHarness, resetStatusFlowModuleCache, } from "../../../../test/support/status-flow-test-harness"; @@ -77,6 +78,131 @@ describe("showSandboxStatus flow", () => { }, ); + it("skips lifecycle locking and Hermes broker setup for unlocked status (#11903)", async () => { + const withMcpLifecycleLock = vi.fn(async () => { + throw new Error("unlocked status unexpectedly requested the lifecycle lock"); + }); + const harness = createStatusFlowHarness({ + mockHermesToolGatewayBroker: true, + portableDisposition: { kind: "openclaw" }, + sandboxEntry: { agent: "hermes", agentVersion: null, hermesToolGateways: [{}] } as never, + withMcpLifecycleLock, + }); + + await harness.withUnlockedSandboxStatusRead(() => harness.showSandboxStatus("alpha")); + + expect(harness.withMcpLifecycleLockSpy).not.toHaveBeenCalled(); + expect(harness.checkAgentVersionSpy).toHaveBeenCalledWith("alpha", { + forceProbe: false, + skipProbe: true, + }); + expect(harness.ensureHermesToolGatewayBrokerSpy).not.toBeNull(); + expect(harness.ensureHermesToolGatewayBrokerSpy).not.toHaveBeenCalled(); + const output = harness.logSpy.mock.calls.flat().join("\n"); + expect(output).toContain("Inference: not probed (another lifecycle operation is in progress)"); + expect(output).not.toContain("Inference: healthy"); + expect(output).not.toContain("ollama backend"); + }); + + it("skips managed llama.cpp readiness probes for unlocked status (#11903)", async () => { + const harness = createStatusFlowHarness({ portableDisposition: { kind: "openclaw" } }); + harness.inspectManagedLlamaCppStatusSpy.mockReturnValue({ + recipeId: "nemotron-mini", + modelDigest: "sha256:fixture", + imageReference: "nvcr.io/nvidia/llama-cpp:fixture", + endpoint: "https://inference.local/v1", + state: "running", + detail: "exact managed container is running and ready", + }); + + await harness.withUnlockedSandboxStatusRead(() => harness.showSandboxStatus("alpha")); + expect(harness.inspectManagedLlamaCppStatusSpy).not.toHaveBeenCalled(); + + await harness.showSandboxStatus("alpha"); + expect(harness.inspectManagedLlamaCppStatusSpy).toHaveBeenCalledOnce(); + expect(harness.logSpy.mock.calls.flat().join("\n")).toContain("Managed llama.cpp: running"); + }); + + it("reports unverified inference state for unlocked reads when gateway state is unknown (#11903)", async () => { + const harness = createStatusFlowHarness({ + inferenceHealth: null, + lookup: { + state: "gateway_unreachable_after_restart", + output: "Gateway: nemoclaw\nclient error (Connect): Connection refused", + }, + }); + + await expect( + harness.withUnlockedSandboxStatusRead(() => harness.showSandboxStatus("alpha")), + ).rejects.toThrow("process.exit(1)"); + + const output = harness.logSpy.mock.calls.flat().join("\n"); + expect(output).toContain("Inference: not verified (gateway/sandbox state not verified)"); + expect(output).not.toContain( + "Inference: not probed (another lifecycle operation is in progress)", + ); + }); + + it("does not wait on a held MCP lifecycle lock for unlocked text or JSON status (#11903)", async () => { + const withMcpLifecycleLock = createRealMcpLifecycleLock({ + pollIntervalMs: 1, + timeoutMs: 100, + }); + const harness = createStatusFlowHarness({ withMcpLifecycleLock }); + let releaseLock!: () => void; + let markLockHeld!: () => void; + const lockHeld = new Promise((resolve) => { + markLockHeld = resolve; + }); + const hold = new Promise((resolve) => { + releaseLock = resolve; + }); + const heldLock = withMcpLifecycleLock("alpha", async () => { + markLockHeld(); + await hold; + }); + + await lockHeld; + try { + const report = await harness.withUnlockedSandboxStatusRead(async () => { + const json = await harness.getSandboxStatusReport("alpha"); + await harness.showSandboxStatus("alpha"); + return json; + }); + + expect(report).toMatchObject({ + schemaVersion: 1, + name: "alpha", + inferenceProbeSuppressed: true, + }); + expect(harness.withMcpLifecycleLockSpy).not.toHaveBeenCalled(); + } finally { + releaseLock(); + await heldLock; + } + }); + + it("skips lifecycle locking for unlocked JSON status reports (#11903)", async () => { + const withMcpLifecycleLock = vi.fn(async () => { + throw new Error("unlocked JSON status unexpectedly requested the lifecycle lock"); + }); + const harness = createStatusFlowHarness({ + portableDisposition: { kind: "openclaw" }, + withMcpLifecycleLock, + }); + + const report = await harness.withUnlockedSandboxStatusRead(() => + harness.getSandboxStatusReport("alpha"), + ); + + expect(report).toMatchObject({ + schemaVersion: 1, + name: "alpha", + inferenceProbeSuppressed: true, + }); + expect(harness.withMcpLifecycleLockSpy).not.toHaveBeenCalled(); + }); + it("rejects malformed portable receipt authority before status probes (#9203)", async () => { const harness = createStatusFlowHarness({ portableDisposition: new Error("invalid portable lifecycle receipt"), diff --git a/src/lib/actions/sandbox/status-snapshot-recovery.test.ts b/src/lib/actions/sandbox/status-snapshot-recovery.test.ts index 866d63ea01a..43078a8e965 100644 --- a/src/lib/actions/sandbox/status-snapshot-recovery.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-recovery.test.ts @@ -10,7 +10,12 @@ import { describe, expect, it, vi } from "vitest"; import type { SandboxEntry } from "../../state/registry"; import type { SandboxInferenceRouteHealth } from "./inference-route-health"; import type { SandboxStatusPreflightResult } from "./status-preflight"; -import { collectSandboxStatusSnapshot, getSandboxStatusReport } from "./status-snapshot"; +import * as gatewayState from "./gateway-state"; +import { + collectSandboxStatusSnapshot, + getSandboxStatusReport, + withUnlockedSandboxStatusRead, +} from "./status-snapshot"; const sandbox: SandboxEntry = { name: "alpha", @@ -177,6 +182,49 @@ describe("collectSandboxStatusSnapshot Docker recovery", () => { } }); + it("keeps unlocked status observations free of gateway and recovery mutations (#11903)", async () => { + const lookup = { + state: "present" as const, + phase: "Ready", + output: "Phase: Ready", + recoveredSandbox: true, + }; + const reconcile = vi + .spyOn(gatewayState, "getReconciledSandboxGatewayState") + .mockResolvedValue(lookup as never); + const { reconcile: _defaultReconcile, ...baseDeps } = snapshotDeps({ + checked: true, + wasRunning: false, + recovered: true, + forwardRecovered: true, + }); + const recordSandboxStopIntent = vi.fn(() => false); + const deps = { ...baseDeps, recordSandboxStopIntent }; + + try { + await withUnlockedSandboxStatusRead(() => + collectSandboxStatusSnapshot("alpha", { + sandboxEntry: { ...sandbox, stopped: true }, + preflight: clearPreflight, + suppressInferenceProbe: true, + deps, + }), + ); + + expect(reconcile).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ + gatewayRecovery: "observe", + selectOwningGateway: false, + }), + ); + expect(recordSandboxStopIntent).not.toHaveBeenCalled(); + expect(deps.recoverSandboxProcesses).not.toHaveBeenCalled(); + } finally { + reconcile.mockRestore(); + } + }); + it("leaves agent delivery recovery to the native image runtime", async () => { const deps = { ...snapshotDeps({ diff --git a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts index 5d053db356a..4ec078a6490 100644 --- a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts @@ -18,7 +18,11 @@ import { } from "../../inference/llama-cpp/managed-state"; import { HOSTED_NATIVE_PROVIDERS } from "../../inference/native-provider/hosted"; import type { SandboxEntry } from "../../state/registry"; -import { collectSandboxStatusSnapshot, getSandboxStatusReport } from "./status-snapshot"; +import { + collectSandboxStatusSnapshot, + getSandboxStatusReport, + withUnlockedSandboxStatusRead, +} from "./status-snapshot"; const capture = vi.mocked(captureOpenshellForStatus); @@ -580,6 +584,147 @@ describe("collectSandboxStatusSnapshot inference invocation route (#9302)", () = }, ); + const hostedNative = HOSTED_NATIVE_PROVIDERS.find( + (definition) => definition.logicalProvider === "openai-api", + )!; + const unlockedNativeStatusEntries: { label: string; sandbox: SandboxEntry }[] = [ + { + label: "native NVIDIA", + sandbox: { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "nvidia-prod", + model: "nvidia/nemotron-3-super-120b-a12b", + preferredInferenceApi: "openai-completions", + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-123", + }, + } as SandboxEntry, + }, + { + label: "native hosted", + sandbox: { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: hostedNative.logicalProvider, + model: "selected-model", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: hostedNative.profileId, + providerName: hostedNative.providerName, + providerId: "native-provider-id", + }, + } as SandboxEntry, + }, + ]; + + it.each(unlockedNativeStatusEntries)( + "suppresses inference probes for unlocked native $label status (#11903)", + async ({ sandbox }) => { + const verifyNvidia = vi.fn(async () => undefined); + const verifyHosted = vi.fn(async () => undefined); + const providerProbe = vi.fn(() => ({ ok: true, probed: true })); + const gatewayProbe = vi.fn(async () => ({ ok: true, probed: true })); + const invocationProbe = vi.fn(async () => ({ ok: true }) as const); + const snapshot = await withUnlockedSandboxStatusRead(() => + collectSandboxStatusSnapshot("alpha", { + sandboxEntry: sandbox, + preflight: { + failure: null, + failureLayer: null, + suppressInferenceProbe: false, + exitCode: 0, + }, + deps: { + getSandbox: () => sandbox, + listPublishedSandboxesAcrossGatewayRoots: () => [sandbox], + reconcile: async () => ({ + state: "present" as const, + phase: "Ready", + output: "Phase: Ready", + }), + inferenceRouteObserver: { + observeInferenceRoute: async () => { + throw new Error("native status should not observe the shared route"); + }, + }, + probeProviderHealthImpl: providerProbe as never, + probeSandboxInferenceGatewayHealthImpl: gatewayProbe as never, + probeSandboxInferenceInvocationImpl: invocationProbe, + verifyNativeNvidiaProviderAttachmentImpl: verifyNvidia, + verifyNativeHostedProviderAttachmentImpl: verifyHosted, + }, + }), + ); + + expect(verifyNvidia).not.toHaveBeenCalled(); + expect(verifyHosted).not.toHaveBeenCalled(); + expect(providerProbe).not.toHaveBeenCalled(); + expect(gatewayProbe).not.toHaveBeenCalled(); + expect(invocationProbe).not.toHaveBeenCalled(); + expect(snapshot.inferenceHealth).toBeNull(); + }, + ); + + it("suppresses shared-route health and invocation probes for unlocked status (#11903)", async () => { + const sandbox = { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "openai-api", + model: "selected-model", + } as SandboxEntry; + const providerProbe = vi.fn(); + const gatewayProbe = vi.fn(); + const invocationProbe = vi.fn(); + const observeInferenceRoute = vi.fn( + async () => + ({ + ok: true, + value: { + state: "configured", + route: { provider: "openai-api", model: "selected-model" }, + }, + }) as never, + ); + + const snapshot = await withUnlockedSandboxStatusRead(() => + collectSandboxStatusSnapshot("alpha", { + sandboxEntry: sandbox, + preflight: { + failure: null, + failureLayer: null, + suppressInferenceProbe: false, + exitCode: 0, + }, + deps: { + getSandbox: () => sandbox, + listPublishedSandboxesAcrossGatewayRoots: () => [sandbox], + reconcile: async () => ({ + state: "present" as const, + phase: "Ready", + output: "Phase: Ready", + }), + inferenceRouteObserver: { observeInferenceRoute }, + probeProviderHealthImpl: providerProbe, + probeSandboxInferenceGatewayHealthImpl: gatewayProbe, + probeSandboxInferenceInvocationImpl: invocationProbe, + }, + }), + ); + + expect(observeInferenceRoute).toHaveBeenCalledOnce(); + expect(providerProbe).not.toHaveBeenCalled(); + expect(gatewayProbe).not.toHaveBeenCalled(); + expect(invocationProbe).not.toHaveBeenCalled(); + expect(snapshot.inferenceHealth).toBeNull(); + }); + it.each(["malformed", "mismatched", "live identity changed"])( "refuses %s native hosted authority without falling back", async (failure) => { diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index 8244db705bf..23775a9e1f4 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { AsyncLocalStorage } from "node:async_hooks"; import { setTimeout as sleep } from "node:timers/promises"; import type { OpenShellStateRpcIssue } from "../../adapters/openshell/gateway-drift"; @@ -84,6 +85,18 @@ import { type TerminalRuntimeOomProbeResult, } from "./terminal-runtime-health"; +const unlockedStatusRead = new AsyncLocalStorage(); + +/** Run a best-effort status read that may observe transitional ordinary sandbox state. */ +export function withUnlockedSandboxStatusRead(operation: () => Promise | T): Promise | T { + return unlockedStatusRead.run(true, operation); +} + +/** Whether status is running in the best-effort ordinary-host read path. */ +export function isUnlockedSandboxStatusRead(): boolean { + return unlockedStatusRead.getStore() === true; +} + type ProbeProviderHealth = ( provider: string, options?: ProviderHealthProbeOptions, @@ -204,6 +217,8 @@ export interface SandboxStatusReport { portableLifecyclePhase?: "pending" | "configuring" | "active"; gatewayState: string; inferenceHealth: ProviderHealthStatus | null; + /** True when host-fence contention suppresses inference-health and invocation probes. */ + inferenceProbeSuppressed?: boolean; rpcIssue: { kind: "image_drift" | "host_process_drift" | "protobuf_mismatch" } | null; hostGpuDetected: boolean; sandboxGpuEnabled: boolean; @@ -488,9 +503,11 @@ export async function collectSandboxStatusSnapshot( ((name: string) => getReconciledSandboxGatewayState(name, { getState: getSandboxGatewayStateForStatus, - ...(initialPreflight?.intentionalStopConfirmed - ? { gatewayRecovery: "observe" as const } - : {}), + ...(isUnlockedSandboxStatusRead() + ? { gatewayRecovery: "observe" as const, selectOwningGateway: false } + : initialPreflight?.intentionalStopConfirmed + ? { gatewayRecovery: "observe" as const } + : {}), })); let lookup: SandboxGatewayState; try { @@ -503,6 +520,7 @@ export async function collectSandboxStatusSnapshot( }; } if ( + !isUnlockedSandboxStatusRead() && sb?.stopped === true && lookup.state === "present" && (lookup.phase === "Ready" || lookup.phase === "Running") && @@ -530,6 +548,7 @@ export async function collectSandboxStatusSnapshot( !initialPreflight?.intentionalStopConfirmed; let recoveredManagedGateway = false; if ( + !isUnlockedSandboxStatusRead() && lookup.state === "present" && (lookup.recoveredSandbox || managedOpenClawDeliveryMustBeProven) ) { @@ -572,8 +591,9 @@ export async function collectSandboxStatusSnapshot( ) : undefined; const suppressInferenceProbe = - (postRecoveryPreflight ?? initialPreflight)?.suppressInferenceProbe ?? - opts.suppressInferenceProbe === true; + isUnlockedSandboxStatusRead() || + ((postRecoveryPreflight ?? initialPreflight)?.suppressInferenceProbe ?? + opts.suppressInferenceProbe === true); const nativeSelection = readNativeStatusSelection(sb); const { attachment: nativeAttachment, label: nativeLabel } = nativeSelection; let nativeAttachmentFailure = nativeSelection.failure; @@ -629,7 +649,13 @@ export async function collectSandboxStatusSnapshot( // as drift instead of being mislabeled as this sandbox's configuration. const currentModel = sb ? sb.model || "unknown" : (live && live.model) || "unknown"; const currentProvider = sb ? sb.provider || "unknown" : (live && live.provider) || "unknown"; - if (!suppressInferenceProbe && lookup.state === "present" && nativeProvider && sb) { + if ( + !isUnlockedSandboxStatusRead() && + !suppressInferenceProbe && + lookup.state === "present" && + nativeProvider && + sb + ) { const expected = nativeAttachment; if (!gatewayName || !expected) { nativeAttachmentFailure = diff --git a/src/lib/actions/sandbox/status-text.ts b/src/lib/actions/sandbox/status-text.ts index 7c0118ffd20..e7d34c136dd 100644 --- a/src/lib/actions/sandbox/status-text.ts +++ b/src/lib/actions/sandbox/status-text.ts @@ -44,6 +44,8 @@ export interface SandboxStatusTextContext extends Pick< | "servingProcessHealth" > { sandboxName: string; + unlockedStatusRead: boolean; + inferenceProbeSuppressed?: boolean; statusAgent: SandboxStatusAgentInfo; phase: string | null; } @@ -116,15 +118,16 @@ function printServingProcessHealth( } function printInferenceStatus(context: SandboxStatusTextContext): void { - if (context.inferenceHealth) { + if (context.lookup.state !== "present") { + console.log(" Inference: not verified (gateway/sandbox state not verified)"); + } else if (context.inferenceProbeSuppressed) { + console.log(" Inference: not probed (another lifecycle operation is in progress)"); + } else if (context.inferenceHealth) { printInferenceProbeLine(context.inferenceHealth); for (const subprobe of context.inferenceHealth.subprobes ?? []) { printInferenceProbeLine(subprobe); } } - if (context.lookup.state !== "present") { - console.log(" Inference: not verified (gateway/sandbox state not verified)"); - } printServingProcessHealth(context.statusAgent, context.servingProcessHealth); } @@ -237,12 +240,9 @@ async function printAgentVersion( ): Promise { try { const { lookup, sandboxName, statusAgent } = context; - const shouldProbe = shouldProbeSandboxRuntimeVersion( - lookup, - context.phase, - sandbox, - statusAgent.agentRuntime, - ); + const shouldProbe = + !context.unlockedStatusRead && + shouldProbeSandboxRuntimeVersion(lookup, context.phase, sandbox, statusAgent.agentRuntime); const versionCheck = await sandboxVersion.checkAgentVersion(sandboxName, { forceProbe: shouldProbe, skipProbe: !shouldProbe, diff --git a/src/lib/actions/sandbox/status.ts b/src/lib/actions/sandbox/status.ts index 7f5bd59e36b..3c3f922634e 100644 --- a/src/lib/actions/sandbox/status.ts +++ b/src/lib/actions/sandbox/status.ts @@ -27,6 +27,7 @@ import { import { collectSandboxStatusSnapshot, getSandboxStatusReport as getLegacySandboxStatusReport, + isUnlockedSandboxStatusRead, normalizeSandboxStatusHostMounts, resolveSandboxStatusAgent, type SandboxStatusReport, @@ -64,6 +65,15 @@ export { type ServingProcessHealth, } from "./status-snapshot"; +function withStatusLifecycleLock( + sandboxName: string, + operation: () => Promise | T, +): Promise | T { + return isUnlockedSandboxStatusRead() + ? operation() + : withSandboxLifecycleLock(sandboxName, operation); +} + function inspectHermesPortableStatus( sandboxName: string, ): HermesPortableAgentLifecycleAuthority | null { @@ -128,21 +138,23 @@ export async function getSandboxStatusReport( sandboxName: string, deps: Parameters[1] = {}, ): Promise { - return withSandboxLifecycleLock(sandboxName, async () => { + const read = async (): Promise => { const hermesPortable = inspectHermesPortableStatus(sandboxName); - if (hermesPortable) { - return await hermesPortableStatusReport( - sandboxName, - hermesPortable, - deps.getGatewayPresets ?? getGatewayPresets, - ); - } - return getLegacySandboxStatusReport(sandboxName, { getGatewayPresets, ...deps }); - }); + const report = hermesPortable + ? await hermesPortableStatusReport( + sandboxName, + hermesPortable, + deps.getGatewayPresets ?? getGatewayPresets, + ) + : await getLegacySandboxStatusReport(sandboxName, { getGatewayPresets, ...deps }); + return isUnlockedSandboxStatusRead() ? { ...report, inferenceProbeSuppressed: true } : report; + }; + return await withStatusLifecycleLock(sandboxName, read); } function maybeEnsureHermesToolGatewayBroker(sb: registry.SandboxEntry | null): void { if ( + isUnlockedSandboxStatusRead() || !sb || sb.agent !== "hermes" || !Array.isArray(sb.hermesToolGateways) || @@ -158,10 +170,23 @@ function maybeEnsureHermesToolGatewayBroker(sb: registry.SandboxEntry | null): v } } +function getManagedLlamaCppStatusForDisplay( + sandboxName: string, + sandboxEntry: registry.SandboxEntry | null, + unlockedStatusRead: boolean, +) { + if (unlockedStatusRead) return null; + return inspectManagedLlamaCppStatus(sandboxName, { + ...(typeof sandboxEntry?.gatewayPort === "number" + ? { gatewayPort: sandboxEntry.gatewayPort } + : {}), + }); +} + export async function showSandboxStatus(sandboxName: string): Promise { let deferredExitCode: number | null = null; try { - await withSandboxLifecycleLock(sandboxName, async () => { + const read = async () => { const hermesPortable = inspectHermesPortableStatus(sandboxName); if (hermesPortable) { console.log(` Sandbox: ${sandboxName}`); @@ -171,7 +196,8 @@ export async function showSandboxStatus(sandboxName: string): Promise { return; } await showLegacySandboxStatus(sandboxName); - }); + }; + await withStatusLifecycleLock(sandboxName, read); } catch (error) { if (!isSandboxLifecycleDeferredExit(error)) throw error; deferredExitCode = error.exitCode; @@ -230,8 +256,11 @@ async function showLegacySandboxStatus(sandboxName: string): Promise { }); deferSandboxLifecycleExit(1); } + const unlockedStatusRead = isUnlockedSandboxStatusRead(); const textContext: SandboxStatusTextContext = { sandboxName, + unlockedStatusRead, + inferenceProbeSuppressed: unlockedStatusRead, sb, lookup, currentModel, @@ -267,9 +296,7 @@ async function showLegacySandboxStatus(sandboxName: string): Promise { printDockerHealth(dockerRuntime); printNimStatus(sandboxName, sb); - const managedLlamaCpp = inspectManagedLlamaCppStatus(sandboxName, { - ...(typeof sb?.gatewayPort === "number" ? { gatewayPort: sb.gatewayPort } : {}), - }); + const managedLlamaCpp = getManagedLlamaCppStatusForDisplay(sandboxName, sb, unlockedStatusRead); if (managedLlamaCpp) { console.log(` Managed llama.cpp: ${managedLlamaCpp.state}`); console.log(` Recipe: ${managedLlamaCpp.recipeId}`); diff --git a/src/lib/cli/nemoclaw-oclif-command.test.ts b/src/lib/cli/nemoclaw-oclif-command.test.ts index 1845e55c5fd..0cb3b0394c0 100644 --- a/src/lib/cli/nemoclaw-oclif-command.test.ts +++ b/src/lib/cli/nemoclaw-oclif-command.test.ts @@ -10,7 +10,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { launchSandbox } from "../actions/sandbox/launch"; import * as portableAgentLifecycle from "../onboard/experimental/portable-agent-lifecycle"; import * as receiptAuthority from "../onboard/experimental/hermes-portable-receipt"; +import { portableDemoReceiptPath } from "../onboard/experimental/portable-runtime-receipt-readiness"; import * as portableHostAuthority from "../state/portable-uninstall-retirement"; +import * as registryCrossPort from "../state/registry/cross-port"; +import { isUnlockedSandboxStatusRead } from "../actions/sandbox/status-snapshot"; +import { acquireProcessBoundLockAt, releaseProcessBoundLock } from "../state/registry/lock"; import { isMcpLifecycleLockHeld, withMcpLifecycleLock, @@ -89,6 +93,16 @@ class ParsedUnsupportedSandboxCommand extends NemoClawCommand { } } +class GlobalStatusReadCommand extends NemoClawCommand { + static id = "status"; + static flags = {}; + static operation: () => Promise = async () => undefined; + + public async run(): Promise { + await GlobalStatusReadCommand.operation(); + } +} + class ParsedSupportedSandboxCommand extends NemoClawCommand { static id = "sandbox:status"; static args = { sandboxName: Args.string({ required: true }) }; @@ -217,6 +231,35 @@ function useHermesPortableAuthority(): void { }); } +function writeOpenClawPortableReceipt(stateDir: string, sandboxName: string): void { + const uid = process.getuid?.() ?? 1001; + const homeDir = process.env.HOME || os.homedir(); + const receiptPath = portableDemoReceiptPath(sandboxName, stateDir); + fs.mkdirSync(path.dirname(receiptPath), { recursive: true, mode: 0o700 }); + fs.writeFileSync( + receiptPath, + `${JSON.stringify({ + schemaVersion: 4, + sandboxName, + sandboxId: `sandbox-${sandboxName}`, + containerId: "a".repeat(64), + dashboardPort: 18789, + registryGeneration: `generation-${sandboxName}`, + runtimeAuthority: { + schemaVersion: 1, + kind: "podman", + ownership: "current-user", + uid, + homeDir, + configHome: path.join(homeDir, ".config"), + runtimeDir: `/run/user/${String(uid)}`, + socketPath: `/run/user/${String(uid)}/podman/podman.sock`, + }, + })}\n`, + { mode: 0o600 }, + ); +} + function makeCommand(): TestCommand { return Object.create(TestCommand.prototype) as TestCommand; } @@ -241,6 +284,7 @@ describe("NemoClawCommand", () => { RawSandboxDoctorCommand.ran = false; ParsedUnsupportedSandboxCommand.ran = false; ParsedSupportedSandboxCommand.operation = async () => undefined; + GlobalStatusReadCommand.operation = async () => undefined; GlobalUnsupportedMutationCommand.ran = false; GlobalUseMutationCommand.ran = false; ProbeOnlyConnectCommand.operation = async () => undefined; @@ -250,6 +294,192 @@ describe("NemoClawCommand", () => { PortableStopCommand.observed = { host: false, lifecycle: false, portableLifecycle: false }; }); + it("runs sandbox status without either lifecycle fence during ordinary-host contention (#11903)", async () => { + const fence = acquireProcessBoundLockAt(portableHostAuthority.portableHostFencePath(stateDir)); + const operation = vi.fn(async () => { + expect(fs.existsSync(portableHostAuthority.portableHostFencePath(stateDir))).toBe(true); + expect(isMcpLifecycleLockHeld("alpha")).toBe(false); + expect(isUnlockedSandboxStatusRead()).toBe(true); + }); + ParsedSupportedSandboxCommand.operation = operation; + try { + await expect( + ParsedSupportedSandboxCommand.run(["alpha"], process.cwd()), + ).resolves.toBeUndefined(); + expect(operation).toHaveBeenCalledOnce(); + } finally { + releaseProcessBoundLock(fence); + } + }); + + it("rejects an unlocked status read if portable authority appears before it completes (#11903)", async () => { + const fence = acquireProcessBoundLockAt(portableHostAuthority.portableHostFencePath(stateDir)); + const authorityDirectory = path.join(stateDir, "hermes-portable-lifecycle"); + const operation = vi.fn(async () => { + fs.mkdirSync(authorityDirectory, { mode: 0o700 }); + fs.writeFileSync(path.join(authorityDirectory, "receipt.json"), "authority\n"); + }); + ParsedSupportedSandboxCommand.operation = operation; + try { + await expect(ParsedSupportedSandboxCommand.run(["alpha"], process.cwd())).rejects.toThrow( + "Another NemoClaw lifecycle operation is in progress on this host.", + ); + expect(operation).toHaveBeenCalledOnce(); + } finally { + releaseProcessBoundLock(fence); + } + }); + + it("rejects a read if OpenClaw Portable authority for another sandbox appears during it (#11903)", async () => { + const fence = acquireProcessBoundLockAt(portableHostAuthority.portableHostFencePath(stateDir)); + const operation = vi.fn(async () => { + writeOpenClawPortableReceipt( + portableHostAuthority.defaultPortableStateDir(process.env), + "beta", + ); + }); + ParsedSupportedSandboxCommand.operation = operation; + try { + await expect(ParsedSupportedSandboxCommand.run(["alpha"], process.cwd())).rejects.toThrow( + "Another NemoClaw lifecycle operation is in progress on this host.", + ); + expect(operation).toHaveBeenCalledOnce(); + } finally { + releaseProcessBoundLock(fence); + } + }); + + it("fails fast rather than bypassing portable authority during status contention (#11903)", async () => { + const authorityDirectory = path.join(stateDir, "hermes-portable-lifecycle"); + fs.mkdirSync(authorityDirectory, { mode: 0o700 }); + fs.writeFileSync(path.join(authorityDirectory, "receipt.json"), "authority\n"); + vi.spyOn(portableHostAuthority, "withCurrentPortableHostFenceTry").mockRejectedValue( + new Error(portableHostAuthority.PORTABLE_HOST_FENCE_BUSY_MESSAGE), + ); + const operation = vi.fn(async () => undefined); + ParsedSupportedSandboxCommand.operation = operation; + + await expect(ParsedSupportedSandboxCommand.run(["alpha"], process.cwd())).rejects.toThrow( + "Another NemoClaw lifecycle operation is in progress on this host.", + ); + expect(operation).not.toHaveBeenCalled(); + expect(portableHostAuthority.withCurrentPortableHostFenceTry).toHaveBeenCalledOnce(); + }); + + it("permits unlocked status with an ordinary Docker Hermes lifecycle generation (#11903)", async () => { + vi.spyOn(portableHostAuthority, "withCurrentPortableHostFenceTry").mockRejectedValue( + new Error(portableHostAuthority.PORTABLE_HOST_FENCE_BUSY_MESSAGE), + ); + vi.spyOn(registryCrossPort, "listInferenceRouteOwnersAcrossGatewayRoots").mockReturnValue([ + { + name: "beta", + agent: "hermes", + openshellDriver: "docker", + lifecycleGeneration: "generation-1", + } as never, + ]); + const operation = vi.fn(async () => { + expect(isUnlockedSandboxStatusRead()).toBe(true); + }); + ParsedSupportedSandboxCommand.operation = operation; + + await expect( + ParsedSupportedSandboxCommand.run(["alpha"], process.cwd()), + ).resolves.toBeUndefined(); + expect(operation).toHaveBeenCalledOnce(); + }); + + it("rejects an unlocked status read when Hermes Portable profile appears during it (#11903)", async () => { + const fence = acquireProcessBoundLockAt(portableHostAuthority.portableHostFencePath(stateDir)); + let registryReads = 0; + vi.spyOn(registryCrossPort, "listInferenceRouteOwnersAcrossGatewayRoots").mockImplementation( + () => { + registryReads += 1; + return registryReads < 3 + ? [] + : [ + { + name: "beta", + agent: "hermes", + openshellDriver: "docker", + lifecycleGeneration: "generation-1", + portableLifecycleProfile: "hermes", + } as never, + ]; + }, + ); + const operation = vi.fn(async () => undefined); + ParsedSupportedSandboxCommand.operation = operation; + try { + await expect(ParsedSupportedSandboxCommand.run(["alpha"], process.cwd())).rejects.toThrow( + "Another NemoClaw lifecycle operation is in progress on this host.", + ); + expect(operation).toHaveBeenCalledOnce(); + expect(registryReads).toBe(3); + } finally { + releaseProcessBoundLock(fence); + } + }); + + it("fails closed on Portable registry authority for another sandbox (#11903)", async () => { + vi.spyOn(portableHostAuthority, "withCurrentPortableHostFenceTry").mockRejectedValue( + new Error(portableHostAuthority.PORTABLE_HOST_FENCE_BUSY_MESSAGE), + ); + vi.spyOn(registryCrossPort, "listInferenceRouteOwnersAcrossGatewayRoots").mockReturnValue([ + { name: "beta", portableLifecycleProfile: "openclaw" } as never, + ]); + const operation = vi.fn(async () => undefined); + ParsedSupportedSandboxCommand.operation = operation; + + await expect(ParsedSupportedSandboxCommand.run(["alpha"], process.cwd())).rejects.toThrow( + "Another NemoClaw lifecycle operation is in progress on this host.", + ); + expect(operation).not.toHaveBeenCalled(); + }); + + it("fails closed on an OpenClaw Portable receipt for another sandbox (#11903)", async () => { + writeOpenClawPortableReceipt( + portableHostAuthority.defaultPortableStateDir(process.env), + "beta", + ); + vi.spyOn(portableHostAuthority, "withCurrentPortableHostFenceTry").mockRejectedValue( + new Error(portableHostAuthority.PORTABLE_HOST_FENCE_BUSY_MESSAGE), + ); + const operation = vi.fn(async () => undefined); + ParsedSupportedSandboxCommand.operation = operation; + + await expect(ParsedSupportedSandboxCommand.run(["alpha"], process.cwd())).rejects.toThrow( + "Another NemoClaw lifecycle operation is in progress on this host.", + ); + expect(operation).not.toHaveBeenCalled(); + }); + + it("waits for the host fence before running global status", async () => { + let releaseFence!: () => void; + const fenceReady = new Promise((resolve) => { + releaseFence = resolve; + }); + const withFence = vi + .spyOn(portableHostAuthority, "withCurrentPortableHostFence") + .mockImplementation(async (operation) => { + await fenceReady; + return await operation(); + }); + const operation = vi.fn(async () => undefined); + GlobalStatusReadCommand.operation = operation; + + const status = GlobalStatusReadCommand.run([], process.cwd()); + try { + await vi.waitFor(() => expect(withFence).toHaveBeenCalledOnce()); + expect(operation).not.toHaveBeenCalled(); + releaseFence(); + await expect(status).resolves.toBeUndefined(); + expect(operation).toHaveBeenCalledOnce(); + } finally { + releaseFence(); + } + }); + it("records status-like command results without throwing", () => { makeCommand().apply({ status: 7 }); diff --git a/src/lib/cli/nemoclaw-oclif-command.ts b/src/lib/cli/nemoclaw-oclif-command.ts index 4074969ec5f..24618f4144c 100644 --- a/src/lib/cli/nemoclaw-oclif-command.ts +++ b/src/lib/cli/nemoclaw-oclif-command.ts @@ -2,6 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 import { Command, Flags, type Interfaces } from "@oclif/core"; +import os from "node:os"; +import path from "node:path"; import { assertHermesPortableCommandSupported, assertHermesPortableCommandUnavailable, @@ -9,13 +11,24 @@ import { HERMES_PORTABLE_UNSUPPORTED_COMMAND_MESSAGE, HERMES_PORTABLE_UNSUPPORTED_DOCTOR_FIX_MESSAGE, } from "../onboard/experimental/portable-agent-lifecycle"; -import { defaultPortableDemoStateDir } from "../onboard/experimental/portable-runtime-receipt-readiness"; +import { HERMES_PORTABLE_RECEIPT_DIRECTORY } from "../onboard/experimental/hermes-portable-receipt"; +import { + defaultPortableDemoStateDir, + portableDemoReceiptDirectory, +} from "../onboard/experimental/portable-runtime-receipt-readiness"; import { redactForLog } from "../security/redact"; import { assertNoHermesPortableHostAuthority, + PORTABLE_HOST_FENCE_BUSY_MESSAGE, + readPortableAuthorityDirectory, + samePortableAuthorityDirectory, + type PortableAuthorityDirectorySnapshot, withCurrentPortableHostFence, + withCurrentPortableHostFenceTry, } from "../state/portable-uninstall-retirement"; import { withSandboxLifecycleLock } from "../actions/sandbox/lifecycle/lock"; +import { withUnlockedSandboxStatusRead } from "../actions/sandbox/status-snapshot"; +import { listInferenceRouteOwnersAcrossGatewayRoots } from "../state/registry/cross-port"; import { enforceRemovedImmutabilityMigrationBoundary, reportRemovedImmutabilityUpgrade, @@ -79,6 +92,58 @@ const REMOVED_IMMUTABILITY_REMEDIATION_COMMANDS = new Set([ "sandbox:stop", ]); +function hasPortableRegistryAuthorityOnHost(): boolean { + return listInferenceRouteOwnersAcrossGatewayRoots(process.env.HOME || os.homedir()).some( + (entry) => entry.portableLifecycleProfile !== undefined, + ); +} + +type PortableAuthorityDirectories = { + readonly hermes: PortableAuthorityDirectorySnapshot; + readonly openclaw: PortableAuthorityDirectorySnapshot; +}; + +function readPortableAuthorityDirectories(stateDir: string): PortableAuthorityDirectories { + return { + hermes: readPortableAuthorityDirectory( + path.join(stateDir, HERMES_PORTABLE_RECEIPT_DIRECTORY), + false, + ), + openclaw: readPortableAuthorityDirectory(portableDemoReceiptDirectory(stateDir), false), + }; +} + +function hasPortableReceiptAuthority(directories: PortableAuthorityDirectories): boolean { + return directories.hermes.entries.length > 0 || directories.openclaw.entries.length > 0; +} + +function samePortableAuthorityDirectories( + left: PortableAuthorityDirectories, + right: PortableAuthorityDirectories, +): boolean { + return ( + samePortableAuthorityDirectory(left.hermes, right.hermes) && + samePortableAuthorityDirectory(left.openclaw, right.openclaw) + ); +} + +function canUseUnlockedSandboxStatusRead(): boolean { + const stateDir = defaultPortableDemoStateDir(process.env); + try { + const before = readPortableAuthorityDirectories(stateDir); + if (hasPortableReceiptAuthority(before) || hasPortableRegistryAuthorityOnHost()) return false; + + const after = readPortableAuthorityDirectories(stateDir); + return ( + !hasPortableReceiptAuthority(after) && + samePortableAuthorityDirectories(before, after) && + !hasPortableRegistryAuthorityOnHost() + ); + } catch { + return false; + } +} + /** * Shared oclif base for NemoClaw commands. * @@ -183,6 +248,39 @@ export abstract class NemoClawCommand extends Command { } return super._run(); }; + if (commandId === "sandbox:status") { + let fencedOperationStarted = false; + try { + return await withCurrentPortableHostFenceTry(() => { + fencedOperationStarted = true; + return withSandboxLifecycleLock(sandboxName, runLocked); + }); + } catch (error) { + if ( + fencedOperationStarted || + !(error instanceof Error) || + error.message !== PORTABLE_HOST_FENCE_BUSY_MESSAGE + ) { + throw error; + } + if (!canUseUnlockedSandboxStatusRead()) { + throw new Error( + "Another NemoClaw lifecycle operation is in progress on this host. Wait for it to finish, then retry status.", + { cause: error }, + ); + } + return await withUnlockedSandboxStatusRead(async () => { + const result = await runLocked(); + if (!canUseUnlockedSandboxStatusRead()) { + throw new Error( + "Another NemoClaw lifecycle operation is in progress on this host. Wait for it to finish, then retry status.", + { cause: error }, + ); + } + return result; + }); + } + } return await withSandboxLifecycleLock(sandboxName, runLocked); } diff --git a/src/lib/state/portable-uninstall-retirement.ts b/src/lib/state/portable-uninstall-retirement.ts index e1b8612850b..513f606c17e 100644 --- a/src/lib/state/portable-uninstall-retirement.ts +++ b/src/lib/state/portable-uninstall-retirement.ts @@ -106,6 +106,8 @@ const tails = new Map>(); export const portableHostFencePath = (homeDir: string): string => path.join(homeDir, ".nemoclaw-portable-host.lock"); +export const PORTABLE_HOST_FENCE_BUSY_MESSAGE = + "Host maintenance is in progress. Retry this command after it completes."; /** Require the current asynchronous operation to own the exact Portable host fence. */ export function assertCurrentPortableHostFenceHeld(homeDir: string): void { @@ -243,7 +245,7 @@ export async function withPortableHostFenceTry( } } if (tails.has(lockPath)) { - throw new Error("Host maintenance is in progress. Retry this command after it completes."); + throw new Error(PORTABLE_HOST_FENCE_BUSY_MESSAGE); } let finish!: () => void; @@ -254,7 +256,7 @@ export async function withPortableHostFenceTry( try { const handle = tryAcquireProcessBoundLockAt(lockPath); if (!handle) { - throw new Error("Host maintenance is in progress. Retry this command after it completes."); + throw new Error(PORTABLE_HOST_FENCE_BUSY_MESSAGE); } let resolveDrained!: () => void; const drained = new Promise((resolve) => (resolveDrained = resolve)); diff --git a/test/support/status-flow-test-harness.ts b/test/support/status-flow-test-harness.ts index 7f00f0e97ec..081d2d065fd 100644 --- a/test/support/status-flow-test-harness.ts +++ b/test/support/status-flow-test-harness.ts @@ -14,6 +14,7 @@ import type { import type { LlamaCppRouteDetails } from "../../src/lib/inference/config"; import type { ProviderHealthStatus } from "../../src/lib/inference/health"; import type { SandboxHostMount } from "../../src/lib/state/registry"; +import type { McpLifecycleLockOptions } from "../../src/lib/state/mcp-lifecycle-lock-acquisition"; type ShowSandboxStatus = (typeof import("../../src/lib/actions/sandbox/status"))["showSandboxStatus"]; @@ -24,6 +25,8 @@ type PortableAgentReceiptDisposition = ReturnType< >; type WithMcpLifecycleLock = (typeof import("../../src/lib/state/mcp-lifecycle-lock-acquisition"))["withMcpLifecycleLock"]; +type WithUnlockedSandboxStatusRead = + (typeof import("../../src/lib/actions/sandbox/status-snapshot"))["withUnlockedSandboxStatusRead"]; const requireDist = createRequire(import.meta.url); const statusModulePath = "../../src/lib/actions/sandbox/status.js"; @@ -39,12 +42,15 @@ export type StatusFlowHarness = { getActiveSandboxSessionsSpy: MockInstance; getSandboxDockerRuntimeSpy: MockInstance; getSandboxStatusReport: GetSandboxStatusReport; + inspectManagedLlamaCppStatusSpy: MockInstance; qualifyPortableAgentLifecycleAuthoritySpy: MockInstance; isSandboxGatewayRunningForStatusSpy: MockInstance; logSpy: MockInstance; removeSandboxSpy: MockInstance; showSandboxStatus: ShowSandboxStatus; withMcpLifecycleLockSpy: MockInstance; + withUnlockedSandboxStatusRead: WithUnlockedSandboxStatusRead; + ensureHermesToolGatewayBrokerSpy: MockInstance | null; }; const baseSandboxEntry = { @@ -85,6 +91,7 @@ export type StatusFlowHarnessOptions = { registryEntry?: "present" | "missing"; publishedAcrossGatewayRoots?: boolean; withMcpLifecycleLock?: WithMcpLifecycleLock; + mockHermesToolGatewayBroker?: boolean; lookup?: SandboxGatewayState; lookupState?: "present" | "missing"; gatewayRunning?: boolean; @@ -116,6 +123,15 @@ export function resetStatusFlowModuleCache(): void { delete require.cache[requireDist.resolve(statusModulePath)]; } +export function createRealMcpLifecycleLock( + options: McpLifecycleLockOptions = {}, +): WithMcpLifecycleLock { + const lockModule = requireDist("../../src/lib/state/mcp-lifecycle-lock-acquisition.js"); + const acquire = lockModule.withMcpLifecycleLock as WithMcpLifecycleLock; + return (sandboxName, operation, overrides = {}) => + acquire(sandboxName, operation, { ...options, ...overrides }); +} + export function createStatusFlowHarness(options: StatusFlowHarnessOptions = {}): StatusFlowHarness { resetStatusFlowModuleCache(); @@ -132,6 +148,7 @@ export function createStatusFlowHarness(options: StatusFlowHarnessOptions = {}): "../../src/lib/onboard/experimental/portable-agent-lifecycle.js", ); const lifecycleLock = requireDist("../../src/lib/state/mcp-lifecycle-lock-acquisition.js"); + const managedLlamaCppStatus = requireDist("../../src/lib/inference/llama-cpp/managed-status.js"); const resolve = requireDist("../../src/lib/adapters/openshell/resolve.js"); const agentRuntime = requireDist("../../src/lib/agent/runtime.js"); const nim = requireDist("../../src/lib/inference/nim.js"); @@ -304,7 +321,18 @@ export function createStatusFlowHarness(options: StatusFlowHarnessOptions = {}): logSpy.mockClear(); + const inspectManagedLlamaCppStatusSpy = vi + .spyOn(managedLlamaCppStatus, "inspectManagedLlamaCppStatus") + .mockReturnValue(null); const statusModule = requireDist(statusModulePath); + const ensureHermesToolGatewayBrokerSpy = options.mockHermesToolGatewayBroker + ? vi + .spyOn( + requireDist("../../src/lib/hermes-tool-gateway-broker.js"), + "ensureHermesToolGatewayBrokerForSandboxEntry", + ) + .mockImplementation(() => undefined) + : null; return { checkAgentVersionSpy, @@ -312,11 +340,14 @@ export function createStatusFlowHarness(options: StatusFlowHarnessOptions = {}): getActiveSandboxSessionsSpy, getSandboxDockerRuntimeSpy, getSandboxStatusReport: statusModule.getSandboxStatusReport, + inspectManagedLlamaCppStatusSpy, qualifyPortableAgentLifecycleAuthoritySpy, isSandboxGatewayRunningForStatusSpy, logSpy, removeSandboxSpy, showSandboxStatus: statusModule.showSandboxStatus, withMcpLifecycleLockSpy, + withUnlockedSandboxStatusRead: statusSnapshot.withUnlockedSandboxStatusRead, + ensureHermesToolGatewayBrokerSpy, } satisfies StatusFlowHarness; }