Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
53 changes: 53 additions & 0 deletions src/lib/actions/sandbox/policy-channel-conflict.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1065,7 +1065,11 @@ describe("Teams host-forward lifecycle (PRA-2)", () => {

await startSandboxChannel("alpha", { channel: "teams" });

expect(applyPresetMock).toHaveBeenCalledWith("alpha", "teams");
expect(rebuildSandboxMock).toHaveBeenCalledWith("alpha", ["--yes"]);
expect(applyPresetMock.mock.invocationCallOrder[0]).toBeLessThan(
rebuildSandboxMock.mock.invocationCallOrder[0],
);
expect(ensureMessagingHostForwardAfterRebuildMock).toHaveBeenCalledWith(
"alpha",
expect.any(Object),
Expand All @@ -1079,6 +1083,55 @@ describe("Teams host-forward lifecycle (PRA-2)", () => {
label: "Microsoft Teams webhook",
});
});

it("channels start reapplies its policy before a non-interactive rebuild is queued", async () => {
process.env.NEMOCLAW_NON_INTERACTIVE = "1";
arrangeRegistry({ current: makeTeamsEntry("alpha", { disabled: true }) });
getDisabledChannelsMock.mockReturnValue(["teams"]);

await startSandboxChannel("alpha", { channel: "teams" });

expect(applyPresetMock).toHaveBeenCalledWith("alpha", "teams");
expect(rebuildSandboxMock).not.toHaveBeenCalled();
expect(loggedText()).toContain("Change queued");
});

it("channels start restores the disabled plan and skips rebuild when its policy preset fails", async () => {
const current = makeTeamsEntry("alpha", { disabled: true });
arrangeRegistry({ current });
getDisabledChannelsMock.mockImplementation(
() => current.messaging?.plan.disabledChannels ?? [],
);
updateSandboxMock.mockImplementation((_name: string, updates: Partial<SandboxEntry>) => {
Object.assign(current, updates);
return true;
});
applyPresetMock.mockReturnValue(false);

await expect(startSandboxChannel("alpha", { channel: "teams" })).rejects.toThrow(
"process.exit(1)",
);

expect(applyPresetMock).toHaveBeenCalledWith("alpha", "teams");
expect(registry.getDisabledChannels("alpha")).toContain("teams");
expect(rebuildSandboxMock).not.toHaveBeenCalled();
expect(loggedText()).toContain("channels start teams");
});

it("channels start prints recovery guidance when policy and disabled-plan rollback both fail", async () => {
arrangeRegistry({ current: makeTeamsEntry("alpha", { disabled: true }) });
getDisabledChannelsMock.mockReturnValue(["teams"]);
applyPresetMock.mockReturnValue(false);
updateSandboxMock.mockReturnValueOnce(true).mockReturnValueOnce(false);

await expect(startSandboxChannel("alpha", { channel: "teams" })).rejects.toThrow(
"process.exit(1)",
);

expect(rebuildSandboxMock).not.toHaveBeenCalled();
expect(loggedText()).toContain("Could not restore 'teams' to disabled state");
expect(loggedText()).toContain("nemoclaw alpha channels stop teams");
});
});

function mockBridgeHealthExec(options: { config: unknown; log: string }): void {
Expand Down
25 changes: 25 additions & 0 deletions src/lib/actions/sandbox/policy-channel-remove-flow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,29 @@ describe("policy channel remove/enable flows", () => {
);
expect(exitSpy).not.toHaveBeenCalled();
});

it("supports start dry runs without applying a preset or persisting the enabled plan", async () => {
const registry = requireDist("../../state/registry.js");
const policies = requireDist("../../policy/index.js");
const rebuild = requireDist("./rebuild.js");
vi.spyOn(registry, "getSandbox").mockReturnValue({ name: "alpha" });
vi.spyOn(registry, "getConfiguredMessagingChannelsFromEntry").mockReturnValue(["telegram"]);
vi.spyOn(registry, "getDisabledChannels").mockReturnValue(["telegram"]);
const updateSandboxSpy = vi.spyOn(registry, "updateSandbox");
const applyPresetSpy = vi.spyOn(policies, "applyPreset");
const rebuildSpy = vi.spyOn(rebuild, "rebuildSandbox");
const policyChannel = requireDist(policyChannelModulePath) as PolicyChannelModule;

await expect(
policyChannel.startSandboxChannel("alpha", { channel: "telegram", dryRun: true }),
).resolves.toBeUndefined();

expect(logSpy.mock.calls.flat().join("\n")).toContain(
"--dry-run: would start channel 'telegram' for 'alpha'.",
);
expect(applyPresetSpy).not.toHaveBeenCalled();
expect(updateSandboxSpy).not.toHaveBeenCalled();
expect(rebuildSpy).not.toHaveBeenCalled();
expect(exitSpy).not.toHaveBeenCalled();
});
});
29 changes: 24 additions & 5 deletions src/lib/actions/sandbox/policy-channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { type AgentDefinition, loadAgent } from "../../agent/defs";
import { CLI_DISPLAY_NAME, CLI_NAME } from "../../cli/branding";
import { prompt as askPrompt, getCredential } from "../../credentials/store";
import { recoverNamedGatewayRuntime } from "../../gateway-runtime-action";
import { getSandboxTargetGatewayName } from "./gateway-target";
import {
type ChannelManifest,
createBuiltInChannelManifestRegistry,
Expand All @@ -30,6 +29,7 @@ import {
} from "../../messaging";
import { hydrateMessagingChannelConfig } from "../../messaging-channel-config";
import { hashCredential } from "../../security/credential-hash";
import { getSandboxTargetGatewayName } from "./gateway-target";

const { isNonInteractive } = require("../../onboard") as { isNonInteractive: () => boolean };
const onboardProviders = require("../../onboard/providers");
Expand Down Expand Up @@ -60,10 +60,10 @@ import {
} from "../../sandbox/channels";
import * as registry from "../../state/registry";
import { isDockerRuntimeDown, printDockerRuntimeDownGuidance } from "./gateway-failure-classifier";
import { ensureMessagingHostForwardAfterRebuild } from "./messaging-host-forward-lifecycle";
import { refreshSandboxPolicyContextFile } from "./policy-context-refresh";
import { executeSandboxCommand, executeSandboxExecCommand } from "./process-recovery";
import { rebuildSandbox } from "./rebuild";
import { ensureMessagingHostForwardAfterRebuild } from "./messaging-host-forward-lifecycle";

type ChannelMutationOptions = {
channel?: string;
Expand Down Expand Up @@ -1120,15 +1120,19 @@ async function rollbackChannelAdd(
return result;
}

export function applyChannelPresetIfAvailable(sandboxName: string, channelName: string): boolean {
export function applyChannelPresetIfAvailable(
sandboxName: string,
channelName: string,
retryAction: "add" | "start" = "add",
): boolean {
try {
const applied = policies.applyPreset(sandboxName, channelName);
if (!applied) {
console.error(
` ${YW}⚠${R} Cannot enable channel '${channelName}': policy preset failed to apply.`,
);
console.error(
` Restore the preset YAML and re-run: ${CLI_NAME} ${sandboxName} channels add ${channelName}`,
` Restore the preset YAML and re-run: ${CLI_NAME} ${sandboxName} channels ${retryAction} ${channelName}`,
);
return false;
}
Expand All @@ -1139,7 +1143,7 @@ export function applyChannelPresetIfAvailable(sandboxName: string, channelName:
const msg = err instanceof Error ? err.message : String(err);
console.error(` ${YW}⚠${R} Failed to apply '${channelName}' policy preset: ${msg}`);
console.error(
` Restore the preset YAML and re-run: ${CLI_NAME} ${sandboxName} channels add ${channelName}`,
` Restore the preset YAML and re-run: ${CLI_NAME} ${sandboxName} channels ${retryAction} ${channelName}`,
);
return false;
}
Expand Down Expand Up @@ -1426,6 +1430,21 @@ async function sandboxChannelsSetEnabled(
console.error(` Could not persist messaging plan for '${sandboxName}'.`);
process.exit(1);
}
// Rebuild persists only the presets it actually restores. Re-apply a
// restarted channel's preset before a queued or immediate rebuild so the
// registry and backup manifest carry the enabled plan's policy intent.
// If policy application fails, put the plan back in its disabled state so
// runtime configuration cannot later be rebuilt without the required egress.
if (!disabled && !applyChannelPresetIfAvailable(sandboxName, normalized, "start")) {
const rolledBack = await persistManifestChannelDisabledPlan(sandboxName, normalized, true);
if (!rolledBack) {
console.error(
` ${YW}⚠${R} Could not restore '${normalized}' to disabled state after its policy preset failed to apply.`,
);
console.error(` Re-run: ${CLI_NAME} ${sandboxName} channels stop ${normalized}`);
}
process.exit(1);
}
const state = disabled ? "disabled" : "enabled";
console.log(` ${G}✓${R} Marked ${normalized} ${state} for '${sandboxName}'.`);
const rebuilt = await promptAndRebuild(sandboxName, `${verb} '${normalized}'`);
Expand Down
Loading