Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 35 additions & 4 deletions src/lib/actions/sandbox/mcp-bridge-remove.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
import {
assertMcpDestroyNotPending,
bridgeState,
clearMcpDestroyMarkers,
ensureSandboxGatewaySelected,
getBridgeAdapter,
getSandboxAgent,
Expand Down Expand Up @@ -89,9 +90,22 @@ export async function removeMcpBridge(
server: string,
options: { force?: boolean; allowResidual?: boolean } = {},
): Promise<void> {
return withMcpLifecycleLock(sandboxName, () =>
removeMcpBridgeUnlocked(sandboxName, server, options),
);
return withMcpLifecycleLock(sandboxName, async () => {
// #6376: capture the recoverable prepared-destroy phase BEFORE the removal.
const before = getSandboxOrThrow(sandboxName).mcp;
const recoverPreparedDestroy =
!!options.force && !!before?.destroyPreparedAt && !before?.destroyPendingAt;
await removeMcpBridgeUnlocked(sandboxName, server, options);
// Clear the phase-one destroy marker only AFTER the removal succeeded, so a
// mid-recovery failure (thrown above) preserves the durable retry marker for
// a later `sandbox destroy` or retry. `setBridgeState` preserves the marker
// across the removal's own writes until this explicit, phase-aware clear.
if (recoverPreparedDestroy && clearMcpDestroyMarkers(sandboxName)) {
console.log(
` Cleared incomplete MCP destroy transaction on sandbox '${sandboxName}' (--force).`,
);
}
});
}

async function removeMcpBridgeUnlocked(
Expand All @@ -102,7 +116,24 @@ async function removeMcpBridgeUnlocked(
validateSandboxName(sandboxName);
validateMcpServerName(server);
const sandbox = getSandboxOrThrow(sandboxName);
assertMcpDestroyNotPending(sandbox);
// #6376: `--force` on `mcp remove` is the documented non-destructive recovery
// for a stuck MCP destroy transaction. It is PHASE-AWARE: only the prepared
// (phase-one) marker — in-sandbox scrub + provider detach done, sandbox NOT
// yet deleted — is recoverable here, because the sandbox still exists. In that
// case skip the guard and run the requested removal; removeMcpBridge clears the
// marker only after this function returns successfully, so a failure preserves
// the durable retry state. Every other state still hits the guard:
// - no `--force`: refuse (the guard's normal behavior);
// - the pending (phase-two) marker: the sandbox was already deleted from
// OpenShell, so the guard's phase-aware message points at `nemoclaw
// <name> destroy` — `mcp remove` cannot recover a deleted sandbox and
// clearing that marker would abandon the still-owed provider/policy
// cleanup.
const recoverPreparedDestroy =
!!options.force && !!sandbox.mcp?.destroyPreparedAt && !sandbox.mcp?.destroyPendingAt;
if (!recoverPreparedDestroy) {
assertMcpDestroyNotPending(sandbox);
}
const entry = bridgeState(sandbox)[server];
if (!entry) {
if (!options.force) {
Expand Down
66 changes: 65 additions & 1 deletion src/lib/actions/sandbox/mcp-bridge-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,75 @@ export function setBridgeState(sandboxName: string, bridges: Record<string, McpB

export function assertMcpDestroyNotPending(sandbox: SandboxEntry): void {
if (!sandbox.mcp?.destroyPreparedAt && !sandbox.mcp?.destroyPendingAt) return;
// Phase-aware recovery guidance. `destroyPendingAt` is written only after
// OpenShell confirmed the sandbox was deleted (mcp-bridge-destroy.ts), so at
// that phase the sandbox no longer exists and the only correct recovery is to
// finish the (idempotent) destroy — a non-destructive `mcp remove --force`
// cannot operate on a deleted sandbox. The prepared-only phase still has a
// live sandbox and is recoverable in place.
if (sandbox.mcp?.destroyPendingAt) {
throw new McpBridgeError(
`Sandbox '${sandbox.name}' is mid-destroy past the point of no return — the sandbox was already deleted from OpenShell. Run \`nemoclaw ${sandbox.name} destroy\` to finish the (idempotent) cleanup.`,
);
}
throw new McpBridgeError(
`Sandbox '${sandbox.name}' has an incomplete MCP destroy transaction. Re-run the sandbox destroy command to finish cleanup before using MCP commands.`,
`Sandbox '${sandbox.name}' has an incomplete MCP destroy transaction. Re-run the sandbox destroy command to finish cleanup, or recover non-destructively (the sandbox still exists) with \`nemoclaw ${sandbox.name} mcp remove <server> --force\`.`,
);
}

/**
* Non-destructive recovery for a stuck MCP destroy transaction — PHASE-AWARE.
*
* When a prior destroy leaves a `destroyPreparedAt` marker behind (phase one:
* in-sandbox scrub + provider detach done, sandbox NOT yet deleted) every MCP
* command is refused by `assertMcpDestroyNotPending`, and rebuild refuses up
* front with the same guard. Before #6376 the only advertised recovery was
* `nemoclaw <name> destroy` — full sandbox destruction.
*
* This helper clears ONLY the prepared (phase-one) marker, in place, so a
* `--force` caller can proceed with the requested removal on a sandbox that
* still exists. It deliberately refuses the pending (phase-two) marker: that
* marker is written only after OpenShell deleted the sandbox, and it is the
* durable retry state that keeps the still-owed provider/policy cleanup
* idempotent. Erasing it would silently abandon that cleanup, so a pending
* transaction must be finished with `nemoclaw <name> destroy`, not cleared.
*
* Callers clear the prepared marker only AFTER the requested removal succeeds
* (see removeMcpBridge), so a failed recovery preserves the retry marker.
* `setBridgeState` preserves the marker across the removal's own writes until
* then.
*
* Returns whether the marker was actually cleared, so callers can log
* accurately (no-op vs. cleared).
*/
export function clearMcpDestroyMarkers(sandboxName: string): boolean {
const sandbox = registry.getSandbox(sandboxName);
const mcpState = sandbox?.mcp;
if (!mcpState?.destroyPreparedAt && !mcpState?.destroyPendingAt) return false;
if (mcpState.destroyPendingAt) {
throw new McpBridgeError(
`Sandbox '${sandboxName}' is mid-destroy past the point of no return — the sandbox was already deleted from OpenShell. Run \`nemoclaw ${sandboxName} destroy\` to finish cleanup; the pending-destroy marker cannot be cleared non-destructively.`,
);
}
const bridges = mcpState.bridges ?? {};
const managedServerNames = mcpState.managedServerNames ?? [];
const updated = registry.updateSandbox(sandboxName, {
mcp:
Object.keys(bridges).length > 0 || managedServerNames.length > 0
? {
bridges,
...(managedServerNames.length > 0 ? { managedServerNames } : {}),
}
: undefined,
});
if (!updated) {
throw new McpBridgeError(
`Could not clear incomplete MCP destroy markers for sandbox '${sandboxName}'.`,
);
}
return true;
}

export function assertNoDerivedResourceCollision(
sandbox: SandboxEntry,
server: string,
Expand Down
79 changes: 79 additions & 0 deletions src/lib/actions/sandbox/rebuild-preflight-confirmation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@

import { afterEach, describe, expect, it, vi } from "vitest";
import * as openshellResolve from "../../adapters/openshell/resolve";
import { redact } from "../../security/redact";
import * as sandboxSession from "../../state/sandbox-session";
import {
confirmSandboxRebuildIfNeeded,
countActiveSandboxSessionsForRebuild,
createRebuildCommandContext,
} from "./rebuild-preflight-confirmation";
import { isSingleAgentRebuildSupported } from "./rebuild-preflight-guards";

Expand Down Expand Up @@ -57,6 +59,83 @@ describe("rebuild confirmation", () => {
});
});

describe("createRebuildCommandContext bail behaviour (#6376)", () => {
it("prints the bail message to stderr before exiting (non-throw mode)", () => {
// Regression for #6376: the non-throw bail path used to discard its
// `message` argument and just call `process.exit(code)`, so an actionable
// reason (e.g. `Failed to preserve MCP bridges before rebuild: Sandbox
// 'X' has an incomplete MCP destroy transaction ...`) exited 1 with NO
// output, leaving the user without a diagnosis.
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);
const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
throw new Error(`process.exit(${code ?? 0})`);
}) as never);

const ctx = createRebuildCommandContext([], { throwOnError: false });
expect(() => ctx.bail("Failed to preserve MCP bridges before rebuild: reason X", 1)).toThrow(
"process.exit(1)",
);

// The message must reach stderr; `console.error` inherits the pipeline's
// leading two-space rebuild-diagnostic prefix.
expect(errorSpy).toHaveBeenCalledWith(
" Failed to preserve MCP bridges before rebuild: reason X",
);
expect(exitSpy).toHaveBeenCalledWith(1);
});

it("still exits with the requested code even when the message is empty (backward compat)", () => {
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);
const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
throw new Error(`process.exit(${code ?? 0})`);
}) as never);

const ctx = createRebuildCommandContext([], { throwOnError: false });
expect(() => ctx.bail("", 2)).toThrow("process.exit(2)");

// Empty messages must NOT be printed as a bare two-space line —
// silence is fine when the caller passed nothing meaningful.
expect(errorSpy).not.toHaveBeenCalled();
expect(exitSpy).toHaveBeenCalledWith(2);
});

it("keeps the throw-on-error path lossless (bail message becomes the Error)", () => {
// Belt-and-suspenders: the other consumer of createRebuildCommandContext
// (test / in-process callers) still gets the message via `throw new Error`.
const ctx = createRebuildCommandContext([], { throwOnError: true });
expect(() => ctx.bail("carried reason", 1)).toThrow("carried reason");
});

it("routes the surfaced bail message through the redaction boundary (#6376)", () => {
// The bail message can wrap a lower-level error (`bail("...: " + err.message)`)
// that carries a URL/token; the new stderr path must not become the one place
// rebuild leaks a secret. It must apply the same `redact` boundary `log` uses.
const raw =
"Failed to preserve MCP bridges before rebuild: probe https://hub.example.test/v1?api_key=SUPERSECRETTOKEN123 failed";
const redacted = redact(raw);
// Sanity: the chosen message actually contains something the boundary scrubs,
// so this test is meaningful regardless of redact's exact patterns.
expect(redacted).not.toBe(raw);
expect(redacted).not.toContain("SUPERSECRETTOKEN123");

const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);
const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
throw new Error(`process.exit(${code ?? 0})`);
}) as never);

const ctx = createRebuildCommandContext([], { throwOnError: false });
expect(() => ctx.bail(raw, 1)).toThrow("process.exit(1)");

// What reached stderr is the redacted form, with the two-space prefix ...
expect(errorSpy).toHaveBeenCalledWith(` ${redacted}`);
// ... and the raw secret never surfaced.
for (const call of errorSpy.mock.calls) {
expect(String(call[0])).not.toContain("SUPERSECRETTOKEN123");
}
expect(exitSpy).toHaveBeenCalledWith(1);
});
});

describe("rebuild preflight guards", () => {
it("rejects a multi-agent sandbox before later rebuild work", () => {
const error = vi.spyOn(console, "error").mockImplementation(() => undefined);
Expand Down
18 changes: 17 additions & 1 deletion src/lib/actions/sandbox/rebuild-preflight-confirmation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,23 @@ export function createRebuildCommandContext(
? (message: string) => {
throw new Error(message);
}
: (_message: string, code = 1) => process.exit(code),
: // #6376: previously discarded `message` entirely, so any bail() call
// that raised an actionable reason (e.g. `Failed to preserve MCP
// bridges before rebuild: Sandbox 'X' has an incomplete MCP destroy
// transaction. Re-run the sandbox destroy command …`) exited 1 with
// no output at all — leaving the user with the last stage's spinner
// line and no diagnosis. Emit the reason on stderr before exit so
// `$?`-gated automation and interactive users see WHY rebuild
// aborted. The message can carry a wrapped lower-level error
// (`bail("...: " + error.message)`), so route it through the same
// `redact` boundary `log` already uses (line above) before surfacing —
// a bailed rebuild must not be the one path that leaks a URL/token.
// `console.error` inherits the rebuild-diagnostic formatting (leading
// two spaces).
(message: string, code = 1) => {
if (message) console.error(` ${redact(message)}`);
process.exit(code);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
},
};
}

Expand Down
14 changes: 14 additions & 0 deletions src/lib/actions/sandbox/rebuild-preflight-phase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { RebuildSandboxOptions } from "../../domain/lifecycle/options";
import type { SandboxMessagingPlan } from "../../messaging";
import { hydrateCredentialEnv } from "../../onboard/credential-env";
import type { RebuildManifest } from "../../state/sandbox";
import { assertMcpDestroyNotPending } from "./mcp-bridge-state";
import {
preflightRebuildCredentials,
type RebuildBail,
Expand Down Expand Up @@ -82,6 +83,19 @@ export async function runRebuildPreflightPhase(
const activeSessionCount = countActiveSandboxSessionsForRebuild(sandboxName);
const sandboxEntry = getRebuildSandboxEntryOrBail(sandboxName, bail);
if (!sandboxEntry) return null;
// #6376: refuse a stuck MCP destroy transaction up front — before backup,
// image prep, or the old-sandbox delete. The only MCP marker check used to
// live inside the destroy phase, which runs AFTER the backup phase, so a
// stuck sandbox paid destructive/backup cost before the guard fired. Moving
// it here fails closed before any destructive work; the guard's message is
// phase-aware (prepared -> non-destructive `mcp remove --force`; pending ->
// finish the destroy).
try {
assertMcpDestroyNotPending(sandboxEntry);
} catch (error) {
bail(error instanceof Error ? error.message : String(error));
return null;
}
const confirmedEntrySnapshot = JSON.stringify(sandboxEntry);
const allowLegacyManagedImageRecovery =
opts.recoveryManifest !== undefined && opts.allowLegacyManagedImageRecovery === true;
Expand Down
Loading
Loading