From 56bca8d4716139e74b899dd44971a33d462ec017 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 10 Sep 2026 15:24:45 -0700 Subject: [PATCH 1/2] refactor(providers): centralize destructive cleanup in typed adapter Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ci/source-architecture-budget.json | 4 +- src/commands/credentials.test.ts | 1 + .../internal/uninstall/run-plan.test.ts | 67 ++++ src/lib/actions/sandbox/destroy-execution.ts | 9 +- src/lib/actions/sandbox/destroy-flow.test.ts | 32 ++ src/lib/actions/sandbox/destroy.test.ts | 46 ++- src/lib/actions/sandbox/destroy.ts | 22 +- .../snapshot-auto-create-failure.test.ts | 8 +- ...apshot-hermes-managed-clone-broker.test.ts | 5 + .../snapshot-managed-clone-providers.test.ts | 12 +- src/lib/actions/sandbox/snapshot.ts | 29 +- .../snapshot/hermes-managed-clone-broker.ts | 6 +- .../snapshot/managed-clone-providers.ts | 74 +--- ...mes-portable-uninstall-transaction.test.ts | 82 ++-- .../hermes-portable-uninstall-transaction.ts | 10 +- .../hermes-portable-uninstall.test.ts | 70 ++-- .../uninstall/hermes-portable-uninstall.ts | 8 +- ...openrouter-runtime-adapter-cleanup.test.ts | 24 +- .../portable-runtime-cleanup-schema5.test.ts | 16 +- .../portable-runtime-cleanup.test-support.ts | 44 +++ .../portable-runtime-cleanup.test.ts | 208 +++++----- .../uninstall/portable-runtime-cleanup.ts | 36 +- .../uninstall/run-plan-absent-sandbox.test.ts | 2 +- .../uninstall/run-plan-docker-scope.test.ts | 32 +- .../uninstall/run-plan-dual-station.test.ts | 48 +-- ...-plan-external-gateway-segregation.test.ts | 4 +- .../run-plan-foreign-user-gateway.test.ts | 16 +- .../run-plan-gateway-scan-entries.test.ts | 32 +- ...-gateway-segregation-selected-port.test.ts | 28 +- .../run-plan-gateway-segregation.test.ts | 92 ++--- .../run-plan-gateway-service.test.ts | 4 +- .../run-plan-hermes-state-volume.test.ts | 4 +- .../run-plan-homebrew-openshell.test.ts | 20 +- .../run-plan-local-model-profile.test.ts | 76 ++-- .../uninstall/run-plan-nvm-leftovers.test.ts | 16 +- .../run-plan-other-gateway-report.test.ts | 38 +- .../run-plan-portable-leftover-state.test.ts | 4 +- .../run-plan-portable-runtime.test.ts | 112 +++--- .../run-plan-pre-uninstall-backup.test.ts | 4 +- .../run-plan-preserved-registry.test.ts | 4 +- src/lib/actions/uninstall/run-plan.test.ts | 136 +++---- src/lib/actions/uninstall/run-plan.ts | 99 ++--- .../provider-adapter-cli-uncertainty.test.ts | 97 ++++- .../openshell/provider-adapter-cli.test.ts | 2 +- .../openshell/provider-adapter-cli.ts | 38 +- .../adapters/openshell/provider-adapter.ts | 1 + .../openshell/provider-diagnostic-cli.ts | 58 ++- src/lib/adapters/uninstall/commands.test.ts | 52 +++ src/lib/adapters/uninstall/commands.ts | 40 ++ ...mes-portable-ollama-gateway-transaction.ts | 53 ++- .../hermes-portable-ollama-inference.test.ts | 14 +- .../remote-openai-surface.test.ts | 124 ++++-- src/lib/onboard/inference-providers/remote.ts | 107 +++-- src/lib/onboard/inference-providers/types.ts | 10 +- .../onboard-orchestration.test.ts | 2 +- src/lib/onboard/providers.ts | 12 +- src/lib/onboard/runtime-provider/contract.ts | 6 +- .../onboard/sandbox-create-intent-types.ts | 4 +- .../sandbox-create-plan-materialization.ts | 2 +- src/lib/onboard/sandbox-create-plan.test.ts | 57 ++- .../sandbox-create/orchestration.test.ts | 14 +- .../onboard/sandbox-create/orchestration.ts | 12 +- src/lib/onboard/sandbox-provider-cleanup.ts | 281 ++++---------- src/lib/onboard/setup-inference.ts | 6 +- src/lib/state/registry-lock.test.ts | 106 +++++ src/lib/state/registry/lock.ts | 43 +- test/fixtures/uninstall-prompt-pty-driver.ts | 65 ++-- test/helpers/destroy-flow-test-harness.ts | 13 +- ...-anthropic-compatible-openai-agent.test.ts | 109 ++++-- .../onboard-inference-gateway-scope.test.ts | 24 +- .../cli/credentials-cli-command.test.ts | 1 + .../destroy-cleanup-sandbox-services.test.ts | 72 ++-- .../sandbox/sandbox-provider-cleanup.test.ts | 366 ++++++++++++------ test/support/setup-inference-test-harness.ts | 39 ++ 74 files changed, 2081 insertions(+), 1333 deletions(-) create mode 100644 src/commands/internal/uninstall/run-plan.test.ts create mode 100644 src/lib/actions/uninstall/portable-runtime-cleanup.test-support.ts create mode 100644 src/lib/adapters/uninstall/commands.test.ts create mode 100644 src/lib/adapters/uninstall/commands.ts diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index 44b4f4fc233..336044b3365 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -10,7 +10,7 @@ "src/lib/adapters/openshell/client.ts": 19, "src/lib/adapters/openshell/command-argv.ts": 22, "src/lib/adapters/openshell/resolve.ts": 25, - "src/lib/adapters/openshell/runtime.ts": 47, + "src/lib/adapters/openshell/runtime.ts": 46, "src/lib/adapters/openshell/sandbox-observer.ts": 35, "src/lib/adapters/openshell/timeouts.ts": 32, "src/lib/agent/defs.ts": 32, @@ -24,7 +24,7 @@ "src/lib/core/wait.ts": 30, "src/lib/credentials/store.ts": 45, "src/lib/inference/config.ts": 30, - "src/lib/messaging/channels/index.ts": 25, + "src/lib/messaging/channels/index.ts": 24, "src/lib/onboard/gateway-binding.ts": 53, "src/lib/runner.ts": 83, "src/lib/security/redact.ts": 52, diff --git a/src/commands/credentials.test.ts b/src/commands/credentials.test.ts index 766f9cdf0f0..96659fa3b09 100644 --- a/src/commands/credentials.test.ts +++ b/src/commands/credentials.test.ts @@ -123,6 +123,7 @@ describe("credentials oclif adapter source coverage", () => { { ignoreError: true, stdio: ["ignore", "pipe", "pipe"], + suppressOutput: true, timeout: 30_000, }, ); diff --git a/src/commands/internal/uninstall/run-plan.test.ts b/src/commands/internal/uninstall/run-plan.test.ts new file mode 100644 index 00000000000..1eec8cf174e --- /dev/null +++ b/src/commands/internal/uninstall/run-plan.test.ts @@ -0,0 +1,67 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; +import type { Config } from "@oclif/core"; + +const mocks = vi.hoisted(() => ({ + runUninstallPlan: vi.fn(), + runUninstallPlanProduction: vi.fn(), +})); + +vi.mock("../../../lib/actions/uninstall/run-plan", () => mocks); +vi.mock("../../../lib/actions/maintenance", () => ({ backupAllUnderPortableHostFence: vi.fn() })); +vi.mock("../../../lib/actions/uninstall/all-gateway-ports", () => ({ + allGatewayPortsRequested: () => false, + runUninstallAllGatewayPorts: vi.fn(), +})); + +import InternalUninstallRunPlanCommand from "./run-plan"; + +describe("internal uninstall command", () => { + it("awaits the production uninstall transaction before applying its exit result", async () => { + const previousExitCode = process.exitCode; + let complete!: (value: { exitCode: number }) => void; + let entered!: () => void; + const started = new Promise((resolve) => { + entered = resolve; + }); + const pending = new Promise<{ exitCode: number }>((resolve) => { + complete = resolve; + }); + mocks.runUninstallPlanProduction.mockImplementation(() => { + entered(); + return pending; + }); + let finished = false; + process.exitCode = undefined; + const instance = new InternalUninstallRunPlanCommand([], {} as Config); + Object.defineProperty(instance, "parse", { + value: vi.fn().mockResolvedValue({ flags: { yes: true, "keep-openshell": true } }), + }); + const command = instance.run().then(() => { + finished = true; + }); + try { + await Promise.race([started, command]); + expect(mocks.runUninstallPlanProduction).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ assumeYes: true, keepOpenShell: true }), + expect.objectContaining({ + backupAllBeforeUninstall: expect.any(Function), + withSandboxMutationLock: expect.any(Function), + }), + ); + expect(mocks.runUninstallPlan).not.toHaveBeenCalled(); + expect(finished).toBe(false); + expect(process.exitCode).toBeUndefined(); + complete({ exitCode: 1 }); + await command; + expect(process.exitCode).toBe(1); + } finally { + complete({ exitCode: 0 }); + await command.finally(() => { + process.exitCode = previousExitCode; + }); + } + }); +}); diff --git a/src/lib/actions/sandbox/destroy-execution.ts b/src/lib/actions/sandbox/destroy-execution.ts index 891d6c82a40..63e3a10f4d6 100644 --- a/src/lib/actions/sandbox/destroy-execution.ts +++ b/src/lib/actions/sandbox/destroy-execution.ts @@ -527,7 +527,7 @@ export async function executeSandboxDestroy({ mcpRecoveryFailure, }; } - const detachProviders = (): DetachSandboxProvidersResult => + const detachProviders = (): Promise => runSandboxProviderPreDeleteCleanup(sandboxName, { runOpenshell: selectedRunOpenshell, redact, @@ -545,8 +545,11 @@ export async function executeSandboxDestroy({ const detachOutcome: DetachSandboxProvidersResult = sandboxConfirmedAbsent ? { detached: [], failures: [] } : runtimeProvider?.cleanup.supported === true && sandbox - ? runtimeProvider.cleanup.prepareDestroy({ sandbox, sandboxName }, { detachProviders }) - : detachProviders(); + ? await runtimeProvider.cleanup.prepareDestroy( + { sandbox, sandboxName }, + { detachProviders }, + ) + : await detachProviders(); // The final identity proof runs immediately before OpenShell delete. A // runtime administrator remains a trusted host authority; this closes the // multi-step window without claiming a cross-runtime transaction. diff --git a/src/lib/actions/sandbox/destroy-flow.test.ts b/src/lib/actions/sandbox/destroy-flow.test.ts index d139ea9f436..2a1a762fd01 100644 --- a/src/lib/actions/sandbox/destroy-flow.test.ts +++ b/src/lib/actions/sandbox/destroy-flow.test.ts @@ -79,6 +79,38 @@ describe("destroySandbox flow", () => { expectStrictSandboxPresenceClassification(); }); + it("waits for provider detach before deleting the sandbox", { timeout: 30_000 }, async () => { + const harness = createDestroyHarness(); + let finishDetach!: () => void; + let detachStarted!: () => void; + const pending = new Promise((resolve) => { + finishDetach = resolve; + }); + const started = new Promise((resolve) => { + detachStarted = resolve; + }); + harness.runSandboxProviderPreDeleteCleanupSpy.mockImplementationOnce(async () => { + detachStarted(); + await pending; + return { detached: [], failures: [] }; + }); + const destroy = harness.destroySandbox("alpha", { yes: true, cleanupGateway: false }); + try { + await Promise.race([started, destroy]); + expect(harness.runSandboxProviderPreDeleteCleanupSpy).toHaveBeenCalledOnce(); + expect(harness.events).not.toContain("delete"); + expect(harness.removeSandboxSpy).not.toHaveBeenCalled(); + expect(harness.lifecycleLockEvents).toContain("acquired"); + expect(harness.lifecycleLockEvents).not.toContain("released"); + } finally { + finishDetach(); + await destroy; + } + expect(harness.events).toContain("delete"); + expect(harness.removeSandboxSpy).toHaveBeenCalledOnce(); + expect(harness.lifecycleLockEvents).toContain("released"); + }); + it( "selects the sandbox gateway, deletes live resources, cleans host state, and removes registry state", { timeout: 30_000 }, diff --git a/src/lib/actions/sandbox/destroy.test.ts b/src/lib/actions/sandbox/destroy.test.ts index 984f56999fd..65dcf0c6694 100644 --- a/src/lib/actions/sandbox/destroy.test.ts +++ b/src/lib/actions/sandbox/destroy.test.ts @@ -5,6 +5,7 @@ import path from "node:path"; import { describe, expect, it, vi } from "vitest"; import type { SandboxEntry } from "../../state/registry"; +import { SANDBOX_PROVIDER_SUFFIXES } from "../../onboard/sandbox-provider-cleanup"; import { assertUnambiguousDestroyContainerIdentity, cleanupSandboxServices } from "./destroy"; const SANDBOX = "mybox"; @@ -12,7 +13,38 @@ const mainPidDir = path.resolve("/tmp", `nemoclaw-services-${SANDBOX}`); const googlechatPidDir = `${mainPidDir}-googlechat`; describe("cleanupSandboxServices Google Chat tunnel cleanup (#7317)", () => { - it("fails closed before later cleanup when the Google Chat tunnel cannot stop", () => { + it("deletes every messaging and search registration through the selected gateway", async () => { + const runOpenshell = vi.fn(() => ({ status: 0 })); + + await cleanupSandboxServices( + SANDBOX, + { stopHostServices: false }, + { + getSandbox: () => null, + listSandboxes: () => ({ sandboxes: [], defaultSandbox: null }), + withOllamaModelOwnershipLock: (operation) => operation(), + loadPersistedOllamaHost: () => "127.0.0.1", + loadPendingOllamaModelCleanup: () => [], + rmSync: vi.fn(), + runOpenshell, + stopGooglechatWebhookTunnel: vi.fn(() => googlechatPidDir), + googlechatWebhookTunnelPidDir: vi.fn(() => googlechatPidDir), + }, + ); + + expect(runOpenshell.mock.calls).toEqual( + SANDBOX_PROVIDER_SUFFIXES.map((suffix) => [ + ["provider", "delete", `${SANDBOX}-${suffix}`], + expect.objectContaining({ + ignoreError: true, + suppressOutput: true, + stdio: ["ignore", "pipe", "pipe"], + }), + ]), + ); + }); + + it("fails closed before later cleanup when the Google Chat tunnel cannot stop", async () => { const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); const rmSync = vi.fn(); const runOpenshell = vi.fn(() => ({ status: 0 })); @@ -23,7 +55,7 @@ describe("cleanupSandboxServices Google Chat tunnel cleanup (#7317)", () => { throw new Error("cloudflared refused to stop"); }); - expect(() => + await expect( cleanupSandboxServices( SANDBOX, { stopHostServices: true }, @@ -36,7 +68,7 @@ describe("cleanupSandboxServices Google Chat tunnel cleanup (#7317)", () => { googlechatWebhookTunnelPidDir, }, ), - ).toThrow(/public Google Chat webhook endpoint may still be running/); + ).rejects.toThrow(/public Google Chat webhook endpoint may still be running/); expect(googlechatWebhookTunnelPidDir).toHaveBeenCalledWith(mainPidDir); // Preserve both PID directories and refuse every later side effect so a @@ -50,12 +82,12 @@ describe("cleanupSandboxServices Google Chat tunnel cleanup (#7317)", () => { warn.mockRestore(); }); - it("removes the Google Chat PID directory after a successful tunnel stop", () => { + it("removes the Google Chat PID directory after a successful tunnel stop", async () => { const rmSync = vi.fn(); const stopGooglechatWebhookTunnel = vi.fn(() => googlechatPidDir); const googlechatWebhookTunnelPidDir = vi.fn(() => googlechatPidDir); - cleanupSandboxServices( + await cleanupSandboxServices( SANDBOX, { stopHostServices: true }, { @@ -73,7 +105,7 @@ describe("cleanupSandboxServices Google Chat tunnel cleanup (#7317)", () => { }); describe("cleanupSandboxServices Ollama ownership", () => { - it("keeps a model shared through a compatible endpoint at the same local daemon", () => { + it("keeps a model shared through a compatible endpoint at the same local daemon", async () => { const own = { name: SANDBOX, provider: "ollama-local", @@ -87,7 +119,7 @@ describe("cleanupSandboxServices Ollama ownership", () => { } as SandboxEntry; const unloadOllamaModels = vi.fn(); - cleanupSandboxServices( + await cleanupSandboxServices( SANDBOX, { stopHostServices: false }, { diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index ef106cf4315..c2c189b07ff 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -37,8 +37,8 @@ import { } from "../../onboard/runtime-provider/access"; import { emitProviderDetachResidualHint, + deleteSandboxProviderRegistrations, removeManagedAgentStateVolumes, - SANDBOX_PROVIDER_SUFFIXES, } from "../../onboard/sandbox-provider-cleanup"; import { validateName } from "../../runner"; import { withMcpLifecycleLock } from "../../state/mcp-lifecycle-lock"; @@ -222,11 +222,11 @@ async function resolveCleanupGatewayDecision(options: DestroySandboxOptions): Pr return trimmed === "y" || trimmed === "yes"; } -export function cleanupSandboxServices( +export async function cleanupSandboxServices( sandboxName: string, { stopHostServices = false }: { stopHostServices?: boolean } = {}, deps: CleanupSandboxServicesDeps = {}, -): void { +): Promise { // Source boundary: this exported helper can be called independently of CLI // dispatch, including from forced local recovery. Validate once before every // host and provider cleanup side effect, then derive the PID path from that @@ -442,12 +442,7 @@ export function cleanupSandboxServices( // onboard rebuild path's pre-delete detach via // `src/lib/onboard/sandbox-provider-cleanup.ts` so the two paths can't // drift on which providers count as per-sandbox state. - for (const suffix of SANDBOX_PROVIDER_SUFFIXES) { - runOpenshell(["provider", "delete", `${validatedSandboxName}-${suffix}`], { - ignoreError: true, - stdio: ["ignore", "ignore", "ignore"], - }); - } + await deleteSandboxProviderRegistrations(validatedSandboxName, "all", { runOpenshell }); } /** @@ -1002,13 +997,13 @@ async function destroySandboxUnlocked( } } } - abortPreparedCleanupOnError(() => { + try { const shouldStopHostServices = shouldStopHostServicesAfterDestroy({ deleteSucceededOrAlreadyGone, registeredSandboxCount: registry.listSandboxes().sandboxes.length, sandboxStillRegistered: !!registry.getSandbox(sandboxName), }); - cleanupSandboxServices( + await cleanupSandboxServices( sandboxName, { stopHostServices: shouldStopHostServices, @@ -1017,7 +1012,10 @@ async function destroySandboxUnlocked( runOpenshell: cleanupRunOpenshell, }, ); - }); + } catch (error) { + preparedManagedLlamaCppCleanup?.abort(); + throw error; + } if (deleteSucceededOrAlreadyGone && commonLlamaCppAuthorityRetired === true) { preparedManagedLlamaCppCleanup?.abort(); } else if (deleteSucceededOrAlreadyGone) { diff --git a/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts b/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts index 082b4bac2db..e3d2342f672 100644 --- a/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts +++ b/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { beforeEach, describe, expect, it, vi } from "vitest"; +import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { hostLocalInferenceReceipt, serializedLlamaCppHostLocalInferenceReceipt, @@ -186,6 +186,7 @@ vi.mock("../../inference/nim", () => ({ })); vi.mock("../../messaging/channels", () => ({ BUILT_IN_CHANNEL_MANIFESTS: [], + createBuiltInChannelManifestRegistry: vi.fn(() => ({ list: () => [] })), getMessagingConfigEnvAliases: vi.fn(() => ({})), getMessagingCredentialEnvKeysByChannel: vi.fn(() => ({})), getMessagingProviderSuffixesByChannel: vi.fn(() => ({})), @@ -268,6 +269,11 @@ vi.mock("./snapshot/dependencies", async (importOriginal) => ({ })); describe("snapshot restore auto-create failures", () => { + beforeAll(async () => { + // Load the mocked action graph before measuring the individual cleanup operations. + await import("./snapshot"); + }, 30_000); + beforeEach(() => { vi.clearAllMocks(); harness.entries.clear(); diff --git a/src/lib/actions/sandbox/snapshot-hermes-managed-clone-broker.test.ts b/src/lib/actions/sandbox/snapshot-hermes-managed-clone-broker.test.ts index af1d745b80c..4f049b96dd6 100644 --- a/src/lib/actions/sandbox/snapshot-hermes-managed-clone-broker.test.ts +++ b/src/lib/actions/sandbox/snapshot-hermes-managed-clone-broker.test.ts @@ -4,6 +4,7 @@ import { createHash } from "node:crypto"; import { describe, expect, it, type Mock, vi } from "vitest"; +import { createManagedProviderAdapter } from "../../adapters/openshell/managed-provider-adapter"; import { managedStartupE2eProfile } from "../../../../scripts/checks/generate-managed-startup-profile-fixture.mts"; import type { HermesToolGatewayCloneBroker } from "../../hermes-tool-gateway-clone-broker"; import { @@ -413,6 +414,8 @@ describe("Hermes managed clone broker transaction", () => { const profile = hermesProfile(); const source = sourceEntry(profile); const runner = providerRunner(); + const providerAdapter = createManagedProviderAdapter(runner.run); + const deleteProvider = vi.spyOn(providerAdapter, "deleteProvider"); const hostBroker = broker(); hostBroker.activateHermesToolGatewayCloneBinding.mockImplementation(() => { throw new Error("activation rejected"); @@ -431,10 +434,12 @@ describe("Hermes managed clone broker transaction", () => { ...authority(source), environment: environment(), runOpenshell: runner.run, + providerAdapter, broker: hostBroker, }), ).rejects.toThrow("activation rejected"); expect(runner.live.size).toBe(0); + expect(deleteProvider).toHaveBeenCalledTimes(2); expect(hostBroker.discardHermesToolGatewayCloneBinding).toHaveBeenCalledOnce(); }); }); diff --git a/src/lib/actions/sandbox/snapshot-managed-clone-providers.test.ts b/src/lib/actions/sandbox/snapshot-managed-clone-providers.test.ts index f4f541e0b24..4157e1269c0 100644 --- a/src/lib/actions/sandbox/snapshot-managed-clone-providers.test.ts +++ b/src/lib/actions/sandbox/snapshot-managed-clone-providers.test.ts @@ -481,7 +481,7 @@ describe("managed clone provider transaction", () => { expect( runner.commands.some((command) => /provider (create|delete|update)/u.test(command)), ).toBe(false); - expect(cleanupManagedCloneProviderTransaction(receipt, runner.run)).toMatchObject({ + expect(await cleanupManagedCloneProviderTransaction(receipt, runner.run)).toMatchObject({ status: "complete", providers: [{ outcome: "reused-preserved" }], }); @@ -659,7 +659,7 @@ describe("managed clone provider transaction", () => { expect(receipt.providers).toEqual([{ binding: TOKEN_BINDING, disposition: "created" }]); expect(Object.isFrozen(receipt.providers[0]?.binding)).toBe(true); - expect(cleanupManagedCloneProviderTransaction(receipt, runner.run)).toMatchObject({ + expect(await cleanupManagedCloneProviderTransaction(receipt, runner.run)).toMatchObject({ status: "complete", providers: [{ outcome: "deleted" }], }); @@ -667,7 +667,7 @@ describe("managed clone provider transaction", () => { const deletesBeforeRetry = runner.commands.filter((command) => command.startsWith("provider delete"), ).length; - expect(cleanupManagedCloneProviderTransaction(receipt, runner.run)).toMatchObject({ + expect(await cleanupManagedCloneProviderTransaction(receipt, runner.run)).toMatchObject({ status: "complete", providers: [{ outcome: "already-cleaned" }], }); @@ -801,7 +801,7 @@ describe("managed clone provider transaction", () => { }); runner.setFailDelete(true); - expect(cleanupManagedCloneProviderTransaction(receipt, runner.run)).toMatchObject({ + expect(await cleanupManagedCloneProviderTransaction(receipt, runner.run)).toMatchObject({ status: "partial", providers: [{ outcome: "delete-failed" }], }); @@ -816,9 +816,9 @@ describe("managed clone provider transaction", () => { runOpenshell: runner.run, }); - expect(() => + await expect( cleanupManagedCloneProviderTransaction(structuredClone(receipt), runner.run), - ).toThrow(/exact process-local ownership receipt/u); + ).rejects.toThrow(/exact process-local ownership receipt/u); expect(runner.live.has(TOKEN_BINDING.providerName)).toBe(true); }); diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index eacc7d3dfdb..a129258225e 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -31,7 +31,7 @@ import { } from "../../inference/gateway-route-compatibility"; import { withGatewayRouteMutationLock } from "../../inference/gateway-route-mutation-lock"; import * as nim from "../../inference/nim"; -import { listMessagingProviderSuffixes } from "../../messaging/channels"; +import { deleteSandboxProviderRegistrations } from "../../onboard/sandbox-provider-cleanup"; import { findAvailableDashboardPort, getRegistryOccupiedDashboardPorts, @@ -683,8 +683,8 @@ async function autoCreateSandboxFromSource( // `stopHostServices`), Ollama model unload, gateway teardown \u2014 are // deliberately skipped here because they can also affect the source sandbox // we are about to clone from. -function deleteSandboxForRestore(name: string): void { - withMcpLifecycleLockSync(name, () => { +async function deleteSandboxForRestore(name: string): Promise { + await withMcpLifecycleLock(name, async () => { const sbMeta = registry.getSandbox(name); if (!sbMeta) { console.error( @@ -761,12 +761,7 @@ function deleteSandboxForRestore(name: string): void { } catch { // PID dir may not exist \u2014 ignore. } - for (const suffix of listMessagingProviderSuffixes()) { - runOpenshell(["provider", "delete", `${name}${suffix}`], { - ignoreError: true, - stdio: ["ignore", "ignore", "ignore"], - }); - } + await deleteSandboxProviderRegistrations(name, "messaging", { runOpenshell }); requireSnapshotDestinationRegistryRemoval(name, removeSandboxRegistryEntryOutcome(name)); }); console.log(` ${G}\u2713${R} '${name}' deleted`); @@ -805,11 +800,11 @@ function verifyRestoreDestinationOnOwnGateway(targetSandbox: string): void { type PendingSnapshotCloneRecovery = "not-pending" | "finalized" | "removed"; -function reconcilePendingSnapshotClone( +async function reconcilePendingSnapshotClone( targetSandbox: string, sourceEntry: SandboxEntry, sourceGatewayName: string, -): PendingSnapshotCloneRecovery { +): Promise { const pending = registry.getSandbox(targetSandbox); if ( !pending || @@ -839,7 +834,7 @@ function reconcilePendingSnapshotClone( } const liveNames = parseLiveSandboxNames(list.output || ""); if (!liveNames.has(targetSandbox)) { - deleteSandboxForRestore(targetSandbox); + await deleteSandboxForRestore(targetSandbox); return "removed"; } @@ -853,7 +848,7 @@ function reconcilePendingSnapshotClone( } const liveIdentityFingerprint = fingerprintSandboxLiveIdentity(get.output || ""); if (liveIdentityFingerprint !== pending.lifecycleLiveIdentityFingerprint) { - deleteSandboxForRestore(targetSandbox); + await deleteSandboxForRestore(targetSandbox); return "removed"; } if (!isSandboxReady(list.output || "", targetSandbox)) { @@ -865,7 +860,7 @@ function reconcilePendingSnapshotClone( (pending.agent || "openclaw") === "openclaw" && !waitForRestoredSandboxGatewaySupervisor(targetSandbox) ) { - deleteSandboxForRestore(targetSandbox); + await deleteSandboxForRestore(targetSandbox); return "removed"; } if (!registry.finalizePendingSandboxRegistration(targetSandbox)) { @@ -1363,7 +1358,7 @@ async function runSnapshotRestoreUnlocked( ); snapshotExit(1); } - const pendingRecovery = reconcilePendingSnapshotClone( + const pendingRecovery = await reconcilePendingSnapshotClone( targetSandbox, lockedSourceEntry, lockedGatewayName, @@ -1406,7 +1401,7 @@ async function runSnapshotRestoreUnlocked( if (targetEntry) { verifyRestoreDestinationOnOwnGateway(targetSandbox); } - deleteSandboxForRestore(targetSandbox); + await deleteSandboxForRestore(targetSandbox); requireLiveSandboxesOnSandboxGateway( sandboxName, " Failed to re-select source sandbox gateway after deleting destination.", @@ -1481,7 +1476,7 @@ async function runSnapshotRestoreUnlocked( console.error( ` Removing incomplete clone '${targetSandbox}' while its exact provider ownership is still registered.`, ); - deleteSandboxForRestore(targetSandbox); + await deleteSandboxForRestore(targetSandbox); snapshotExit(1); } } diff --git a/src/lib/actions/sandbox/snapshot/hermes-managed-clone-broker.ts b/src/lib/actions/sandbox/snapshot/hermes-managed-clone-broker.ts index a216106bad8..225cfd138f4 100644 --- a/src/lib/actions/sandbox/snapshot/hermes-managed-clone-broker.ts +++ b/src/lib/actions/sandbox/snapshot/hermes-managed-clone-broker.ts @@ -301,7 +301,11 @@ export async function provisionHermesManagedCloneBrokerTransaction( ); } const cleanup = providerReceipt - ? cleanupManagedCloneProviderTransaction(providerReceipt, input.runOpenshell) + ? await cleanupManagedCloneProviderTransaction( + providerReceipt, + input.runOpenshell, + providerAdapter, + ) : undefined; let discarded = false; try { diff --git a/src/lib/actions/sandbox/snapshot/managed-clone-providers.ts b/src/lib/actions/sandbox/snapshot/managed-clone-providers.ts index 98d87c8b7e3..c48222e50f0 100644 --- a/src/lib/actions/sandbox/snapshot/managed-clone-providers.ts +++ b/src/lib/actions/sandbox/snapshot/managed-clone-providers.ts @@ -16,11 +16,7 @@ import { REPOSITORY_ROOT } from "../../../core/repository-root"; import type { SandboxMessagingPlan } from "../../../messaging/manifest"; import { MESSAGING_CREDENTIAL_PROVIDER_TYPE } from "../../../messaging/provider-profile"; import { isValidName, isValidProviderName } from "../../../name-validation"; -import { reportsExactProviderNotFound } from "../../../adapters/openshell/provider-diagnostic-cli"; -import { - matchesGatewayCredentialOnlyProviderBinding, - parseGatewayProviderMetadata, -} from "../../../onboard/gateway-provider-metadata"; +import { matchesGatewayCredentialOnlyProviderBinding } from "../../../onboard/gateway-provider-metadata"; import type { ManagedStartupProfile } from "../../../onboard/managed-startup/profile"; import { normalizeRuntimeProviderIdentity } from "../../../onboard/runtime-provider/registry"; import { deleteProviderWithRecovery } from "../../../onboard/sandbox-provider-cleanup"; @@ -33,7 +29,6 @@ import { import type { SandboxEntry } from "../../../state/registry/types"; import * as sandboxState from "../../../state/sandbox"; -const PROVIDER_PROBE_DIAGNOSTIC_LIMIT = 64 * 1024; export const MANAGED_CLONE_PROVIDER_CREATE_TIMEOUT_MS = 30_000; const PROVIDER_PROBE_TIMEOUT_MS = 5_000; const PROVIDER_TYPE_PATTERN = /^[A-Za-z0-9._:-]{1,64}$/u; @@ -148,59 +143,11 @@ function fail(message: string, cause?: unknown): never { ); } -function commandStreamText(value: string | Buffer | null | undefined): string { - return Buffer.isBuffer(value) ? value.toString("utf8") : (value ?? ""); -} - type ProviderInspection = | { readonly kind: "collision" } | { readonly kind: "exact" } | { readonly kind: "missing" }; -/** - * TODO(#9806, Slice 8): retire this raw-runner bridge when cleanup inspection and deletion use - * the typed provider adapter. Exit when both cleanup call sites below use typed get/delete - * operations and this helper has no callers. - */ -function inspectProviderForCleanup( - binding: ManagedCloneProviderBinding, - runOpenshell: ManagedCloneProviderRunner, -): ProviderInspection { - const result = runOpenshell(["provider", "get", binding.providerName], { - ignoreError: true, - maxBuffer: PROVIDER_PROBE_DIAGNOSTIC_LIMIT, - stdio: ["ignore", "pipe", "pipe"], - suppressOutput: true, - timeout: PROVIDER_PROBE_TIMEOUT_MS, - }); - if (result.error || result.signal || result.status !== 0) { - const output = `${commandStreamText(result.stdout)}\n${commandStreamText(result.stderr)}`; - if ( - !result.error && - !result.signal && - result.status === 1 && - reportsExactProviderNotFound(output, binding.providerName, PROVIDER_PROBE_DIAGNOSTIC_LIMIT) - ) { - return { kind: "missing" }; - } - fail( - `could not prove whether provider '${binding.providerName}' exists; ` + - "refusing destination mutation", - ); - } - - const metadata = parseGatewayProviderMetadata( - `${commandStreamText(result.stdout)}\n${commandStreamText(result.stderr)}`, - ); - return matchesGatewayCredentialOnlyProviderBinding(metadata, { - name: binding.providerName, - type: binding.providerType, - credentialKey: binding.providerEnvKey, - }) - ? { kind: "exact" } - : { kind: "collision" }; -} - async function inspectProvider( binding: ManagedCloneProviderBinding, providerAdapter: OpenShellProviderAdapter, @@ -655,7 +602,11 @@ export async function provisionManagedCloneProviderTransaction( return issueReceipt(prepared, confirmed); } catch (cause) { const partialReceipt = issueReceipt(prepared, confirmed); - const rollback = cleanupManagedCloneProviderTransaction(partialReceipt, input.runOpenshell); + const rollback = await cleanupManagedCloneProviderTransaction( + partialReceipt, + input.runOpenshell, + providerAdapter, + ); const detail = cause instanceof Error ? cause.message : String(cause); throw new ManagedCloneProviderTransactionError(detail, { cause, @@ -670,10 +621,11 @@ export async function provisionManagedCloneProviderTransaction( * receipt. Once a name is cleaned, the ledger never re-inspects it, preventing * a repeated cleanup from deleting a later same-name provider. */ -export function cleanupManagedCloneProviderTransaction( +export async function cleanupManagedCloneProviderTransaction( receipt: ManagedCloneProviderTransactionReceipt, runOpenshell: ManagedCloneProviderRunner, -): ManagedCloneProviderCleanupResult { + providerAdapter: OpenShellProviderAdapter = createManagedProviderAdapter(runOpenshell), +): Promise { if (!issuedReceipts.has(receipt)) { fail("cleanup requires the exact process-local ownership receipt"); } @@ -695,7 +647,7 @@ export function cleanupManagedCloneProviderTransaction( } let inspection: ProviderInspection; try { - inspection = inspectProviderForCleanup(provider.binding, runOpenshell); + inspection = await inspectProvider(provider.binding, providerAdapter); } catch { outcomes.push({ providerName, outcome: "inspection-failed" }); continue; @@ -709,8 +661,8 @@ export function cleanupManagedCloneProviderTransaction( outcomes.push({ providerName, outcome: "drift-preserved" }); continue; } - const deletion = deleteProviderWithRecovery(providerName, { - runOpenshell, + const deletion = await deleteProviderWithRecovery(providerName, { + providerAdapter, allowedSandboxes: [receipt.destinationSandboxName], }); if (!deletion.ok) { @@ -718,7 +670,7 @@ export function cleanupManagedCloneProviderTransaction( continue; } try { - if (inspectProviderForCleanup(provider.binding, runOpenshell).kind !== "missing") { + if ((await inspectProvider(provider.binding, providerAdapter)).kind !== "missing") { outcomes.push({ providerName, outcome: "delete-failed" }); continue; } diff --git a/src/lib/actions/uninstall/hermes-portable-uninstall-transaction.test.ts b/src/lib/actions/uninstall/hermes-portable-uninstall-transaction.test.ts index eeb1edbfa08..2d062c7bfd7 100644 --- a/src/lib/actions/uninstall/hermes-portable-uninstall-transaction.test.ts +++ b/src/lib/actions/uninstall/hermes-portable-uninstall-transaction.test.ts @@ -217,7 +217,37 @@ afterEach(() => { }); describe("Hermes Portable uninstall transaction", () => { - it("coordinates phases through the injected journal state store (#9608)", () => { + it("keeps the journal at sandbox retirement until provider cleanup completes", async () => { + const state = stateDir(); + const fixture = transactionDeps(state); + let releaseProvider!: () => void; + let providerStarted!: () => void; + const started = new Promise((resolve) => { + providerStarted = resolve; + }); + const pending = new Promise((resolve) => { + releaseProvider = resolve; + }); + const transaction = runHermesPortableUninstallTransaction(state, { + ...fixture.deps, + reconcileProviders: async (authority) => { + providerStarted(); + await pending; + await fixture.deps.reconcileProviders(authority); + }, + }); + await started; + try { + expect(inspectHermesPortableUninstallJournal(state)?.phase).toBe("sandboxes-retired"); + expect(fixture.mutations).toEqual(["sandbox"]); + } finally { + releaseProvider(); + await transaction; + } + expect(inspectHermesPortableUninstallJournal(state)?.phase).toBe("completed"); + }); + + it("coordinates phases through the injected journal state store (#9608)", async () => { const state = stateDir(); const fixture = transactionDeps(state); const persisted = createHermesPortableUninstallJournalStore(state); @@ -230,7 +260,7 @@ describe("Hermes Portable uninstall transaction", () => { }; expect( - runHermesPortableUninstallTransaction(state, { ...fixture.deps, journalStore }), + await runHermesPortableUninstallTransaction(state, { ...fixture.deps, journalStore }), ).toMatchObject({ phase: "completed", targetCount: 1 }); expect(journalStore.read).toHaveBeenCalledOnce(); expect(journalStore.publishPrepared).toHaveBeenCalledOnce(); @@ -246,16 +276,16 @@ describe("Hermes Portable uninstall transaction", () => { "resources-absent", "registry-retired", "receipts-retired", - ] as const)("reconciles an interruption after the %s action (#9608)", (phase) => { + ] as const)("reconciles an interruption after the %s action (#9608)", async (phase) => { const state = stateDir(); const fixture = transactionDeps(state, phase); - expect(() => runHermesPortableUninstallTransaction(state, fixture.deps)).toThrow( - `interrupted after ${phase}`, - ); + await expect( + async () => await runHermesPortableUninstallTransaction(state, fixture.deps), + ).rejects.toThrow(`interrupted after ${phase}`); expect(inspectHermesPortableUninstallJournal(state)?.phase).toBe(phase); - const resumed = runHermesPortableUninstallTransaction(state, fixture.deps); + const resumed = await runHermesPortableUninstallTransaction(state, fixture.deps); expect(resumed.phase).toBe("completed"); expect(inspectHermesPortableUninstallJournal(state)?.phase).toBe("completed"); expect(fs.statSync(hermesPortableUninstallJournalPath(state)).mode & 0o777).toBe(0o600); @@ -266,7 +296,7 @@ describe("Hermes Portable uninstall transaction", () => { ); const mutations = [...fixture.mutations]; - expect(runHermesPortableUninstallTransaction(state, fixture.deps)).toEqual({ + expect(await runHermesPortableUninstallTransaction(state, fixture.deps)).toEqual({ phase: "completed", sandboxContainersRemoved: 0, targetCount: 1, @@ -274,32 +304,34 @@ describe("Hermes Portable uninstall transaction", () => { expect(fixture.mutations).toEqual(mutations); }); - it("cleans the phase temporary file when journal replacement fails (#9608)", () => { + it("cleans the phase temporary file when journal replacement fails (#9608)", async () => { const state = stateDir(); const fixture = transactionDeps(state, "prepared"); - expect(() => runHermesPortableUninstallTransaction(state, fixture.deps)).toThrow( - "interrupted after prepared", - ); + await expect( + async () => await runHermesPortableUninstallTransaction(state, fixture.deps), + ).rejects.toThrow("interrupted after prepared"); const rename = vi.spyOn(fs, "renameSync").mockImplementationOnce(() => { throw new Error("rename failed"); }); try { - expect(() => runHermesPortableUninstallTransaction(state, fixture.deps)).toThrow( - "rename failed", - ); + await expect( + async () => await runHermesPortableUninstallTransaction(state, fixture.deps), + ).rejects.toThrow("rename failed"); expect(fs.readdirSync(state).filter((entry) => entry.endsWith(".next"))).toEqual([]); } finally { rename.mockRestore(); } }); - it("replaces a completed journal when a later install publishes new authority (#9608)", () => { + it("replaces a completed journal when a later install publishes new authority (#9608)", async () => { const state = stateDir(); const fixture = transactionDeps(state); - expect(runHermesPortableUninstallTransaction(state, fixture.deps).phase).toBe("completed"); + expect((await runHermesPortableUninstallTransaction(state, fixture.deps)).phase).toBe( + "completed", + ); fixture.replaceInstallation(); - expect(runHermesPortableUninstallTransaction(state, fixture.deps)).toEqual({ + expect(await runHermesPortableUninstallTransaction(state, fixture.deps)).toEqual({ phase: "completed", sandboxContainersRemoved: 1, targetCount: 1, @@ -310,17 +342,17 @@ describe("Hermes Portable uninstall transaction", () => { expect(fixture.mutations.filter((mutation) => mutation === "sandbox")).toHaveLength(2); }); - it("fails closed on a same-name replacement after sandbox deletion (#9608)", () => { + it("fails closed on a same-name replacement after sandbox deletion (#9608)", async () => { const state = stateDir(); const fixture = transactionDeps(state, "prepared"); - expect(() => runHermesPortableUninstallTransaction(state, fixture.deps)).toThrow( - "interrupted after prepared", - ); + await expect( + async () => await runHermesPortableUninstallTransaction(state, fixture.deps), + ).rejects.toThrow("interrupted after prepared"); fixture.setReplacement(true); - expect(() => runHermesPortableUninstallTransaction(state, fixture.deps)).toThrow( - "same-name replacement", - ); + await expect( + async () => await runHermesPortableUninstallTransaction(state, fixture.deps), + ).rejects.toThrow("same-name replacement"); expect(fixture.mutations).toEqual(["sandbox"]); expect(inspectHermesPortableUninstallJournal(state)?.phase).toBe("prepared"); }); diff --git a/src/lib/actions/uninstall/hermes-portable-uninstall-transaction.ts b/src/lib/actions/uninstall/hermes-portable-uninstall-transaction.ts index 0da4e9a2ebf..de9d38e72d3 100644 --- a/src/lib/actions/uninstall/hermes-portable-uninstall-transaction.ts +++ b/src/lib/actions/uninstall/hermes-portable-uninstall-transaction.ts @@ -28,7 +28,9 @@ export interface HermesPortableUninstallTransactionDeps { phase: HermesPortableUninstallPhase, ) => void; readonly reconcileSandboxes: (authority: HermesPortableUninstallAuthority) => number; - readonly reconcileProviders: (authority: HermesPortableUninstallAuthority) => void; + readonly reconcileProviders: ( + authority: HermesPortableUninstallAuthority, + ) => void | Promise; readonly reconcileInference: (authority: HermesPortableUninstallAuthority) => void; readonly verifyResourcesAbsent: (authority: HermesPortableUninstallAuthority) => void; readonly retireRegistry: (authority: HermesPortableUninstallAuthority) => void; @@ -45,10 +47,10 @@ export interface HermesPortableUninstallTransactionResult { } /** Run or resume the exact schema-5 transaction after its lifecycle and registry locks are held. */ -export function runHermesPortableUninstallTransaction( +export async function runHermesPortableUninstallTransaction( stateDir: string, deps: HermesPortableUninstallTransactionDeps, -): HermesPortableUninstallTransactionResult { +): Promise { const journalStore = deps.journalStore ?? createHermesPortableUninstallJournalStore(stateDir); let journal = journalStore.read(); if (!journal) journal = journalStore.publishPrepared(deps.prepare()); @@ -80,7 +82,7 @@ export function runHermesPortableUninstallTransaction( } if (phase === "sandboxes-retired") { deps.revalidateResources(journal.authority, phase); - deps.reconcileProviders(journal.authority); + await deps.reconcileProviders(journal.authority); deps.afterPhaseAction?.(phase); journal = journalStore.replacePhase(journal, "providers-retired"); continue; diff --git a/src/lib/actions/uninstall/hermes-portable-uninstall.test.ts b/src/lib/actions/uninstall/hermes-portable-uninstall.test.ts index 94f60a40de0..b33845374f2 100644 --- a/src/lib/actions/uninstall/hermes-portable-uninstall.test.ts +++ b/src/lib/actions/uninstall/hermes-portable-uninstall.test.ts @@ -30,9 +30,9 @@ import { inspectHermesPortableUninstallJournal } from "./hermes-portable-uninsta let homeDir: string; let fixture: HermesPortableUninstallFixture | undefined; -function runCleanup(target: HermesPortableUninstallFixture) { +async function runCleanup(target: HermesPortableUninstallFixture) { const legacyOpenShell = vi.fn(() => true); - const result = runPortableRuntimeCleanupTransaction(target.cleanupInput, legacyOpenShell, { + const result = await runPortableRuntimeCleanupTransaction(target.cleanupInput, legacyOpenShell, { hermesPortable: target.deps, withRegistryLock: (_registryFile, operation) => operation(), }); @@ -58,7 +58,7 @@ describe("Hermes Portable schema-5 uninstall", () => { expect(fixture.targetRow.credentialEnv).toBeNull(); expect(fixture.targetRow.hostLocalInferenceReceipt).toEqual(expect.any(String)); expect(fixture.targetRow.hostLocalInferenceProvenance).toBeUndefined(); - expect(runCleanup(fixture)).toMatchObject({ + expect(await runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 1, selectorsRemoved: [], }); @@ -78,7 +78,7 @@ describe("Hermes Portable schema-5 uninstall", () => { const eventCount = fixture.operationEvents.length; const providerCallCount = fixture.gatewayProvider.calls().length; - expect(runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 0 }); + expect(await runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 0 }); expect(fixture.operationEvents).toHaveLength(eventCount); expect(fixture.gatewayProvider.calls()).toHaveLength(providerCallCount); expect(fixture.sandboxDeleteCount()).toBe(1); @@ -109,7 +109,9 @@ describe("Hermes Portable schema-5 uninstall", () => { }, }); - expect(() => runCleanup(fixture!)).toThrow("registry row 'portable-hermes' is incomplete"); + await expect(async () => await runCleanup(fixture!)).rejects.toThrow( + "registry row 'portable-hermes' is incomplete", + ); expect(fixture.sandboxDeleteCount()).toBe(0); expect(fixture.gatewayProvider.isPresent()).toBe(true); expect(fixture.harness.container()).not.toBeNull(); @@ -119,12 +121,12 @@ describe("Hermes Portable schema-5 uninstall", () => { it("replaces completed journal authority after a later install (#9608)", async () => { fixture = await createHermesPortableUninstallFixture(homeDir); - expect(runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 1 }); + expect(await runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 1 }); const firstAuthority = inspectHermesPortableUninstallJournal(fixture.stateDir)?.authoritySha256; fixture.restore(); fixture = await createHermesPortableUninstallFixture(homeDir); - expect(runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 1 }); + expect(await runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 1 }); expect(inspectHermesPortableUninstallJournal(fixture.stateDir)?.authoritySha256).not.toBe( firstAuthority, ); @@ -135,7 +137,9 @@ describe("Hermes Portable schema-5 uninstall", () => { fixture = await createHermesPortableUninstallFixture(homeDir, { interruptAfter: "receipts-retired", }); - expect(() => runCleanup(fixture!)).toThrow("interrupted after receipts-retired"); + await expect(async () => await runCleanup(fixture!)).rejects.toThrow( + "interrupted after receipts-retired", + ); const blockedOperation = vi.fn(); await expect( @@ -179,7 +183,7 @@ describe("Hermes Portable schema-5 uninstall", () => { expect(replacementOnboarding.events).toEqual(["lock-enter", "lock-exit"]); expect(replacementInput.buildContext.assertCurrentSource).not.toHaveBeenCalled(); - expect(runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 0 }); + expect(await runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 0 }); expect(inspectHermesPortableUninstallJournal(fixture.stateDir)?.phase).toBe("completed"); expect(() => assertHermesPortableUninstallCompleteForOnboarding(fixture!.stateDir), @@ -190,14 +194,14 @@ describe("Hermes Portable schema-5 uninstall", () => { lifecycleGeneration: "generation-2", }); expect(fixture.targetRow.lifecycleGeneration).toBe("generation-2"); - expect(runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 1 }); + expect(await runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 1 }); expect(inspectHermesPortableUninstallJournal(fixture.stateDir)?.phase).toBe("completed"); }); it("preserves a provider, inference runtime, and recovery evidence shared by a sibling (#9608)", async () => { fixture = await createHermesPortableUninstallFixture(homeDir, { shared: true }); - expect(runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 1 }); + expect(await runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 1 }); expect(fixture.gatewayProvider.isPresent()).toBe(true); expect(fixture.harness.container()).not.toBeNull(); expect(fs.existsSync(fixture.inferenceDirectory)).toBe(true); @@ -208,7 +212,7 @@ describe("Hermes Portable schema-5 uninstall", () => { ]); const eventCount = fixture.operationEvents.length; - expect(runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 0 }); + expect(await runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 0 }); expect(fixture.operationEvents).toHaveLength(eventCount); expect(fixture.gatewayProvider.isPresent()).toBe(true); expect(fixture.harness.container()).not.toBeNull(); @@ -219,7 +223,7 @@ describe("Hermes Portable schema-5 uninstall", () => { providerOnlyShared: true, }); - expect(runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 1 }); + expect(await runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 1 }); expect(fixture.gatewayProvider.isPresent()).toBe(true); expect(fixture.harness.container()).toBeNull(); expect(fs.existsSync(fixture.inferenceDirectory)).toBe(true); @@ -228,7 +232,7 @@ describe("Hermes Portable schema-5 uninstall", () => { ]); const eventCount = fixture.operationEvents.length; - expect(runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 0 }); + expect(await runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 0 }); expect(fixture.operationEvents).toHaveLength(eventCount); expect(fixture.gatewayProvider.isPresent()).toBe(true); expect(fixture.harness.container()).toBeNull(); @@ -245,13 +249,15 @@ describe("Hermes Portable schema-5 uninstall", () => { ] as const)("resumes the real transaction after the %s action (#9608)", async (phase) => { fixture = await createHermesPortableUninstallFixture(homeDir, { interruptAfter: phase }); - expect(() => runCleanup(fixture!)).toThrow(`interrupted after ${phase}`); + await expect(async () => await runCleanup(fixture!)).rejects.toThrow( + `interrupted after ${phase}`, + ); expect(inspectHermesPortableUninstallJournal(fixture.stateDir)?.phase).toBe(phase); - expect(runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 0 }); + expect(await runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 0 }); expect(inspectHermesPortableUninstallJournal(fixture.stateDir)?.phase).toBe("completed"); const eventCount = fixture.operationEvents.length; - expect(runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 0 }); + expect(await runCleanup(fixture)).toMatchObject({ sandboxContainersRemoved: 0 }); expect(fixture.operationEvents).toHaveLength(eventCount); expect(fixture.sandboxDeleteCount()).toBe(1); expect( @@ -284,7 +290,7 @@ describe("Hermes Portable schema-5 uninstall", () => { fixture = await createHermesPortableUninstallFixture(homeDir); mutate(fixture); - expect(() => runCleanup(fixture!)).toThrow(message); + await expect(async () => await runCleanup(fixture!)).rejects.toThrow(message); expect(fixture.sandboxDeleteCount()).toBe(0); expect(fixture.gatewayProvider.isPresent()).toBe(true); expect(fixture.harness.container()).not.toBeNull(); @@ -296,9 +302,13 @@ describe("Hermes Portable schema-5 uninstall", () => { interruptAfter: "prepared", }); - expect(() => runCleanup(fixture!)).toThrow("interrupted after prepared"); + await expect(async () => await runCleanup(fixture!)).rejects.toThrow( + "interrupted after prepared", + ); fixture.replaceSandbox(); - expect(() => runCleanup(fixture!)).toThrow("OpenShell sandbox identity disagrees"); + await expect(async () => await runCleanup(fixture!)).rejects.toThrow( + "OpenShell sandbox identity disagrees", + ); expect(fixture.sandboxDeleteCount()).toBe(1); expect(fixture.gatewayProvider.isPresent()).toBe(true); expect(fixture.harness.container()).not.toBeNull(); @@ -330,7 +340,7 @@ describe("Hermes Portable schema-5 uninstall", () => { fixture = await createHermesPortableUninstallFixture(homeDir); fixture[mutate](); - expect(() => runCleanup(fixture!)).toThrow(message); + await expect(async () => await runCleanup(fixture!)).rejects.toThrow(message); expect(fixture.sandboxDeleteCount()).toBe(0); expect(fixture.gatewayProvider.isPresent()).toBe(true); expect(fixture.harness.container()).not.toBeNull(); @@ -343,7 +353,7 @@ describe("Hermes Portable schema-5 uninstall", () => { fixture = await createHermesPortableUninstallFixture(homeDir); fs.chmodSync(fixture.inferenceDirectory, 0o755); - expect(() => runCleanup(fixture!)).toThrow( + await expect(async () => await runCleanup(fixture!)).rejects.toThrow( "Hermes Portable inference gateway provider journal directory lacks private authority", ); expect(fs.statSync(fixture.inferenceDirectory).mode & 0o777).toBe(0o755); @@ -355,7 +365,9 @@ describe("Hermes Portable schema-5 uninstall", () => { fixture = await createHermesPortableUninstallFixture(homeDir); fs.rmSync(fixture.inferenceDirectory, { recursive: true }); - expect(() => runCleanup(fixture!)).toThrow("authority directory is missing"); + await expect(async () => await runCleanup(fixture!)).rejects.toThrow( + "authority directory is missing", + ); expect(fs.existsSync(fixture.inferenceDirectory)).toBe(false); expect(fixture.sandboxDeleteCount()).toBe(0); expect(inspectHermesPortableUninstallJournal(fixture.stateDir)).toBeNull(); @@ -366,9 +378,11 @@ describe("Hermes Portable schema-5 uninstall", () => { interruptAfter: "prepared", }); - expect(() => runCleanup(fixture!)).toThrow("interrupted after prepared"); + await expect(async () => await runCleanup(fixture!)).rejects.toThrow( + "interrupted after prepared", + ); fixture.gatewayProvider.setPresent(false); - expect(() => runCleanup(fixture!)).toThrow( + await expect(async () => await runCleanup(fixture!)).rejects.toThrow( "gateway provider disappeared before uninstall journaled it", ); expect(inspectHermesPortableUninstallJournal(fixture.stateDir)?.phase).toBe("prepared"); @@ -381,10 +395,12 @@ describe("Hermes Portable schema-5 uninstall", () => { async (phase) => { fixture = await createHermesPortableUninstallFixture(homeDir, { interruptAfter: phase }); - expect(() => runCleanup(fixture!)).toThrow(`interrupted after ${phase}`); + await expect(async () => await runCleanup(fixture!)).rejects.toThrow( + `interrupted after ${phase}`, + ); const containerId = fixture.harness.container()!.id; expect(fixture.harness.engine.capture(["rm", "--force", containerId], 1_000).status).toBe(0); - expect(() => runCleanup(fixture!)).toThrow( + await expect(async () => await runCleanup(fixture!)).rejects.toThrow( "Podman host-local inference container inspection failed", ); expect(inspectHermesPortableUninstallJournal(fixture.stateDir)?.phase).toBe(phase); diff --git a/src/lib/actions/uninstall/hermes-portable-uninstall.ts b/src/lib/actions/uninstall/hermes-portable-uninstall.ts index 738b9c07dbc..e3a13c0bef4 100644 --- a/src/lib/actions/uninstall/hermes-portable-uninstall.ts +++ b/src/lib/actions/uninstall/hermes-portable-uninstall.ts @@ -475,10 +475,10 @@ function requireCache(cache: LoadedAuthority | null): LoadedAuthority { } /** Run schema-5 cleanup after the host fence, sorted lifecycle locks, and registry lock. */ -export function runHermesPortableUninstall( +export async function runHermesPortableUninstall( input: HermesPortableUninstallInput, deps: HermesPortableUninstallDeps = {}, -): HermesPortableUninstallTransactionResult { +): Promise { let cache: LoadedAuthority | null = null; return runHermesPortableUninstallTransaction(input.stateDir, { prepare: () => { @@ -501,10 +501,10 @@ export function runHermesPortableUninstall( } return removed; }, - reconcileProviders: () => { + reconcileProviders: async () => { for (const target of requireCache(cache).targets) { if (target.authority.provider.disposition === "remove") { - target.provider.removeAndVerify(); + await target.provider.removeAndVerify(); } } }, diff --git a/src/lib/actions/uninstall/openrouter-runtime-adapter-cleanup.test.ts b/src/lib/actions/uninstall/openrouter-runtime-adapter-cleanup.test.ts index 4f7163acaf5..5cadf1eded8 100644 --- a/src/lib/actions/uninstall/openrouter-runtime-adapter-cleanup.test.ts +++ b/src/lib/actions/uninstall/openrouter-runtime-adapter-cleanup.test.ts @@ -23,8 +23,8 @@ function notFound(): RunResult { return { status: 1, stdout: "", stderr: "" }; } -function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { - return runUninstallPlanBase(options, { +async function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { + return await runUninstallPlanBase(options, { resolveGatewayTeardownAuthority: ({ gatewayName, gatewayPort }) => ({ gatewayName, gatewayPort, @@ -182,7 +182,7 @@ function lsofPortStub(ports: string[], portPids: Map) { describe("runtime adapter uninstall cleanup", () => { it.each(RUNTIME_ADAPTERS)( "stops $label from its persisted PID before state removal$issueSuffix", - ({ cmdline, label, persistedPid, pidFile: pidFilename }) => { + async ({ cmdline, label, persistedPid, pidFile: pidFilename }) => { const logs: string[] = []; const killed: number[] = []; const exited = new Set(); @@ -197,7 +197,7 @@ describe("runtime adapter uninstall cleanup", () => { } try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -241,7 +241,7 @@ describe("runtime adapter uninstall cleanup", () => { }, ); - it("stops the uninstall plan before State cleanup when Bedrock TERM and KILL do not exit (#9552)", () => { + it("stops the uninstall plan before State cleanup when Bedrock TERM and KILL do not exit (#9552)", async () => { const tmpHome = fs.mkdtempSync( path.join(os.tmpdir(), "nemoclaw-uninstall-bedrock-exhaustion-"), ); @@ -251,7 +251,7 @@ describe("runtime adapter uninstall cleanup", () => { writeBedrockEvidence(tmpHome, 45_552, BEDROCK_RUNTIME_ADAPTER_CMDLINE); try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -307,12 +307,12 @@ describe("runtime adapter uninstall cleanup", () => { it.each(RUNTIME_ADAPTERS.filter(({ pidFile }) => pidFile !== "bedrock-runtime-adapter.pid"))( "stops an owned $label orphan on its configured port$issueSuffix", - ({ cmdline, customPort, defaultPort, envPort, label, orphanPid }) => { + async ({ cmdline, customPort, defaultPort, envPort, label, orphanPid }) => { const logs: string[] = []; const killed: number[] = []; const exited = new Set(); const lsofPorts: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -351,7 +351,7 @@ describe("runtime adapter uninstall cleanup", () => { it.each(RUNTIME_ADAPTERS)( "does not signal an unrelated process on the $label port$issueSuffix", - ({ defaultPort, foreignPid, label }) => { + async ({ defaultPort, foreignPid, label }) => { const logs: string[] = []; const killed: number[] = []; const lsofPorts: string[] = []; @@ -359,7 +359,7 @@ describe("runtime adapter uninstall cleanup", () => { exited: new Set(), cmdline: "/usr/sbin/nginx -g daemon off;\n", }); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -393,7 +393,7 @@ describe("runtime adapter uninstall cleanup", () => { }, ); - it("fails closed on incomplete Bedrock PID evidence before process or port discovery (#9552)", () => { + it("fails closed on incomplete Bedrock PID evidence before process or port discovery (#9552)", async () => { const foreignPid = 99995; const killed: number[] = []; const lsofPorts: string[] = []; @@ -408,7 +408,7 @@ describe("runtime adapter uninstall cleanup", () => { }); try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, diff --git a/src/lib/actions/uninstall/portable-runtime-cleanup-schema5.test.ts b/src/lib/actions/uninstall/portable-runtime-cleanup-schema5.test.ts index 949e1b00fba..2e009791586 100644 --- a/src/lib/actions/uninstall/portable-runtime-cleanup-schema5.test.ts +++ b/src/lib/actions/uninstall/portable-runtime-cleanup-schema5.test.ts @@ -8,13 +8,13 @@ import { describe, expect, it, vi } from "vitest"; import { runPortableRuntimeCleanupTransaction } from "./portable-runtime-cleanup"; describe("Hermes Portable runtime uninstall cleanup", () => { - it("orders schema-5 lifecycle locks before the process registry lock (#9608)", () => { + it("orders schema-5 lifecycle locks before the process registry lock (#9608)", async () => { const order: string[] = []; const continueLegacyOpenShell = vi.fn(() => true); const homeDir = path.resolve("test", "fixtures", "hermes-portable-uninstall"); let registryHeld = false; - const result = runPortableRuntimeCleanupTransaction( + const result = await runPortableRuntimeCleanupTransaction( { env: {}, gatewayName: "nemoclaw", @@ -26,24 +26,26 @@ describe("Hermes Portable runtime uninstall cleanup", () => { continueLegacyOpenShell, { inspectHermesPortableSandboxNames: () => ["beta", "alpha"], - runHermesPortableUninstall: () => { + runHermesPortableUninstall: async () => { + expect(registryHeld).toBe(true); + await Promise.resolve(); expect(registryHeld).toBe(true); order.push("transaction"); return { phase: "completed", sandboxContainersRemoved: 2, targetCount: 2 }; }, - withLifecycleLock: (sandboxName, operation) => { + withLifecycleLock: async (sandboxName, operation) => { order.push(`acquire:${sandboxName}`); try { - return operation(); + return await operation(); } finally { order.push(`release:${sandboxName}`); } }, - withRegistryLock: (_registryFile, operation) => { + withRegistryLock: async (_registryFile, operation) => { order.push("acquire:registry"); registryHeld = true; try { - return operation(); + return await operation(); } finally { registryHeld = false; order.push("release:registry"); diff --git a/src/lib/actions/uninstall/portable-runtime-cleanup.test-support.ts b/src/lib/actions/uninstall/portable-runtime-cleanup.test-support.ts new file mode 100644 index 00000000000..a52d7480ab0 --- /dev/null +++ b/src/lib/actions/uninstall/portable-runtime-cleanup.test-support.ts @@ -0,0 +1,44 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export const RETIREMENT_COMPETITOR_SCRIPT = String.raw` + import fs from "node:fs"; + const [lifecycleUrl, registryUrl, stateDir, registryFile, receiptFile, marker, sandboxName, control] = process.argv.slice(1); + const lifecycleModule = await import(lifecycleUrl); + const registryModule = await import(registryUrl); + const lifecycle = lifecycleModule.default ?? lifecycleModule; + const registry = registryModule.default ?? registryModule; + if (typeof lifecycle.withMcpLifecycleLockSync !== "function" || + typeof registry.withRegistryLockAt !== "function") process.exit(3); + const attempt = (owner) => { + const mutate = () => { + fs.writeFileSync(marker, "entered"); + fs.unlinkSync(receiptFile); + }; + try { + if (owner === "registry-only") { + registry.withRegistryLockAt(registryFile, mutate, { maxRetries: 2, wait: () => {} }); + } else { + lifecycle.withMcpLifecycleLockSync(owner, () => registry.withRegistryLockAt( + registryFile, + mutate, + { maxRetries: 2, wait: () => {} }, + ), { stateDir, pollIntervalMs: 1, timeoutMs: 1_000 }); + } + return 0; + } catch (error) { + if (error?.name === "ProcessBoundLockContentionError" || + (error instanceof Error && error.message.startsWith("Timed out waiting for the sandbox mutation lock for '"))) return 2; + console.error(error); + return 3; + } + }; + if (!control) process.exit(attempt(sandboxName)); + fs.writeFileSync(control + ".ready", "ready"); + while (!fs.existsSync(control + ".trigger")) await new Promise(resolve => setTimeout(resolve, 1)); + const resultPayload = JSON.stringify([attempt(sandboxName), attempt("registry-only")]); + const resultTmp = control + ".result.tmp"; + fs.writeFileSync(resultTmp, resultPayload); + fs.renameSync(resultTmp, control + ".result"); + process.exit(0); +`; diff --git a/src/lib/actions/uninstall/portable-runtime-cleanup.test.ts b/src/lib/actions/uninstall/portable-runtime-cleanup.test.ts index 12cee9bf411..cbbf526d998 100644 --- a/src/lib/actions/uninstall/portable-runtime-cleanup.test.ts +++ b/src/lib/actions/uninstall/portable-runtime-cleanup.test.ts @@ -10,7 +10,7 @@ import { afterAll, afterEach, assert, beforeAll, describe, expect, it, vi } from import type { CheckpointPortableRuntimeAuthority } from "../../state/onboard-checkpoint-types"; import { createSession } from "../../state/onboard-session"; -import { withMcpLifecycleLockSync } from "../../state/mcp-lifecycle-lock-acquisition"; +import { withMcpLifecycleLock } from "../../state/mcp-lifecycle-lock-acquisition"; import { hasPortableRetirementRecord, inspectPortableRetirementRecovery, @@ -25,7 +25,7 @@ import { import { listPortableDemoSandboxLifecycleReceipts } from "../../onboard/experimental/portable-demo-lifecycle"; import { portableDemoReceiptPath } from "../../onboard/experimental/portable-runtime-receipt-readiness"; import { - withProcessBoundRegistryLockAt, + withProcessBoundRegistryLockAtAsync, withRegistryLockAt, type RegistryLockDeps, } from "../../state/registry/lock"; @@ -35,6 +35,7 @@ import { type PortableRuntimeCleanupDeps, type PortableRuntimeCleanupInput, } from "./portable-runtime-cleanup"; +import { RETIREMENT_COMPETITOR_SCRIPT } from "./portable-runtime-cleanup.test-support"; const UID = process.getuid?.() ?? 1001; const ALPHA_ID = "a".repeat(64); @@ -51,41 +52,6 @@ interface ContainerRecord { const temporaryDirectories: string[] = []; -const RETIREMENT_COMPETITOR_SCRIPT = String.raw` - import fs from "node:fs"; - const [lifecycleUrl, registryUrl, stateDir, registryFile, receiptFile, marker, sandboxName, control] = process.argv.slice(1); - const lifecycle = (await import(lifecycleUrl)).default; - const registry = (await import(registryUrl)).default; - const attempt = (owner) => { - const mutate = () => { - fs.writeFileSync(marker, "entered"); - fs.unlinkSync(receiptFile); - }; - try { - if (owner === "registry-only") { - registry.withRegistryLockAt(registryFile, mutate, { maxRetries: 2, wait: () => {} }); - } else { - lifecycle.withMcpLifecycleLockSync(owner, () => registry.withRegistryLockAt( - registryFile, - mutate, - { maxRetries: 2, wait: () => {} }, - ), { stateDir, pollIntervalMs: 1, timeoutMs: 10 }); - } - return 0; - } catch { - return 2; - } - }; - if (!control) process.exit(attempt(sandboxName)); - fs.writeFileSync(control + ".ready", "ready"); - while (!fs.existsSync(control + ".trigger")) await new Promise(resolve => setTimeout(resolve, 1)); - const resultPayload = JSON.stringify([attempt(sandboxName), attempt("registry-only")]); - const resultTmp = control + ".result.tmp"; - fs.writeFileSync(resultTmp, resultPayload); - fs.renameSync(resultTmp, control + ".result"); - process.exit(0); -`; - function fixture() { const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-portable-uninstall-")); temporaryDirectories.push(homeDir); @@ -328,8 +294,11 @@ function fixture() { }; } -function completeCleanup(input: PortableRuntimeCleanupInput, deps: PortableRuntimeCleanupDeps) { - return runPortableRuntimeCleanupTransaction(input, () => true, deps); +async function completeCleanup( + input: PortableRuntimeCleanupInput, + deps: PortableRuntimeCleanupDeps, +) { + return await runPortableRuntimeCleanupTransaction(input, () => true, deps); } type PodmanObservation = ReturnType>; @@ -363,7 +332,7 @@ function authorityDeps(test: ReturnType) { listReceipts: listPortableDemoSandboxLifecycleReceipts, loadRegistry: () => JSON.parse(fs.readFileSync(test.registryFile, "utf8")), withLifecycleLock: async (sandboxName: string, operation: () => Promise | T) => - await withMcpLifecycleLockSync(sandboxName, operation, { + await withMcpLifecycleLock(sandboxName, operation, { stateDir: path.join(test.stateDir, "state"), }), }; @@ -753,7 +722,7 @@ describe("portable runtime uninstall cleanup", () => { const originalLoad = scope.authority.deps.loadRegistry; const loadRegistry = () => { fs.writeFileSync(`${control}.trigger`, "trigger"); - const deadline = Date.now() + 1_000; + const deadline = Date.now() + 5_000; while (!fs.existsSync(`${control}.result`) && Date.now() < deadline) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1); expect(JSON.parse(fs.readFileSync(`${control}.result`, "utf8"))).toEqual([2, 2]); @@ -932,11 +901,11 @@ describe("portable runtime uninstall cleanup", () => { }, ); - it("removes only exact receipt-owned containers and exact current selector projections (#9189)", () => { + it("removes only exact receipt-owned containers and exact current selector projections (#9189)", async () => { const test = fixture(); expect(hasPortableRuntimeCleanup(test.stateDir)).toBe(true); - const cleanup = completeCleanup(test.input, test.deps); + const cleanup = await completeCleanup(test.input, test.deps); expect(cleanup).toEqual({ registryRemoved: true, @@ -963,13 +932,13 @@ describe("portable runtime uninstall cleanup", () => { expect(fs.existsSync(`${test.registryFile}.lock`)).toBe(false); }); - it("retries one failed read-only sandbox discovery under reasserted authority (#9499)", () => { + it("retries one failed read-only sandbox discovery under reasserted authority (#9499)", async () => { const test = fixture(); const observations = interceptSandboxDiscoveries(test, [ { status: 125, stdout: "", stderr: "transient local Podman observation failure" }, ]); - expect(completeCleanup(test.input, test.deps)).toEqual({ + expect(await completeCleanup(test.input, test.deps)).toEqual({ registryRemoved: true, sandboxContainersRemoved: 1, selectorsRemoved: ["CONTAINERS_CONF", "NETAVARK_FW"], @@ -981,11 +950,11 @@ describe("portable runtime uninstall cleanup", () => { it.each([ ["non-125 status", { status: 126, stdout: "", stderr: "permission denied" }], ["spawn error", { status: null, stdout: "", stderr: "", error: new Error("spawn EACCES") }], - ] as const)("does not retry a %s sandbox discovery failure (#9499)", (_label, failure) => { + ] as const)("does not retry a %s sandbox discovery failure (#9499)", async (_label, failure) => { const test = fixture(); const observations = interceptSandboxDiscoveries(test, [failure]); - expect(() => completeCleanup(test.input, test.deps)).toThrow( + await expect(async () => await completeCleanup(test.input, test.deps)).rejects.toThrow( "Finding portable sandbox 'alpha' failed", ); expect(observations()).toBe(1); @@ -994,7 +963,7 @@ describe("portable runtime uninstall cleanup", () => { expect(test.podmanCalls.some((args) => args[0] === "rm")).toBe(false); }); - it("stops a status-125 retry when socket authority changes before re-observation (#9499)", () => { + it("stops a status-125 retry when socket authority changes before re-observation (#9499)", async () => { const test = fixture(); let authorityChanged = false; const authorityError = "Podman socket authority changed after it was qualified"; @@ -1012,7 +981,9 @@ describe("portable runtime uninstall cleanup", () => { }, ]); - expect(() => completeCleanup(test.input, test.deps)).toThrow(authorityError); + await expect(async () => await completeCleanup(test.input, test.deps)).rejects.toThrow( + authorityError, + ); expect(observations()).toBe(1); expect(assertSocketAuthority).toHaveBeenCalled(); expect(test.containers.has(ALPHA_ID)).toBe(true); @@ -1020,7 +991,7 @@ describe("portable runtime uninstall cleanup", () => { expect(test.podmanCalls.some((args) => args[0] === "rm")).toBe(false); }); - it("stops without mutation after two failed read-only sandbox discoveries (#9499)", () => { + it("stops without mutation after two failed read-only sandbox discoveries (#9499)", async () => { const test = fixture(); const failure = { status: 125, @@ -1029,7 +1000,7 @@ describe("portable runtime uninstall cleanup", () => { }; const observations = interceptSandboxDiscoveries(test, [failure, failure]); - expect(() => completeCleanup(test.input, test.deps)).toThrow( + await expect(async () => await completeCleanup(test.input, test.deps)).rejects.toThrow( "Finding portable sandbox 'alpha' failed", ); expect(observations()).toBe(2); @@ -1038,12 +1009,12 @@ describe("portable runtime uninstall cleanup", () => { expect(test.podmanCalls.some((args) => args[0] === "rm")).toBe(false); }); - it("preserves changed current-user manager selector values (#9189)", () => { + it("preserves changed current-user manager selector values (#9189)", async () => { const test = fixture(); test.selectors.set("CONTAINERS_CONF", "/home/test/user-containers.conf"); test.selectors.set("NETAVARK_FW", "nftables"); - expect(completeCleanup(test.input, test.deps)).toEqual({ + expect(await completeCleanup(test.input, test.deps)).toEqual({ registryRemoved: true, sandboxContainersRemoved: 1, selectorsRemoved: [], @@ -1052,7 +1023,7 @@ describe("portable runtime uninstall cleanup", () => { expect(test.selectors.get("NETAVARK_FW")).toBe("nftables"); }); - it("prevalidates every receipt before deleting the first container (#9189)", () => { + it("prevalidates every receipt before deleting the first container (#9189)", async () => { const test = fixture(); test.writeReceipt("beta", BETA_ID, "sandbox-beta"); test.addSandbox("beta", "sandbox-beta", BETA_ID, { "openshell.managed": "false" }); @@ -1069,7 +1040,7 @@ describe("portable runtime uninstall cleanup", () => { }; fs.writeFileSync(test.registryFile, `${JSON.stringify(registry)}\n`); - expect(() => completeCleanup(test.input, test.deps)).toThrow( + await expect(async () => await completeCleanup(test.input, test.deps)).rejects.toThrow( /OpenShell identity does not match sandbox 'beta'/, ); expect(test.containers.has(ALPHA_ID)).toBe(true); @@ -1127,11 +1098,13 @@ describe("portable runtime uninstall cleanup", () => { }, /conflicting gateway identity/, ], - ])("rejects a %s registry row before any mutation (#9189)", (_case, prepare, expected) => { + ])("rejects a %s registry row before any mutation (#9189)", async (_case, prepare, expected) => { const test = fixture(); prepare(test); - expect(() => completeCleanup(test.input, test.deps)).toThrow(expected); + await expect(async () => await completeCleanup(test.input, test.deps)).rejects.toThrow( + expected, + ); expect(test.containers.has(ALPHA_ID)).toBe(true); expect(test.containers.has(REGISTRY_ID)).toBe(true); expect(test.selectors.has("CONTAINERS_CONF")).toBe(true); @@ -1139,14 +1112,16 @@ describe("portable runtime uninstall cleanup", () => { expect(test.podmanCalls.some((args) => args[0] === "rm")).toBe(false); }); - it("preserves shared portable evidence when exact OpenShell retirement fails (#9189)", () => { + it("preserves shared portable evidence when exact OpenShell retirement fails (#9189)", async () => { const test = fixture(); const configMarker = path.join(test.homeDir, ".config", "nemoclaw", "keep-for-retry"); fs.mkdirSync(path.dirname(configMarker), { recursive: true }); fs.writeFileSync(configMarker, "retry\n"); const retireOpenShell = vi.fn(() => false); - expect(runPortableRuntimeCleanupTransaction(test.input, retireOpenShell, test.deps)).toBeNull(); + expect( + await runPortableRuntimeCleanupTransaction(test.input, retireOpenShell, test.deps), + ).toBeNull(); expect(retireOpenShell).toHaveBeenCalledWith(1, ["alpha"], "nemoclaw"); expect(test.containers.has(ALPHA_ID)).toBe(false); expect(test.containers.has(REGISTRY_ID)).toBe(true); @@ -1157,7 +1132,7 @@ describe("portable runtime uninstall cleanup", () => { expect(fs.existsSync(test.stateDir)).toBe(true); }); - it("holds sorted lifecycle locks before the registry lock and releases in reverse (#9189)", () => { + it("holds sorted lifecycle locks before the registry lock and releases in reverse (#9189)", async () => { const test = fixture(); const order: string[] = []; test.writeReceipt("beta", BETA_ID, "sandbox-beta"); @@ -1176,20 +1151,20 @@ describe("portable runtime uninstall cleanup", () => { fs.writeFileSync(test.registryFile, `${JSON.stringify(registry)}\n`); expect( - runPortableRuntimeCleanupTransaction(test.input, () => true, { + await runPortableRuntimeCleanupTransaction(test.input, () => true, { ...test.deps, - withLifecycleLock: (sandboxName, operation) => { + withLifecycleLock: async (sandboxName, operation) => { order.push(`acquire:${sandboxName}`); try { - return operation(); + return await operation(); } finally { order.push(`release:${sandboxName}`); } }, - withRegistryLock: (_registryFile, operation) => { + withRegistryLock: async (_registryFile, operation) => { order.push("acquire:registry"); try { - return operation(); + return await operation(); } finally { order.push("release:registry"); } @@ -1206,7 +1181,7 @@ describe("portable runtime uninstall cleanup", () => { ]); }); - it("runs final evidence retirement while both production lock primitives are held (#9189)", () => { + it("runs final evidence retirement while both production lock primitives are held (#9189)", async () => { const test = fixture(); const lifecycleStateDir = path.join(test.stateDir, "state"); const lockDeps: RegistryLockDeps = { @@ -1222,16 +1197,16 @@ describe("portable runtime uninstall cleanup", () => { }); expect( - runPortableRuntimeCleanupTransaction(test.input, () => true, { + await runPortableRuntimeCleanupTransaction(test.input, () => true, { ...test.deps, publishRetirement: retireEvidence, withLifecycleLock: (sandboxName, operation, stateDir) => - withMcpLifecycleLockSync( + withMcpLifecycleLock( sandboxName, - () => { + async () => { lifecycleHeld = true; try { - return operation(); + return await operation(); } finally { lifecycleHeld = false; } @@ -1239,12 +1214,12 @@ describe("portable runtime uninstall cleanup", () => { { stateDir }, ), withRegistryLock: (registryFile, operation) => - withProcessBoundRegistryLockAt( + withProcessBoundRegistryLockAtAsync( registryFile, - () => { + async () => { registryHeld = true; try { - return operation(); + return await operation(); } finally { registryHeld = false; } @@ -1259,7 +1234,7 @@ describe("portable runtime uninstall cleanup", () => { expect(fs.existsSync(path.join(lifecycleStateDir, "mcp-lifecycle-locks"))).toBe(true); }); - it("preserves receipts and selectors when exact container removal cannot be verified (#9189)", () => { + it("preserves receipts and selectors when exact container removal cannot be verified (#9189)", async () => { const test = fixture(); test.deps.podman = vi.fn((rawArgs: readonly string[], env?: NodeJS.ProcessEnv) => { const args = rawArgs[0] === "--url" ? rawArgs.slice(2) : rawArgs; @@ -1268,12 +1243,14 @@ describe("portable runtime uninstall cleanup", () => { : test.podman(rawArgs, env); }); - expect(() => completeCleanup(test.input, test.deps)).toThrow(/still has/); + await expect(async () => await completeCleanup(test.input, test.deps)).rejects.toThrow( + /still has/, + ); expect(test.systemctlCalls.some((args) => args[1] === "unset-environment")).toBe(false); expect(fs.existsSync(portableDemoReceiptPath("alpha", test.stateDir))).toBe(true); }); - it("preserves retry evidence when managed registry removal fails (#9189)", () => { + it("preserves retry evidence when managed registry removal fails (#9189)", async () => { const test = fixture(); const failingDeps: PortableRuntimeCleanupDeps = { ...test.deps, @@ -1285,21 +1262,21 @@ describe("portable runtime uninstall cleanup", () => { }), }; - expect(() => completeCleanup(test.input, failingDeps)).toThrow( + await expect(async () => await completeCleanup(test.input, failingDeps)).rejects.toThrow( /Removing the managed portable registry container failed: registry removal denied/, ); expect(test.containers.has(REGISTRY_ID)).toBe(true); expect(test.systemctlCalls.some((args) => args[1] === "unset-environment")).toBe(false); expect(fs.existsSync(portableDemoReceiptPath("alpha", test.stateDir))).toBe(true); - expect(completeCleanup(test.input, test.deps)).toEqual({ + expect(await completeCleanup(test.input, test.deps)).toEqual({ registryRemoved: true, sandboxContainersRemoved: 0, selectorsRemoved: ["CONTAINERS_CONF", "NETAVARK_FW"], }); }); - it("retries selector cleanup after the managed registry was already removed (#9189)", () => { + it("retries selector cleanup after the managed registry was already removed (#9189)", async () => { const test = fixture(); const systemctl = test.deps.systemctl!; const failingDeps: PortableRuntimeCleanupDeps = { @@ -1311,23 +1288,23 @@ describe("portable runtime uninstall cleanup", () => { ), }; - expect(() => completeCleanup(test.input, failingDeps)).toThrow( + await expect(async () => await completeCleanup(test.input, failingDeps)).rejects.toThrow( /Clearing NemoClaw portable selectors.*permission denied/, ); expect(test.containers.has(REGISTRY_ID)).toBe(false); expect(fs.existsSync(portableDemoReceiptPath("alpha", test.stateDir))).toBe(true); - expect(completeCleanup(test.input, test.deps)).toEqual({ + expect(await completeCleanup(test.input, test.deps)).toEqual({ registryRemoved: false, sandboxContainersRemoved: 0, selectorsRemoved: ["CONTAINERS_CONF", "NETAVARK_FW"], }); }); - it("accepts an already-absent exact sandbox on retry but rejects a replaced identity (#9189)", () => { + it("accepts an already-absent exact sandbox on retry but rejects a replaced identity (#9189)", async () => { const retry = fixture(); retry.containers.delete(ALPHA_ID); - expect(completeCleanup(retry.input, retry.deps)).toEqual({ + expect(await completeCleanup(retry.input, retry.deps)).toEqual({ registryRemoved: true, sandboxContainersRemoved: 0, selectorsRemoved: ["CONTAINERS_CONF", "NETAVARK_FW"], @@ -1336,22 +1313,24 @@ describe("portable runtime uninstall cleanup", () => { const replaced = fixture(); replaced.containers.delete(ALPHA_ID); replaced.addSandbox("alpha", "sandbox-replacement", BETA_ID); - expect(() => completeCleanup(replaced.input, replaced.deps)).toThrow( + await expect(async () => await completeCleanup(replaced.input, replaced.deps)).rejects.toThrow( /replaced or ambiguous container/, ); }); - it("rejects duplicate containers in the sandbox label index before removal (#9189)", () => { + it("rejects duplicate containers in the sandbox label index before removal (#9189)", async () => { const test = fixture(); test.addSandbox("alpha", "sandbox-duplicate", BETA_ID); - expect(() => completeCleanup(test.input, test.deps)).toThrow(/replaced or ambiguous container/); + await expect(async () => await completeCleanup(test.input, test.deps)).rejects.toThrow( + /replaced or ambiguous container/, + ); expect(test.containers.has(ALPHA_ID)).toBe(true); expect(test.containers.has(BETA_ID)).toBe(true); expect(test.podmanCalls.some((args) => args[0] === "rm")).toBe(false); }); - it("fails closed on malformed receipts and mismatched lifecycle generations (#9189)", () => { + it("fails closed on malformed receipts and mismatched lifecycle generations (#9189)", async () => { const malformed = fixture(); fs.writeFileSync(portableDemoReceiptPath("alpha", malformed.stateDir), "{not-json\n"); expect(() => hasPortableRuntimeCleanup(malformed.stateDir)).toThrow(/malformed/); @@ -1362,13 +1341,13 @@ describe("portable runtime uninstall cleanup", () => { }; registry.sandboxes.alpha.lifecycleGeneration = "different-generation"; fs.writeFileSync(mismatch.registryFile, `${JSON.stringify(registry)}\n`); - expect(() => completeCleanup(mismatch.input, mismatch.deps)).toThrow( + await expect(async () => await completeCleanup(mismatch.input, mismatch.deps)).rejects.toThrow( /current registry ownership/, ); expect(mismatch.containers.has(ALPHA_ID)).toBe(true); }); - it("blocks a destroy-shaped retirement until exact shared cleanup completes (#9189)", () => { + it("blocks a destroy-shaped retirement until exact shared cleanup completes (#9189)", async () => { const test = fixture(); const receiptFile = portableDemoReceiptPath("alpha", test.stateDir); const configMarker = path.join(test.homeDir, ".config", "nemoclaw", "keep-for-retry"); @@ -1383,7 +1362,7 @@ describe("portable runtime uninstall cleanup", () => { }; fs.mkdirSync(path.dirname(configMarker), { recursive: true }); fs.writeFileSync(configMarker, "retry\n"); - const competingDestroy = () => + const competingDestroy = (lifecycleModuleUrl = lifecycleUrl) => spawnSync( process.execPath, [ @@ -1393,7 +1372,7 @@ describe("portable runtime uninstall cleanup", () => { "--input-type=module", "-e", RETIREMENT_COMPETITOR_SCRIPT, - lifecycleUrl, + lifecycleModuleUrl, registryUrl, lifecycleStateDir, test.registryFile, @@ -1404,7 +1383,7 @@ describe("portable runtime uninstall cleanup", () => { { encoding: "utf8" }, ); - const cleanup = runPortableRuntimeCleanupTransaction( + const cleanup = await runPortableRuntimeCleanupTransaction( test.input, () => { expect(competingDestroy().status).toBe(2); @@ -1416,9 +1395,9 @@ describe("portable runtime uninstall cleanup", () => { expect(competingDestroy().status).toBe(2); }, withLifecycleLock: (sandboxName, operation, stateDir) => - withMcpLifecycleLockSync(sandboxName, operation, { stateDir }), + withMcpLifecycleLock(sandboxName, operation, { stateDir }), withRegistryLock: (registryFile, operation) => - withProcessBoundRegistryLockAt(registryFile, operation, lockDeps), + withProcessBoundRegistryLockAtAsync(registryFile, operation, lockDeps), }, ); @@ -1439,9 +1418,13 @@ describe("portable runtime uninstall cleanup", () => { ).toHaveProperty("alpha"); expect(fs.existsSync(configMarker)).toBe(true); expect(fs.existsSync(`${test.registryFile}.lock`)).toBe(false); - }); + expect(competingDestroy("node:fs").status).toBe(3); + expect(competingDestroy()).toMatchObject({ status: 0, stderr: "" }); + expect(fs.existsSync(competitorMarker)).toBe(true); + expect(fs.existsSync(receiptFile)).toBe(false); + }, 20_000); - it("fails before mutation when destroy retires ownership before lock acquisition (#9189)", () => { + it("fails before mutation when destroy retires ownership before lock acquisition (#9189)", async () => { const test = fixture(); const receiptFile = portableDemoReceiptPath("alpha", test.stateDir); const lifecycleLocks = path.join(test.stateDir, "test-pre-acquisition-locks"); @@ -1450,11 +1433,14 @@ describe("portable runtime uninstall cleanup", () => { isProcessAlive: () => true, readProcessIdentity: () => PROCESS_IDENTITY, }; - const withLifecycleLock = (sandboxName: string, operation: () => Value): Value => { + const withLifecycleLock = async ( + sandboxName: string, + operation: () => Value | Promise, + ): Promise => { const lockPath = path.join(lifecycleLocks, sandboxName); fs.mkdirSync(lockPath, { recursive: false }); try { - return operation(); + return await operation(); } finally { fs.rmdirSync(lockPath); } @@ -1473,22 +1459,26 @@ describe("portable runtime uninstall cleanup", () => { lockDeps, ), ); - const acquireAfterRetirement = (sandboxName: string, operation: () => Value): Value => { - retireOwnership(); - return withLifecycleLock(sandboxName, operation); + const acquireAfterRetirement = async ( + sandboxName: string, + operation: () => Value | Promise, + ): Promise => { + await retireOwnership(); + return await withLifecycleLock(sandboxName, operation); }; fs.mkdirSync(lifecycleLocks, { recursive: true }); fs.mkdirSync(path.dirname(configMarker), { recursive: true }); fs.writeFileSync(configMarker, "retry\n"); - expect(() => - runPortableRuntimeCleanupTransaction(test.input, () => true, { - ...test.deps, - withLifecycleLock: acquireAfterRetirement, - withRegistryLock: (registryFile, operation) => - withProcessBoundRegistryLockAt(registryFile, operation, lockDeps), - }), - ).toThrow(/state changed while uninstall acquired its fences/); + await expect( + async () => + await runPortableRuntimeCleanupTransaction(test.input, () => true, { + ...test.deps, + withLifecycleLock: acquireAfterRetirement, + withRegistryLock: (registryFile, operation) => + withProcessBoundRegistryLockAtAsync(registryFile, operation, lockDeps), + }), + ).rejects.toThrow(/state changed while uninstall acquired its fences/); expect(test.containers.has(ALPHA_ID)).toBe(true); expect(test.containers.has(REGISTRY_ID)).toBe(true); expect(test.selectors.has("CONTAINERS_CONF")).toBe(true); diff --git a/src/lib/actions/uninstall/portable-runtime-cleanup.ts b/src/lib/actions/uninstall/portable-runtime-cleanup.ts index bada7b1bfa0..a83a7988484 100644 --- a/src/lib/actions/uninstall/portable-runtime-cleanup.ts +++ b/src/lib/actions/uninstall/portable-runtime-cleanup.ts @@ -9,7 +9,7 @@ import { isDeepStrictEqual } from "node:util"; import type { CheckpointPortableRuntimeAuthority } from "../../state/onboard-checkpoint-types"; import { hasPortableUninstallAuthority } from "../../onboard/portable-retirement-authority"; -import { withMcpLifecycleLockSync } from "../../state/mcp-lifecycle-lock-acquisition"; +import { withMcpLifecycleLock } from "../../state/mcp-lifecycle-lock-acquisition"; import { inspectPortableRetirementRecovery, PORTABLE_RETIREMENT_STATE_ENTRIES, @@ -22,7 +22,7 @@ import { } from "../../state/portable-uninstall-retirement"; export { PORTABLE_RETIREMENT_STATE_ENTRIES, withPortableHostFence }; -import { withProcessBoundRegistryLockAt } from "../../state/registry/lock"; +import { withProcessBoundRegistryLockAtAsync } from "../../state/registry/lock"; import { readGatewayRegistryFile, registryEntryGatewayPort, @@ -84,8 +84,12 @@ export interface PortableRuntimeCleanupDeps extends PortableDemoLifecycleDeps { args: readonly string[], env: NodeJS.ProcessEnv, ) => PortablePodmanLifecycleCommandResult; - readonly withLifecycleLock?: (sandboxName: string, operation: () => T, stateDir: string) => T; - readonly withRegistryLock?: (registryFile: string, operation: () => T) => T; + readonly withLifecycleLock?: ( + sandboxName: string, + operation: () => Promise, + stateDir: string, + ) => Promise; + readonly withRegistryLock?: (registryFile: string, operation: () => Promise) => Promise; readonly inspectRetirement?: (homeDir: string) => PortableRetirementRecovery | null; readonly prepareRetirement?: ( homeDir: string, @@ -129,23 +133,23 @@ function isMissingContainer(result: PortablePodmanLifecycleCommandResult): boole ); } -function withPortableFences( +async function withPortableFences( input: PortableRuntimeCleanupInput, sandboxNames: readonly string[], deps: PortableRuntimeCleanupDeps, - operation: () => T, -): T { + operation: () => T | Promise, +): Promise { const lifecycleStateDir = path.join(input.stateDir, "state"); const withLifecycleLock = deps.withLifecycleLock ?? - ((sandboxName: string, inner: () => Value, stateDir: string) => - withMcpLifecycleLockSync(sandboxName, inner, { stateDir })); - const withRegistryLock = deps.withRegistryLock ?? withProcessBoundRegistryLockAt; - const acquireNext = (index: number): T => { + ((sandboxName: string, inner: () => Promise, stateDir: string) => + withMcpLifecycleLock(sandboxName, inner, { stateDir })); + const withRegistryLock = deps.withRegistryLock ?? withProcessBoundRegistryLockAtAsync; + const acquireNext = async (index: number): Promise => { const sandboxName = sandboxNames[index]; return sandboxName ? withLifecycleLock(sandboxName, () => acquireNext(index + 1), lifecycleStateDir) - : withRegistryLock(input.registryFile, operation); + : withRegistryLock(input.registryFile, async () => operation()); }; return acquireNext(0); } @@ -281,7 +285,7 @@ function recordedRegistrySandboxNames(registryBytes: Buffer): string[] { } /** Remove receipt-owned portable resources under lifecycle and registry locks through retirement. */ -export function runPortableRuntimeCleanupTransaction( +export async function runPortableRuntimeCleanupTransaction( input: PortableRuntimeCleanupInput, continueAfterSandboxRemoval: ( removed: number, @@ -289,7 +293,7 @@ export function runPortableRuntimeCleanupTransaction( gatewayName: string, ) => boolean, deps: PortableRuntimeCleanupDeps = {}, -): PortableRuntimeCleanupResult | null { +): Promise { const hermesInput = { env: input.env, homeDir: input.homeDir, @@ -301,8 +305,8 @@ export function runPortableRuntimeCleanupTransaction( )(hermesInput); if (hermesSandboxNames) { const names = [...hermesSandboxNames].sort(compareCodeUnits); - return withPortableFences(input, names, deps, () => { - const result = (deps.runHermesPortableUninstall ?? runHermesPortableUninstall)( + return withPortableFences(input, names, deps, async () => { + const result = await (deps.runHermesPortableUninstall ?? runHermesPortableUninstall)( hermesInput, deps.hermesPortable, ); diff --git a/src/lib/actions/uninstall/run-plan-absent-sandbox.test.ts b/src/lib/actions/uninstall/run-plan-absent-sandbox.test.ts index df48a0ceedd..02ed7b2b232 100644 --- a/src/lib/actions/uninstall/run-plan-absent-sandbox.test.ts +++ b/src/lib/actions/uninstall/run-plan-absent-sandbox.test.ts @@ -146,7 +146,7 @@ describe("uninstall sandbox delete outcomes (#7906)", () => { const calls: string[][] = []; const warnings: string[] = []; - const result = runPortUninstall( + const result = await runPortUninstall( { assumeYes: true, deleteModels: false, diff --git a/src/lib/actions/uninstall/run-plan-docker-scope.test.ts b/src/lib/actions/uninstall/run-plan-docker-scope.test.ts index 1e6cb45c3a5..c8aa8d3260d 100644 --- a/src/lib/actions/uninstall/run-plan-docker-scope.test.ts +++ b/src/lib/actions/uninstall/run-plan-docker-scope.test.ts @@ -14,8 +14,8 @@ function ok(stdout = ""): RunResult { return { status: 0, stdout, stderr: "" }; } -function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { - return runUninstallPlanBase(options, { +async function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { + return await runUninstallPlanBase(options, { resolveGatewayTeardownAuthority: ({ gatewayName, gatewayPort }) => ({ gatewayName, gatewayPort, @@ -70,7 +70,7 @@ function collectDockerCalls(): { calls: string[][]; runDocker: UninstallRunDeps[ return { calls, runDocker }; } -function runWithDockerInventory(): string[][] { +async function runWithDockerInventory(): Promise { const { calls, runDocker } = collectDockerCalls(); const run = vi.fn((command: string, args: string[]) => { const stubbed: Record = { @@ -85,7 +85,7 @@ function runWithDockerInventory(): string[][] { ); }); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -109,16 +109,16 @@ function runWithDockerInventory(): string[][] { } describe("uninstall Docker resource scope", () => { - it("keeps containers belonging to the separate OpenClaw project (#8496)", () => { - const calls = runWithDockerInventory(); + it("keeps containers belonging to the separate OpenClaw project (#8496)", async () => { + const calls = await runWithDockerInventory(); expect(calls).not.toContainEqual(["rm", "-f", "c-openclaw"]); expect(calls).not.toContainEqual(["rm", "-f", "c-registry"]); expect(calls).not.toContainEqual(["rm", "-f", "c-unrelated"]); }); - it("keeps images belonging to the separate OpenClaw project (#8496)", () => { - const calls = runWithDockerInventory(); + it("keeps images belonging to the separate OpenClaw project (#8496)", async () => { + const calls = await runWithDockerInventory(); expect(calls).not.toContainEqual(["rmi", "-f", "i-openclaw"]); expect(calls).not.toContainEqual(["rmi", "-f", "i-tag"]); @@ -126,28 +126,28 @@ describe("uninstall Docker resource scope", () => { expect(calls).not.toContainEqual(["rmi", "-f", "i-unrelated"]); }); - it("still removes the gateway and sandbox containers it owns by name", () => { - const calls = runWithDockerInventory(); + it("still removes the gateway and sandbox containers it owns by name", async () => { + const calls = await runWithDockerInventory(); expect(calls).toContainEqual(["rm", "-f", "c-cluster"]); expect(calls).toContainEqual(["rm", "-f", "c-sandbox"]); }); - it("still reclaims a randomly named probe container by its NemoClaw image", () => { - const calls = runWithDockerInventory(); + it("still reclaims a randomly named probe container by its NemoClaw image", async () => { + const calls = await runWithDockerInventory(); expect(calls).toContainEqual(["rm", "-f", "c-probe"]); }); - it("still removes NemoClaw images published under a registry path", () => { - const calls = runWithDockerInventory(); + it("still removes NemoClaw images published under a registry path", async () => { + const calls = await runWithDockerInventory(); expect(calls).toContainEqual(["rmi", "-f", "i-nemoclaw"]); expect(calls).toContainEqual(["rmi", "-f", "i-managed"]); }); - it("still removes gateway-built OpenShell sandbox images", () => { - const calls = runWithDockerInventory(); + it("still removes gateway-built OpenShell sandbox images", async () => { + const calls = await runWithDockerInventory(); expect(calls).toContainEqual(["rmi", "-f", "i-openshell"]); }); diff --git a/src/lib/actions/uninstall/run-plan-dual-station.test.ts b/src/lib/actions/uninstall/run-plan-dual-station.test.ts index 456009fa0b3..9199813d9f5 100644 --- a/src/lib/actions/uninstall/run-plan-dual-station.test.ts +++ b/src/lib/actions/uninstall/run-plan-dual-station.test.ts @@ -30,8 +30,8 @@ function ok(stdout = ""): RunResult { return { status: 0, stdout, stderr: "" }; } -function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { - return runUninstallPlanBase(options, { +async function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { + return await runUninstallPlanBase(options, { hasPortableRuntimeCleanup: () => false, resolveGatewayTeardownAuthority: ({ gatewayName, gatewayPort }) => ({ gatewayName, @@ -62,7 +62,7 @@ function managedRuntimeBindingPath(receiptPath: string): string { describe("managed distributed vLLM runtime uninstall", () => { it.each(["dual-station-vllm-runtime.json", "managed-cluster-vllm-runtime.json"])( "removes the runtime owned by %s before the remaining full-uninstall steps", - (receiptFile) => { + async (receiptFile) => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-dual-pair-")); const stateDir = path.join(home, ".nemoclaw"); fs.mkdirSync(stateDir, { mode: 0o700 }); @@ -76,7 +76,7 @@ describe("managed distributed vLLM runtime uninstall", () => { const runDocker = vi.fn(() => ok()); try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -103,7 +103,7 @@ describe("managed distributed vLLM runtime uninstall", () => { }, ); - it("stops a distributed runtime before requesting shared Hugging Face cache-data cleanup", () => { + it("stops a distributed runtime before requesting shared Hugging Face cache-data cleanup", async () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-cache-order-")); const stateDir = path.join(home, ".nemoclaw"); const receiptPath = path.join(stateDir, DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE); @@ -116,7 +116,7 @@ describe("managed distributed vLLM runtime uninstall", () => { const runHuggingFaceCacheDataCleanup = vi.fn(() => ok()); try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: true, keepOpenShell: true }, { commandExists: (command) => command === "openshell", @@ -159,7 +159,7 @@ describe("managed distributed vLLM runtime uninstall", () => { vi.stubEnv("NEMOCLAW_GATEWAY_PORT", String(port)); vi.resetModules(); const { runUninstallPlan: runPortUninstallBase } = await import("./run-plan"); - const result = runPortUninstallBase( + const result = await runPortUninstallBase( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -199,7 +199,7 @@ describe("managed distributed vLLM runtime uninstall", () => { } }); - it("associates a canonical cluster discovery binding with its durable receipt", () => { + it("associates a canonical cluster discovery binding with its durable receipt", async () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-spark-claim-")); const stateDir = path.join(home, ".nemoclaw"); const receiptPath = path.join(stateDir, "managed-cluster-vllm-runtime.json"); @@ -214,7 +214,7 @@ describe("managed distributed vLLM runtime uninstall", () => { const runDualStationRuntimeCleanup = vi.fn(() => ok()); try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -254,7 +254,7 @@ describe("managed distributed vLLM runtime uninstall", () => { receiptFile: "dual-station-vllm-runtime.json", bindingSegments: ["managed-cluster-managed-serving.json.spark-worker.ssh-binding"], }, - ])("refuses $title", ({ receiptFile, bindingSegments }) => { + ])("refuses $title", async ({ receiptFile, bindingSegments }) => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-spark-claim-other-")); const stateDir = path.join(home, ".nemoclaw"); const receiptPath = path.join(stateDir, receiptFile); @@ -269,7 +269,7 @@ describe("managed distributed vLLM runtime uninstall", () => { const runDocker = vi.fn(() => ok()); try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -298,7 +298,7 @@ describe("managed distributed vLLM runtime uninstall", () => { } }); - it("targets the exact Station receipt found under a stale non-default gateway root", () => { + it("targets the exact Station receipt found under a stale non-default gateway root", async () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-stale-station-")); const receiptPath = path.join( home, @@ -312,7 +312,7 @@ describe("managed distributed vLLM runtime uninstall", () => { const runDualStationRuntimeCleanup = vi.fn(() => ok()); try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -337,7 +337,7 @@ describe("managed distributed vLLM runtime uninstall", () => { } }); - it("preserves host-global pair ownership while sibling gateways remain", () => { + it("preserves host-global pair ownership while sibling gateways remain", async () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-dual-scoped-")); const stateDir = path.join(home, ".nemoclaw"); const gatewayStateDir = path.join( @@ -375,7 +375,7 @@ describe("managed distributed vLLM runtime uninstall", () => { const runDualStationRuntimeCleanup = vi.fn(() => ok()); try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, destroyUserData: true, keepOpenShell: true }, withProvenManagedGatewayProcess({ isPortFree: () => true, @@ -405,7 +405,7 @@ describe("managed distributed vLLM runtime uninstall", () => { } }); - it("does not start the remaining uninstall steps when managed pair cleanup fails", () => { + it("does not start the remaining uninstall steps when managed pair cleanup fails", async () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-dual-fail-")); const stateDir = path.join(home, ".nemoclaw"); fs.mkdirSync(stateDir, { mode: 0o700 }); @@ -417,7 +417,7 @@ describe("managed distributed vLLM runtime uninstall", () => { const runDocker = vi.fn(() => ok()); try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: false }, { commandExists: () => true, @@ -448,7 +448,7 @@ describe("managed distributed vLLM runtime uninstall", () => { } }); - it("refuses ambiguous Spark and Station receipts before cleanup or other mutation", () => { + it("refuses ambiguous Spark and Station receipts before cleanup or other mutation", async () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-dual-conflict-")); const stateDir = path.join(home, ".nemoclaw"); fs.mkdirSync(stateDir, { mode: 0o700 }); @@ -466,7 +466,7 @@ describe("managed distributed vLLM runtime uninstall", () => { const rmSync = vi.fn(); try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: false }, { commandExists: () => true, @@ -498,7 +498,7 @@ describe("managed distributed vLLM runtime uninstall", () => { "managed-cluster-vllm-runtime.json.rank-1.ssh-binding", "managed-cluster-managed-serving.json.spark-worker.ssh-binding", "dual-station-vllm-runtime.json.ssh-binding", - ])("refuses an orphaned %s before cleanup or other mutation", (bindingEntry) => { + ])("refuses an orphaned %s before cleanup or other mutation", async (bindingEntry) => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-binding-orphan-")); const stateDir = path.join(home, ".nemoclaw"); const bindingPath = path.join(stateDir, bindingEntry); @@ -509,7 +509,7 @@ describe("managed distributed vLLM runtime uninstall", () => { const rmSync = vi.fn(); try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: false }, { commandExists: () => true, @@ -566,7 +566,7 @@ describe("managed distributed vLLM runtime uninstall", () => { vi.stubEnv("NEMOCLAW_GATEWAY_PORT", "18080"); vi.resetModules(); const { runUninstallPlan: runFreshUninstallPlan } = await import("./run-plan"); - const result = runFreshUninstallPlan( + const result = await runFreshUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -619,7 +619,7 @@ describe("managed distributed vLLM runtime uninstall", () => { fs.writeFileSync(stateDir, "not a directory\n", { mode: 0o600 }); }, }, - ])("fails closed when the host-global managed state root is a $shape", ({ arrange }) => { + ])("fails closed when the host-global managed state root is a $shape", async ({ arrange }) => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-unsafe-root-")); const stateDir = path.join(home, ".nemoclaw"); arrange(stateDir, home); @@ -628,7 +628,7 @@ describe("managed distributed vLLM runtime uninstall", () => { const runDocker = vi.fn(() => ok()); try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, diff --git a/src/lib/actions/uninstall/run-plan-external-gateway-segregation.test.ts b/src/lib/actions/uninstall/run-plan-external-gateway-segregation.test.ts index 846be425fb4..7dc2e2270a5 100644 --- a/src/lib/actions/uninstall/run-plan-external-gateway-segregation.test.ts +++ b/src/lib/actions/uninstall/run-plan-external-gateway-segregation.test.ts @@ -53,8 +53,8 @@ function writeScopedGatewayState(home: string): string { return configPath; } -function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { - return runUninstallPlanBase( +async function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { + return await runUninstallPlanBase( options, withSuccessfulPreUninstallBackup( withProvenManagedGatewayProcess({ diff --git a/src/lib/actions/uninstall/run-plan-foreign-user-gateway.test.ts b/src/lib/actions/uninstall/run-plan-foreign-user-gateway.test.ts index e152c6580dc..48780f628e8 100644 --- a/src/lib/actions/uninstall/run-plan-foreign-user-gateway.test.ts +++ b/src/lib/actions/uninstall/run-plan-foreign-user-gateway.test.ts @@ -19,10 +19,10 @@ function notFound(): RunResult { return { status: 1, stdout: "", stderr: "" }; } -function uninstallWithHostGatewayOwnedBy(uid: number): { +async function uninstallWithHostGatewayOwnedBy(uid: number): Promise<{ errors: string[]; exitCode: number; -} { +}> { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-foreign-")); const errors: string[] = []; const psResults = new Map([ @@ -42,7 +42,7 @@ function uninstallWithHostGatewayOwnedBy(uid: number): { ? ok("[]") : ok(); try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: false }, { commandExists: (command) => command === "pgrep" || command === "openshell", @@ -76,8 +76,10 @@ function uninstallWithHostGatewayOwnedBy(uid: number): { } describe("uninstall with a host gateway owned by another user", () => { - it("completes when the only unstoppable gateway process belongs to another user", () => { - const { errors, exitCode } = uninstallWithHostGatewayOwnedBy((process.getuid?.() ?? 0) + 1); + it("completes when the only unstoppable gateway process belongs to another user", async () => { + const { errors, exitCode } = await uninstallWithHostGatewayOwnedBy( + (process.getuid?.() ?? 0) + 1, + ); expect(exitCode).toBe(0); expect(errors).toContainEqual( @@ -89,8 +91,8 @@ describe("uninstall with a host gateway owned by another user", () => { ); }); - it("still fails when the current user's own gateway process cannot be stopped", () => { - const { errors, exitCode } = uninstallWithHostGatewayOwnedBy(process.getuid?.() ?? 0); + it("still fails when the current user's own gateway process cannot be stopped", async () => { + const { errors, exitCode } = await uninstallWithHostGatewayOwnedBy(process.getuid?.() ?? 0); expect(exitCode).toBe(1); expect(errors).toContainEqual( diff --git a/src/lib/actions/uninstall/run-plan-gateway-scan-entries.test.ts b/src/lib/actions/uninstall/run-plan-gateway-scan-entries.test.ts index f015db37232..c432980d79e 100644 --- a/src/lib/actions/uninstall/run-plan-gateway-scan-entries.test.ts +++ b/src/lib/actions/uninstall/run-plan-gateway-scan-entries.test.ts @@ -45,8 +45,8 @@ function withManagedGatewayAuthority(deps: UninstallRunDeps): UninstallRunDeps { }); } -function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { - return runUninstallPlanBase(options, withManagedGatewayAuthority(deps)); +async function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { + return await runUninstallPlanBase(options, withManagedGatewayAuthority(deps)); } function okWithKnownGatewayList(command: string, args: readonly string[]): RunResult { @@ -129,7 +129,7 @@ function writeScopedGatewayState(home: string, port = 8080): void { * assertions read the outcome rather than the calls a test double recorded. * Captures both `log` and `error` (runtime warnings) for assertion. */ -function uninstall( +async function uninstall( home: string, shims: readonly string[], options: Pick & { @@ -137,7 +137,7 @@ function uninstall( } = {}, ) { const logs: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, @@ -171,11 +171,11 @@ function writeForeignCliShims(shims: readonly string[]): void { describe("uninstall gateway-directory scan", () => { it.each([[".DS_Store"], [".localized"], ["._sandboxes.json"]])( "removes the CLI shims when the gateways directory holds only %s (#7905)", - (entry) => { + async (entry) => { const { home, shims } = makeHome("nemoclaw-uninstall-metadata-", [entry]); try { - const { result, logs, survivors } = uninstall(home, shims); + const { result, logs, survivors } = await uninstall(home, shims); expect(result.exitCode).toBe(0); expect(logs).not.toContain(SCOPED_RETENTION_LOG); @@ -190,12 +190,12 @@ describe("uninstall gateway-directory scan", () => { // live gateway state, so each of these keeps the conservative treatment. it.each([["not-a-port"], ["._"], [".DS_Store/"]])( "keeps the CLI shims when the gateways directory holds %s (#7905)", - (entry) => { + async (entry) => { const { home, shims } = makeHome("nemoclaw-uninstall-conservative-", [entry]); writeScopedGatewayState(home); try { - const { result, logs, survivors } = uninstall(home, shims); + const { result, logs, survivors } = await uninstall(home, shims); expect(result.exitCode).toBe(0); expect(logs).toContain(SCOPED_RETENTION_LOG); @@ -208,7 +208,7 @@ describe("uninstall gateway-directory scan", () => { it.skipIf(process.platform === "win32")( "keeps the CLI shims for a desktop-metadata symlink (#7905)", - () => { + async () => { const { home, shims } = makeHome("nemoclaw-uninstall-conservative-", []); writeScopedGatewayState(home); fs.symlinkSync( @@ -217,7 +217,7 @@ describe("uninstall gateway-directory scan", () => { ); try { - const { result, logs, survivors } = uninstall(home, shims); + const { result, logs, survivors } = await uninstall(home, shims); expect(result.exitCode).toBe(0); expect(logs).toContain(SCOPED_RETENTION_LOG); @@ -230,12 +230,12 @@ describe("uninstall gateway-directory scan", () => { it.each([["not-a-port"], ["._"], [".DS_Store/"]])( "removes managed CLI shims with --destroy-user-data when the gateways directory holds %s (#9277)", - (entry) => { + async (entry) => { const { home, shims } = makeHome("nemoclaw-uninstall-destroy-shim-", [entry]); writeScopedGatewayState(home); try { - const { result, logs, survivors } = uninstall(home, shims, { destroyUserData: true }); + const { result, logs, survivors } = await uninstall(home, shims, { destroyUserData: true }); expect(result.exitCode).toBe(0); expect(logs).toContain(SCOPED_PACKAGE_RETENTION_LOG); @@ -248,13 +248,13 @@ describe("uninstall gateway-directory scan", () => { }, ); - it("preserves foreign CLI files under --destroy-user-data without claiming removal (#9277)", () => { + it("preserves foreign CLI files under --destroy-user-data without claiming removal (#9277)", async () => { const { home, shims } = makeHome("nemoclaw-uninstall-destroy-foreign-", ["not-a-port"]); writeScopedGatewayState(home); writeForeignCliShims(shims); try { - const { result, logs, survivors } = uninstall(home, shims, { destroyUserData: true }); + const { result, logs, survivors } = await uninstall(home, shims, { destroyUserData: true }); expect(result.exitCode).toBe(0); expect(logs).toContain(SCOPED_PACKAGE_RETENTION_LOG); @@ -267,12 +267,12 @@ describe("uninstall gateway-directory scan", () => { } }); - it("keeps managed CLI shims with --destroy-user-data when a confirmed sibling gateway remains (#9277)", () => { + it("keeps managed CLI shims with --destroy-user-data when a confirmed sibling gateway remains (#9277)", async () => { const { home, shims } = makeHome("nemoclaw-uninstall-destroy-sibling-", []); writeScopedGatewayState(home); try { - const { result, logs, survivors } = uninstall(home, shims, { + const { result, logs, survivors } = await uninstall(home, shims, { destroyUserData: true, run: okWithSiblingGatewayList, }); diff --git a/src/lib/actions/uninstall/run-plan-gateway-segregation-selected-port.test.ts b/src/lib/actions/uninstall/run-plan-gateway-segregation-selected-port.test.ts index e914052a64c..c9146284286 100644 --- a/src/lib/actions/uninstall/run-plan-gateway-segregation-selected-port.test.ts +++ b/src/lib/actions/uninstall/run-plan-gateway-segregation-selected-port.test.ts @@ -95,7 +95,7 @@ afterEach(() => { }); describe("uninstall selected gateway-port segregation (#3053)", () => { - it("does not treat the selected gateway's own port directory as a sibling (#7987)", () => { + it("does not treat the selected gateway's own port directory as a sibling (#7987)", async () => { const tmpHome = fs.mkdtempSync(path.join(process.cwd(), "nemoclaw-uninstall-self-sibling-")); try { const stateDir = path.join(tmpHome, ".nemoclaw"); @@ -115,7 +115,7 @@ describe("uninstall selected gateway-port segregation (#3053)", () => { writeScopedGatewayState(tmpHome); const logs: string[] = []; const openshellCalls: string[][] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, destroyUserData: true, keepOpenShell: false }, { commandExists: (command) => command === "openshell", @@ -146,7 +146,7 @@ describe("uninstall selected gateway-port segregation (#3053)", () => { } }); - it("still detects a live sibling alongside the selected gateway's own port directory (#7987)", () => { + it("still detects a live sibling alongside the selected gateway's own port directory (#7987)", async () => { const tmpHome = fs.mkdtempSync( path.join(process.cwd(), "nemoclaw-uninstall-self-and-sibling-"), ); @@ -166,7 +166,7 @@ describe("uninstall selected gateway-port segregation (#3053)", () => { writeScopedGatewayState(tmpHome); const logs: string[] = []; const openshellCalls: string[][] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, destroyUserData: true, keepOpenShell: false }, { commandExists: (command) => command === "openshell", @@ -251,7 +251,7 @@ describe("uninstall selected gateway-port segregation (#3053)", () => { const openshellCalls: string[][] = []; const errors = vi.fn(); - const result = runPortUninstall( + const result = await runPortUninstall( { assumeYes: true, deleteModels: false, @@ -336,7 +336,7 @@ describe("uninstall selected gateway-port segregation (#3053)", () => { const calls: string[][] = []; const logs: string[] = []; - const result = runPortUninstall( + const result = await runPortUninstall( { assumeYes: true, deleteModels: false, @@ -416,7 +416,7 @@ describe("uninstall selected gateway-port segregation (#3053)", () => { const logs: string[] = []; const run = vi.fn(() => ok()); - const result = runPortUninstall( + const result = await runPortUninstall( { assumeYes: true, deleteModels: false, @@ -469,7 +469,7 @@ describe("uninstall selected gateway-port segregation (#3053)", () => { const warnings = vi.fn(); try { - const result = runPortUninstall( + const result = await runPortUninstall( { assumeYes: true, deleteModels: false, @@ -521,7 +521,7 @@ describe("uninstall selected gateway-port segregation (#3053)", () => { writeScopedGatewayState(tmpHome, port, customGatewayState); let competingOnboardingWasBlocked = false; - const result = runPortUninstall( + const result = await runPortUninstall( { assumeYes: true, deleteModels: false, @@ -609,7 +609,7 @@ describe("uninstall selected gateway-port segregation (#3053)", () => { restore = mutate(tmpHome, customGatewayState); const warnings = vi.fn(); - const result = runPortUninstall( + const result = await runPortUninstall( { assumeYes: true, deleteModels: false, @@ -667,7 +667,7 @@ describe("uninstall selected gateway-port segregation (#3053)", () => { }); const warnings = vi.fn(); - const result = runPortUninstall( + const result = await runPortUninstall( { assumeYes: true, deleteModels: false, @@ -773,7 +773,7 @@ describe("uninstall selected gateway-port segregation (#3053)", () => { writeEvidence(customGatewayState); const errors = vi.fn(); - const result = runPortUninstall( + const result = await runPortUninstall( { assumeYes: true, deleteModels: false, @@ -830,7 +830,7 @@ describe("uninstall selected gateway-port segregation (#3053)", () => { const rmSync = vi.fn(); const errors = vi.fn(); - const result = runPortUninstall( + const result = await runPortUninstall( { assumeYes: true, deleteModels: false, @@ -895,7 +895,7 @@ describe("uninstall selected gateway-port segregation (#3053)", () => { const openshellCalls: string[][] = []; const warnings = vi.fn(); - const result = runPortUninstall( + const result = await runPortUninstall( { assumeYes: true, deleteModels: false, diff --git a/src/lib/actions/uninstall/run-plan-gateway-segregation.test.ts b/src/lib/actions/uninstall/run-plan-gateway-segregation.test.ts index 3d36f5026cc..1dba954a040 100644 --- a/src/lib/actions/uninstall/run-plan-gateway-segregation.test.ts +++ b/src/lib/actions/uninstall/run-plan-gateway-segregation.test.ts @@ -140,7 +140,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { executable: "/usr/local/bin/openshell-gateway", commandLine: "/usr/local/bin/openshell-gateway --name nemoclaw --port 8091", }, - ])("refuses scoped cleanup when $title", ({ executable, commandLine }) => { + ])("refuses scoped cleanup when $title", async ({ executable, commandLine }) => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-external-proof-")); try { const shared = path.join(tmpHome, ".nemoclaw"); @@ -161,7 +161,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { const warnings: string[] = []; const externalPid = 4242; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, destroyUserData: true, keepOpenShell: true }, { commandExists: (command) => command === "openshell", @@ -213,7 +213,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { } }); - it("does not use legacy gateway destroy when external registration removal is unsupported (#6576)", () => { + it("does not use legacy gateway destroy when external registration removal is unsupported (#6576)", async () => { const calls: Array<{ args: string[]; command: string }> = []; const responses = new Map([ ["openshell gateway list -o json", ok(JSON.stringify([{ name: "nemoclaw" }]))], @@ -222,7 +222,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { { status: 2, stdout: "", stderr: "unrecognized subcommand 'remove'" }, ], ]); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command === "openshell", @@ -260,12 +260,12 @@ describe("uninstall gateway-port segregation (#3053)", () => { expect(openshellCalls).not.toContainEqual(["gateway", "destroy", "-g", "nemoclaw"]); }); - it("fails before uninstall effects when gateway authority revalidation fails (#6576)", () => { + it("fails before uninstall effects when gateway authority revalidation fails (#6576)", async () => { const run = vi.fn(() => ok()); const runDocker = vi.fn(() => ok()); const rmSync = vi.fn(); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { env: { HOME: STATIC_TEST_HOME } as NodeJS.ProcessEnv, @@ -286,7 +286,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { expect(rmSync).not.toHaveBeenCalled(); }); - it("falls back to legacy gateway destroy only when gateway remove is unsupported", () => { + it("falls back to legacy gateway destroy only when gateway remove is unsupported", async () => { const calls: Array<{ args: string[]; command: string }> = []; const responses = new Map([ ["openshell gateway list -o json", ok(JSON.stringify([{ name: "nemoclaw" }]))], @@ -295,7 +295,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { { status: 2, stdout: "", stderr: "unrecognized subcommand 'remove'" }, ], ]); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command !== "docker" && command !== "pgrep", @@ -366,7 +366,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { }, ])( "preserves state when gateway cleanup reports $name (#9859)", - ({ + async ({ diagnostic, expectedCause = "exit 1).", legacyDestroyDiagnostic, @@ -395,7 +395,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { } : ok(), ); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command !== "docker" && command !== "pgrep", @@ -442,7 +442,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { }, ); - it("preserves the gateways/ subtree so uninstalling one environment leaves the others", () => { + it("preserves the gateways/ subtree so uninstalling one environment leaves the others", async () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gwpreserve-")); try { const stateDir = path.join(tmpHome, ".nemoclaw"); @@ -470,7 +470,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { const logs: string[] = []; const kill = vi.fn(() => true); const run = vi.fn((_command: string, _args: string[]) => ok()); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command === "openshell", @@ -492,9 +492,9 @@ describe("uninstall gateway-port segregation (#3053)", () => { expect(fs.existsSync(path.join(otherEnv, "sandboxes.json"))).toBe(true); expect(fs.existsSync(path.join(stateDir, "sandboxes.json"))).toBe(false); expect(fs.existsSync(stateDir)).toBe(true); - expect(adapterStateEntries.every((name) => fs.existsSync(path.join(stateDir, name)))).toBe( - true, - ); + expect( + adapterStateEntries.map((name) => fs.existsSync(path.join(stateDir, name))), + ).not.toContain(false); expect(kill).not.toHaveBeenCalled(); expect( run.mock.calls.some( @@ -508,7 +508,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { } }); - it("does not scan or signal a sibling Bedrock adapter during selected-gateway uninstall (#9552)", () => { + it("does not scan or signal a sibling Bedrock adapter during selected-gateway uninstall (#9552)", async () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-bedrock-scope-")); try { const stateDir = path.join(tmpHome, ".nemoclaw"); @@ -532,7 +532,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { const kill = vi.fn((_pid: number) => true); let adapterExited = false; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, destroyUserData: true, keepOpenShell: true }, { commandExists: (command) => command === "lsof" || command === "openshell", @@ -579,7 +579,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { } }); - it("keeps the host-shared /swapfile when other gateway-port environments remain", () => { + it("keeps the host-shared /swapfile when other gateway-port environments remain", async () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-swap-")); try { const stateDir = path.join(tmpHome, ".nemoclaw"); @@ -588,7 +588,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { writeScopedGatewayState(tmpHome); const logs: string[] = []; const runCalls: string[][] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command !== "docker" && command !== "pgrep", @@ -662,7 +662,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { }; const options = { assumeYes: true, deleteModels: false, keepOpenShell: true }; - const protectedResult = runPortUninstall(options, deps); + const protectedResult = await runPortUninstall(options, deps); expect(protectedResult.exitCode).toBe(0); expect(runCalls.some((args) => args[0] === "swapoff")).toBe(false); expect(fs.existsSync(path.join(stateDir, "managed_swap"))).toBe(true); @@ -670,7 +670,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { fs.rmSync(defaultSession); fs.mkdirSync(selectedEnv, { recursive: true }); runCalls.length = 0; - const result = runPortUninstall(options, deps); + const result = await runPortUninstall(options, deps); expect(result.exitCode).toBe(0); expect(runCalls).toContainEqual(["swapoff", "/swapfile"]); @@ -700,7 +700,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { writeScopedGatewayState(tmpHome, port); const runCalls: string[][] = []; - const result = runPortUninstall( + const result = await runPortUninstall( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command !== "docker" && command !== "pgrep", @@ -761,7 +761,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { writeScopedGatewayState(tmpHome, port); const runCalls: string[][] = []; - const result = runPortUninstall( + const result = await runPortUninstall( { assumeYes: true, deleteModels: false, @@ -832,7 +832,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { expect(migration.migratedSandboxNames).toEqual(["selected-box"]); writeScopedGatewayState(tmpHome, selectedPort); const calls: Array<{ command: string; args: string[] }> = []; - const result = runPortUninstall( + const result = await runPortUninstall( { assumeYes: true, deleteModels: false, @@ -911,7 +911,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { writeScopedGatewayState(tmpHome); const calls: Array<{ command: string; args: string[] }> = []; - const result = runDefaultUninstall( + const result = await runDefaultUninstall( { assumeYes: true, deleteModels: false, @@ -1038,7 +1038,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { `selected-id image openshell-cluster-nemoclaw-${String(port)}`, ].join("\n"), }; - const result = runPortUninstall( + const result = await runPortUninstall( { assumeYes: true, deleteModels: true, @@ -1087,9 +1087,9 @@ describe("uninstall gateway-port segregation (#3053)", () => { expect(runCalls.some(({ command }) => command === "systemctl")).toBe(false); expect(fs.existsSync(path.join(nemoclawConfig, "keep"))).toBe(true); expect(kill.mock.calls.every(([pid]) => pid !== 4242)).toBe(true); - expect(proxyStateEntries.every((entry) => fs.existsSync(path.join(shared, entry)))).toBe( - true, - ); + expect( + proxyStateEntries.map((entry) => fs.existsSync(path.join(shared, entry))), + ).not.toContain(false); expect(logs).toContain( "Preserving the shared Ollama auth proxy for the remaining gateway ports", ); @@ -1098,7 +1098,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { } }); - it("removes host-shared resources when the only gateways/ entries are OpenShell orphans (#7315)", () => { + it("removes host-shared resources when the only gateways/ entries are OpenShell orphans (#7315)", async () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-orphan-sibling-")); try { const stateDir = path.join(tmpHome, ".nemoclaw"); @@ -1117,7 +1117,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { writeScopedGatewayState(tmpHome); const logs: string[] = []; const openshellCalls: string[][] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, destroyUserData: true, keepOpenShell: false }, { commandExists: (command) => command === "openshell", @@ -1148,7 +1148,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { } }); - it("removes host-shared resources when the only sibling registry row is an OpenShell orphan (#7315)", () => { + it("removes host-shared resources when the only sibling registry row is an OpenShell orphan (#7315)", async () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-orphan-registry-")); try { const stateDir = path.join(tmpHome, ".nemoclaw"); @@ -1167,7 +1167,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { writeScopedGatewayState(tmpHome); const logs: string[] = []; const openshellCalls: string[][] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, destroyUserData: true, keepOpenShell: false }, { commandExists: (command) => command === "openshell", @@ -1198,7 +1198,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { } }); - it("keeps host-shared resources when a sibling registry row is a live OpenShell gateway (#7315)", () => { + it("keeps host-shared resources when a sibling registry row is a live OpenShell gateway (#7315)", async () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-live-registry-")); try { const stateDir = path.join(tmpHome, ".nemoclaw"); @@ -1215,7 +1215,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { writeScopedGatewayState(tmpHome); const logs: string[] = []; const openshellCalls: string[][] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, destroyUserData: true, keepOpenShell: false }, { commandExists: (command) => command === "openshell", @@ -1243,7 +1243,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { } }); - it("refuses host-wide cleanup when OpenShell is unavailable and no sibling files exist (#7315)", () => { + it("refuses host-wide cleanup when OpenShell is unavailable and no sibling files exist (#7315)", async () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-no-openshell-")); try { const servicePath = path.join( @@ -1260,7 +1260,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { const logs: string[] = []; const rmSync = vi.fn(); const warnings: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, destroyUserData: true, keepOpenShell: false }, { commandExists: (command) => command === "npm" || command === "systemctl", @@ -1310,7 +1310,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { case: "the gateway list is not an array", gatewayListResponse: ok(JSON.stringify({ name: "nemoclaw" })), }, - ])("keeps host-shared resources when $case (#7315)", ({ gatewayListResponse }) => { + ])("keeps host-shared resources when $case (#7315)", async ({ gatewayListResponse }) => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-malformed-list-")); try { const stateDir = path.join(tmpHome, ".nemoclaw"); @@ -1340,7 +1340,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { writeScopedGatewayState(tmpHome); const logs: string[] = []; const openshellCalls: string[][] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, destroyUserData: true, keepOpenShell: false }, { commandExists: (command) => command === "openshell", @@ -1369,7 +1369,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { } }); - it("switches to scoped cleanup when a sibling gateway appears before destruction (#7315)", () => { + it("switches to scoped cleanup when a sibling gateway appears before destruction (#7315)", async () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-new-sibling-")); try { const stateDir = path.join(tmpHome, ".nemoclaw"); @@ -1392,7 +1392,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { const openshellCalls: string[][] = []; const warnings: string[] = []; let gatewayListCalls = 0; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, destroyUserData: true, keepOpenShell: false }, { commandExists: (command) => command === "openshell", @@ -1430,7 +1430,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { } }); - it("keeps host-shared resources when a gateways/ entry is a live OpenShell gateway (#7315)", () => { + it("keeps host-shared resources when a gateways/ entry is a live OpenShell gateway (#7315)", async () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-live-sibling-")); try { const stateDir = path.join(tmpHome, ".nemoclaw"); @@ -1461,7 +1461,7 @@ describe("uninstall gateway-port segregation (#3053)", () => { const logs: string[] = []; const openshellCalls: string[][] = []; let proxyProcessIsRunning = true; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, destroyUserData: true, keepOpenShell: false }, { commandExists: (command) => command === "openshell", @@ -1490,9 +1490,9 @@ describe("uninstall gateway-port segregation (#3053)", () => { expect(logs.join("\n")).toContain("Sibling gateways remain"); expect(fs.existsSync(path.join(stateDir, "gateways", "8091"))).toBe(true); expect(proxyProcessIsRunning).toBe(true); - expect(proxyStateEntries.every((entry) => fs.existsSync(path.join(stateDir, entry)))).toBe( - true, - ); + expect( + proxyStateEntries.map((entry) => fs.existsSync(path.join(stateDir, entry))), + ).not.toContain(false); } finally { fs.rmSync(tmpHome, { recursive: true, force: true }); } diff --git a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts index 46f298c008c..49df90c268d 100644 --- a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts +++ b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts @@ -118,14 +118,14 @@ function writeGatewayState(test: Fixture): string { return configPath; } -function uninstall( +async function uninstall( test: Fixture, keepOpenShell: boolean, deps: Partial = {}, gateways: { name: string }[] = [{ name: "nemoclaw" }], ) { const { commandExists = () => false, run = () => ok(), ...overrides } = deps; - return runUninstallPlanProduction( + return await runUninstallPlanProduction( { assumeYes: true, deleteModels: false, keepOpenShell }, withProvenManagedGatewayProcess({ backupAllBeforeUninstall: async () => undefined, diff --git a/src/lib/actions/uninstall/run-plan-hermes-state-volume.test.ts b/src/lib/actions/uninstall/run-plan-hermes-state-volume.test.ts index 2129604a181..ecef2be8b85 100644 --- a/src/lib/actions/uninstall/run-plan-hermes-state-volume.test.ts +++ b/src/lib/actions/uninstall/run-plan-hermes-state-volume.test.ts @@ -32,8 +32,8 @@ function ok(stdout = ""): RunResult { return { status: 0, stdout, stderr: "" }; } -function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { - return runUninstallPlanBase( +async function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { + return await runUninstallPlanBase( options, withSuccessfulPreUninstallBackup({ resolveGatewayTeardownAuthority: ({ gatewayName, gatewayPort }) => ({ diff --git a/src/lib/actions/uninstall/run-plan-homebrew-openshell.test.ts b/src/lib/actions/uninstall/run-plan-homebrew-openshell.test.ts index e2bf3d9ae54..40aa566beea 100644 --- a/src/lib/actions/uninstall/run-plan-homebrew-openshell.test.ts +++ b/src/lib/actions/uninstall/run-plan-homebrew-openshell.test.ts @@ -21,8 +21,8 @@ function ok(stdout = ""): RunResult { return { status: 0, stdout, stderr: "" }; } -function runUninstallPlan(deps: UninstallRunDeps) { - return runUninstallPlanBase( +async function runUninstallPlan(deps: UninstallRunDeps) { + return await runUninstallPlanBase( { assumeYes: true, deleteModels: false, keepOpenShell: false }, { resolveGatewayTeardownAuthority: ({ gatewayName, gatewayPort }) => ({ @@ -40,7 +40,7 @@ function runUninstallPlan(deps: UninstallRunDeps) { ); } -function uninstallOpenShell(options: { +async function uninstallOpenShell(options: { brewAvailable: boolean; brewStatus: number | null; platform?: NodeJS.Platform; @@ -56,7 +56,7 @@ function uninstallOpenShell(options: { removed.push(target); return ok(); }; - const result = runUninstallPlan({ + const result = await runUninstallPlan({ commandExists: (command) => command === "openshell" || (command === "brew" && options.brewAvailable), env: { HOME: home } as NodeJS.ProcessEnv, @@ -82,8 +82,8 @@ function uninstallOpenShell(options: { return { calls, executablePaths, logs, remaining: [...existing], removed, result }; } -it("retains a Homebrew-managed OpenShell and reports its removal command (#8882)", () => { - const { calls, executablePaths, logs, remaining, removed, result } = uninstallOpenShell({ +it("retains a Homebrew-managed OpenShell and reports its removal command (#8882)", async () => { + const { calls, executablePaths, logs, remaining, removed, result } = await uninstallOpenShell({ brewAvailable: true, brewStatus: 0, }); @@ -117,8 +117,8 @@ it.each([ brewStatus: null, report: `Kept OpenShell executables because Homebrew did not confirm ${FORMULA}. Check the formula before removing OpenShell.`, }, -])("retains OpenShell when $label (#8882)", ({ brewAvailable, brewStatus, report }) => { - const { calls, executablePaths, logs, remaining, removed, result } = uninstallOpenShell({ +])("retains OpenShell when $label (#8882)", async ({ brewAvailable, brewStatus, report }) => { + const { calls, executablePaths, logs, remaining, removed, result } = await uninstallOpenShell({ brewAvailable, brewStatus, }); @@ -132,8 +132,8 @@ it.each([ expect(logs).toContain(report); }); -it("removes managed OpenShell executables on Linux (#8882)", () => { - const { executablePaths, remaining, removed, result } = uninstallOpenShell({ +it("removes managed OpenShell executables on Linux (#8882)", async () => { + const { executablePaths, remaining, removed, result } = await uninstallOpenShell({ brewAvailable: false, brewStatus: 0, platform: "linux", diff --git a/src/lib/actions/uninstall/run-plan-local-model-profile.test.ts b/src/lib/actions/uninstall/run-plan-local-model-profile.test.ts index fafefb2d584..1b6977f566e 100644 --- a/src/lib/actions/uninstall/run-plan-local-model-profile.test.ts +++ b/src/lib/actions/uninstall/run-plan-local-model-profile.test.ts @@ -50,8 +50,8 @@ const ORPHANED_VLLM_INSPECT_ARGS = [ const RESERVED_INFERENCE_NAMES_ARGS = ["ps", "-a", "--format", "{{.Names}}"]; -function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { - return runUninstallPlanBase(options, { +async function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { + return await runUninstallPlanBase(options, { resolveGatewayTeardownAuthority: ({ gatewayName, gatewayPort }) => ({ gatewayName, gatewayPort, @@ -124,13 +124,13 @@ function writeScopedGatewayState(home: string): void { } describe("uninstall local model profile cleanup", () => { - it("removes an orphaned host-local vLLM container only when its managed label is present (#8981)", () => { + it("removes an orphaned host-local vLLM container only when its managed label is present (#8981)", async () => { const containerId = "a".repeat(64); const runDocker = dockerResults( new Map([[JSON.stringify(ORPHANED_VLLM_INSPECT_ARGS), ok(`${containerId} true\n`)]]), ); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command === "openshell" || command === "docker", @@ -150,7 +150,7 @@ describe("uninstall local model profile cleanup", () => { ); }); - it("preserves an orphaned host-local vLLM container without the managed label (#8981)", () => { + it("preserves an orphaned host-local vLLM container without the managed label (#8981)", async () => { const errors: string[] = []; const runDocker = dockerResults( new Map([ @@ -159,7 +159,7 @@ describe("uninstall local model profile cleanup", () => { ]), ); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command === "openshell" || command === "docker", @@ -178,7 +178,7 @@ describe("uninstall local model profile cleanup", () => { expect(errors.join("\n")).toContain("remains after ownership-aware cleanup"); }); - it("preserves an orphaned host-local vLLM container after malformed inspection output (#8981)", () => { + it("preserves an orphaned host-local vLLM container after malformed inspection output (#8981)", async () => { const errors: string[] = []; const runDocker = dockerResults( new Map([ @@ -187,7 +187,7 @@ describe("uninstall local model profile cleanup", () => { ]), ); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command === "openshell" || command === "docker", @@ -206,7 +206,7 @@ describe("uninstall local model profile cleanup", () => { expect(errors.join("\n")).toContain("remains after ownership-aware cleanup"); }); - it("stops uninstall when orphaned host-local vLLM removal fails (#8981)", () => { + it("stops uninstall when orphaned host-local vLLM removal fails (#8981)", async () => { const errors: string[] = []; const containerId = "c".repeat(64); const runDocker = dockerResults( @@ -216,7 +216,7 @@ describe("uninstall local model profile cleanup", () => { ]), ); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command === "openshell" || command === "docker", @@ -239,7 +239,7 @@ describe("uninstall local model profile cleanup", () => { expect(runDocker.mock.calls.some(([args]) => args[0] === "ps")).toBe(false); }); - it("fails before generic Docker cleanup when a reserved inference name remains", () => { + it("fails before generic Docker cleanup when a reserved inference name remains", async () => { const errors: string[] = []; const psResults = new Map([ [ @@ -272,7 +272,7 @@ describe("uninstall local model profile cleanup", () => { return result!; }); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command === "openshell" || command === "docker", @@ -294,9 +294,9 @@ describe("uninstall local model profile cleanup", () => { expect(errors.join("\n")).toContain("remains after ownership-aware cleanup"); }); - it("fails closed when Docker cannot inventory reserved inference names", () => { + it("fails closed when Docker cannot inventory reserved inference names", async () => { const errors: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command === "openshell" || command === "docker", @@ -316,9 +316,9 @@ describe("uninstall local model profile cleanup", () => { expect(errors.join("\n")).toContain("could not inventory reserved managed inference"); }); - it("states that model deletion removes every Ollama model and non-credential Hugging Face cache data", () => { + it("states that model deletion removes every Ollama model and non-credential Hugging Face cache data", async () => { const logs: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: false, deleteModels: true, keepOpenShell: true }, { commandExists: (command) => command === "openshell", @@ -339,13 +339,13 @@ describe("uninstall local model profile cleanup", () => { expect(logs).toContain("Aborted."); }); - it("requests shared Hugging Face cache-data cleanup during Model stores", () => { + it("requests shared Hugging Face cache-data cleanup during Model stores", async () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-llama-cache-")); const cacheDir = path.join(tmpHome, ".cache", "huggingface"); const log = vi.fn(); const runHuggingFaceCacheDataCleanup = vi.fn(() => ok()); try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: true, keepOpenShell: true }, { commandExists: (command) => command === "openshell", @@ -374,7 +374,7 @@ describe("uninstall local model profile cleanup", () => { } }); - it("deletes every model returned by Ollama inventory", () => { + it("deletes every model returned by Ollama inventory", async () => { const run = runWithOllamaInventory( ok( [ @@ -385,7 +385,7 @@ describe("uninstall local model profile cleanup", () => { ), ); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: true, keepOpenShell: true }, { commandExists: (command) => command === "openshell" || command === "ollama", @@ -418,10 +418,10 @@ describe("uninstall local model profile cleanup", () => { ).toEqual([60_000, 60_000]); }); - it("ignores a remote Ollama environment override during model cleanup", () => { + it("ignores a remote Ollama environment override during model cleanup", async () => { const run = runWithOllamaInventory(ok("NAME ID SIZE MODIFIED\nlocal-model 111 1 GB now\n")); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: true, keepOpenShell: true }, { commandExists: (command) => command === "openshell" || command === "ollama", @@ -445,13 +445,13 @@ describe("uninstall local model profile cleanup", () => { }); }); - it("fails without deleting any Ollama model when inventory is malformed", () => { + it("fails without deleting any Ollama model when inventory is malformed", async () => { const errors: string[] = []; const run = runWithOllamaInventory( ok("NAME ID SIZE MODIFIED\n--unsafe 111111111111 1 GB now\n"), ); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: true, keepOpenShell: true }, { commandExists: (command) => command === "openshell" || command === "ollama", @@ -471,14 +471,14 @@ describe("uninstall local model profile cleanup", () => { expect(errors.join("\n")).toContain("No Ollama models were removed"); }); - it("fails without deleting any Ollama model when inventory execution fails", () => { + it("fails without deleting any Ollama model when inventory execution fails", async () => { const run = runWithOllamaInventory({ status: 1, stdout: "", stderr: "daemon unavailable", }); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: true, keepOpenShell: true }, { commandExists: (command) => command === "openshell" || command === "ollama", @@ -496,13 +496,13 @@ describe("uninstall local model profile cleanup", () => { ); }); - it("attempts every inventoried Ollama removal and fails when one removal fails", () => { + it("attempts every inventoried Ollama removal and fails when one removal fails", async () => { const run = runWithOllamaInventory( ok("NAME ID SIZE MODIFIED\nfirst 111 1 GB now\nsecond 222 1 GB now\n"), ["first"], ); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: true, keepOpenShell: true }, { commandExists: (command) => command === "openshell" || command === "ollama", @@ -522,10 +522,10 @@ describe("uninstall local model profile cleanup", () => { ).toEqual(["first", "second"]); }); - it("does not inventory or remove Ollama models without delete-models", () => { + it("does not inventory or remove Ollama models without delete-models", async () => { const run = vi.fn(okWithKnownGatewayList); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command === "openshell" || command === "ollama", @@ -541,7 +541,7 @@ describe("uninstall local model profile cleanup", () => { expect(run.mock.calls.some(([command]) => command === "ollama")).toBe(false); }); - it("cleans selected gateway-owned llama.cpp state before scoped uninstall removes state", () => { + it("cleans selected gateway-owned llama.cpp state before scoped uninstall removes state", async () => { const tmpHome = fs.realpathSync( fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-llama-scoped-")), ); @@ -555,7 +555,7 @@ describe("uninstall local model profile cleanup", () => { return ok(`state:${stateDir}`); }); try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: true, keepOpenShell: true }, withProvenManagedGatewayProcess({ commandExists: (command) => command === "openshell", @@ -582,7 +582,7 @@ describe("uninstall local model profile cleanup", () => { } }); - it("cleans orphaned gateway-scoped llama.cpp authority before a full uninstall", () => { + it("cleans orphaned gateway-scoped llama.cpp authority before a full uninstall", async () => { const tmpHome = fs.realpathSync( fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-llama-all-")), ); @@ -595,7 +595,7 @@ describe("uninstall local model profile cleanup", () => { return ok(`state:${stateDir}`); }); try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command === "openshell", @@ -617,7 +617,7 @@ describe("uninstall local model profile cleanup", () => { } }); - it("continues unrelated uninstall after managed llama.cpp cleanup fails (#9575)", () => { + it("continues unrelated uninstall after managed llama.cpp cleanup fails (#9575)", async () => { const tmpHome = fs.realpathSync( fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-llama-fail-")), ); @@ -642,7 +642,7 @@ describe("uninstall local model profile cleanup", () => { stderr: "qualified endpoint changed", })); try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: true, keepOpenShell: true }, withProvenManagedGatewayProcess({ commandExists: (command) => command === "openshell", @@ -683,10 +683,10 @@ describe("uninstall local model profile cleanup", () => { } }); - it("stops before generic Docker cleanup when host-local cleanup fails", () => { + it("stops before generic Docker cleanup when host-local cleanup fails", async () => { const errors: string[] = []; const runDocker = vi.fn((_args: string[]) => ok()); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: true, keepOpenShell: true }, { commandExists: (command) => command === "openshell" || command === "docker", diff --git a/src/lib/actions/uninstall/run-plan-nvm-leftovers.test.ts b/src/lib/actions/uninstall/run-plan-nvm-leftovers.test.ts index 120dc88fb4c..684b621ca13 100644 --- a/src/lib/actions/uninstall/run-plan-nvm-leftovers.test.ts +++ b/src/lib/actions/uninstall/run-plan-nvm-leftovers.test.ts @@ -13,8 +13,8 @@ function ok(stdout = ""): RunResult { return { status: 0, stdout, stderr: "" }; } -function runNvmSweep(tmpHome: string, existing: readonly string[], removed: string[]) { - return runUninstallPlan( +async function runNvmSweep(tmpHome: string, existing: readonly string[], removed: string[]) { + return await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: false }, { commandExists: (command) => command !== "docker" && command !== "lsof" && command !== "pgrep", @@ -48,7 +48,7 @@ function runNvmSweep(tmpHome: string, existing: readonly string[], removed: stri } describe("uninstall NVM leftovers", () => { - it("removes package-owned CLI bins and preserves foreign same-named entries (#9500)", () => { + it("removes package-owned CLI bins and preserves foreign same-named entries (#9500)", async () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-nvm-bins-")); const nodeVersionsDir = path.join(tmpHome, ".nvm", "versions", "node"); const ownedVersion = path.join(nodeVersionsDir, "v22.19.0"); @@ -94,7 +94,7 @@ describe("uninstall NVM leftovers", () => { const removed: string[] = []; try { - const result = runNvmSweep(tmpHome, [...shims, nodeVersionsDir], removed); + const result = await runNvmSweep(tmpHome, [...shims, nodeVersionsDir], removed); expect(result.exitCode).toBe(0); expect(links.filter((entry) => removed.includes(entry))).toEqual([...shims, ...ownedBins]); } finally { @@ -102,7 +102,7 @@ describe("uninstall NVM leftovers", () => { } }); - it("preserves a linked package while removing its package-owned CLI bins", () => { + it("preserves a linked package while removing its package-owned CLI bins", async () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-nvm-link-")); const versionDir = path.join(tmpHome, ".nvm", "versions", "node", "v22.19.0"); const packageLink = path.join(versionDir, "lib", "node_modules", "nemoclaw"); @@ -133,7 +133,7 @@ describe("uninstall NVM leftovers", () => { const removed: string[] = []; try { const nodeVersionsDir = path.join(tmpHome, ".nvm", "versions", "node"); - expect(runNvmSweep(tmpHome, [nodeVersionsDir], removed).exitCode).toBe(0); + expect((await runNvmSweep(tmpHome, [nodeVersionsDir], removed)).exitCode).toBe(0); expect(new Set(removed)).toEqual(new Set(bins)); bins.forEach((bin) => expect(fs.existsSync(bin)).toBe(false)); expect(fs.readlinkSync(packageLink)).toBe(linkedPackage); @@ -145,7 +145,7 @@ describe("uninstall NVM leftovers", () => { it.each(["versions", "modules", "bin"] as const)( "skips an unreadable NVM %s directory without deleting its bin", - (blockedDirectory) => { + async (blockedDirectory) => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-nvm-unreadable-")); const nodeVersionsDir = path.join(tmpHome, ".nvm", "versions", "node"); const versionDir = path.join(nodeVersionsDir, "v22.19.0"); @@ -179,7 +179,7 @@ describe("uninstall NVM leftovers", () => { }) as typeof fs.readdirSync); try { const removed: string[] = []; - expect(runNvmSweep(tmpHome, [nodeVersionsDir], removed).exitCode).toBe(0); + expect((await runNvmSweep(tmpHome, [nodeVersionsDir], removed)).exitCode).toBe(0); expect(removed).not.toContain(bin); } finally { spy.mockRestore(); diff --git a/src/lib/actions/uninstall/run-plan-other-gateway-report.test.ts b/src/lib/actions/uninstall/run-plan-other-gateway-report.test.ts index 9333b99349c..4253aadd5ea 100644 --- a/src/lib/actions/uninstall/run-plan-other-gateway-report.test.ts +++ b/src/lib/actions/uninstall/run-plan-other-gateway-report.test.ts @@ -70,14 +70,14 @@ function withManagedAuthority(deps: UninstallRunDeps): UninstallRunDeps { }); } -function uninstallOutputFor( +async function uninstallOutputFor( registry: string | null, liveGatewayNames: readonly string[], retainedGatewayPorts: readonly number[] = [], env: NodeJS.ProcessEnv = { NO_COLOR: "1" }, stderrIsTty = false, stderrHasColors = stderrIsTty, -): { logs: string[]; warnings: string[] } { +): Promise<{ logs: string[]; warnings: string[] }> { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-report-")); const logs: string[] = []; const warnings: string[] = []; @@ -93,7 +93,7 @@ function uninstallOutputFor( writeRegistry[registry === null ? "absent" : "present"](); const gatewayList = JSON.stringify(liveGatewayNames.map((name) => ({ name }))); - runUninstallPlan( + await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, withManagedAuthority({ commandExists: () => true, @@ -130,8 +130,8 @@ describe("uninstall reporting for other gateway-port environments (#7791)", () = ["a live sibling gateway with no registry row", null], ] as const)( "warns that %s remains after the selected-port uninstall (#8797)", - (_scenario, registry) => { - const { logs, warnings } = uninstallOutputFor(registry, ["nemoclaw", "nemoclaw-9000"]); + async (_scenario, registry) => { + const { logs, warnings } = await uninstallOutputFor(registry, ["nemoclaw", "nemoclaw-9000"]); expect(warnings).toContainEqual( expect.stringContaining("⚠ Other NemoClaw gateway-port environments remain on this host"), @@ -147,23 +147,29 @@ describe("uninstall reporting for other gateway-port environments (#7791)", () = }, ); - it("colors the retained gateway warning only for interactive stderr without NO_COLOR (#8797)", () => { + it("colors the retained gateway warning only for interactive stderr without NO_COLOR (#8797)", async () => { vi.stubEnv("NO_COLOR", undefined); - const { warnings } = uninstallOutputFor(null, ["nemoclaw", "nemoclaw-9000"], [], {}, true); - const { warnings: redirectedWarnings } = uninstallOutputFor( + const { warnings } = await uninstallOutputFor( + null, + ["nemoclaw", "nemoclaw-9000"], + [], + {}, + true, + ); + const { warnings: redirectedWarnings } = await uninstallOutputFor( null, ["nemoclaw", "nemoclaw-9000"], [], {}, ); - const { warnings: noColorWarnings } = uninstallOutputFor( + const { warnings: noColorWarnings } = await uninstallOutputFor( null, ["nemoclaw", "nemoclaw-9000"], [], { NO_COLOR: "" }, true, ); - const { warnings: unsupportedColorWarnings } = uninstallOutputFor( + const { warnings: unsupportedColorWarnings } = await uninstallOutputFor( null, ["nemoclaw", "nemoclaw-9000"], [], @@ -189,8 +195,8 @@ describe("uninstall reporting for other gateway-port environments (#7791)", () = expect(unsupportedColorWarnings).not.toContainEqual(expect.stringContaining("\x1b[33m")); }); - it("stays silent about other gateway ports when this host has none", () => { - const { logs, warnings } = uninstallOutputFor(null, ["nemoclaw"]); + it("stays silent about other gateway ports when this host has none", async () => { + const { logs, warnings } = await uninstallOutputFor(null, ["nemoclaw"]); expect(logs).not.toContainEqual( expect.stringContaining("gateway-port environments remain on this host"), @@ -202,8 +208,8 @@ describe("uninstall reporting for other gateway-port environments (#7791)", () = expect(warnings).not.toContainEqual(expect.stringContaining("--all-gateway-ports")); }); - it("keeps shared host resources for a failed sweep port whose gateway is already gone (#7791)", () => { - const { logs, warnings } = uninstallOutputFor(null, ["nemoclaw"], [9000]); + it("keeps shared host resources for a failed sweep port whose gateway is already gone (#7791)", async () => { + const { logs, warnings } = await uninstallOutputFor(null, ["nemoclaw"], [9000]); expect(warnings).toContainEqual(" · gateway 'nemoclaw-9000' on port 9000"); expect(logs).toContainEqual( @@ -214,9 +220,9 @@ describe("uninstall reporting for other gateway-port environments (#7791)", () = ); }); - it("returns nonzero when the orphan gateway-process scan cannot run", () => { + it("returns nonzero when the orphan gateway-process scan cannot run", async () => { const errors: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, destroyUserData: true, keepOpenShell: false }, withManagedAuthority({ commandExists: (command) => command === "openshell", diff --git a/src/lib/actions/uninstall/run-plan-portable-leftover-state.test.ts b/src/lib/actions/uninstall/run-plan-portable-leftover-state.test.ts index dcbf89ce8e7..cbcd0150b92 100644 --- a/src/lib/actions/uninstall/run-plan-portable-leftover-state.test.ts +++ b/src/lib/actions/uninstall/run-plan-portable-leftover-state.test.ts @@ -89,8 +89,8 @@ function deps(host: ReturnType): UninstallRunDeps { }; } -function uninstall(host: ReturnType, destroyUserData = false) { - return runUninstallPlanBase( +async function uninstall(host: ReturnType, destroyUserData = false) { + return await runUninstallPlanBase( { assumeYes: true, deleteModels: false, destroyUserData, keepOpenShell: false }, withSuccessfulPreUninstallBackup(deps(host)), ); diff --git a/src/lib/actions/uninstall/run-plan-portable-runtime.test.ts b/src/lib/actions/uninstall/run-plan-portable-runtime.test.ts index 712ed722c86..ee1cb54cc4b 100644 --- a/src/lib/actions/uninstall/run-plan-portable-runtime.test.ts +++ b/src/lib/actions/uninstall/run-plan-portable-runtime.test.ts @@ -66,12 +66,12 @@ function withManagedGatewayAuthority(deps: UninstallRunDeps): UninstallRunDeps { }; } -function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { - return runUninstallPlanBase(options, withManagedGatewayAuthority(deps)); +async function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { + return await runUninstallPlanBase(options, withManagedGatewayAuthority(deps)); } -function runUninstallPlanWithBackup(options: UninstallRunOptions, deps: UninstallRunDeps) { - return runUninstallPlanProduction( +async function runUninstallPlanWithBackup(options: UninstallRunOptions, deps: UninstallRunDeps) { + return await runUninstallPlanProduction( options, withSuccessfulPreUninstallBackup(withManagedGatewayAuthority(deps)), ); @@ -261,11 +261,11 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption (_home, state) => directoryEvidence(path.join(state, "portable-demo-lifecycle"), 0o700, 1_025), ], - ])("rejects %s before generic effects (#9189)", (_case, mutate) => { + ])("rejects %s before generic effects (#9189)", async (_case, mutate) => { const scope = admissionFailureScope("nemoclaw-portable-admission-"); const evidence = mutate(scope.homeDir, scope.stateDir); const expectedRegistry = fs.readFileSync(scope.registry, "utf8"); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: true, destroyUserData: true, keepOpenShell: false }, admissionFailureDeps(scope), ); @@ -412,7 +412,7 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption expect(fs.existsSync(journalEvidence)).toBe(true); }); - it("uses exact receipt names with external gateway state and no all-sandbox mutation (#10544)", () => { + it("uses exact receipt names with external gateway state and no all-sandbox mutation (#10544)", async () => { const order: string[] = []; const logs: string[] = []; const registeredSandboxes = new Set(["alpha", "unrelated"]); @@ -475,7 +475,7 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption const runDocker = vi.fn(() => ok("")); const kill = vi.fn(() => true); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: true, keepOpenShell: false }, { commandExists: (command) => @@ -533,7 +533,7 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption expect(logs.join("\n")).toContain("exact retry and lifecycle reconciliation"); }); - it("keeps explicit receipt gateway scope when ambient selection drifts (#9189)", () => { + it("keeps explicit receipt gateway scope when ambient selection drifts (#9189)", async () => { const registeredSandboxes = new Set([ "nemoclaw/alpha", "nemoclaw/beta", @@ -601,7 +601,7 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption }, ); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: false }, { commandExists: (command) => ["openshell", "pgrep", "lsof"].includes(command), @@ -656,7 +656,7 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption ).toEqual(ok("other/alpha usable")); }); - it("settles one failed delete only after the connected gateway proves exact absence (#9499)", () => { + it("settles one failed delete only after the connected gateway proves exact absence (#9499)", async () => { const registeredSandboxes = new Set(["unrelated"]); const { homeDir, sharedPaths: sharedOpenShellPaths } = sharedOpenShellFixture( "nemoclaw-portable-absent-", @@ -698,7 +698,7 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption }, ); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: false }, { commandExists: (command) => ["openshell", "pgrep", "lsof"].includes(command), @@ -737,7 +737,7 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption ["exit zero while the sandbox remains", Number.POSITIVE_INFINITY, 1, 4], ])( "%s after a scoped delete uses bounded exact-name verification (#9189)", - (_case, absentAttempt, expectedExit, expectedSleeps) => { + async (_case, absentAttempt, expectedExit, expectedSleeps) => { let getCalls = 0; const sleep = vi.fn(); const runHandlers = new Map RunResult>([ @@ -772,7 +772,7 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption : null, ); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, destroyUserData: true, keepOpenShell: false }, { commandExists: (command) => ["openshell", "pgrep", "lsof"].includes(command), @@ -835,7 +835,7 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption ], ])( "rejects %s and preserves all retry evidence (#9189)", - (_caseName, deleteError, statusResult, expectedError) => { + async (_caseName, deleteError, statusResult, expectedError) => { const removed: string[] = []; const errors: string[] = []; const registeredSandboxes = new Set(["alpha", "unrelated"]); @@ -902,7 +902,7 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption }, ); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, @@ -954,7 +954,7 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption }, ); - it("preserves retry evidence after an exact cleanup failure with destroy data (#9189)", () => { + it("preserves retry evidence after an exact cleanup failure with destroy data (#9189)", async () => { const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-portable-retry-cli-")); temporaryDirectories.push(homeDir); const sourceMarker = path.join(homeDir, ".nemoclaw/source/retry-source-marker"); @@ -965,7 +965,7 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption const run = vi.fn((command: string, args: string[]) => ["pgrep", "lsof"].includes(command) ? notFound() : okWithKnownGatewayList(command, args), ); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, @@ -998,7 +998,7 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption it.each(["config", "registry"] as const)( "keeps repeated %s-stage retirement uninstalls out of generic cleanup (#9189)", - (crashTarget) => { + async (crashTarget) => { const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-portable-repeat-")); temporaryDirectories.push(homeDir); const stateDir = path.join(homeDir, ".nemoclaw"); @@ -1048,8 +1048,8 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption runDocker, runHuggingFaceCacheDataCleanup: runModelCleanup, runLocalModelRuntimeCleanup: runModelCleanup, - runPortableRuntimeCleanupTransaction: (input, continueAfterSandboxRemoval) => - runPortableRuntimeCleanupTransaction(input, continueAfterSandboxRemoval, { + runPortableRuntimeCleanupTransaction: async (input, continueAfterSandboxRemoval) => + await runPortableRuntimeCleanupTransaction(input, continueAfterSandboxRemoval, { withRegistryLock: (_registryFile, operation) => { !stagedObserved && expect(fs.existsSync(stage)).toBe(true); stagedObserved = true; @@ -1059,15 +1059,19 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption }; expect( - runUninstallPlan( - { assumeYes: true, deleteModels: true, destroyUserData: true, keepOpenShell: false }, - deps, + ( + await runUninstallPlan( + { assumeYes: true, deleteModels: true, destroyUserData: true, keepOpenShell: false }, + deps, + ) ).exitCode, ).toBe(0); expect( - runUninstallPlan( - { assumeYes: true, deleteModels: true, destroyUserData: true, keepOpenShell: false }, - deps, + ( + await runUninstallPlan( + { assumeYes: true, deleteModels: true, destroyUserData: true, keepOpenShell: false }, + deps, + ) ).exitCode, ).toBe(0); expect(runDocker).not.toHaveBeenCalled(); @@ -1081,7 +1085,7 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption }, ); - it("stops state deletion when portable state changes after sandbox removal (#9189)", () => { + it("stops state deletion when portable state changes after sandbox removal (#9189)", async () => { const errors: string[] = []; const removed: string[] = []; const runPortableCleanup = vi.fn( @@ -1100,7 +1104,7 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption }, ); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, @@ -1249,7 +1253,7 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption } }); - it("leaves keep-openshell and external-supervisor flows unchanged (#9189)", () => { + it("leaves keep-openshell and external-supervisor flows unchanged (#9189)", async () => { const hasPortable = vi.fn(() => true); const runPortableCleanup = vi.fn(() => ({ registryRemoved: true, @@ -1270,29 +1274,35 @@ describe("portable runtime cleanup in the uninstall run plan", testTimeoutOption }; expect( - runUninstallPlan({ assumeYes: true, deleteModels: false, keepOpenShell: true }, baseDeps) - .exitCode, + ( + await runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: true }, + baseDeps, + ) + ).exitCode, ).toBe(0); expect( - runUninstallPlan( - { assumeYes: true, deleteModels: false, keepOpenShell: false }, - { - ...baseDeps, - resolveGatewayTeardownAuthority: ({ gatewayName, gatewayPort }) => ({ - gatewayName, - gatewayPort, - mode: "externally-supervised", - source: "declared", - endpoint: "https://127.0.0.1:8080", - stateDir: "/srv/external-openshell", - supervisor: { - kind: "systemd-system", - serviceName: "external-openshell.service", - execPath: "/usr/local/bin/openshell-gateway", - }, - requiredCapabilities: [], - }), - }, + ( + await runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: false }, + { + ...baseDeps, + resolveGatewayTeardownAuthority: ({ gatewayName, gatewayPort }) => ({ + gatewayName, + gatewayPort, + mode: "externally-supervised", + source: "declared", + endpoint: "https://127.0.0.1:8080", + stateDir: "/srv/external-openshell", + supervisor: { + kind: "systemd-system", + serviceName: "external-openshell.service", + execPath: "/usr/local/bin/openshell-gateway", + }, + requiredCapabilities: [], + }), + }, + ) ).exitCode, ).toBe(0); expect(hasPortable).not.toHaveBeenCalled(); diff --git a/src/lib/actions/uninstall/run-plan-pre-uninstall-backup.test.ts b/src/lib/actions/uninstall/run-plan-pre-uninstall-backup.test.ts index f8734d46abc..aeaa62eae1f 100644 --- a/src/lib/actions/uninstall/run-plan-pre-uninstall-backup.test.ts +++ b/src/lib/actions/uninstall/run-plan-pre-uninstall-backup.test.ts @@ -134,10 +134,10 @@ describe("pre-uninstall sandbox backup", () => { expect(fixture.logs).toContain("Backing up current sandbox state before uninstall..."); }); - it("stops the synchronous entrypoint before protected sandbox deletion", () => { + it("stops the synchronous entrypoint before protected sandbox deletion", async () => { const fixture = createFixture(); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, fixture.deps, ); diff --git a/src/lib/actions/uninstall/run-plan-preserved-registry.test.ts b/src/lib/actions/uninstall/run-plan-preserved-registry.test.ts index 9efd3ac3eda..cdcf1cbb60e 100644 --- a/src/lib/actions/uninstall/run-plan-preserved-registry.test.ts +++ b/src/lib/actions/uninstall/run-plan-preserved-registry.test.ts @@ -31,8 +31,8 @@ function notFound(): RunResult { return { status: 1, stdout: "", stderr: "" }; } -function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { - return runUninstallPlanBase( +async function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { + return await runUninstallPlanBase( options, withSuccessfulPreUninstallBackup({ resolveGatewayTeardownAuthority: ({ gatewayName, gatewayPort }) => ({ diff --git a/src/lib/actions/uninstall/run-plan.test.ts b/src/lib/actions/uninstall/run-plan.test.ts index 697ad7a0226..2bfd6f44d17 100644 --- a/src/lib/actions/uninstall/run-plan.test.ts +++ b/src/lib/actions/uninstall/run-plan.test.ts @@ -47,12 +47,12 @@ function withManagedGatewayAuthority(deps: UninstallRunDeps): UninstallRunDeps { }; } -function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { - return runUninstallPlanBase(options, withManagedGatewayAuthority(deps)); +async function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) { + return await runUninstallPlanBase(options, withManagedGatewayAuthority(deps)); } -function runUninstallPlanWithBackup(options: UninstallRunOptions, deps: UninstallRunDeps) { - return runUninstallPlanProduction( +async function runUninstallPlanWithBackup(options: UninstallRunOptions, deps: UninstallRunDeps) { + return await runUninstallPlanProduction( options, withSuccessfulPreUninstallBackup(withManagedGatewayAuthority(deps)), ); @@ -107,7 +107,7 @@ describe("uninstall run plan", () => { ); }); - it("applies a non-destructive uninstall run with fake tools", () => { + it("applies a non-destructive uninstall run with fake tools", async () => { const logs: string[] = []; const run = vi.fn((command: string, args: string[]) => { if (args[0] === "-c") return ok("/fake/bin/tool\n"); @@ -122,7 +122,7 @@ describe("uninstall run plan", () => { return ok(); }); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -158,7 +158,7 @@ describe("uninstall run plan", () => { ).toBe(true); }); - it("removes all managed OpenShell helper binaries from the writable user bin", () => { + it("removes all managed OpenShell helper binaries from the writable user bin", async () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-openshell-bins-")); const userBin = path.join(tmpHome, ".local", "bin"); fs.mkdirSync(userBin, { recursive: true }); @@ -173,7 +173,7 @@ describe("uninstall run plan", () => { ]); try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: false }, { commandExists: (command) => @@ -208,7 +208,7 @@ describe("uninstall run plan", () => { } }); - it("removes sibling CLI wrapper shims via binName-aware fd-read classification (#6098)", () => { + it("removes sibling CLI wrapper shims via binName-aware fd-read classification (#6098)", async () => { // Symlinks classify via the metadata fast path. Wrapper scripts go through // classifyShimPath's fd-read branch which reads the file and matches the // wrapper contract with the per-alias binName. Both paths must remove. @@ -231,7 +231,7 @@ describe("uninstall run plan", () => { const removed: string[] = []; try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: false }, { commandExists: (command) => @@ -257,11 +257,11 @@ describe("uninstall run plan", () => { } }); - it("uses NemoHermes uninstall copy when Hermes is the active agent", () => { + it("uses NemoHermes uninstall copy when Hermes is the active agent", async () => { const logs: string[] = []; const warnings: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: false, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command === "openshell", @@ -295,7 +295,7 @@ describe("uninstall run plan", () => { expect(logs).not.toContain("Claws retracted. Until next time."); }); - it("accepts typed interactive confirmation", () => { + it("accepts typed interactive confirmation", async () => { const logs: string[] = []; const run = vi.fn((_command: string, args: string[]) => { if (args[0] === "-c") return ok("/fake/bin/tool\n"); @@ -303,7 +303,7 @@ describe("uninstall run plan", () => { return okWithKnownGatewayList(_command, args); }); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: false, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command === "openshell", @@ -324,10 +324,10 @@ describe("uninstall run plan", () => { expect(logs).toContain("Claws retracted. Until next time."); }); - it("aborts without applying the plan when confirmation is declined", () => { + it("aborts without applying the plan when confirmation is declined", async () => { const logs: string[] = []; const run = vi.fn(); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: false, deleteModels: false, keepOpenShell: true }, { commandExists: () => false, @@ -343,10 +343,10 @@ describe("uninstall run plan", () => { expect(run).not.toHaveBeenCalled(); }); - it("explains how to proceed when stdin yields no input at the confirm prompt", () => { + it("explains how to proceed when stdin yields no input at the confirm prompt", async () => { const logs: string[] = []; const run = vi.fn(); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: false, deleteModels: false, keepOpenShell: true }, { commandExists: () => false, @@ -365,10 +365,10 @@ describe("uninstall run plan", () => { expect(run).not.toHaveBeenCalled(); }); - it("builds the default runtime without touching process.stdin (#5188)", () => { + it("builds the default runtime without touching process.stdin (#5188)", async () => { const stdinGet = vi.spyOn(process, "stdin", "get"); try { - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command === "openshell", @@ -391,7 +391,7 @@ describe("uninstall run plan", () => { } }); - it("kills the Ollama auth proxy via the persisted PID file (#2759)", () => { + it("kills the Ollama auth proxy via the persisted PID file (#2759)", async () => { const logs: string[] = []; const killed: number[] = []; const exited = new Set(); @@ -403,7 +403,7 @@ describe("uninstall run plan", () => { try { const stub = psStub("44321", { exited }); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -440,7 +440,7 @@ describe("uninstall run plan", () => { } }); - it("kills an orphan auth proxy via lsof :11435 when the PID file is gone", () => { + it("kills an orphan auth proxy via lsof :11435 when the PID file is gone", async () => { const logs: string[] = []; const killed: number[] = []; const exited = new Set(); @@ -448,7 +448,7 @@ describe("uninstall run plan", () => { exited, cmdline: "/usr/bin/node /opt/nemoclaw/scripts/ollama-auth-proxy.mts\n", }); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -486,11 +486,11 @@ describe("uninstall run plan", () => { expect(logs).toContain("Stopped Ollama auth proxy 55678"); }); - it("never stops a foreign-owned auth proxy on :11435 even if cmdline matches", () => { + it("never stops a foreign-owned auth proxy on :11435 even if cmdline matches", async () => { const logs: string[] = []; const killed: number[] = []; const stub = psStub("77777", { exited: new Set(), owner: "someone-else" }); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -527,13 +527,13 @@ describe("uninstall run plan", () => { expect(logs).toContain("No Ollama auth proxy processes found"); }); - it("uses the persisted Ollama proxy port for orphan cleanup (#8704)", () => { + it("uses the persisted Ollama proxy port for orphan cleanup (#8704)", async () => { const logs: string[] = []; const killed: number[] = []; const exited = new Set(); const stub = psStub("33333", { exited }); const lsofPorts: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -586,14 +586,14 @@ describe("uninstall run plan", () => { it.each(["ollama-auth-proxy-helper.mjs", "ollama-auth-proxy.mts.backup"])( "never kills the near-named %s process on :11435", - (scriptName) => { + async (scriptName) => { const logs: string[] = []; const killed: number[] = []; const stub = psStub("99999", { exited: new Set(), cmdline: `/usr/bin/node /opt/nemoclaw/scripts/${scriptName}\n`, }); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -631,7 +631,7 @@ describe("uninstall run plan", () => { }, ); - it("kills the model router via onboard-session routerPid (#5169)", () => { + it("kills the model router via onboard-session routerPid (#5169)", async () => { const logs: string[] = []; const killed: number[] = []; const exited = new Set(); @@ -643,7 +643,7 @@ describe("uninstall run plan", () => { try { const stub = psStub("55432", { exited, cmdline: MODEL_ROUTER_CMDLINE }); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -679,12 +679,12 @@ describe("uninstall run plan", () => { } }); - it("kills an orphan model router via lsof :4000 when onboard-session is gone", () => { + it("kills an orphan model router via lsof :4000 when onboard-session is gone", async () => { const logs: string[] = []; const killed: number[] = []; const exited = new Set(); const stub = psStub("55679", { exited, cmdline: MODEL_ROUTER_CMDLINE }); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -725,7 +725,7 @@ describe("uninstall run plan", () => { expect(logs).toContain("Stopped model router 55679"); }); - it("never stops a foreign-owned model router on :4000 even if cmdline matches", () => { + it("never stops a foreign-owned model router on :4000 even if cmdline matches", async () => { const logs: string[] = []; const killed: number[] = []; const stub = psStub("77888", { @@ -733,7 +733,7 @@ describe("uninstall run plan", () => { owner: "someone-else", cmdline: MODEL_ROUTER_CMDLINE, }); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -773,14 +773,14 @@ describe("uninstall run plan", () => { expect(logs).toContain("No model router processes found"); }); - it("never kills a process on :4000 whose cmdline is not the model router", () => { + it("never kills a process on :4000 whose cmdline is not the model router", async () => { const logs: string[] = []; const killed: number[] = []; const stub = psStub("88888", { exited: new Set(), cmdline: "/usr/sbin/nginx -g daemon off;\n", }); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -820,7 +820,7 @@ describe("uninstall run plan", () => { expect(logs).toContain("No model router processes found"); }); - it("escalates to SIGKILL and reports failure when SIGTERM is ignored", () => { + it("escalates to SIGKILL and reports failure when SIGTERM is ignored", async () => { const logs: string[] = []; const warnings: string[] = []; const signals: NodeJS.Signals[] = []; @@ -833,7 +833,7 @@ describe("uninstall run plan", () => { // exited stays empty — pidExists() always reports alive, simulating a // process that ignores SIGTERM and survives SIGKILL. const stub = psStub("44322", { exited: new Set() }); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -870,10 +870,10 @@ describe("uninstall run plan", () => { } }); - it("warns instead of claiming success when lsof is unavailable for orphan scan", () => { + it("warns instead of claiming success when lsof is unavailable for orphan scan", async () => { const logs: string[] = []; const warnings: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command !== "lsof", @@ -898,9 +898,9 @@ describe("uninstall run plan", () => { expect(logs).not.toContain("No Ollama auth proxy processes found"); }); - it("logs and continues when no Ollama auth proxy is running", () => { + it("logs and continues when no Ollama auth proxy is running", async () => { const logs: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, @@ -924,10 +924,10 @@ describe("uninstall run plan", () => { expect(logs).toContain("No Ollama auth proxy processes found"); }); - it("does not report swap cleanup success when swapoff fails", () => { + it("does not report swap cleanup success when swapoff fails", async () => { const warnings: string[] = []; const logs: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command !== "docker" && command !== "pgrep", @@ -1069,11 +1069,11 @@ describe("uninstall run plan", () => { } }); - it("purges the whole state dir when NEMOCLAW_UNINSTALL_DESTROY_USER_DATA=1 is set", () => { + it("purges the whole state dir when NEMOCLAW_UNINSTALL_DESTROY_USER_DATA=1 is set", async () => { const { tmpHome, stateDir } = setupStateDir(); try { const logs: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, preserveCaseDeps(tmpHome, logs, { envOverrides: { NEMOCLAW_UNINSTALL_DESTROY_USER_DATA: "1" }, @@ -1092,11 +1092,11 @@ describe("uninstall run plan", () => { } }); - it("purges the whole state dir when destroyUserData is set, even with --yes on a non-TTY", () => { + it("purges the whole state dir when destroyUserData is set, even with --yes on a non-TTY", async () => { const { tmpHome, stateDir } = setupStateDir(); try { const logs: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, destroyUserData: true, keepOpenShell: true }, preserveCaseDeps(tmpHome, logs), ); @@ -1113,12 +1113,12 @@ describe("uninstall run plan", () => { } }); - it("destroyUserData purges on a TTY without prompting", () => { + it("destroyUserData purges on a TTY without prompting", async () => { const { tmpHome, stateDir } = setupStateDir(); const readLine = vi.fn(() => "y"); try { const logs: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, destroyUserData: true, keepOpenShell: true }, preserveCaseDeps(tmpHome, logs, { isTty: true, readLine }), ); @@ -1139,11 +1139,11 @@ describe("uninstall run plan", () => { } }); - it("destroyUserData without --yes renders a purge-aware global confirmation and skips the user-data prompt", () => { + it("destroyUserData without --yes renders a purge-aware global confirmation and skips the user-data prompt", async () => { const { tmpHome, stateDir } = setupStateDir(); try { const logs: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: false, deleteModels: false, destroyUserData: true, keepOpenShell: true }, preserveCaseDeps(tmpHome, logs, { isTty: true, readLine: () => "y" }), ); @@ -1170,11 +1170,11 @@ describe("uninstall run plan", () => { } }); - it("env var without --yes renders a purge-aware global confirmation", () => { + it("env var without --yes renders a purge-aware global confirmation", async () => { const { tmpHome, stateDir } = setupStateDir(); try { const logs: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: false, deleteModels: false, keepOpenShell: true }, preserveCaseDeps(tmpHome, logs, { envOverrides: { NEMOCLAW_UNINSTALL_DESTROY_USER_DATA: "1" }, @@ -1193,11 +1193,11 @@ describe("uninstall run plan", () => { } }); - it("destroyUserData takes precedence over NEMOCLAW_UNINSTALL_DESTROY_USER_DATA env var", () => { + it("destroyUserData takes precedence over NEMOCLAW_UNINSTALL_DESTROY_USER_DATA env var", async () => { const { tmpHome, stateDir } = setupStateDir(); try { const logs: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, destroyUserData: true, keepOpenShell: true }, preserveCaseDeps(tmpHome, logs, { envOverrides: { NEMOCLAW_UNINSTALL_DESTROY_USER_DATA: "1" }, @@ -1244,12 +1244,12 @@ describe("uninstall run plan", () => { } }); - it("purges via interactive y/N prompt when user answers yes", () => { + it("purges via interactive y/N prompt when user answers yes", async () => { const { tmpHome, stateDir } = setupStateDir(); try { const logs: string[] = []; const replies = ["yes", "y"]; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: false, deleteModels: false, keepOpenShell: true }, preserveCaseDeps(tmpHome, logs, { isTty: true, @@ -1317,7 +1317,7 @@ describe("uninstall run plan", () => { } }); - it("fails closed before cleanup when ~/.nemoclaw cannot be inspected", () => { + it("fails closed before cleanup when ~/.nemoclaw cannot be inspected", async () => { const { tmpHome, stateDir } = setupStateDir(); const realLstat = fs.lstatSync; const lstatSpy = vi.spyOn(fs, "lstatSync").mockImplementation((p: fs.PathLike) => { @@ -1331,7 +1331,7 @@ describe("uninstall run plan", () => { try { const logs: string[] = []; const warnings: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { ...preserveCaseDeps(tmpHome, logs), @@ -1351,7 +1351,7 @@ describe("uninstall run plan", () => { } }); - it("refuses to follow or remove ~/.nemoclaw when it is a symlink", () => { + it("refuses to follow or remove ~/.nemoclaw when it is a symlink", async () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-preserve-")); const realTarget = fs.mkdtempSync( path.join(os.tmpdir(), "nemoclaw-uninstall-preserve-target-"), @@ -1364,7 +1364,7 @@ describe("uninstall run plan", () => { try { const logs: string[] = []; const errors: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command === "openshell", @@ -1391,14 +1391,14 @@ describe("uninstall run plan", () => { } }); - it("skips the preservation notice when no protected entries exist on disk", () => { + it("skips the preservation notice when no protected entries exist on disk", async () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-preserve-")); const stateDir = path.join(tmpHome, ".nemoclaw"); fs.mkdirSync(stateDir, { recursive: true }); fs.writeFileSync(path.join(stateDir, "ollama-auth-proxy.pid"), "1234"); try { const logs: string[] = []; - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command === "openshell", @@ -1421,11 +1421,11 @@ describe("uninstall run plan", () => { }); }); - it("kills host openshell-gateway process during full uninstall (#3516)", () => { + it("kills host openshell-gateway process during full uninstall (#3516)", async () => { const logs: string[] = []; const killed: number[] = []; const exited = new Set(); - const result = runUninstallPlan( + const result = await runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: false }, { commandExists: () => true, diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index 6e9a9623f34..8fe622c6552 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -1,13 +1,18 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { type SpawnSyncOptions, type SpawnSyncReturns, spawnSync } from "node:child_process"; +import type { SpawnSyncOptions } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { isDeepStrictEqual } from "node:util"; -import { dockerSpawnSync } from "../../adapters/docker/exec"; +import { + defaultRun, + defaultRunDocker, + createUninstallProviderAdapter, + type RunResult, +} from "../../adapters/uninstall/commands"; import { type OpenRegularFile, openRegularFileNoFollow } from "../../adapters/fs/regular-file"; import { type AgentBranding, getAgentBranding } from "../../cli/branding"; import { isErrnoException } from "../../core/errno"; @@ -121,11 +126,7 @@ import { withPortableHostFence, } from "./portable-runtime-cleanup"; -export interface RunResult { - status: number | null; - stdout: string; - stderr: string; -} +export type { RunResult } from "../../adapters/uninstall/commands"; export interface UninstallRunOptions { assumeYes: boolean; @@ -175,7 +176,7 @@ export interface UninstallRunDeps { sandboxNames: readonly string[], gatewayName: string, ) => boolean, - ) => PortableRuntimeCleanupResult | null; + ) => PortableRuntimeCleanupResult | null | Promise; stderrHasColors?: boolean; stderrIsTty?: boolean; withPortableHostFence?: typeof withPortableHostFence; @@ -197,22 +198,6 @@ const OPENSHELL_COMMAND_MISSING_ERROR = export const MANAGED_INFERENCE_CONTAINER_NAME_PATTERN = /^(?:nemoclaw-vllm|nemoclaw-vllm-worker|nemoclaw-llama-cpp|nemoclaw-vllm-cluster-rank-[0-9]+)$/; -function toRunResult(result: SpawnSyncReturns): RunResult { - return { - status: result.status, - stdout: typeof result.stdout === "string" ? result.stdout : String(result.stdout ?? ""), - stderr: typeof result.stderr === "string" ? result.stderr : String(result.stderr ?? ""), - }; -} - -function defaultRun(command: string, args: string[], options: SpawnSyncOptions = {}): RunResult { - return toRunResult(spawnSync(command, args, { encoding: "utf-8", ...options })); -} - -function defaultRunDocker(args: string[], options: SpawnSyncOptions = {}): RunResult { - return toRunResult(dockerSpawnSync(args, { encoding: "utf-8", ...options })); -} - function defaultCommandExists(command: string, env: NodeJS.ProcessEnv): boolean { if (!command || command.includes("\0")) return false; const hasPathSeparator = @@ -550,7 +535,7 @@ interface UninstallRuntime { sandboxNames: readonly string[], gatewayName: string, ) => boolean, - ) => PortableRuntimeCleanupResult | null; + ) => PortableRuntimeCleanupResult | null | Promise; stderrHasColors: boolean; stderrIsTty: boolean; warn: (message: string) => void; @@ -1543,14 +1528,14 @@ function finishScopedOpenShellCleanup( ); } -function removeOpenShellResources( +async function removeOpenShellResources( paths: UninstallPaths, options: UninstallRunOptions, runtime: UninstallRuntime, scopedToSelectedGateway: boolean, sandboxNames: readonly string[], teardownAuthority: GatewayOwner, -): boolean { +): Promise { if (!runtime.commandExists("openshell")) { runtime.error(OPENSHELL_COMMAND_MISSING_ERROR); return false; @@ -1594,14 +1579,14 @@ function removeOpenShellResources( onSkip: OPENSHELL_SANDBOXES_DELETE_SKIP_MESSAGE, }, ); - for (const provider of NEMOCLAW_PROVIDERS) { - runOptional( - runtime, - `Deleted provider '${provider}'`, - "openshell", - ["provider", "delete", provider], - { onSkip: providerDeleteSkipMessage(provider) }, - ); + const providerAdapter = createUninstallProviderAdapter(runtime.run, runtime.env); + for (const providerName of NEMOCLAW_PROVIDERS) { + const result = await providerAdapter.deleteProvider({ + target: { kind: "selected" }, + providerName, + }); + if (result.ok) runtime.log(`Deleted provider '${providerName}'`); + else runtime.warn(providerDeleteSkipMessage(providerName)); } return removeGatewayRegistration(runtime, gatewayLabel, !externallySupervised); } @@ -2896,7 +2881,7 @@ function resolvePreserveSet( return PRESERVED_USER_DATA_ENTRIES; } -function executeOpenShellResourceCleanup( +async function executeOpenShellResourceCleanup( paths: UninstallPaths, options: UninstallRunOptions, runtime: UninstallRuntime, @@ -2905,7 +2890,7 @@ function executeOpenShellResourceCleanup( managedHermesStateVolumes: readonly ManagedHermesStateVolumeContext[], teardownAuthority: GatewayOwner, portableRuntimeCleanup: boolean, -): boolean { +): Promise { const externallySupervised = isExternallySupervised(teardownAuthority); const portableCleanupInput: PortableRuntimeCleanupInput = { env: runtime.env, @@ -2917,7 +2902,7 @@ function executeOpenShellResourceCleanup( }; if (portableRuntimeCleanup) { try { - const cleanup = runtime.runPortableRuntimeCleanupTransaction( + const cleanup = await runtime.runPortableRuntimeCleanupTransaction( portableCleanupInput, (removed, receiptSandboxNames, receiptGatewayName) => { runtime.log(`Removed ${String(removed)} receipt-owned portable sandbox container(s).`); @@ -2939,14 +2924,14 @@ function executeOpenShellResourceCleanup( return false; } } else if ( - !removeOpenShellResources( + !(await removeOpenShellResources( paths, options, runtime, scopedToSelectedGateway, sandboxNames, teardownAuthority, - ) + )) ) { return false; } @@ -3161,7 +3146,7 @@ function prepareOpenShellCleanup( } } -function executePlan( +async function executePlan( plan: UninstallPlan, paths: UninstallPaths, options: UninstallRunOptions, @@ -3175,7 +3160,7 @@ function executePlan( teardownAuthority: GatewayOwner, portableRuntimeCleanup: boolean, portableRetirementEntries: ReturnType, -): { ok: boolean } { +): Promise<{ ok: boolean }> { const preparedOpenShellCleanup = prepareOpenShellCleanup( paths, options, @@ -3187,7 +3172,7 @@ function executePlan( const { disposition: openShellCleanup, stateLifecycleLock } = preparedOpenShellCleanup; try { if (openShellCleanup === "blocked") return { ok: false }; - return executePreparedPlan( + return await executePreparedPlan( plan, paths, options, @@ -3208,7 +3193,7 @@ function executePlan( } } -function executePreparedPlan( +async function executePreparedPlan( plan: UninstallPlan, paths: UninstallPaths, options: UninstallRunOptions, @@ -3223,7 +3208,7 @@ function executePreparedPlan( portableRuntimeCleanup: boolean, portableRetirementEntries: ReturnType, openShellCleanup: Exclude, -): { ok: boolean } { +): Promise<{ ok: boolean }> { const externallySupervised = isExternallySupervised(teardownAuthority); let ok = true; const failedManagedLlamaStateDirs: string[] = []; @@ -3337,7 +3322,7 @@ function executePreparedPlan( if (openShellCleanup === "reservation-removed") { runtime.log("No OpenShell gateway resources were created; skipped gateway cleanup."); } else if ( - !executeOpenShellResourceCleanup( + !(await executeOpenShellResourceCleanup( paths, options, runtime, @@ -3346,12 +3331,12 @@ function executePreparedPlan( managedHermesStateVolumes, teardownAuthority, false, - ) + )) ) { return { ok: false }; } } else if (step.name === "NemoClaw CLI") { - const completion = completePortablePlan( + const completion = await completePortablePlan( ok, portableRuntimeCleanup, paths, @@ -3505,7 +3490,7 @@ function executePreparedPlan( return { ok }; } -function completePortablePlan( +async function completePortablePlan( ok: boolean, portable: boolean, paths: UninstallPaths, @@ -3514,11 +3499,11 @@ function completePortablePlan( scoped: boolean, sandboxNames: readonly string[], authority: GatewayOwner, -): { ok: boolean } { +): Promise<{ ok: boolean }> { if (!portable) return { ok: true }; if (!ok) return { ok }; if ( - !executeOpenShellResourceCleanup( + !(await executeOpenShellResourceCleanup( paths, options, runtime, @@ -3527,7 +3512,7 @@ function completePortablePlan( [], authority, true, - ) + )) ) return { ok: false }; runtime.log( @@ -3752,7 +3737,9 @@ function prepareUninstallRun( }; } -function executePreparedUninstall(prepared: PreparedUninstallRun): UninstallRunOutcome { +async function executePreparedUninstall( + prepared: PreparedUninstallRun, +): Promise { const { paths, plan, @@ -3767,7 +3754,7 @@ function executePreparedUninstall(prepared: PreparedUninstallRun): UninstallRunO } = prepared; let ok = false; try { - ({ ok } = executePlan( + ({ ok } = await executePlan( plan, paths, resolvedOptions, @@ -3940,10 +3927,10 @@ async function backUpAndExecutePreparedUninstall( return executePreparedUninstall(prepared); } -export function runUninstallPlan( +export async function runUninstallPlan( options: UninstallRunOptions, deps: UninstallRunDeps = {}, -): UninstallRunOutcome { +): Promise { const preparation = prepareUninstallRun(options, deps); if (preparation.kind === "complete") return preparation.outcome; if (!admitRemovedImmutabilityUninstall(preparation.prepared)) { diff --git a/src/lib/adapters/openshell/provider-adapter-cli-uncertainty.test.ts b/src/lib/adapters/openshell/provider-adapter-cli-uncertainty.test.ts index d5980b730f1..55ac1da2486 100644 --- a/src/lib/adapters/openshell/provider-adapter-cli-uncertainty.test.ts +++ b/src/lib/adapters/openshell/provider-adapter-cli-uncertainty.test.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { createCliOpenShellProviderAdapter } from "./provider-adapter-cli"; import { selectedOpenShellGateway } from "./sandbox-observer"; @@ -11,6 +11,101 @@ function captured(status: number | null, stderr: string) { } describe("CLI OpenShell provider adapter uncertain mutations", () => { + it("captures delete diagnostics without printing raw command output", async () => { + const run = vi.fn(() => captured(1, "provider remains attached")); + const adapter = createCliOpenShellProviderAdapter({ run }); + const result = await adapter.deleteProvider({ + target: selectedOpenShellGateway(), + providerName: "search-prod", + }); + expect(result).toMatchObject({ + ok: false, + error: { kind: "command", reason: "failed" }, + }); + expect(run).toHaveBeenCalledWith( + ["provider", "delete", "search-prod"], + expect.objectContaining({ + suppressOutput: true, + stdio: ["ignore", "pipe", "pipe"], + }), + ); + }); + it.each([ + [ + "connection reset; sandbox 'alpha' not found", + { kind: "transport", reason: "connection_loss" }, + ], + ["unauthorized; sandbox 'alpha' not found", { kind: "authentication" }], + ])( + "does not turn a transport or authentication failure into sandbox absence: %s", + async (stderr, error) => { + const adapter = createCliOpenShellProviderAdapter({ run: () => captured(1, stderr) }); + const result = await adapter.detachProvider({ + target: selectedOpenShellGateway(), + providerName: "search-prod", + sandboxName: "alpha", + }); + expect(result).toMatchObject({ + ok: false, + error, + }); + }, + ); + it.each([ + ["sandbox 'alpha' not found", "sandbox_not_found"], + ["sandbox 'other-box' not found", "failed"], + ["status: NotFound, code: PermissionDenied, message: \"sandbox 'alpha' not found\"", "failed"], + ["sandbox 'other' not found, message: \"sandbox 'alpha' not found\"", "failed"], + ["status: NotFound, message: \"sandbox 'alpha' not found\"", "sandbox_not_found"], + ["sandbox not found", "failed"], + ["sandbox alpha not found", "failed"], + ["sandbox 'alpha' not found\nsandbox 'other-box' not found", "failed"], + ["provider 'search-prod' not found", "not_found"], + ["provider 'sandbox-telegram' not found", "failed"], + ["provider 'other-provider' not found", "failed"], + ["provider search-prod not found", "failed"], + ["NotFound", "failed"], + ])("distinguishes the missing detach resource: %s (#9806)", async (stderr, reason) => { + const adapter = createCliOpenShellProviderAdapter({ run: () => captured(1, stderr) }); + await expect( + adapter.detachProvider({ + target: selectedOpenShellGateway(), + providerName: "search-prod", + sandboxName: "alpha", + }), + ).resolves.toMatchObject({ ok: false, error: { kind: "command", reason } }); + }); + + it.each([ + "provider other-provider is not attached", + "status: NotAttached, provider 'other-provider' is not bound", + "unauthorized; provider search-prod is not attached", + "connection reset; NotAttached", + "internal gateway error: shield 'sentry' is not attached to its expected anchor", + ])("rejects an unrelated or contradictory detach diagnostic: %s", async (stderr) => { + const adapter = createCliOpenShellProviderAdapter({ run: () => captured(1, stderr) }); + await expect( + adapter.detachProvider({ + target: selectedOpenShellGateway(), + providerName: "search-prod", + sandboxName: "alpha", + }), + ).resolves.toMatchObject({ ok: false }); + }); + + it("recognizes the requested sandbox-prefixed provider as missing", async () => { + const adapter = createCliOpenShellProviderAdapter({ + run: () => captured(1, "provider 'sandbox-telegram' not found"), + }); + await expect( + adapter.detachProvider({ + target: selectedOpenShellGateway(), + providerName: "sandbox-telegram", + sandboxName: "alpha", + }), + ).resolves.toMatchObject({ ok: false, error: { kind: "command", reason: "not_found" } }); + }); + it.each([ ["status-less", captured(null, "NotAttached")], [ diff --git a/src/lib/adapters/openshell/provider-adapter-cli.test.ts b/src/lib/adapters/openshell/provider-adapter-cli.test.ts index bed4fb2f015..a7057068905 100644 --- a/src/lib/adapters/openshell/provider-adapter-cli.test.ts +++ b/src/lib/adapters/openshell/provider-adapter-cli.test.ts @@ -1373,7 +1373,7 @@ describe("CLI OpenShell provider adapter", () => { }); }); - it.each(["provider search-prod NotFound", "provider search-prod not found"])( + it.each(["provider 'search-prod' NotFound", "provider 'search-prod' not found"])( "does not report a missing provider as detached: %s (#9806)", async (diagnostic) => { const adapter = createCliOpenShellProviderAdapter({ diff --git a/src/lib/adapters/openshell/provider-adapter-cli.ts b/src/lib/adapters/openshell/provider-adapter-cli.ts index a1068b865b4..e3194f784a1 100644 --- a/src/lib/adapters/openshell/provider-adapter-cli.ts +++ b/src/lib/adapters/openshell/provider-adapter-cli.ts @@ -27,7 +27,11 @@ import { type OpenShellProviderResult, type UpdateOpenShellProviderRequest, } from "./provider-adapter"; -import { reportsExactProviderNotFound } from "./provider-diagnostic-cli"; +import { + reportsExactProviderNotFound, + reportsExactSandboxNotFound, + reportsProviderNotAttached, +} from "./provider-diagnostic-cli"; import { isValidCliOpenShellProviderIdentifier, parseCliOpenShellProviderMetadata, @@ -97,7 +101,6 @@ const TERMINAL_CSI_RE = /(?:\x1B\[|\x9B)[0-?]*[ -/]*[@-~]/gu; const TERMINAL_CONTROL_RE = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/gu; const ATTACHED_TO_SANDBOX_RE = /attached(?:\s|│)+to(?:\s|│)+sandbox\(\s*es?\s*\)?\s*:\s*([^"\n]+?)(?=\.\s+[a-z]|["\n]|$)/iu; -const TOLERATED_DETACH_OUTPUT_RE = /\bNotAttached\b|\bnot\s+attached\b/iu; const PROVIDER_GET_DIAGNOSTIC_LIMIT = 64 * 1024; const REFRESH_STATUS_PATTERN = /^[a-z][a-z0-9_-]{0,31}$/u; const NO_PROVIDER_ATTACHMENTS_RE = /^No providers attached to sandbox\b/mu; @@ -644,7 +647,13 @@ export function createCliOpenShellProviderAdapter( ) => { const targetError = namedGatewayEndpointOverrideError(request.target, environment); if (targetError) return failure(targetError); - const result = invoke(["provider", "delete", request.providerName], request); + const result = invoke( + ["provider", "delete", request.providerName], + request, + undefined, + 2, + true, + ); const output = commandOutput(result); if ( !result.error && @@ -678,6 +687,7 @@ export function createCliOpenShellProviderAdapter( request, undefined, 3, + true, ); const output = commandOutput(result); const error = commandError(result); @@ -685,10 +695,30 @@ export function createCliOpenShellProviderAdapter( !result.error && !result.signal && result.status !== null && - TOLERATED_DETACH_OUTPUT_RE.test(output); + reportsProviderNotAttached(output, request.providerName); if (confirmedIdempotentDetach) { return success({ changed: false }); } + if ( + !result.error && + !result.signal && + result.status !== null && + error?.kind === "command" && + reportsExactSandboxNotFound(output, request.sandboxName, PROVIDER_GET_DIAGNOSTIC_LIMIT) + ) { + return failure({ + kind: "command", + reason: "sandbox_not_found", + message: `OpenShell sandbox not found: '${request.sandboxName}'.`, + }); + } + if ( + error?.kind === "command" && + error.reason === "not_found" && + !reportsExactProviderNotFound(output, request.providerName, PROVIDER_GET_DIAGNOSTIC_LIMIT) + ) { + return failure({ ...error, reason: "failed" }); + } return error ? failure(error) : success({ changed: true }); }; diff --git a/src/lib/adapters/openshell/provider-adapter.ts b/src/lib/adapters/openshell/provider-adapter.ts index 9a381b6a867..f6e6f1d8818 100644 --- a/src/lib/adapters/openshell/provider-adapter.ts +++ b/src/lib/adapters/openshell/provider-adapter.ts @@ -11,6 +11,7 @@ export type OpenShellProviderCommandReason = | "invalid_request" | "not_found" | "profile_incompatible" + | "sandbox_not_found" | "uncertain"; export type OpenShellProviderTransportReason = diff --git a/src/lib/adapters/openshell/provider-diagnostic-cli.ts b/src/lib/adapters/openshell/provider-diagnostic-cli.ts index a991a065eb3..b3afe448144 100644 --- a/src/lib/adapters/openshell/provider-diagnostic-cli.ts +++ b/src/lib/adapters/openshell/provider-diagnostic-cli.ts @@ -105,19 +105,25 @@ function normalizedNotFoundSuffix(value: string): string { function providerNameFromNotFoundLine(line: string): string | null { return ( - providerNameFromNotFoundText(stripDiagnosticPrefixes(line)) ?? providerNameFromMessage(line) + resourceNameFromNotFoundText(stripDiagnosticPrefixes(line)) ?? resourceNameFromMessage(line) ); } -function providerNameFromNotFoundText(text: string): string | null { +function resourceNameFromNotFoundText( + text: string, + resource: "provider" | "sandbox" = "provider", +): string | null { let hasNotFoundStatusPrefix = false; if (text.toLowerCase().startsWith("notfound:")) { text = text.slice("notfound:".length).trimStart(); hasNotFoundStatusPrefix = true; } - const providerPrefix = "provider "; - if (!text.toLowerCase().startsWith(providerPrefix)) return null; - const quoted = readQuotedValue(text, providerPrefix.length); + const resourcePrefix = `${resource} `; + if (!text.toLowerCase().startsWith(resourcePrefix)) return null; + if (resource === "sandbox" && !/^["'`]/u.test(text.slice(resourcePrefix.length).trimStart())) { + return null; + } + const quoted = readQuotedValue(text, resourcePrefix.length); if (!quoted) return null; const suffix = normalizedNotFoundSuffix(text.slice(quoted.end)); return (suffix === "" && hasNotFoundStatusPrefix) || NOT_FOUND_SUFFIXES.has(suffix) @@ -125,7 +131,10 @@ function providerNameFromNotFoundText(text: string): string | null { : null; } -function providerNameFromMessage(line: string): string | null { +function resourceNameFromMessage( + line: string, + resource: "provider" | "sandbox" = "provider", +): string | null { const text = stripDiagnosticPrefixes(line); const markerIndex = text.toLowerCase().indexOf("message:"); if (markerIndex < 0) return null; @@ -135,9 +144,9 @@ function providerNameFromMessage(line: string): string | null { if (quote === "'" || quote === '"' || quote === "`") { const end = text.indexOf(quote, cursor + 1); if (end < 0) return null; - return providerNameFromNotFoundText(text.slice(cursor + 1, end)); + return resourceNameFromNotFoundText(text.slice(cursor + 1, end), resource); } - return providerNameFromNotFoundText(text.slice(cursor)); + return resourceNameFromNotFoundText(text.slice(cursor), resource); } function readMessageValue(line: string): string | null { @@ -232,3 +241,36 @@ export function reportsExactProviderNotFound( return diagnosticLines.every((line) => providerNameFromNotFoundLine(line) === providerName); } + +/** A missing sandbox permits cleanup only when every diagnostic names the requested sandbox. */ +export function reportsExactSandboxNotFound( + output: string, + sandboxName: string, + diagnosticLimit: number, +): boolean { + if (output.length > diagnosticLimit) return false; + const lines = output.split(/\r?\n/).map(stripIssueDecoration).filter(Boolean); + return ( + lines.length > 0 && + lines.every((line) => { + if (lineReportsMissingGateway(line)) return false; + const status = structuredStatusValue(line); + if (status && normalizeStatus(status) !== "notfound") return false; + const text = stripDiagnosticPrefixes(line).replace(/^NotFound,\s*/iu, ""); + // Match the whole structured diagnostic, not a message embedded after + // another resource or conflicting status. Provider parsing is separate. + const message = /^(?:code\s*[:=]\s*NotFound,\s*)?message:\s*(["'`])(.+)\1$/iu.exec(text); + return resourceNameFromNotFoundText(message?.[2] ?? text, "sandbox") === sandboxName; + }) + ); +} + +/** Accept an absent attachment only when the complete diagnostic matches this operation. */ +export function reportsProviderNotAttached(output: string, providerName: string): boolean { + const text = stripDiagnosticPrefixes(output.trim()); + if (/^(?:NotAttached|provider not attached to sandbox)[.!]?$/iu.test(text)) return true; + const compact = /^NotAttached, provider (["'`])(.+)\1 is not bound[.!]?$/iu.exec(text); + if (compact) return compact[2] === providerName; + const named = /^provider (?:(["'`])(.+)\1|([^\s]+)) is not attached[.!]?$/iu.exec(text); + return Boolean(named && (named[2] ?? named[3]) === providerName); +} diff --git a/src/lib/adapters/uninstall/commands.test.ts b/src/lib/adapters/uninstall/commands.test.ts new file mode 100644 index 00000000000..41b480c8e72 --- /dev/null +++ b/src/lib/adapters/uninstall/commands.test.ts @@ -0,0 +1,52 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; + +const { spawn, docker } = vi.hoisted(() => ({ spawn: vi.fn(), docker: vi.fn() })); +vi.mock("node:child_process", () => ({ spawnSync: spawn })); +vi.mock("../docker/exec", () => ({ dockerSpawnSync: docker })); + +import { defaultRun, defaultRunDocker, createUninstallProviderAdapter } from "./commands"; + +describe("uninstall host command execution", () => { + it("preserves command arguments, environment, and captured output", () => { + spawn.mockReturnValue({ status: 7, stdout: "out", stderr: Buffer.from("err") }); + const env = { PATH: "/trusted/bin" }; + expect(defaultRun("openshell", ["provider", "list"], { env })).toEqual({ + status: 7, + stdout: "out", + stderr: "err", + }); + expect(spawn).toHaveBeenCalledExactlyOnceWith("openshell", ["provider", "list"], { + encoding: "utf-8", + env, + }); + }); + + it("uses the Docker boundary and preserves uncertain exit status", () => { + docker.mockReturnValue({ status: null, stdout: null, stderr: undefined }); + expect(defaultRunDocker(["inspect", "owned"], { encoding: "buffer" })).toEqual({ + status: null, + stdout: "", + stderr: "", + }); + expect(docker).toHaveBeenCalledExactlyOnceWith(["inspect", "owned"], { + encoding: "buffer", + }); + }); +}); + +it("binds provider deletion to the uninstall environment and preserves uncertainty", async () => { + const env = { HOME: "/home/uninstall", OPENSHELL_GATEWAY: "owned-gateway" }; + const run = vi.fn(() => ({ status: null, stdout: "", stderr: "connection reset" })); + const adapter = createUninstallProviderAdapter(run, env); + await expect( + adapter.deleteProvider({ target: { kind: "selected" }, providerName: "nvidia-nim" }), + ).resolves.toMatchObject({ ok: false, error: { kind: "command", reason: "uncertain" } }); + expect(run).toHaveBeenCalledExactlyOnceWith( + "openshell", + ["provider", "delete", "nvidia-nim"], + expect.objectContaining({ env }), + ); +}); diff --git a/src/lib/adapters/uninstall/commands.ts b/src/lib/adapters/uninstall/commands.ts new file mode 100644 index 00000000000..6edcf4c0843 --- /dev/null +++ b/src/lib/adapters/uninstall/commands.ts @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { type SpawnSyncOptions, type SpawnSyncReturns, spawnSync } from "node:child_process"; + +import { createCliOpenShellProviderAdapter } from "../openshell/provider-adapter-cli"; +import { dockerSpawnSync } from "../docker/exec"; + +export interface RunResult { + status: number | null; + stdout: string; + stderr: string; +} + +function toRunResult(result: SpawnSyncReturns): RunResult { + return { + status: result.status, + stdout: typeof result.stdout === "string" ? result.stdout : String(result.stdout ?? ""), + stderr: typeof result.stderr === "string" ? result.stderr : String(result.stderr ?? ""), + }; +} + +export function defaultRun( + command: string, + args: string[], + options: SpawnSyncOptions = {}, +): RunResult { + return toRunResult(spawnSync(command, args, { encoding: "utf-8", ...options })); +} + +export function defaultRunDocker(args: string[], options: SpawnSyncOptions = {}): RunResult { + return toRunResult(dockerSpawnSync(args, { encoding: "utf-8", ...options })); +} + +export function createUninstallProviderAdapter(run: typeof defaultRun, env: NodeJS.ProcessEnv) { + return createCliOpenShellProviderAdapter({ + environment: env, + run: (args, options) => run("openshell", args, { ...options, env }), + }); +} diff --git a/src/lib/onboard/experimental/hermes-portable-ollama-gateway-transaction.ts b/src/lib/onboard/experimental/hermes-portable-ollama-gateway-transaction.ts index f3c802323a0..f303c25cff2 100644 --- a/src/lib/onboard/experimental/hermes-portable-ollama-gateway-transaction.ts +++ b/src/lib/onboard/experimental/hermes-portable-ollama-gateway-transaction.ts @@ -7,6 +7,7 @@ import path from "node:path"; import { isDeepStrictEqual } from "node:util"; import { checkOpenAiInferenceProviderProfile } from "../../adapters/openshell/provider-profile-registration"; +import { createManagedProviderAdapter } from "../../adapters/openshell/managed-provider-adapter"; import { ensureConfigDir, rejectSymlinksOnPath } from "../../state/config-io"; import { parseGatewayProviderMetadata } from "../gateway-provider-metadata"; import type { HostLocalInferenceReceiptWriter } from "../runtime-provider/host-local-inference"; @@ -543,10 +544,10 @@ function exactGatewayMutation( observation.kind === "present" && observation.resourceVersion === 1 ? Object.freeze({ id: observation.id, resourceVersion: observation.resourceVersion }) : null; - const deleteRecordedProvider = ( + const deleteRecordedProvider = async ( provider: string, journal: GatewayProviderJournal, - ): GatewayProviderJournal => { + ): Promise => { const authority = journal.providerAuthority; if (journal.phase !== "rolling-back" || !authority) { throw new Error("Hermes Portable inference gateway provider rollback journal is incomplete."); @@ -558,11 +559,18 @@ function exactGatewayMutation( if (!matchesAuthority(current, authority)) { throw new Error("Hermes Portable inference refused to mutate changed gateway authority."); } - const removed = runGatewayOpenshell(["provider", "delete", provider], { - ignoreError: true, - suppressOutput: true, - stdio: ["ignore", "pipe", "pipe"], - timeout: GATEWAY_PROVIDER_MUTATION_TIMEOUT_MS, + const removed = await createManagedProviderAdapter((args, opts) => + runGatewayOpenshell(args, { + ...opts, + ignoreError: true, + suppressOutput: true, + stdio: ["ignore", "pipe", "pipe"], + timeout: GATEWAY_PROVIDER_MUTATION_TIMEOUT_MS, + }), + ).deleteProvider({ + target: { kind: "selected" }, + providerName: provider, + timeoutMs: GATEWAY_PROVIDER_MUTATION_TIMEOUT_MS, }); const after = readExact(provider); if (after.kind === "absent") { @@ -573,7 +581,7 @@ function exactGatewayMutation( "Hermes Portable inference gateway authority changed during recorded rollback.", ); } - if (removed.status !== 0) { + if (!removed.ok) { throw new Error("Hermes Portable inference could not resume its gateway provider rollback."); } throw new Error("Hermes Portable inference gateway provider remained after recorded rollback."); @@ -627,7 +635,7 @@ function exactGatewayMutation( let journal = journalStore.load(); let current = readExact(input.provider); if (journal?.phase === "rolling-back") { - journal = deleteRecordedProvider(input.provider, journal); + journal = await deleteRecordedProvider(input.provider, journal); current = readExact(input.provider); } if (receiptPublished) { @@ -776,7 +784,7 @@ function exactGatewayMutation( throw new Error("Hermes Portable inference gateway provider authority changed."); } }, - rollback() { + async rollback() { let active = journalStore.load(); if (!active) { throw new Error( @@ -817,7 +825,7 @@ function exactGatewayMutation( } active = journalStore.transition(active, "rolling-back", active.providerAuthority); } - deleteRecordedProvider(input.provider, active); + await deleteRecordedProvider(input.provider, active); }, }); }; @@ -1096,7 +1104,7 @@ export interface PreparedHermesPortableOllamaProviderRetirement { journalSha256: string; }>; readonly present: boolean; - readonly removeAndVerify: () => void; + readonly removeAndVerify: () => Promise; readonly verifyAbsent: () => void; } @@ -1177,18 +1185,25 @@ export function prepareHermesPortableOllamaProviderRetirement(options: { journalSha256: createHash("sha256").update(expectedJournal, "utf8").digest("hex"), }), present: initial.kind === "present", - removeAndVerify() { + async removeAndVerify() { requireJournal(); const current = observe(); if (current.kind === "absent") return; if (!matches(current)) { throw new Error("Hermes Portable refused to remove changed gateway provider authority."); } - const removed = options.runGatewayOpenshell(["provider", "delete", "ollama-local"], { - ignoreError: true, - suppressOutput: true, - stdio: ["ignore", "pipe", "pipe"], - timeout: GATEWAY_PROVIDER_MUTATION_TIMEOUT_MS, + const removed = await createManagedProviderAdapter((args, opts) => + options.runGatewayOpenshell(args, { + ...opts, + ignoreError: true, + suppressOutput: true, + stdio: ["ignore", "pipe", "pipe"], + timeout: GATEWAY_PROVIDER_MUTATION_TIMEOUT_MS, + }), + ).deleteProvider({ + target: { kind: "selected" }, + providerName: "ollama-local", + timeoutMs: GATEWAY_PROVIDER_MUTATION_TIMEOUT_MS, }); const after = observe(); if (after.kind === "absent") { @@ -1198,7 +1213,7 @@ export function prepareHermesPortableOllamaProviderRetirement(options: { if (!matches(after)) { throw new Error("Hermes Portable gateway provider changed during uninstall."); } - if (removed.status !== 0) { + if (!removed.ok) { throw new Error("Hermes Portable could not remove its exact gateway provider."); } throw new Error("Hermes Portable gateway provider remained after uninstall."); diff --git a/src/lib/onboard/experimental/hermes-portable-ollama-inference.test.ts b/src/lib/onboard/experimental/hermes-portable-ollama-inference.test.ts index 6756c51e08c..c9e62a37dd3 100644 --- a/src/lib/onboard/experimental/hermes-portable-ollama-inference.test.ts +++ b/src/lib/onboard/experimental/hermes-portable-ollama-inference.test.ts @@ -413,7 +413,7 @@ describe("Hermes Portable Ollama inference activation", () => { id: "portable-ollama-provider", resourceVersion: 1, }); - prepared.removeAndVerify(); + await prepared.removeAndVerify(); expect(fixture.gatewayProvider.isPresent()).toBe(false); const retry = prepareHermesPortableOllamaProviderRetirement({ @@ -421,7 +421,7 @@ describe("Hermes Portable Ollama inference activation", () => { allowAbsent: true, }); expect(retry.present).toBe(false); - retry.removeAndVerify(); + await retry.removeAndVerify(); retry.verifyAbsent(); expect( fixture.gatewayProvider @@ -723,7 +723,7 @@ describe("Hermes Portable Ollama inference activation", () => { runGatewayOpenshell: fixture.gatewayProvider.run, }); expect(retirement.present).toBe(true); - retirement.removeAndVerify(); + await retirement.removeAndVerify(); retirement.verifyAbsent(); }); @@ -1236,7 +1236,9 @@ describe("Hermes Portable Ollama inference activation", () => { createExactGatewayProvider(mutation); fixture.gatewayProvider.bumpResourceVersion(); expect(() => mutation.commit()).toThrow("gateway provider authority changed"); - expect(() => mutation.rollback()).toThrow("refused to delete changed gateway authority"); + await expect(mutation.rollback()).rejects.toThrow( + "refused to delete changed gateway authority", + ); expect(fixture.gatewayProvider.isPresent()).toBe(true); }); @@ -1330,7 +1332,9 @@ describe("Hermes Portable Ollama inference activation", () => { createExactGatewayProvider(mutation); await mutation.commit(); fixture.gatewayProvider.setDeleteFailure(true); - expect(() => mutation.rollback()).toThrow("could not resume its gateway provider rollback"); + await expect(mutation.rollback()).rejects.toThrow( + "could not resume its gateway provider rollback", + ); expect(fixture.gatewayProvider.isPresent()).toBe(true); expect(gatewayJournal(fixture)).toMatchObject({ phase: "rolling-back" }); diff --git a/src/lib/onboard/inference-providers/remote-openai-surface.test.ts b/src/lib/onboard/inference-providers/remote-openai-surface.test.ts index f032ae8ea1a..47108ceb6a5 100644 --- a/src/lib/onboard/inference-providers/remote-openai-surface.test.ts +++ b/src/lib/onboard/inference-providers/remote-openai-surface.test.ts @@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { withCredentialOverrides } from "../../credentials/scoped-overrides"; +import { createManagedProviderAdapter } from "../../adapters/openshell/managed-provider-adapter"; import { noAuthProxy, withOllamaProxyLifecycleTransaction } from "../../inference/ollama/proxy"; import { hydrateCredentialEnv } from "../credential-env"; import { setupRemoteProviderInference } from "./remote"; @@ -22,6 +23,10 @@ const CREDENTIAL_ENV = "COMPATIBLE_ANTHROPIC_API_KEY"; const SANDBOX = "target-box"; const NO_AUTH_ENV = "NEMOCLAW_OLLAMA_PROXY_TOKEN"; const SUCCESS = { status: 0, stdout: "", stderr: "" }; +const ANTHROPIC_PROVIDER = { + ...SUCCESS, + stdout: `Name: ${PROVIDER}\nType: anthropic\nCredential keys: ${CREDENTIAL_ENV}\nConfig keys: ANTHROPIC_BASE_URL`, +}; function makeArgs(sandboxName: string | null) { return { @@ -36,16 +41,11 @@ function makeArgs(sandboxName: string | null) { } function createHarness() { - const runOpenshell = vi.fn(() => SUCCESS); + const runOpenshell = vi.fn((args: string[]) => + args[0] === "provider" && args[1] === "get" ? ANTHROPIC_PROVIDER : SUCCESS, + ); const upsertProvider = vi.fn(async () => ({ ok: true })); const probeOpenAiLikeEndpoint = vi.fn(() => ({ ok: true })); - const readGatewayProviderMetadata = vi.fn(() => ({ - name: PROVIDER, - type: "anthropic", - credentialKeys: [CREDENTIAL_ENV], - configKeys: ["ANTHROPIC_BASE_URL"], - })); - const deleteGatewayProvider = vi.fn(() => ({ ok: true })); const hydrateCredential = vi.fn((_name: string) => "test-secret"); const exitProcess = vi.fn((code: number): never => { throw new Error(`EXIT_CALLED:${code}`); @@ -107,8 +107,6 @@ function createHarness() { redact: vi.fn((value: string) => value), compactText: vi.fn((value: string) => value.trim()), probeOpenAiLikeEndpoint, - readGatewayProviderMetadata, - deleteGatewayProvider, } satisfies RemoteProviderDeps; return { @@ -116,8 +114,6 @@ function createHarness() { runOpenshell, upsertProvider, probeOpenAiLikeEndpoint, - readGatewayProviderMetadata, - deleteGatewayProvider, exitProcess, error, }; @@ -192,14 +188,19 @@ describe("custom Anthropic provider replacement on the OpenAI surface", () => { "test-secret", { skipResponsesProbe: true, pinnedAddresses: ["93.184.216.34"] }, ); - expect(harness.readGatewayProviderMetadata).toHaveBeenCalledWith( - PROVIDER, - harness.runOpenshell, + expect(harness.runOpenshell).toHaveBeenNthCalledWith( + 1, + ["provider", "get", PROVIDER], + expect.objectContaining({ ignoreError: true, suppressOutput: true }), + ); + expect(harness.runOpenshell).toHaveBeenNthCalledWith( + 2, + ["provider", "delete", PROVIDER], + expect.objectContaining({ + ignoreError: true, + suppressOutput: true, + }), ); - expect(harness.runOpenshell).toHaveBeenNthCalledWith(1, ["provider", "delete", PROVIDER], { - ignoreError: true, - suppressOutput: true, - }); expect(harness.probeOpenAiLikeEndpoint.mock.invocationCallOrder[0]).toBeLessThan( harness.runOpenshell.mock.invocationCallOrder[0], ); @@ -210,27 +211,33 @@ describe("custom Anthropic provider replacement on the OpenAI surface", () => { OPENAI_SURFACE, { [CREDENTIAL_ENV]: "test-secret" }, ); - expect(harness.probeOpenAiLikeEndpoint.mock.invocationCallOrder[0]).toBeLessThan( + expect(harness.runOpenshell.mock.invocationCallOrder[1]).toBeLessThan( harness.upsertProvider.mock.invocationCallOrder[0], ); }); it("authorizes detach recovery only for the current sandbox (#6294)", async () => { const harness = createHarness(); - harness.runOpenshell.mockReturnValueOnce({ + const providerAdapter = createManagedProviderAdapter(harness.runOpenshell); + const deleteProvider = vi.spyOn(providerAdapter, "deleteProvider"); + const attached = { status: 1, stdout: "", stderr: `provider '${PROVIDER}' is attached to sandbox(es): ${SANDBOX}`, - }); + }; + harness.runOpenshell.mockReturnValueOnce(ANTHROPIC_PROVIDER).mockReturnValueOnce(attached); - await expect(setupRemoteProviderInference(makeArgs(SANDBOX), harness.deps)).resolves.toEqual({ - done: false, - }); + await expect( + setupRemoteProviderInference(makeArgs(SANDBOX), { ...harness.deps, providerAdapter }), + ).resolves.toEqual({ done: false }); - expect(harness.deleteGatewayProvider).toHaveBeenCalledWith(PROVIDER, { - runOpenshell: harness.runOpenshell, - allowedSandboxes: [SANDBOX], - }); + expect(harness.runOpenshell.mock.calls.slice(0, 4).map(([args]) => args)).toEqual([ + ["provider", "get", PROVIDER], + ["provider", "delete", PROVIDER], + ["sandbox", "provider", "detach", SANDBOX, PROVIDER], + ["provider", "delete", PROVIDER], + ]); + expect(deleteProvider).toHaveBeenCalledTimes(2); expect(harness.upsertProvider).toHaveBeenCalledWith( PROVIDER, "openai", @@ -238,14 +245,43 @@ describe("custom Anthropic provider replacement on the OpenAI surface", () => { OPENAI_SURFACE, { [CREDENTIAL_ENV]: "test-secret" }, ); - expect(harness.deleteGatewayProvider.mock.invocationCallOrder[0]).toBeLessThan( + expect(harness.runOpenshell.mock.invocationCallOrder[3]).toBeLessThan( harness.upsertProvider.mock.invocationCallOrder[0], ); }); + it("does not retry deletion or register a provider after an uncertain detach", async () => { + const harness = createHarness(); + const providerAdapter = createManagedProviderAdapter(harness.runOpenshell); + vi.spyOn(providerAdapter, "detachProvider").mockResolvedValue({ + ok: false, + error: { kind: "command", reason: "uncertain", message: "outcome unknown" }, + }); + harness.runOpenshell.mockReturnValueOnce(ANTHROPIC_PROVIDER).mockReturnValueOnce({ + status: 1, + stdout: "", + stderr: `provider '${PROVIDER}' is attached to sandbox(es): ${SANDBOX}`, + }); + + await expect( + setupRemoteProviderInference(makeArgs(SANDBOX), { ...harness.deps, providerAdapter }), + ).rejects.toThrow("EXIT_CALLED:1"); + + expect(providerAdapter.detachProvider).toHaveBeenCalledExactlyOnceWith({ + target: { kind: "selected" }, + sandboxName: SANDBOX, + providerName: PROVIDER, + }); + expect(harness.runOpenshell.mock.calls.map(([args]) => args)).toEqual([ + ["provider", "get", PROVIDER], + ["provider", "delete", PROVIDER], + ]); + expect(harness.upsertProvider).not.toHaveBeenCalled(); + }); + it("fails closed when a foreign sandbox is attached (#6294)", async () => { const harness = createHarness(); - harness.runOpenshell.mockReturnValueOnce({ + harness.runOpenshell.mockReturnValueOnce(ANTHROPIC_PROVIDER).mockReturnValueOnce({ status: 1, stdout: "", stderr: `provider '${PROVIDER}' is attached to sandbox(es): ${SANDBOX}, foreign-box`, @@ -259,13 +295,13 @@ describe("custom Anthropic provider replacement on the OpenAI surface", () => { expect(harness.error).toHaveBeenCalledWith( expect.stringContaining("attached to other sandbox(es) (foreign-box)"), ); - expect(harness.deleteGatewayProvider).not.toHaveBeenCalled(); + expect(harness.runOpenshell).toHaveBeenCalledTimes(2); expect(harness.upsertProvider).not.toHaveBeenCalled(); }); it("refuses detach recovery without a confirmed sandbox (#6294)", async () => { const harness = createHarness(); - harness.runOpenshell.mockReturnValueOnce({ + harness.runOpenshell.mockReturnValueOnce(ANTHROPIC_PROVIDER).mockReturnValueOnce({ status: 1, stdout: "", stderr: `provider '${PROVIDER}' is attached to sandbox(es): ${SANDBOX}`, @@ -279,7 +315,27 @@ describe("custom Anthropic provider replacement on the OpenAI surface", () => { expect(harness.error).toHaveBeenCalledWith( expect.stringContaining("no target sandbox was confirmed"), ); - expect(harness.deleteGatewayProvider).not.toHaveBeenCalled(); + expect(harness.runOpenshell).toHaveBeenCalledTimes(2); + expect(harness.upsertProvider).not.toHaveBeenCalled(); + }); + + it("reports a redacted provider lookup failure through the setup result", async () => { + const harness = createHarness(); + harness.runOpenshell.mockReturnValueOnce({ + status: 1, + stdout: "", + stderr: "unauthorized token=secret", + }); + harness.deps.redact.mockImplementation((value: string) => value.replaceAll("secret", "safe")); + + await expect(setupRemoteProviderInference(makeArgs(SANDBOX), harness.deps)).rejects.toThrow( + "EXIT_CALLED:1", + ); + + expect(harness.error).toHaveBeenCalledWith( + " Failed to inspect provider 'compatible-anthropic-endpoint' before replacement: OpenShell could not authenticate the provider operation.", + ); + expect(JSON.stringify(harness.error.mock.calls)).not.toContain("secret"); expect(harness.upsertProvider).not.toHaveBeenCalled(); }); }); diff --git a/src/lib/onboard/inference-providers/remote.ts b/src/lib/onboard/inference-providers/remote.ts index 87065367dac..a48d9ad5cca 100644 --- a/src/lib/onboard/inference-providers/remote.ts +++ b/src/lib/onboard/inference-providers/remote.ts @@ -13,8 +13,8 @@ import { withOllamaProxyLifecycleTransaction, } from "../../inference/ollama/proxy"; import { OPENROUTER_PROVIDER_NAME } from "../../inference/openrouter"; -import { readGatewayProviderMetadata } from "../gateway-provider-metadata"; -import { deleteProviderWithRecovery, parseAttachedSandboxes } from "../sandbox-provider-cleanup"; +import { deleteProviderWithRecovery } from "../sandbox-provider-cleanup"; +import { createManagedProviderAdapter } from "../../adapters/openshell/managed-provider-adapter"; import { gatewayReachableCompatibleEndpointUrl, reuseRegisteredProviderWithGatewayEndpoint, @@ -40,46 +40,69 @@ type StaleProviderReplaceResult = { ok: boolean; status?: number | null; message * Security containment: force-detach recovery may only touch the sandbox being * onboarded. The authorized set is exactly the confirmed `sandboxName`; every * attachment reported by the delete failure is revalidated against it before - * any detach, and the same set is threaded into `removeGatewayProvider` so its - * own re-parse also fails closed on an outside sandbox. With no confirmed + * any detach by `deleteProviderWithRecovery`. With no confirmed * sandbox (`sandboxName === null`) there is nothing to authorize against, so * force-detach recovery is refused with an actionable error rather than run * unconstrained. A provider still attached to other live sandboxes fails closed * too — flipping its type would silently break their Anthropic routing. */ -function replaceStaleAnthropicProviderForOpenAiSurface(args: { +async function replaceStaleAnthropicProviderForOpenAiSurface(args: { provider: string; sandboxName: string | null; runOpenshell: RemoteProviderDeps["runOpenshell"]; - readProviderMetadata: NonNullable; - removeGatewayProvider: NonNullable; + providerAdapter: RemoteProviderDeps["providerAdapter"]; redact: RemoteProviderDeps["redact"]; compactText: RemoteProviderDeps["compactText"]; -}): StaleProviderReplaceResult { - const { - provider, - sandboxName, - runOpenshell, - readProviderMetadata, - removeGatewayProvider, - redact, - compactText, - } = args; - const live = readProviderMetadata(provider, runOpenshell); - if (!live || live.type === "openai") return { ok: true }; - const attempt = runOpenshell(["provider", "delete", provider], { - ignoreError: true, - suppressOutput: true, +}): Promise { + const { provider, sandboxName, runOpenshell, providerAdapter, redact, compactText } = args; + const adapter = + providerAdapter ?? + createManagedProviderAdapter((command, options) => { + const result = runOpenshell(command, options); + return { + ...result, + stdout: + typeof result.stdout === "string" || Buffer.isBuffer(result.stdout) + ? result.stdout + : null, + stderr: + typeof result.stderr === "string" || Buffer.isBuffer(result.stderr) + ? result.stderr + : null, + }; + }); + const result = await adapter.getProvider({ + target: { kind: "selected" }, + providerName: provider, }); - if (attempt.status === 0) return { ok: true }; - const raw = `${attempt.stderr || ""}\n${attempt.stdout || ""}`; - const attached = parseAttachedSandboxes(raw); + if (!result.ok) { + if (result.error.kind === "command" && result.error.reason === "not_found") { + return { ok: true }; + } + const detail = compactText(redact(result.error.message)); + return { + ok: false, + status: 1, + message: `Failed to inspect provider '${provider}' before replacement${detail ? `: ${detail}` : "."}`, + }; + } + if (result.value.type === "openai") return { ok: true }; + const attempt = await deleteProviderWithRecovery(provider, { + providerAdapter: adapter, + allowedSandboxes: sandboxName === null ? [] : [sandboxName], + }); + if (attempt.ok) return { ok: true }; + const raw = attempt.error.message; + const attached = + attempt.error.kind === "command" && attempt.error.reason === "attached" + ? [...(attempt.error.attachedSandboxes ?? [])] + : []; const allowedSandboxes = sandboxName === null ? [] : [sandboxName]; const foreign = attached.filter((name) => !allowedSandboxes.includes(name)); if (sandboxName === null && attached.length > 0) { return { ok: false, - status: attempt.status ?? 1, + status: 1, message: `Provider '${provider}' is attached to sandbox(es) (${attached.join(", ")}) ` + `but no target sandbox was confirmed, so it cannot be safely force-detached ` + @@ -87,21 +110,10 @@ function replaceStaleAnthropicProviderForOpenAiSurface(args: { `explicit sandbox, or remove those sandboxes first.`, }; } - if (attached.length > 0 && foreign.length === 0) { - const recovery = removeGatewayProvider(provider, { runOpenshell, allowedSandboxes }); - const detail = compactText(redact(`${recovery.stderr || ""} ${recovery.stdout || ""}`)); - return recovery.ok - ? { ok: true } - : { - ok: false, - status: recovery.status ?? 1, - message: `Failed to replace provider '${provider}' for the OpenAI-compatible route${detail ? `: ${detail}` : "."}`, - }; - } if (foreign.length > 0) { return { ok: false, - status: attempt.status ?? 1, + status: 1, message: `Provider '${provider}' is attached to other sandbox(es) (${foreign.join(", ")}) ` + `and cannot be re-registered for the OpenAI-compatible route without breaking ` + @@ -112,7 +124,7 @@ function replaceStaleAnthropicProviderForOpenAiSurface(args: { const detail = compactText(redact(raw)); return { ok: false, - status: attempt.status ?? 1, + status: 1, message: `Failed to replace provider '${provider}' for the OpenAI-compatible route${detail ? `: ${detail}` : "."}`, }; } @@ -230,18 +242,6 @@ export async function setupRemoteProviderInference( const useOpenAiSurface = provider === "compatible-anthropic-endpoint" && preferredInferenceApi === "openai-completions"; const probeOpenAiSurface = deps.probeOpenAiLikeEndpoint ?? probeOpenAiLikeEndpointOptimized; - // The concrete modules type their openshell runners independently; the deps - // runner is call-compatible with both, so bridge the nominal mismatch here. - const readProviderMetadata = - deps.readGatewayProviderMetadata ?? - (readGatewayProviderMetadata as unknown as NonNullable< - RemoteProviderDeps["readGatewayProviderMetadata"] - >); - const removeGatewayProvider = - deps.deleteGatewayProvider ?? - (deleteProviderWithRecovery as unknown as NonNullable< - RemoteProviderDeps["deleteGatewayProvider"] - >); const configureProvider = async (): Promise< { done: true; result: SetupInferenceResult } | { done: false } > => { @@ -326,12 +326,11 @@ export async function setupRemoteProviderInference( } else { // `provider update` cannot change --type, so a provider left behind // by an earlier Anthropic-Messages registration must be replaced. - const replaced = replaceStaleAnthropicProviderForOpenAiSurface({ + const replaced = await replaceStaleAnthropicProviderForOpenAiSurface({ provider, sandboxName, runOpenshell, - readProviderMetadata, - removeGatewayProvider, + providerAdapter: deps.providerAdapter, redact, compactText, }); diff --git a/src/lib/onboard/inference-providers/types.ts b/src/lib/onboard/inference-providers/types.ts index 3bcb65845e6..509b3650ca6 100644 --- a/src/lib/onboard/inference-providers/types.ts +++ b/src/lib/onboard/inference-providers/types.ts @@ -16,6 +16,7 @@ // duplicate every helper's exact signature. import type { TrustedPrivateEndpointCapability } from "../../inference/endpoint-ssrf-preflight"; +import type { OpenShellProviderAdapter } from "../../adapters/openshell/provider-adapter"; import type { HermesAuthMethod } from "../hermes-auth"; import type { OnboardInferenceCapabilityCache } from "../inference-capability-cache"; @@ -115,14 +116,7 @@ export type RemoteProviderDeps = CommonDeps & { apiKey: string, options?: Record, ) => { ok: boolean; message?: string } | Promise<{ ok: boolean; message?: string }>; - readGatewayProviderMetadata?: ( - name: string, - runOpenshell: RunOpenshell, - ) => { name: string; type: string; credentialKeys: string[]; configKeys: string[] } | null; - deleteGatewayProvider?: ( - name: string, - deps: { runOpenshell: RunOpenshell; allowedSandboxes?: readonly string[] }, - ) => { ok: boolean; status?: number | null; stderr?: string; stdout?: string }; + providerAdapter?: OpenShellProviderAdapter; bedrockRuntimeOnboard: { setupBedrockRuntimeInference(input: { sandboxName: string | null; diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.test.ts b/src/lib/onboard/managed-workload/onboard-orchestration.test.ts index cb9131166f6..0389e4bc0fb 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.test.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.test.ts @@ -639,7 +639,7 @@ describe("managed workload onboard orchestration", () => { plan: { intent: {}, rebindMessagingTokenDefs: async () => [], - runProviderPreDeleteCleanup: vi.fn(), + runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(() => "unused"), discloseInitialSandboxPolicy: vi.fn(), diff --git a/src/lib/onboard/providers.ts b/src/lib/onboard/providers.ts index 879e604cb1b..5550b5b4113 100644 --- a/src/lib/onboard/providers.ts +++ b/src/lib/onboard/providers.ts @@ -479,26 +479,24 @@ async function upsertProvider( }; } if (exists && options.replaceExisting) { - const { deleteProviderWithRecovery } = require("./sandbox-provider-cleanup"); + const { deleteProviderWithRecovery } = + require("./sandbox-provider-cleanup") as typeof import("./sandbox-provider-cleanup"); const runOpenshell = identityCheckedRunner( _runOpenshell, options.revalidateSandboxIdentity, operation, ); - const r = deleteProviderWithRecovery(name, { + const r = await deleteProviderWithRecovery(name, { runOpenshell, allowedSandboxes: options.allowedSandboxes, }); if (!r.ok) { - const base = - compactText(redact(r.stderr)) || - compactText(redact(r.stdout)) || - `Failed to replace provider '${name}'.`; + const base = compactText(redact(r.error.message)) || `Failed to replace provider '${name}'.`; const detail = r.recoveryFailures.length > 0 ? ` (detach failures: ${r.recoveryFailures.map((f) => `${f.sandbox}: ${compactText(redact(f.output))}`).join("; ")})` : ""; - return { ok: false, status: r.status || 1, message: `${base}${detail}` }; + return { ok: false, status: 1, message: `${base}${detail}` }; } } const action = exists && !options.replaceExisting ? "update" : "create"; diff --git a/src/lib/onboard/runtime-provider/contract.ts b/src/lib/onboard/runtime-provider/contract.ts index a3bf86b9cdd..4b9f12c47fa 100644 --- a/src/lib/onboard/runtime-provider/contract.ts +++ b/src/lib/onboard/runtime-provider/contract.ts @@ -495,7 +495,9 @@ export type RuntimeProviderWorkloadCleanupResult = }; export interface RuntimeProviderCleanupOperations { - readonly detachProviders: () => RuntimeProviderProviderDetachResult; + readonly detachProviders: () => + | RuntimeProviderProviderDetachResult + | Promise; } /** @@ -724,7 +726,7 @@ export type RuntimeProviderCleanupSurface = prepareDestroy( input: RuntimeProviderCleanupInput, operations: RuntimeProviderCleanupOperations, - ): RuntimeProviderProviderDetachResult; + ): RuntimeProviderProviderDetachResult | Promise; /** * Produce a side-effect-free cleanup plan before any destructive * sandbox action. Providers must revalidate the same authority inside diff --git a/src/lib/onboard/sandbox-create-intent-types.ts b/src/lib/onboard/sandbox-create-intent-types.ts index dfe1feb00ec..895a5b8a2ab 100644 --- a/src/lib/onboard/sandbox-create-intent-types.ts +++ b/src/lib/onboard/sandbox-create-intent-types.ts @@ -104,7 +104,9 @@ export type MaterializeSandboxCreatePlanInput = { messagingTokenDefs: MessagingTokenDef[]; /** Non-secret config captured in the messaging plan that owns exact policy endpoints. */ messagingConfig?: MessagingChannelConfig | null; - runProviderPreDeleteCleanup(revalidateSandboxIdentity?: (operation: string) => void): void; + runProviderPreDeleteCleanup( + revalidateSandboxIdentity?: (operation: string) => void, + ): Promise; upsertMessagingProviders( tokenDefs: MessagingTokenDef[], options: { diff --git a/src/lib/onboard/sandbox-create-plan-materialization.ts b/src/lib/onboard/sandbox-create-plan-materialization.ts index ace7be5211d..dc252dad2ee 100644 --- a/src/lib/onboard/sandbox-create-plan-materialization.ts +++ b/src/lib/onboard/sandbox-create-plan-materialization.ts @@ -375,7 +375,7 @@ export async function materializeSandboxCreatePlan({ const activateProviderEffects = async ( revalidateSandboxIdentity?: (operation: string) => void, ): Promise => { - runProviderPreDeleteCleanup(revalidateSandboxIdentity); + await runProviderPreDeleteCleanup(revalidateSandboxIdentity); const activatedMessagingProviders = filterMessagingProvidersForSandboxCreate( [ ...(await upsertMessagingProviders(enabledMessagingTokenDefs, { diff --git a/src/lib/onboard/sandbox-create-plan.test.ts b/src/lib/onboard/sandbox-create-plan.test.ts index 6dad770e8a1..3b78f463806 100644 --- a/src/lib/onboard/sandbox-create-plan.test.ts +++ b/src/lib/onboard/sandbox-create-plan.test.ts @@ -131,7 +131,7 @@ function materializeDiscordCreatePlan( return materializeSandboxCreatePlan({ ...resolved, fromRef: "/tmp/Dockerfile", - runProviderPreDeleteCleanup: vi.fn(), + runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => [discordProviderName]), getHermesToolGatewayProviderName: vi.fn(), ...overrides, @@ -170,7 +170,7 @@ async function expectCredentialBindingFailure({ policyPath: "/tmp/policy.yaml", appliedPresets: [], })); - const cleanupProviders = vi.fn(); + const cleanupProviders = vi.fn(async () => {}); const upsertProviders = vi.fn(() => []); await expect( @@ -269,7 +269,7 @@ describe("prepareSandboxCreatePolicy", () => { fromRef: "/tmp/Dockerfile", messagingTokenDefs, messagingConfig: { WECHAT_BASE_URL: "https://idc-37.weixin.qq.com" }, - runProviderPreDeleteCleanup: vi.fn(), + runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => [providerName]), getHermesToolGatewayProviderName: vi.fn(), }); @@ -514,7 +514,7 @@ describe("resolveSandboxCreateIntent", () => { selected: true, }); const cleanupPolicy = vi.fn(() => true); - const cleanupProviders = vi.fn(); + const cleanupProviders = vi.fn(async () => {}); const upsertMessagingProviders = vi.fn(() => [discordProviderName]); await expect( @@ -566,7 +566,7 @@ describe("resolveSandboxCreateIntent", () => { intent, fromRef: "/tmp/Dockerfile", messagingTokenDefs: [], - runProviderPreDeleteCleanup: vi.fn(), + runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders, getHermesToolGatewayProviderName: vi.fn(), prepareInitialSandboxCreatePolicy: vi.fn(() => ({ @@ -614,7 +614,7 @@ describe("resolveSandboxCreateIntent", () => { fromRef: "/tmp/nemoclaw-build-1/Dockerfile", messagingTokenDefs: [], prepareInitialSandboxCreatePolicy: preparePolicy, - runProviderPreDeleteCleanup: vi.fn(), + runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(() => "sandbox-hermes-tools"), }); @@ -662,8 +662,16 @@ describe("resolveSandboxCreateIntent", () => { }); const serializedIntent = JSON.stringify(intent); const events: string[] = []; + let completeCleanup!: () => void; + let cleanupStarted!: () => void; + const pendingCleanup = new Promise((resolve) => { + completeCleanup = resolve; + }); + const started = new Promise((resolve) => { + cleanupStarted = resolve; + }); - const result = await materializeSandboxCreatePlan({ + const materializing = materializeSandboxCreatePlan({ intent, fromRef: "/tmp/nemoclaw-build-1/Dockerfile", messagingTokenDefs: tokenDefs, @@ -675,7 +683,11 @@ describe("resolveSandboxCreateIntent", () => { events.push("disclose"); expect(policy.appliedPresets).toEqual(["telegram"]); }, - runProviderPreDeleteCleanup: () => events.push("cleanup"), + runProviderPreDeleteCleanup: async () => { + cleanupStarted(); + await pendingCleanup; + events.push("cleanup"); + }, upsertMessagingProviders: vi.fn((receivedTokenDefs, options) => { events.push("upsert"); expect(receivedTokenDefs).toEqual(tokenDefs); @@ -691,6 +703,13 @@ describe("resolveSandboxCreateIntent", () => { }, }); + try { + await Promise.race([started, materializing]); + expect(events).not.toContain("upsert"); + } finally { + completeCleanup(); + } + const result = await materializing; expect(events).toEqual(["policy", "hermes", "disclose", "cleanup", "upsert"]); expect(result.createArgs).toEqual([ "--from", @@ -752,7 +771,9 @@ describe("resolveSandboxCreateIntent", () => { events.push("policy-cleanup"); return true; }); - const runProviderPreDeleteCleanup = vi.fn(() => events.push("provider-cleanup")); + const runProviderPreDeleteCleanup = vi.fn(async () => { + events.push("provider-cleanup"); + }); const upsertMessagingProviders = vi.fn(() => { events.push("upsert"); return ["sandbox-telegram-bridge"]; @@ -815,7 +836,7 @@ describe("resolveSandboxCreateIntent", () => { policyPath: "/tmp/policy.yaml", appliedPresets: [], }), - runProviderPreDeleteCleanup: vi.fn(), + runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }); @@ -889,7 +910,7 @@ describe("resolveSandboxCreateIntent", () => { fromRef: "/tmp/nemoclaw-build-1/Dockerfile", messagingTokenDefs: [], prepareInitialSandboxCreatePolicy: vi.fn(), - runProviderPreDeleteCleanup: vi.fn(), + runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }), @@ -923,7 +944,7 @@ describe("resolveSandboxCreateIntent", () => { policyPath: "/tmp/policy.yaml", appliedPresets: [], })), - runProviderPreDeleteCleanup: vi.fn(), + runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }); @@ -984,7 +1005,7 @@ describe("resolveSandboxCreateIntent", () => { policyPath: "/tmp/policy.yaml", appliedPresets: [], })), - runProviderPreDeleteCleanup: vi.fn(), + runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }); @@ -1039,7 +1060,7 @@ describe("resolveSandboxCreateIntent", () => { policyPath: "/tmp/policy.yaml", appliedPresets: [], })), - runProviderPreDeleteCleanup: vi.fn(), + runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }); @@ -1088,7 +1109,7 @@ describe("resolveSandboxCreateIntent", () => { policyPath: "/tmp/policy.yaml", appliedPresets: [], })), - runProviderPreDeleteCleanup: vi.fn(), + runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }), @@ -1113,7 +1134,7 @@ describe("resolveSandboxCreateIntent", () => { sandboxGpuLogMessage: null, }); const cleanupPolicy = vi.fn(() => true); - const cleanupProviders = vi.fn(); + const cleanupProviders = vi.fn(async () => {}); const upsertProviders = vi.fn(() => []); await expect( @@ -1153,7 +1174,7 @@ describe("resolveSandboxCreateIntent", () => { appliedPresets: [], cleanup: cleanupPolicy, })), - runProviderPreDeleteCleanup: vi.fn(), + runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: async () => { throw providerFailure; }, @@ -1244,7 +1265,7 @@ describe("resolveSandboxCreateIntent", () => { policyPath: "/tmp/policy.yaml", appliedPresets: [], })), - runProviderPreDeleteCleanup: vi.fn(), + runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }); diff --git a/src/lib/onboard/sandbox-create/orchestration.test.ts b/src/lib/onboard/sandbox-create/orchestration.test.ts index 3de1d8733cf..5154bb6689b 100644 --- a/src/lib/onboard/sandbox-create/orchestration.test.ts +++ b/src/lib/onboard/sandbox-create/orchestration.test.ts @@ -440,7 +440,7 @@ describe("APF create policy selection", () => { }); describe("deferred provider effect authority", () => { - it("carries identity authority through every provider cleanup effect (#9833)", () => { + it("carries identity authority through every provider cleanup effect (#9833)", async () => { let liveIdentity = "identity-a"; const operations: string[] = []; const revalidateSandboxIdentity = vi.fn((operation: string) => { @@ -450,7 +450,7 @@ describe("deferred provider effect authority", () => { throw new Error("sandbox identity changed"); })(); }); - const runProviderPreDeleteCleanup = vi.fn((_sandboxName, deps) => { + const runProviderPreDeleteCleanup = vi.fn(async (_sandboxName, deps) => { expect(deps.revalidateSandboxIdentity).toBe(revalidateSandboxIdentity); deps.revalidateSandboxIdentity?.("detaching provider"); liveIdentity = "identity-b"; @@ -458,7 +458,7 @@ describe("deferred provider effect authority", () => { return { detached: [], failures: [] }; }); - expect(() => + await expect( runAuthorityBoundProviderCleanup({ sandboxName: "alpha", revalidateSandboxIdentity, @@ -466,7 +466,7 @@ describe("deferred provider effect authority", () => { runOpenshell: vi.fn(), redact: (value) => value, }), - ).toThrow(/sandbox identity changed/u); + ).rejects.toThrow(/sandbox identity changed/u); expect(runProviderPreDeleteCleanup).toHaveBeenCalledOnce(); expect(operations).toEqual([ "cleaning up providers for sandbox 'alpha'", @@ -475,7 +475,7 @@ describe("deferred provider effect authority", () => { ]); }); - it("refuses provider cleanup when a sandbox appears after verified absence (#9833)", () => { + it("refuses provider cleanup when a sandbox appears after verified absence (#9833)", async () => { let observationCount = 0; const revalidateSandboxIdentity = vi.fn(); const runOpenshell = vi.fn(() => ({ @@ -487,7 +487,7 @@ describe("deferred provider effect authority", () => { signal: null, })); - expect(() => + await expect( runAuthorityBoundProviderCleanup({ sandboxName: "alpha", observeSandbox: () => @@ -500,7 +500,7 @@ describe("deferred provider effect authority", () => { redact: (value) => value, tolerateMissingSandbox: true, }), - ).toThrow(/appeared after absence was verified/u); + ).rejects.toThrow(/appeared after absence was verified/u); expect(revalidateSandboxIdentity).toHaveBeenCalledOnce(); expect(runOpenshell).not.toHaveBeenCalled(); }); diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index cd804659b75..35ab2bc6a60 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -1274,7 +1274,7 @@ type SandboxProviderCleanupAuthority = readonly revalidateSandboxIdentity: (operation: string) => void; }; -export function runAuthorityBoundProviderCleanup( +export async function runAuthorityBoundProviderCleanup( input: { readonly sandboxName: string; readonly runProviderPreDeleteCleanup: SandboxCreateOrchestrationRuntime["runSandboxProviderPreDeleteCleanup"]; @@ -1282,7 +1282,7 @@ export function runAuthorityBoundProviderCleanup( readonly redact: SandboxCreateOrchestrationRuntime["redact"]; readonly tolerateMissingSandbox?: boolean; } & SandboxProviderCleanupAuthority, -): void { +): Promise { const revalidateSandboxIdentity = "observeSandbox" in input ? (operation: string): void => { @@ -1295,7 +1295,7 @@ export function runAuthorityBoundProviderCleanup( } : input.revalidateSandboxIdentity; revalidateSandboxIdentity(`cleaning up providers for sandbox '${input.sandboxName}'`); - input.runProviderPreDeleteCleanup(input.sandboxName, { + await input.runProviderPreDeleteCleanup(input.sandboxName, { runOpenshell: input.runOpenshell, redact: input.redact, ...(input.tolerateMissingSandbox ? { tolerateMissingSandbox: true } : {}), @@ -2261,7 +2261,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche revalidateSandboxIdentity(true, `recreating sandbox '${sandboxName}'`); if (recreateRuntime.beginDelete() === "source") { - runAuthorityBoundProviderCleanup({ + await runAuthorityBoundProviderCleanup({ sandboxName, revalidateSandboxIdentity: (operation) => revalidateSandboxIdentity(true, operation), runProviderPreDeleteCleanup: runSandboxProviderPreDeleteCleanup, @@ -2419,8 +2419,8 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche ) ).messagingTokenDefs; }, - runProviderPreDeleteCleanup: (verifiedIdentityRevalidation) => { - runAuthorityBoundProviderCleanup({ + runProviderPreDeleteCleanup: async (verifiedIdentityRevalidation) => { + await runAuthorityBoundProviderCleanup({ sandboxName, runProviderPreDeleteCleanup: runSandboxProviderPreDeleteCleanup, runOpenshell, diff --git a/src/lib/onboard/sandbox-provider-cleanup.ts b/src/lib/onboard/sandbox-provider-cleanup.ts index de129f16b87..b383e743009 100644 --- a/src/lib/onboard/sandbox-provider-cleanup.ts +++ b/src/lib/onboard/sandbox-provider-cleanup.ts @@ -3,7 +3,11 @@ import { listMessagingProviderSuffixes } from "../messaging/channels"; import { listMessagingBridgeProfiles } from "./messaging-bridge-provider"; -import { NAME_MAX_LENGTH, NAME_VALID_PATTERN } from "../name-validation"; +import { createManagedProviderAdapter } from "../adapters/openshell/managed-provider-adapter"; +import type { + OpenShellProviderAdapter, + OpenShellProviderMutationResult, +} from "../adapters/openshell/provider-adapter"; export { applyExtraProviderReconciliation, @@ -40,6 +44,7 @@ export type SandboxProviderRunOpenshell = ( export type DetachSandboxProvidersDeps = { runOpenshell?: SandboxProviderRunOpenshell; + providerAdapter?: OpenShellProviderAdapter; revalidateSandboxIdentity?: (operation: string) => void; /** * Treat OpenShell `sandbox not found` outputs as success-equivalent. Used @@ -51,17 +56,7 @@ export type DetachSandboxProvidersDeps = { }; export type DeleteProviderWithRecoveryDeps = DetachSandboxProvidersDeps & { - /** - * Security containment for the force-detach recovery path. When provided, - * `deleteProviderWithRecovery` may only force-detach sandboxes whose names - * appear in this set — the authorized set for the onboarding operation - * (normally exactly the sandbox being onboarded). If the gateway's - * FailedPrecondition diagnostic lists ANY sandbox outside this set, the - * recovery fails closed (no detach is issued) so a mis-parsed, racing, or - * otherwise unexpected attachment can never silently detach an unrelated - * sandbox. When omitted, recovery is unconstrained — callers that own the - * whole gateway (resume-after-prune / credential-reset) opt out explicitly. - */ + /** Only detach attachments in this set. An omitted set authorizes gateway-wide recovery. */ allowedSandboxes?: readonly string[]; }; @@ -90,69 +85,41 @@ export const SANDBOX_PROVIDER_SUFFIXES = [ export type SandboxProviderSuffix = string; -const TOLERATED_DETACH_OUTPUT_RE = - /\bNotAttached\b|\bnot\s+attached\b|provider[^\n]{0,200}?(?:\bNotFound\b|\bnot\s+found\b)/i; - -const MISSING_SANDBOX_OUTPUT_RE = /sandbox[^\n]{0,200}?(?:\bNotFound\b|\bnot\s+found\b)/i; - -const ATTACHED_TO_SANDBOX_RE = /attached\s+to(?:\s|│)+sandbox\(\s*es?\s*\)?\s*:\s*([^"\n]+)/i; - -const MAX_WARNING_OUTPUT_CHARS = 500; - -function bufferOrStringToText(value: string | Buffer | null | undefined): string { - if (typeof value === "string") return value; - if (value && typeof (value as Buffer).toString === "function") { - return (value as Buffer).toString(); +/** Deletes registrations after sandbox removal. Failures can leave stale registrations. */ +export async function deleteSandboxProviderRegistrations( + sandboxName: string, + scope: "messaging" | "all", + deps: DetachSandboxProvidersDeps = {}, +): Promise { + const adapter = deps.providerAdapter ?? createManagedProviderAdapter(deps.runOpenshell); + const suffixes = + scope === "messaging" + ? listMessagingProviderSuffixes().map((suffix) => suffix.replace(/^-/, "")) + : SANDBOX_PROVIDER_SUFFIXES; + for (const suffix of suffixes) { + await adapter.deleteProvider({ + target: { kind: "selected" }, + providerName: `${sandboxName}-${suffix}`, + }); } - return ""; } -function defaultRunOpenshell( - args: string[], - opts?: Record, -): ReturnType { - const runtime = require("../adapters/openshell/runtime") as { - runOpenshell: SandboxProviderRunOpenshell; - }; - return runtime.runOpenshell(args, opts); -} +const MAX_WARNING_OUTPUT_CHARS = 500; function identityRedact(input: string): string { return input; } /** - * Detach every per-sandbox messaging and search provider before the sandbox - * itself is removed. OpenShell `sandbox delete` does not auto-detach - * providers, so a follow-up `provider delete` (or `provider create` after a - * `replaceExisting` upsert) trips on FailedPrecondition with - * "is attached to sandbox(es): " — the canonical pattern is detach - * first, then delete the sandbox, then delete the provider. - * - * Source boundary and removal condition: this helper owns the - * NemoClaw-side workaround for OpenShell's sandbox-deletion lifecycle. The - * source-of-truth fix lives in OpenShell — `sandbox delete` should either - * fail fast on attached providers or release the attachment as part of the - * deletion. When OpenShell guarantees one of those behaviours (released by - * a future gateway/CLI version that surfaces a structured "detached on - * delete" signal), this helper and both production call sites can be - * removed in one pass. - * - * Best-effort across the full suffix set. Tolerated diagnostics are - * narrowly scoped — `NotAttached` / "not attached" (the attachment is - * already gone) and `provider … NotFound` / `provider … not found` (the - * provider itself never existed or has already been deleted). Bare - * `NotFound` is intentionally NOT tolerated because the same wording is - * also used for missing-sandbox errors during the resume / pruned-sandbox - * path, where the attachment may still be stale and require manual recovery. - * Non-matching failures are returned in `failures` for the caller to - * surface; the caller decides whether to abort or continue. + * Detach owned messaging and search providers before sandbox removal. + * Return failures to the lifecycle owner; it decides whether cleanup can continue. + * Missing sandboxes are tolerated only by the explicit resume-after-prune caller. */ -export function detachSandboxProviders( +export async function detachSandboxProviders( sandboxName: string, deps: DetachSandboxProvidersDeps = {}, -): DetachSandboxProvidersResult { - const runOpenshell = deps.runOpenshell ?? defaultRunOpenshell; +): Promise { + const adapter = deps.providerAdapter ?? createManagedProviderAdapter(deps.runOpenshell); const detached: string[] = []; const failures: Array<{ name: string; output: string }> = []; for (const suffix of SANDBOX_PROVIDER_SUFFIXES) { @@ -161,23 +128,25 @@ export function detachSandboxProviders( // replacement and stop later detaches; they do not make this command an atomic, // identity-bound mutation. Operators must not mutate the sandbox concurrently. deps.revalidateSandboxIdentity?.(`detaching provider '${name}' from sandbox '${sandboxName}'`); - const result = runOpenshell(["sandbox", "provider", "detach", sandboxName, name], { - ignoreError: true, - stdio: ["ignore", "pipe", "pipe"], - suppressOutput: true, + const result = await adapter.detachProvider({ + target: { kind: "selected" }, + sandboxName, + providerName: name, }); deps.revalidateSandboxIdentity?.( `confirming provider '${name}' detach from sandbox '${sandboxName}'`, ); - if (result.status === 0) { - detached.push(name); - continue; - } - const output = `${bufferOrStringToText(result.stdout)}${bufferOrStringToText(result.stderr)}`; - if (TOLERATED_DETACH_OUTPUT_RE.test(output)) { + if (result.ok) { + if (result.value.changed) detached.push(name); continue; } - if (deps.tolerateMissingSandbox && MISSING_SANDBOX_OUTPUT_RE.test(output)) { + const output = result.error.message; + if (result.error.kind === "command" && result.error.reason === "not_found") continue; + if ( + deps.tolerateMissingSandbox && + result.error.kind === "command" && + result.error.reason === "sandbox_not_found" + ) { continue; } failures.push({ name, output: output.trim() }); @@ -185,93 +154,13 @@ export function detachSandboxProviders( return { detached, failures }; } -/** - * Parse the sandbox names from an OpenShell `provider delete` FailedPrecondition - * diagnostic of the shape - * `provider 'X' is attached to sandbox(es): A, B` - * Returns an empty array when the input has no recognisable list. - */ -export function parseAttachedSandboxes(output: string): string[] { - const match = ATTACHED_TO_SANDBOX_RE.exec(output); - if (!match) return []; - return match[1] - .split(/[,\s]+/) - .map((s) => s.trim().replace(/[.'"`]+$/u, "")) - .filter((s) => s.length > 0 && s.length <= NAME_MAX_LENGTH && NAME_VALID_PATTERN.test(s)); -} - -export type RecoverProviderResult = { - detached: string[]; - failures: Array<{ sandbox: string; output: string }>; -}; - -/** - * Recovery path for `provider delete` failures whose attachment list points - * at a sandbox that the local recreate / destroy pass could not reach (the - * resume-after-prune case: sandbox already gone, but the gateway still - * tracks the orphaned attachment). Issues `sandbox provider detach - * ` for each listed sandbox, then returns the per-name - * outcome so the caller can retry the original delete. - */ -export function recoverAttachedProvider( - providerName: string, - attachedSandboxes: string[], - deps: DetachSandboxProvidersDeps = {}, -): RecoverProviderResult { - const runOpenshell = deps.runOpenshell ?? defaultRunOpenshell; - const detached: string[] = []; - const failures: Array<{ sandbox: string; output: string }> = []; - for (const sandbox of attachedSandboxes) { - const result = runOpenshell(["sandbox", "provider", "detach", sandbox, providerName], { - ignoreError: true, - stdio: ["ignore", "pipe", "pipe"], - suppressOutput: true, - }); - if (result.status === 0) { - detached.push(sandbox); - continue; - } - const out = `${bufferOrStringToText(result.stdout)}${bufferOrStringToText(result.stderr)}`; - if (TOLERATED_DETACH_OUTPUT_RE.test(out)) { - detached.push(sandbox); - continue; - } - failures.push({ sandbox, output: out.trim() }); - } - return { detached, failures }; -} - -/** - * Run the recreate / destroy preflight that detaches every per-sandbox - * messaging and search provider, then surfaces any non-tolerated failure - * through the injected `warn` channel with the failure output redacted and - * length-capped. Returns the same result as `detachSandboxProviders` so - * callers can inspect / re-test specific names if they want to short-circuit - * downstream work. - * - * Non-tolerated detach failures are advisory rather than fatal because the - * downstream operations that immediately follow the cleanup already surface - * the same residual attachment with an actionable, name-scoped error: - * - * - The onboard recreate path runs typed messaging provider application with - * `replaceExisting: true` next; a residual attachment rejects with a - * name-scoped `MessagingProviderApplyError` and preserves retry state. - * - The destroy path runs `runOpenshell(["sandbox", "delete", sandboxName])` - * next; that call hard-fails on non-`alreadyGone` errors before any - * registry state is removed, so a real gateway outage stops destroy - * before it can drop state needed for retry. - * - * Treating a non-tolerated detach return as a hard failure here would - * regress the merely-flaky-gateway case (where the subsequent operation - * succeeds) without gaining any signal that the immediately-following step - * does not already provide. Callers that want stricter semantics inspect - * the returned `failures` array directly. - */ -export function runSandboxProviderPreDeleteCleanup( +/** Report bounded, redacted detach failures; the following lifecycle mutation remains authoritative. */ +export async function runSandboxProviderPreDeleteCleanup( sandboxName: string, deps: SandboxRecreateCleanupDeps = {}, -): DetachSandboxProvidersResult { - const result = detachSandboxProviders(sandboxName, { +): Promise { + const result = await detachSandboxProviders(sandboxName, { + providerAdapter: deps.providerAdapter, runOpenshell: deps.runOpenshell, revalidateSandboxIdentity: deps.revalidateSandboxIdentity, tolerateMissingSandbox: deps.tolerateMissingSandbox, @@ -288,73 +177,43 @@ export function runSandboxProviderPreDeleteCleanup( return result; } -export type ProviderDeleteWithRecoveryResult = { - ok: boolean; - status: number | null; - stderr: string; - stdout: string; +export type ProviderDeleteWithRecoveryResult = OpenShellProviderMutationResult & { recoveryFailures: Array<{ sandbox: string; output: string }>; }; /** - * Delete an OpenShell provider, recovering from a FailedPrecondition that - * reports the provider as still attached to one or more sandboxes. The - * source-of-truth fix lives in OpenShell: `provider delete` should either - * cascade through the gateway-side attachment record or expose a structured - * "force" path. Until that lands, this helper parses the attached-sandbox - * list out of the diagnostic, force-detaches each entry (rejecting any - * parsed name that fails NemoClaw's sandbox-name validator before issuing - * a detach), and retries the delete once. Removable in the same future - * OpenShell version that lets `runSandboxProviderPreDeleteCleanup` go away. - * - * Security containment: when `deps.allowedSandboxes` is supplied, the parsed - * attachment list is revalidated against that authorized set BEFORE any - * detach is issued. If any listed sandbox falls outside the set, the recovery - * fails closed — no detach runs and the original delete failure is returned — - * so a stale, racing, or mis-parsed diagnostic can never force-detach a - * sandbox the caller did not authorize. Callers that omit `allowedSandboxes` - * (they own the whole gateway) keep the unconstrained behaviour. - * - * Returns the final `provider delete` outcome plus the list of per-sandbox - * detach failures, so the caller can fold those into the user-facing error - * if the retry still doesn't land. + * Delete once. On a confirmed attachment failure, detach only authorized sandboxes, + * then retry once after every detach succeeds. Preserve uncertain or partial failures. */ -export function deleteProviderWithRecovery( +export async function deleteProviderWithRecovery( providerName: string, deps: DeleteProviderWithRecoveryDeps = {}, -): ProviderDeleteWithRecoveryResult { - const runOpenshell = deps.runOpenshell ?? defaultRunOpenshell; - let result = runOpenshell(["provider", "delete", providerName], { - ignoreError: true, - stdio: ["ignore", "pipe", "pipe"], - suppressOutput: true, - }); - let recoveryFailures: Array<{ sandbox: string; output: string }> = []; - if (result.status !== 0) { - const raw = `${bufferOrStringToText(result.stderr)}${bufferOrStringToText(result.stdout)}`; - const attached = parseAttachedSandboxes(raw); +): Promise { + const adapter = deps.providerAdapter ?? createManagedProviderAdapter(deps.runOpenshell); + const request = { target: { kind: "selected" as const }, providerName }; + let result = await adapter.deleteProvider(request); + const recoveryFailures: Array<{ sandbox: string; output: string }> = []; + if (!result.ok && result.error.kind === "command" && result.error.reason === "attached") { + const attached = [...(result.error.attachedSandboxes ?? [])]; // Fail closed when the diagnostic names any sandbox outside the caller's // authorized set: force-detaching it could break an unrelated sandbox. const allowed = deps.allowedSandboxes; const outsideAuthorizedSet = allowed !== undefined && attached.some((name) => !allowed.includes(name)); if (attached.length > 0 && !outsideAuthorizedSet) { - const recovery = recoverAttachedProvider(providerName, attached, { runOpenshell }); - recoveryFailures = recovery.failures; - result = runOpenshell(["provider", "delete", providerName], { - ignoreError: true, - stdio: ["ignore", "pipe", "pipe"], - suppressOutput: true, - }); + for (const sandboxName of attached) { + const detached = await adapter.detachProvider({ ...request, sandboxName }); + if ( + !detached.ok && + !(detached.error.kind === "command" && detached.error.reason === "not_found") + ) { + recoveryFailures.push({ sandbox: sandboxName, output: detached.error.message }); + } + } + if (recoveryFailures.length === 0) result = await adapter.deleteProvider(request); } } - return { - ok: result.status === 0, - status: result.status, - stderr: bufferOrStringToText(result.stderr), - stdout: bufferOrStringToText(result.stdout), - recoveryFailures, - }; + return { ...result, recoveryFailures }; } /** diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 48d130dbcba..eec9839bd86 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -242,8 +242,7 @@ export type SetupInferenceDeps = ProviderBranchDeps & { // #6294 optional overrides for the remote-provider OpenAI-surface branch; // production omits these and remote.ts falls back to the real modules. probeOpenAiLikeEndpoint?: RemoteProviderDeps["probeOpenAiLikeEndpoint"]; - readGatewayProviderMetadata?: RemoteProviderDeps["readGatewayProviderMetadata"]; - deleteGatewayProvider?: RemoteProviderDeps["deleteGatewayProvider"]; + providerAdapter?: RemoteProviderDeps["providerAdapter"]; log: (message: string) => void; error: (message: string) => void; exitProcess: (code: number) => never; @@ -979,8 +978,7 @@ export function createSetupInference( redact: deps.redact, compactText: deps.compactText, probeOpenAiLikeEndpoint: deps.probeOpenAiLikeEndpoint, - readGatewayProviderMetadata: deps.readGatewayProviderMetadata, - deleteGatewayProvider: deps.deleteGatewayProvider, + providerAdapter: deps.providerAdapter, }, ); if (outcome.done) return outcome.result; diff --git a/src/lib/state/registry-lock.test.ts b/src/lib/state/registry-lock.test.ts index e39ba4a2d68..9d11c8fdc24 100644 --- a/src/lib/state/registry-lock.test.ts +++ b/src/lib/state/registry-lock.test.ts @@ -12,6 +12,7 @@ import { ProcessBoundLockContentionError, releaseProcessBoundLock, withProcessBoundRegistryLockAt, + withProcessBoundRegistryLockAtAsync, withRegistryLockAt, type RegistryLockDeps, } from "./registry/lock"; @@ -156,6 +157,111 @@ describe("registry lock ownership decisions", () => { }); describe("process-bound registry locking", () => { + it.each([false, true])( + "lets a waiting async caller enter after the holder settles (reject=%s)", + async (reject) => { + const test = fixture("nemoclaw-async-contenders-"); + const events: string[] = []; + const failure = new Error("holder failed"); + const holder = withProcessBoundRegistryLockAtAsync( + test.registryFile, + async () => { + events.push("holder-entered"); + await new Promise((resolve) => setTimeout(resolve, 0)); + events.push("holder-settled"); + return reject ? Promise.reject(failure) : "holder"; + }, + exactDeps(), + ); + const contender = withProcessBoundRegistryLockAtAsync( + test.registryFile, + () => { + events.push("contender-entered"); + return "contender"; + }, + exactDeps({ wait: undefined, maxRetries: 3 }), + ); + const results = await Promise.allSettled([holder, contender]); + expect(results).toEqual([ + reject ? { status: "rejected", reason: failure } : { status: "fulfilled", value: "holder" }, + { status: "fulfilled", value: "contender" }, + ]); + expect(events).toEqual(["holder-entered", "holder-settled", "contender-entered"]); + expect(fs.existsSync(test.lockDir)).toBe(false); + }, + ); + + it("bounds async contention without entering or removing the held generation", async () => { + const test = fixture("nemoclaw-async-contention-bound-"); + const handle = acquireProcessBoundLockAt(test.lockDir, exactDeps()); + const wait = vi.fn(); + const operation = vi.fn(); + try { + await expect( + withProcessBoundRegistryLockAtAsync( + test.registryFile, + operation, + exactDeps({ wait, maxRetries: 2 }), + ), + ).rejects.toThrow(ProcessBoundLockContentionError); + expect(wait).toHaveBeenCalledTimes(2); + expect(operation).not.toHaveBeenCalled(); + expect(fs.readFileSync(test.ownerFile, "utf8")).toBe(String(process.pid)); + } finally { + releaseProcessBoundLock(handle); + } + expect(fs.existsSync(test.lockDir)).toBe(false); + }); + + it.each([ + { + outcome: "success", + finish: () => "removed", + assert: (operation: Promise) => expect(operation).resolves.toBe("removed"), + }, + { + outcome: "failure", + finish: (): string => { + throw new Error("cleanup failed"); + }, + assert: (operation: Promise) => expect(operation).rejects.toThrow("cleanup failed"), + }, + ])( + "holds the registry lock until asynchronous cleanup settles: $outcome", + async ({ finish, assert }) => { + const test = fixture("nemoclaw-async-provider-cleanup-lock-"); + let settle!: () => void; + const pending = new Promise((resolve) => { + settle = resolve; + }); + const operation = withProcessBoundRegistryLockAtAsync( + test.registryFile, + async () => { + await pending; + expect(fs.existsSync(test.lockDir)).toBe(true); + return finish(); + }, + exactDeps(), + ); + expect(fs.existsSync(test.lockDir)).toBe(true); + expect(() => + withProcessBoundRegistryLockAt( + test.registryFile, + () => undefined, + exactDeps({ maxRetries: 1 }), + ), + ).toThrow(ProcessBoundLockContentionError); + settle(); + await assert(operation); + expect(fs.existsSync(test.lockDir)).toBe(false); + const contender = vi.fn(() => "entered"); + expect( + withProcessBoundRegistryLockAt(test.registryFile, contender, exactDeps({ maxRetries: 1 })), + ).toBe("entered"); + expect(contender).toHaveBeenCalledOnce(); + }, + ); + it("holds beyond ten seconds and makes a contender exhaust 120 bounded retries", () => { const test = fixture("nemoclaw-process-bound-lock-"); const wait = vi.fn(); diff --git a/src/lib/state/registry/lock.ts b/src/lib/state/registry/lock.ts index 06281faefee..cfb1a47d049 100644 --- a/src/lib/state/registry/lock.ts +++ b/src/lib/state/registry/lock.ts @@ -231,7 +231,12 @@ function tryRemove( } } -function acquire(directory: string, exact: boolean, deps: RegistryLockDeps): Acquired { +// Yield only while contended, before owning a generation, so async callers can let holders resume. +function* acquisitionAttempts( + directory: string, + exact: boolean, + deps: RegistryLockDeps, +): Generator { const readIdentity = deps.readProcessIdentity ?? processIdentity; const initialIdentity = readIdentity(process.pid); if (exact && (initialIdentity === null || process.getuid?.() === undefined)) @@ -240,8 +245,6 @@ function acquire(directory: string, exact: boolean, deps: RegistryLockDeps): Acq const alive = deps.isProcessAlive ?? isProcessAlive; const retries = deps.maxRetries ?? LOCK_MAX_RETRIES; const now = deps.now ?? Date.now; - const sleep = new Int32Array(new SharedArrayBuffer(4)); - const wait = deps.wait ?? (() => Atomics.wait(sleep, 0, 0, LOCK_RETRY_MS)); fs.mkdirSync(path.dirname(directory), { recursive: true }); for (let attempt = 0; attempt < retries; attempt++) { try { @@ -282,7 +285,7 @@ function acquire(directory: string, exact: boolean, deps: RegistryLockDeps): Acq ) ) continue; - wait(); + yield; continue; } @@ -335,6 +338,18 @@ function acquire(directory: string, exact: boolean, deps: RegistryLockDeps): Acq throw new ProcessBoundLockContentionError(directory, retries); } +function acquire(directory: string, exact: boolean, deps: RegistryLockDeps): Acquired { + const attempts = acquisitionAttempts(directory, exact, deps); + const sleep = new Int32Array(new SharedArrayBuffer(4)); + const wait = deps.wait ?? (() => Atomics.wait(sleep, 0, 0, LOCK_RETRY_MS)); + let step = attempts.next(); + while (!step.done) { + wait(); + step = attempts.next(); + } + return step.value; +} + function release(acquired: Acquired): void { const files: [string, Identity][] = [[acquired.paths.owner, acquired.ownerFile]]; if (acquired.processFile) files.push([acquired.paths.processStart, acquired.processFile]); @@ -399,6 +414,26 @@ export function withProcessBoundRegistryLockAt( ): T { return withAcquired(`${registryFile}.lock`, true, operation, deps); } +export async function withProcessBoundRegistryLockAtAsync( + registryFile: string, + operation: () => T | Promise, + deps: RegistryLockDeps = {}, +): Promise { + const attempts = acquisitionAttempts(`${registryFile}.lock`, true, deps); + const wait = + deps.wait ?? (() => new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS))); + let step = attempts.next(); + while (!step.done) { + await wait(); + step = attempts.next(); + } + const lock = step.value; + try { + return await operation(); + } finally { + release(lock); + } +} export function acquireProcessBoundLockAt( lockDirectory: string, deps: RegistryLockDeps = {}, diff --git a/test/fixtures/uninstall-prompt-pty-driver.ts b/test/fixtures/uninstall-prompt-pty-driver.ts index f1805e7d587..34d0b818d08 100644 --- a/test/fixtures/uninstall-prompt-pty-driver.ts +++ b/test/fixtures/uninstall-prompt-pty-driver.ts @@ -54,32 +54,39 @@ const knownGatewayListResult: RunResult = { stderr: "", }; -const { exitCode } = runUninstallPlan( - { assumeYes: false, deleteModels: false, keepOpenShell: true }, - { - commandExists: (command) => command === "openshell", - // Hermetic env: the runtime merges the real process.env, so a developer - // shell exporting NEMOCLAW_* knobs (non-interactive mode, destroy-user- - // data acknowledgement, agent branding) would change which prompts run - // and what they print. Pin them empty so scenarios behave identically on - // every machine. - env: { - HOME: home, - NEMOCLAW_AGENT: "", - NEMOCLAW_NON_INTERACTIVE: "", - NEMOCLAW_UNINSTALL_DESTROY_USER_DATA: "", - TMPDIR: home, - } as NodeJS.ProcessEnv, - existsSync: fs.existsSync, - kill: () => true, - rmSync: (() => {}) as never, - run: (command, args) => - command === "openshell" && args[0] === "gateway" && args[1] === "list" - ? knownGatewayListResult - : okResult, - runDocker: () => okResult, - // readLine and isTty are deliberately NOT injected: the default - // readLineFromStdin/isStdinTty pair reading the pty is what is under test. - }, -); -process.exit(exitCode); +async function main(): Promise { + const { exitCode } = await runUninstallPlan( + { assumeYes: false, deleteModels: false, keepOpenShell: true }, + { + commandExists: (command) => command === "openshell", + // Hermetic env: the runtime merges the real process.env, so a developer + // shell exporting NEMOCLAW_* knobs (non-interactive mode, destroy-user- + // data acknowledgement, agent branding) would change which prompts run + // and what they print. Pin them empty so scenarios behave identically on + // every machine. + env: { + HOME: home, + NEMOCLAW_AGENT: "", + NEMOCLAW_NON_INTERACTIVE: "", + NEMOCLAW_UNINSTALL_DESTROY_USER_DATA: "", + TMPDIR: home, + } as NodeJS.ProcessEnv, + existsSync: fs.existsSync, + kill: () => true, + rmSync: (() => {}) as never, + run: (command, args) => + command === "openshell" && args[0] === "gateway" && args[1] === "list" + ? knownGatewayListResult + : okResult, + runDocker: () => okResult, + // readLine and isTty are deliberately NOT injected: the default + // readLineFromStdin/isStdinTty pair reading the pty is what is under test. + }, + ); + process.exit(exitCode); +} + +void main().catch((error: unknown) => { + console.error(error); + process.exitCode = 1; +}); diff --git a/test/helpers/destroy-flow-test-harness.ts b/test/helpers/destroy-flow-test-harness.ts index 9ea27539d02..259ec4c1c7b 100644 --- a/test/helpers/destroy-flow-test-harness.ts +++ b/test/helpers/destroy-flow-test-harness.ts @@ -58,6 +58,7 @@ export type DestroyHarness = { revokeHttpsPinRuntimeAdapterRouteSpy: MockInstance; restoreMcpBridgesAfterDestroyAbortSpy: MockInstance; runOpenshellSpy: MockInstance; + runSandboxProviderPreDeleteCleanupSpy: MockInstance; selectGatewaySpy: MockInstance; sessionState: Session; setDockerIdentityResult: (result: { @@ -620,10 +621,13 @@ export function createDestroyHarness(options: DestroyHarnessOptions = {}): Destr providerIdentity: options.runtimeProviderIdentityProof, }); } - vi.spyOn(sandboxProviderCleanup, "runSandboxProviderPreDeleteCleanup").mockImplementation(() => { - events.push("detach"); - return { detached: options.detachedProviders ?? [], failures: [] }; - }); + const runSandboxProviderPreDeleteCleanupSpy = vi + .spyOn(sandboxProviderCleanup, "runSandboxProviderPreDeleteCleanup") + .mockImplementation(async () => { + await Promise.resolve(); + events.push("detach"); + return { detached: options.detachedProviders ?? [], failures: [] }; + }); vi.spyOn(sandboxProviderCleanup, "emitProviderDetachResidualHint").mockImplementation( () => undefined, ); @@ -712,6 +716,7 @@ export function createDestroyHarness(options: DestroyHarnessOptions = {}): Destr errorSpy, events, executeSandboxDestroySpy, + runSandboxProviderPreDeleteCleanupSpy, enforceRemovedImmutabilityMigrationBoundarySpy, finalizeMcpBridgesAfterSandboxDeleteSpy, gatewayPinsAtMcpPrepare, diff --git a/test/onboarding/onboard-anthropic-compatible-openai-agent.test.ts b/test/onboarding/onboard-anthropic-compatible-openai-agent.test.ts index 94500892729..99497f93f7c 100644 --- a/test/onboarding/onboard-anthropic-compatible-openai-agent.test.ts +++ b/test/onboarding/onboard-anthropic-compatible-openai-agent.test.ts @@ -10,12 +10,26 @@ // branch re-adds it for both the probe and the registered base URL — keeping // the probed URL identical to the one OpenShell calls at runtime. -import { afterEach, describe, expect, it, vi } from "vitest"; +import fs from "node:fs"; +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { SetupInference, SetupInferenceDeps } from "../../src/lib/onboard/setup-inference.js"; -import { createDirectSetupInferenceHarnessFactory } from "../support/setup-inference-test-harness.js"; +import { + createDirectSetupInferenceHarnessFactory, + createStaleAnthropicProviderRunner, +} from "../support/setup-inference-test-harness.js"; -const onboard = require("../../src/lib/onboard") as { - createSetupInference: (overrides?: Partial) => SetupInference; +const testHome = await vi.hoisted(async () => { + const fs = await import("node:fs"); + const os = await import("node:os"); + const path = await import("node:path"); + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-remote-provider-")); + // The production registry captures its path when the harness imports onboarding. + vi.stubEnv("HOME", home); + return home; +}); + +const { default: onboard } = (await import("../../src/lib/onboard")) as unknown as { + default: { createSetupInference: (overrides?: Partial) => SetupInference }; }; const createDirectSetupInferenceHarness = createDirectSetupInferenceHarnessFactory( onboard.createSetupInference, @@ -43,18 +57,48 @@ function commandStubs(routes: Record ({ - name: PROVIDER, - type: "anthropic", - credentialKeys: [CREDENTIAL_ENV], - configKeys: ["ANTHROPIC_BASE_URL"], -}); - describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#6294)", () => { + beforeEach(() => { + vi.stubEnv("HOME", testHome); + }); afterEach(() => { vi.unstubAllEnvs(); vi.restoreAllMocks(); }); + afterAll(() => fs.rmSync(testHome, { recursive: true, force: true })); + + it.each<[string, string[]]>([ + ["get", ["provider", "get", "other-provider"]], + ["delete", ["provider", "delete", "other-provider"]], + ["detach", ["sandbox", "provider", "detach", "test-box", "other-provider"]], + ])( + "rejects a mismatched provider name during fixture %s without changing its state", + (_operation, args) => { + const runner = createStaleAnthropicProviderRunner(PROVIDER, CREDENTIAL_ENV, ["test-box"]); + expect(runner(args, {}, [])).toEqual({ + status: 1, + stderr: "provider 'other-provider' not found", + }); + expect(runner(["provider", "get", PROVIDER], {}, [])?.status).toBe(0); + expect(runner(["provider", "delete", PROVIDER], {}, [])).toEqual({ + status: 1, + stderr: `provider '${PROVIDER}' is attached to sandbox(es): test-box`, + }); + }, + ); + + it.each<[string, string[]]>([ + ["get", ["provider", "get", PROVIDER]], + ["delete", ["provider", "delete", PROVIDER]], + ["detach", ["sandbox", "provider", "detach", "test-box", PROVIDER]], + ])("reports provider absence during fixture %s after deletion", (_operation, args) => { + const runner = createStaleAnthropicProviderRunner(PROVIDER, CREDENTIAL_ENV); + expect(runner(["provider", "delete", PROVIDER], {}, [])).toEqual({ status: 0 }); + expect(runner(args, {}, [])).toEqual({ + status: 1, + stderr: `provider '${PROVIDER}' not found`, + }); + }); it("registers the provider as type=openai on the /v1 surface after the probe passes", async () => { vi.stubEnv(CREDENTIAL_ENV, "hub-secret"); @@ -90,11 +134,9 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 it("replaces an unattached stale Anthropic-surface registration with a plain delete", async () => { vi.stubEnv(CREDENTIAL_ENV, "hub-secret"); const probeOpenAiLikeEndpoint = vi.fn(() => ({ ok: true })); - const readGatewayProviderMetadata = vi.fn(staleAnthropicMetadata); - const deleteGatewayProvider = vi.fn(() => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ - runOpenshell: providerAbsentRunner, - overrides: { probeOpenAiLikeEndpoint, readGatewayProviderMetadata, deleteGatewayProvider }, + runOpenshell: createStaleAnthropicProviderRunner(PROVIDER, CREDENTIAL_ENV), + overrides: { probeOpenAiLikeEndpoint }, }); await harness.setupInference("test-box", MODEL, PROVIDER, ENDPOINT, CREDENTIAL_ENV, null, [], { @@ -105,7 +147,7 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 expect( harness.commands.some(({ command }) => command === `provider delete -g nemoclaw ${PROVIDER}`), ).toBe(true); - expect(deleteGatewayProvider).not.toHaveBeenCalled(); + expect(harness.commands.some(({ command }) => command.includes("provider detach"))).toBe(false); const createCommand = harness.commands.find(({ command }) => command.startsWith("provider create"), ); @@ -115,24 +157,20 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 it("recovers the flip when the stale provider is attached only to the onboarding sandbox", async () => { vi.stubEnv(CREDENTIAL_ENV, "hub-secret"); const probeOpenAiLikeEndpoint = vi.fn(() => ({ ok: true })); - const readGatewayProviderMetadata = vi.fn(staleAnthropicMetadata); - const deleteGatewayProvider = vi.fn(() => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ - runOpenshell: commandStubs({ - "provider get": { status: 1 }, - "provider delete": { - status: 1, - stderr: `provider '${PROVIDER}' is attached to sandbox(es): test-box`, - }, - }), - overrides: { probeOpenAiLikeEndpoint, readGatewayProviderMetadata, deleteGatewayProvider }, + runOpenshell: createStaleAnthropicProviderRunner(PROVIDER, CREDENTIAL_ENV, ["test-box"]), + overrides: { probeOpenAiLikeEndpoint }, }); await harness.setupInference("test-box", MODEL, PROVIDER, ENDPOINT, CREDENTIAL_ENV, null, [], { preferredInferenceApi: "openai-completions", }); - expect(deleteGatewayProvider).toHaveBeenCalledWith(PROVIDER, expect.anything()); + expect(harness.commands.filter(({ command }) => command.includes("provider detach"))).toEqual([ + expect.objectContaining({ + command: `sandbox provider detach -g nemoclaw test-box ${PROVIDER}`, + }), + ]); const createCommand = harness.commands.find(({ command }) => command.startsWith("provider create"), ); @@ -143,20 +181,13 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 vi.stubEnv(CREDENTIAL_ENV, "hub-secret"); const exitProcess = createInjectedExit(); const probeOpenAiLikeEndpoint = vi.fn(() => ({ ok: true })); - const readGatewayProviderMetadata = vi.fn(staleAnthropicMetadata); - const deleteGatewayProvider = vi.fn(() => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ - runOpenshell: commandStubs({ - "provider get": { status: 1 }, - "provider delete": { - status: 1, - stderr: `provider '${PROVIDER}' is attached to sandbox(es): other-box, test-box`, - }, - }), + runOpenshell: createStaleAnthropicProviderRunner(PROVIDER, CREDENTIAL_ENV, [ + "other-box", + "test-box", + ]), overrides: { probeOpenAiLikeEndpoint, - readGatewayProviderMetadata, - deleteGatewayProvider, exitProcess, isNonInteractive: () => true, }, @@ -168,7 +199,7 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 }), ).rejects.toThrow("EXIT_CALLED:1"); - expect(deleteGatewayProvider).not.toHaveBeenCalled(); + expect(harness.commands.some(({ command }) => command.includes("provider detach"))).toBe(false); expect( harness.errors.some((message) => message.includes("attached to other sandbox(es) (other-box)"), diff --git a/test/onboarding/onboard-inference-gateway-scope.test.ts b/test/onboarding/onboard-inference-gateway-scope.test.ts index 45081891b8d..e048993d134 100644 --- a/test/onboarding/onboard-inference-gateway-scope.test.ts +++ b/test/onboarding/onboard-inference-gateway-scope.test.ts @@ -1,7 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { describe, expect, it, vi } from "vitest"; +import fs from "node:fs"; +import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; import type { SetupInference, SetupInferenceDeps } from "../../src/lib/onboard/setup-inference.js"; import { createDirectCommandRouter, @@ -9,9 +10,19 @@ import { withProcessEnv, } from "../support/setup-inference-test-harness.js"; -const onboard = require("../../src/lib/onboard") as { - createSetupInference: (overrides?: Partial) => SetupInference; +const testHome = await vi.hoisted(async () => { + const fs = await import("node:fs"); + const os = await import("node:os"); + const path = await import("node:path"); + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-scope-")); + vi.stubEnv("HOME", directory); + return directory; +}); +const { default: onboard } = (await import("../../src/lib/onboard")) as unknown as { + default: { createSetupInference: (overrides?: Partial) => SetupInference }; }; +afterAll(() => fs.rmSync(testHome, { recursive: true, force: true })); +beforeEach(() => vi.stubEnv("HOME", testHome)); const createHarness = createDirectSetupInferenceHarnessFactory(onboard.createSetupInference); const GATEWAY = "nemoclaw-9090"; @@ -191,11 +202,6 @@ describe("onboarding inference gateway scope", () => { name: "provider-delete", matches: (command) => command.startsWith(`provider delete -g ${GATEWAY}`), results: [ - { - status: 1, - stderr: - "provider 'compatible-anthropic-endpoint' is attached to sandbox(es): test-box", - }, { status: 1, stderr: @@ -225,7 +231,7 @@ describe("onboarding inference gateway scope", () => { ), ).resolves.toEqual({ ok: true }); - expect(commandRouter.callCount("provider-delete")).toBe(3); + expect(commandRouter.callCount("provider-delete")).toBe(2); expect(harness.commands.map(({ command }) => command)).toContain( `sandbox provider detach -g ${GATEWAY} test-box compatible-anthropic-endpoint`, ); diff --git a/test/package-contract/cli/credentials-cli-command.test.ts b/test/package-contract/cli/credentials-cli-command.test.ts index 851e7ae23cf..be3927f30da 100644 --- a/test/package-contract/cli/credentials-cli-command.test.ts +++ b/test/package-contract/cli/credentials-cli-command.test.ts @@ -352,6 +352,7 @@ describe("credentials oclif commands", () => { ignoreError: true, replaceEnv: true, stdio: ["ignore", "pipe", "pipe"], + suppressOutput: true, timeout: 30_000, }, }, diff --git a/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts b/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts index 9eda677a291..91a5bb50063 100644 --- a/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts +++ b/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts @@ -96,10 +96,10 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { message: "could not connect", }; - it("delegates GPU unload to stopAll() exactly once when stopHostServices=true", () => { + it("delegates GPU unload to stopAll() exactly once when stopHostServices=true", async () => { const harness = buildDeps({ provider: "ollama-local" }); - cleanupSandboxServices("regression-2717", { stopHostServices: true }, harness.deps); + await cleanupSandboxServices("regression-2717", { stopHostServices: true }, harness.deps); expect(harness.deps.stopAll).toHaveBeenCalledTimes(1); expect(harness.stopAllCalls[0]).toEqual( @@ -113,10 +113,10 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { expect(harness.unloadCalls).toBe(1); }); - it("skips host-wide Ollama discovery for a final sandbox with no Ollama ownership", () => { + it("skips host-wide Ollama discovery for a final sandbox with no Ollama ownership", async () => { const harness = buildDeps({ provider: "nvidia-prod" }); - cleanupSandboxServices("regression-2717", { stopHostServices: true }, harness.deps); + await cleanupSandboxServices("regression-2717", { stopHostServices: true }, harness.deps); expect(harness.stopAllCalls).toEqual([ expect.objectContaining({ @@ -128,11 +128,11 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { expect(harness.deps.unloadOllamaModels).not.toHaveBeenCalled(); }); - it("keeps host-wide Ollama cleanup enabled for retained model recovery", () => { + it("keeps host-wide Ollama cleanup enabled for retained model recovery", async () => { const harness = buildDeps({ provider: "nvidia-prod" }); vi.mocked(harness.deps.loadPendingOllamaModelCleanup).mockReturnValue(["old-model"]); - cleanupSandboxServices("regression-2717", { stopHostServices: true }, harness.deps); + await cleanupSandboxServices("regression-2717", { stopHostServices: true }, harness.deps); expect(harness.stopAllCalls).toEqual([ expect.objectContaining({ @@ -144,7 +144,7 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { expect(harness.deps.unloadOllamaModels).toHaveBeenCalledOnce(); }); - it("holds model ownership while final host-wide cleanup runs", () => { + it("holds model ownership while final host-wide cleanup runs", async () => { const harness = buildDeps({ provider: "ollama-local" }); let ownershipHeld = false; harness.deps.withOllamaModelOwnershipLock = vi.fn((operation) => { @@ -159,17 +159,17 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { expect(ownershipHeld).toBe(true); }); - cleanupSandboxServices("regression-2717", { stopHostServices: true }, harness.deps); + await cleanupSandboxServices("regression-2717", { stopHostServices: true }, harness.deps); expect(harness.deps.stopAll).toHaveBeenCalledOnce(); expect(harness.deps.unloadOllamaModels).toHaveBeenCalledOnce(); expect(ownershipHeld).toBe(false); }); - it("calls unloadOllamaModels() exactly once for an Ollama sandbox when stopHostServices=false", () => { + it("calls unloadOllamaModels() exactly once for an Ollama sandbox when stopHostServices=false", async () => { const harness = buildDeps({ provider: "ollama-local" }); - cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); + await cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); expect(harness.deps.stopAll).not.toHaveBeenCalled(); expect(harness.deps.unloadOllamaModels).toHaveBeenCalledTimes(1); @@ -177,31 +177,31 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { expect(harness.unloadCalls).toBe(1); }); - it("releases only the destroyed sandbox model when another Ollama sandbox uses a different model", () => { + it("releases only the destroyed sandbox model when another Ollama sandbox uses a different model", async () => { const harness = buildDeps({ provider: "ollama-local", model: "target-model:latest" }, [ { name: "peer", provider: "ollama-local", model: "peer-model:latest" }, ]); - cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); + await cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); expect(harness.unloadArgs).toEqual([["target-model:latest"]]); }); - it("keeps a model that another Ollama sandbox shares", () => { + it("keeps a model that another Ollama sandbox shares", async () => { const harness = buildDeps({ provider: "ollama-local", model: "shared-model" }, [ { name: "peer", provider: "ollama-local", model: "shared-model:latest" }, ]); - cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); + await cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); expect(harness.deps.unloadOllamaModels).not.toHaveBeenCalled(); }); - it("retries a pending superseded model after the sandbox route changes", () => { + it("retries a pending superseded model after the sandbox route changes", async () => { const harness = buildDeps({ provider: "nvidia-prod", model: "new-model" }); vi.mocked(harness.deps.loadPendingOllamaModelCleanup).mockReturnValue(["old-model"]); - cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); + await cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); expect(harness.unloadArgs).toEqual([["old-model"]]); expect(harness.deps.clearPendingOllamaModelCleanup).toHaveBeenCalledWith("regression-2717", [ @@ -209,29 +209,29 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { ]); }); - it("keeps a pending superseded model that an Ollama peer shares", () => { + it("keeps a pending superseded model that an Ollama peer shares", async () => { const harness = buildDeps({ provider: "nvidia-prod", model: "new-model" }, [ { name: "peer", provider: "ollama-local", model: "old-model:latest" }, ]); vi.mocked(harness.deps.loadPendingOllamaModelCleanup).mockReturnValue(["old-model"]); - cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); + await cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); expect(harness.deps.unloadOllamaModels).not.toHaveBeenCalled(); expect(harness.deps.clearPendingOllamaModelCleanup).not.toHaveBeenCalled(); }); - it("preserves destroy recovery state when stopAll cannot release Ollama", () => { + it("preserves destroy recovery state when stopAll cannot release Ollama", async () => { const harness = buildDeps({ provider: "ollama-local" }); vi.mocked(harness.deps.stopAll).mockReturnValue(cleanupFailure); - expect(() => + await expect( cleanupSandboxServices("regression-2717", { stopHostServices: true }, harness.deps), - ).toThrow(/saved route were retained.*retry destroy/); + ).rejects.toThrow(/saved route were retained.*retry destroy/); expect(harness.deps.rmSync).not.toHaveBeenCalled(); }); - it("preserves destroy recovery state when stopAll throws unexpectedly (#10553)", () => { + it("preserves destroy recovery state when stopAll throws unexpectedly (#10553)", async () => { const harness = buildDeps({ provider: "ollama-local" }); const stopError = new Error(`unexpected cleanup failure ${"detail ".repeat(100)}`); vi.mocked(harness.deps.stopAll).mockImplementation(() => { @@ -240,7 +240,7 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { let thrown: unknown; try { - cleanupSandboxServices("regression-2717", { stopHostServices: true }, harness.deps); + await cleanupSandboxServices("regression-2717", { stopHostServices: true }, harness.deps); } catch (error) { thrown = error; } @@ -255,29 +255,29 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { expect(harness.deps.runOpenshell).not.toHaveBeenCalled(); }); - it("preserves destroy recovery state when scoped Ollama release fails", () => { + it("preserves destroy recovery state when scoped Ollama release fails", async () => { const harness = buildDeps({ provider: "ollama-local" }); vi.mocked(harness.deps.unloadOllamaModels).mockReturnValue(cleanupFailure); - expect(() => + await expect( cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps), - ).toThrow(/saved route were retained.*retry destroy/); + ).rejects.toThrow(/saved route were retained.*retry destroy/); expect(harness.deps.rmSync).not.toHaveBeenCalled(); }); - it("skips unloadOllamaModels() entirely for non-Ollama providers", () => { + it("skips unloadOllamaModels() entirely for non-Ollama providers", async () => { const harness = buildDeps({ provider: "nvidia-prod" }); - cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); + await cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); expect(harness.deps.stopAll).not.toHaveBeenCalled(); expect(harness.deps.unloadOllamaModels).not.toHaveBeenCalled(); }); - it("removes the sandbox PID dir and tears down all messaging providers", () => { + it("removes the sandbox PID dir and tears down all messaging providers", async () => { const harness = buildDeps({ provider: "ollama-local" }); - cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); + await cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); expect(harness.deps.rmSync).toHaveBeenCalledWith( path.join("/tmp", "nemoclaw-services-regression-2717"), @@ -298,15 +298,15 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { ); }); - it("fails closed before other cleanup when the Google Chat tunnel cannot stop", () => { + it("fails closed before other cleanup when the Google Chat tunnel cannot stop", async () => { const harness = buildDeps({ provider: "ollama-local" }); vi.mocked(harness.deps.stopGooglechatWebhookTunnel).mockImplementation(() => { throw new Error("cloudflared refused to stop"); }); - expect(() => + await expect( cleanupSandboxServices("regression-2717", { stopHostServices: true }, harness.deps), - ).toThrow(/Refusing to finish sandbox cleanup/); + ).rejects.toThrow(/Refusing to finish sandbox cleanup/); expect(harness.deps.getSandbox).not.toHaveBeenCalled(); expect(harness.deps.stopAll).not.toHaveBeenCalled(); @@ -315,12 +315,12 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { expect(harness.deps.runOpenshell).not.toHaveBeenCalled(); }); - it("rejects traversal-shaped sandbox names before any cleanup side effect", () => { + it("rejects traversal-shaped sandbox names before any cleanup side effect", async () => { const harness = buildDeps({ provider: "ollama-local" }); - expect(() => + await expect( cleanupSandboxServices("x/../../victim", { stopHostServices: true }, harness.deps), - ).toThrow("Invalid sandbox name"); + ).rejects.toThrow("Invalid sandbox name"); expect(harness.deps.getSandbox).not.toHaveBeenCalled(); expect(harness.deps.stopAll).not.toHaveBeenCalled(); diff --git a/test/runtime/sandbox/sandbox-provider-cleanup.test.ts b/test/runtime/sandbox/sandbox-provider-cleanup.test.ts index 11aaca2304e..e38b4b6ea69 100644 --- a/test/runtime/sandbox/sandbox-provider-cleanup.test.ts +++ b/test/runtime/sandbox/sandbox-provider-cleanup.test.ts @@ -2,14 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; +import { createCliOpenShellProviderAdapter } from "../../../src/lib/adapters/openshell/provider-adapter-cli"; +import type { + OpenShellProviderAdapter, + OpenShellProviderError, +} from "../../../src/lib/adapters/openshell/provider-adapter"; import { deleteProviderWithRecovery, detachSandboxProviders, type DetachSandboxProvidersDeps, emitProviderDetachResidualHint, - parseAttachedSandboxes, - recoverAttachedProvider, runSandboxProviderPreDeleteCleanup, SANDBOX_PROVIDER_SUFFIXES, } from "../../../src/lib/onboard/sandbox-provider-cleanup.js"; @@ -31,7 +34,7 @@ function buildRunOpenshell( } describe("SANDBOX_PROVIDER_SUFFIXES", () => { - it("covers the full set of per-sandbox messaging and search providers", () => { + it("covers the full set of per-sandbox messaging and search providers", async () => { expect([...SANDBOX_PROVIDER_SUFFIXES].sort()).toEqual( [ "telegram-bridge", @@ -49,10 +52,10 @@ describe("SANDBOX_PROVIDER_SUFFIXES", () => { }); describe("detachSandboxProviders", () => { - it("issues 'sandbox provider detach' for every suffix in the shared set", () => { + it("issues 'sandbox provider detach' for every suffix in the shared set", async () => { const { runOpenshell, calls } = buildRunOpenshell(new Map()); - const result = detachSandboxProviders("spark-nemo", { runOpenshell }); + const result = await detachSandboxProviders("spark-nemo", { runOpenshell }); const detachCalls = calls.filter( (argv) => argv[0] === "sandbox" && argv[1] === "provider" && argv[2] === "detach", @@ -70,7 +73,7 @@ describe("detachSandboxProviders", () => { expect(result.failures).toEqual([]); }); - it("detects a same-name replacement after one detach and stops later detaches (#9833)", () => { + it("detects a same-name replacement after one detach and stops later detaches (#9833)", async () => { const calls: string[][] = []; const expectedIdentity = "identity-a"; let liveIdentity = expectedIdentity; @@ -87,7 +90,9 @@ describe("detachSandboxProviders", () => { }); const deps: DetachSandboxProvidersDeps = { runOpenshell, revalidateSandboxIdentity }; - expect(() => detachSandboxProviders("alpha", deps)).toThrow(/sandbox identity changed/u); + await expect(detachSandboxProviders("alpha", deps)).rejects.toThrow( + /sandbox identity changed/u, + ); expect(calls).toHaveLength(1); expect(revalidateSandboxIdentity.mock.calls.map(([operation]) => operation)).toEqual([ expect.stringMatching(/^detaching provider /u), @@ -95,13 +100,13 @@ describe("detachSandboxProviders", () => { ]); }); - it("treats provider-scoped NotFound / not attached outputs as success-equivalent", () => { + it("treats provider-scoped NotFound / not attached outputs as success-equivalent", async () => { const responses = new Map([ [ "sandbox provider detach alpha alpha-telegram-bridge", { status: 1, - stderr: "Error: status: NotFound, provider 'alpha-telegram-bridge' not found", + stderr: "Error: provider 'alpha-telegram-bridge' not found", }, ], [ @@ -111,7 +116,7 @@ describe("detachSandboxProviders", () => { ]); const { runOpenshell } = buildRunOpenshell(responses); - const result = detachSandboxProviders("alpha", { runOpenshell }); + const result = await detachSandboxProviders("alpha", { runOpenshell }); expect(result.failures).toEqual([]); expect(result.detached).toContain("alpha-discord-bridge"); @@ -119,7 +124,7 @@ describe("detachSandboxProviders", () => { expect(result.detached).not.toContain("alpha-brave-search"); }); - it("tolerates the compact NotAttached status spelling", () => { + it("tolerates the compact NotAttached status spelling", async () => { const responses = new Map([ [ "sandbox provider detach gamma gamma-slack-bridge", @@ -128,13 +133,13 @@ describe("detachSandboxProviders", () => { ]); const { runOpenshell } = buildRunOpenshell(responses); - const result = detachSandboxProviders("gamma", { runOpenshell }); + const result = await detachSandboxProviders("gamma", { runOpenshell }); expect(result.failures).toEqual([]); expect(result.detached).not.toContain("gamma-slack-bridge"); }); - it("does not tolerate a bare sandbox-not-found diagnostic — stale attachment may remain", () => { + it("does not tolerate a bare sandbox-not-found diagnostic — stale attachment may remain", async () => { const responses = new Map([ [ "sandbox provider detach zulu zulu-telegram-bridge", @@ -143,17 +148,17 @@ describe("detachSandboxProviders", () => { ]); const { runOpenshell } = buildRunOpenshell(responses); - const result = detachSandboxProviders("zulu", { runOpenshell }); + const result = await detachSandboxProviders("zulu", { runOpenshell }); expect(result.failures).toEqual([ { name: "zulu-telegram-bridge", - output: "Error: status: NotFound, sandbox 'zulu' not found", + output: "OpenShell sandbox not found: 'zulu'.", }, ]); }); - it("does not tolerate unrelated gateway errors that incidentally contain 'not attached'", () => { + it("does not tolerate unrelated gateway errors that incidentally contain 'not attached'", async () => { const responses = new Map([ [ "sandbox provider detach yankee yankee-telegram-bridge", @@ -166,16 +171,42 @@ describe("detachSandboxProviders", () => { ]); const { runOpenshell } = buildRunOpenshell(responses); - const result = detachSandboxProviders("yankee", { runOpenshell }); + const result = await detachSandboxProviders("yankee", { runOpenshell }); - // Stricter expectation would require structured status codes — until OpenShell - // exposes those, this stays as a regression marker: when a real diagnostic of - // this shape ships and shows up here, tighten the tolerance regex around the - // canonical detach diagnostics rather than the word fragments. - expect(result.failures.some((f) => f.name === "yankee-telegram-bridge")).toBe(false); + expect(result.failures).toEqual([ + { + name: "yankee-telegram-bridge", + output: + "Error: internal gateway error: shield 'sentry' is not attached to its expected anchor", + }, + ]); }); - it("tolerates sandbox-not-found when tolerateMissingSandbox is set (opportunistic call)", () => { + it("retains a detach failure for a different missing sandbox even when absence is tolerated", async () => { + const { runOpenshell } = buildRunOpenshell( + new Map([ + [ + "sandbox provider detach phantom phantom-telegram-bridge", + { + status: 1, + stderr: "Error: status: NotFound, sandbox 'other-box' not found", + }, + ], + ]), + ); + const result = await detachSandboxProviders("phantom", { + runOpenshell, + tolerateMissingSandbox: true, + }); + expect(result.failures).toEqual([ + { + name: "phantom-telegram-bridge", + output: "Error: status: NotFound, sandbox 'other-box' not found", + }, + ]); + }); + + it("tolerates sandbox-not-found when tolerateMissingSandbox is set (opportunistic call)", async () => { const responses = new Map([ [ "sandbox provider detach phantom phantom-telegram-bridge", @@ -184,7 +215,7 @@ describe("detachSandboxProviders", () => { ]); const { runOpenshell } = buildRunOpenshell(responses); - const result = detachSandboxProviders("phantom", { + const result = await detachSandboxProviders("phantom", { runOpenshell, tolerateMissingSandbox: true, }); @@ -192,13 +223,13 @@ describe("detachSandboxProviders", () => { expect(result.failures).toEqual([]); }); - it("suppresses output for tolerated missing-sandbox detach probes", () => { + it("suppresses output for tolerated missing-sandbox detach probes", async () => { const { runOpenshell } = buildRunOpenshell(new Map(), { status: 1, stderr: "Error: status: NotFound, sandbox 'phantom' not found", }); - const result = detachSandboxProviders("phantom", { + const result = await detachSandboxProviders("phantom", { runOpenshell, tolerateMissingSandbox: true, }); @@ -214,7 +245,7 @@ describe("detachSandboxProviders", () => { }); }); - it("collects non-tolerated failures without aborting the loop", () => { + it("collects non-tolerated failures without aborting the loop", async () => { const responses = new Map([ [ "sandbox provider detach beta beta-telegram-bridge", @@ -223,7 +254,7 @@ describe("detachSandboxProviders", () => { ]); const { runOpenshell, calls } = buildRunOpenshell(responses); - const result = detachSandboxProviders("beta", { runOpenshell }); + const result = await detachSandboxProviders("beta", { runOpenshell }); const detachCalls = calls.filter( (argv) => argv[0] === "sandbox" && argv[1] === "provider" && argv[2] === "detach", @@ -235,10 +266,10 @@ describe("detachSandboxProviders", () => { expect(result.detached).toHaveLength(SANDBOX_PROVIDER_SUFFIXES.length - 1); }); - it("includes Brave and Tavily search providers in the detach set", () => { + it("includes Brave and Tavily search providers in the detach set", async () => { const { runOpenshell, calls } = buildRunOpenshell(new Map()); - detachSandboxProviders("spark-nemo", { runOpenshell }); + await detachSandboxProviders("spark-nemo", { runOpenshell }); const braveCall = calls.find( (argv) => @@ -260,17 +291,17 @@ describe("detachSandboxProviders", () => { }); describe("runSandboxProviderPreDeleteCleanup", () => { - it("emits no warning when every detach succeeds", () => { + it("emits no warning when every detach succeeds", async () => { const { runOpenshell } = buildRunOpenshell(new Map()); const warn = vi.fn(); - const result = runSandboxProviderPreDeleteCleanup("spark-nemo", { runOpenshell, warn }); + const result = await runSandboxProviderPreDeleteCleanup("spark-nemo", { runOpenshell, warn }); expect(warn).not.toHaveBeenCalled(); expect(result.failures).toEqual([]); }); - it("redacts the OpenShell failure output before warning", () => { + it("redacts the OpenShell failure output before warning", async () => { const tokenOutput = "Error: token AKIA0123456789ABCDEF failed: status Internal, gateway timeout"; const responses = new Map([ @@ -280,18 +311,22 @@ describe("runSandboxProviderPreDeleteCleanup", () => { const warn = vi.fn(); const redact = vi.fn((s: string) => s.replace(/AKIA[0-9A-Z]+/, "[REDACTED]")); - const result = runSandboxProviderPreDeleteCleanup("delta", { runOpenshell, warn, redact }); + const result = await runSandboxProviderPreDeleteCleanup("delta", { + runOpenshell, + warn, + redact, + }); expect(result.failures).toHaveLength(1); expect(redact).toHaveBeenCalledWith(result.failures[0].output); expect(warn).toHaveBeenCalledTimes(1); const warning = warn.mock.calls[0][0] as string; - expect(warning).toContain("[REDACTED]"); + expect(warning).toContain(""); expect(warning).not.toContain("AKIA0123456789ABCDEF"); expect(warning).toContain("delta-telegram-bridge"); }); - it("caps the warning output length to bound terminal noise on huge stderr", () => { + it("caps the warning output length to bound terminal noise on huge stderr", async () => { const longTail = "X".repeat(2000); const responses = new Map([ [ @@ -302,17 +337,17 @@ describe("runSandboxProviderPreDeleteCleanup", () => { const { runOpenshell } = buildRunOpenshell(responses); const warn = vi.fn(); - runSandboxProviderPreDeleteCleanup("echo", { runOpenshell, warn }); + await runSandboxProviderPreDeleteCleanup("echo", { runOpenshell, warn }); expect(warn).toHaveBeenCalledTimes(1); const warning = warn.mock.calls[0][0] as string; expect(warning.length).toBeLessThan(900); }); - it("runs the detach pass before any caller-driven sandbox delete", () => { + it("runs the detach pass before any caller-driven sandbox delete", async () => { const { runOpenshell, calls } = buildRunOpenshell(new Map()); - runSandboxProviderPreDeleteCleanup("foxtrot", { runOpenshell }); + await runSandboxProviderPreDeleteCleanup("foxtrot", { runOpenshell }); runOpenshell(["sandbox", "delete", "foxtrot"], { ignoreError: true }); const detachCount = calls.filter( @@ -324,100 +359,179 @@ describe("runSandboxProviderPreDeleteCleanup", () => { }); }); -describe("parseAttachedSandboxes", () => { - it("parses a single sandbox name from a FailedPrecondition diagnostic", () => { - const output = - "Error: × status: FailedPrecondition, message: \"provider 'spark-nemo-telegram-bridge' is attached to sandbox(es): spark-nemo\""; - expect(parseAttachedSandboxes(output)).toEqual(["spark-nemo"]); - }); - - it("parses an OpenShell diagnostic wrapped with continuation markers", () => { - const output = - "Error: × code: 'The system is not in a state required for the operation's\n" + - "│ execution', message: \"provider 'compatible-endpoint' is attached to\n" + - '│ sandbox(es): e2e-diag"'; - expect(parseAttachedSandboxes(output)).toEqual(["e2e-diag"]); - }); - - it("parses multiple sandbox names from the same diagnostic", () => { - const output = "provider 'x' is attached to sandbox(es): alpha, beta, gamma"; - expect(parseAttachedSandboxes(output)).toEqual(["alpha", "beta", "gamma"]); - }); - - it("returns empty when the diagnostic has no attached-to list", () => { - expect(parseAttachedSandboxes("some unrelated error message")).toEqual([]); - }); - - it("rejects names that fail NemoClaw sandbox-name validation", () => { - expect( - parseAttachedSandboxes( - "attached to sandbox(es): --rm, UPPERCASE, valid-name, " + - "thisnameiswaytoolongtobeavalidkubernetesresourcelabel-but-keeps-going-1234567890", - ), - ).toEqual(["valid-name"]); +describe("deleteProviderWithRecovery", () => { + it.each([ + { status: 0 }, + { status: 1, stderr: "status: NotAttached, provider 'p' is not bound" }, + { status: 1, stderr: "provider 'p' not found" }, + ])("confirms every authorized attachment before the single delete retry: %#", async (detach) => { + const runOpenshell = vi + .fn() + .mockReturnValueOnce({ + status: 1, + stderr: "provider 'p' is attached to sandbox(es): first, second", + }) + .mockReturnValueOnce(detach) + .mockReturnValueOnce(detach) + .mockReturnValueOnce({ status: 0 }); + await expect( + deleteProviderWithRecovery("p", { + runOpenshell, + allowedSandboxes: ["first", "second"], + }), + ).resolves.toEqual({ ok: true, recoveryFailures: [] }); + expect(runOpenshell.mock.calls.map(([args]) => args)).toEqual([ + ["provider", "delete", "p"], + ["sandbox", "provider", "detach", "first", "p"], + ["sandbox", "provider", "detach", "second", "p"], + ["provider", "delete", "p"], + ]); }); -}); -describe("recoverAttachedProvider", () => { - it("calls detach for each attached sandbox and reports the cleared ones", () => { - const { runOpenshell, calls } = buildRunOpenshell(new Map()); + it("does not retry deletion when detach reports a different provider as missing", async () => { + const runOpenshell = vi + .fn() + .mockReturnValueOnce({ + status: 1, + stderr: "provider 'owned-provider' is attached to sandbox(es): mine", + }) + .mockReturnValueOnce({ status: 1, stderr: "provider 'other-provider' not found" }); - const result = recoverAttachedProvider("orphan-provider", ["sandbox-a", "sandbox-b"], { + const result = await deleteProviderWithRecovery("owned-provider", { runOpenshell, + allowedSandboxes: ["mine"], }); - expect(result.detached).toEqual(["sandbox-a", "sandbox-b"]); - expect(result.failures).toEqual([]); - expect(calls).toEqual([ - ["sandbox", "provider", "detach", "sandbox-a", "orphan-provider"], - ["sandbox", "provider", "detach", "sandbox-b", "orphan-provider"], + expect(result.ok).toBe(false); + expect(result.recoveryFailures).toEqual([ + { sandbox: "mine", output: "provider 'other-provider' not found" }, ]); - }); - - it("treats NotAttached / provider-not-found as already-cleared (not failure)", () => { - const responses = new Map([ - [ - "sandbox provider detach ghost orphan-provider", - { status: 1, stderr: "status: NotAttached, provider 'orphan-provider' is not bound" }, - ], + expect(runOpenshell.mock.calls.map(([args]) => args)).toEqual([ + ["provider", "delete", "owned-provider"], + ["sandbox", "provider", "detach", "mine", "owned-provider"], ]); - const { runOpenshell } = buildRunOpenshell(responses); - - const result = recoverAttachedProvider("orphan-provider", ["ghost"], { runOpenshell }); - - expect(result.detached).toEqual(["ghost"]); - expect(result.failures).toEqual([]); }); - it("returns non-tolerated detach failures for the caller to surface", () => { - const responses = new Map([ - [ - "sandbox provider detach alpha orphan-provider", - { status: 1, stderr: "Error: status: Internal, gateway timeout" }, - ], - ]); - const { runOpenshell } = buildRunOpenshell(responses); - - const result = recoverAttachedProvider("orphan-provider", ["alpha"], { runOpenshell }); - - expect(result.detached).toEqual([]); - expect(result.failures).toEqual([ - { sandbox: "alpha", output: "Error: status: Internal, gateway timeout" }, - ]); + it("waits for every typed detach before retrying an attached provider deletion", async () => { + const events: string[] = []; + let releaseDetach!: () => void; + const pendingDetach = new Promise((resolve) => { + releaseDetach = resolve; + }); + const adapter: OpenShellProviderAdapter = { + ...createCliOpenShellProviderAdapter({ + run: () => { + throw new Error("unexpected transport"); + }, + }), + deleteProvider: vi.fn(async () => { + events.push("delete"); + return events.length === 1 + ? { + ok: false as const, + error: { + kind: "command" as const, + reason: "attached" as const, + message: "attached", + attachedSandboxes: ["owned"], + }, + } + : { ok: true as const }; + }), + detachProvider: vi.fn(async () => { + events.push("detach-start"); + await pendingDetach; + events.push("detach-complete"); + return { ok: true as const, value: { changed: true } }; + }), + }; + const cleanup = deleteProviderWithRecovery("provider", { + providerAdapter: adapter, + allowedSandboxes: ["owned"], + }); + await vi.waitFor(() => expect(events).toEqual(["delete", "detach-start"])); + releaseDetach(); + await expect(cleanup).resolves.toMatchObject({ ok: true }); + expect(events).toEqual(["delete", "detach-start", "detach-complete", "delete"]); }); -}); -describe("deleteProviderWithRecovery", () => { - it("returns ok on first-attempt success without recovery", () => { + it.each([ + { kind: "timeout", message: "timed out" }, + { kind: "transport", reason: "connection_loss", message: "connection lost" }, + { kind: "command", reason: "uncertain", message: "outcome unknown" }, + ])( + "preserves recovery state without another delete after a failed detach: $kind", + async (error) => { + const adapter: OpenShellProviderAdapter = { + ...createCliOpenShellProviderAdapter({ + run: () => { + throw new Error("unexpected transport"); + }, + }), + deleteProvider: vi.fn(async () => ({ + ok: false, + error: { + kind: "command", + reason: "attached", + message: "attached", + attachedSandboxes: ["owned"], + }, + })), + detachProvider: vi.fn(async () => ({ + ok: false, + error, + })), + }; + await expect( + deleteProviderWithRecovery("provider", { + providerAdapter: adapter, + allowedSandboxes: ["owned"], + }), + ).resolves.toMatchObject({ + ok: false, + recoveryFailures: [{ sandbox: "owned", output: error.message }], + }); + expect(adapter.deleteProvider).toHaveBeenCalledOnce(); + }, + ); + + it("does not detach or retry an uncertain delete even if its diagnostic names attachments", async () => { + const adapter: OpenShellProviderAdapter = { + ...createCliOpenShellProviderAdapter({ + run: () => { + throw new Error("unexpected transport"); + }, + }), + deleteProvider: vi.fn(async () => ({ + ok: false, + error: { + kind: "command", + reason: "uncertain", + message: "attached to sandbox(es): owned", + attachedSandboxes: ["owned"], + }, + })), + detachProvider: vi.fn(), + }; + await expect( + deleteProviderWithRecovery("provider", { + providerAdapter: adapter, + allowedSandboxes: ["owned"], + }), + ).resolves.toMatchObject({ ok: false }); + expect(adapter.deleteProvider).toHaveBeenCalledOnce(); + expect(adapter.detachProvider).not.toHaveBeenCalled(); + }); + it("returns ok on first-attempt success without recovery", async () => { const { runOpenshell } = buildRunOpenshell(new Map()); - const result = deleteProviderWithRecovery("happy-provider", { runOpenshell }); + const result = await deleteProviderWithRecovery("happy-provider", { runOpenshell }); expect(result.ok).toBe(true); expect(result.recoveryFailures).toEqual([]); }); - it("retries delete after force-detaching a sandbox from a wrapped diagnostic", () => { + it("retries delete after force-detaching a sandbox from a wrapped diagnostic", async () => { let attempt = 0; const calls: string[][] = []; const runOpenshell = vi.fn((args: string[]) => { @@ -439,7 +553,7 @@ describe("deleteProviderWithRecovery", () => { return { status: 0, stdout: "", stderr: "" }; }); - const result = deleteProviderWithRecovery("p", { runOpenshell }); + const result = await deleteProviderWithRecovery("p", { runOpenshell }); expect(result.ok).toBe(true); expect(result.recoveryFailures).toEqual([]); @@ -450,7 +564,7 @@ describe("deleteProviderWithRecovery", () => { ]); }); - it("returns recovery failures and final delete failure when the retry still trips", () => { + it("returns recovery failures and final delete failure when the retry still trips", async () => { const runOpenshell = vi.fn((args: string[]) => { if (args[0] === "provider" && args[1] === "delete") { return { @@ -466,7 +580,7 @@ describe("deleteProviderWithRecovery", () => { return { status: 0, stdout: "", stderr: "" }; }); - const result = deleteProviderWithRecovery("p", { runOpenshell }); + const result = await deleteProviderWithRecovery("p", { runOpenshell }); expect(result.ok).toBe(false); expect(result.recoveryFailures).toEqual([ @@ -474,7 +588,7 @@ describe("deleteProviderWithRecovery", () => { ]); }); - it("force-detaches when every attached sandbox is inside the allowed set", () => { + it("force-detaches when every attached sandbox is inside the allowed set", async () => { const calls: string[][] = []; let attempt = 0; const runOpenshell = vi.fn((args: string[]) => { @@ -491,7 +605,10 @@ describe("deleteProviderWithRecovery", () => { : { status: 0, stdout: "", stderr: "" }; }); - const result = deleteProviderWithRecovery("p", { runOpenshell, allowedSandboxes: ["mine"] }); + const result = await deleteProviderWithRecovery("p", { + runOpenshell, + allowedSandboxes: ["mine"], + }); expect(result.ok).toBe(true); expect(calls).toEqual([ @@ -501,7 +618,7 @@ describe("deleteProviderWithRecovery", () => { ]); }); - it("fails closed without detaching when a sandbox outside the allowed set appears (security)", () => { + it("fails closed without detaching when a sandbox outside the allowed set appears (security)", async () => { const calls: string[][] = []; const runOpenshell = vi.fn((args: string[]) => { calls.push(args); @@ -513,7 +630,10 @@ describe("deleteProviderWithRecovery", () => { }; }); - const result = deleteProviderWithRecovery("p", { runOpenshell, allowedSandboxes: ["mine"] }); + const result = await deleteProviderWithRecovery("p", { + runOpenshell, + allowedSandboxes: ["mine"], + }); expect(result.ok).toBe(false); expect(result.recoveryFailures).toEqual([]); @@ -523,13 +643,13 @@ describe("deleteProviderWithRecovery", () => { }); describe("emitProviderDetachResidualHint", () => { - it("emits nothing when there are no failures", () => { + it("emits nothing when there are no failures", async () => { const warn = vi.fn(); emitProviderDetachResidualHint("alpha", [], warn); expect(warn).not.toHaveBeenCalled(); }); - it("emits a detach-then-delete sequence keyed to the sandbox name", () => { + it("emits a detach-then-delete sequence keyed to the sandbox name", async () => { const warn = vi.fn(); emitProviderDetachResidualHint( "alpha", diff --git a/test/support/setup-inference-test-harness.ts b/test/support/setup-inference-test-harness.ts index 0632bbf9236..0caa314136e 100644 --- a/test/support/setup-inference-test-harness.ts +++ b/test/support/setup-inference-test-harness.ts @@ -52,6 +52,45 @@ export type DirectSetupHarnessOptions = { overrides?: Partial; }; +/** Model stale Anthropic registration removal without bypassing provider parsing or recovery. */ +export function createStaleAnthropicProviderRunner( + provider: string, + credentialEnv: string, + attachedSandboxes: readonly string[] = [], +): NonNullable { + let exists = true; + let attached = attachedSandboxes; + return (args) => { + const isProviderOperation = + (args[0] === "provider" && ["get", "delete"].includes(args[1])) || + (args[0] === "sandbox" && args[1] === "provider" && args[2] === "detach"); + if (isProviderOperation && (!exists || args.at(-1) !== provider)) { + return { status: 1, stderr: `provider '${args.at(-1)}' not found` }; + } + if (args[0] === "provider" && args[1] === "get") { + return { + status: 0, + stdout: `Name: ${provider}\nType: anthropic\nCredential keys: ${credentialEnv}\nConfig keys: ANTHROPIC_BASE_URL`, + }; + } + if (args[0] === "provider" && args[1] === "delete") { + if (attached.length > 0) { + return { + status: 1, + stderr: `provider '${provider}' is attached to sandbox(es): ${attached.join(", ")}`, + }; + } + exists = false; + return { status: 0 }; + } + if (args[0] === "sandbox" && args[1] === "provider" && args.includes("detach")) { + attached = attached.filter((sandbox) => !args.includes(sandbox)); + return { status: 0 }; + } + return undefined; + }; +} + const OPENAI_ENDPOINTLESS_PROFILE = JSON.stringify({ id: "openai", credentials: [], From 5159f1bc5b22cce6aa774d62ad39a2c82bcfd3bb Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:01:31 -0700 Subject: [PATCH 2/2] fix(providers): preserve cleanup failure and absence diagnostics Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../provider-adapter-cli-uncertainty.test.ts | 3 ++ .../openshell/provider-adapter-cli.test.ts | 31 +++++++++--------- .../openshell/provider-adapter-cli.ts | 2 +- .../openshell/provider-diagnostic-cli.ts | 8 ++++- src/lib/adapters/uninstall/commands.test.ts | 32 +++++++++++++++++++ src/lib/adapters/uninstall/commands.ts | 4 +++ .../remote-openai-surface.test.ts | 9 +++++- src/lib/onboard/inference-providers/remote.ts | 5 ++- ...-anthropic-compatible-openai-agent.test.ts | 10 +++--- test/support/setup-inference-test-harness.ts | 2 +- 10 files changed, 81 insertions(+), 25 deletions(-) diff --git a/src/lib/adapters/openshell/provider-adapter-cli-uncertainty.test.ts b/src/lib/adapters/openshell/provider-adapter-cli-uncertainty.test.ts index 55ac1da2486..c5b96d2d177 100644 --- a/src/lib/adapters/openshell/provider-adapter-cli-uncertainty.test.ts +++ b/src/lib/adapters/openshell/provider-adapter-cli-uncertainty.test.ts @@ -78,6 +78,9 @@ describe("CLI OpenShell provider adapter uncertain mutations", () => { it.each([ "provider other-provider is not attached", + "Provider other-provider was not attached to sandbox alpha.", + "Provider search-prod was not attached to sandbox other-sandbox.", + "unauthorized; Provider search-prod was not attached to sandbox alpha.", "status: NotAttached, provider 'other-provider' is not bound", "unauthorized; provider search-prod is not attached", "connection reset; NotAttached", diff --git a/src/lib/adapters/openshell/provider-adapter-cli.test.ts b/src/lib/adapters/openshell/provider-adapter-cli.test.ts index a7057068905..4112374535f 100644 --- a/src/lib/adapters/openshell/provider-adapter-cli.test.ts +++ b/src/lib/adapters/openshell/provider-adapter-cli.test.ts @@ -1277,22 +1277,23 @@ describe("CLI OpenShell provider adapter", () => { ); }); - it.each(["NotAttached", "provider search-prod is not attached"])( - "treats an idempotent detach result as already detached: %s (#9806)", - async (diagnostic) => { - const adapter = createCliOpenShellProviderAdapter({ - run: () => captured(1, "", diagnostic), - }); + it.each([ + "NotAttached", + "provider search-prod is not attached", + "Provider search-prod was not attached to sandbox alpha.", + ])("treats an idempotent detach result as already detached: %s (#9806)", async (diagnostic) => { + const adapter = createCliOpenShellProviderAdapter({ + run: () => captured(1, "", diagnostic), + }); - await expect( - adapter.detachProvider({ - target: selectedOpenShellGateway(), - providerName: "search-prod", - sandboxName: "alpha", - }), - ).resolves.toEqual({ ok: true, value: { changed: false } }); - }, - ); + await expect( + adapter.detachProvider({ + target: selectedOpenShellGateway(), + providerName: "search-prod", + sandboxName: "alpha", + }), + ).resolves.toEqual({ ok: true, value: { changed: false } }); + }); it("classifies the exact provider-detach resource-version race (#9806)", async () => { const diagnostic = diff --git a/src/lib/adapters/openshell/provider-adapter-cli.ts b/src/lib/adapters/openshell/provider-adapter-cli.ts index e3194f784a1..66b5d5a618d 100644 --- a/src/lib/adapters/openshell/provider-adapter-cli.ts +++ b/src/lib/adapters/openshell/provider-adapter-cli.ts @@ -695,7 +695,7 @@ export function createCliOpenShellProviderAdapter( !result.error && !result.signal && result.status !== null && - reportsProviderNotAttached(output, request.providerName); + reportsProviderNotAttached(output, request.providerName, request.sandboxName); if (confirmedIdempotentDetach) { return success({ changed: false }); } diff --git a/src/lib/adapters/openshell/provider-diagnostic-cli.ts b/src/lib/adapters/openshell/provider-diagnostic-cli.ts index b3afe448144..b0ea56266af 100644 --- a/src/lib/adapters/openshell/provider-diagnostic-cli.ts +++ b/src/lib/adapters/openshell/provider-diagnostic-cli.ts @@ -266,9 +266,15 @@ export function reportsExactSandboxNotFound( } /** Accept an absent attachment only when the complete diagnostic matches this operation. */ -export function reportsProviderNotAttached(output: string, providerName: string): boolean { +export function reportsProviderNotAttached( + output: string, + providerName: string, + sandboxName: string, +): boolean { const text = stripDiagnosticPrefixes(output.trim()); if (/^(?:NotAttached|provider not attached to sandbox)[.!]?$/iu.test(text)) return true; + const absent = /^provider (.+) was not attached to sandbox (.+?)[.!]?$/iu.exec(text); + if (absent) return absent[1] === providerName && absent[2] === sandboxName; const compact = /^NotAttached, provider (["'`])(.+)\1 is not bound[.!]?$/iu.exec(text); if (compact) return compact[2] === providerName; const named = /^provider (?:(["'`])(.+)\1|([^\s]+)) is not attached[.!]?$/iu.exec(text); diff --git a/src/lib/adapters/uninstall/commands.test.ts b/src/lib/adapters/uninstall/commands.test.ts index 41b480c8e72..3a7c98d8829 100644 --- a/src/lib/adapters/uninstall/commands.test.ts +++ b/src/lib/adapters/uninstall/commands.test.ts @@ -50,3 +50,35 @@ it("binds provider deletion to the uninstall environment and preserves uncertain expect.objectContaining({ env }), ); }); + +it.each([ + ["ETIMEDOUT", { kind: "timeout" }], + ["ENOENT", { kind: "transport", reason: "process_start" }], + ["EACCES", { kind: "transport", reason: "process_start" }], +])( + "preserves %s from the uninstall subprocess through provider classification", + async (code, error) => { + spawn.mockReturnValue({ + status: null, + stdout: "", + stderr: "", + error: Object.assign(new Error(code), { code }), + }); + const adapter = createUninstallProviderAdapter(defaultRun, {}); + await expect( + adapter.deleteProvider({ target: { kind: "selected" }, providerName: "nvidia-nim" }), + ).resolves.toMatchObject({ ok: false, error }); + }, +); + +it("preserves a signal so interrupted detach cannot look idempotent", async () => { + spawn.mockReturnValue({ status: 1, stdout: "NotAttached", stderr: "", signal: "SIGTERM" }); + const adapter = createUninstallProviderAdapter(defaultRun, {}); + await expect( + adapter.detachProvider({ + target: { kind: "selected" }, + providerName: "nvidia-nim", + sandboxName: "alpha", + }), + ).resolves.toMatchObject({ ok: false }); +}); diff --git a/src/lib/adapters/uninstall/commands.ts b/src/lib/adapters/uninstall/commands.ts index 6edcf4c0843..a1404f4fbea 100644 --- a/src/lib/adapters/uninstall/commands.ts +++ b/src/lib/adapters/uninstall/commands.ts @@ -8,6 +8,8 @@ import { dockerSpawnSync } from "../docker/exec"; export interface RunResult { status: number | null; + error?: Error; + signal?: NodeJS.Signals | null; stdout: string; stderr: string; } @@ -15,6 +17,8 @@ export interface RunResult { function toRunResult(result: SpawnSyncReturns): RunResult { return { status: result.status, + ...(result.error ? { error: result.error } : {}), + ...(result.signal ? { signal: result.signal } : {}), stdout: typeof result.stdout === "string" ? result.stdout : String(result.stdout ?? ""), stderr: typeof result.stderr === "string" ? result.stderr : String(result.stderr ?? ""), }; diff --git a/src/lib/onboard/inference-providers/remote-openai-surface.test.ts b/src/lib/onboard/inference-providers/remote-openai-surface.test.ts index 47108ceb6a5..c6508ba7c2f 100644 --- a/src/lib/onboard/inference-providers/remote-openai-surface.test.ts +++ b/src/lib/onboard/inference-providers/remote-openai-surface.test.ts @@ -253,9 +253,12 @@ describe("custom Anthropic provider replacement on the OpenAI surface", () => { it("does not retry deletion or register a provider after an uncertain detach", async () => { const harness = createHarness(); const providerAdapter = createManagedProviderAdapter(harness.runOpenshell); + harness.deps.redact.mockImplementation((value) => + value.replaceAll("test-secret", "[redacted]"), + ); vi.spyOn(providerAdapter, "detachProvider").mockResolvedValue({ ok: false, - error: { kind: "command", reason: "uncertain", message: "outcome unknown" }, + error: { kind: "command", reason: "uncertain", message: "outcome unknown: test-secret" }, }); harness.runOpenshell.mockReturnValueOnce(ANTHROPIC_PROVIDER).mockReturnValueOnce({ status: 1, @@ -267,6 +270,10 @@ describe("custom Anthropic provider replacement on the OpenAI surface", () => { setupRemoteProviderInference(makeArgs(SANDBOX), { ...harness.deps, providerAdapter }), ).rejects.toThrow("EXIT_CALLED:1"); + expect(harness.error).toHaveBeenCalledWith( + expect.stringContaining(`detach failures: ${SANDBOX}: outcome unknown: [redacted]`), + ); + expect(harness.error.mock.calls.flat().join(" ")).not.toContain("test-secret"); expect(providerAdapter.detachProvider).toHaveBeenCalledExactlyOnceWith({ target: { kind: "selected" }, sandboxName: SANDBOX, diff --git a/src/lib/onboard/inference-providers/remote.ts b/src/lib/onboard/inference-providers/remote.ts index a48d9ad5cca..ce600dbedd6 100644 --- a/src/lib/onboard/inference-providers/remote.ts +++ b/src/lib/onboard/inference-providers/remote.ts @@ -121,11 +121,14 @@ async function replaceStaleAnthropicProviderForOpenAiSurface(args: { `endpoint or remove those sandboxes first.`, }; } + const recovery = attempt.recoveryFailures + .map((failure) => compactText(redact(`${failure.sandbox}: ${failure.output}`))) + .join("; "); const detail = compactText(redact(raw)); return { ok: false, status: 1, - message: `Failed to replace provider '${provider}' for the OpenAI-compatible route${detail ? `: ${detail}` : "."}`, + message: `Failed to replace provider '${provider}' for the OpenAI-compatible route${detail ? `: ${detail}` : "."}${recovery ? ` (detach failures: ${recovery})` : ""}`, }; } diff --git a/test/onboarding/onboard-anthropic-compatible-openai-agent.test.ts b/test/onboarding/onboard-anthropic-compatible-openai-agent.test.ts index 99497f93f7c..a4234926077 100644 --- a/test/onboarding/onboard-anthropic-compatible-openai-agent.test.ts +++ b/test/onboarding/onboard-anthropic-compatible-openai-agent.test.ts @@ -75,12 +75,12 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 "rejects a mismatched provider name during fixture %s without changing its state", (_operation, args) => { const runner = createStaleAnthropicProviderRunner(PROVIDER, CREDENTIAL_ENV, ["test-box"]); - expect(runner(args, {}, [])).toEqual({ + expect(runner(args)).toEqual({ status: 1, stderr: "provider 'other-provider' not found", }); - expect(runner(["provider", "get", PROVIDER], {}, [])?.status).toBe(0); - expect(runner(["provider", "delete", PROVIDER], {}, [])).toEqual({ + expect(runner(["provider", "get", PROVIDER])?.status).toBe(0); + expect(runner(["provider", "delete", PROVIDER])).toEqual({ status: 1, stderr: `provider '${PROVIDER}' is attached to sandbox(es): test-box`, }); @@ -93,8 +93,8 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 ["detach", ["sandbox", "provider", "detach", "test-box", PROVIDER]], ])("reports provider absence during fixture %s after deletion", (_operation, args) => { const runner = createStaleAnthropicProviderRunner(PROVIDER, CREDENTIAL_ENV); - expect(runner(["provider", "delete", PROVIDER], {}, [])).toEqual({ status: 0 }); - expect(runner(args, {}, [])).toEqual({ + expect(runner(["provider", "delete", PROVIDER])).toEqual({ status: 0 }); + expect(runner(args)).toEqual({ status: 1, stderr: `provider '${PROVIDER}' not found`, }); diff --git a/test/support/setup-inference-test-harness.ts b/test/support/setup-inference-test-harness.ts index 0caa314136e..38484ca1a40 100644 --- a/test/support/setup-inference-test-harness.ts +++ b/test/support/setup-inference-test-harness.ts @@ -57,7 +57,7 @@ export function createStaleAnthropicProviderRunner( provider: string, credentialEnv: string, attachedSandboxes: readonly string[] = [], -): NonNullable { +): (args: string[]) => DirectRunStubResult | undefined { let exists = true; let attached = attachedSandboxes; return (args) => {