Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
1a7f0b3
fix(policy): resolve review advisor findings
apurvvkumaria Aug 26, 2026
55a2b1b
fix(policy): complete review advisor follow-up
apurvvkumaria Aug 26, 2026
403cb65
fix(shields): keep cleanup behind lifecycle gate
apurvvkumaria Aug 26, 2026
9981455
fix(policy): enforce advisor ownership boundaries
apurvvkumaria Aug 26, 2026
bdf2d84
merge(policy): reconcile current main
apurvvkumaria Aug 26, 2026
863527c
test(onboard): repair canonical authority fixtures
apurvvkumaria Aug 26, 2026
e7cbebc
merge: resolve conflicts with main
github-actions[bot] Aug 26, 2026
ab02516
merge: sync current main and preserve advisor repairs
apurvvkumaria Aug 26, 2026
b6d6d4e
fix(snapshot): preserve service cleanup state on restore
apurvvkumaria Aug 26, 2026
a9f0cff
merge: integrate APF recovery findings from main
apurvvkumaria Aug 26, 2026
f04062b
merge: update PR #10317 from current main
apurvvkumaria Aug 26, 2026
a01ebc9
fix(onboard): persist retained APF recovery
apurvvkumaria Aug 26, 2026
85d81a6
merge: update PR #10317 from current main
apurvvkumaria Aug 26, 2026
71972bf
fix(onboard): persist APF recovery before terminal exits
apurvvkumaria Aug 26, 2026
4c8a017
merge: update PR #10317 from current main
apurvvkumaria Aug 26, 2026
80d1f52
merge: resolve conflicts with main
github-actions[bot] Aug 26, 2026
0ec6f9c
merge: resolve conflicts with main
github-actions[bot] Aug 26, 2026
c0cd880
merge: update PR #10317 from current main
apurvvkumaria Aug 26, 2026
e767d34
merge: update PR #10317 from current main
apurvvkumaria Aug 26, 2026
6d7ba74
merge: resolve conflicts with main
github-actions[bot] Aug 26, 2026
57642f3
merge: resolve conflicts with main
github-actions[bot] Aug 27, 2026
59ea693
merge: resolve conflicts with main
github-actions[bot] Aug 27, 2026
e94fda0
merge: resolve conflicts with main
github-actions[bot] Aug 27, 2026
133760d
merge: synchronize #10317 with main
apurvvkumaria Aug 27, 2026
48345b8
fix(policy): restore review repair boundaries
apurvvkumaria Aug 27, 2026
6a04937
test(policy): preserve structured capture failures
apurvvkumaria Aug 27, 2026
115d3f0
merge: resolve conflicts with main
github-actions[bot] Aug 27, 2026
5465193
test(policy): cover allowed adapter imports
cjagwani Aug 27, 2026
dcb305d
Merge branch 'main' into codex/9833-pr-advisor-followup
cv Aug 27, 2026
3aa719f
merge: resolve conflicts with main
github-actions[bot] Aug 27, 2026
0324c5a
merge: resolve conflicts with main
github-actions[bot] Aug 28, 2026
f2a466f
merge: resolve conflicts with main
github-actions[bot] Aug 28, 2026
3531dd0
merge: resolve conflicts with main
github-actions[bot] Aug 28, 2026
5539db0
merge: resolve conflicts with main
github-actions[bot] Aug 28, 2026
4f2ba85
merge: resolve conflicts with main
github-actions[bot] Aug 28, 2026
b1518cd
merge: resolve conflicts with main
github-actions[bot] Aug 28, 2026
6f084f1
merge: resolve conflicts with main
github-actions[bot] Aug 29, 2026
1ab8faf
merge: resolve conflicts with main
github-actions[bot] Aug 29, 2026
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
2 changes: 1 addition & 1 deletion ci/source-architecture-budget.json
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
13 changes: 13 additions & 0 deletions scripts/checks/layer-import-boundaries.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
18 changes: 6 additions & 12 deletions scripts/checks/openshell-policy-mutation-read.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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"),
],
},
Expand All @@ -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"),
],
},
Expand All @@ -140,6 +133,7 @@ export interface DiscoveredPolicyReadSite {
}

const POLICY_GET_BUILDERS = new Map<string, PolicyReadView>([
["buildGlobalPolicyGetFullJsonArgs", "full"],
["buildPolicyGetCommand", "base"],
["buildPolicyGetArgs", "base"],
["buildPolicyGetFullCommand", "full"],
Expand Down
89 changes: 3 additions & 86 deletions src/lib/actions/sandbox/destroy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<boolean> {
const decision = resolveDestroyGatewayCleanupDecision(options, {
nonInteractive: isNonInteractiveEnv(),
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -713,7 +629,8 @@ async function destroySandboxUnlocked(
let destructiveResult: Awaited<ReturnType<typeof executeSandboxDestroy>>;
try {
destructiveResult = await executeSandboxDestroy({
cleanupShieldsArtifacts: cleanupShieldsDestroyArtifacts,
cleanupShieldsArtifacts: (name) =>
cleanupShieldsDestroyArtifacts(name, { warn: defaultDestroyWarn }),
cliName: CLI_NAME,
force: normalized.force === true,
getSandbox: registry.getSandbox,
Expand Down
57 changes: 55 additions & 2 deletions src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
(
Expand Down Expand Up @@ -57,6 +58,8 @@ const reserveSandboxInferenceRouteMock = vi.fn((name: string, route: Record<stri
});
const restoreSandboxStateMock = vi.fn();
const captureSnapshotRestoreAuthorityMock = vi.fn();
const cleanupSandboxServicesMock = vi.fn();
const cleanupShieldsDestroyArtifactsMock = vi.fn();
const streamSandboxCreateMock = vi.fn<SnapshotStreamSandboxCreateMock>(async () => ({
status: 7,
output: "create failed before registry write",
Expand Down Expand Up @@ -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", () => ({
Expand Down Expand Up @@ -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 })),
}));
Expand All @@ -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",
Expand Down Expand Up @@ -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<typeof getLatestBackup>);
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();
});
});
10 changes: 9 additions & 1 deletion src/lib/actions/sandbox/snapshot-restore-test-fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> | null),
withTimerBoundMock: vi.fn(
Expand Down Expand Up @@ -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) =>
Expand Down Expand Up @@ -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" });
Expand Down
Loading