diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index 87b60637a41..f6c72121e7a 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -39,7 +39,7 @@ "maxByFile": { "src/lib/actions/inference-set.ts": 32, "src/lib/actions/sandbox/connect.ts": 43, - "src/lib/actions/sandbox/destroy.ts": 29, + "src/lib/actions/sandbox/destroy.ts": 28, "src/lib/actions/sandbox/doctor.ts": 29, "src/lib/actions/sandbox/gateway-state.ts": 21, "src/lib/actions/sandbox/status-snapshot.ts": 19, diff --git a/scripts/checks/layer-import-boundaries.mts b/scripts/checks/layer-import-boundaries.mts index 7c0f9297391..b279bc58fa7 100644 --- a/scripts/checks/layer-import-boundaries.mts +++ b/scripts/checks/layer-import-boundaries.mts @@ -309,6 +309,19 @@ function checkAdapterFile( violations: Violation[], ): void { for (const ref of imports) { + if (repoPath.startsWith("src/lib/adapters/openshell/")) { + const policyTarget = importTargetsForbiddenLayer(absPath, ref, ["src/lib/policy/"]); + if (policyTarget) { + addViolation( + violations, + repoPath, + ref.line, + ref.column, + "openshell-adapters-no-policy", + `OpenShell adapters must not import policy module ${policyTarget}`, + ); + } + } const target = importTargetsForbiddenLayer(absPath, ref, ["src/commands/"], true); if (target) { addViolation( diff --git a/scripts/checks/openshell-policy-mutation-read.mts b/scripts/checks/openshell-policy-mutation-read.mts index 61296288d78..d0ac8b5513a 100644 --- a/scripts/checks/openshell-policy-mutation-read.mts +++ b/scripts/checks/openshell-policy-mutation-read.mts @@ -7,8 +7,8 @@ * * invalidState: a refactor introduces an unclassified policy read or changes a * mutation to consume provider-composed `--full` output. - * sourceBoundary: typed command builders own argv construction; this audit owns - * exhaustive discovery and classification of their production call sites. + * sourceBoundary: policy command builders and the OpenShell authority adapter + * own argv construction; this audit classifies their production read sites. * whyNotSourceFix: TypeScript cannot distinguish a command array after it * crosses the process runner, so this defense-in-depth check intentionally uses * deterministic AST classifications plus repository-wide read-site discovery. @@ -100,6 +100,7 @@ const NON_MUTATION_POLICY_READS: readonly AuditedPolicyReadFile[] = [ relativePath: "src/lib/adapters/openshell/policy-authority.ts", expectedReads: [ unclassifiedBase("captureSandboxBasePolicy"), + unclassifiedFull("inspectActiveGlobalPolicy"), unclassifiedFull("inspectSandboxPolicyAuthority"), ], }, @@ -118,16 +119,8 @@ const NON_MUTATION_POLICY_READS: readonly AuditedPolicyReadFile[] = [ relativePath: "src/lib/policy/commands.ts", expectedReads: [ unclassifiedFull("buildGlobalPolicyGetFullJsonArgs"), - { - site: "buildPolicyGetArgs", - view: "base", - failureHandling: "unclassified", - }, - { - site: "buildPolicyGetFullCommand", - view: "full", - failureHandling: "unclassified", - }, + unclassifiedBase("buildPolicyGetArgs"), + unclassifiedFull("buildPolicyGetFullCommand"), unclassifiedFull("buildPolicyGetFullJsonArgs"), ], }, @@ -140,6 +133,7 @@ export interface DiscoveredPolicyReadSite { } const POLICY_GET_BUILDERS = new Map([ + ["buildGlobalPolicyGetFullJsonArgs", "full"], ["buildPolicyGetCommand", "base"], ["buildPolicyGetArgs", "base"], ["buildPolicyGetFullCommand", "full"], diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 9aba963667b..d511e3097b2 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -35,11 +35,10 @@ import { SANDBOX_PROVIDER_SUFFIXES, } from "../../onboard/sandbox-provider-cleanup"; import { validateName } from "../../runner"; -import { killTimer as defaultKillShieldsTimer } from "../../shields/timer-control"; +import { cleanupShieldsDestroyArtifacts } from "../../shields/destroy-cleanup"; import { withMcpLifecycleLock } from "../../state/mcp-lifecycle-lock"; import * as onboardSession from "../../state/onboard-session"; import type { RetainedSandboxRecoveryRecord } from "../../state/onboard-session/retained-sandbox-recovery"; -import { resolveNemoclawStateDir } from "../../state/paths"; import * as registry from "../../state/registry"; import { assertSandboxDestroyCommandAvailable, @@ -175,22 +174,6 @@ export type CleanupSandboxServicesDeps = { googlechatWebhookTunnelPidDir?: (servicePidDir: string) => string; }; -type ShieldsTimerNeutralizeResult = { - warnings?: string[]; -}; - -type CleanupShieldsDestroyArtifactsDeps = { - killShieldsTimer?: (sandboxName: string) => ShieldsTimerNeutralizeResult | void; - rmSync?: typeof fs.rmSync; - stateDir?: string; - warn?: (message: string) => void; -}; - -type RemoveShieldsStateDeps = { - rmSync?: typeof fs.rmSync; - warn?: (message: string) => void; -}; - async function resolveCleanupGatewayDecision(options: DestroySandboxOptions): Promise { const decision = resolveDestroyGatewayCleanupDecision(options, { nonInteractive: isNonInteractiveEnv(), @@ -333,54 +316,6 @@ export function cleanupSandboxServices( } } -/** - * Remove host-side Shields state and recovery artifacts for a sandbox. - * - * Without this cleanup, stale state or an external policy handoff from a - * previous sandbox can survive destroy → re-onboard under the same name. - * - * See: https://github.com/NVIDIA/NemoClaw/issues/3114 - */ -export function removeShieldsState( - sandboxName: string, - stateDir = resolveNemoclawStateDir(), - deps: RemoveShieldsStateDeps = {}, -): void { - const rmSync = deps.rmSync ?? fs.rmSync; - const warn = deps.warn ?? ((message: string) => console.warn(` ${YW}⚠${R} ${message}`)); - const resolvedStateDir = path.resolve(stateDir); - const recoveryArtifactName = `shields-external-policy-${sandboxName}.yaml`; - const artifactNames = [ - recoveryArtifactName, - `shields-${sandboxName}.json`, - `shields-timer-${sandboxName}.json`, - ]; - for (const artifactName of artifactNames) { - const filePath = path.resolve(resolvedStateDir, artifactName); - if (!filePath.startsWith(`${resolvedStateDir}${path.sep}`)) { - // Defense-in-depth: sandbox names are validated to [a-z0-9-] at - // all entry points, but reject traversal attempts just in case. - continue; - } - try { - rmSync(filePath, { force: true }); - } catch (error) { - // force: true already suppresses ENOENT. A recovery handoff must not - // become unbound under a reusable sandbox name, so preserve Shields - // state and stop cleanup when that artifact cannot be removed. - if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; - const message = error instanceof Error ? error.message : String(error); - if (artifactName === recoveryArtifactName) { - throw new Error( - `Could not remove external Shields policy recovery artifact '${filePath}': ${message}. Shields state was preserved for retry.`, - { cause: error }, - ); - } - warn(`Failed to remove Shields cleanup artifact '${filePath}': ${message}`); - } - } -} - /** * Remove only a provider-owned per-sandbox workload image. Shared managed * cohorts and ambiguous ownership are never deleted. @@ -508,25 +443,6 @@ export async function revokeDestroyedSandboxHttpsPinRoute( } } -export function cleanupShieldsDestroyArtifacts( - sandboxName: string, - deps: CleanupShieldsDestroyArtifactsDeps = {}, -): void { - const killShieldsTimer = deps.killShieldsTimer ?? defaultKillShieldsTimer; - const stateDir = deps.stateDir ?? resolveNemoclawStateDir(); - const warn = deps.warn ?? defaultDestroyWarn; - - const timerResult = killShieldsTimer(sandboxName); - for (const warning of timerResult?.warnings ?? []) { - warn(warning); - } - - removeShieldsState(sandboxName, stateDir, { - rmSync: deps.rmSync ?? fs.rmSync, - warn, - }); -} - export type { WipeSandboxStateDeps }; // Re-export so existing callers (tests, downstream code) keep working after // the wipe was extracted out of the destroy monolith (#5455 PRA-2). @@ -713,7 +629,8 @@ async function destroySandboxUnlocked( let destructiveResult: Awaited>; try { destructiveResult = await executeSandboxDestroy({ - cleanupShieldsArtifacts: cleanupShieldsDestroyArtifacts, + cleanupShieldsArtifacts: (name) => + cleanupShieldsDestroyArtifacts(name, { warn: defaultDestroyWarn }), cliName: CLI_NAME, force: normalized.force === true, getSandbox: registry.getSandbox, 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 cedcf0fb240..55678cdf9bd 100644 --- a/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts +++ b/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts @@ -26,6 +26,7 @@ const captureOpenshellMock = vi.fn(() => ({ status: 0, output: "alpha Ready\nbeta Ready\nId: beta-runtime-id\n", })); +const parseLiveSandboxNamesMock = vi.fn(() => new Set(["alpha"])); const getSandboxMock = vi.fn((name?: string) => harness.entries.get(name ?? "") ?? null); const registerSandboxMock = vi.fn( ( @@ -57,6 +58,8 @@ const reserveSandboxInferenceRouteMock = vi.fn((name: string, route: Record(async () => ({ status: 7, output: "create failed before registry write", @@ -190,7 +193,7 @@ vi.mock("../../runner", () => ({ validateName: vi.fn((value: string) => value), })); vi.mock("../../runtime-recovery", () => ({ - parseLiveSandboxNames: vi.fn(() => new Set(["alpha"])), + parseLiveSandboxNames: parseLiveSandboxNamesMock, })); vi.mock("../../sandbox/create-stream", () => ({ streamSandboxCreate: streamSandboxCreateMock })); vi.mock("../../shields", () => ({ @@ -241,8 +244,11 @@ vi.mock("../../state/sandbox", () => ({ listBackups: vi.fn(() => []), restoreSandboxState: restoreSandboxStateMock, })); +vi.mock("../../shields/destroy-cleanup", () => ({ + cleanupShieldsDestroyArtifacts: cleanupShieldsDestroyArtifactsMock, +})); vi.mock("./destroy", () => ({ - cleanupShieldsDestroyArtifacts: vi.fn(), + cleanupSandboxServices: cleanupSandboxServicesMock, removeSandboxRegistryEntryOutcome: removeSandboxRegistryEntryOutcomeMock, requireSandboxDestructiveCleanupAuthority: vi.fn(() => ({ provider: runtimeProvider })), })); @@ -265,6 +271,8 @@ describe("snapshot restore auto-create failures", () => { vi.clearAllMocks(); harness.entries.clear(); harness.entries.set("alpha", sourceEntry()); + cleanupSandboxServicesMock.mockImplementation(() => undefined); + parseLiveSandboxNamesMock.mockReturnValue(new Set(["alpha"])); streamSandboxCreateMock.mockResolvedValue({ status: 7, output: "create failed before registry write", @@ -417,9 +425,54 @@ describe("snapshot restore auto-create failures", () => { const nimRuntime = await import("../../inference/nim"); expect(nimRuntime.stopNimContainer).not.toHaveBeenCalled(); expect(nimRuntime.stopNimContainerByName).not.toHaveBeenCalled(); + expect(cleanupSandboxServicesMock).toHaveBeenCalledWith("beta"); expect(removeSandboxRegistryEntryOutcomeMock).toHaveBeenCalledWith("beta"); + expect(cleanupSandboxServicesMock.mock.invocationCallOrder[0]).toBeLessThan( + cleanupShieldsDestroyArtifactsMock.mock.invocationCallOrder[0]!, + ); + expect(cleanupShieldsDestroyArtifactsMock.mock.invocationCallOrder[0]).toBeLessThan( + removeSandboxRegistryEntryOutcomeMock.mock.invocationCallOrder[0]!, + ); expect(getSandboxMock("beta")).toBeNull(); expect(consoleError.mock.calls.flat().join("\n")).toContain("injected live route failure"); expect(restoreSandboxStateMock).not.toHaveBeenCalled(); }); + + it("preserves cleanup state when the Google Chat tunnel cannot stop (#9833)", async () => { + const destination = { + name: "beta", + openshellDriver: "docker", + provider: "vllm-local", + model: "model-b", + endpointUrl: "https://inference.local/v1", + lifecycleGeneration: "beta-generation-1", + }; + harness.entries.set("beta", destination); + parseLiveSandboxNamesMock.mockReturnValue(new Set(["alpha", "beta"])); + cleanupSandboxServicesMock.mockImplementationOnce(() => { + throw new Error("Refusing to finish sandbox cleanup while its Google Chat tunnel remains"); + }); + vi.spyOn(console, "log").mockImplementation(() => {}); + const { getLatestBackup } = await import("../../state/sandbox"); + vi.mocked(getLatestBackup).mockReturnValue({ + timestamp: "2026-06-15T00:00:00.000Z", + backupPath: "/tmp/backup-alpha", + } as ReturnType); + const { runSandboxSnapshot } = await import("./snapshot"); + + await expect( + runSandboxSnapshot("alpha", { + kind: "restore", + to: "beta", + force: true, + yes: true, + }), + ).rejects.toThrow("Refusing to finish sandbox cleanup"); + + expect(cleanupSandboxServicesMock).toHaveBeenCalledWith("beta"); + expect(cleanupShieldsDestroyArtifactsMock).not.toHaveBeenCalled(); + expect(removeSandboxRegistryEntryOutcomeMock).not.toHaveBeenCalled(); + expect(harness.entries.get("beta")).toBe(destination); + expect(streamSandboxCreateMock).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts b/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts index cacf6e50622..aa7be19cc30 100644 --- a/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts +++ b/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts @@ -141,6 +141,7 @@ const lifecycleMock = vi.hoisted(() => { const events: string[] = []; return { events, + cleanupSandboxServicesMock: vi.fn(() => events.push("cleanup-services")), cleanupShieldsDestroyArtifactsMock: vi.fn(() => events.push("cleanup-shields")), readTimerMarkerMock: vi.fn(() => null as Record | null), withTimerBoundMock: vi.fn( @@ -353,12 +354,16 @@ vi.mock("../../state/sandbox", () => ({ restoreSandboxState: restoreSandboxStateMock, })); +vi.mock("../../shields/destroy-cleanup", () => ({ + cleanupShieldsDestroyArtifacts: lifecycleMock.cleanupShieldsDestroyArtifactsMock, +})); + vi.mock("./destroy", async () => { const runtimeProviders = await vi.importActual< typeof import("../../onboard/runtime-provider/access") >("../../onboard/runtime-provider/access"); return { - cleanupShieldsDestroyArtifacts: lifecycleMock.cleanupShieldsDestroyArtifactsMock, + cleanupSandboxServices: lifecycleMock.cleanupSandboxServicesMock, removeSandboxRegistryEntry: vi.fn(() => true), removeSandboxRegistryEntryOutcome: removeSandboxRegistryEntryOutcomeMock, requireSandboxDestructiveCleanupAuthority: (sandboxName: string, sandbox: SandboxRecord) => @@ -387,6 +392,9 @@ export function resetSnapshotRestoreMocks(): void { shieldsMock.isShieldsDownMock.mockReturnValue(true); shieldsMock.shieldsUpMock.mockImplementation(() => lifecycleMock.events.push("harden")); lifecycleMock.events.length = 0; + lifecycleMock.cleanupSandboxServicesMock + .mockReset() + .mockImplementation(() => lifecycleMock.events.push("cleanup-services")); lifecycleMock.readTimerMarkerMock.mockReturnValue(null); captureOpenshellMock.mockImplementation((args) => defaultOpenshellResponses(args)); dockerInspectMock.mockReturnValue({ status: 0, stdout: "true\n" }); diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index 241403f054e..aab83491093 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -27,7 +27,6 @@ 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 { findAvailableDashboardPort, getRegistryOccupiedDashboardPorts, @@ -52,6 +51,7 @@ import { ROOT, run, shellQuote, validateName } from "../../runner"; import { parseLiveSandboxNames } from "../../runtime-recovery"; import { streamSandboxCreate } from "../../sandbox/create-stream"; import * as shields from "../../shields"; +import { cleanupShieldsDestroyArtifacts } from "../../shields/destroy-cleanup"; import { withTimerBoundShieldsMutationLock } from "../../shields/timer-bound-lock"; import { readTimerMarker } from "../../shields/timer-control"; import { isSandboxReady } from "../../state/gateway"; @@ -67,7 +67,7 @@ import { parseDcodeProbeState, } from "./dcode-activity-probe"; import { - cleanupShieldsDestroyArtifacts, + cleanupSandboxServices, removeSandboxRegistryEntryOutcome, requireSandboxDestructiveCleanupAuthority, } from "./destroy"; @@ -654,16 +654,11 @@ async function autoCreateSandboxFromSource( // Delete an existing destination sandbox so `snapshot restore --to --force` // can recreate it from the source's image. Stops the destination's NIM // container, runs `openshell sandbox delete`, performs the destination-only -// cleanups that `sandboxDestroy` does (PID dir, per-sandbox messaging -// providers, shields state), then drops the NemoClaw registry entry. Throws -// SnapshotCommandError on failure so the caller does not proceed into a -// partially-deleted target. -// -// Host-shared cleanups that destroy.ts performs \u2014 Ollama auth proxy -// (`killStaleProxy`), host services (`cleanupSandboxServices` with -// `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. +// per-sandbox service, provider, and Shields cleanup that `sandboxDestroy` +// owns, then drops the NemoClaw registry entry. Shared host services and +// gateway teardown stay running because they can also serve the source sandbox +// we are about to clone from. Throws SnapshotCommandError on failure so the +// caller does not proceed into a partially-deleted target. function deleteSandboxForRestore(name: string): void { withTimerBoundShieldsMutationLock(name, "delete snapshot restore destination", () => { const sbMeta = registry.getSandbox(name); @@ -737,26 +732,7 @@ function deleteSandboxForRestore(name: string): void { snapshotExit(1); } } - // Destination-only cleanup so the recreated sandbox does not inherit stale - // host-side state or hit provider-name conflicts (Codex #3796 P2): - // - /tmp/nemoclaw-services-: PID dir for this sandbox's services - // - OpenShell per-sandbox messaging bridge providers declared by channel - // manifests. - // - shields-.json + shields timer: per-sandbox shields artifacts - try { - fs.rmSync(`/tmp/nemoclaw-services-${name}`, { - recursive: true, - force: true, - }); - } catch { - // PID dir may not exist \u2014 ignore. - } - for (const suffix of listMessagingProviderSuffixes()) { - runOpenshell(["provider", "delete", `${name}${suffix}`], { - ignoreError: true, - stdio: ["ignore", "ignore", "ignore"], - }); - } + cleanupSandboxServices(name); cleanupShieldsDestroyArtifacts(name); requireSnapshotDestinationRegistryRemoval(name, removeSandboxRegistryEntryOutcome(name)); }); diff --git a/src/lib/adapters/openshell/policy-authority.test.ts b/src/lib/adapters/openshell/policy-authority.test.ts index c11d5859119..fb5a5e7afce 100644 --- a/src/lib/adapters/openshell/policy-authority.test.ts +++ b/src/lib/adapters/openshell/policy-authority.test.ts @@ -7,17 +7,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import * as openshellRuntimeModule from "./runtime"; import { - assertExternalPolicyRequirements, assertOpenShellGatewayPortBinding, - assertRecordedPolicyAuthority, captureSandboxBasePolicy, inspectActiveGlobalPolicy, inspectOpenShellSandboxPolicyReadiness, inspectOpenShellSandboxIdentityFingerprint, inspectSandboxPolicyAuthority, - isExternalPolicyAuthorityRefusalError, policyAuthorityInternals, - type SandboxPolicyAuthorityInspection, } from "./policy-authority"; function captureResult( @@ -489,101 +485,3 @@ describe("OpenShell policy authority inspection", () => { expect(error.message).not.toContain("captured-stderr-secret"); }); }); - -describe("recorded policy authority", () => { - it("accepts unchanged authority and refuses missing or changed authority (#9833)", () => { - expect(() => - assertRecordedPolicyAuthority("externally-managed", "externally-managed", "rebuild"), - ).not.toThrow(); - expect(() => - assertRecordedPolicyAuthority(undefined, "externally-managed", "restore the snapshot"), - ).toThrow(/recorded policy authority is unavailable or invalid/); - expect(() => - assertRecordedPolicyAuthority( - "nemoclaw-managed", - "externally-managed", - "restore the snapshot", - ), - ).toThrow(/changed from nemoclaw-managed to externally-managed/); - expect(() => - assertRecordedPolicyAuthority("externally-managed", "unknown", "restore the snapshot"), - ).toThrow(/observed OpenShell policy authority is unavailable or invalid/); - }); - - it("classifies an observed external authority without parsing diagnostics (#9833)", () => { - const externalError = errorFrom(() => - assertRecordedPolicyAuthority( - "nemoclaw-managed", - "externally-managed", - "restore the snapshot", - ), - ); - const managedError = errorFrom(() => - assertRecordedPolicyAuthority( - "externally-managed", - "nemoclaw-managed", - "restore the snapshot", - ), - ); - - expect(isExternalPolicyAuthorityRefusalError(externalError)).toBe(true); - expect(isExternalPolicyAuthorityRefusalError(managedError)).toBe(false); - }); -}); - -describe("externally managed policy requirements", () => { - it("compares exact requirements and redacts missing or drifted contents (#9833)", () => { - const requiredPolicy = { - version: 1, - filesystem_policy: { read_only: ["/required-secret"] }, - process: { run_as_user: 1000 }, - network_policies: { - exact: { endpoints: [{ host: "api.test", port: 443 }], mode: "allow" }, - missing: { endpoints: [{ host: "missing-secret.test", port: 443 }] }, - drifted: { endpoints: [{ host: "required-secret.test", port: 443 }] }, - }, - }; - const inspection: SandboxPolicyAuthorityInspection = { - authority: "externally-managed", - policyIdentity: { hash: "policy-alpha", activeVersion: 7 }, - effectivePolicy: { - version: 9, - filesystem_policy: { read_only: ["/observed-secret"] }, - network_policies: { - exact: { mode: "allow", endpoints: [{ port: 443, host: "api.test" }] }, - drifted: { endpoints: [{ host: "observed-secret.test", port: 443 }] }, - }, - }, - }; - - const error = errorFrom(() => - assertExternalPolicyRequirements({ - inspection, - requiredPolicy, - operation: "enable messaging", - sandboxName: "alpha", - }), - ); - expect(error.message).toContain('missing sections "process"'); - expect(error.message).toContain('drifted sections "filesystem_policy"'); - expect(error.message).toContain('missing entries "missing"'); - expect(error.message).toContain('drifted entries "drifted"'); - expect(error.message).not.toMatch( - /required-secret|observed-secret|missing-secret\.test|observed-secret\.test/u, - ); - }); - - it("leaves NemoClaw-managed requirements to the mutation path (#9833)", () => { - expect(() => - assertExternalPolicyRequirements({ - inspection: { - authority: "nemoclaw-managed", - effectivePolicy: {}, - policyIdentity: { hash: "policy-alpha", activeVersion: 7 }, - }, - requiredPolicy: { network_policies: { required: { endpoints: ["api.test"] } } }, - operation: "apply a preset", - }), - ).not.toThrow(); - }); -}); diff --git a/src/lib/adapters/openshell/policy-authority.ts b/src/lib/adapters/openshell/policy-authority.ts index 99302e2974e..c87c5badd2d 100644 --- a/src/lib/adapters/openshell/policy-authority.ts +++ b/src/lib/adapters/openshell/policy-authority.ts @@ -8,22 +8,13 @@ import { NAME_MAX_LENGTH, } from "../../sandbox-name-contract"; import { - buildGlobalPolicyGetFullJsonArgs, - buildGlobalPolicyListArgs, - buildPolicyGetArgs, - buildPolicyGetFullJsonArgs, -} from "../../policy/commands"; -import { - assertExternalPolicyRequirementContainment, - assertMatchingPolicyAuthority, - assertPolicyRequirementContainment, classifyOpenShellGlobalPolicyHistory, parseActiveGlobalPolicyAuthorityMetadata, type ActiveGlobalPolicyInspection, type OpenShellPolicyAuthority, parseSandboxPolicyAuthorityMetadata, type SandboxPolicyAuthorityInspection as CanonicalSandboxPolicyAuthorityInspection, -} from "../../policy/merge"; +} from "../../../../nemoclaw/dist/shared/openshell-policy-boundary.cjs"; import * as openshellRuntime from "./runtime"; import { fingerprintOpenShellSandboxId, @@ -37,7 +28,7 @@ type JsonObject = Record; export type SandboxPolicyAuthority = OpenShellPolicyAuthority; export type SandboxPolicyAuthorityInspection = CanonicalSandboxPolicyAuthorityInspection; -export type { ActiveGlobalPolicyInspection } from "../../policy/merge"; +export type { ActiveGlobalPolicyInspection }; export type OpenShellSandboxPolicyReadiness = | { readonly state: "ready" } @@ -148,14 +139,6 @@ function captureAuthorityRead( runtimeSelection?: { readonly gatewayName?: string }, ): { readonly output: string; readonly stdout: string; readonly stderr: string } { const result = captureBoundedOpenShell(args, subject, runtimeSelection); - if ( - !isObject(result) || - typeof result.output !== "string" || - typeof result.stdout !== "string" || - typeof result.stderr !== "string" - ) { - failInspection(subject, "the policy query returned an invalid result"); - } const errorCode = (result.error as NodeJS.ErrnoException | undefined)?.code; if (errorCode === "ETIMEDOUT") { failInspection(subject, "the policy query timed out"); @@ -169,7 +152,7 @@ function captureAuthorityRead( if (result.status !== 0) { failInspection(subject, "the policy query did not complete successfully"); } - return { output: result.output, stdout: result.stdout, stderr: result.stderr }; + return { output: result.output, stdout: result.stdout ?? "", stderr: result.stderr ?? "" }; } function capturePolicyRead( @@ -191,7 +174,15 @@ export function inspectSandboxPolicyAuthority({ ? undefined : validatePolicyAuthorityName(gatewayName, "gateway name"); const raw = capturePolicyRead( - buildPolicyGetFullJsonArgs(validatedSandboxName, validatedGatewayName), + [ + "policy", + "get", + ...(validatedGatewayName ? ["-g", validatedGatewayName] : []), + "--full", + "--output", + "json", + validatedSandboxName, + ], "sandbox", { gatewayName: validatedGatewayName }, ); @@ -256,16 +247,33 @@ export function inspectActiveGlobalPolicy({ gatewayName === undefined ? undefined : validatePolicyAuthorityName(gatewayName, "gateway name"); - const history = captureAuthorityRead(buildGlobalPolicyListArgs(validatedGatewayName), "global", { - gatewayName: validatedGatewayName, - }); + const history = captureAuthorityRead( + [ + "policy", + "list", + ...(validatedGatewayName ? ["-g", validatedGatewayName] : []), + "--global", + "--limit", + "1", + ], + "global", + { gatewayName: validatedGatewayName }, + ); const historyState = classifyOpenShellGlobalPolicyHistory(history.stdout, history.stderr); if (historyState === "absent") return { state: "absent" }; if (historyState === "invalid") { failInspection("global", "OpenShell returned invalid global policy history"); } const raw = captureAuthorityRead( - buildGlobalPolicyGetFullJsonArgs(validatedGatewayName), + [ + "policy", + "get", + ...(validatedGatewayName ? ["-g", validatedGatewayName] : []), + "--global", + "--full", + "--output", + "json", + ], "global", { gatewayName: validatedGatewayName }, ).stdout; @@ -281,12 +289,10 @@ export function inspectActiveGlobalPolicy({ /** Read one sandbox base policy through the same bounded OpenShell adapter. */ export function captureSandboxBasePolicy(sandboxName: string, gatewayName: string): string { + const validatedSandboxName = validatePolicyAuthorityName(sandboxName, "sandbox name"); const validatedGatewayName = validatePolicyAuthorityName(gatewayName, "gateway name"); return capturePolicyRead( - buildPolicyGetArgs( - validatePolicyAuthorityName(sandboxName, "sandbox name"), - validatedGatewayName, - ), + ["policy", "get", "-g", validatedGatewayName, "--base", validatedSandboxName], "sandbox", { gatewayName: validatedGatewayName }, ); @@ -348,80 +354,6 @@ export function assertOpenShellGatewayPortBinding(options: { } } -function operationLabel(operation: string): string { - return typeof operation === "string" && operation.trim().length > 0 - ? operation.trim() - : "continue the policy-dependent operation"; -} - -/** Refuse a lifecycle operation when its durable and observed authority disagree. */ -export function assertRecordedPolicyAuthority( - recorded: unknown, - observed: unknown, - operation: string, -): void { - const label = operationLabel(operation); - try { - assertMatchingPolicyAuthority(recorded, observed); - } catch (error) { - const detail = error instanceof Error ? error.message : "policy authority is invalid"; - const observedAuthority = - observed === "nemoclaw-managed" || observed === "externally-managed" ? observed : undefined; - throw new PolicyAuthorityRefusalError(`Refusing to ${label}: ${detail}.`, observedAuthority); - } -} - -/** - * Verify that an externally supplied policy contains each required entry and - * section without claiming ownership. Unrelated external entries are allowed. - */ -export function assertExternalPolicyRequirements({ - inspection, - requiredPolicy, - operation, - sandboxName, -}: { - readonly inspection: SandboxPolicyAuthorityInspection; - readonly requiredPolicy: JsonObject; - readonly operation: string; - readonly sandboxName?: string; -}): void { - const label = operationLabel(operation); - const target = sandboxName ? ` for sandbox ${JSON.stringify(sandboxName)}` : ""; - try { - assertExternalPolicyRequirementContainment(inspection, requiredPolicy); - } catch (error) { - const detail = error instanceof Error ? error.message : "the policy requirement is invalid"; - throw new PolicyAuthorityRefusalError( - `Refusing to ${label}${target}: ${detail}. Ask the external policy authority to supply the exact required entries.`, - ); - } -} - -/** Verify required entries without assigning ownership to a sandbox-scoped policy. */ -export function assertObservedPolicyRequirements({ - inspection, - requiredPolicy, - operation, - sandboxName, -}: { - readonly inspection: SandboxPolicyAuthorityInspection; - readonly requiredPolicy: JsonObject; - readonly operation: string; - readonly sandboxName?: string; -}): void { - const label = operationLabel(operation); - const target = sandboxName ? ` for sandbox ${JSON.stringify(sandboxName)}` : ""; - try { - assertPolicyRequirementContainment(inspection, requiredPolicy); - } catch (error) { - const detail = error instanceof Error ? error.message : "the policy requirement is invalid"; - throw new PolicyAuthorityRefusalError( - `Refusing to ${label}${target}: ${detail}. The verified policy must supply the exact required entries.`, - ); - } -} - export const policyAuthorityInternals = { captureMaxBytes: POLICY_AUTHORITY_CAPTURE_MAX_BYTES, captureTimeoutMs: POLICY_AUTHORITY_CAPTURE_TIMEOUT_MS, diff --git a/src/lib/adapters/openshell/runtime.test.ts b/src/lib/adapters/openshell/runtime.test.ts index ad40ae62628..33132abf5c8 100644 --- a/src/lib/adapters/openshell/runtime.test.ts +++ b/src/lib/adapters/openshell/runtime.test.ts @@ -41,6 +41,7 @@ function largeOutputExecutable(name: string): string { } afterEach(() => { + vi.restoreAllMocks(); vi.unstubAllEnvs(); for (const directory of directories.splice(0)) { fs.rmSync(directory, { recursive: true, force: true }); @@ -93,4 +94,24 @@ describe("captureResolvedOpenshell", () => { expect(result.status).toBe(0); expect(result.output).toBe("snapshot"); }); + + it("keeps ignored spawn failures nonfatal and redacted (#9833)", () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openshell-runtime-test-")); + directories.push(directory); + const unavailable = path.join(directory, "openshell"); + fs.writeFileSync(unavailable, "not executable", { mode: 0o600 }); + const exit = vi.spyOn(process, "exit").mockImplementation((code) => { + throw new Error(`unexpected exit ${String(code)}`); + }); + const errorLine = vi.spyOn(console, "error").mockImplementation(() => undefined); + + expect(() => + captureResolvedOpenshell([], { + ignoreError: true, + openshellBinary: unavailable, + }), + ).toThrow("OpenShell capture could not run"); + expect(exit).not.toHaveBeenCalled(); + expect(errorLine).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/adapters/openshell/runtime.ts b/src/lib/adapters/openshell/runtime.ts index c24e656996b..f9ede2cfbf1 100644 --- a/src/lib/adapters/openshell/runtime.ts +++ b/src/lib/adapters/openshell/runtime.ts @@ -19,7 +19,6 @@ type CommandArgs = string[]; export { buildOpenShellSubprocessEnv, OPENSHELL_OPERATION_TIMEOUT_MS }; export { classifyManagedGatewayEndpointBinding } from "./client"; -export { runCaptureEx } from "../../runner"; type RunnerOptions = { /** Exact canonical executable selected by the caller. */ @@ -96,6 +95,7 @@ export function captureResolvedOpenshell(args: CommandArgs, opts: RunnerOptions const openshell = opts.openshellBinary ?? resolveOpenshellBinaryOrNull(); if (!openshell) throw new Error("OpenShell is unavailable"); if (!path.isAbsolute(openshell)) throw new Error("OpenShell executable must be absolute"); + const keepCaptureNonfatal = opts.ignoreError === true; return captureOpenshellCommand(openshell, args, { cwd: ROOT, env: opts.env, @@ -107,8 +107,12 @@ export function captureResolvedOpenshell(args: CommandArgs, opts: RunnerOptions killSignal: opts.killSignal, killProcessTreeOnTimeout: opts.killProcessTreeOnTimeout, maxBuffer: opts.maxBuffer, - errorLine: console.error, - exit: (code: number) => process.exit(code), + errorLine: keepCaptureNonfatal ? () => undefined : console.error, + exit: keepCaptureNonfatal + ? () => { + throw new Error("OpenShell capture could not run"); + } + : (code: number) => process.exit(code), }); } diff --git a/src/lib/onboard/created-sandbox-failure.test.ts b/src/lib/onboard/created-sandbox-failure.test.ts index 69fe3edc5d2..3b289f0f7c0 100644 --- a/src/lib/onboard/created-sandbox-failure.test.ts +++ b/src/lib/onboard/created-sandbox-failure.test.ts @@ -1,9 +1,11 @@ // 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 { afterEach, describe, expect, it, vi } from "vitest"; import { + formatRetainedApfSandboxRecoveryReceipt, + persistAndReportRetainedApfSandboxRecovery, reportSandboxCreateFailure, reportSandboxReadinessFailure, type SandboxCreateFailureReportDeps, @@ -11,8 +13,80 @@ import { type SandboxReadinessFailureReportDeps, type SandboxReadinessFailureReportOptions, } from "./created-sandbox-failure"; +import { printOnboardResumeHint, resetOnboardResumeHintForTests } from "./resume-hint"; import type { CreatedSandboxReadinessResult } from "./sandbox-readiness-tracing"; +afterEach(resetOnboardResumeHintForTests); + +describe("retained APF sandbox recovery", () => { + const createAttemptNonce = "a".repeat(62); + + it.each([ + ["identifiable", "b".repeat(64)], + ["label-only", null], + ])( + "persists bounded exact %s evidence and suppresses generic resume", + (_caseName, fingerprint) => { + const logs: string[] = []; + const persist = vi.fn(() => true); + + persistAndReportRetainedApfSandboxRecovery({ + sandboxName: "alpha", + gatewayName: "nemoclaw", + failureDescription: "sandbox creation failed", + evidence: { createAttemptNonce, liveIdentityFingerprint: fingerprint }, + persist, + log: (message) => logs.push(message), + }); + + const receipt = formatRetainedApfSandboxRecoveryReceipt({ + createAttemptNonce, + liveIdentityFingerprint: fingerprint, + }); + expect(receipt.length).toBeLessThanOrEqual(240); + expect(persist).toHaveBeenCalledExactlyOnceWith({ + sandboxName: "alpha", + gatewayName: "nemoclaw", + createAttemptNonce, + liveIdentityFingerprint: fingerprint, + message: receipt, + }); + expect(logs.join("\n")).toContain("onboard --fresh --apf-interceptor --name "); + expect(logs.join("\n")).not.toContain("onboard --resume"); + const genericRecovery: string[] = []; + printOnboardResumeHint(false, (line) => genericRecovery.push(line)); + expect(genericRecovery).toEqual([]); + }, + ); + + it.each([ + ["returns false", () => false], + [ + "throws", + () => { + throw new Error("injected persistence failure"); + }, + ], + ])("reports blocked recovery when persistence %s", (_caseName, persist) => { + const logs: string[] = []; + + expect(() => + persistAndReportRetainedApfSandboxRecovery({ + sandboxName: "alpha", + gatewayName: "nemoclaw", + failureDescription: "sandbox creation failed", + evidence: { createAttemptNonce, liveIdentityFingerprint: null }, + persist, + log: (message) => logs.push(message), + }), + ).not.toThrow(); + + expect(logs.join("\n")).toContain( + "APF recovery is blocked because NemoClaw could not save this create-attempt evidence", + ); + }); +}); + class ExitSignal extends Error { constructor(readonly code: number) { super(`exit:${code}`); diff --git a/src/lib/onboard/created-sandbox-failure.ts b/src/lib/onboard/created-sandbox-failure.ts index 820c4fddbdd..42288a100aa 100644 --- a/src/lib/onboard/created-sandbox-failure.ts +++ b/src/lib/onboard/created-sandbox-failure.ts @@ -1,9 +1,77 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { NEMOCLAW_CREATE_ATTEMPT_LABEL } from "../adapters/openshell/sandbox-identity"; import { redact } from "../security/redact"; +import { noteOnboardResumeHintShown, onboardFreshRecoveryCommand } from "./resume-hint"; import type { CreatedSandboxReadinessResult } from "./sandbox-readiness-tracing"; +export interface RetainedApfSandboxRecoveryEvidence { + readonly createAttemptNonce: string; + readonly liveIdentityFingerprint: string | null; +} + +export interface RetainedApfSandboxRecovery extends RetainedApfSandboxRecoveryEvidence { + readonly sandboxName: string; + readonly gatewayName: string; + /** Compact, secret-free evidence that must survive session normalization unchanged. */ + readonly message: string; +} + +/** Format exact APF recovery authority within the persisted failure-message bound. */ +export function formatRetainedApfSandboxRecoveryReceipt( + evidence: RetainedApfSandboxRecoveryEvidence, +): string { + return ( + `APF retained sandbox: ${NEMOCLAW_CREATE_ATTEMPT_LABEL}=${evidence.createAttemptNonce}; ` + + `live-identity-sha256=${evidence.liveIdentityFingerprint ?? "unresolved"}` + ); +} + +/** Persist APF recovery authority before reporting identity-bound operator guidance. */ +export function persistAndReportRetainedApfSandboxRecovery(input: { + readonly sandboxName: string; + readonly gatewayName: string; + readonly failureDescription: string; + readonly evidence: RetainedApfSandboxRecoveryEvidence; + readonly persist: (recovery: RetainedApfSandboxRecovery) => boolean; + readonly log?: (message: string) => void; +}): void { + const log = input.log ?? ((message: string) => console.error(message)); + const identity = input.evidence.liveIdentityFingerprint + ? `Durable sandbox identity fingerprint: ${input.evidence.liveIdentityFingerprint}. Use it only to compare the surviving sandbox with this create attempt.` + : "OpenShell did not return one exact durable sandbox identity for this create attempt. Recovery is blocked until an OpenShell administrator resolves the create-attempt label to one sandbox."; + const guidance = + `APF sandbox '${input.sandboxName}' may have been retained after ${input.failureDescription}. ` + + `${identity} Create-attempt label: ${NEMOCLAW_CREATE_ATTEMPT_LABEL}=${input.evidence.createAttemptNonce}. ` + + "Do not delete a sandbox by mutable name; use an identity-bound administrator recovery procedure."; + const recovery: RetainedApfSandboxRecovery = { + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + createAttemptNonce: input.evidence.createAttemptNonce, + liveIdentityFingerprint: input.evidence.liveIdentityFingerprint, + message: formatRetainedApfSandboxRecoveryReceipt(input.evidence), + }; + + noteOnboardResumeHintShown(); + let persisted = false; + try { + persisted = input.persist(recovery); + } catch { + persisted = false; + } + log(` ${guidance}`); + if (!persisted) { + log( + " APF recovery is blocked because NemoClaw could not save this create-attempt evidence. Preserve the terminal output for an OpenShell administrator.", + ); + } + log( + " After an OpenShell administrator confirms identity-bound cleanup, start a new APF attempt:", + ); + log(` ${onboardFreshRecoveryCommand(false)} --apf-interceptor --name `); +} + export type SandboxCreateFailureReportOptions = { sandboxName: string; /** Non-zero exit status from the create stream. */ diff --git a/src/lib/onboard/docker-gpu-sandbox-create-lifecycle.test.ts b/src/lib/onboard/docker-gpu-sandbox-create-lifecycle.test.ts index fde42865d83..16793ba8e60 100644 --- a/src/lib/onboard/docker-gpu-sandbox-create-lifecycle.test.ts +++ b/src/lib/onboard/docker-gpu-sandbox-create-lifecycle.test.ts @@ -441,20 +441,23 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { expect(onPatchFailureExit).not.toHaveBeenCalled(); }); - it("records patchError when recreate throws and exitOnPatchError reports it via printDockerGpuPatchFailureAndExit", async () => { + it("invokes retained-sandbox recovery once before reporting a deferred patch failure (#9833)", async () => { + const events: string[] = []; const deps = makeDeps(); const recreatePatch = vi.fn(() => { throw new Error("docker rename failed"); }); const waitForSupervisor = vi.fn(); const finalizeBackup = vi.fn(); - const onPatchFailureExit = vi.fn(); + const beforeFailureExit = vi.fn(() => events.push("before-failure-exit")); + const onPatchFailureExit = vi.fn(() => events.push("failure-exit")); const findContainerIds = vi.fn(() => ["existing-container"]); const patch = createDockerGpuSandboxCreatePatch({ route: "compatibility", sandboxName: "alpha", timeoutSecs: 60, + beforeFailureExit, deps, overrides: { findContainerIds, @@ -468,7 +471,9 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { patch.maybeApplyDuringCreate(); expect(patch.createFailureMessage()).toMatch(/Docker GPU patch failed/); await patch.exitOnPatchError(); + expect(beforeFailureExit).toHaveBeenCalledOnce(); expect(onPatchFailureExit).toHaveBeenCalledTimes(1); + expect(events).toEqual(["before-failure-exit", "failure-exit"]); // Supervisor wait must be skipped because needsSupervisorWait stayed false. patch.waitForSupervisorReconnectIfNeeded(); expect(waitForSupervisor).not.toHaveBeenCalled(); diff --git a/src/lib/onboard/docker-gpu-sandbox-create.ts b/src/lib/onboard/docker-gpu-sandbox-create.ts index 67e2f0ea893..18c376ea99f 100644 --- a/src/lib/onboard/docker-gpu-sandbox-create.ts +++ b/src/lib/onboard/docker-gpu-sandbox-create.ts @@ -87,6 +87,8 @@ type DockerGpuSandboxCreatePatchOptions = { requiredUlimits?: Parameters[0]["requiredUlimits"]; timeoutSecs: number; backend?: DockerGpuPatchBackend; + /** Persist caller-owned recovery evidence immediately before a terminal failure report. */ + beforeFailureExit?: () => void; /** * Whether the host is Docker Desktop WSL. Defaults to the cached * `isDockerDesktopWslRuntime()` probe. When true, the GPU patch skips the CDI @@ -177,8 +179,12 @@ export function createDockerGpuSandboxCreatePatch( const finalizeBackup = options.overrides?.finalizeBackup ?? finalizeDockerGpuPatchBackup; const captureFailedClone = options.overrides?.capturePreRollbackDiagnostics ?? captureDockerGpuPreRollbackDiagnostics; - const onPatchFailureExit = + const reportPatchFailureAndExit = options.overrides?.onPatchFailureExit ?? printDockerGpuPatchFailureAndExit; + const onPatchFailureExit: PatchFailureExitFn = (sandboxName, error, deps) => { + options.beforeFailureExit?.(); + reportPatchFailureAndExit(sandboxName, error, deps); + }; const failureDiagnosticDeps = { runCaptureOpenshell: options.deps.runCaptureOpenshell, dockerCapture: options.deps.dockerCapture, diff --git a/src/lib/onboard/machine/handlers/policies.ts b/src/lib/onboard/machine/handlers/policies.ts index 1fcb49cdffd..2836c4b364f 100644 --- a/src/lib/onboard/machine/handlers/policies.ts +++ b/src/lib/onboard/machine/handlers/policies.ts @@ -6,7 +6,7 @@ import { assertRecordedPolicyAuthority, PolicyAuthorityRefusalError, type SandboxPolicyAuthority, -} from "../../../adapters/openshell/policy-authority"; +} from "../../../policy/policy-authority"; import type { Session, SessionUpdates } from "../../../state/onboard-session"; import { normalizeAgentNameForResumeState } from "../../agent-resume-state"; import { diff --git a/src/lib/onboard/managed-bootstrap/docker-runtime.test.ts b/src/lib/onboard/managed-bootstrap/docker-runtime.test.ts index 319dbef2bb5..2f75ce34aaa 100644 --- a/src/lib/onboard/managed-bootstrap/docker-runtime.test.ts +++ b/src/lib/onboard/managed-bootstrap/docker-runtime.test.ts @@ -590,7 +590,8 @@ describe("Docker managed-bootstrap lifecycle composition", () => { } }); - it("does not finalize rollback after a claimed commit loses acknowledgement", async () => { + it("persists recovery before a managed commit loses acknowledgement (#9833)", async () => { + const events: string[] = []; const stateRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-docker-runtime-")); const seed = authority("openclaw"); const prepared = Object.freeze({}) as ManagedBootstrapPreparedTransaction; @@ -607,7 +608,9 @@ describe("Docker managed-bootstrap lifecycle composition", () => { }); adapterMocks.activate.mockResolvedValue(activated); adapterMocks.finalize.mockRejectedValue(new Error("commit acknowledgement lost")); + const beforeFailureExit = vi.fn(() => events.push("before-failure-exit")); const onPatchFailure = vi.fn((error: unknown): never => { + events.push("failure-exit"); throw error; }); const lifecycle = createDockerManagedBootstrapSurface().createLifecycle({ @@ -637,6 +640,7 @@ describe("Docker managed-bootstrap lifecycle composition", () => { }, requiredLimits: [], timeoutSecs: 30, + beforeFailureExit, dockerClientEnv: {}, onPatchFailure, network: { @@ -664,7 +668,9 @@ describe("Docker managed-bootstrap lifecycle composition", () => { expect.anything(), expect.objectContaining({ outcome: "commit", transaction: activated }), ); + expect(beforeFailureExit).toHaveBeenCalledOnce(); expect(onPatchFailure).toHaveBeenCalledOnce(); + expect(events).toEqual(["before-failure-exit", "failure-exit"]); await expect(lifecycle.recoverUnfinished()).resolves.toEqual({ receipts: [], failures: [] }); fs.rmSync(stateRoot, { recursive: true, force: true }); }); diff --git a/src/lib/onboard/managed-bootstrap/docker-runtime.ts b/src/lib/onboard/managed-bootstrap/docker-runtime.ts index 61c6433f93d..e87f0fc8c8d 100644 --- a/src/lib/onboard/managed-bootstrap/docker-runtime.ts +++ b/src/lib/onboard/managed-bootstrap/docker-runtime.ts @@ -224,6 +224,7 @@ function createDockerLifecycle( timeoutSecs: input.timeoutSecs, backend, dockerDesktopWsl, + beforeFailureExit: input.beforeFailureExit, deps: input.dependencies, ...(input.onPatchFailure ? { diff --git a/src/lib/onboard/managed-bootstrap/runtime-create.ts b/src/lib/onboard/managed-bootstrap/runtime-create.ts index 94059ff97da..6a189e9fb99 100644 --- a/src/lib/onboard/managed-bootstrap/runtime-create.ts +++ b/src/lib/onboard/managed-bootstrap/runtime-create.ts @@ -102,6 +102,8 @@ export interface ManagedBootstrapRuntimeCreateLifecycleInput { readonly sandboxGpuConfig: SandboxGpuConfig; readonly requiredLimits: readonly ManagedBootstrapRuntimeLimit[]; readonly timeoutSecs: number; +/** Persist caller-owned recovery evidence before canonical patch termination. */ + readonly beforeFailureExit?: () => void; /** Docker client authority used by the owning managed sandbox create. */ readonly dockerClientEnv: NodeJS.ProcessEnv; readonly onPatchFailure?: (error: unknown) => never; diff --git a/src/lib/onboard/policy-authority/preflight.ts b/src/lib/onboard/policy-authority/preflight.ts index 48bcac367e4..6a95551ec4f 100644 --- a/src/lib/onboard/policy-authority/preflight.ts +++ b/src/lib/onboard/policy-authority/preflight.ts @@ -17,7 +17,7 @@ import { PolicyAuthorityRefusalError, type SandboxPolicyAuthority, type SandboxPolicyAuthorityInspection, -} from "../../adapters/openshell/policy-authority"; +} from "../../policy/policy-authority"; import { assertNemoClawPolicyCreationReceiptMatches, parseOpenShellPolicy, diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index 1cffc904a7c..827fa347dc7 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -9,7 +9,7 @@ import { assertRecordedPolicyAuthority, isPolicyAuthorityRefusalError, PolicyAuthorityRefusalError, -} from "../../adapters/openshell/policy-authority"; +} from "../../policy/policy-authority"; import type { SandboxPolicyAuthority } from "../../adapters/openshell/policy-authority"; import { HERMES_PORTABLE_OPENSHELL_VERSION } from "../../adapters/openshell/resolve-shared"; import { NEMOCLAW_CREATE_ATTEMPT_LABEL } from "../../adapters/openshell/sandbox-identity"; @@ -28,10 +28,6 @@ import * as policyAuthorityPreflight from "../policy-authority/preflight"; import type { PreparedSandboxBuildContext } from "../build-context-stage"; import type { DcodeSelectionDriftReader } from "../dcode-selection-drift"; import { assertProviderlessInterceptorEnvironment } from "../entry-options"; -import type { - ManagedHermesStateVolumeCleanupResult, - ManagedHermesStateVolumeContext, -} from "../managed-workload/hermes-state-volume"; import type { OwnedSandboxRecreateRuntime } from "../onboard-recreate-journal"; import type { SandboxGpuConfig } from "../sandbox-gpu-mode"; import { cliName } from "../branding"; @@ -121,8 +117,8 @@ export function persistRetainedSandboxRecoveryMessage( markRetainedSandboxRecovery: ( sandboxName: string, message: string, - sandboxIdentityFingerprint: string | undefined, - context: RetainedSandboxRecoveryContext, + sandboxIdentityFingerprint?: string, + context?: RetainedSandboxRecoveryContext, ) => unknown | null, ): boolean { return Boolean( @@ -212,8 +208,8 @@ export function persistPostCreateRecovery(input: { readonly markRetainedSandboxRecovery: ( sandboxName: string, message: string, - sandboxIdentityFingerprint: string | undefined, - context: RetainedSandboxRecoveryContext, + sandboxIdentityFingerprint?: string, + context?: RetainedSandboxRecoveryContext, ) => unknown | null; }): void { const message = @@ -375,11 +371,8 @@ function assertProviderlessApfCreateInput(input: { if (input.createIntent?.apfInterceptorRequested !== true) return; const resolved = input.createIntent.resolved; const requestedAgent = input.agent?.name.trim().toLowerCase() ?? "openclaw"; - const resolvedAgent = resolved?.policy.options.agentName?.trim().toLowerCase() || null; const hasProviderIntent = requestedAgent !== "openclaw" || - (resolvedAgent !== null && - (resolvedAgent !== "openclaw" || resolvedAgent !== requestedAgent)) || input.webSearchConfig !== null || input.createIntent.reuseRegisteredCredentials === true || [ @@ -424,66 +417,6 @@ type SandboxRecreateReasonInput = { existingSandboxState: string; }; -type RecreatedSourceHermesStateVolumeCleanupInput = { - readonly sandboxName: string; - readonly sourceEntry: SandboxEntry | null; - readonly targetKeepsManagedHermesStateVolume: boolean; -}; - -type RecreatedSourceHermesStateVolumeCleanupDeps = { - readonly normalizeRuntimeProviderIdentity: (driverName: string | null | undefined) => string; - readonly removeManagedHermesStateVolume: ( - context: ManagedHermesStateVolumeContext, - ) => ManagedHermesStateVolumeCleanupResult; - readonly note: (message: string) => void; - readonly warn: (message: string) => void; - readonly redact: (message: string) => string; -}; - -type RecreatedSourceHermesStateVolumeFinalizationInput = - RecreatedSourceHermesStateVolumeCleanupInput & { - readonly sourceConfirmedAbsent: boolean; - }; - -type RecreatedSourceHermesStateVolumeFinalizationDeps = - RecreatedSourceHermesStateVolumeCleanupDeps & { - readonly removeSourceRegistryEntry: (entry: SandboxEntry, sandboxName: string) => void; - }; - -export function cleanupRecreatedSourceHermesStateVolume( - input: RecreatedSourceHermesStateVolumeCleanupInput, - deps: RecreatedSourceHermesStateVolumeCleanupDeps, -): void { - if (!input.sourceEntry || input.targetKeepsManagedHermesStateVolume) return; - - const cleanup = deps.removeManagedHermesStateVolume({ - agentName: input.sourceEntry.agent, - runtimeProviderId: deps.normalizeRuntimeProviderIdentity(input.sourceEntry.openshellDriver), - sandboxName: input.sandboxName, - workloadKind: input.sourceEntry.workload?.kind ?? "", - }); - if (cleanup.status === "failed") { - throw new Error( - `OpenShell confirmed that sandbox '${input.sandboxName}' is absent, but Docker could not remove its managed Hermes state volume '${cleanup.volumeName}': ${deps.redact(cleanup.detail)}. NemoClaw preserved the sandbox registry entry so a subsequent recreation can retry the volume removal.`, - ); - } - if (cleanup.status === "not-owned") { - deps.warn(` Left Docker volume '${cleanup.volumeName}' untouched because ${cleanup.detail}.`); - } else if (cleanup.status === "removed") { - deps.note(` Removed managed Hermes state volume for '${input.sandboxName}'.`); - } -} - -export function finalizeRecreatedSourceHermesStateVolume( - input: RecreatedSourceHermesStateVolumeFinalizationInput, - deps: RecreatedSourceHermesStateVolumeFinalizationDeps, -): void { - if (!input.sourceConfirmedAbsent || !input.sourceEntry) return; - - cleanupRecreatedSourceHermesStateVolume(input, deps); - deps.removeSourceRegistryEntry(input.sourceEntry, input.sandboxName); -} - export function readManagedDcodeCreateSelectionDrift( input: { sandboxName: string; @@ -608,7 +541,10 @@ export function reconcileCreatedHermesCredentialEnvironment( deps.revalidatePolicyAuthority( `reconciling Hermes messaging credentials for sandbox '${input.sandboxName}'`, ); - const reconciliation = deps.reconcileCredentialEnv(input.plan, deps.revalidatePolicyAuthority); + const reconciliation = deps.reconcileCredentialEnv( + input.plan, + deps.revalidatePolicyAuthority, + ); deps.revalidatePolicyAuthority( `confirming Hermes messaging credential reconciliation for sandbox '${input.sandboxName}'`, ); @@ -706,8 +642,8 @@ export async function runSandboxCreateWithPolicyAuthorityChecks< recoveryAttempted = true; const validationDetail = validationError instanceof Error && isPolicyAuthorityRefusalError(validationError) - ? validationError.message - : null; + ? validationError.message + : null; const identityGuidance = exactIdentity ? `Durable sandbox identity fingerprint: ${exactIdentity}. Use it only to compare the surviving sandbox with the failed create.` : "OpenShell did not return a durable sandbox identity fingerprint for comparison."; @@ -1015,46 +951,6 @@ export function createProviderEffectBoundary(input: { }; } -type SandboxProviderCleanupAuthority = - | { - readonly revalidateSandboxIdentity: (operation: string) => void; - } - | { - readonly observeSandbox: () => ReturnType< - SandboxCreateOrchestrationRuntime["getSandboxRecreateObservation"] - >; - readonly revalidatePolicyAuthority: (operation: string) => void; - }; - -export function runAuthorityBoundProviderCleanup( - input: { - readonly sandboxName: string; - readonly runProviderPreDeleteCleanup: SandboxCreateOrchestrationRuntime["runSandboxProviderPreDeleteCleanup"]; - readonly runOpenshell: SandboxCreateOrchestrationRuntime["runOpenshell"]; - readonly redact: SandboxCreateOrchestrationRuntime["redact"]; - readonly tolerateMissingSandbox?: boolean; - } & SandboxProviderCleanupAuthority, -): void { - const revalidateSandboxIdentity = - "observeSandbox" in input - ? (operation: string): void => { - if (input.observeSandbox().state !== "missing") { - throw new Error( - `Cannot clean up providers for sandbox '${input.sandboxName}': a sandbox with that name appeared after absence was verified while ${operation}.`, - ); - } - input.revalidatePolicyAuthority(operation); - } - : input.revalidateSandboxIdentity; - revalidateSandboxIdentity(`cleaning up providers for sandbox '${input.sandboxName}'`); - input.runProviderPreDeleteCleanup(input.sandboxName, { - runOpenshell: input.runOpenshell, - redact: input.redact, - ...(input.tolerateMissingSandbox ? { tolerateMissingSandbox: true } : {}), - revalidateSandboxIdentity, - }); -} - export function readSandboxRecreateRegistryEntry(input: { readonly sandboxName: string; readonly recreateTransaction: boolean; @@ -1528,27 +1424,6 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche sandboxName, workloadKind: workload.source.kind, }); - const finalizeRecreatedSourceHermesVolume = ( - sourceConfirmedAbsent: boolean, - sourceEntry: SandboxEntry | null, - targetKeepsManagedHermesStateVolume: boolean, - ) => - finalizeRecreatedSourceHermesStateVolume( - { - sandboxName, - sourceConfirmedAbsent, - sourceEntry, - targetKeepsManagedHermesStateVolume, - }, - { - normalizeRuntimeProviderIdentity: managedWorkloadOnboard.normalizeRuntimeProviderIdentity, - removeManagedHermesStateVolume: managedWorkloadOnboard.removeManagedHermesStateVolume, - removeSourceRegistryEntry: sandboxLifecycle.removeSandboxUnlessSessionReservation, - note, - warn: (message) => console.warn(message), - redact, - }, - ); await validatePortableManagedWorkloadSelection({ portableLifecycle: agentCreateInput.portableLifecycle, selectionNeedsValidation: tempManagedRuntime || managedWorkloadRebuild !== null, @@ -2049,13 +1924,8 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche revalidatePolicyAuthority(true, `recreating sandbox '${sandboxName}'`); if (recreateRuntime.beginDelete() === "source") { - runAuthorityBoundProviderCleanup({ - sandboxName, - revalidateSandboxIdentity: (operation) => revalidatePolicyAuthority(true, operation), - runProviderPreDeleteCleanup: runSandboxProviderPreDeleteCleanup, - runOpenshell, - redact, - }); + revalidatePolicyAuthority(true, `cleaning up providers for sandbox '${sandboxName}'`); + runSandboxProviderPreDeleteCleanup(sandboxName, { runOpenshell, redact }); revalidatePolicyAuthority(true, `deleting sandbox '${sandboxName}'`); runOpenshell( [ @@ -2079,7 +1949,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche ); } recreateRuntime.confirmDeleted(); - finalizeRecreatedSourceHermesVolume(true, previousEntry, hermesStateVolumeLifecycle !== null); + sandboxLifecycle.removeSandboxUnlessSessionReservation(previousEntry, sandboxName); await hermesApiPortReservationScope.rebindAfterOwnedForwardDelete( hermesApiPortReservationInput, ); @@ -2094,11 +1964,6 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche } preparedSandboxWorkload = await ensurePreparedSandboxWorkload(); hermesStateVolumeLifecycle = prepareHermesStateVolumeLifecycle(preparedSandboxWorkload); - finalizeRecreatedSourceHermesVolume( - !liveExists, - existingEntry, - hermesStateVolumeLifecycle !== null, - ); } runForNewSandboxCreate(resumingVerifiedCreate, () => { revalidatePolicyAuthority(false, `creating sandbox '${sandboxName}'`); @@ -2204,30 +2069,24 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche ).messagingTokenDefs; }, runProviderPreDeleteCleanup: (verifiedPolicyRevalidation) => { - runAuthorityBoundProviderCleanup({ - sandboxName, - runProviderPreDeleteCleanup: runSandboxProviderPreDeleteCleanup, + (verifiedPolicyRevalidation ?? + ((operation) => revalidatePolicyAuthority(false, operation)))( + `cleaning up providers for sandbox '${sandboxName}'`, + ); + runSandboxProviderPreDeleteCleanup(sandboxName, { runOpenshell, redact, tolerateMissingSandbox: true, - ...(verifiedPolicyRevalidation - ? { revalidateSandboxIdentity: verifiedPolicyRevalidation } - : { - observeSandbox: () => - getSandboxRecreateObservation(sandboxName, GATEWAY_NAME), - revalidatePolicyAuthority: (operation: string) => - revalidatePolicyAuthority(false, operation), - }), }); }, upsertMessagingProviders: (tokenDefs, options) => upsertMessagingProviders(tokenDefs, { ...options, revalidatePolicyRequirements: (operation) => - ( - options.revalidatePolicyRequirements ?? - ((targetOperation) => revalidatePolicyAuthority(false, targetOperation)) - )(operation), + (options.revalidatePolicyRequirements ?? + ((targetOperation) => revalidatePolicyAuthority(false, targetOperation)))( + operation, + ), }), getHermesToolGatewayProviderName: (targetSandbox) => getHermesToolGatewayBroker().getHermesToolGatewayProviderName(targetSandbox), @@ -2258,12 +2117,10 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche }, dependencies: { materializeSandboxCreatePlan: (input) => - hermesStateVolumeLifecycle - ? hermesStateVolumeLifecycle.materializeSandboxCreatePlan( - input, - sandboxCreatePlanMaterialization.materializeSandboxCreatePlan, - ) - : sandboxCreatePlanMaterialization.materializeSandboxCreatePlan(input), + hermesStateVolumeLifecycle.materializeSandboxCreatePlan( + input, + sandboxCreatePlanMaterialization.materializeSandboxCreatePlan, + ), prepareSandboxBuildPatchConfig: sandboxBuildPatchConfig.prepareSandboxBuildPatchConfig, }, @@ -2753,6 +2610,18 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche ...(apfInterceptorRequested ? { requirePolicylessCreate: true as const, + persistRetainedApfSandboxRecovery: ( + recovery: import("../sandbox-gpu-create-flow").RetainedApfSandboxRecovery, + ) => { + const persisted = onboardSession.finalizeIncompleteOnboardStep( + "sandbox", + recovery.message, + ); + return ( + persisted?.failure?.message === recovery.message && + persisted.steps.sandbox?.error === recovery.message + ); + }, } : {}), persistRetainedSandboxRecovery: ( @@ -3073,7 +2942,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche } return runWithPostCreateRecovery( () => { - hermesStateVolumeLifecycle?.commit(); + hermesStateVolumeLifecycle.commit(); if ("complete" in recreateRuntime) recreateRuntime.complete(); if (agentCreateInput.hermesPortableLifecycle) return sandboxName; return completeOrdinaryOnboardSandboxCreation( diff --git a/src/lib/onboard/sandbox-create/policy-creation-receipt.ts b/src/lib/onboard/sandbox-create/policy-creation-receipt.ts index 9e1df18a93b..e646ae5eb64 100644 --- a/src/lib/onboard/sandbox-create/policy-creation-receipt.ts +++ b/src/lib/onboard/sandbox-create/policy-creation-receipt.ts @@ -5,8 +5,6 @@ import fs from "node:fs"; import { isDeepStrictEqual } from "node:util"; import { - assertExternalPolicyRequirements, - assertObservedPolicyRequirements, assertOpenShellGatewayPortBinding, captureSandboxBasePolicy, inspectOpenShellSandboxPolicyReadiness, @@ -14,6 +12,10 @@ import { PolicyAuthorityRefusalError, type SandboxPolicyAuthority, } from "../../adapters/openshell/policy-authority"; +import { + assertExternalPolicyRequirements, + assertObservedPolicyRequirements, +} from "../../policy/policy-authority"; import { waitUntil } from "../../core/wait"; import type { NemoClawPolicyCreationReceipt } from "../../policy/merge"; import { normalizePendingSandboxPolicyVerification } from "../../state/registry-normalization"; diff --git a/src/lib/onboard/sandbox-gpu-create-attempt.ts b/src/lib/onboard/sandbox-gpu-create-attempt.ts index 71279406a56..d6a2f24f25d 100644 --- a/src/lib/onboard/sandbox-gpu-create-attempt.ts +++ b/src/lib/onboard/sandbox-gpu-create-attempt.ts @@ -8,6 +8,7 @@ import { initialDockerGpuRoute, type SelectedDockerGpuRoute, } from "./docker-gpu-route"; +import type { RetainedApfSandboxRecoveryEvidence } from "./created-sandbox-failure"; import type { ManagedBootstrapNativeGpuFallbackOwnerCleanupHandoff } from "./managed-bootstrap/runtime-create"; import { type OpenShellDockerSandboxContainerQuery, @@ -33,10 +34,7 @@ export type SandboxGpuCreateAttemptFailure = { stage: SandboxGpuCreateFailureStage; error: unknown; fallbackEligible: boolean; - retainedSandboxRecovery?: { - readonly createAttemptNonce: string; - readonly liveIdentityFingerprint: string | null; - }; + retainedSandboxRecovery?: RetainedApfSandboxRecoveryEvidence; /** Strict native `--gpu` parser rejection observed before build or create progress. */ nativeCreateRejectedBeforeProgress?: true; nativeCleanupHandoff?: ManagedBootstrapNativeGpuFallbackOwnerCleanupHandoff; diff --git a/src/lib/onboard/sandbox-gpu-create-flow.ts b/src/lib/onboard/sandbox-gpu-create-flow.ts index 8b5b9bc7190..09d13150092 100644 --- a/src/lib/onboard/sandbox-gpu-create-flow.ts +++ b/src/lib/onboard/sandbox-gpu-create-flow.ts @@ -2,12 +2,15 @@ // SPDX-License-Identifier: Apache-2.0 import type { AgentDefinition } from "../agent/defs"; -import { NEMOCLAW_CREATE_ATTEMPT_LABEL } from "../adapters/openshell/sandbox-identity"; import type { StreamSandboxCreateResult } from "../sandbox/create-stream"; import { redactFull } from "../security/redact"; import type { CheckpointPortableRuntimeAuthority } from "../state/onboard-checkpoint-types"; import { parsePortableRuntimeAuthority } from "../state/onboard/portable-runtime-authority"; import type { SandboxEntry, SandboxGpuProofResult } from "../state/registry"; +import { + persistAndReportRetainedApfSandboxRecovery, + type RetainedApfSandboxRecovery, +} from "./created-sandbox-failure"; import * as dockerGpuLocalInference from "./docker-gpu-local-inference"; import { collectDockerGpuPatchDiagnostics } from "./docker-gpu-patch"; import type { DockerGpuPatchDeps, DockerUlimit } from "./docker-gpu-patch-types"; @@ -214,16 +217,16 @@ export interface SandboxGpuCreateFlowInput { resumeVerifiedCreate?: { readonly route: SelectedDockerGpuRoute; readonly liveIdentityFingerprint: string; - readonly createAttemptNonce?: string; }; /** Reject every initial or fallback create attempt that carries a caller policy. */ requirePolicylessCreate?: true; - /** Durably retain exact create-attempt recovery evidence before identity-bound recovery stops. */ +/** Durably retain create-attempt recovery evidence before identity-bound recovery stops. */ persistRetainedSandboxRecovery?: ( message: string, sandboxIdentityFingerprint?: string, - createAttemptNonce?: string, ) => boolean; + /** Durably retain exact APF create-attempt recovery evidence before a fallback refusal exits. */ + persistRetainedApfSandboxRecovery?: (recovery: RetainedApfSandboxRecovery) => boolean; provider: string; sandboxGpuConfig: SandboxGpuConfig; gpuRoutePlan: import("./docker-gpu-route").DockerGpuRoutePlan; @@ -274,10 +277,11 @@ export interface SandboxGpuCreateFlowInput { export interface CreatedSandboxIdentity { readonly sandboxId: string; readonly liveIdentityFingerprint: string; - readonly createAttemptNonce: string; readonly route: SelectedDockerGpuRoute; } +export type { RetainedApfSandboxRecovery } from "./created-sandbox-failure"; + /** Refuse APF fallback when OpenShell can remove the failed sandbox only by mutable name. */ export function refuseApfMutableNameFallbackCleanup(sandboxName: string) { return { @@ -374,7 +378,7 @@ export async function runSandboxGpuCreateFlow( input.requirePolicylessCreate && (!input.verifyCreatedSandboxBeforeEffects || !input.revalidateVerifiedSandboxBeforeEffect || - !input.persistRetainedSandboxRecovery) + !input.persistRetainedApfSandboxRecovery) ) { throw new Error( "APF interceptor sandbox creation requires exact post-create verification and durable fallback recovery.", @@ -553,44 +557,24 @@ export async function runSandboxGpuCreateFlow( : ` Sandbox '${input.sandboxName}' may still exist. Verify its durable identity before manual cleanup; do not act by mutable name alone.`, ); if (input.requirePolicylessCreate) { - const persistRetainedSandboxRecovery = input.persistRetainedSandboxRecovery; - if (!persistRetainedSandboxRecovery) { + const persistRetainedApfSandboxRecovery = input.persistRetainedApfSandboxRecovery; + if (!persistRetainedApfSandboxRecovery) { throw new Error("APF interceptor sandbox creation requires durable fallback recovery."); } const evidence = gpuCreateOutcome.retainedSandboxRecovery; if (!evidence) { - console.error( - " APF recovery is blocked because the create attempt returned no durable identity or create-attempt label.", + throw new Error( + "APF interceptor sandbox creation returned no create-attempt recovery evidence.", ); - } else { - const identityGuidance = evidence.liveIdentityFingerprint - ? "Use that fingerprint only to compare the surviving sandbox with this create attempt." - : "OpenShell did not return one exact durable sandbox identity for this create attempt. Recovery is blocked until an OpenShell administrator resolves the create-attempt label to one sandbox."; - const message = - `Create-attempt label: ${NEMOCLAW_CREATE_ATTEMPT_LABEL}=${evidence.createAttemptNonce}. ` + - `${evidence.liveIdentityFingerprint ? `Durable sandbox identity fingerprint: ${evidence.liveIdentityFingerprint}. ` : ""}` + - `APF sandbox '${input.sandboxName}' may have been retained after native GPU fallback stopped. ` + - `Gateway '${input.gatewayName}'. ${identityGuidance} ` + - "Do not delete a sandbox by mutable name; use an identity-bound administrator recovery procedure."; - let persisted = false; - try { - persisted = evidence.liveIdentityFingerprint - ? persistRetainedSandboxRecovery( - message, - evidence.liveIdentityFingerprint, - evidence.createAttemptNonce, - ) - : persistRetainedSandboxRecovery(message, undefined, evidence.createAttemptNonce); - } catch { - persisted = false; - } - console.error(` ${message}`); - if (!persisted) { - console.error( - " APF recovery is blocked because NemoClaw could not save this create-attempt evidence. Preserve the terminal output for an OpenShell administrator.", - ); - } + } + persistAndReportRetainedApfSandboxRecovery({ + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + failureDescription: "native GPU fallback stopped", + evidence, + persist: persistRetainedApfSandboxRecovery, + }); } process.exit(1); } diff --git a/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts b/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts index 1432e27f918..6967d2b02d2 100644 --- a/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts +++ b/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts @@ -63,11 +63,13 @@ import { resetGpuFlowMocks, setupGpuFlowMocks, } from "./__test-helpers__/sandbox-gpu-create-flow"; +import { formatRetainedApfSandboxRecoveryReceipt } from "./created-sandbox-failure"; import { createHermesPortableReadyCapture, createHermesPortableReadyRunner, } from "./experimental/hermes-portable-onboarding"; import { runSandboxGpuCreateFlow } from "./sandbox-gpu-create-flow"; +import { resetOnboardResumeHintForTests } from "./resume-hint"; import { fingerprintSandboxRecreateValue } from "./sandbox-recreate-transaction"; function sandboxListJson( @@ -118,7 +120,10 @@ function refuseEffectStartingWith(prefix: string): (operation: string) => void { } beforeEach(() => setupGpuFlowMocks(mocks)); -afterEach(resetGpuFlowMocks); +afterEach(() => { + resetGpuFlowMocks(); + resetOnboardResumeHintForTests(); +}); describe("created sandbox identity gate", () => { it("resumes the exact verified sandbox without issuing another create (#9833)", async () => { @@ -128,14 +133,12 @@ describe("created sandbox identity gate", () => { input.resumeVerifiedCreate = { route: "none", liveIdentityFingerprint: fingerprintSandboxRecreateValue(sandboxId), - createAttemptNonce: "a".repeat(62), }; input.verifyCreatedSandboxBeforeEffects = vi.fn(async (identity) => { events.push("verify-created"); expect(identity).toEqual({ sandboxId, liveIdentityFingerprint: fingerprintSandboxRecreateValue(sandboxId), - createAttemptNonce: "a".repeat(62), route: "none", }); }); @@ -191,7 +194,6 @@ describe("created sandbox identity gate", () => { input.resumeVerifiedCreate = { route: "none", liveIdentityFingerprint: fingerprintSandboxRecreateValue("expected-id"), - createAttemptNonce: "a".repeat(62), }; input.verifyCreatedSandboxBeforeEffects = vi.fn(); input.revalidateVerifiedSandboxBeforeEffect = vi.fn(); @@ -213,22 +215,6 @@ describe("created sandbox identity gate", () => { expect(patch.ensureApplied).not.toHaveBeenCalled(); }); - it("refuses a resume checkpoint without durable create-attempt authority (#9833)", async () => { - const input = noGpuInput(); - input.resumeVerifiedCreate = { - route: "none", - liveIdentityFingerprint: fingerprintSandboxRecreateValue("expected-id"), - }; - const deps = createGpuFlowDeps(); - - await expect(runSandboxGpuCreateFlow(input, deps)).rejects.toThrow( - "durable create-attempt authority", - ); - - expect(deps.runOpenshell).not.toHaveBeenCalled(); - expect(mocks.streamSandboxCreate).not.toHaveBeenCalled(); - }); - it("requires a durable recovery owner for verified create attempts (#9211)", async () => { const input = noGpuInput(); input.verifyCreatedSandboxBeforeEffects = vi.fn(); @@ -251,7 +237,6 @@ describe("created sandbox identity gate", () => { expect(identity).toEqual({ sandboxId: "alpha-sandbox-id", liveIdentityFingerprint: expect.stringMatching(/^[0-9a-f]{64}$/u), - createAttemptNonce: expect.stringMatching(/^[0-9a-f]{62}$/u), route: "none", }); expect(patch.ensureApplied).not.toHaveBeenCalled(); @@ -607,7 +592,6 @@ describe("created sandbox identity gate", () => { `Durable sandbox identity fingerprint: ${fingerprintSandboxRecreateValue("alpha-sandbox-id")}`, ), fingerprintSandboxRecreateValue("alpha-sandbox-id"), - nonce, ); expect(patch.exitOnPatchError).not.toHaveBeenCalled(); expect(patch.ensureApplied).not.toHaveBeenCalled(); @@ -647,7 +631,6 @@ describe("created sandbox identity gate", () => { `Durable sandbox identity fingerprint: ${fingerprintSandboxRecreateValue("alpha-sandbox-id")}`, ), fingerprintSandboxRecreateValue("alpha-sandbox-id"), - nonce, ); expect(patch.exitOnPatchError).not.toHaveBeenCalled(); expect(patch.ensureApplied).not.toHaveBeenCalled(); @@ -724,8 +707,6 @@ describe("created sandbox identity gate", () => { "u", ), ), - undefined, - nonce, ); expect(events).toEqual(["persist-recovery", "rejected"]); expect(deps.runCaptureOpenshell).toHaveBeenCalledOnce(); @@ -836,6 +817,8 @@ describe("created sandbox identity gate", () => { input.verifyCreatedSandboxBeforeEffects = vi.fn(); input.revalidateVerifiedSandboxBeforeEffect = vi.fn(); input.persistRetainedSandboxRecovery = vi.fn(() => true); + const persistRetainedApfSandboxRecovery = vi.fn(() => true); + input.persistRetainedApfSandboxRecovery = persistRetainedApfSandboxRecovery; mocks.streamSandboxCreate.mockImplementationOnce(async (_command, args) => { nonce = createAttemptNonce(args); return { @@ -867,17 +850,17 @@ describe("created sandbox identity gate", () => { await expect(runSandboxGpuCreateFlow(input, deps)).rejects.toThrow("process.exit:1"); const fingerprint = fingerprintSandboxRecreateValue("alpha-sandbox-id"); - expect(input.persistRetainedSandboxRecovery).toHaveBeenCalledExactlyOnceWith( - expect.stringMatching( - new RegExp( - `^Create-attempt label: ${NEMOCLAW_CREATE_ATTEMPT_LABEL}=${nonce}\\. Durable sandbox identity fingerprint: ${fingerprint}\\.`, - "u", - ), - ), - fingerprint, - nonce, - ); - expect(input.persistRetainedSandboxRecovery).toHaveBeenCalledBefore(exit); + expect(persistRetainedApfSandboxRecovery).toHaveBeenCalledExactlyOnceWith({ + sandboxName: "alpha", + gatewayName: "nemoclaw", + createAttemptNonce: nonce, + liveIdentityFingerprint: fingerprint, + message: formatRetainedApfSandboxRecoveryReceipt({ + createAttemptNonce: nonce, + liveIdentityFingerprint: fingerprint, + }), + }); + expect(persistRetainedApfSandboxRecovery).toHaveBeenCalledBefore(exit); const output = vi.mocked(console.error).mock.calls.flat().join("\n"); expect(output).toContain(`${NEMOCLAW_CREATE_ATTEMPT_LABEL}=${nonce}`); expect(output).toContain(`Durable sandbox identity fingerprint: ${fingerprint}`); @@ -896,6 +879,8 @@ describe("created sandbox identity gate", () => { input.verifyCreatedSandboxBeforeEffects = vi.fn(); input.revalidateVerifiedSandboxBeforeEffect = vi.fn(); input.persistRetainedSandboxRecovery = vi.fn(() => true); + const persistRetainedApfSandboxRecovery = vi.fn(() => true); + input.persistRetainedApfSandboxRecovery = persistRetainedApfSandboxRecovery; mocks.streamSandboxCreate.mockImplementationOnce(async (_command, args) => { nonce = createAttemptNonce(args); return { @@ -924,16 +909,16 @@ describe("created sandbox identity gate", () => { await expect(runSandboxGpuCreateFlow(input, deps)).rejects.toThrow("process.exit:1"); - expect(input.persistRetainedSandboxRecovery).toHaveBeenCalledExactlyOnceWith( - expect.stringMatching( - new RegExp( - `^Create-attempt label: ${NEMOCLAW_CREATE_ATTEMPT_LABEL}=${nonce}\\..*Recovery is blocked until an OpenShell administrator resolves the create-attempt label`, - "u", - ), - ), - undefined, - nonce, - ); + expect(persistRetainedApfSandboxRecovery).toHaveBeenCalledExactlyOnceWith({ + sandboxName: "alpha", + gatewayName: "nemoclaw", + createAttemptNonce: nonce, + liveIdentityFingerprint: null, + message: formatRetainedApfSandboxRecoveryReceipt({ + createAttemptNonce: nonce, + liveIdentityFingerprint: null, + }), + }); const output = vi.mocked(console.error).mock.calls.flat().join("\n"); expect(output).toContain(`${NEMOCLAW_CREATE_ATTEMPT_LABEL}=${nonce}`); expect(output).toContain("Recovery is blocked"); diff --git a/src/lib/onboard/sandbox-gpu-create-run-attempt.ts b/src/lib/onboard/sandbox-gpu-create-run-attempt.ts index 9204e0deab8..e5686b617f9 100644 --- a/src/lib/onboard/sandbox-gpu-create-run-attempt.ts +++ b/src/lib/onboard/sandbox-gpu-create-run-attempt.ts @@ -22,7 +22,11 @@ import { getReadyCheckOutputPatternsForAgent } from "../sandbox/create-stream-re import { getSandboxFailurePhase, isSandboxReady } from "../state/gateway"; import type { SandboxGpuProofResult } from "../state/registry"; import { classifySandboxCreateFailure } from "../validation"; -import { reportSandboxCreateFailure } from "./created-sandbox-failure"; +import { + persistAndReportRetainedApfSandboxRecovery, + reportSandboxCreateFailure, + type RetainedApfSandboxRecoveryEvidence, +} from "./created-sandbox-failure"; import * as dockerGpuLocalInference from "./docker-gpu-local-inference"; import type { SelectedDockerGpuRoute } from "./docker-gpu-route"; import { createDockerGpuSandboxCreatePatch } from "./docker-gpu-sandbox-create"; @@ -31,6 +35,7 @@ import { enforceManagedBootstrapRecoveryForSandbox } from "./managed-bootstrap/a import type { ManagedBootstrapNativeGpuFallbackOwnerCleanupHandoff, ManagedBootstrapRuntimeCreateLifecycle, + ManagedBootstrapRuntimeOnboardRouting, ManagedBootstrapRuntimePatch, ManagedBootstrapRuntimeSnapshot, } from "./managed-bootstrap/runtime-create"; @@ -370,6 +375,184 @@ class ManagedBootstrapCreateStreamFailure extends Error { } } +function persistApfCreateFailureRecovery( + input: SandboxGpuCreateFlowInput, + captureRecovery: () => { + readonly retainedSandboxRecovery?: RetainedApfSandboxRecoveryEvidence; + }, +): void { + if (!input.requirePolicylessCreate) return; + const persist = input.persistRetainedApfSandboxRecovery; + const evidence = captureRecovery().retainedSandboxRecovery; + if (!persist || !evidence) { + throw new Error( + "APF interceptor sandbox creation returned no create-attempt recovery authority.", + ); + } + persistAndReportRetainedApfSandboxRecovery({ + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + failureDescription: "sandbox creation failed", + evidence, + persist, + }); +} + +function captureRetainedApfSandboxRecovery( + input: SandboxGpuCreateFlowInput, + deps: SandboxGpuCreateFlowDeps, + createAttemptNonce: string | null, +): { readonly retainedSandboxRecovery?: RetainedApfSandboxRecoveryEvidence } { + if (!input.requirePolicylessCreate || !createAttemptNonce) return {}; + let liveIdentityFingerprint: string | null = null; + try { + const sandboxId = resolveCreatedOpenShellSandboxId({ + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + createAttemptNonce, + runCaptureOpenshell: deps.runCaptureOpenshell, + }); + liveIdentityFingerprint = fingerprintSandboxRecreateValue(sandboxId); + } catch { + // The nonce remains durable recovery evidence when identity lookup is unavailable. + } + return { + retainedSandboxRecovery: { + createAttemptNonce, + liveIdentityFingerprint, + }, + }; +} + +function recordNativeCreateFallbackEvidence(input: { + readonly route: SelectedDockerGpuRoute; + readonly gpuRoutePlan: SandboxGpuCreateFlowInput["gpuRoutePlan"]; + readonly nativeFallbackHasCleanBaseline: boolean; + readonly createResult: Awaited>; + readonly managedRouting: ManagedBootstrapRuntimeOnboardRouting | undefined; + readonly inspectNativeRuntime: () => NativeRuntimeSnapshot | null; + readonly prebuildImageRef: string | null; + readonly state: SandboxGpuCreateAttemptState; +}): "pre-progress-rejection" | "runtime-error" | null { + if ( + input.route !== "native" || + input.gpuRoutePlan !== "native-with-fallback" || + !input.nativeFallbackHasCleanBaseline + ) { + return null; + } + const routingFailure = input.managedRouting + ? input.managedRouting.isNativeCreateRoutingFailure( + input.createResult.output, + input.createResult.sawProgress, + ) + : sandboxGpuCreateAttempt.isNativeGpuCreateRoutingFailure(input.createResult.output, { + sawProgress: input.createResult.sawProgress, + }); + if (routingFailure) { + input.state.allowUnbuiltCompatibilitySource = input.prebuildImageRef === null; + return "pre-progress-rejection"; + } + const snapshot = input.inspectNativeRuntime(); + if (!snapshot) return null; + const trustedRuntimeError = input.managedRouting + ? input.managedRouting.isTrustedNativeRuntimeError(snapshot.stateError) + : sandboxGpuCreateAttempt.isTrustedNativeGpuRuntimeError(snapshot.stateError); + if (!trustedRuntimeError) return null; + input.state.nativeRuntimeSnapshot = snapshot; + return "runtime-error"; +} + +async function handleFailedSandboxCreate(input: { + readonly route: SelectedDockerGpuRoute; + readonly flow: SandboxGpuCreateFlowInput; + readonly createResult: Awaited>; + readonly managedIncompleteCreateRecovered: boolean; + readonly nativeFallbackHasCleanBaseline: boolean; + readonly managedRouting: ManagedBootstrapRuntimeOnboardRouting | undefined; + readonly inspectNativeRuntime: () => NativeRuntimeSnapshot | null; + readonly state: SandboxGpuCreateAttemptState; + readonly managedLifecycle: ManagedBootstrapRuntimeCreateLifecycle | null; + readonly runtimePatch: ManagedBootstrapRuntimePatch; + readonly captureRetainedSandboxRecovery: () => ReturnType< + typeof captureRetainedApfSandboxRecovery + >; + readonly printCreateFailureDiagnostics: NonNullable< + SandboxGpuCreateFlowDeps["printCreateFailureDiagnostics"] + >; +}) { + const failure = classifySandboxCreateFailure(input.createResult.output); + if (failure.kind === "sandbox_create_incomplete") { + console.warn(""); + if (input.managedIncompleteCreateRecovered) { + console.warn( + ` Create stream exited with code ${input.createResult.status}; the exact durable sandbox reached Ready, and onboarding is continuing with final checks.`, + ); + } else { + console.warn( + ` Create stream exited with code ${input.createResult.status} after sandbox was created.`, + ); + console.warn(" Checking whether the sandbox reaches Ready state..."); + } + return null; + } + const fallbackEvidence = recordNativeCreateFallbackEvidence({ + route: input.route, + gpuRoutePlan: input.flow.gpuRoutePlan, + nativeFallbackHasCleanBaseline: input.nativeFallbackHasCleanBaseline, + createResult: input.createResult, + managedRouting: input.managedRouting, + inspectNativeRuntime: input.inspectNativeRuntime, + prebuildImageRef: input.flow.prebuild.imageRef, + state: input.state, + }); + if (fallbackEvidence) { + let nativeCleanup: NativeFallbackCleanupEvidence = {}; + if (fallbackEvidence === "pre-progress-rejection") { + await input.runtimePatch.rollbackManagedStartupAfterCreateFailure(); + } else { + nativeCleanup = await rollbackNativeGpuFailureForFallback( + input.managedLifecycle, + input.runtimePatch, + ); + } + return { + ok: false, + route: input.route, + stage: "create", + error: new Error("Native OpenShell GPU sandbox creation was rejected."), + fallbackEligible: true, + ...input.captureRetainedSandboxRecovery(), + ...(fallbackEvidence === "pre-progress-rejection" + ? { nativeCreateRejectedBeforeProgress: true as const } + : {}), + ...nativeCleanup, + } as const; + } + await input.runtimePatch.rollbackManagedStartupAfterCreateFailure(); + persistApfCreateFailureRecovery(input.flow, input.captureRetainedSandboxRecovery); + reportSandboxCreateFailure( + { + sandboxName: input.flow.sandboxName, + createStatus: input.createResult.status, + createOutput: input.createResult.output, + restoreBackupPath: input.flow.restoreBackupPath, + createArgs: input.flow.prebuild.createArgs, + }, + { + classifyCreateFailure: classifySandboxCreateFailure, + printCreateFailureDiagnostics: input.printCreateFailureDiagnostics, + printRecoveryHints: input.flow.requirePolicylessCreate + ? () => undefined + : printSandboxCreateRecoveryHints, + warn: (message) => console.warn(message), + error: (message) => console.error(message), + exitProcess: (code) => process.exit(code), + }, + ); + return null; +} + export function createSandboxGpuCreateAttemptRunner( input: SandboxGpuCreateFlowInput, deps: SandboxGpuCreateFlowDeps, @@ -426,7 +609,11 @@ export function createSandboxGpuCreateAttemptRunner( const nativeFallbackHasCleanBaseline = managedRouting?.nativeFallbackHasCleanBaseline ?? (nativeFallbackBaseline?.ok === true && nativeFallbackBaseline.ids.length === 0); - const runAttempt = async (route: SelectedDockerGpuRoute) => { + const runAttemptCore = async ( + route: SelectedDockerGpuRoute, + armApfPostCreateRecovery: (persist: () => void) => void, + persistApfPostCreateRecoveryOnce: () => void, + ) => { const deferPostCreateEffects = input.verifyCreatedSandboxBeforeEffects !== undefined; const compatibility = route === "compatibility"; if (compatibility && input.initialGpuRoute === "native") { @@ -482,26 +669,13 @@ export function createSandboxGpuCreateAttemptRunner( throw error; } }; - const captureRetainedSandboxRecovery = () => { - if (!input.requirePolicylessCreate || !createAttemptNonce) return {}; - let liveIdentityFingerprint: string | null = null; - try { - const sandboxId = resolveCreatedOpenShellSandboxId({ - sandboxName: input.sandboxName, - gatewayName: input.gatewayName, - createAttemptNonce, - runCaptureOpenshell: deps.runCaptureOpenshell, - }); - liveIdentityFingerprint = fingerprintSandboxRecreateValue(sandboxId); - } catch { - // The nonce remains durable recovery evidence when identity lookup is unavailable. - } - return { - retainedSandboxRecovery: { - createAttemptNonce, - liveIdentityFingerprint, - }, - } as const; + const captureRetainedSandboxRecovery = () => + captureRetainedApfSandboxRecovery(input, deps, createAttemptNonce); + const armRetainedApfSandboxRecovery = (): void => { + if (!input.requirePolicylessCreate) return; + armApfPostCreateRecovery(() => + persistApfCreateFailureRecovery(input, captureRetainedSandboxRecovery), + ); }; const attemptArgv = createAttemptNonce ? addCreateAttemptIdentityLabel(unboundAttemptArgv, createAttemptNonce) @@ -532,6 +706,7 @@ export function createSandboxGpuCreateAttemptRunner( sandboxGpuConfig: input.sandboxGpuConfig, requiredLimits: input.requiredUlimits ?? [], timeoutSecs: input.sandboxReadyTimeoutSecs, + beforeFailureExit: persistApfPostCreateRecoveryOnce, dockerClientEnv: input.sandboxEnv, network: { inferenceProvider: input.provider, @@ -573,6 +748,7 @@ export function createSandboxGpuCreateAttemptRunner( requiredUlimits: input.requiredUlimits, timeoutSecs: input.sandboxReadyTimeoutSecs, backend: input.sandboxGpuConfig.hostGpuPlatform === "jetson" ? "jetson" : "generic", + beforeFailureExit: persistApfPostCreateRecoveryOnce, deps, })); const inspectNativeRuntime = (): NativeRuntimeSnapshot | null => { @@ -685,6 +861,7 @@ export function createSandboxGpuCreateAttemptRunner( if (result.status !== 0 && createFailure?.kind !== "sandbox_create_incomplete") { throw new ManagedBootstrapCreateStreamFailure(result); } + armRetainedApfSandboxRecovery(); if (createFailure?.kind === "sandbox_create_incomplete") { const readiness = sandboxReadinessTracing.waitForCreatedSandboxReadyWithTrace({ sandboxName: input.sandboxName, @@ -722,12 +899,11 @@ export function createSandboxGpuCreateAttemptRunner( let sandboxId: string; try { sandboxId = createAttemptNonce - ? settleCreatedOpenShellSandboxId({ + ? resolveCreatedOpenShellSandboxId({ sandboxName: input.sandboxName, gatewayName: input.gatewayName, createAttemptNonce, runCaptureOpenshell: deps.runCaptureOpenshell, - sleep: (milliseconds) => deps.sleep(milliseconds / 1000), }) : resolveOpenShellSandboxId(input.sandboxName, deps.runCaptureOpenshell); } catch (error) { @@ -773,91 +949,23 @@ export function createSandboxGpuCreateAttemptRunner( if (createResult && !state.firstCreateOutput) state.firstCreateOutput = createResult.output; if (!deferPostCreateEffects) await runtimePatch.exitOnPatchError(); if (createResult && createResult.status !== 0) { - const failure = classifySandboxCreateFailure(createResult.output); - let nativeCreateRejectedBeforeProgress = false; - if (failure.kind === "sandbox_create_incomplete") { - console.warn(""); - if (managedIncompleteCreateRecovered) { - console.warn( - ` Create stream exited with code ${createResult.status}; the exact durable sandbox reached Ready, and onboarding is continuing with final checks.`, - ); - } else { - console.warn( - ` Create stream exited with code ${createResult.status} after sandbox was created.`, - ); - console.warn(" Checking whether the sandbox reaches Ready state..."); - } - } else if ( - route === "native" && - input.gpuRoutePlan === "native-with-fallback" && - nativeFallbackHasCleanBaseline && - (() => { - if ( - managedRouting - ? managedRouting.isNativeCreateRoutingFailure( - createResult.output, - createResult.sawProgress, - ) - : sandboxGpuCreateAttempt.isNativeGpuCreateRoutingFailure(createResult.output, { - sawProgress: createResult.sawProgress, - }) - ) { - nativeCreateRejectedBeforeProgress = true; - state.allowUnbuiltCompatibilitySource = input.prebuild.imageRef === null; - return true; - } - const snapshot = inspectNativeRuntime(); - if ( - snapshot && - (managedRouting - ? managedRouting.isTrustedNativeRuntimeError(snapshot.stateError) - : sandboxGpuCreateAttempt.isTrustedNativeGpuRuntimeError(snapshot.stateError)) - ) { - state.nativeRuntimeSnapshot = snapshot; - return true; - } - return false; - })() - ) { - let nativeCleanup: NativeFallbackCleanupEvidence = {}; - if (nativeCreateRejectedBeforeProgress) { - await runtimePatch.rollbackManagedStartupAfterCreateFailure(); - } else { - nativeCleanup = await rollbackNativeGpuFailureForFallback(managedLifecycle, runtimePatch); - } - return { - ok: false, - route, - stage: "create", - error: new Error("Native OpenShell GPU sandbox creation was rejected."), - fallbackEligible: true, - ...captureRetainedSandboxRecovery(), - ...(nativeCreateRejectedBeforeProgress - ? { nativeCreateRejectedBeforeProgress: true as const } - : {}), - ...nativeCleanup, - } as const; - } else { - await runtimePatch.rollbackManagedStartupAfterCreateFailure(); - reportSandboxCreateFailure( - { - sandboxName: input.sandboxName, - createStatus: createResult.status, - createOutput: createResult.output, - restoreBackupPath: input.restoreBackupPath, - createArgs: input.prebuild.createArgs, - }, - { - classifyCreateFailure: classifySandboxCreateFailure, - printCreateFailureDiagnostics, - printRecoveryHints: printSandboxCreateRecoveryHints, - warn: (message) => console.warn(message), - error: (message) => console.error(message), - exitProcess: (code) => process.exit(code), - }, - ); - } + const failureResult = await handleFailedSandboxCreate({ + route, + flow: input, + createResult, + managedIncompleteCreateRecovered, + nativeFallbackHasCleanBaseline, + managedRouting, + inspectNativeRuntime, + state, + managedLifecycle, + runtimePatch, + captureRetainedSandboxRecovery, + printCreateFailureDiagnostics, + }); + if (failureResult) return failureResult; } + armRetainedApfSandboxRecovery(); if (!createdSandboxVerified && deferPostCreateEffects) { if (!createAttemptNonce) { throw new Error("Sandbox create-attempt identity was not generated."); @@ -894,6 +1002,7 @@ export function createSandboxGpuCreateAttemptRunner( resumedSandboxId ?? (preRecreateIdentity?.state === "identified" ? preRecreateIdentity.sandboxId : null); if (deferRestartSafeCutover && !expectedRecreatedSandboxId) { + persistApfPostCreateRecoveryOnce(); console.error(""); console.error( ` Sandbox '${input.sandboxName}' reached Ready, but OpenShell did not return one exact durable sandbox ID before runtime recreation.`, @@ -979,6 +1088,7 @@ export function createSandboxGpuCreateAttemptRunner( ...nativeCleanup, } as const; } + persistApfPostCreateRecoveryOnce(); await runtimePatch.rollbackManagedStartupAfterCreateFailure(); printCreateFailureDiagnostics(input.sandboxName, { backupPath: input.restoreBackupPath, @@ -1026,6 +1136,7 @@ export function createSandboxGpuCreateAttemptRunner( }, ); } catch (error) { + persistApfPostCreateRecoveryOnce(); await runtimePatch.rollbackManagedStartupAfterCreateFailure(); throw error; } @@ -1051,6 +1162,7 @@ export function createSandboxGpuCreateAttemptRunner( } as const; } } + persistApfPostCreateRecoveryOnce(); await runtimePatch.rollbackManagedStartupAfterCreateFailure(); console.error(""); console.error(" Native sandbox GPU proof failed."); @@ -1066,6 +1178,7 @@ export function createSandboxGpuCreateAttemptRunner( ); } if (proof.status === "failed") { + persistApfPostCreateRecoveryOnce(); await runtimePatch.rollbackManagedStartupAfterCreateFailure(); throw new Error("Sandbox GPU proof returned failed status."); } @@ -1088,5 +1201,27 @@ export function createSandboxGpuCreateAttemptRunner( } as const; }; + const runAttempt = async (route: SelectedDockerGpuRoute) => { + let persistApfPostCreateRecovery: (() => void) | null = null; + let apfPostCreateRecoveryPersisted = false; + const persistApfPostCreateRecoveryOnce = (): void => { + if (apfPostCreateRecoveryPersisted || !persistApfPostCreateRecovery) return; + apfPostCreateRecoveryPersisted = true; + persistApfPostCreateRecovery(); + }; + try { + return await runAttemptCore( + route, + (persist) => { + persistApfPostCreateRecovery ??= persist; + }, + persistApfPostCreateRecoveryOnce, + ); + } catch (error) { + persistApfPostCreateRecoveryOnce(); + throw error; + } + }; + return { state, managedRouting, runAttempt }; } diff --git a/src/lib/policy/README.md b/src/lib/policy/README.md index 210d553cbbd..47ec5af2141 100644 --- a/src/lib/policy/README.md +++ b/src/lib/policy/README.md @@ -11,9 +11,12 @@ under `src/lib/domain/**` when they can be isolated. ## Policy authority The policy module reads the effective OpenShell policy through the sandbox's recorded gateway. -NemoClaw records the first qualified authority before another policy read or set. +For a policy-mutation flow, NemoClaw records the first qualified authority before another policy +read or set. NemoClaw refuses the operation when it cannot write that record. +Shields recovery can read live authority without changing the durable recorded authority. + Immediately before each policy set, NemoClaw reads authority again and compares it with the record. NemoClaw refuses the policy set when: diff --git a/src/lib/policy/commands.test.ts b/src/lib/policy/commands.test.ts index f3e3519a1eb..28cc53daebd 100644 --- a/src/lib/policy/commands.test.ts +++ b/src/lib/policy/commands.test.ts @@ -32,7 +32,33 @@ describe("OpenShell policy command builders", () => { ]); }); - it("pins policy authority reads to the selected gateway", () => { + it("pins policy operations and authority reads to the selected gateway", () => { + expect(buildPolicyGetCommand("alpha", "nemoclaw").slice(1)).toEqual([ + "policy", + "get", + "-g", + "nemoclaw", + "--base", + "alpha", + ]); + expect(buildPolicyGetFullCommand("alpha", "nemoclaw").slice(1)).toEqual([ + "policy", + "get", + "-g", + "nemoclaw", + "--full", + "alpha", + ]); + expect(buildPolicySetCommand("/tmp/policy.yaml", "alpha", "nemoclaw").slice(1)).toEqual([ + "policy", + "set", + "-g", + "nemoclaw", + "--policy", + "/tmp/policy.yaml", + "--wait", + "alpha", + ]); expect(buildPolicyGetArgs("alpha", "nemoclaw")).toEqual([ "policy", "get", diff --git a/src/lib/policy/index.ts b/src/lib/policy/index.ts index fb7447514d9..ca977858e0e 100644 --- a/src/lib/policy/index.ts +++ b/src/lib/policy/index.ts @@ -11,7 +11,6 @@ import readline from "node:readline"; import { isDeepStrictEqual } from "node:util"; import YAML from "yaml"; -// Namespace access keeps resolveOpenshell spyable in focused policy tests. import { assertExternalPolicyRequirements, assertRecordedPolicyAuthority, @@ -23,7 +22,8 @@ import { PolicyAuthorityRefusalError, type SandboxPolicyAuthority, type SandboxPolicyAuthorityInspection, -} from "../adapters/openshell/policy-authority"; +} from "./policy-authority"; +// Namespace access keeps resolveOpenshell spyable in focused policy tests. import * as openshellResolveModule from "../adapters/openshell/resolve"; import { loadAgent, requireAgentPolicyAdditionsPath } from "../agent/defs"; import { CLI_NAME } from "../cli/branding"; diff --git a/src/lib/policy/policy-authority.test.ts b/src/lib/policy/policy-authority.test.ts new file mode 100644 index 00000000000..45dad622d43 --- /dev/null +++ b/src/lib/policy/policy-authority.test.ts @@ -0,0 +1,157 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; + +import { + assertExternalPolicyRequirements, + assertObservedPolicyRequirements, + assertRecordedPolicyAuthority, + isExternalPolicyAuthorityRefusalError, + type SandboxPolicyAuthorityInspection, +} from "./policy-authority"; + +function errorFrom(action: () => unknown): Error { + try { + action(); + } catch (error) { + expect(error).toBeInstanceOf(Error); + return error as Error; + } + throw new Error("expected the action to throw"); +} + +describe("recorded policy authority", () => { + it("accepts unchanged authority and refuses missing or changed authority (#9833)", () => { + expect(() => + assertRecordedPolicyAuthority("externally-managed", "externally-managed", "rebuild"), + ).not.toThrow(); + expect(() => + assertRecordedPolicyAuthority(undefined, "externally-managed", "restore the snapshot"), + ).toThrow(/recorded policy authority is unavailable or invalid/); + expect(() => + assertRecordedPolicyAuthority( + "nemoclaw-managed", + "externally-managed", + "restore the snapshot", + ), + ).toThrow(/changed from nemoclaw-managed to externally-managed/); + expect(() => + assertRecordedPolicyAuthority("externally-managed", "unknown", "restore the snapshot"), + ).toThrow(/observed OpenShell policy authority is unavailable or invalid/); + }); + + it("classifies an observed external authority without parsing diagnostics (#9833)", () => { + const externalError = errorFrom(() => + assertRecordedPolicyAuthority( + "nemoclaw-managed", + "externally-managed", + "restore the snapshot", + ), + ); + const managedError = errorFrom(() => + assertRecordedPolicyAuthority( + "externally-managed", + "nemoclaw-managed", + "restore the snapshot", + ), + ); + + expect(isExternalPolicyAuthorityRefusalError(externalError)).toBe(true); + expect(isExternalPolicyAuthorityRefusalError(managedError)).toBe(false); + }); +}); + +describe("externally managed policy requirements", () => { + it("compares exact requirements and redacts missing or drifted contents (#9833)", () => { + const requiredPolicy = { + version: 1, + filesystem_policy: { read_only: ["/required-secret"] }, + process: { run_as_user: 1000 }, + network_policies: { + exact: { endpoints: [{ host: "api.test", port: 443 }], mode: "allow" }, + missing: { endpoints: [{ host: "missing-secret.test", port: 443 }] }, + drifted: { endpoints: [{ host: "required-secret.test", port: 443 }] }, + }, + }; + const inspection: SandboxPolicyAuthorityInspection = { + authority: "externally-managed", + policyIdentity: { hash: "policy-alpha", activeVersion: 7 }, + effectivePolicy: { + version: 9, + filesystem_policy: { read_only: ["/observed-secret"] }, + network_policies: { + exact: { mode: "allow", endpoints: [{ port: 443, host: "api.test" }] }, + drifted: { endpoints: [{ host: "observed-secret.test", port: 443 }] }, + }, + }, + }; + + const error = errorFrom(() => + assertExternalPolicyRequirements({ + inspection, + requiredPolicy, + operation: "enable messaging", + sandboxName: "alpha", + }), + ); + expect(error.message).toContain('missing sections "process"'); + expect(error.message).toContain('drifted sections "filesystem_policy"'); + expect(error.message).toContain('missing entries "missing"'); + expect(error.message).toContain('drifted entries "drifted"'); + expect(error.message).not.toMatch( + /required-secret|observed-secret|missing-secret\.test|observed-secret\.test/u, + ); + }); + + it("leaves NemoClaw-managed requirements to the mutation path (#9833)", () => { + expect(() => + assertExternalPolicyRequirements({ + inspection: { + authority: "nemoclaw-managed", + policyIdentity: { hash: "policy-alpha", activeVersion: 7 }, + effectivePolicy: {}, + }, + requiredPolicy: { network_policies: { required: { endpoints: ["api.test"] } } }, + operation: "apply a preset", + }), + ).not.toThrow(); + }); +}); + +describe("observed policy requirements", () => { + it("checks owner-unknown policy contents without assigning ownership (#9833)", () => { + const inspection: SandboxPolicyAuthorityInspection = { + authority: "owner-unknown", + policyIdentity: { hash: "policy-alpha", activeVersion: 7 }, + effectivePolicy: { + network_policies: { required: { endpoints: ["api.test"] } }, + }, + }; + + expect(() => + assertObservedPolicyRequirements({ + inspection, + requiredPolicy: { + network_policies: { required: { endpoints: ["api.test"] } }, + }, + operation: "verify the created sandbox policy", + sandboxName: "alpha", + }), + ).not.toThrow(); + + const error = errorFrom(() => + assertObservedPolicyRequirements({ + inspection, + requiredPolicy: { + network_policies: { missing: { endpoints: ["required-secret.test"] } }, + }, + operation: "verify the created sandbox policy", + sandboxName: "alpha", + }), + ); + expect(error.message).toContain('missing entries "missing"'); + expect(error.message).toContain("The verified policy must supply the exact required entries"); + expect(error.message).not.toContain("required-secret.test"); + }); +}); diff --git a/src/lib/policy/policy-authority.ts b/src/lib/policy/policy-authority.ts new file mode 100644 index 00000000000..6ee64d9e228 --- /dev/null +++ b/src/lib/policy/policy-authority.ts @@ -0,0 +1,113 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { + assertOpenShellGatewayPortBinding, + captureSandboxBasePolicy, + inspectActiveGlobalPolicy, + inspectOpenShellSandboxIdentityFingerprint, + inspectSandboxPolicyAuthority, + isExternalPolicyAuthorityRefusalError, + isPolicyAuthorityRefusalError, + PolicyAuthorityRefusalError, + type ActiveGlobalPolicyInspection, + type SandboxPolicyAuthority, + type SandboxPolicyAuthorityInspection, +} from "../adapters/openshell/policy-authority"; +import { + assertExternalPolicyRequirementContainment, + assertMatchingPolicyAuthority, + assertPolicyRequirementContainment, +} from "./merge"; + +type JsonObject = Record; + +export { + assertOpenShellGatewayPortBinding, + captureSandboxBasePolicy, + inspectActiveGlobalPolicy, + inspectOpenShellSandboxIdentityFingerprint, + inspectSandboxPolicyAuthority, + isExternalPolicyAuthorityRefusalError, + isPolicyAuthorityRefusalError, + PolicyAuthorityRefusalError, +}; +export type { + ActiveGlobalPolicyInspection, + SandboxPolicyAuthority, + SandboxPolicyAuthorityInspection, +}; + +function operationLabel(operation: string): string { + return typeof operation === "string" && operation.trim().length > 0 + ? operation.trim() + : "continue the policy-dependent operation"; +} + +/** Refuse a lifecycle operation when its durable and observed authority disagree. */ +export function assertRecordedPolicyAuthority( + recorded: unknown, + observed: unknown, + operation: string, +): void { + const label = operationLabel(operation); + try { + assertMatchingPolicyAuthority(recorded, observed); + } catch (error) { + const detail = error instanceof Error ? error.message : "policy authority is invalid"; + const observedAuthority = + observed === "nemoclaw-managed" || observed === "externally-managed" ? observed : undefined; + throw new PolicyAuthorityRefusalError(`Refusing to ${label}: ${detail}.`, observedAuthority); + } +} + +/** + * Verify that an externally supplied policy contains each required entry and + * section without claiming ownership. Unrelated external entries are allowed. + */ +export function assertExternalPolicyRequirements({ + inspection, + requiredPolicy, + operation, + sandboxName, +}: { + readonly inspection: SandboxPolicyAuthorityInspection; + readonly requiredPolicy: JsonObject; + readonly operation: string; + readonly sandboxName?: string; +}): void { + const label = operationLabel(operation); + const target = sandboxName ? ` for sandbox ${JSON.stringify(sandboxName)}` : ""; + try { + assertExternalPolicyRequirementContainment(inspection, requiredPolicy); + } catch (error) { + const detail = error instanceof Error ? error.message : "the policy requirement is invalid"; + throw new PolicyAuthorityRefusalError( + `Refusing to ${label}${target}: ${detail}. Ask the external policy authority to supply the exact required entries.`, + ); + } +} + +/** Verify required entries without assigning ownership to a sandbox-scoped policy. */ +export function assertObservedPolicyRequirements({ + inspection, + requiredPolicy, + operation, + sandboxName, +}: { + readonly inspection: SandboxPolicyAuthorityInspection; + readonly requiredPolicy: JsonObject; + readonly operation: string; + readonly sandboxName?: string; +}): void { + const label = operationLabel(operation); + const target = sandboxName ? ` for sandbox ${JSON.stringify(sandboxName)}` : ""; + try { + assertPolicyRequirementContainment(inspection, requiredPolicy); + } catch (error) { + const detail = error instanceof Error ? error.message : "the policy requirement is invalid"; + throw new PolicyAuthorityRefusalError( + `Refusing to ${label}${target}: ${detail}. The verified policy must supply the exact required entries.`, + ); + } +} diff --git a/src/lib/shields/destroy-cleanup.test.ts b/src/lib/shields/destroy-cleanup.test.ts new file mode 100644 index 00000000000..e2e35fe0ddc --- /dev/null +++ b/src/lib/shields/destroy-cleanup.test.ts @@ -0,0 +1,202 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { describe, expect, it, vi } from "vitest"; + +import { cleanupShieldsDestroyArtifacts } from "./destroy-cleanup"; + +describe("Shields destroy cleanup", () => { + it("destroy neutralizes active shields timer and only deletes target sandbox files", () => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "destroy-shields-")); + const alphaRecovery = path.join(stateDir, "shields-external-policy-alpha.yaml"); + const alphaState = path.join(stateDir, "shields-alpha.json"); + const alphaTimer = path.join(stateDir, "shields-timer-alpha.json"); + const betaRecovery = path.join(stateDir, "shields-external-policy-beta.yaml"); + const betaState = path.join(stateDir, "shields-beta.json"); + const betaTimer = path.join(stateDir, "shields-timer-beta.json"); + + fs.writeFileSync(alphaRecovery, "version: 1\nnetwork_policies: {}\n"); + fs.writeFileSync(alphaState, '{"shieldsDown":true}'); + fs.writeFileSync(alphaTimer, '{"pid":9999}'); + fs.writeFileSync(betaRecovery, "version: 1\nnetwork_policies: {}\n"); + fs.writeFileSync(betaState, '{"shieldsDown":true}'); + fs.writeFileSync(betaTimer, '{"pid":9999}'); + + const cleanupCalls: string[] = []; + cleanupShieldsDestroyArtifacts("alpha", { + stateDir, + killShieldsTimer: (sandboxName) => { + cleanupCalls.push(`revoke:${sandboxName}`); + return { + authorityRevoked: true, + warnings: [], + }; + }, + rmSync: ((...args: Parameters) => { + cleanupCalls.push(`remove:${path.basename(String(args[0]))}`); + fs.rmSync(...args); + }) as typeof fs.rmSync, + }); + + expect(cleanupCalls).toEqual([ + "revoke:alpha", + "remove:shields-external-policy-alpha.yaml", + "remove:shields-alpha.json", + "remove:shields-timer-alpha.json", + ]); + expect(fs.existsSync(alphaRecovery)).toBe(false); + expect(fs.existsSync(alphaState)).toBe(false); + expect(fs.existsSync(alphaTimer)).toBe(false); + expect(fs.existsSync(betaRecovery)).toBe(true); + expect(fs.existsSync(betaState)).toBe(true); + expect(fs.existsSync(betaTimer)).toBe(true); + + fs.rmSync(stateDir, { recursive: true, force: true }); + }); + + it("destroy preserves all Shields artifacts when timer authority revocation fails (#9833)", () => { + const warnings: string[] = []; + const rmSync = vi.fn(); + + expect(() => + cleanupShieldsDestroyArtifacts("alpha", { + stateDir: "/tmp/nonexistent-state-dir", + rmSync: rmSync as unknown as typeof fs.rmSync, + killShieldsTimer: () => ({ + authorityRevoked: false, + warnings: ["Failed to remove the Shields timer marker"], + }), + warn: (message) => warnings.push(message), + }), + ).toThrow( + "Could not revoke Shields timer authority for sandbox 'alpha'. Shields cleanup artifacts were preserved for retry.", + ); + + expect(warnings).toEqual(["Failed to remove the Shields timer marker"]); + expect(rmSync).not.toHaveBeenCalled(); + }); + + it("destroy restores the recovery artifact when Shields state removal fails (#9833)", () => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "destroy-shields-rollback-")); + const recoveryPath = path.join(stateDir, "shields-external-policy-alpha.yaml"); + const statePath = path.join(stateDir, "shields-alpha.json"); + const timerPath = path.join(stateDir, "shields-timer-alpha.json"); + const recoveryContent = "version: 1\nnetwork_policies: {}\n"; + const stateContent = '{"shieldsDown":true}'; + fs.writeFileSync(recoveryPath, recoveryContent, { mode: 0o600 }); + fs.writeFileSync(statePath, stateContent, { mode: 0o600 }); + fs.writeFileSync(timerPath, '{"pid":9999}', { mode: 0o600 }); + const rmSync = vi.fn((...args: Parameters) => { + const [artifactPath] = args; + switch (path.basename(String(artifactPath))) { + case "shields-alpha.json": { + const error = new Error("permission denied") as NodeJS.ErrnoException; + error.code = "EACCES"; + throw error; + } + default: + fs.rmSync(...args); + } + }); + + try { + expect(() => + cleanupShieldsDestroyArtifacts("alpha", { + stateDir, + rmSync: rmSync as unknown as typeof fs.rmSync, + killShieldsTimer: () => ({ authorityRevoked: true, warnings: [] }), + }), + ).toThrow( + `Could not remove Shields state record '${statePath}': permission denied. Shields cleanup artifacts were restored or retained for retry.`, + ); + + expect(fs.readFileSync(recoveryPath, "utf8")).toBe(recoveryContent); + expect(fs.readFileSync(statePath, "utf8")).toBe(stateContent); + expect(fs.existsSync(timerPath)).toBe(true); + expect( + rmSync.mock.calls.map(([artifactPath]) => path.basename(String(artifactPath))), + ).toEqual(["shields-external-policy-alpha.yaml", "shields-alpha.json"]); + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }); + } + }); + + it("destroy preserves Shields state when external recovery cleanup fails (#9833)", () => { + const warnings: string[] = []; + const rmSync = vi.fn((artifactPath: string) => { + switch (path.basename(artifactPath)) { + case "shields-external-policy-alpha.yaml": { + const error = new Error("permission denied") as NodeJS.ErrnoException; + error.code = "EACCES"; + throw error; + } + } + }); + + expect(() => + cleanupShieldsDestroyArtifacts("alpha", { + stateDir: "/tmp/nonexistent-state-dir", + rmSync: rmSync as unknown as typeof fs.rmSync, + killShieldsTimer: () => ({ + authorityRevoked: true, + warnings: ["Failed to terminate Shields timer PID 4242"], + }), + warn: (message) => warnings.push(message), + }), + ).toThrow( + "Could not remove external Shields policy recovery artifact '/tmp/nonexistent-state-dir/shields-external-policy-alpha.yaml': permission denied. Shields state was preserved for retry.", + ); + + expect(warnings).toEqual(["Failed to terminate Shields timer PID 4242"]); + expect(rmSync).toHaveBeenCalledOnce(); + expect(rmSync.mock.calls[0][0]).toContain("shields-external-policy-alpha.yaml"); + }); +}); + +describe("shields state cleanup on destroy (#3114)", () => { + it("tolerates missing Shields artifacts after revoking timer authority", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); + try { + const killShieldsTimer = vi.fn(() => ({ authorityRevoked: true, warnings: [] })); + + expect(() => + cleanupShieldsDestroyArtifacts("nonexistent", { + stateDir: tmpDir, + killShieldsTimer, + }), + ).not.toThrow(); + + expect(killShieldsTimer).toHaveBeenCalledWith("nonexistent"); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + + it("rejects path traversal in sandbox name", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); + const escapedFile = path.join(tmpDir, "..", "shields-traversal.json"); + const killShieldsTimer = vi.fn(() => ({ authorityRevoked: true, warnings: [] })); + const rmSync = vi.fn(); + try { + fs.writeFileSync(escapedFile, "should survive"); + + // A name containing ../ should not delete files outside stateDir + cleanupShieldsDestroyArtifacts("../../../../shields-traversal", { + stateDir: tmpDir, + killShieldsTimer, + rmSync: rmSync as unknown as typeof fs.rmSync, + }); + + expect(killShieldsTimer).toHaveBeenCalledWith("../../../../shields-traversal"); + expect(rmSync).not.toHaveBeenCalled(); + expect(fs.existsSync(escapedFile)).toBe(true); + } finally { + fs.rmSync(escapedFile, { force: true }); + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); +}); diff --git a/src/lib/shields/destroy-cleanup.ts b/src/lib/shields/destroy-cleanup.ts new file mode 100644 index 00000000000..9fadfc31017 --- /dev/null +++ b/src/lib/shields/destroy-cleanup.ts @@ -0,0 +1,152 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; + +import { openRegularFileNoFollow } from "../adapters/fs/regular-file"; +import { resolveNemoclawStateDir } from "../state/paths"; +import { killTimer, type KillTimerResult } from "./timer-control"; + +type RemoveShieldsStateDeps = { + rmSync?: typeof fs.rmSync; + warn?: (message: string) => void; +}; + +export type CleanupShieldsDestroyArtifactsDeps = RemoveShieldsStateDeps & { + killShieldsTimer?: ( + sandboxName: string, + ) => Pick; + stateDir?: string; +}; + +function defaultCleanupWarn(message: string): void { + console.warn(` ⚠ ${message}`); +} + +// Match the maximum size accepted by the owning Shields policy-artifact boundary. +const MAX_SHIELDS_CLEANUP_SNAPSHOT_BYTES = 16 * 1024 * 1024; + +function readShieldsCleanupSnapshot(filePath: string): Buffer | undefined { + let artifact: ReturnType | undefined; + try { + artifact = openRegularFileNoFollow(filePath); + return artifact.readBytes(MAX_SHIELDS_CLEANUP_SNAPSHOT_BYTES); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; + const message = error instanceof Error ? error.message : String(error); + throw new Error( + `Could not read Shields cleanup artifact '${filePath}' before removal: ${message}. Shields state was preserved for retry.`, + { cause: error }, + ); + } finally { + artifact?.close(); + } +} + +function restoreShieldsCleanupSnapshot(filePath: string, snapshot: Buffer | undefined): void { + if (snapshot === undefined) return; + fs.writeFileSync(filePath, snapshot, { flag: "wx", mode: 0o600 }); +} + +function removeShieldsRecoveryStatePair( + recoveryArtifactPath: string, + stateRecordPath: string, + rmSync: typeof fs.rmSync, +): void { + const recoverySnapshot = readShieldsCleanupSnapshot(recoveryArtifactPath); + try { + rmSync(recoveryArtifactPath, { force: true }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error( + `Could not remove external Shields policy recovery artifact '${recoveryArtifactPath}': ${message}. Shields state was preserved for retry.`, + { cause: error }, + ); + } + + try { + rmSync(stateRecordPath, { force: true }); + } catch (error) { + let rollbackError: unknown; + try { + restoreShieldsCleanupSnapshot(recoveryArtifactPath, recoverySnapshot); + } catch (error) { + rollbackError = error; + } + const message = error instanceof Error ? error.message : String(error); + const rollbackStatus = + rollbackError === undefined + ? "Shields cleanup artifacts were restored or retained for retry." + : `Shields cleanup rollback was incomplete: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}.`; + throw new Error( + `Could not remove Shields state record '${stateRecordPath}': ${message}. ${rollbackStatus}`, + { cause: error }, + ); + } +} + +/** + * Remove host-side Shields state and recovery artifacts for a sandbox. + * + * Without this cleanup, stale state or an external policy handoff from a + * previous sandbox can survive destroy → re-onboard under the same name. + * + * See: https://github.com/NVIDIA/NemoClaw/issues/3114 + */ +function removeShieldsState( + sandboxName: string, + stateDir = resolveNemoclawStateDir(), + deps: RemoveShieldsStateDeps = {}, +): void { + const rmSync = deps.rmSync ?? fs.rmSync; + const warn = deps.warn ?? defaultCleanupWarn; + const resolvedStateDir = path.resolve(stateDir); + const filePaths = [ + `shields-external-policy-${sandboxName}.yaml`, + `shields-${sandboxName}.json`, + `shields-timer-${sandboxName}.json`, + ].map((artifactName) => path.resolve(resolvedStateDir, artifactName)); + if (filePaths.some((filePath) => !filePath.startsWith(`${resolvedStateDir}${path.sep}`))) { + // Defense-in-depth: sandbox names are validated to [a-z0-9-] at all + // entry points, but reject traversal attempts just in case. + return; + } + const [recoveryArtifactPath, stateRecordPath, timerMarkerPath] = filePaths as [ + string, + string, + string, + ]; + removeShieldsRecoveryStatePair(recoveryArtifactPath, stateRecordPath, rmSync); + try { + rmSync(timerMarkerPath, { force: true }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return; + const message = error instanceof Error ? error.message : String(error); + warn(`Failed to remove Shields cleanup artifact '${timerMarkerPath}': ${message}`); + } +} + +/** Revoke timer authority before retiring Shields destroy-cleanup state. */ +export function cleanupShieldsDestroyArtifacts( + sandboxName: string, + deps: CleanupShieldsDestroyArtifactsDeps = {}, +): void { + const killShieldsTimer = deps.killShieldsTimer ?? killTimer; + const warn = deps.warn ?? defaultCleanupWarn; + + const timerResult = killShieldsTimer(sandboxName); + for (const warning of timerResult.warnings) { + warn(warning); + } + if (!timerResult.authorityRevoked) { + throw new Error( + `Could not revoke Shields timer authority for sandbox '${sandboxName}'. Shields cleanup artifacts were preserved for retry.`, + ); + } + + removeShieldsState(sandboxName, deps.stateDir ?? resolveNemoclawStateDir(), { + rmSync: deps.rmSync ?? fs.rmSync, + warn, + }); +} diff --git a/src/lib/state/onboard-session-apf-recovery.test.ts b/src/lib/state/onboard-session-apf-recovery.test.ts new file mode 100644 index 00000000000..6ce51260540 --- /dev/null +++ b/src/lib/state/onboard-session-apf-recovery.test.ts @@ -0,0 +1,62 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { formatRetainedApfSandboxRecoveryReceipt } from "../onboard/created-sandbox-failure"; + +const originalHome = process.env.HOME; +type OnboardSessionModule = typeof import("./onboard-session"); +let session: OnboardSessionModule; +let tmpDir: string; + +beforeEach(async () => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-apf-recovery-")); + process.env.HOME = tmpDir; + vi.resetModules(); + session = await import("./onboard-session"); + session.clearSession(); +}); + +afterEach(() => { + vi.resetModules(); + fs.rmSync(tmpDir, { recursive: true, force: true }); + Reflect.deleteProperty(process.env, "HOME"); + Object.assign(process.env, originalHome === undefined ? {} : { HOME: originalHome }); +}); + +describe("APF retained-sandbox session recovery", () => { + it.each([ + ["identifiable", "b".repeat(64)], + ["label-only", null], + ])("round-trips exact %s evidence through terminal failure (#9833)", (_caseName, fingerprint) => { + const createAttemptNonce = "a".repeat(62); + const receipt = formatRetainedApfSandboxRecoveryReceipt({ + createAttemptNonce, + liveIdentityFingerprint: fingerprint, + }); + session.saveSession( + session.createSession({ + apfInterceptorRequested: true, + sandboxName: "alpha", + }), + ); + + const finalized = session.finalizeIncompleteOnboardStep("sandbox", receipt); + const loaded = session.loadSession(); + const onDisk = JSON.parse(fs.readFileSync(session.SESSION_FILE, "utf8")); + + expect(receipt.length).toBeLessThanOrEqual(240); + expect(finalized?.failure?.message).toBe(receipt); + expect(finalized?.steps.sandbox?.error).toBe(receipt); + expect(loaded?.failure?.message).toBe(receipt); + expect(loaded?.steps.sandbox?.error).toBe(receipt); + expect(onDisk.failure.message).toBe(receipt); + expect(onDisk.steps.sandbox.error).toBe(receipt); + expect(loaded?.failure?.message).toContain(createAttemptNonce); + expect(loaded?.failure?.message).toContain(fingerprint ?? "unresolved"); + }); +}); diff --git a/test/automation/pull-requests/pr-review-advisor-specialists.test.ts b/test/automation/pull-requests/pr-review-advisor-specialists.test.ts index 3c635f7aaf7..d7e511aecd1 100644 --- a/test/automation/pull-requests/pr-review-advisor-specialists.test.ts +++ b/test/automation/pull-requests/pr-review-advisor-specialists.test.ts @@ -11,9 +11,15 @@ import { canonicalRepoReadPath } from "../../../tools/advisors/repo-read-only-to import { describe, expect, it, onTestFinished, vi } from "vitest"; import { TERMINOLOGY_TRACE_TOOL } from "../../../tools/pr-review-advisor/terminology.mts"; -import { runSpecialistAdvisor, writeSpecialistSummary } from "../../../tools/pr-review-advisor/run-specialist.mts"; +import { + runSpecialistAdvisor, + writeSpecialistSummary, +} from "../../../tools/pr-review-advisor/run-specialist.mts"; import { writeSpecialistDiff } from "../../../tools/pr-review-advisor/specialist-context.mts"; -import type { RunAdvisorResult, RunReadOnlyAdvisorOptions } from "../../../tools/advisors/session.mts"; +import type { + RunAdvisorResult, + RunReadOnlyAdvisorOptions, +} from "../../../tools/advisors/session.mts"; import { ADVISOR_INTERESTS, buildSpecialistInvestigateTurn, @@ -55,7 +61,9 @@ describe("PR review advisor specialist prompts", () => { const file = writeSpecialistDiff(directory, "diff evidence"); expect(file).toBe(expected); - await expect(canonicalRepoReadPath(directory, "diff.patch")).resolves.toBe(expected); + await expect(canonicalRepoReadPath(directory, "diff.patch")).resolves.toBe( + fs.realpathSync(expected), + ); expect(fs.readFileSync(file, "utf8")).toBe("diff evidence"); expect(fs.statSync(directory).mode & 0o777).toBe(0o700); expect(fs.statSync(file).mode & 0o777).toBe(0o600); diff --git a/test/helpers/destroy-flow-test-harness.ts b/test/helpers/destroy-flow-test-harness.ts index 206183c9537..d6c159998e4 100644 --- a/test/helpers/destroy-flow-test-harness.ts +++ b/test/helpers/destroy-flow-test-harness.ts @@ -610,7 +610,7 @@ export function createDestroyHarness(options: DestroyHarnessOptions = {}): Destr }); const killTimerSpy = vi.spyOn(timerControl, "killTimer").mockImplementation(() => { events.push("timer-cleanup"); - return { warnings: [] }; + return { authorityRevoked: true, warnings: [] }; }); const preparedServers = options.mcpAddState === "prepared" ? [] : (options.mcpServers ?? []); const mcpPreparation = { diff --git a/test/helpers/onboard-script-mocks.cjs b/test/helpers/onboard-script-mocks.cjs index 3dbbf88023b..6e1425adb5d 100644 --- a/test/helpers/onboard-script-mocks.cjs +++ b/test/helpers/onboard-script-mocks.cjs @@ -1003,13 +1003,38 @@ function mockStructuredOpenShellCaptureFromRunner(options = {}) { ...(options.includeStreams === true ? { stdout: "", stderr } : {}), }; } + const isStructuredPolicyRead = + args[0] === "policy" && (args[1] === "get" || args[1] === "list"); + const structuredPolicyRead = isStructuredPolicyRead + ? runner.runCaptureEx([binary, ...args], { + ...options, + ignoreError: true, + includeStderr: false, + }) + : null; const stdout = String( - runner.runCapture([binary, ...args], { - ...options, - ignoreError: true, - includeStderr: false, - }) || "", + structuredPolicyRead?.stdout ?? + runner.runCapture([binary, ...args], { + ...options, + ignoreError: true, + includeStderr: false, + }) ?? + "", ); + const stderr = String(structuredPolicyRead?.stderr ?? ""); + if (structuredPolicyRead) { + const error = structuredPolicyRead.timedOut + ? Object.assign(new Error("OpenShell fixture capture timed out"), { code: "ETIMEDOUT" }) + : undefined; + if (error || structuredPolicyRead.exitCode !== 0 || stdout.trim().length > 0) { + return { + status: structuredPolicyRead.exitCode, + output: options.includeStderr === true ? `${stdout}${stderr}`.trim() : stdout.trim(), + ...(options.includeStreams === true ? { stdout, stderr } : {}), + ...(error ? { error } : {}), + }; + } + } if (isCreatedSandboxPolicyRead && stdout.trim().length === 0) { const fallback = JSON.stringify({ scope: "sandbox", diff --git a/test/onboarding/onboard-fresh-create-identity.test.ts b/test/onboarding/onboard-fresh-create-identity.test.ts index b526635f735..39fc03eb9bf 100644 --- a/test/onboarding/onboard-fresh-create-identity.test.ts +++ b/test/onboarding/onboard-fresh-create-identity.test.ts @@ -328,6 +328,18 @@ runner.run = (command, opts = {}) => { } if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; return ""; +}; +runner.runCaptureEx = (command) => { + const cmd = _n(command); + if (cmd.endsWith("policy get -g nemoclaw-18080 --full --output json my-assistant")) { + return { + stdout: JSON.stringify({ scope: "sandbox", sandbox: "my-assistant", status: "effective", policy_source: "sandbox", hash: "fixture-policy", active_version: 1, policy: effectivePolicy }), + stderr: "", + exitCode: 0, + timedOut: false, + }; + } + return { stdout: "", stderr: "", exitCode: 0, timedOut: false }; }; const retainedRegistryEntry = recoveryReentry && fs.existsSync(${JSON.stringify(payloadPath)}) ? JSON.parse(fs.readFileSync(${JSON.stringify(payloadPath)}, "utf8")).currentRegistryEntry diff --git a/test/platform/images/image-cleanup.test.ts b/test/platform/images/image-cleanup.test.ts index aa64651e8a9..b38f376e063 100644 --- a/test/platform/images/image-cleanup.test.ts +++ b/test/platform/images/image-cleanup.test.ts @@ -4,18 +4,13 @@ // Verify that sandbox lifecycle operations clean up host-side Docker images. // See: https://github.com/NVIDIA/NemoClaw/issues/2086 -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; import { describe, expect, it, vi } from "vitest"; import { help as renderRootHelp } from "../../../src/lib/actions/root-help"; import { - cleanupShieldsDestroyArtifacts, removeSandboxImage, removeSandboxRegistryEntry, removeSandboxRegistryEntryOutcome, removeSandboxRegistryEntryWithReceipt, - removeShieldsState, requireSandboxDestructiveCleanupAuthority, } from "../../../src/lib/actions/sandbox/destroy"; import { requireSnapshotDestinationRegistryRemoval } from "../../../src/lib/actions/sandbox/snapshot"; @@ -25,7 +20,6 @@ import { normalizeGarbageCollectImagesOptions } from "../../../src/lib/domain/li import { getSandboxDeleteOutcome } from "../../../src/lib/domain/sandbox/destroy"; import { createDockerRuntimeProviderBundle } from "../../../src/lib/onboard/runtime-provider/docker"; import { createRuntimeProviderBundleRegistry } from "../../../src/lib/onboard/runtime-provider/registry"; -import { resolveNemoclawStateDir } from "../../../src/lib/state/paths"; describe("image cleanup: sandbox destroy removes Docker image (#2086)", () => { it("removes sandbox images before deleting the registry entry", () => { @@ -295,142 +289,6 @@ describe("image cleanup: sandbox destroy removes Docker image (#2086)", () => { gatewayUnreachable: false, }); }); - - it("destroy neutralizes active shields timer and only deletes target sandbox files", () => { - const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "destroy-shields-")); - const alphaRecovery = path.join(stateDir, "shields-external-policy-alpha.yaml"); - const alphaState = path.join(stateDir, "shields-alpha.json"); - const alphaTimer = path.join(stateDir, "shields-timer-alpha.json"); - const betaRecovery = path.join(stateDir, "shields-external-policy-beta.yaml"); - const betaState = path.join(stateDir, "shields-beta.json"); - const betaTimer = path.join(stateDir, "shields-timer-beta.json"); - - fs.writeFileSync(alphaRecovery, "version: 1\nnetwork_policies: {}\n"); - fs.writeFileSync(alphaState, '{"shieldsDown":true}'); - fs.writeFileSync(alphaTimer, '{"pid":9999}'); - fs.writeFileSync(betaRecovery, "version: 1\nnetwork_policies: {}\n"); - fs.writeFileSync(betaState, '{"shieldsDown":true}'); - fs.writeFileSync(betaTimer, '{"pid":9999}'); - - const killCalls: string[] = []; - cleanupShieldsDestroyArtifacts("alpha", { - stateDir, - killShieldsTimer: (sandboxName) => { - killCalls.push(sandboxName); - return { - warnings: [], - }; - }, - }); - - expect(killCalls).toEqual(["alpha"]); - expect(fs.existsSync(alphaRecovery)).toBe(false); - expect(fs.existsSync(alphaState)).toBe(false); - expect(fs.existsSync(alphaTimer)).toBe(false); - expect(fs.existsSync(betaRecovery)).toBe(true); - expect(fs.existsSync(betaState)).toBe(true); - expect(fs.existsSync(betaTimer)).toBe(true); - - fs.rmSync(stateDir, { recursive: true, force: true }); - }); - - it("destroy preserves Shields state when external recovery cleanup fails (#9833)", () => { - const warnings: string[] = []; - const rmSync = vi.fn((artifactPath: string) => { - if (artifactPath.endsWith("shields-external-policy-alpha.yaml")) { - const error = new Error("permission denied") as NodeJS.ErrnoException; - error.code = "EACCES"; - throw error; - } - }); - - expect(() => - cleanupShieldsDestroyArtifacts("alpha", { - stateDir: "/tmp/nonexistent-state-dir", - rmSync: rmSync as unknown as typeof fs.rmSync, - killShieldsTimer: () => ({ - warnings: ["Failed to terminate Shields timer PID 4242"], - }), - warn: (message) => warnings.push(message), - }), - ).toThrow( - "Could not remove external Shields policy recovery artifact '/tmp/nonexistent-state-dir/shields-external-policy-alpha.yaml': permission denied. Shields state was preserved for retry.", - ); - - expect(warnings).toEqual(["Failed to terminate Shields timer PID 4242"]); - expect(rmSync).toHaveBeenCalledOnce(); - expect(rmSync.mock.calls[0][0]).toContain("shields-external-policy-alpha.yaml"); - }); - - it("state-dir helper resolves ~/.nemoclaw/state from a single shared helper", () => { - const resolved = resolveNemoclawStateDir("/tmp/example-home"); - expect(resolved).toBe(path.join("/tmp/example-home", ".nemoclaw", "state")); - }); -}); - -describe("shields state cleanup on destroy (#3114)", () => { - it("removes Shields state, timer, and external recovery files for the sandbox", () => { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); - try { - const shieldsFile = path.join(tmpDir, "shields-alpha.json"); - const timerFile = path.join(tmpDir, "shields-timer-alpha.json"); - const recoveryFile = path.join(tmpDir, "shields-external-policy-alpha.yaml"); - fs.writeFileSync(shieldsFile, JSON.stringify({ shieldsDown: false })); - fs.writeFileSync(timerFile, JSON.stringify({ pid: 12345 })); - fs.writeFileSync(recoveryFile, "version: 1\nnetwork_policies: {}\n"); - - removeShieldsState("alpha", tmpDir); - - expect(fs.existsSync(shieldsFile)).toBe(false); - expect(fs.existsSync(timerFile)).toBe(false); - expect(fs.existsSync(recoveryFile)).toBe(false); - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }); - } - }); - - it("is a no-op when no shields state files exist", () => { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); - try { - // Must not throw - removeShieldsState("nonexistent", tmpDir); - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }); - } - }); - - it("does not remove state files for other sandboxes", () => { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); - try { - const otherFile = path.join(tmpDir, "shields-bravo.json"); - const otherRecoveryFile = path.join(tmpDir, "shields-external-policy-bravo.yaml"); - fs.writeFileSync(otherFile, JSON.stringify({ shieldsDown: false })); - fs.writeFileSync(otherRecoveryFile, "version: 1\nnetwork_policies: {}\n"); - - removeShieldsState("alpha", tmpDir); - - expect(fs.existsSync(otherFile)).toBe(true); - expect(fs.existsSync(otherRecoveryFile)).toBe(true); - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }); - } - }); - - it("rejects path traversal in sandbox name", () => { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); - const escapedFile = path.join(tmpDir, "..", "shields-traversal.json"); - try { - fs.writeFileSync(escapedFile, "should survive"); - - // A name containing ../ should not delete files outside stateDir - removeShieldsState("../../../../shields-traversal", tmpDir); - - expect(fs.existsSync(escapedFile)).toBe(true); - } finally { - fs.rmSync(escapedFile, { force: true }); - fs.rmSync(tmpDir, { recursive: true, force: true }); - } - }); }); describe("image cleanup: gc command exists (#2086)", () => { diff --git a/test/repository/layer-import-boundaries.test.ts b/test/repository/layer-import-boundaries.test.ts index 8cc3db8229a..9d4ee6c4483 100644 --- a/test/repository/layer-import-boundaries.test.ts +++ b/test/repository/layer-import-boundaries.test.ts @@ -73,6 +73,33 @@ describe("CLI layer import boundaries (#6245)", () => { ); }); + it("keeps OpenShell adapters independent from policy modules (#9833)", () => { + const violations = scanFixture( + fixturePath("src/lib/adapters/openshell", "policy"), + 'import { buildPolicyGetCommand } from "../../policy/commands";\nexport { buildPolicyGetCommand };\n', + ); + + expect(violations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + detail: "OpenShell adapters must not import policy module src/lib/policy/commands.ts", + rule: "openshell-adapters-no-policy", + }), + ]), + ); + }); + + it("allows OpenShell adapters to import neighboring adapter modules (#9833)", () => { + const violations = scanFixture( + fixturePath("src/lib/adapters/openshell", "runtime"), + 'import { captureResolvedOpenshell } from "./runtime";\nexport { captureResolvedOpenshell };\n', + ); + + expect(violations).not.toEqual( + expect.arrayContaining([expect.objectContaining({ rule: "openshell-adapters-no-policy" })]), + ); + }); + it("blocks bare fs imports in messaging manifests (#6245)", () => { const violations = scanFixture( fixturePath("src/lib/messaging/manifest", "bare-fs"), diff --git a/test/runtime/policy/policy-mutation-read-discovery.test.ts b/test/runtime/policy/policy-mutation-read-discovery.test.ts index d09cd1ec54a..f4f95959830 100644 --- a/test/runtime/policy/policy-mutation-read-discovery.test.ts +++ b/test/runtime/policy/policy-mutation-read-discovery.test.ts @@ -51,7 +51,7 @@ function shieldsAuditSource( describe("OpenShell policy mutation read discovery (#6921)", () => { it("counts canonical builder bindings and direct argv reads", () => { const source = [ - 'import { buildPolicyGetCommand as buildBase } from "./policy/commands";', + 'import { buildPolicyGetCommand as buildBase, buildPolicyGetFullJsonArgs as buildFullJsonArgs } from "./policy/commands";', 'import * as policyBuilders from "./policy/index";', 'const { buildPolicyGetFullCommand: buildFull } = require("./policy");', 'const requiredPolicyBuilders = require("./policy");', @@ -62,13 +62,14 @@ describe("OpenShell policy mutation read discovery (#6921)", () => { 'policyBuilders["buildPolicyGetFullCommand"](sandboxName);', "buildFull(sandboxName);", "requiredPolicyBuilders.buildPolicyGetCommand(sandboxName);", + "buildFullJsonArgs(sandboxName);", '["openshell", "policy", "get", "--base", sandboxName];', '["policy", "get", "--full", sandboxName];', 'const arrayDecoy = `["policy", "get", "--base", sandboxName]`;', '["not-openshell", "policy", "get", "--base", sandboxName];', ].join("\n"); - expect(countPolicyReadCalls(source, "/repo/src/lib/fixture.ts", "/repo")).toBe(7); + expect(countPolicyReadCalls(source, "/repo/src/lib/fixture.ts", "/repo")).toBe(8); }); it("classifies gateway-pinned direct policy reads", () => { @@ -81,15 +82,16 @@ describe("OpenShell policy mutation read discovery (#6921)", () => { "}", ].join("\n"); - expect(classifyPolicyReadCalls(source, "/repo/nemoclaw/src/blueprint/runner.ts", "/repo")) - .toEqual([ - { site: "actionApply", view: "base", failureHandling: "error-preserving" }, - { - site: "inspectAuthority", - view: "full", - failureHandling: "error-preserving", - }, - ]); + expect( + classifyPolicyReadCalls(source, "/repo/nemoclaw/src/blueprint/runner.ts", "/repo"), + ).toEqual([ + { site: "actionApply", view: "base", failureHandling: "error-preserving" }, + { + site: "inspectAuthority", + view: "full", + failureHandling: "error-preserving", + }, + ]); }); it("ignores direct policy reads with ambiguous view flags (#9833)", () => { diff --git a/test/runtime/policy/policy-mutation-read-failure.test.ts b/test/runtime/policy/policy-mutation-read-failure.test.ts index 81560f7761a..1b8195c5f59 100644 --- a/test/runtime/policy/policy-mutation-read-failure.test.ts +++ b/test/runtime/policy/policy-mutation-read-failure.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import fs from "node:fs"; +import { spawnSync } from "node:child_process"; import { createRequire } from "node:module"; import os from "node:os"; import path from "node:path"; @@ -70,6 +71,126 @@ describe("OpenShell policy mutation read failures", () => { } }); + it.each([ + ["a nonzero status", 42, false], + ["a timeout", null, true], + ] as const)( + "refuses policy mutation when the full JSON authority read reports %s (#9833)", + (failure, exitCode, timedOut) => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-policy-authority-read-")); + tempDirs.push(tempDir); + const fakeOpenshell = path.join(tempDir, "openshell"); + const scriptPath = path.join(tempDir, "policy-authority-read.cjs"); + const repoRoot = path.join(import.meta.dirname, "../../.."); + fs.writeFileSync(fakeOpenshell, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + + const script = String.raw` +const fixtureMocks = require(${JSON.stringify(path.join(repoRoot, "test/helpers/onboard-script-mocks.cjs"))}); +const runner = require(${JSON.stringify(path.join(repoRoot, "src/lib/runner.ts"))}); +fixtureMocks.mockStandaloneGatewayTeardownAuthority(); +const registry = require(${JSON.stringify(path.join(repoRoot, "src/lib/state/registry.ts"))}); +const policy = require(${JSON.stringify(path.join(repoRoot, "src/lib/policy/index.ts"))}); + +const calls = []; +const fullMetadata = JSON.stringify({ + scope: "sandbox", + sandbox: "alpha", + status: "effective", + policy_source: "sandbox", + hash: "fixture-policy", + active_version: 1, + policy: {}, +}); +const sandbox = fixtureMocks.managedSandboxPolicyReceiptFixture({ + name: "alpha", + agent: "openclaw", + policies: [], +}); +registry.getSandbox = () => structuredClone(sandbox); +registry.getBaselineExclusions = () => []; +registry.updateSandbox = () => true; + +const normalize = (command) => command.map(String).join(" "); +runner.runCaptureEx = (command) => { + const normalized = normalize(command); + calls.push({ seam: "structured", command: normalized }); + if (normalized.includes("policy get") && normalized.includes("--full --output json")) { + return { + stdout: fullMetadata, + stderr: "private-policy-diagnostic", + exitCode: ${JSON.stringify(exitCode)}, + timedOut: ${JSON.stringify(timedOut)}, + }; + } + if (normalized.includes("policy get") && normalized.includes("--base")) { + return { + stdout: "version: 1\nnetwork_policies: {}\n", + stderr: "", + exitCode: 0, + timedOut: false, + }; + } + return { stdout: "", stderr: "", exitCode: 0, timedOut: false }; +}; +runner.runCapture = (command) => { + const normalized = normalize(command); + calls.push({ seam: "string", command: normalized }); + if (normalized.includes("policy get") && normalized.includes("--full --output json")) { + return fullMetadata; + } + if (normalized.includes("policy get") && normalized.includes("--base")) { + return "version: 1\nnetwork_policies: {}\n"; + } + if (normalized.includes("sandbox get")) { + return "Name: alpha\nId: fixture-created-sandbox\n"; + } + return ""; +}; +runner.run = (command) => { + calls.push({ seam: "run", command: normalize(command) }); + return { status: 0, stdout: Buffer.alloc(0), stderr: Buffer.alloc(0) }; +}; + +const applied = policy.applyPresetContent( + "alpha", + "advisor-regression", + "network_policies:\n advisor-regression:\n endpoints:\n - host: example.com\n port: 443\n", + { nonFatal: true, skipRegistryUpdate: true, suppressDisclosure: true }, +); +console.log(JSON.stringify({ applied, calls })); +`; + fs.writeFileSync(scriptPath, script); + + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf8", + env: { + ...process.env, + HOME: tempDir, + NEMOCLAW_OPENSHELL_BIN: fakeOpenshell, + }, + }); + + expect(result.status, result.stderr).toBe(0); + const payload = JSON.parse(result.stdout.trim().split("\n").at(-1) ?? "") as { + applied: boolean; + calls: Array<{ command: string; seam: string }>; + }; + expect(payload.applied).toBe(false); + expect(payload.calls).toContainEqual({ + seam: "structured", + command: `${fakeOpenshell} policy get -g nemoclaw --full --output json alpha`, + }); + expect( + payload.calls.some( + ({ command }) => command.includes("policy set") && command.includes("--wait"), + ), + `${failure} must stop before policy set`, + ).toBe(false); + expect(`${result.stdout}\n${result.stderr}`).not.toContain("private-policy-diagnostic"); + }, + ); + describe.each([ { mutation: "applyPresetContent", diff --git a/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts b/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts index 2bdb5ab6e5c..7997d1b6c7a 100644 --- a/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts +++ b/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts @@ -112,7 +112,7 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { ); }); - it("fails closed before other cleanup when the Google Chat tunnel cannot stop", () => { + it("retains service PID directories and fails closed when the Google Chat tunnel cannot stop", () => { const harness = buildDeps({ provider: "ollama-local" }); vi.mocked(harness.deps.stopGooglechatWebhookTunnel).mockImplementation(() => { throw new Error("cloudflared refused to stop");