From b0526006fff503a81395991c365dcd16a6020c2d Mon Sep 17 00:00:00 2001 From: San Dang Date: Thu, 15 Oct 2026 15:09:48 +0700 Subject: [PATCH 1/7] feat(onboard): add --policy-tier and pre-select NEMOCLAW_POLICY_TIER Add `nemoclaw onboard --policy-tier `. The flag selects the tier for one run in interactive and non-interactive mode, skips the interactive tier prompt, and takes precedence over NEMOCLAW_POLICY_TIER. It is rejected for the Portable profile and when resuming, where the recorded presets would silently override it. The interactive wizard now pre-selects a valid NEMOCLAW_POLICY_TIER instead of always pre-selecting Balanced. An invalid value is still ignored interactively. The default is unchanged when neither is set. Refs #13180 Signed-off-by: San Dang --- docs/reference/architecture.mdx | 2 +- docs/reference/commands.mdx | 28 +++++- docs/reference/network-policies.mdx | 10 +- src/lib/actions/onboard.test.ts | 23 +++++ src/lib/actions/onboard.ts | 16 +++- src/lib/onboard/command-policy-tier.test.ts | 95 +++++++++++++++++++ src/lib/onboard/command-support.test.ts | 18 +++- src/lib/onboard/command-support.ts | 13 ++- src/lib/onboard/command.test.ts | 2 + src/lib/onboard/command.ts | 53 +++++++++++ .../onboard/policy-selection-prompts.test.ts | 78 ++++++++++++++- src/lib/onboard/policy-selection-prompts.ts | 32 ++++++- src/lib/onboard/policy-tier-env.ts | 24 +++++ test/onboarding/presets-checkbox.test.ts | 2 + .../policy/policy-tiers-onboard.test.ts | 6 +- 15 files changed, 381 insertions(+), 21 deletions(-) create mode 100644 src/lib/onboard/command-policy-tier.test.ts diff --git a/docs/reference/architecture.mdx b/docs/reference/architecture.mdx index 9339ceeb573..429412e29f1 100644 --- a/docs/reference/architecture.mdx +++ b/docs/reference/architecture.mdx @@ -438,7 +438,7 @@ The following environment variables configure optional services and local access | `SLACK_ALLOWED_CHANNELS` | Comma-separated Slack channel IDs where channel `@mention` events are enabled (e.g. `C012AB3CD,C987ZY6XW`). Baked into the sandbox image at build time. Combine with `SLACK_ALLOWED_USERS` to restrict both channel and member. | -| `NEMOCLAW_POLICY_TIER` | Optional non-interactive policy tier selection during onboarding. | +| `NEMOCLAW_POLICY_TIER` | Optional policy tier for onboarding. Selects the tier in non-interactive mode and pre-selects it in the interactive prompt. `--policy-tier` takes precedence. | | `TAVILY_API_KEY` | Host-side input for the optional managed Tavily provider. Register it with `$$nemoclaw credentials add tavily-search --type tavily --agent dcode --credential TAVILY_API_KEY` before attaching the provider to Deep Agents. | diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 5a9687c1c95..91b5508fb3a 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -415,7 +415,7 @@ Use the stable `id` value with `$$nemoclaw onboard --profile `. Display na Run the interactive setup wizard (recommended for new installs). The wizard creates an OpenShell gateway, registers inference providers, selects the exact managed image (or builds an explicit custom Dockerfile), and creates the sandbox. Use this command for new installs and for recreating a sandbox after changes to policy or configuration. ```bash -$$nemoclaw onboard [--profile ] [--non-interactive] [--resume | --fresh] [--recreate-sandbox] [--apf-interceptor] [--gpu | --no-gpu] [--from | --from-image @sha256:] [--name ] [--host-mount ] [--sandbox-gpu | --no-sandbox-gpu] [--sandbox-gpu-device ] [--vllm-gpu-device ] [--agent ] [--agents ] [--tool-disclosure ] [--observability | --no-observability] [--control-ui-port ] [--events=jsonl] [--yes | -y] [--no-ollama-autostart] [--yes-i-accept-third-party-software] +$$nemoclaw onboard [--profile ] [--non-interactive] [--resume | --fresh] [--recreate-sandbox] [--apf-interceptor] [--gpu | --no-gpu] [--from | --from-image @sha256:] [--name ] [--host-mount ] [--sandbox-gpu | --no-sandbox-gpu] [--sandbox-gpu-device ] [--vllm-gpu-device ] [--agent ] [--agents ] [--tool-disclosure ] [--policy-tier ] [--observability | --no-observability] [--control-ui-port ] [--events=jsonl] [--yes | -y] [--no-ollama-autostart] [--yes-i-accept-third-party-software] ``` @@ -686,6 +686,18 @@ $$nemoclaw onboard --name my-assistant --recreate-sandbox --tool-disclosure dire Recreation without an explicit flag or environment value preserves the recorded setting and only falls back to `progressive` for legacy state. Resuming an interrupted session with a different explicit setting fails with a conflict instead of changing behavior mid-session. +#### `--policy-tier ` + +Select the network policy tier for this onboarding run: `restricted`, `balanced`, `open`, or `personal`. +In interactive mode, the wizard skips the tier prompt and still shows the preset review screen. +The flag works in interactive and non-interactive mode and takes precedence over `NEMOCLAW_POLICY_TIER`. +It cannot be combined with `--resume`; start with `--fresh` to choose a new tier. +For tier details, refer to [Network Policies](network-policies#policy-tiers). + +```bash +$$nemoclaw onboard --policy-tier restricted +``` + #### `--observability` and `--no-observability` @@ -873,13 +885,19 @@ Four tiers are available: After selecting a tier, the wizard shows a combined preset and access-mode screen where you can include or exclude individual presets and toggle each between read and read-write access. When Personal is selected during the current onboarding run, `personal-open-internet` is mandatory for every agent and every onboarding entry point. The picker and policy modes control only additional presets; they cannot deselect, skip, or replace Personal's required web authority. For details on tiers and the presets each includes, refer to [Network Policies](network-policies#policy-tiers). When onboarding creates a sandbox with presets, NemoClaw prints the exact finalized create-time policy scope before registering providers or creating the sandbox. NemoClaw does not persist that selection as desired policy state; later lifecycle operations read the current OpenShell policy, including host edits. -In non-interactive mode, set the tier with `NEMOCLAW_POLICY_TIER` (default: `balanced`): +To choose the tier without the prompt, pass [`--policy-tier`](#--policy-tier-tier): + +```bash +$$nemoclaw onboard --policy-tier restricted +``` + +You can also set the tier with `NEMOCLAW_POLICY_TIER` (default: `balanced`): ```bash NEMOCLAW_POLICY_TIER=restricted $$nemoclaw onboard --non-interactive --yes-i-accept-third-party-software ``` -Unset, blank, or whitespace-only `NEMOCLAW_POLICY_TIER` values use the `balanced` default. In non-interactive mode, any non-blank value must be one of `restricted`, `balanced`, `open`, or `personal`; otherwise onboarding exits before preflight, gateway, or inference side effects with an error listing the valid options. Interactive onboarding ignores an invalid environment value and shows the normal tier prompt. +Unset, blank, or whitespace-only `NEMOCLAW_POLICY_TIER` values use the `balanced` default. In non-interactive mode, `NEMOCLAW_POLICY_TIER` selects the tier, and any non-blank value must be one of `restricted`, `balanced`, `open`, or `personal`; otherwise onboarding exits before preflight, gateway, or inference side effects with an error listing the valid options. In interactive mode, a valid value pre-selects that tier in the prompt. Interactive onboarding ignores an invalid value and pre-selects `balanced`. `--policy-tier` takes precedence over `NEMOCLAW_POLICY_TIER`. `NEMOCLAW_POLICY_MODE` controls how non-interactive onboarding reconciles the tier-derived suggestions against the sandbox's currently-applied presets. The default is `suggested`, which is _additive_. Onboarding applies tier defaults and preserves any presets you previously added with [`$$nemoclaw policy add`](#$$nemoclaw-name-policy-add) across re-onboards. Use `custom` with `NEMOCLAW_POLICY_PRESETS` when you want the explicit list to be authoritative for optional presets. Onboarding removes any optional preset that is not in the list. `skip` does not add optional tier defaults and retains eligible optional presets already applied. It still applies the required preset for each messaging channel enabled during the same onboarding run so the configured channel can reach its service. For Personal, all modes still apply or retain the mandatory `personal-open-internet` preset. NemoClaw filters tier suggestions and resume selections by active agent support and the selected web search provider. During automatic suggestion and resume reconciliation, it removes stale web-search selections when they conflict with the active agent or selected provider. The Personal tier instead uses `personal-open-internet` for web transport and does not select Brave Search or Tavily Search merely to enable ordinary web fetches. This makes keyless fetches available to any sandbox binary, but it does not add a provider-free `web_search` implementation. @@ -3746,7 +3764,7 @@ For Deep Agents sandboxes, run `$$nemoclaw onboard --fresh --name The `$$nemoclaw setup` command is deprecated. Use `$$nemoclaw onboard` instead. -This command remains as a compatibility alias to `$$nemoclaw onboard` and accepts the same flags: `--profile `, `--non-interactive`, `--resume`, `--fresh`, `--recreate-sandbox`, `--apf-interceptor`, `--gpu` / `--no-gpu`, `--from`, `--from-image`, `--name`, `--host-mount`, `--sandbox-gpu` / `--no-sandbox-gpu`, `--sandbox-gpu-device`, `--vllm-gpu-device`, `--agent`, `--agents `, `--tool-disclosure `, `--observability` / `--no-observability`, `--control-ui-port`, `--yes` / `-y`, `--no-ollama-autostart`, `--yes-i-accept-third-party-software`. +This command remains as a compatibility alias to `$$nemoclaw onboard` and accepts the same flags: `--profile `, `--non-interactive`, `--resume`, `--fresh`, `--recreate-sandbox`, `--apf-interceptor`, `--gpu` / `--no-gpu`, `--from`, `--from-image`, `--name`, `--host-mount`, `--sandbox-gpu` / `--no-sandbox-gpu`, `--sandbox-gpu-device`, `--vllm-gpu-device`, `--agent`, `--agents `, `--tool-disclosure `, `--policy-tier `, `--observability` / `--no-observability`, `--control-ui-port`, `--yes` / `-y`, `--no-ollama-autostart`, `--yes-i-accept-third-party-software`. ```bash $$nemoclaw setup @@ -3759,7 +3777,7 @@ $$nemoclaw setup onboard` instead, because current OpenShell releases handle the older DGX Spark cgroup behavior. -This command remains as a compatibility alias to `$$nemoclaw onboard` and accepts the same flags: `--profile `, `--non-interactive`, `--resume`, `--fresh`, `--recreate-sandbox`, `--apf-interceptor`, `--gpu` / `--no-gpu`, `--from`, `--from-image`, `--name`, `--host-mount`, `--sandbox-gpu` / `--no-sandbox-gpu`, `--sandbox-gpu-device`, `--vllm-gpu-device`, `--agent`, `--agents `, `--tool-disclosure `, `--observability` / `--no-observability`, `--control-ui-port`, `--yes` / `-y`, `--no-ollama-autostart`, `--yes-i-accept-third-party-software`. +This command remains as a compatibility alias to `$$nemoclaw onboard` and accepts the same flags: `--profile `, `--non-interactive`, `--resume`, `--fresh`, `--recreate-sandbox`, `--apf-interceptor`, `--gpu` / `--no-gpu`, `--from`, `--from-image`, `--name`, `--host-mount`, `--sandbox-gpu` / `--no-sandbox-gpu`, `--sandbox-gpu-device`, `--vllm-gpu-device`, `--agent`, `--agents `, `--tool-disclosure `, `--policy-tier `, `--observability` / `--no-observability`, `--control-ui-port`, `--yes` / `-y`, `--no-ollama-autostart`, `--yes-i-accept-third-party-software`. ```bash $$nemoclaw setup-spark diff --git a/docs/reference/network-policies.mdx b/docs/reference/network-policies.mdx index 11cd4b49639..d0b0e7c25a2 100644 --- a/docs/reference/network-policies.mdx +++ b/docs/reference/network-policies.mdx @@ -209,13 +209,19 @@ NemoClaw-managed Anthropic inference remains mediated by OpenShell. Tier definitions are stored in `nemoclaw-blueprint/policies/tiers.yaml`. -In non-interactive mode, set the tier with `NEMOCLAW_POLICY_TIER`: +To choose the tier without the prompt, pass `--policy-tier` in interactive or non-interactive mode: + +```bash +$$nemoclaw onboard --policy-tier restricted +``` + +You can also set the tier with `NEMOCLAW_POLICY_TIER`: ```bash NEMOCLAW_POLICY_TIER=open $$nemoclaw onboard --non-interactive --yes-i-accept-third-party-software ``` -Unset, blank, or whitespace-only `NEMOCLAW_POLICY_TIER` values use the `balanced` default. In non-interactive onboarding, a non-blank value that does not match a known tier exits before preflight, gateway, or inference side effects and lists the valid options. Interactive onboarding ignores an invalid environment value and shows the normal tier prompt. +Unset, blank, or whitespace-only `NEMOCLAW_POLICY_TIER` values use the `balanced` default. In non-interactive onboarding, a non-blank value that does not match a known tier exits before preflight, gateway, or inference side effects and lists the valid options. In interactive onboarding, a valid value pre-selects that tier in the prompt, and an invalid value is ignored. `--policy-tier` takes precedence over `NEMOCLAW_POLICY_TIER`. ### Inference diff --git a/src/lib/actions/onboard.test.ts b/src/lib/actions/onboard.test.ts index 4085f1e87ff..a50e4d77a64 100644 --- a/src/lib/actions/onboard.test.ts +++ b/src/lib/actions/onboard.test.ts @@ -13,6 +13,7 @@ vi.mock("../agent/defs", () => ({ listAgents: mocks.listAgents })); vi.mock("../onboard", () => ({ onboard: mocks.onboard })); vi.mock("../onboard/command", () => ({ runOnboardCommand: mocks.runOnboardCommand })); +import { readRequestedPolicyTier } from "../onboard/policy-tier-env"; import { runOnboardAction } from "./onboard"; describe("onboard action runtime composition", () => { @@ -39,4 +40,26 @@ describe("onboard action runtime composition", () => { googlechatTunnelRuntime, }); }); + + it("scopes --policy-tier to one legacy onboarding run (#13180)", async () => { + let observed: string | null = null; + mocks.runOnboardCommand.mockImplementation( + async (deps: { + listPolicyTiers(): readonly string[]; + runOnboard(options: unknown): Promise; + }) => { + expect(deps.listPolicyTiers()).toEqual(["restricted", "balanced", "open", "personal"]); + await deps.runOnboard({ requestedPolicyTier: "restricted" }); + }, + ); + mocks.onboard.mockImplementationOnce(async () => { + observed = readRequestedPolicyTier(); + throw new Error("boom"); + }); + + await expect(runOnboardAction({ "policy-tier": "restricted" })).rejects.toThrow("boom"); + + expect(observed).toBe("restricted"); + expect(readRequestedPolicyTier()).toBeNull(); + }); }); diff --git a/src/lib/actions/onboard.ts b/src/lib/actions/onboard.ts index 9beb40d57d8..f24f42cc53b 100644 --- a/src/lib/actions/onboard.ts +++ b/src/lib/actions/onboard.ts @@ -4,7 +4,11 @@ import { loadServingCatalog } from "../inference/serving/catalog-loader"; import type { GooglechatTunnelRuntimeDeps } from "../messaging/channels/googlechat/hooks/tunnel-runtime"; import { type OnboardCommandOptions, runOnboardCommand } from "../onboard/command"; -import { type OnboardFlags, readAgentRegistryNames } from "../onboard/command-support"; +import { + ONBOARD_POLICY_TIER_VALUES, + type OnboardFlags, + readAgentRegistryNames, +} from "../onboard/command-support"; import { resolveOnboardResumeIntent } from "../onboard/session-bootstrap"; import { loadOnboardCommandResumeSession } from "../onboard/sandbox-registration"; import type { OnboardOptions } from "../onboard/types"; @@ -22,7 +26,14 @@ async function runOnboard( const { onboard } = (await import("../onboard")) as unknown as { onboard: (onboardOptions?: OnboardOptions) => Promise; }; - await onboard({ ...options, googlechatTunnelRuntime: runtimeDeps.googlechatTunnelRuntime }); + // An explicit --policy-tier makes the wizard skip its tier prompt for this run only. + const { setRequestedPolicyTier } = await import("../onboard/policy-tier-env"); + setRequestedPolicyTier(options.requestedPolicyTier ?? null); + try { + await onboard({ ...options, googlechatTunnelRuntime: runtimeDeps.googlechatTunnelRuntime }); + } finally { + setRequestedPolicyTier(null); + } } function buildOnboardCommandDeps(flags: OnboardFlags, runtimeDeps: OnboardActionRuntimeDeps) { @@ -31,6 +42,7 @@ function buildOnboardCommandDeps(flags: OnboardFlags, runtimeDeps: OnboardAction env: process.env, runOnboard: (options: OnboardCommandOptions) => runOnboard(options, runtimeDeps), listAgents: () => [...readAgentRegistryNames()], + listPolicyTiers: () => ONBOARD_POLICY_TIER_VALUES, loadServingCatalog, loadSession: loadOnboardCommandResumeSession, resolveResumeIntent: resolveOnboardResumeIntent, diff --git a/src/lib/onboard/command-policy-tier.test.ts b/src/lib/onboard/command-policy-tier.test.ts new file mode 100644 index 00000000000..c248ba5fce6 --- /dev/null +++ b/src/lib/onboard/command-policy-tier.test.ts @@ -0,0 +1,95 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; + +import { resolveOnboardOptions, runOnboardCommand } from "./command"; +import { ONBOARD_POLICY_TIER_VALUES, type OnboardFlags } from "./command-support"; + +function exitWithCode(code: number): never { + throw new Error(`exit:${code}`); +} + +function resolve( + flags: OnboardFlags, + overrides: Partial[1]> = {}, +) { + return resolveOnboardOptions(flags, { + env: {}, + error: () => {}, + exit: exitWithCode, + listPolicyTiers: () => ONBOARD_POLICY_TIER_VALUES, + ...overrides, + }); +} + +describe("onboard --policy-tier (#13180)", () => { + it("normalizes --policy-tier and rejects unknown, Portable, or resumed use (#13180)", () => { + expect(resolve({ "policy-tier": " Restricted " }).requestedPolicyTier).toBe("restricted"); + expect(resolve({}).requestedPolicyTier).toBeNull(); + + const errors: string[] = []; + const error = (message?: string) => errors.push(String(message)); + expect(() => resolve({ "policy-tier": "locked" }, { error })).toThrow("exit:1"); + expect(() => + resolve({ "policy-tier": "open", "experimental-profile": "portable" }, { error }), + ).toThrow("exit:1"); + expect(() => resolve({ "policy-tier": "open", resume: true }, { error })).toThrow("exit:1"); + expect(errors).toEqual([ + " Unknown policy tier: locked. Valid: restricted, balanced, open, personal", + " --policy-tier cannot be used with the Portable profile.", + " --policy-tier cannot be used when resuming onboarding; use --fresh to choose a new tier.", + ]); + }); + + it("scopes --policy-tier over NEMOCLAW_POLICY_TIER for one onboarding run (#13180)", async () => { + const env: NodeJS.ProcessEnv = { NEMOCLAW_POLICY_TIER: "open" }; + let observed: string | undefined; + await runOnboardCommand({ + flags: { "policy-tier": "restricted" }, + env, + runOnboard: async (options) => { + observed = env.NEMOCLAW_POLICY_TIER; + expect(options.requestedPolicyTier).toBe("restricted"); + }, + }); + expect(observed).toBe("restricted"); + expect(env.NEMOCLAW_POLICY_TIER).toBe("open"); + + const unsetEnv: NodeJS.ProcessEnv = {}; + await runOnboardCommand({ + flags: { "policy-tier": "personal" }, + env: unsetEnv, + runOnboard: async () => { + expect(unsetEnv.NEMOCLAW_POLICY_TIER).toBe("personal"); + }, + }); + expect(Object.prototype.hasOwnProperty.call(unsetEnv, "NEMOCLAW_POLICY_TIER")).toBe(false); + }); + + it("restores NEMOCLAW_POLICY_TIER after a failed onboarding run", async () => { + const env: NodeJS.ProcessEnv = {}; + await expect( + runOnboardCommand({ + flags: { "policy-tier": "restricted" }, + env, + runOnboard: async () => { + throw Object.assign(new Error("boom"), { code: "EOF" }); + }, + error: () => {}, + exit: exitWithCode, + }), + ).rejects.toThrow("exit:"); + expect(Object.prototype.hasOwnProperty.call(env, "NEMOCLAW_POLICY_TIER")).toBe(false); + }); + + it("leaves the tier prompt in charge when the flag is absent", async () => { + await runOnboardCommand({ + flags: {}, + env: { NEMOCLAW_POLICY_TIER: "open" }, + runOnboard: async (options) => { + expect(options.requestedPolicyTier).toBeNull(); + }, + }); + }); +}); diff --git a/src/lib/onboard/command-support.test.ts b/src/lib/onboard/command-support.test.ts index fcef7cae4b8..7b89abd81ae 100644 --- a/src/lib/onboard/command-support.test.ts +++ b/src/lib/onboard/command-support.test.ts @@ -3,7 +3,13 @@ import { afterEach, describe, expect, it } from "vitest"; -import { buildOnboardFlags, onboardUsage, setAgentRegistryReaderForTest } from "./command-support"; +import { listTiers } from "../policy/tiers"; +import { + buildOnboardFlags, + ONBOARD_POLICY_TIER_VALUES, + onboardUsage, + setAgentRegistryReaderForTest, +} from "./command-support"; afterEach(() => { setAgentRegistryReaderForTest(null); @@ -56,6 +62,16 @@ describe("buildOnboardFlags --apf-interceptor help", () => { }); }); +describe("buildOnboardFlags --policy-tier help (#13180)", () => { + it("offers exactly the tiers defined in tiers.yaml", () => { + const flags = buildOnboardFlags(); + + expect(flags["policy-tier"].options).toEqual(listTiers().map((tier) => tier.name)); + expect([...ONBOARD_POLICY_TIER_VALUES]).toEqual(listTiers().map((tier) => tier.name)); + expect(onboardUsage.join(" ")).toContain("--policy-tier "); + }); +}); + describe("buildOnboardFlags --events help", () => { it("exposes the JSONL observer only on the canonical onboard command", () => { const onboardFlags = buildOnboardFlags({ includeEvents: true }); diff --git a/src/lib/onboard/command-support.ts b/src/lib/onboard/command-support.ts index 7624042e8ef..12989026cea 100644 --- a/src/lib/onboard/command-support.ts +++ b/src/lib/onboard/command-support.ts @@ -7,6 +7,10 @@ import { describeAgentFlag } from "./agent-flag-help"; import { PORTABLE_EXPERIMENTAL_PROFILE } from "./docker-driver-platform"; import { NOTICE_ACCEPT_FLAG, NOTICE_ACCEPT_FLAG_NAME } from "./usage-notice"; +// Mirrors nemoclaw-blueprint/policies/tiers.yaml. Kept inline so command help +// does not load the tier registry; a unit test keeps the two lists aligned. +export const ONBOARD_POLICY_TIER_VALUES = ["restricted", "balanced", "open", "personal"] as const; + type AgentRegistryReader = () => readonly string[]; let agentRegistryReaderForTest: AgentRegistryReader | null = null; @@ -47,7 +51,7 @@ function agentFlagDescription(): string { } export const onboardUsage = [ - `onboard [--profile ] [--non-interactive] [--resume | --fresh] [--recreate-sandbox] [--apf-interceptor] [--gpu | --no-gpu] [--from | --from-image ] [--name ] [--host-mount ] [--sandbox-gpu | --no-sandbox-gpu] [--sandbox-gpu-device ] [--vllm-gpu-device ] [--agent ] [--agents ] [--tool-disclosure ] [--observability | --no-observability] [--control-ui-port ] [--events=jsonl] [--yes | -y] [--no-ollama-autostart] [${NOTICE_ACCEPT_FLAG}]`, + `onboard [--profile ] [--non-interactive] [--resume | --fresh] [--recreate-sandbox] [--apf-interceptor] [--gpu | --no-gpu] [--from | --from-image ] [--name ] [--host-mount ] [--sandbox-gpu | --no-sandbox-gpu] [--sandbox-gpu-device ] [--vllm-gpu-device ] [--agent ] [--agents ] [--tool-disclosure ] [--policy-tier ] [--observability | --no-observability] [--control-ui-port ] [--events=jsonl] [--yes | -y] [--no-ollama-autostart] [${NOTICE_ACCEPT_FLAG}]`, ]; export const onboardExamples = [ @@ -60,6 +64,7 @@ export const onboardExamples = [ "<%= config.bin %> onboard --from-image registry.example.com/agent@sha256: --name alpha", "<%= config.bin %> onboard --name alpha --host-mount /home/user/project:/sandbox/project", "<%= config.bin %> onboard --agents ./agents.yaml", + "<%= config.bin %> onboard --policy-tier restricted", "<%= config.bin %> onboard --sandbox-gpu --sandbox-gpu-device nvidia.com/gpu=0", `<%= config.bin %> onboard --non-interactive --yes --name alpha ${NOTICE_ACCEPT_FLAG}`, ]; @@ -85,6 +90,7 @@ export type OnboardFlags = { agent?: string; agents?: string; "tool-disclosure"?: ToolDisclosure; + "policy-tier"?: string; observability?: boolean; "control-ui-port"?: number; events?: "jsonl"; @@ -162,6 +168,11 @@ export function buildOnboardFlags(options: { includeEvents?: boolean } = {}): Re "Choose progressive tool discovery or direct exposure of all session-authorized tools", options: [...TOOL_DISCLOSURE_VALUES], }), + "policy-tier": Flags.string({ + description: + "Select the network policy tier without the tier prompt (overrides NEMOCLAW_POLICY_TIER)", + options: [...ONBOARD_POLICY_TIER_VALUES], + }), observability: Flags.boolean({ allowNo: true, description: diff --git a/src/lib/onboard/command.test.ts b/src/lib/onboard/command.test.ts index 3199aed0def..7d5760a29dc 100644 --- a/src/lib/onboard/command.test.ts +++ b/src/lib/onboard/command.test.ts @@ -305,6 +305,7 @@ describe("onboard command options", () => { agent: "langchain-deepagents-code", agentsManifest: null, toolDisclosure: "direct", + requestedPolicyTier: null, observabilityEnabled: true, controlUiPort: 18790, deferProcessExit: true, @@ -353,6 +354,7 @@ describe("onboard command options", () => { agent: null, agentsManifest: null, toolDisclosure: null, + requestedPolicyTier: null, observabilityEnabled: null, controlUiPort: null, deferProcessExit: true, diff --git a/src/lib/onboard/command.ts b/src/lib/onboard/command.ts index b89fe8ced58..55f279cb79c 100644 --- a/src/lib/onboard/command.ts +++ b/src/lib/onboard/command.ts @@ -84,6 +84,8 @@ export interface OnboardCommandOptions { agent: string | null; agentsManifest: string | null; toolDisclosure: ToolDisclosure | null; + /** Operator-selected `--policy-tier`; skips the tier prompt when set. */ + requestedPolicyTier: string | null; observabilityEnabled: boolean | null; controlUiPort: number | null; gpu: boolean; @@ -104,6 +106,7 @@ export interface ResolveOnboardOptionsDeps { arch?: NodeJS.Architecture; runtimeProviders?: import("./runtime-provider/access").RuntimeProviderBundleRegistry; listAgents?: () => string[]; + listPolicyTiers?: () => readonly string[]; listServingProfiles?: () => ServingProfileListEntry[]; loadServingCatalog?: () => CompiledServingCatalog; loadSession?: () => { @@ -472,6 +475,28 @@ function resolveOnboardToolDisclosure( } } +function resolveRequestedPolicyTier( + requested: string | undefined, + experimentalProfile: ExperimentalOnboardProfile | null, + resume: boolean, + deps: ResolveOnboardOptionsDeps, +): string | null { + if (requested === undefined) return null; + const name = requested.trim().toLowerCase(); + const knownTiers = deps.listPolicyTiers?.() ?? []; + if (knownTiers.length > 0 && !knownTiers.includes(name)) { + fail(deps, ` Unknown policy tier: ${requested}. Valid: ${knownTiers.join(", ")}`); + } + if (experimentalProfile) fail(deps, " --policy-tier cannot be used with the Portable profile."); + if (resume) { + fail( + deps, + " --policy-tier cannot be used when resuming onboarding; use --fresh to choose a new tier.", + ); + } + return name; +} + function resolveExternalImageReference( value: string | undefined, deps: ResolveOnboardOptionsDeps, @@ -503,6 +528,12 @@ export function resolveOnboardOptions( if (experimentalProfile === PORTABLE_EXPERIMENTAL_PROFILE && fromImage) { fail(deps, " --from-image cannot be used with the Portable profile."); } + const requestedPolicyTier = resolveRequestedPolicyTier( + flags["policy-tier"], + experimentalProfile, + resume, + deps, + ); return { tempManagedRuntime: flags["temp-managed-runtime"] === true, tempManagedRuntimeCatalog: resolveFileOption( @@ -528,6 +559,7 @@ export function resolveOnboardOptions( agent, agentsManifest: resolveAgentsManifest(flags.agents, agent, deps), toolDisclosure, + requestedPolicyTier, observabilityEnabled: typeof flags.observability === "boolean" ? flags.observability : null, controlUiPort: flags["control-ui-port"] ?? null, gpu: flags.gpu === true, @@ -718,6 +750,24 @@ function restoreOnboardCommandEnvironment( } } +// Scope `--policy-tier` to one run. The flag overrides an ambient +// NEMOCLAW_POLICY_TIER so every non-interactive tier consumer sees the same +// choice. The onboard action separately tells the wizard to skip its prompt. +function applyRequestedPolicyTierEnvironment( + options: OnboardCommandOptions, + env: NodeJS.ProcessEnv, +): () => void { + const tier = options.requestedPolicyTier; + if (!tier) return () => {}; + const present = Object.prototype.hasOwnProperty.call(env, "NEMOCLAW_POLICY_TIER"); + const previous = env.NEMOCLAW_POLICY_TIER; + env.NEMOCLAW_POLICY_TIER = tier; + return () => { + if (present) env.NEMOCLAW_POLICY_TIER = previous ?? ""; + else delete env.NEMOCLAW_POLICY_TIER; + }; +} + async function runOnboardCommandAttempt( deps: RunOnboardCommandDeps, env: NodeJS.ProcessEnv, @@ -729,6 +779,7 @@ async function runOnboardCommandAttempt( resumeIntent, }); let restoreServingProfileEnvironment = () => {}; + let restorePolicyTierEnvironment = () => {}; const environmentSnapshot: OnboardCommandEnvironmentSnapshot = { agentsManifest: env.NEMOCLAW_EXTRA_AGENTS_JSON, toolDisclosure: env[TOOL_DISCLOSURE_ENV], @@ -757,11 +808,13 @@ async function runOnboardCommandAttempt( if (options.noOllamaAutostart && !options.experimentalProfile) { env.NEMOCLAW_OLLAMA_NO_AUTOSTART = "1"; } + restorePolicyTierEnvironment = applyRequestedPolicyTierEnvironment(options, env); await withCredentialOverrides(activation.credentialOverrides, () => deps.runOnboard(options)); return "complete"; } catch (error) { return handleOnboardCommandAttemptError(error, deps, attempt); } finally { + restorePolicyTierEnvironment(); restoreOnboardCommandEnvironment( env, options, diff --git a/src/lib/onboard/policy-selection-prompts.test.ts b/src/lib/onboard/policy-selection-prompts.test.ts index f07d2969460..6002958655e 100644 --- a/src/lib/onboard/policy-selection-prompts.test.ts +++ b/src/lib/onboard/policy-selection-prompts.test.ts @@ -67,17 +67,24 @@ function createHarness({ stdinTTY = true, stdoutTTY = true, promptReplies = [], + envTier = null, + explicitTier = null, + nonInteractive = false, }: { tiers?: TierDefinition[]; stdinTTY?: boolean; stdoutTTY?: boolean; promptReplies?: string[]; + envTier?: string | null; + explicitTier?: string | null; + nonInteractive?: boolean; } = {}) { const stdin = new FakeInput(stdinTTY); const stdout = new FakeOutput(stdoutTTY); const processEvents = new EventEmitter(); const markCancelled = vi.fn(); const prompt = vi.fn(async () => promptReplies.shift() ?? ""); + const note = vi.fn(); const helpers = createPolicySelectionPromptHelpers({ tiers: { @@ -85,10 +92,12 @@ function createHarness({ getTier: (name) => tiers.find((tier) => tier.name === name) ?? null, }, policyTierEnv: { - resolvePolicyTierFromEnv: () => "balanced", + resolvePolicyTierFromEnv: () => envTier ?? "balanced", + readPolicyTierPreselectionFromEnv: () => envTier, + readRequestedPolicyTier: () => explicitTier, }, - isNonInteractive: () => false, - note: vi.fn(), + isNonInteractive: () => nonInteractive, + note, prompt, selectFromNumberedMenuOrExit, makeOnboardCancelExit: (rollback, cleanup, exit) => () => { @@ -103,7 +112,7 @@ function createHarness({ processEvents, }); - return { helpers, markCancelled, processEvents, prompt, stdin, stdout }; + return { helpers, markCancelled, note, processEvents, prompt, stdin, stdout }; } afterEach(() => { @@ -134,6 +143,67 @@ describe("createPolicySelectionPromptHelpers", () => { await expect(helpers.selectPolicyTier()).resolves.toBe("balanced"); }); + it("selectPolicyTier pre-selects NEMOCLAW_POLICY_TIER in the non-TTY fallback (#13180)", async () => { + vi.spyOn(console, "log").mockImplementation(() => undefined); + const { helpers, note, prompt } = createHarness({ + stdinTTY: false, + stdoutTTY: false, + promptReplies: [""], + envTier: "restricted", + }); + + await expect(helpers.selectPolicyTier()).resolves.toBe("restricted"); + expect(prompt).toHaveBeenCalledWith(expect.stringContaining("(default: 1 restricted)")); + expect(note).toHaveBeenCalledWith(expect.stringContaining("NEMOCLAW_POLICY_TIER: Restricted")); + }); + + it("selectPolicyTier pre-selects NEMOCLAW_POLICY_TIER in the raw-mode TUI (#13180)", async () => { + const { helpers, stdin, stdout } = createHarness({ envTier: "open" }); + + const selection = helpers.selectPolicyTier(); + stdin.emit("data", "\r"); + + await expect(selection).resolves.toBe("open"); + expect(stdout.chunks.join("")).toContain("> [✓] Open"); + }); + + it("selectPolicyTier ignores an unknown interactive NEMOCLAW_POLICY_TIER (#13180)", async () => { + vi.spyOn(console, "log").mockImplementation(() => undefined); + const { helpers, note } = createHarness({ + stdinTTY: false, + stdoutTTY: false, + promptReplies: [""], + envTier: "locked", + }); + + await expect(helpers.selectPolicyTier()).resolves.toBe("balanced"); + expect(note).toHaveBeenCalledWith( + expect.stringContaining("Ignoring unknown NEMOCLAW_POLICY_TIER 'locked'"), + ); + }); + + it("selectPolicyTier uses --policy-tier without prompting (#13180)", async () => { + const { helpers, note, prompt, stdin } = createHarness({ + explicitTier: "restricted", + envTier: "open", + }); + + await expect(helpers.selectPolicyTier()).resolves.toBe("restricted"); + expect(prompt).not.toHaveBeenCalled(); + expect(stdin.setRawMode).not.toHaveBeenCalled(); + expect(note).toHaveBeenCalledWith(" Policy tier: Restricted (from --policy-tier)"); + }); + + it("selectPolicyTier prefers --policy-tier over the non-interactive env tier (#13180)", async () => { + const { helpers } = createHarness({ + explicitTier: "restricted", + envTier: "open", + nonInteractive: true, + }); + + await expect(helpers.selectPolicyTier()).resolves.toBe("restricted"); + }); + it("selectTierPresetsAndAccess honors comma-separated non-TTY allowlists", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); diff --git a/src/lib/onboard/policy-selection-prompts.ts b/src/lib/onboard/policy-selection-prompts.ts index bf9ff28d0be..a224efe6efa 100644 --- a/src/lib/onboard/policy-selection-prompts.ts +++ b/src/lib/onboard/policy-selection-prompts.ts @@ -34,6 +34,9 @@ export interface PolicySelectionPromptDeps { }; policyTierEnv: { resolvePolicyTierFromEnv(): string; + readPolicyTierPreselectionFromEnv(): string | null; + /** Tier chosen with `onboard --policy-tier`; skips the tier prompt when set. */ + readRequestedPolicyTier(): string | null; }; isNonInteractive(): boolean; note(message: string): void; @@ -123,23 +126,48 @@ export function createPolicySelectionPromptHelpers(deps: PolicySelectionPromptDe /** * Prompt the user to select a policy tier (restricted / balanced / open / personal). * Uses the same radio-style TUI as presetsCheckboxSelector (single-select). + * An explicit `--policy-tier` choice skips the prompt in every mode. * In non-interactive mode reads NEMOCLAW_POLICY_TIER (default: balanced). + * In interactive mode a valid NEMOCLAW_POLICY_TIER pre-selects that tier. * Returns the tier name string. */ async function selectPolicyTier(): Promise { const allTiers = tiers.listTiers(); - const defaultTier = allTiers.find((tier) => tier.name === "balanced") ?? allTiers[1]; + const balancedTier = allTiers.find((tier) => tier.name === "balanced") ?? allTiers[1]; - if (!defaultTier) { + if (!balancedTier) { throw new Error("No policy tiers are configured."); } + const explicitName = policyTierEnv.readRequestedPolicyTier(); + if (explicitName) { + const explicitTier = tiers.getTier(explicitName); + if (!explicitTier) { + throw new Error(`Unknown policy tier from --policy-tier: ${explicitName}`); + } + note(` Policy tier: ${explicitTier.label} (from --policy-tier)`); + return explicitTier.name; + } + if (isNonInteractive()) { const name = policyTierEnv.resolvePolicyTierFromEnv(); note(` [non-interactive] Policy tier: ${name}`); return name; } + const envName = policyTierEnv.readPolicyTierPreselectionFromEnv(); + const envTier = envName ? allTiers.find((tier) => tier.name === envName) : undefined; + if (envName && !envTier) { + note( + ` Ignoring unknown NEMOCLAW_POLICY_TIER '${envName}'. Valid: ${allTiers + .map((tier) => tier.name) + .join(", ")}`, + ); + } else if (envTier) { + note(` Pre-selected policy tier from NEMOCLAW_POLICY_TIER: ${envTier.label}`); + } + const defaultTier = envTier ?? balancedTier; + const RADIO_ON = useColor ? "[\x1b[32m✓\x1b[0m]" : "[✓]"; const RADIO_OFF = useColor ? "\x1b[2m[ ]\x1b[0m" : "[ ]"; diff --git a/src/lib/onboard/policy-tier-env.ts b/src/lib/onboard/policy-tier-env.ts index 5e7471a8818..47bdb092388 100644 --- a/src/lib/onboard/policy-tier-env.ts +++ b/src/lib/onboard/policy-tier-env.ts @@ -26,6 +26,30 @@ export function resolvePolicyTierFromEnv(): string { return name; } +// Tier selected with `onboard --policy-tier`. The onboard command sets it for +// one run and clears it afterward; null means the wizard asks for the tier. +let requestedPolicyTier: string | null = null; + +export function setRequestedPolicyTier(name: string | null): void { + requestedPolicyTier = name; +} + +export function readRequestedPolicyTier(): string | null { + return requestedPolicyTier; +} + +/** + * Read NEMOCLAW_POLICY_TIER for interactive pre-selection. Returns the + * normalized name, or null when the env var is unset or blank. Does not + * validate or exit: the interactive wizard ignores an unknown value and keeps + * its normal default. + */ +export function readPolicyTierPreselectionFromEnv(): string | null { + const raw = process.env.NEMOCLAW_POLICY_TIER; + const trimmed = typeof raw === "string" ? raw.trim().toLowerCase() : ""; + return trimmed || null; +} + /** * Early gate intended for the top of onboard(): runs the validation * only when the env var is explicitly set to a non-blank value, so the diff --git a/test/onboarding/presets-checkbox.test.ts b/test/onboarding/presets-checkbox.test.ts index 05bb74390ef..9fbd142e67d 100644 --- a/test/onboarding/presets-checkbox.test.ts +++ b/test/onboarding/presets-checkbox.test.ts @@ -51,6 +51,8 @@ async function runCheckboxSelector( }, policyTierEnv: { resolvePolicyTierFromEnv: () => "balanced", + readPolicyTierPreselectionFromEnv: () => null, + readRequestedPolicyTier: () => null, }, isNonInteractive: () => false, note: () => undefined, diff --git a/test/runtime/policy/policy-tiers-onboard.test.ts b/test/runtime/policy/policy-tiers-onboard.test.ts index 540c1a1b559..c902eca3b40 100644 --- a/test/runtime/policy/policy-tiers-onboard.test.ts +++ b/test/runtime/policy/policy-tiers-onboard.test.ts @@ -22,7 +22,7 @@ import { createPolicySelectionPromptHelpers, type PolicySelectionPromptDeps, } from "../../../src/lib/onboard/policy-selection-prompts"; -import { resolvePolicyTierFromEnv } from "../../../src/lib/onboard/policy-tier-env"; +import * as policyTierEnv from "../../../src/lib/onboard/policy-tier-env"; import * as policy from "../../../src/lib/policy"; import * as tiers from "../../../src/lib/policy/tiers"; @@ -67,7 +67,7 @@ function createPromptHarness({ } = {}) { const deps: PolicySelectionPromptDeps = { tiers, - policyTierEnv: { resolvePolicyTierFromEnv }, + policyTierEnv, isNonInteractive: () => nonInteractive, note: (message) => notes.push(message), prompt: async (question) => { @@ -319,7 +319,7 @@ describe("policy tier selection", () => { throw new Error(`process.exit(${String(code)})`); }) as never); - assert.throws(() => resolvePolicyTierFromEnv(), /process\.exit\(1\)/); + assert.throws(() => policyTierEnv.resolvePolicyTierFromEnv(), /process\.exit\(1\)/); assert.equal(exit.mock.calls[0]?.[0], 1); assert.match( errors.join("\n"), From 1b35f6a3a7c8c20edd0c4a6872b41412025d84a3 Mon Sep 17 00:00:00 2001 From: San Dang Date: Thu, 15 Oct 2026 18:03:15 +0700 Subject: [PATCH 2/7] fix(onboard): carry --policy-tier on the onboarding run Replace the process-global requested-tier state and the temporary NEMOCLAW_POLICY_TIER override with a per-run request. The tier now flows from the onboard options through the runtime-control requests to the sandbox phase, which passes it to create-time policy resolution, and to the policy phase, which applies it without the tier prompt. Add a live interactive E2E case that runs onboard with --policy-tier restricted against a conflicting NEMOCLAW_POLICY_TIER=open, asserts the tier selector is skipped, and checks that the created sandbox policy does not apply the Open-tier npm default. Record the three maintainer-approved live assertions in the assertion budget, add the candidate growth exception for local hooks, and raise the target time budget for the second onboarding. Refs #13180 Signed-off-by: San Dang --- ci/e2e-assertion-budget.json | 16 +- ci/e2e-assertion-growth-exceptions.json | 6 +- src/lib/actions/onboard.test.ts | 22 +-- src/lib/actions/onboard.ts | 9 +- src/lib/onboard.ts | 4 +- src/lib/onboard/command-policy-tier.test.ts | 39 +---- src/lib/onboard/command.ts | 21 --- src/lib/onboard/machine/core-flow-phases.ts | 3 + src/lib/onboard/machine/final-flow-phases.ts | 3 + .../onboard/machine/handlers/policies.test.ts | 16 ++ src/lib/onboard/machine/handlers/policies.ts | 5 +- .../sandbox-create-intent-boundary.test.ts | 16 ++ src/lib/onboard/machine/handlers/sandbox.ts | 9 + .../onboard/policy-selection-prompts.test.ts | 29 +--- src/lib/onboard/policy-selection-prompts.ts | 13 -- src/lib/onboard/policy-selection.ts | 4 + src/lib/onboard/policy-tier-env.ts | 12 -- src/lib/onboard/runtime-control-flow.test.ts | 14 ++ src/lib/onboard/runtime-control-flow.ts | 13 ++ src/lib/onboard/types.ts | 2 + .../onboard-policy-preset-sequencing.test.ts | 159 +++++++++++++++--- test/onboarding/presets-checkbox.test.ts | 1 - .../policy/policy-tiers-onboard.test.ts | 14 ++ tools/e2e/target-catalogue.mts | 2 +- 24 files changed, 274 insertions(+), 158 deletions(-) diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index 2db5c54bcc5..36a8bf8b50f 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -1,5 +1,5 @@ { - "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nInitial no-growth baseline for issue #10934 and Epic #10920. The epic reference remains fixed at fe18b2f004e2304c52db33cf7bb5895828197f9a. Current main is lower because #10722 removed the live Shields assertion suites before this ratchet landed. PR #10341 adds the accepted public deferred-install and same-home credential continuation boundary for Hermes and Deep Agents Code; existing per-file budgets remain unchanged. PR #13055 adds five explicitly approved assertions for the native Deep Agents Code OpenRouter request in the existing hosted OpenRouter target.", + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nInitial no-growth baseline for issue #10934 and Epic #10920. The epic reference remains fixed at fe18b2f004e2304c52db33cf7bb5895828197f9a. Current main is lower because #10722 removed the live Shields assertion suites before this ratchet landed. PR #10341 adds the accepted public deferred-install and same-home credential continuation boundary for Hermes and Deep Agents Code; existing per-file budgets remain unchanged. PR #13055 adds five explicitly approved assertions for the native Deep Agents Code OpenRouter request in the existing hosted OpenRouter target. PR #13244 adds three assertions, requested by the PR owner, for the interactive `onboard --policy-tier` journey in the existing policy preset sequencing target.", "schemaVersion": 1, "issue": 10934, "epic": 10920, @@ -15,26 +15,26 @@ "testFileCount": 77, "liveFileCount": 186, "direct": { - "expectCalls": 1257, - "matcherAssertions": 1236, + "expectCalls": 1260, + "matcherAssertions": 1239, "nodeAssertions": 104, "namedAssertionHelpers": 417, "failCalls": 0, "throwGuards": 50, "objectFieldAssertions": 177, - "assertionPoints": 1984, + "assertionPoints": 1987, "generatedProbeBlocks": 87, "generatedProbeConditions": 216 }, "unique": { - "expectCalls": 1680, - "matcherAssertions": 1654, + "expectCalls": 1683, + "matcherAssertions": 1657, "nodeAssertions": 127, "namedAssertionHelpers": 661, "failCalls": 1, "throwGuards": 526, "objectFieldAssertions": 254, - "assertionPoints": 3223, + "assertionPoints": 3226, "generatedProbeBlocks": 209, "generatedProbeConditions": 721 }, @@ -91,7 +91,7 @@ "test/e2e/live/native-runtime-qualification-case.test.ts": [0,0,9,84,0], "test/e2e/live/network-policy.test.ts": [18,19,18,19,1], "test/e2e/live/ollama-auth-proxy.test.ts": [21,29,21,29,0], - "test/e2e/live/onboard-policy-preset-sequencing.test.ts": [7,7,7,7,1], + "test/e2e/live/onboard-policy-preset-sequencing.test.ts": [10,10,10,10,1], "test/e2e/live/onboard-repair.test.ts": [22,26,22,26,0], "test/e2e/live/onboard-resume.test.ts": [59,63,59,63,0], "test/e2e/live/openclaw-discord-pairing.test.ts": [13,20,28,86,10], diff --git a/ci/e2e-assertion-growth-exceptions.json b/ci/e2e-assertion-growth-exceptions.json index a07d8549acc..22636f3af54 100644 --- a/ci/e2e-assertion-growth-exceptions.json +++ b/ci/e2e-assertion-growth-exceptions.json @@ -1,5 +1,5 @@ { - "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12718 is the prerequisite for the PR #12382 budget transition recorded below. The exception matches only PR #12382 and both budget digests. A changed base or candidate budget invalidates it. The independent check reads trusted base policy, so this prerequisite must land on main before #12382 uses the exception. Remove after #12382 merges.\n\nMaintainer Prekshi Vyas (@prekshivyas) approved this exact refreshed PR #12382 transition on 2026-10-08: base budget SHA-256 53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441 to candidate budget SHA-256 8162408384d7a6b97ef0062042c73d4bc9486f54d2dfa6c0c5732e42d1060e2a. Acceptance record: https://github.com/NVIDIA/NemoClaw/pull/12840#issuecomment-6066319444. It includes one additional unique assertion point and one generated probe condition. This refresh preserves the #12608 concurrent-gateway-ports reduction and the previously reviewed runtime assertion changes. The independent check is not waived: the refreshed exception must land on main before enforcement can accept it. A different PR or budget digest remains rejected. Remove after #12382 merges.\n\nPR #12777 adds exactly two approved live assertions for native host-local inference success and sibling provider isolation. Deterministic behavior remains in unit/integration tests. Approval transcription: https://github.com/NVIDIA/NemoClaw/pull/12777#issuecomment-6048385152. The independent check reads trusted base policy; this entry does not disable it. Remove after #12777 merges.\n\nThe #12777 budget digests account for main #12608 removing seven assertions from concurrent-gateway-ports. The candidate preserves that reduction and adds only the same two approved inference-routing assertions. No other file budget increases.\n\nPR #12886 approved the provider-smoke transition extracted by #12955. Approval: https://github.com/NVIDIA/NemoClaw/pull/12886#issuecomment-6083839176. The unchanged change digest binds the same nine assertion points and companion inventory. This entry supports local preliminary validation and the Slice 2 consumer. Independent CI for the prerequisite requires its own maintainer approval record; this entry does not approve that PR.\n\nPR #12958 extracts the same approved provider-smoke budget transition for #12955. Its exact, unedited maintainer approval is https://github.com/NVIDIA/NemoClaw/pull/12958#issuecomment-6093851571. This candidate entry supports static hooks; the independent check continues to verify the PR-specific approval on GitHub. Remove after #12958 merges.", + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12718 is the prerequisite for the PR #12382 budget transition recorded below. The exception matches only PR #12382 and both budget digests. A changed base or candidate budget invalidates it. The independent check reads trusted base policy, so this prerequisite must land on main before #12382 uses the exception. Remove after #12382 merges.\n\nMaintainer Prekshi Vyas (@prekshivyas) approved this exact refreshed PR #12382 transition on 2026-10-08: base budget SHA-256 53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441 to candidate budget SHA-256 8162408384d7a6b97ef0062042c73d4bc9486f54d2dfa6c0c5732e42d1060e2a. Acceptance record: https://github.com/NVIDIA/NemoClaw/pull/12840#issuecomment-6066319444. It includes one additional unique assertion point and one generated probe condition. This refresh preserves the #12608 concurrent-gateway-ports reduction and the previously reviewed runtime assertion changes. The independent check is not waived: the refreshed exception must land on main before enforcement can accept it. A different PR or budget digest remains rejected. Remove after #12382 merges.\n\nPR #12777 adds exactly two approved live assertions for native host-local inference success and sibling provider isolation. Deterministic behavior remains in unit/integration tests. Approval transcription: https://github.com/NVIDIA/NemoClaw/pull/12777#issuecomment-6048385152. The independent check reads trusted base policy; this entry does not disable it. Remove after #12777 merges.\n\nThe #12777 budget digests account for main #12608 removing seven assertions from concurrent-gateway-ports. The candidate preserves that reduction and adds only the same two approved inference-routing assertions. No other file budget increases.\n\nPR #12886 approved the provider-smoke transition extracted by #12955. Approval: https://github.com/NVIDIA/NemoClaw/pull/12886#issuecomment-6083839176. The unchanged change digest binds the same nine assertion points and companion inventory. This entry supports local preliminary validation and the Slice 2 consumer. Independent CI for the prerequisite requires its own maintainer approval record; this entry does not approve that PR.\n\nPR #12958 extracts the same approved provider-smoke budget transition for #12955. Its exact, unedited maintainer approval is https://github.com/NVIDIA/NemoClaw/pull/12958#issuecomment-6093851571. This candidate entry supports static hooks; the independent check continues to verify the PR-specific approval on GitHub. Remove after #12958 merges.\n\nPR #13244 adds three live assertions for the interactive `onboard --policy-tier` journey in the existing policy preset sequencing target. Its exact, unedited maintainer approval is https://github.com/NVIDIA/NemoClaw/pull/13244#issuecomment-6190493931. This candidate entry supports static hooks; the independent check continues to verify the PR-specific approval on GitHub. Remove after #13244 merges.", "schemaVersion": 1, "exceptions": [ { @@ -42,6 +42,10 @@ { "pullRequest": 13055, "changeSha256": "d0435766039881c9598d3740f650e3bffdbace9f5a3f29fdc70238522c521f79" + }, + { + "pullRequest": 13244, + "changeSha256": "ee325f45fb2d97779f14e3bed8b4e3798b4058e46d6e8b91817de420595c8da8" } ] } diff --git a/src/lib/actions/onboard.test.ts b/src/lib/actions/onboard.test.ts index a50e4d77a64..eeb7150f16c 100644 --- a/src/lib/actions/onboard.test.ts +++ b/src/lib/actions/onboard.test.ts @@ -13,7 +13,6 @@ vi.mock("../agent/defs", () => ({ listAgents: mocks.listAgents })); vi.mock("../onboard", () => ({ onboard: mocks.onboard })); vi.mock("../onboard/command", () => ({ runOnboardCommand: mocks.runOnboardCommand })); -import { readRequestedPolicyTier } from "../onboard/policy-tier-env"; import { runOnboardAction } from "./onboard"; describe("onboard action runtime composition", () => { @@ -41,25 +40,26 @@ describe("onboard action runtime composition", () => { }); }); - it("scopes --policy-tier to one legacy onboarding run (#13180)", async () => { - let observed: string | null = null; + it("passes each run's --policy-tier on its own invocation without env state (#13180)", async () => { mocks.runOnboardCommand.mockImplementation( async (deps: { + flags: { "policy-tier"?: string }; listPolicyTiers(): readonly string[]; runOnboard(options: unknown): Promise; }) => { expect(deps.listPolicyTiers()).toEqual(["restricted", "balanced", "open", "personal"]); - await deps.runOnboard({ requestedPolicyTier: "restricted" }); + await deps.runOnboard({ requestedPolicyTier: deps.flags["policy-tier"] }); }, ); - mocks.onboard.mockImplementationOnce(async () => { - observed = readRequestedPolicyTier(); - throw new Error("boom"); - }); + const ambient = process.env.NEMOCLAW_POLICY_TIER; - await expect(runOnboardAction({ "policy-tier": "restricted" })).rejects.toThrow("boom"); + await runOnboardAction({ "policy-tier": "restricted" }); + await runOnboardAction({ "policy-tier": "open" }); - expect(observed).toBe("restricted"); - expect(readRequestedPolicyTier()).toBeNull(); + expect(mocks.onboard.mock.calls.map(([options]) => options.requestedPolicyTier)).toEqual([ + "restricted", + "open", + ]); + expect(process.env.NEMOCLAW_POLICY_TIER).toBe(ambient); }); }); diff --git a/src/lib/actions/onboard.ts b/src/lib/actions/onboard.ts index f24f42cc53b..b010fcbdc23 100644 --- a/src/lib/actions/onboard.ts +++ b/src/lib/actions/onboard.ts @@ -26,14 +26,7 @@ async function runOnboard( const { onboard } = (await import("../onboard")) as unknown as { onboard: (onboardOptions?: OnboardOptions) => Promise; }; - // An explicit --policy-tier makes the wizard skip its tier prompt for this run only. - const { setRequestedPolicyTier } = await import("../onboard/policy-tier-env"); - setRequestedPolicyTier(options.requestedPolicyTier ?? null); - try { - await onboard({ ...options, googlechatTunnelRuntime: runtimeDeps.googlechatTunnelRuntime }); - } finally { - setRequestedPolicyTier(null); - } + await onboard({ ...options, googlechatTunnelRuntime: runtimeDeps.googlechatTunnelRuntime }); } function buildOnboardCommandDeps(flags: OnboardFlags, runtimeDeps: OnboardActionRuntimeDeps) { diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index a0bd185746a..36b48aa6874 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -3010,8 +3010,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { recreateJournalTargetIntentFingerprint: opts.recreateJournalTargetIntentFingerprint ?? null, resumeAgentChanged, - requestedObservabilityEnabled: runtimeControlRequests.requestedObservabilityEnabled, - requestedDcodeAutoApprovalMode: runtimeControlRequests.requestedDcodeAutoApprovalMode, + ...runtimeControlFlow.sandboxFlowRuntimeControlOptions(runtimeControlRequests), hostMounts: effectiveHostMounts, endpointProvenance, recreateSandbox: isRecreateSandbox, @@ -3140,6 +3139,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { portableRuntimeContext: agent?.name === "hermes" ? lockedRuntime.portableRuntimeContext : null, preserveRebuildLivePolicy: opts.rebuildPolicySourcePath !== undefined, + requestedPolicyTier: runtimeControlRequests.requestedPolicyTier, agentSetupDeps: { handleAgentSetup: agentOnboard.handleAgentSetup, agentSetupContext: () => ({ diff --git a/src/lib/onboard/command-policy-tier.test.ts b/src/lib/onboard/command-policy-tier.test.ts index c248ba5fce6..31b64dec5ed 100644 --- a/src/lib/onboard/command-policy-tier.test.ts +++ b/src/lib/onboard/command-policy-tier.test.ts @@ -42,45 +42,20 @@ describe("onboard --policy-tier (#13180)", () => { ]); }); - it("scopes --policy-tier over NEMOCLAW_POLICY_TIER for one onboarding run (#13180)", async () => { + it("carries --policy-tier on the run options without mutating the environment (#13180)", async () => { const env: NodeJS.ProcessEnv = { NEMOCLAW_POLICY_TIER: "open" }; - let observed: string | undefined; + const seen: Array = []; await runOnboardCommand({ flags: { "policy-tier": "restricted" }, env, + listPolicyTiers: () => ONBOARD_POLICY_TIER_VALUES, runOnboard: async (options) => { - observed = env.NEMOCLAW_POLICY_TIER; - expect(options.requestedPolicyTier).toBe("restricted"); + seen.push(options.requestedPolicyTier); + expect(env.NEMOCLAW_POLICY_TIER).toBe("open"); }, }); - expect(observed).toBe("restricted"); - expect(env.NEMOCLAW_POLICY_TIER).toBe("open"); - - const unsetEnv: NodeJS.ProcessEnv = {}; - await runOnboardCommand({ - flags: { "policy-tier": "personal" }, - env: unsetEnv, - runOnboard: async () => { - expect(unsetEnv.NEMOCLAW_POLICY_TIER).toBe("personal"); - }, - }); - expect(Object.prototype.hasOwnProperty.call(unsetEnv, "NEMOCLAW_POLICY_TIER")).toBe(false); - }); - - it("restores NEMOCLAW_POLICY_TIER after a failed onboarding run", async () => { - const env: NodeJS.ProcessEnv = {}; - await expect( - runOnboardCommand({ - flags: { "policy-tier": "restricted" }, - env, - runOnboard: async () => { - throw Object.assign(new Error("boom"), { code: "EOF" }); - }, - error: () => {}, - exit: exitWithCode, - }), - ).rejects.toThrow("exit:"); - expect(Object.prototype.hasOwnProperty.call(env, "NEMOCLAW_POLICY_TIER")).toBe(false); + expect(seen).toEqual(["restricted"]); + expect(env).toEqual({ NEMOCLAW_POLICY_TIER: "open" }); }); it("leaves the tier prompt in charge when the flag is absent", async () => { diff --git a/src/lib/onboard/command.ts b/src/lib/onboard/command.ts index 55f279cb79c..f51badaef9f 100644 --- a/src/lib/onboard/command.ts +++ b/src/lib/onboard/command.ts @@ -750,24 +750,6 @@ function restoreOnboardCommandEnvironment( } } -// Scope `--policy-tier` to one run. The flag overrides an ambient -// NEMOCLAW_POLICY_TIER so every non-interactive tier consumer sees the same -// choice. The onboard action separately tells the wizard to skip its prompt. -function applyRequestedPolicyTierEnvironment( - options: OnboardCommandOptions, - env: NodeJS.ProcessEnv, -): () => void { - const tier = options.requestedPolicyTier; - if (!tier) return () => {}; - const present = Object.prototype.hasOwnProperty.call(env, "NEMOCLAW_POLICY_TIER"); - const previous = env.NEMOCLAW_POLICY_TIER; - env.NEMOCLAW_POLICY_TIER = tier; - return () => { - if (present) env.NEMOCLAW_POLICY_TIER = previous ?? ""; - else delete env.NEMOCLAW_POLICY_TIER; - }; -} - async function runOnboardCommandAttempt( deps: RunOnboardCommandDeps, env: NodeJS.ProcessEnv, @@ -779,7 +761,6 @@ async function runOnboardCommandAttempt( resumeIntent, }); let restoreServingProfileEnvironment = () => {}; - let restorePolicyTierEnvironment = () => {}; const environmentSnapshot: OnboardCommandEnvironmentSnapshot = { agentsManifest: env.NEMOCLAW_EXTRA_AGENTS_JSON, toolDisclosure: env[TOOL_DISCLOSURE_ENV], @@ -808,13 +789,11 @@ async function runOnboardCommandAttempt( if (options.noOllamaAutostart && !options.experimentalProfile) { env.NEMOCLAW_OLLAMA_NO_AUTOSTART = "1"; } - restorePolicyTierEnvironment = applyRequestedPolicyTierEnvironment(options, env); await withCredentialOverrides(activation.credentialOverrides, () => deps.runOnboard(options)); return "complete"; } catch (error) { return handleOnboardCommandAttemptError(error, deps, attempt); } finally { - restorePolicyTierEnvironment(); restoreOnboardCommandEnvironment( env, options, diff --git a/src/lib/onboard/machine/core-flow-phases.ts b/src/lib/onboard/machine/core-flow-phases.ts index 5ebe3484f38..271cccfa48f 100644 --- a/src/lib/onboard/machine/core-flow-phases.ts +++ b/src/lib/onboard/machine/core-flow-phases.ts @@ -82,6 +82,8 @@ export interface SandboxOnboardFlowPhaseOptions< resumeAgentChanged: boolean; requestedObservabilityEnabled?: boolean | null; requestedDcodeAutoApprovalMode?: DcodeAutoApprovalMode | null; + /** Operator-selected `--policy-tier` for this run. */ + requestedPolicyTier?: string | null; rebuildPolicySourcePath?: string; hostMounts?: readonly import("../../state/registry/types").SandboxHostMount[]; endpointProvenance: EndpointProvenanceOptions; @@ -346,6 +348,7 @@ export function createSandboxOnboardFlowPhase< endpointSource: endpointProvenance.endpointSource, resumeAgentChanged: options.resumeAgentChanged, requestedObservabilityEnabled: options.requestedObservabilityEnabled, + requestedPolicyTier: options.requestedPolicyTier ?? null, requestedDcodeAutoApprovalMode: options.requestedDcodeAutoApprovalMode, rebuildPolicySourcePath: options.rebuildPolicySourcePath, hostMounts: options.hostMounts, diff --git a/src/lib/onboard/machine/final-flow-phases.ts b/src/lib/onboard/machine/final-flow-phases.ts index 38acb79f133..3d055b4b51d 100644 --- a/src/lib/onboard/machine/final-flow-phases.ts +++ b/src/lib/onboard/machine/final-flow-phases.ts @@ -42,6 +42,8 @@ export interface FinalOnboardFlowPhaseOptions< branchState: "agent_setup" | "openclaw"; managedOpenclawStartup?: boolean; preserveRebuildLivePolicy?: boolean; + /** Operator-selected `--policy-tier`; skips the policy-tier prompt. */ + requestedPolicyTier?: string | null; agentSetupDeps: AgentSetupStateOptions["deps"]; policiesDeps: PoliciesStateOptions["deps"]; finalization: { @@ -129,6 +131,7 @@ export function createFinalOnboardFlowPhases< const policiesResult = await handlePoliciesState({ resume: context.resume, preserveRebuildLivePolicy: options.preserveRebuildLivePolicy, + requestedPolicyTier: options.requestedPolicyTier ?? null, sandboxName: context.sandboxName, provider: context.provider, hostLocalInferenceRouteOnly: context.hostLocalInferenceRouteOnly === true, diff --git a/src/lib/onboard/machine/handlers/policies.test.ts b/src/lib/onboard/machine/handlers/policies.test.ts index 8b6eab155d0..4915222f17f 100644 --- a/src/lib/onboard/machine/handlers/policies.test.ts +++ b/src/lib/onboard/machine/handlers/policies.test.ts @@ -62,6 +62,22 @@ describe("policy state handler", () => { ); }); + it("passes an explicit --policy-tier to fresh policy selection (#13180)", async () => { + const { deps, calls } = createPolicyHandlerDeps(); + await handlePoliciesState({ ...basePolicyHandlerOptions(deps), requestedPolicyTier: "open" }); + expect(calls.setupPolicies).toHaveBeenCalledWith( + "my-assistant", + expect.objectContaining({ selectedPresets: null, tierName: "open" }), + ); + + const unset = createPolicyHandlerDeps(); + await handlePoliciesState(basePolicyHandlerOptions(unset.deps)); + expect(unset.calls.setupPolicies).toHaveBeenCalledWith( + "my-assistant", + expect.objectContaining({ tierName: null }), + ); + }); + it("does not reconcile presets after a rebuild consumed OpenShell's live policy", async () => { const { deps, calls } = createPolicyHandlerDeps(); diff --git a/src/lib/onboard/machine/handlers/policies.ts b/src/lib/onboard/machine/handlers/policies.ts index aa2af7993db..38a371ccd85 100644 --- a/src/lib/onboard/machine/handlers/policies.ts +++ b/src/lib/onboard/machine/handlers/policies.ts @@ -32,6 +32,8 @@ export interface PolicyResumeSelection { export interface PoliciesStateOptions { resume: boolean; preserveRebuildLivePolicy?: boolean; + /** Operator-selected `--policy-tier`; skips the policy-tier prompt. */ + requestedPolicyTier?: string | null; sandboxName: string; provider: string; hostLocalInferenceRouteOnly?: boolean; @@ -132,6 +134,7 @@ export interface PoliciesStateResult { export async function handlePoliciesState({ resume, preserveRebuildLivePolicy = false, + requestedPolicyTier = null, sandboxName, provider, hostLocalInferenceRouteOnly = false, @@ -285,7 +288,7 @@ export async function handlePoliciesState({ // Hermes runs keep their own name. agent: normalizeAgentNameForResumeState((agent as { name?: string } | null)?.name), observabilityEnabled, - tierName: null, + tierName: requestedPolicyTier, webSearchSupported, hermesToolGateways, onSelection: () => undefined, diff --git a/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts b/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts index e6946e1c3ad..ad042ef1c3a 100644 --- a/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts @@ -299,6 +299,22 @@ describe("sandbox create intent machine boundary", () => { }, ); + it("carries an explicit --policy-tier into create-time policy resolution (#13180)", async () => { + const session = createSession({ sandboxName: "tiered" }); + const { deps, calls } = createDeps(); + + await handleSandboxState({ + ...baseOptions(deps, session), + sandboxName: "tiered", + requestedPolicyTier: "restricted", + }); + + expect(calls.resolveCreateIntent).toHaveBeenCalledWith( + expect.objectContaining({ policyTier: "restricted" }), + ); + expect(calls.createSandbox.mock.calls[0]?.at(-2)).toMatchObject({ policyTier: "restricted" }); + }); + it("carries an explicit recreate request through a fresh sandbox decision (#8847)", async () => { const session = createSession({ sandboxName: "same-sandbox" }); const { deps, calls } = createDeps({ getSandboxReuseState: () => "ready" }); diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index 1390010cba4..9fa52935c18 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -212,6 +212,8 @@ export interface SandboxStateOptions< resumeAgentChanged: boolean; requestedObservabilityEnabled?: boolean | null; requestedDcodeAutoApprovalMode?: DcodeAutoApprovalMode | null; + /** Operator-selected `--policy-tier`; governs the create-time policy tier. */ + requestedPolicyTier?: string | null; rebuildPolicySourcePath?: string; hostMounts?: readonly import("../../../state/registry/types").SandboxHostMount[]; recreateSandbox: (requested?: boolean) => boolean; @@ -1147,6 +1149,11 @@ class SandboxStateFlow< if (bindingCheck.status === "stale") this.rejectStaleCheckpointBindings(bindingCheck); } + private requestedPolicyTierIntent(): { policyTier?: string } { + const tier = this.options.requestedPolicyTier; + return tier ? { policyTier: tier } : {}; + } + private applyObservabilityRequest( state: SandboxStepState, ): SandboxStepState { @@ -1931,6 +1938,7 @@ class SandboxStateFlow< staleExtraProviders, hostMounts: this.options.hostMounts, ...(reuseRegisteredCredentials ? { reuseRegisteredCredentials: true } : {}), + ...this.requestedPolicyTierIntent(), }); const recreate = requiresSandboxRecreation(decision, this.options.recreateSandbox(false)); return { @@ -1973,6 +1981,7 @@ class SandboxStateFlow< ...(this.options.rebuildPolicySourcePath ? { rebuildPolicySourcePath: this.options.rebuildPolicySourcePath } : {}), + ...this.requestedPolicyTierIntent(), extraProviders, }; } diff --git a/src/lib/onboard/policy-selection-prompts.test.ts b/src/lib/onboard/policy-selection-prompts.test.ts index 6002958655e..6b47954a2ce 100644 --- a/src/lib/onboard/policy-selection-prompts.test.ts +++ b/src/lib/onboard/policy-selection-prompts.test.ts @@ -68,16 +68,12 @@ function createHarness({ stdoutTTY = true, promptReplies = [], envTier = null, - explicitTier = null, - nonInteractive = false, }: { tiers?: TierDefinition[]; stdinTTY?: boolean; stdoutTTY?: boolean; promptReplies?: string[]; envTier?: string | null; - explicitTier?: string | null; - nonInteractive?: boolean; } = {}) { const stdin = new FakeInput(stdinTTY); const stdout = new FakeOutput(stdoutTTY); @@ -94,9 +90,8 @@ function createHarness({ policyTierEnv: { resolvePolicyTierFromEnv: () => envTier ?? "balanced", readPolicyTierPreselectionFromEnv: () => envTier, - readRequestedPolicyTier: () => explicitTier, }, - isNonInteractive: () => nonInteractive, + isNonInteractive: () => false, note, prompt, selectFromNumberedMenuOrExit, @@ -182,28 +177,6 @@ describe("createPolicySelectionPromptHelpers", () => { ); }); - it("selectPolicyTier uses --policy-tier without prompting (#13180)", async () => { - const { helpers, note, prompt, stdin } = createHarness({ - explicitTier: "restricted", - envTier: "open", - }); - - await expect(helpers.selectPolicyTier()).resolves.toBe("restricted"); - expect(prompt).not.toHaveBeenCalled(); - expect(stdin.setRawMode).not.toHaveBeenCalled(); - expect(note).toHaveBeenCalledWith(" Policy tier: Restricted (from --policy-tier)"); - }); - - it("selectPolicyTier prefers --policy-tier over the non-interactive env tier (#13180)", async () => { - const { helpers } = createHarness({ - explicitTier: "restricted", - envTier: "open", - nonInteractive: true, - }); - - await expect(helpers.selectPolicyTier()).resolves.toBe("restricted"); - }); - it("selectTierPresetsAndAccess honors comma-separated non-TTY allowlists", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); diff --git a/src/lib/onboard/policy-selection-prompts.ts b/src/lib/onboard/policy-selection-prompts.ts index a224efe6efa..18e116b4a3d 100644 --- a/src/lib/onboard/policy-selection-prompts.ts +++ b/src/lib/onboard/policy-selection-prompts.ts @@ -35,8 +35,6 @@ export interface PolicySelectionPromptDeps { policyTierEnv: { resolvePolicyTierFromEnv(): string; readPolicyTierPreselectionFromEnv(): string | null; - /** Tier chosen with `onboard --policy-tier`; skips the tier prompt when set. */ - readRequestedPolicyTier(): string | null; }; isNonInteractive(): boolean; note(message: string): void; @@ -126,7 +124,6 @@ export function createPolicySelectionPromptHelpers(deps: PolicySelectionPromptDe /** * Prompt the user to select a policy tier (restricted / balanced / open / personal). * Uses the same radio-style TUI as presetsCheckboxSelector (single-select). - * An explicit `--policy-tier` choice skips the prompt in every mode. * In non-interactive mode reads NEMOCLAW_POLICY_TIER (default: balanced). * In interactive mode a valid NEMOCLAW_POLICY_TIER pre-selects that tier. * Returns the tier name string. @@ -139,16 +136,6 @@ export function createPolicySelectionPromptHelpers(deps: PolicySelectionPromptDe throw new Error("No policy tiers are configured."); } - const explicitName = policyTierEnv.readRequestedPolicyTier(); - if (explicitName) { - const explicitTier = tiers.getTier(explicitName); - if (!explicitTier) { - throw new Error(`Unknown policy tier from --policy-tier: ${explicitName}`); - } - note(` Policy tier: ${explicitTier.label} (from --policy-tier)`); - return explicitTier.name; - } - if (isNonInteractive()) { const name = policyTierEnv.resolvePolicyTierFromEnv(); note(` [non-interactive] Policy tier: ${name}`); diff --git a/src/lib/onboard/policy-selection.ts b/src/lib/onboard/policy-selection.ts index 4fce6bd043c..bd714c33a65 100644 --- a/src/lib/onboard/policy-selection.ts +++ b/src/lib/onboard/policy-selection.ts @@ -536,6 +536,10 @@ async function setupPoliciesWithSelectionInner( return resumeSelection; } + if (requestedTierName) { + const label = deps.tiers.getTier(requestedTierName)?.label ?? requestedTierName; + deps.note(` Policy tier: ${label} (from --policy-tier)`); + } const tierName = requestedTierName ?? (await deps.selectPolicyTier()); if (personalAlreadyActive && tierName !== PERSONAL_POLICY_TIER_NAME) { refuseInPlacePersonalRemoval(personalAlreadyActive, []); diff --git a/src/lib/onboard/policy-tier-env.ts b/src/lib/onboard/policy-tier-env.ts index 47bdb092388..7c0535044db 100644 --- a/src/lib/onboard/policy-tier-env.ts +++ b/src/lib/onboard/policy-tier-env.ts @@ -26,18 +26,6 @@ export function resolvePolicyTierFromEnv(): string { return name; } -// Tier selected with `onboard --policy-tier`. The onboard command sets it for -// one run and clears it afterward; null means the wizard asks for the tier. -let requestedPolicyTier: string | null = null; - -export function setRequestedPolicyTier(name: string | null): void { - requestedPolicyTier = name; -} - -export function readRequestedPolicyTier(): string | null { - return requestedPolicyTier; -} - /** * Read NEMOCLAW_POLICY_TIER for interactive pre-selection. Returns the * normalized name, or null when the env var is unset or blank. Does not diff --git a/src/lib/onboard/runtime-control-flow.test.ts b/src/lib/onboard/runtime-control-flow.test.ts index b7ab1ac59f8..51f858021ac 100644 --- a/src/lib/onboard/runtime-control-flow.test.ts +++ b/src/lib/onboard/runtime-control-flow.test.ts @@ -7,6 +7,7 @@ import { createSession } from "../state/onboard-session"; import { applyOnboardRuntimeControlRequests, planSelectedAgentTransition, + sandboxFlowRuntimeControlOptions, updateSessionAgent, } from "./runtime-control-flow"; @@ -21,17 +22,29 @@ describe("onboard runtime control flow", () => { toolDisclosure: "direct", observabilityEnabled: true, dcodeAutoApprovalMode: "thread-opt-in", + requestedPolicyTier: "restricted", }), ).toEqual({ requestedToolDisclosure: "direct", requestedObservabilityEnabled: true, requestedDcodeAutoApprovalMode: "thread-opt-in", + requestedPolicyTier: "restricted", }); delete process.env.NEMOCLAW_TOOL_DISCLOSURE; expect(applyOnboardRuntimeControlRequests({})).toEqual({ requestedToolDisclosure: null, requestedObservabilityEnabled: null, requestedDcodeAutoApprovalMode: null, + requestedPolicyTier: null, + }); + }); + + it("hands the per-run policy tier to the sandbox phase (#13180)", () => { + const requests = applyOnboardRuntimeControlRequests({ requestedPolicyTier: "personal" }); + expect(sandboxFlowRuntimeControlOptions(requests)).toEqual({ + requestedObservabilityEnabled: null, + requestedDcodeAutoApprovalMode: null, + requestedPolicyTier: "personal", }); }); @@ -45,6 +58,7 @@ describe("onboard runtime control flow", () => { requestedToolDisclosure: null, requestedObservabilityEnabled: null, requestedDcodeAutoApprovalMode: null, + requestedPolicyTier: null, }); }); diff --git a/src/lib/onboard/runtime-control-flow.ts b/src/lib/onboard/runtime-control-flow.ts index b59bd4f315c..00ebcea28ee 100644 --- a/src/lib/onboard/runtime-control-flow.ts +++ b/src/lib/onboard/runtime-control-flow.ts @@ -39,6 +39,7 @@ export function applyOnboardRuntimeControlRequests( | "observabilityEnabled" | "observabilityRequestedExplicitly" | "dcodeAutoApprovalMode" + | "requestedPolicyTier" >, ) { const observabilityIsExplicit = opts.observabilityRequestedExplicitly !== false; @@ -51,6 +52,18 @@ export function applyOnboardRuntimeControlRequests( requestedDcodeAutoApprovalMode: isDcodeAutoApprovalMode(opts.dcodeAutoApprovalMode) ? opts.dcodeAutoApprovalMode : null, + requestedPolicyTier: opts.requestedPolicyTier ?? null, + }; +} + +/** Per-run requests consumed by the sandbox phase. */ +export function sandboxFlowRuntimeControlOptions( + requests: ReturnType, +) { + return { + requestedObservabilityEnabled: requests.requestedObservabilityEnabled, + requestedDcodeAutoApprovalMode: requests.requestedDcodeAutoApprovalMode, + requestedPolicyTier: requests.requestedPolicyTier, }; } diff --git a/src/lib/onboard/types.ts b/src/lib/onboard/types.ts index 886df7bf54d..71c059b8631 100644 --- a/src/lib/onboard/types.ts +++ b/src/lib/onboard/types.ts @@ -202,6 +202,8 @@ export type OnboardOptions = { dcodeAutoApprovalMode?: import("./dcode-auto-approval").DcodeAutoApprovalMode | null; /** Internal authoritative rebuild tier; never exposed as an onboard CLI option. */ policyTier?: string | null; + /** Operator-selected `onboard --policy-tier`; governs create-time and policy-step tier. */ + requestedPolicyTier?: string | null; controlUiPort?: number | null; gpu?: boolean; noGpu?: boolean; diff --git a/test/e2e/live/onboard-policy-preset-sequencing.test.ts b/test/e2e/live/onboard-policy-preset-sequencing.test.ts index a141ccfe832..afff3ded387 100644 --- a/test/e2e/live/onboard-policy-preset-sequencing.test.ts +++ b/test/e2e/live/onboard-policy-preset-sequencing.test.ts @@ -9,7 +9,8 @@ import { expect, test } from "../fixtures/e2e-test.ts"; import { startFakeOpenAiCompatibleServer } from "../fixtures/fake-openai-compatible.ts"; import { CLI_ENTRYPOINT, REPO_ROOT } from "../fixtures/paths.ts"; import { redactString } from "../fixtures/redaction.ts"; -import { driveInteractiveCommand } from "./onboard-interactive-pty.ts"; +import { driveInteractiveCommand, type InteractiveCommandRule } from "./onboard-interactive-pty.ts"; +import { parsePolicyPresetState } from "./policy-list-state.ts"; // Regression coverage for #6042: "interactive onboard wizard skips Policy // Presets TUI step". Three independent investigations could not reproduce a @@ -29,6 +30,8 @@ import { driveInteractiveCommand } from "./onboard-interactive-pty.ts"; const SANDBOX_NAME = process.env.NEMOCLAW_SANDBOX_NAME ?? "e2e-policy-order"; validateSandboxName(SANDBOX_NAME); +const POLICY_TIER_FLAG_SANDBOX_NAME = "e2e-policy-tier"; +validateSandboxName(POLICY_TIER_FLAG_SANDBOX_NAME); const ONBOARD_TIMEOUT_MS = 40 * 60_000; const MODEL = "test-model"; // A Docker network namespace cannot reach host loopback directly; bind the @@ -51,6 +54,36 @@ const ORDERED_STEP_MARKERS = [ "[8/8] Policy presets", ] as const; +// The raw-mode tier selector's header. The bare "Policy tier" text also +// appears in the `--policy-tier` confirmation note, so a rule meant to prove +// the prompt is skipped must match the selector itself. +const POLICY_TIER_PROMPT_HEADER = "Policy tier — controls which network presets"; + +// Answers shared by every interactive compatible-endpoint journey in this file, +// up to (but not including) the policy tier selector. +function compatibleEndpointRules(baseUrl: string, apiKey: string): InteractiveCommandRule[] { + return [ + // A reused host can already have accepted this first-run license + // notice, so this rule might not fire. + { trigger: "Type 'yes' to accept", response: "yes\n" }, + // Only appears when the preflight resource check warns; skipped on + // an adequately provisioned CI runner. + { trigger: "Continue with onboarding?", response: "y\n" }, + // "Other OpenAI-compatible endpoint" — position depends on + // src/lib/onboard/providers.ts's provider list for the openclaw agent. + { trigger: "Select your inference provider:", response: "4\n" }, + { trigger: "Other OpenAI-compatible endpoint", response: "" }, + { trigger: "OpenAI-compatible base URL", response: `${baseUrl}\n` }, + { trigger: "Other OpenAI-compatible endpoint API key:", response: `${apiKey}\n` }, + { trigger: "endpoint model", response: `${MODEL}\n` }, + { trigger: "Choose an action:", response: "1\n" }, + { trigger: "Enable web search", response: "1\n" }, + // Raw-mode messaging-channel selector; Enter with none toggled skips. + { trigger: "Press 1-7 to toggle", response: "\r" }, + { trigger: "Resource profiles:", response: "6\n" }, + ]; +} + test( "interactive onboard wizard reaches Policy presets in step order (#6042)", { @@ -109,24 +142,7 @@ test( cwd: REPO_ROOT, env: buildAvailabilityProbeEnv(), rules: [ - // A reused host can already have accepted this first-run license - // notice, so this rule might not fire. - { trigger: "Type 'yes' to accept", response: "yes\n" }, - // Only appears when the preflight resource check warns; skipped on - // an adequately provisioned CI runner. - { trigger: "Continue with onboarding?", response: "y\n" }, - // "Other OpenAI-compatible endpoint" — position depends on - // src/lib/onboard/providers.ts's provider list for the openclaw agent. - { trigger: "Select your inference provider:", response: "4\n" }, - { trigger: "Other OpenAI-compatible endpoint", response: "" }, - { trigger: "OpenAI-compatible base URL", response: `${fake.baseUrl}\n` }, - { trigger: "Other OpenAI-compatible endpoint API key:", response: `${apiKey}\n` }, - { trigger: "endpoint model", response: `${MODEL}\n` }, - { trigger: "Choose an action:", response: "1\n" }, - { trigger: "Enable web search", response: "1\n" }, - // Raw-mode messaging-channel selector; Enter with none toggled skips. - { trigger: "Press 1-7 to toggle", response: "\r" }, - { trigger: "Resource profiles:", response: "6\n" }, + ...compatibleEndpointRules(fake.baseUrl, apiKey), // Raw-mode Policy tier selector; Enter confirms the pre-selected // default (Balanced). This is the exact prompt the issue claims the // wizard never reaches. @@ -173,3 +189,108 @@ test( ).not.toBeGreaterThanOrEqual(0); }, ); + +// #13180: `--policy-tier` must govern the interactive journey end to end. The +// conflicting NEMOCLAW_POLICY_TIER=open would otherwise pre-select Open, whose +// defaults include npm and pypi; Restricted applies neither. Unit tests own the +// precedence and threading logic; this case proves the real CLI-to-wizard +// handoff skips the tier selector and that the created sandbox's live +// OpenShell policy carries the Restricted result. +test( + "interactive onboard applies --policy-tier over NEMOCLAW_POLICY_TIER without the tier prompt (#13180)", + { + timeout: ONBOARD_TIMEOUT_MS, + meta: { + e2ePhases: [ + "start the local compatible-endpoint fake server", + "drive interactive onboard with --policy-tier restricted and NEMOCLAW_POLICY_TIER=open", + "confirm the tier selector was skipped", + "confirm the live sandbox policy has no Open-tier defaults", + ], + }, + }, + async ({ artifacts, cleanup, host, progress, runtimeProvider }) => { + await runtimeProvider.requireAvailable({ + artifactName: "prereq-runtime-provider-info-policy-tier-flag", + scenarioLabel: "onboard --policy-tier", + }); + + progress.phase("start the local compatible-endpoint fake server"); + const apiKey = `e2e-13180-${randomBytes(16).toString("hex")}`; + const fake = await startFakeOpenAiCompatibleServer({ + apiKey, + chatContent: "PONG", + host: "0.0.0.0", + model: MODEL, + progress, + publicHost: SANDBOX_HOST_ALIAS, + requireAuth: true, + responseText: "PONG", + }); + artifacts.addRedactionValues([apiKey]); + cleanup.trackDisposable("close fake compatible-endpoint server", () => fake.close()); + cleanup.trackSandbox(host, POLICY_TIER_FLAG_SANDBOX_NAME, { + artifactName: "cleanup-nemoclaw-destroy-onboard-policy-tier-flag", + env: buildAvailabilityProbeEnv(), + redactionValues: [apiKey], + timeoutMs: 120_000, + }); + + progress.phase( + "drive interactive onboard with --policy-tier restricted and NEMOCLAW_POLICY_TIER=open", + ); + const result = await driveInteractiveCommand({ + activityLabel: "command: onboard-interactive-pty-policy-tier-flag", + progress, + cmd: [ + process.execPath, + CLI_ENTRYPOINT, + "onboard", + "--fresh", + "--agent", + "openclaw", + "--name", + POLICY_TIER_FLAG_SANDBOX_NAME, + "--policy-tier", + "restricted", + "--yes-i-accept-third-party-software", + ], + cwd: REPO_ROOT, + env: { ...buildAvailabilityProbeEnv(), NEMOCLAW_POLICY_TIER: "open" }, + rules: [ + ...compatibleEndpointRules(fake.baseUrl, apiKey), + // Must not fire: answering it keeps a regression from hanging the + // run, and the assertion below fails if the selector appeared. + { trigger: POLICY_TIER_PROMPT_HEADER, response: "\r" }, + // The preset review still runs with the flag's tier defaults. + { trigger: "Presets (", response: "\r" }, + ], + timeoutMs: ONBOARD_TIMEOUT_MS - 5 * 60_000, + }); + await artifacts.writeText("onboard-policy-tier-flag-transcript.txt", result.output); + + const redactedTranscript = redactString(result.output, [apiKey]); + // A driver timeout exits 124, so the exit code also covers the timeout. + expect( + result.exitCode, + `onboard command failed; see onboard-policy-tier-flag-transcript.txt:\n${redactedTranscript}`, + ).toBe(0); + + progress.phase("confirm the tier selector was skipped"); + expect(result.firedTriggers).not.toContain(POLICY_TIER_PROMPT_HEADER); + + progress.phase("confirm the live sandbox policy has no Open-tier defaults"); + const policyList = await host.nemoclaw([POLICY_TIER_FLAG_SANDBOX_NAME, "policy-list"], { + artifactName: "policy-tier-flag-policy-list-after-onboard", + env: buildAvailabilityProbeEnv(), + timeoutMs: 120_000, + }); + const policyListText = `${policyList.stdout}\n${policyList.stderr}`; + // npm is a Balanced and Open default but not a Restricted one. A failed or + // unverified listing parses as another state and fails this assertion. + expect( + parsePolicyPresetState(policyListText, "npm"), + `Restricted must not apply the Open-tier npm default:\n${policyListText}`, + ).toBe("inactive"); + }, +); diff --git a/test/onboarding/presets-checkbox.test.ts b/test/onboarding/presets-checkbox.test.ts index 9fbd142e67d..b54d68d290b 100644 --- a/test/onboarding/presets-checkbox.test.ts +++ b/test/onboarding/presets-checkbox.test.ts @@ -52,7 +52,6 @@ async function runCheckboxSelector( policyTierEnv: { resolvePolicyTierFromEnv: () => "balanced", readPolicyTierPreselectionFromEnv: () => null, - readRequestedPolicyTier: () => null, }, isNonInteractive: () => false, note: () => undefined, diff --git a/test/runtime/policy/policy-tiers-onboard.test.ts b/test/runtime/policy/policy-tiers-onboard.test.ts index c902eca3b40..25973fd5e51 100644 --- a/test/runtime/policy/policy-tiers-onboard.test.ts +++ b/test/runtime/policy/policy-tiers-onboard.test.ts @@ -398,6 +398,20 @@ describe("policy tier selection", () => { }); describe("policy tier setup", () => { + it.each([true, false])( + "applies an explicit --policy-tier without asking for the tier (nonInteractive=%s) (#13180)", + async (nonInteractive) => { + const { applied, notes } = await runPolicySetup( + { tierName: "open", nonInteractive }, + { agent: "openclaw", tierName: "restricted" }, + ); + + expect(notes).toContain(" Policy tier: Restricted (from --policy-tier)"); + expect(applied).not.toContain("npm"); + expect(applied).not.toContain("slack"); + }, + ); + it.each([true, false])( "requests Open-tier messaging defaults for fresh OpenClaw without channels (nonInteractive=%s) (#11058)", async (nonInteractive) => { diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index 1bad5bdc3ac..37c8d0a1fd0 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -1177,7 +1177,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ agentRuntime: "openclaw", environmentOrInferenceEndpoint: "Ubuntu; no inference endpoint", profile: "standard", - timeoutMinutes: 60, + timeoutMinutes: 90, installMode: "authenticated", restoreCli: true, exposeCliBin: true, From d53702403ac1769f0c7a292ab2311b898e935730 Mon Sep 17 00:00:00 2001 From: San Dang Date: Thu, 15 Oct 2026 18:52:05 +0700 Subject: [PATCH 3/7] test(e2e): map --policy-tier fast tests to the sequencing live E2E The live onboard-policy-preset-sequencing test now covers the interactive --policy-tier journey. Map the source tests that own its deterministic option, policy-step, and handler behavior so mock/live parity requires them to change with the live case. Refs #13180 Signed-off-by: San Dang --- test/e2e/mock-parity.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 1ac67563b22..42bf4b8659a 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -457,7 +457,10 @@ "live": "test/e2e/live/onboard-policy-preset-sequencing.test.ts", "fast": [ "test/e2e/support/onboard-interactive-pty.test.ts", - "test/e2e/support/runtime-provider-fixture.test.ts" + "test/e2e/support/runtime-provider-fixture.test.ts", + "src/lib/onboard/command-policy-tier.test.ts", + "src/lib/onboard/machine/handlers/policies.test.ts", + "test/runtime/policy/policy-tiers-onboard.test.ts" ] }, { From af5eada63b8ee7b49ff4f6411afd6ebeefe3e823 Mon Sep 17 00:00:00 2001 From: San Dang Date: Thu, 15 Oct 2026 20:16:14 +0700 Subject: [PATCH 4/7] fix(onboard): record --policy-tier with the onboarding session Record an explicit --policy-tier in the onboarding session instead of threading it through the flow options. The sandbox step passes the recorded tier to create-time policy resolution, and the policy step applies it without the tier prompt, for fresh and resumed runs alike. Resume accepts --policy-tier only when it matches the recorded tier and reports a conflict otherwise. When --policy-tier governs the run, skip the NEMOCLAW_POLICY_TIER fail-fast check, because the environment value is unused. Move the tier names to one lightweight domain module shared by command help, session parsing, and create-time planning. Move the environment fail-fast decision out of runOnboard and lower its policy-decision budget. Give the sequencing E2E target a 100-minute budget for its two bounded interactive journeys. Refs #13180 Signed-off-by: San Dang --- ci/onboard-entry-composition-budget.json | 2 +- docs/reference/commands.mdx | 7 +-- docs/reference/network-policies.mdx | 2 +- src/lib/actions/onboard.ts | 9 ++-- src/lib/domain/policy-tier-names.ts | 15 ++++++ src/lib/onboard.ts | 13 +++-- src/lib/onboard/command-policy-tier.test.ts | 13 ++--- src/lib/onboard/command-support.test.ts | 10 ++-- src/lib/onboard/command-support.ts | 7 +-- src/lib/onboard/command.ts | 8 --- src/lib/onboard/machine/core-flow-phases.ts | 3 -- src/lib/onboard/machine/final-flow-phases.ts | 3 -- .../onboard/machine/handlers/policies.test.ts | 9 ++-- src/lib/onboard/machine/handlers/policies.ts | 6 +-- .../sandbox-create-intent-boundary.test.ts | 12 ++--- src/lib/onboard/machine/handlers/sandbox.ts | 16 +++--- src/lib/onboard/policy-selection.ts | 2 +- src/lib/onboard/policy-tier-env.test.ts | 50 +++++++++++++++++++ src/lib/onboard/policy-tier-env.ts | 30 +++++++++++ src/lib/onboard/resume-config.test.ts | 17 +++++++ src/lib/onboard/resume-config.ts | 12 +++++ src/lib/onboard/runtime-control-flow.test.ts | 10 ---- src/lib/onboard/runtime-control-flow.ts | 11 ---- src/lib/onboard/sandbox-create-plan.ts | 13 +++-- src/lib/onboard/session-bootstrap.test.ts | 2 + src/lib/onboard/session-bootstrap.ts | 12 +++++ .../onboard-session-normalization.test.ts | 16 ++++++ src/lib/state/onboard-session.ts | 12 +++++ .../onboard-session/selection-provenance.ts | 3 +- tools/e2e/target-catalogue.mts | 3 +- 30 files changed, 223 insertions(+), 105 deletions(-) create mode 100644 src/lib/domain/policy-tier-names.ts create mode 100644 src/lib/onboard/policy-tier-env.test.ts diff --git a/ci/onboard-entry-composition-budget.json b/ci/onboard-entry-composition-budget.json index 37e43fc0134..558be71b3ee 100644 --- a/ci/onboard-entry-composition-budget.json +++ b/ci/onboard-entry-composition-budget.json @@ -12,7 +12,7 @@ }, "policy": { "preflightAuthoritativeRebuildTarget": 1, - "runOnboard": 4, + "runOnboard": 1, "sandboxCreateIntentResolver.getAgentPolicyPath": 1 }, "provider": { diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 91b5508fb3a..03709334e9e 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -690,8 +690,9 @@ Recreation without an explicit flag or environment value preserves the recorded Select the network policy tier for this onboarding run: `restricted`, `balanced`, `open`, or `personal`. In interactive mode, the wizard skips the tier prompt and still shows the preset review screen. -The flag works in interactive and non-interactive mode and takes precedence over `NEMOCLAW_POLICY_TIER`. -It cannot be combined with `--resume`; start with `--fresh` to choose a new tier. +The flag works in interactive and non-interactive mode and takes precedence over `NEMOCLAW_POLICY_TIER`, which is then not used or validated. +NemoClaw records the tier with the onboarding session, so a resumed session keeps it. +When you pass `--policy-tier` while resuming, it must match the recorded tier; start with `--fresh` to choose a different tier. For tier details, refer to [Network Policies](network-policies#policy-tiers). ```bash @@ -897,7 +898,7 @@ You can also set the tier with `NEMOCLAW_POLICY_TIER` (default: `balanced`): NEMOCLAW_POLICY_TIER=restricted $$nemoclaw onboard --non-interactive --yes-i-accept-third-party-software ``` -Unset, blank, or whitespace-only `NEMOCLAW_POLICY_TIER` values use the `balanced` default. In non-interactive mode, `NEMOCLAW_POLICY_TIER` selects the tier, and any non-blank value must be one of `restricted`, `balanced`, `open`, or `personal`; otherwise onboarding exits before preflight, gateway, or inference side effects with an error listing the valid options. In interactive mode, a valid value pre-selects that tier in the prompt. Interactive onboarding ignores an invalid value and pre-selects `balanced`. `--policy-tier` takes precedence over `NEMOCLAW_POLICY_TIER`. +Unset, blank, or whitespace-only `NEMOCLAW_POLICY_TIER` values use the `balanced` default. In non-interactive mode, `NEMOCLAW_POLICY_TIER` selects the tier, and any non-blank value must be one of `restricted`, `balanced`, `open`, or `personal`; otherwise onboarding exits before preflight, gateway, or inference side effects with an error listing the valid options. In interactive mode, a valid value pre-selects that tier in the prompt. Interactive onboarding ignores an invalid value and pre-selects `balanced`. `--policy-tier` takes precedence over `NEMOCLAW_POLICY_TIER`; when the flag is set, NemoClaw does not validate the environment value. `NEMOCLAW_POLICY_MODE` controls how non-interactive onboarding reconciles the tier-derived suggestions against the sandbox's currently-applied presets. The default is `suggested`, which is _additive_. Onboarding applies tier defaults and preserves any presets you previously added with [`$$nemoclaw policy add`](#$$nemoclaw-name-policy-add) across re-onboards. Use `custom` with `NEMOCLAW_POLICY_PRESETS` when you want the explicit list to be authoritative for optional presets. Onboarding removes any optional preset that is not in the list. `skip` does not add optional tier defaults and retains eligible optional presets already applied. It still applies the required preset for each messaging channel enabled during the same onboarding run so the configured channel can reach its service. For Personal, all modes still apply or retain the mandatory `personal-open-internet` preset. NemoClaw filters tier suggestions and resume selections by active agent support and the selected web search provider. During automatic suggestion and resume reconciliation, it removes stale web-search selections when they conflict with the active agent or selected provider. The Personal tier instead uses `personal-open-internet` for web transport and does not select Brave Search or Tavily Search merely to enable ordinary web fetches. This makes keyless fetches available to any sandbox binary, but it does not add a provider-free `web_search` implementation. diff --git a/docs/reference/network-policies.mdx b/docs/reference/network-policies.mdx index d0b0e7c25a2..5c2e084a518 100644 --- a/docs/reference/network-policies.mdx +++ b/docs/reference/network-policies.mdx @@ -221,7 +221,7 @@ You can also set the tier with `NEMOCLAW_POLICY_TIER`: NEMOCLAW_POLICY_TIER=open $$nemoclaw onboard --non-interactive --yes-i-accept-third-party-software ``` -Unset, blank, or whitespace-only `NEMOCLAW_POLICY_TIER` values use the `balanced` default. In non-interactive onboarding, a non-blank value that does not match a known tier exits before preflight, gateway, or inference side effects and lists the valid options. In interactive onboarding, a valid value pre-selects that tier in the prompt, and an invalid value is ignored. `--policy-tier` takes precedence over `NEMOCLAW_POLICY_TIER`. +Unset, blank, or whitespace-only `NEMOCLAW_POLICY_TIER` values use the `balanced` default. In non-interactive onboarding, a non-blank value that does not match a known tier exits before preflight, gateway, or inference side effects and lists the valid options. In interactive onboarding, a valid value pre-selects that tier in the prompt, and an invalid value is ignored. `--policy-tier` takes precedence over `NEMOCLAW_POLICY_TIER`; when the flag is set, NemoClaw does not validate the environment value. NemoClaw records the flag's tier with the onboarding session, so a resumed session keeps it. ### Inference diff --git a/src/lib/actions/onboard.ts b/src/lib/actions/onboard.ts index b010fcbdc23..d8e55b8a30c 100644 --- a/src/lib/actions/onboard.ts +++ b/src/lib/actions/onboard.ts @@ -4,11 +4,8 @@ import { loadServingCatalog } from "../inference/serving/catalog-loader"; import type { GooglechatTunnelRuntimeDeps } from "../messaging/channels/googlechat/hooks/tunnel-runtime"; import { type OnboardCommandOptions, runOnboardCommand } from "../onboard/command"; -import { - ONBOARD_POLICY_TIER_VALUES, - type OnboardFlags, - readAgentRegistryNames, -} from "../onboard/command-support"; +import { POLICY_TIER_NAMES } from "../domain/policy-tier-names"; +import { type OnboardFlags, readAgentRegistryNames } from "../onboard/command-support"; import { resolveOnboardResumeIntent } from "../onboard/session-bootstrap"; import { loadOnboardCommandResumeSession } from "../onboard/sandbox-registration"; import type { OnboardOptions } from "../onboard/types"; @@ -35,7 +32,7 @@ function buildOnboardCommandDeps(flags: OnboardFlags, runtimeDeps: OnboardAction env: process.env, runOnboard: (options: OnboardCommandOptions) => runOnboard(options, runtimeDeps), listAgents: () => [...readAgentRegistryNames()], - listPolicyTiers: () => ONBOARD_POLICY_TIER_VALUES, + listPolicyTiers: () => POLICY_TIER_NAMES, loadServingCatalog, loadSession: loadOnboardCommandResumeSession, resolveResumeIntent: resolveOnboardResumeIntent, diff --git a/src/lib/domain/policy-tier-names.ts b/src/lib/domain/policy-tier-names.ts new file mode 100644 index 00000000000..3312da26090 --- /dev/null +++ b/src/lib/domain/policy-tier-names.ts @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +/** + * Canonical policy tier names. Mirrors nemoclaw-blueprint/policies/tiers.yaml + * without loading the runtime tier registry, so command help, session parsing, + * and create-time planning can share it. A unit test keeps the two aligned. + */ +export const POLICY_TIER_NAMES = ["restricted", "balanced", "open", "personal"] as const; + +export type PolicyTierName = (typeof POLICY_TIER_NAMES)[number]; + +export function isPolicyTierName(value: unknown): value is PolicyTierName { + return typeof value === "string" && (POLICY_TIER_NAMES as readonly string[]).includes(value); +} diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 36b48aa6874..fd5875a4119 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2464,7 +2464,7 @@ const { selectPolicyTier, selectTierPresetsAndAccess, setupPoliciesWithSelection, - validatePolicyTierEnvEarly, + createPolicyTierEnvGate, } = createOnboardPolicyApplication({ localInferenceProviders: [...LOCAL_INFERENCE_PROVIDERS, "llama-cpp-local"], step, @@ -2605,9 +2605,8 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { const { fresh, nonInteractive, cannotPrompt, resume } = entryOptions; const { requestedFromDockerfile, requestedSandboxName } = entryOptions; NON_INTERACTIVE = nonInteractive; - const validatePolicyTierBeforeRuntime = - isNonInteractive() && !resume && opts.experimentalProfile !== "portable"; - if (validatePolicyTierBeforeRuntime) validatePolicyTierEnvEarly(); + const policyTierEnvGate = createPolicyTierEnvGate(opts, resume, isNonInteractive); + policyTierEnvGate.beforeRuntime(); const baseImageResolutionContext = baseImageResolutionFlow.createBaseImageResolutionContext({ fresh, initialHint: opts.baseImageResolutionHint, @@ -2622,7 +2621,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { portableEnvScope = lockedRuntime.environmentScope; entryDecisions.clearGatewayEnvironmentWithoutBinding(authoritativeGateway, process.env); preparedDcodeRuntime.applyGatewayEnv(process.env); - if (isNonInteractive() && !validatePolicyTierBeforeRuntime) validatePolicyTierEnvEarly(); + policyTierEnvGate.afterRuntime(onboardSession.loadSession); // Validate provider/model hints only after the locked profile and runtime authority are active. const stationSessionInput = onboardEntryOptions.prepareSessionInput( runtimeControlRequests, @@ -3010,7 +3009,8 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { recreateJournalTargetIntentFingerprint: opts.recreateJournalTargetIntentFingerprint ?? null, resumeAgentChanged, - ...runtimeControlFlow.sandboxFlowRuntimeControlOptions(runtimeControlRequests), + requestedObservabilityEnabled: runtimeControlRequests.requestedObservabilityEnabled, + requestedDcodeAutoApprovalMode: runtimeControlRequests.requestedDcodeAutoApprovalMode, hostMounts: effectiveHostMounts, endpointProvenance, recreateSandbox: isRecreateSandbox, @@ -3139,7 +3139,6 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { portableRuntimeContext: agent?.name === "hermes" ? lockedRuntime.portableRuntimeContext : null, preserveRebuildLivePolicy: opts.rebuildPolicySourcePath !== undefined, - requestedPolicyTier: runtimeControlRequests.requestedPolicyTier, agentSetupDeps: { handleAgentSetup: agentOnboard.handleAgentSetup, agentSetupContext: () => ({ diff --git a/src/lib/onboard/command-policy-tier.test.ts b/src/lib/onboard/command-policy-tier.test.ts index 31b64dec5ed..b77187a7c51 100644 --- a/src/lib/onboard/command-policy-tier.test.ts +++ b/src/lib/onboard/command-policy-tier.test.ts @@ -4,7 +4,8 @@ import { describe, expect, it } from "vitest"; import { resolveOnboardOptions, runOnboardCommand } from "./command"; -import { ONBOARD_POLICY_TIER_VALUES, type OnboardFlags } from "./command-support"; +import { POLICY_TIER_NAMES } from "../domain/policy-tier-names"; +import type { OnboardFlags } from "./command-support"; function exitWithCode(code: number): never { throw new Error(`exit:${code}`); @@ -18,13 +19,13 @@ function resolve( env: {}, error: () => {}, exit: exitWithCode, - listPolicyTiers: () => ONBOARD_POLICY_TIER_VALUES, + listPolicyTiers: () => POLICY_TIER_NAMES, ...overrides, }); } describe("onboard --policy-tier (#13180)", () => { - it("normalizes --policy-tier and rejects unknown, Portable, or resumed use (#13180)", () => { + it("normalizes --policy-tier and rejects unknown or Portable use (#13180)", () => { expect(resolve({ "policy-tier": " Restricted " }).requestedPolicyTier).toBe("restricted"); expect(resolve({}).requestedPolicyTier).toBeNull(); @@ -34,11 +35,11 @@ describe("onboard --policy-tier (#13180)", () => { expect(() => resolve({ "policy-tier": "open", "experimental-profile": "portable" }, { error }), ).toThrow("exit:1"); - expect(() => resolve({ "policy-tier": "open", resume: true }, { error })).toThrow("exit:1"); + // Resume is checked against the recorded session tier during session bootstrap. + expect(resolve({ "policy-tier": "open", resume: true }).requestedPolicyTier).toBe("open"); expect(errors).toEqual([ " Unknown policy tier: locked. Valid: restricted, balanced, open, personal", " --policy-tier cannot be used with the Portable profile.", - " --policy-tier cannot be used when resuming onboarding; use --fresh to choose a new tier.", ]); }); @@ -48,7 +49,7 @@ describe("onboard --policy-tier (#13180)", () => { await runOnboardCommand({ flags: { "policy-tier": "restricted" }, env, - listPolicyTiers: () => ONBOARD_POLICY_TIER_VALUES, + listPolicyTiers: () => POLICY_TIER_NAMES, runOnboard: async (options) => { seen.push(options.requestedPolicyTier); expect(env.NEMOCLAW_POLICY_TIER).toBe("open"); diff --git a/src/lib/onboard/command-support.test.ts b/src/lib/onboard/command-support.test.ts index 7b89abd81ae..681c0e114fd 100644 --- a/src/lib/onboard/command-support.test.ts +++ b/src/lib/onboard/command-support.test.ts @@ -3,13 +3,9 @@ import { afterEach, describe, expect, it } from "vitest"; +import { POLICY_TIER_NAMES } from "../domain/policy-tier-names"; import { listTiers } from "../policy/tiers"; -import { - buildOnboardFlags, - ONBOARD_POLICY_TIER_VALUES, - onboardUsage, - setAgentRegistryReaderForTest, -} from "./command-support"; +import { buildOnboardFlags, onboardUsage, setAgentRegistryReaderForTest } from "./command-support"; afterEach(() => { setAgentRegistryReaderForTest(null); @@ -67,7 +63,7 @@ describe("buildOnboardFlags --policy-tier help (#13180)", () => { const flags = buildOnboardFlags(); expect(flags["policy-tier"].options).toEqual(listTiers().map((tier) => tier.name)); - expect([...ONBOARD_POLICY_TIER_VALUES]).toEqual(listTiers().map((tier) => tier.name)); + expect([...POLICY_TIER_NAMES]).toEqual(listTiers().map((tier) => tier.name)); expect(onboardUsage.join(" ")).toContain("--policy-tier "); }); }); diff --git a/src/lib/onboard/command-support.ts b/src/lib/onboard/command-support.ts index 12989026cea..93f9b7c2f3c 100644 --- a/src/lib/onboard/command-support.ts +++ b/src/lib/onboard/command-support.ts @@ -2,15 +2,12 @@ // SPDX-License-Identifier: Apache-2.0 import { Flags } from "@oclif/core"; +import { POLICY_TIER_NAMES } from "../domain/policy-tier-names"; import { TOOL_DISCLOSURE_VALUES, type ToolDisclosure } from "../tool-disclosure"; import { describeAgentFlag } from "./agent-flag-help"; import { PORTABLE_EXPERIMENTAL_PROFILE } from "./docker-driver-platform"; import { NOTICE_ACCEPT_FLAG, NOTICE_ACCEPT_FLAG_NAME } from "./usage-notice"; -// Mirrors nemoclaw-blueprint/policies/tiers.yaml. Kept inline so command help -// does not load the tier registry; a unit test keeps the two lists aligned. -export const ONBOARD_POLICY_TIER_VALUES = ["restricted", "balanced", "open", "personal"] as const; - type AgentRegistryReader = () => readonly string[]; let agentRegistryReaderForTest: AgentRegistryReader | null = null; @@ -171,7 +168,7 @@ export function buildOnboardFlags(options: { includeEvents?: boolean } = {}): Re "policy-tier": Flags.string({ description: "Select the network policy tier without the tier prompt (overrides NEMOCLAW_POLICY_TIER)", - options: [...ONBOARD_POLICY_TIER_VALUES], + options: [...POLICY_TIER_NAMES], }), observability: Flags.boolean({ allowNo: true, diff --git a/src/lib/onboard/command.ts b/src/lib/onboard/command.ts index f51badaef9f..8772eac6c37 100644 --- a/src/lib/onboard/command.ts +++ b/src/lib/onboard/command.ts @@ -478,7 +478,6 @@ function resolveOnboardToolDisclosure( function resolveRequestedPolicyTier( requested: string | undefined, experimentalProfile: ExperimentalOnboardProfile | null, - resume: boolean, deps: ResolveOnboardOptionsDeps, ): string | null { if (requested === undefined) return null; @@ -488,12 +487,6 @@ function resolveRequestedPolicyTier( fail(deps, ` Unknown policy tier: ${requested}. Valid: ${knownTiers.join(", ")}`); } if (experimentalProfile) fail(deps, " --policy-tier cannot be used with the Portable profile."); - if (resume) { - fail( - deps, - " --policy-tier cannot be used when resuming onboarding; use --fresh to choose a new tier.", - ); - } return name; } @@ -531,7 +524,6 @@ export function resolveOnboardOptions( const requestedPolicyTier = resolveRequestedPolicyTier( flags["policy-tier"], experimentalProfile, - resume, deps, ); return { diff --git a/src/lib/onboard/machine/core-flow-phases.ts b/src/lib/onboard/machine/core-flow-phases.ts index 271cccfa48f..5ebe3484f38 100644 --- a/src/lib/onboard/machine/core-flow-phases.ts +++ b/src/lib/onboard/machine/core-flow-phases.ts @@ -82,8 +82,6 @@ export interface SandboxOnboardFlowPhaseOptions< resumeAgentChanged: boolean; requestedObservabilityEnabled?: boolean | null; requestedDcodeAutoApprovalMode?: DcodeAutoApprovalMode | null; - /** Operator-selected `--policy-tier` for this run. */ - requestedPolicyTier?: string | null; rebuildPolicySourcePath?: string; hostMounts?: readonly import("../../state/registry/types").SandboxHostMount[]; endpointProvenance: EndpointProvenanceOptions; @@ -348,7 +346,6 @@ export function createSandboxOnboardFlowPhase< endpointSource: endpointProvenance.endpointSource, resumeAgentChanged: options.resumeAgentChanged, requestedObservabilityEnabled: options.requestedObservabilityEnabled, - requestedPolicyTier: options.requestedPolicyTier ?? null, requestedDcodeAutoApprovalMode: options.requestedDcodeAutoApprovalMode, rebuildPolicySourcePath: options.rebuildPolicySourcePath, hostMounts: options.hostMounts, diff --git a/src/lib/onboard/machine/final-flow-phases.ts b/src/lib/onboard/machine/final-flow-phases.ts index 3d055b4b51d..38acb79f133 100644 --- a/src/lib/onboard/machine/final-flow-phases.ts +++ b/src/lib/onboard/machine/final-flow-phases.ts @@ -42,8 +42,6 @@ export interface FinalOnboardFlowPhaseOptions< branchState: "agent_setup" | "openclaw"; managedOpenclawStartup?: boolean; preserveRebuildLivePolicy?: boolean; - /** Operator-selected `--policy-tier`; skips the policy-tier prompt. */ - requestedPolicyTier?: string | null; agentSetupDeps: AgentSetupStateOptions["deps"]; policiesDeps: PoliciesStateOptions["deps"]; finalization: { @@ -131,7 +129,6 @@ export function createFinalOnboardFlowPhases< const policiesResult = await handlePoliciesState({ resume: context.resume, preserveRebuildLivePolicy: options.preserveRebuildLivePolicy, - requestedPolicyTier: options.requestedPolicyTier ?? null, sandboxName: context.sandboxName, provider: context.provider, hostLocalInferenceRouteOnly: context.hostLocalInferenceRouteOnly === true, diff --git a/src/lib/onboard/machine/handlers/policies.test.ts b/src/lib/onboard/machine/handlers/policies.test.ts index 4915222f17f..b8e99c37ae1 100644 --- a/src/lib/onboard/machine/handlers/policies.test.ts +++ b/src/lib/onboard/machine/handlers/policies.test.ts @@ -4,6 +4,7 @@ import { describe, expect, it, vi } from "vitest"; import { makeMessagingPlan } from "../../../../../test/helpers/messaging-plan-fixtures"; +import { createSession } from "../../../state/onboard-session"; import { createPolicyHandlerDeps, basePolicyHandlerOptions } from "./policies-test-fixture"; import { handlePoliciesState } from "./policies"; @@ -62,9 +63,11 @@ describe("policy state handler", () => { ); }); - it("passes an explicit --policy-tier to fresh policy selection (#13180)", async () => { - const { deps, calls } = createPolicyHandlerDeps(); - await handlePoliciesState({ ...basePolicyHandlerOptions(deps), requestedPolicyTier: "open" }); + it("passes a recorded --policy-tier to policy selection (#13180)", async () => { + const { deps, calls } = createPolicyHandlerDeps({ + loadSession: () => createSession({ policyTier: "open" }), + }); + await handlePoliciesState(basePolicyHandlerOptions(deps)); expect(calls.setupPolicies).toHaveBeenCalledWith( "my-assistant", expect.objectContaining({ selectedPresets: null, tierName: "open" }), diff --git a/src/lib/onboard/machine/handlers/policies.ts b/src/lib/onboard/machine/handlers/policies.ts index 38a371ccd85..fac2d79292c 100644 --- a/src/lib/onboard/machine/handlers/policies.ts +++ b/src/lib/onboard/machine/handlers/policies.ts @@ -32,8 +32,6 @@ export interface PolicyResumeSelection { export interface PoliciesStateOptions { resume: boolean; preserveRebuildLivePolicy?: boolean; - /** Operator-selected `--policy-tier`; skips the policy-tier prompt. */ - requestedPolicyTier?: string | null; sandboxName: string; provider: string; hostLocalInferenceRouteOnly?: boolean; @@ -134,7 +132,6 @@ export interface PoliciesStateResult { export async function handlePoliciesState({ resume, preserveRebuildLivePolicy = false, - requestedPolicyTier = null, sandboxName, provider, hostLocalInferenceRouteOnly = false, @@ -288,7 +285,8 @@ export async function handlePoliciesState({ // Hermes runs keep their own name. agent: normalizeAgentNameForResumeState((agent as { name?: string } | null)?.name), observabilityEnabled, - tierName: requestedPolicyTier, + // A recorded `--policy-tier` replaces the tier prompt. + tierName: latestSession?.policyTier ?? null, webSearchSupported, hermesToolGateways, onSelection: () => undefined, diff --git a/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts b/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts index ad042ef1c3a..2170ae17b64 100644 --- a/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts @@ -299,15 +299,11 @@ describe("sandbox create intent machine boundary", () => { }, ); - it("carries an explicit --policy-tier into create-time policy resolution (#13180)", async () => { - const session = createSession({ sandboxName: "tiered" }); - const { deps, calls } = createDeps(); + it("carries a recorded --policy-tier into create-time policy resolution (#13180)", async () => { + const session = createSession({ sandboxName: "tiered", policyTier: "restricted" }); + const { deps, calls } = createDeps({}, session); - await handleSandboxState({ - ...baseOptions(deps, session), - sandboxName: "tiered", - requestedPolicyTier: "restricted", - }); + await handleSandboxState({ ...baseOptions(deps, session), sandboxName: "tiered" }); expect(calls.resolveCreateIntent).toHaveBeenCalledWith( expect.objectContaining({ policyTier: "restricted" }), diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index 9fa52935c18..c56443d1e94 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -212,8 +212,6 @@ export interface SandboxStateOptions< resumeAgentChanged: boolean; requestedObservabilityEnabled?: boolean | null; requestedDcodeAutoApprovalMode?: DcodeAutoApprovalMode | null; - /** Operator-selected `--policy-tier`; governs the create-time policy tier. */ - requestedPolicyTier?: string | null; rebuildPolicySourcePath?: string; hostMounts?: readonly import("../../../state/registry/types").SandboxHostMount[]; recreateSandbox: (requested?: boolean) => boolean; @@ -1149,11 +1147,6 @@ class SandboxStateFlow< if (bindingCheck.status === "stale") this.rejectStaleCheckpointBindings(bindingCheck); } - private requestedPolicyTierIntent(): { policyTier?: string } { - const tier = this.options.requestedPolicyTier; - return tier ? { policyTier: tier } : {}; - } - private applyObservabilityRequest( state: SandboxStepState, ): SandboxStepState { @@ -1938,7 +1931,7 @@ class SandboxStateFlow< staleExtraProviders, hostMounts: this.options.hostMounts, ...(reuseRegisteredCredentials ? { reuseRegisteredCredentials: true } : {}), - ...this.requestedPolicyTierIntent(), + ...requestedPolicyTierIntent(state.session), }); const recreate = requiresSandboxRecreation(decision, this.options.recreateSandbox(false)); return { @@ -1981,7 +1974,7 @@ class SandboxStateFlow< ...(this.options.rebuildPolicySourcePath ? { rebuildPolicySourcePath: this.options.rebuildPolicySourcePath } : {}), - ...this.requestedPolicyTierIntent(), + ...requestedPolicyTierIntent(state.session), extraProviders, }; } @@ -2777,6 +2770,11 @@ class SandboxStateFlow< } } +/** A recorded `--policy-tier` governs create-time policy for fresh and resumed runs. */ +function requestedPolicyTierIntent(session: Session | null | undefined): { policyTier?: string } { + return session?.policyTier ? { policyTier: session.policyTier } : {}; +} + export async function handleSandboxState< Gpu, Agent, diff --git a/src/lib/onboard/policy-selection.ts b/src/lib/onboard/policy-selection.ts index bd714c33a65..c27f2a45e1e 100644 --- a/src/lib/onboard/policy-selection.ts +++ b/src/lib/onboard/policy-selection.ts @@ -242,7 +242,7 @@ export function createOnboardPolicyApplication(deps: OnboardPolicyApplicationDep setupPoliciesWithSelection(setupDeps, sandboxName, options), ); }, - validatePolicyTierEnvEarly: policyTierEnv.validatePolicyTierEnvEarly, + createPolicyTierEnvGate: policyTierEnv.createPolicyTierEnvGate, }; } diff --git a/src/lib/onboard/policy-tier-env.test.ts b/src/lib/onboard/policy-tier-env.test.ts new file mode 100644 index 00000000000..c8dd9928ded --- /dev/null +++ b/src/lib/onboard/policy-tier-env.test.ts @@ -0,0 +1,50 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { createPolicyTierEnvGate } from "./policy-tier-env"; + +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); +}); + +function stubInvalidEnvTier() { + vi.stubEnv("NEMOCLAW_POLICY_TIER", "locked"); + vi.spyOn(console, "error").mockImplementation(() => undefined); + return vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`exit:${code}`); + }) as typeof process.exit); +} + +describe("policy tier environment gate (#13180)", () => { + it("fails fast on an invalid environment tier without --policy-tier", () => { + stubInvalidEnvTier(); + const gate = createPolicyTierEnvGate({}, false, () => true); + expect(() => gate.beforeRuntime()).toThrow("exit:1"); + }); + + it("does not validate an unused environment tier when --policy-tier is set", () => { + const exit = stubInvalidEnvTier(); + const fresh = createPolicyTierEnvGate({ requestedPolicyTier: "restricted" }, false, () => true); + fresh.beforeRuntime(); + fresh.afterRuntime(() => null); + const resumed = createPolicyTierEnvGate( + { requestedPolicyTier: "restricted" }, + true, + () => true, + ); + resumed.afterRuntime(() => null); + expect(exit).not.toHaveBeenCalled(); + }); + + it("uses a recorded resume tier instead of validating the environment", () => { + const exit = stubInvalidEnvTier(); + const gate = createPolicyTierEnvGate({}, true, () => true); + gate.beforeRuntime(); + gate.afterRuntime(() => ({ policyTier: "restricted" })); + expect(exit).not.toHaveBeenCalled(); + expect(() => gate.afterRuntime(() => ({ policyTier: null }))).toThrow("exit:1"); + }); +}); diff --git a/src/lib/onboard/policy-tier-env.ts b/src/lib/onboard/policy-tier-env.ts index 7c0535044db..3609f875101 100644 --- a/src/lib/onboard/policy-tier-env.ts +++ b/src/lib/onboard/policy-tier-env.ts @@ -38,6 +38,36 @@ export function readPolicyTierPreselectionFromEnv(): string | null { return trimmed || null; } +/** + * Run the NEMOCLAW_POLICY_TIER fail-fast check at the right onboarding point. + * Fresh non-interactive runs validate before runtime side effects; resumed or + * Portable runs validate after the locked runtime is active. An explicit or + * recorded `--policy-tier` governs the run, so the environment value is unused + * and is not validated (#13180). + */ +export function createPolicyTierEnvGate( + opts: { requestedPolicyTier?: string | null; experimentalProfile?: string | null }, + resume: boolean, + isNonInteractive: () => boolean, +): { + beforeRuntime(): void; + afterRuntime(loadSession: () => { policyTier?: string | null } | null): void; +} { + const explicit = Boolean(opts.requestedPolicyTier); + const validatesBeforeRuntime = + isNonInteractive() && !resume && opts.experimentalProfile !== "portable"; + return { + beforeRuntime() { + if (validatesBeforeRuntime && !explicit) validatePolicyTierEnvEarly(); + }, + afterRuntime(loadSession) { + if (!isNonInteractive() || validatesBeforeRuntime || explicit) return; + if (resume && loadSession()?.policyTier) return; + validatePolicyTierEnvEarly(); + }, + }; +} + /** * Early gate intended for the top of onboard(): runs the validation * only when the env var is explicitly set to a non-blank value, so the diff --git a/src/lib/onboard/resume-config.test.ts b/src/lib/onboard/resume-config.test.ts index d69c965269f..14baeef6965 100644 --- a/src/lib/onboard/resume-config.test.ts +++ b/src/lib/onboard/resume-config.test.ts @@ -70,6 +70,23 @@ describe("authoritative rebuild resume config", () => { }); }); + it("resumes a recorded --policy-tier and rejects a different explicit tier (#13180)", () => { + const session = { sandboxName: "demo", policyTier: "restricted" }; + const tierConflicts = (policyTier: string | null, recorded: object = session) => + getResumeConfigConflicts(recorded, { policyTier }).filter( + ({ field }) => field === "policy tier", + ); + + expect(tierConflicts(null)).toEqual([]); + expect(tierConflicts("restricted")).toEqual([]); + expect(tierConflicts("open")).toEqual([ + { field: "policy tier", requested: "open", recorded: "restricted" }, + ]); + expect(tierConflicts("open", { sandboxName: "demo" })).toEqual([ + { field: "policy tier", requested: "open", recorded: null }, + ]); + }); + it("resumes an adopted external-image disclosure when the operator made no explicit choice", () => { expect( getResumeConfigConflicts( diff --git a/src/lib/onboard/resume-config.ts b/src/lib/onboard/resume-config.ts index 260056ef956..f21f21426ab 100644 --- a/src/lib/onboard/resume-config.ts +++ b/src/lib/onboard/resume-config.ts @@ -21,6 +21,7 @@ export interface ResumeSessionLike { agent?: string | null; toolDisclosure?: ToolDisclosure; observabilityEnabled?: boolean; + policyTier?: string | null; metadata?: { fromDockerfile?: string | null; fromImage?: string | null; @@ -144,6 +145,7 @@ export function getResumeConfigConflicts( agent?: string | null; toolDisclosure?: ToolDisclosure | null; observabilityEnabled?: boolean | null; + policyTier?: string | null; hostMounts?: readonly SandboxHostMount[]; /** * Internal rebuild-resume mode: the caller already rewrote the session from @@ -237,6 +239,16 @@ export function getResumeConfigConflicts( }); } + const requestedPolicyTier = opts.policyTier ?? null; + const recordedPolicyTier = session?.policyTier ?? null; + if (requestedPolicyTier && requestedPolicyTier !== recordedPolicyTier) { + conflicts.push({ + field: "policy tier", + requested: requestedPolicyTier, + recorded: recordedPolicyTier, + }); + } + const requestedToolDisclosure = normalizeToolDisclosure(opts.toolDisclosure); const recordedToolDisclosure = normalizeToolDisclosure(session?.toolDisclosure); if (hasInvalidSessionToolDisclosure(session)) { diff --git a/src/lib/onboard/runtime-control-flow.test.ts b/src/lib/onboard/runtime-control-flow.test.ts index 51f858021ac..9ecf6d752de 100644 --- a/src/lib/onboard/runtime-control-flow.test.ts +++ b/src/lib/onboard/runtime-control-flow.test.ts @@ -7,7 +7,6 @@ import { createSession } from "../state/onboard-session"; import { applyOnboardRuntimeControlRequests, planSelectedAgentTransition, - sandboxFlowRuntimeControlOptions, updateSessionAgent, } from "./runtime-control-flow"; @@ -39,15 +38,6 @@ describe("onboard runtime control flow", () => { }); }); - it("hands the per-run policy tier to the sandbox phase (#13180)", () => { - const requests = applyOnboardRuntimeControlRequests({ requestedPolicyTier: "personal" }); - expect(sandboxFlowRuntimeControlOptions(requests)).toEqual({ - requestedObservabilityEnabled: null, - requestedDcodeAutoApprovalMode: null, - requestedPolicyTier: "personal", - }); - }); - it("keeps an authoritative inherited observability value out of explicit request handling", () => { expect( applyOnboardRuntimeControlRequests({ diff --git a/src/lib/onboard/runtime-control-flow.ts b/src/lib/onboard/runtime-control-flow.ts index 00ebcea28ee..535dcab0e95 100644 --- a/src/lib/onboard/runtime-control-flow.ts +++ b/src/lib/onboard/runtime-control-flow.ts @@ -56,17 +56,6 @@ export function applyOnboardRuntimeControlRequests( }; } -/** Per-run requests consumed by the sandbox phase. */ -export function sandboxFlowRuntimeControlOptions( - requests: ReturnType, -) { - return { - requestedObservabilityEnabled: requests.requestedObservabilityEnabled, - requestedDcodeAutoApprovalMode: requests.requestedDcodeAutoApprovalMode, - requestedPolicyTier: requests.requestedPolicyTier, - }; -} - export function updateSessionAgent( session: Session, agentName: string | null | undefined, diff --git a/src/lib/onboard/sandbox-create-plan.ts b/src/lib/onboard/sandbox-create-plan.ts index 3f8c51da58a..ff8d3979699 100644 --- a/src/lib/onboard/sandbox-create-plan.ts +++ b/src/lib/onboard/sandbox-create-plan.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { POLICY_TIER_NAMES } from "../domain/policy-tier-names"; + export { resolvePrimaryMessagingCredentialEnvKeys, resolveSandboxCreateIntent, @@ -20,13 +22,10 @@ export { validateSandboxCreateIntentBindings, } from "./sandbox-create-plan-materialization"; -// Known canonical policy tier names. Kept inline so the create-time path -// validates the env value without pulling `../policy/tiers` (which transitively -// requires `runner.ts` and breaks vitest source resolution for this module's -// tests). The list mirrors `nemoclaw-blueprint/policies/tiers.yaml`; adding a -// tier there requires updating this set so an explicit tier env value reaches -// the create-time policy decision. -const KNOWN_POLICY_TIER_NAMES = new Set(["restricted", "balanced", "open", "personal"]); +// Validate the env value against the lightweight canonical tier names, not +// `../policy/tiers` (which transitively requires `runner.ts` and breaks vitest +// source resolution for this module's tests). +const KNOWN_POLICY_TIER_NAMES: ReadonlySet = new Set(POLICY_TIER_NAMES); export function resolveSandboxCreatePolicyTier(requestedPolicyTier?: string | null): string | null { if (requestedPolicyTier !== undefined) return requestedPolicyTier; diff --git a/src/lib/onboard/session-bootstrap.test.ts b/src/lib/onboard/session-bootstrap.test.ts index 36177d90945..4331d1fa98d 100644 --- a/src/lib/onboard/session-bootstrap.test.ts +++ b/src/lib/onboard/session-bootstrap.test.ts @@ -262,6 +262,7 @@ describe("prepareOnboardSession", () => { nonInteractive: true, requestedToolDisclosure: "direct", requestedObservabilityEnabled: true, + requestedPolicyTier: "restricted", apfInterceptorRequested: true, requestedHostMounts: [ { source: "/srv/project", target: "/sandbox/project", readOnly: true }, @@ -281,6 +282,7 @@ describe("prepareOnboardSession", () => { expect(result.session?.observabilityEnabled).toBe(true); expect(result.session?.observabilityRequestedExplicitly).toBe(true); expect(result.session?.apfInterceptorRequested).toBe(true); + expect(result.session?.policyTier).toBe("restricted"); expect(getSession()?.sessionId).not.toBe("old-session"); }); diff --git a/src/lib/onboard/session-bootstrap.ts b/src/lib/onboard/session-bootstrap.ts index 0205171a0a8..abf98cb77bd 100644 --- a/src/lib/onboard/session-bootstrap.ts +++ b/src/lib/onboard/session-bootstrap.ts @@ -486,6 +486,7 @@ export interface OnboardSessionBootstrapInput { envAgent?: string | null; requestedToolDisclosure?: ToolDisclosure | null; requestedObservabilityEnabled?: boolean | null; + requestedPolicyTier?: string | null; apfInterceptorRequested?: boolean | null; stationExpressIntent?: StationExpressResumeIntent | null; requestedHostMounts?: readonly import("../state/registry/types").SandboxHostMount[]; @@ -512,6 +513,7 @@ export interface OnboardSessionBootstrapDeps { agent?: string | null; toolDisclosure?: ToolDisclosure | null; observabilityEnabled?: boolean | null; + policyTier?: string | null; hostMounts?: readonly import("../state/registry/types").SandboxHostMount[]; authoritativeResumeConfig?: boolean; }, @@ -666,6 +668,14 @@ function reportResumeConflict( } return; } + if (conflict.field === "policy tier") { + deps.error( + conflict.recorded + ? ` Session was started with --policy-tier '${conflict.recorded}', not '${conflict.requested}'.` + : " Session was started without --policy-tier; resume without that flag or start a fresh onboarding session.", + ); + return; + } if (conflict.field === "fromImage") { if (!conflict.recorded) { deps.error( @@ -768,6 +778,7 @@ async function prepareResumeSession( agent: input.agentFlag || null, toolDisclosure: input.requestedToolDisclosure ?? null, observabilityEnabled: input.requestedObservabilityEnabled ?? null, + policyTier: input.requestedPolicyTier ?? null, hostMounts: input.requestedHostMounts, authoritativeResumeConfig: input.authoritativeResumeConfig, }); @@ -816,6 +827,7 @@ function prepareFreshSession( observabilityEnabled: input.requestedObservabilityEnabled === true, observabilityRequestedExplicitly: typeof input.requestedObservabilityEnabled === "boolean", apfInterceptorRequested: input.apfInterceptorRequested === true, + policyTier: input.requestedPolicyTier ?? null, stationExpressIntent: input.stationExpressIntent ?? null, servingProfileProvenance: input.servingProfileProvenance ?? null, vllmGpuDevice: parseVllmGpuDevice(process.env[NEMOCLAW_VLLM_GPU_DEVICE_ENV]), diff --git a/src/lib/state/onboard-session-normalization.test.ts b/src/lib/state/onboard-session-normalization.test.ts index 5a73df0d8af..334dab25759 100644 --- a/src/lib/state/onboard-session-normalization.test.ts +++ b/src/lib/state/onboard-session-normalization.test.ts @@ -103,6 +103,22 @@ describe("onboard session normalization", () => { ).toBe(false); }); + it("keeps a recorded --policy-tier and rejects an unknown saved tier (#13180)", () => { + const selected = createSession({ policyTier: "restricted" }); + expect(normalizeSession(selected)?.policyTier).toBe("restricted"); + expect(createSession().policyTier).toBeNull(); + const legacy: Record = { ...selected }; + delete legacy.policyTier; + expect( + normalizeSession(legacy as Parameters[0])?.policyTier, + ).toBeNull(); + expect( + normalizeSession({ ...selected, policyTier: "locked" } as Parameters< + typeof normalizeSession + >[0]), + ).toBeNull(); + }); + it("refuses malformed saved APF create intent instead of downgrading it (#9833)", () => { const selected = createSession({ apfInterceptorRequested: true }); const malformed = { ...selected, apfInterceptorRequested: "true" }; diff --git a/src/lib/state/onboard-session.ts b/src/lib/state/onboard-session.ts index ef143c64837..f6a83f72b45 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -13,6 +13,7 @@ import path from "node:path"; import { readModelSelectionProvenance, type ModelSelectionProvenance, + isPolicyTierName, parseServingProfileProvenance, type ServingProfileProvenance, } from "./onboard-session/selection-provenance"; @@ -323,6 +324,8 @@ export interface Session { observabilityRequestedExplicitly: boolean; /** Operator-selected APF create mode; this is not observed policy provenance. */ apfInterceptorRequested: boolean; + /** Tier selected with `onboard --policy-tier`; null when the wizard or environment chooses. */ + policyTier: string | null; hermesToolGateways: string[] | null; messagingPlan: SandboxMessagingPlan | null; /** Non-secret names of credential providers registered before sandbox setup completed. */ @@ -1031,6 +1034,7 @@ export function createSession(overrides: Partial = {}): Session { observabilityEnabled: overrides.observabilityEnabled === true, observabilityRequestedExplicitly: overrides.observabilityRequestedExplicitly === true, apfInterceptorRequested: overrides.apfInterceptorRequested === true, + policyTier: isPolicyTierName(overrides.policyTier) ? overrides.policyTier : null, hermesToolGateways: readStringArray(overrides.hermesToolGateways), messagingPlan: parseSandboxMessagingPlan(overrides.messagingPlan), stagedCredentialProviders: readStringArray(overrides.stagedCredentialProviders) ?? [], @@ -1082,6 +1086,13 @@ export function normalizeSession(data: Session | SessionJsonValue | undefined): if (hasOwn(data, "vllmGpuDevice") && data.vllmGpuDevice !== null && !vllmGpuDevice) { return null; } + if ( + hasOwn(data, "policyTier") && + data.policyTier !== null && + !isPolicyTierName(data.policyTier) + ) { + return null; + } const compatibleEndpointReasoningEffort = normalizeReasoningEffort( data.compatibleEndpointReasoningEffort, ); @@ -1168,6 +1179,7 @@ export function normalizeSession(data: Session | SessionJsonValue | undefined): observabilityEnabled: data.observabilityEnabled === true, observabilityRequestedExplicitly: data.observabilityRequestedExplicitly === true, apfInterceptorRequested: data.apfInterceptorRequested === true, + policyTier: isPolicyTierName(data.policyTier) ? data.policyTier : null, hermesToolGateways: readStringArray(data.hermesToolGateways), messagingPlan: parseSandboxMessagingPlan(data.messagingPlan), stagedCredentialProviders: readStringArray(data.stagedCredentialProviders) ?? [], diff --git a/src/lib/state/onboard-session/selection-provenance.ts b/src/lib/state/onboard-session/selection-provenance.ts index aff68946a51..83491268395 100644 --- a/src/lib/state/onboard-session/selection-provenance.ts +++ b/src/lib/state/onboard-session/selection-provenance.ts @@ -1,7 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -/** Shared validation for the two route-selection receipts persisted in an onboard session. */ +/** Shared validation for operator selections persisted in an onboard session. */ +export { isPolicyTierName } from "../../domain/policy-tier-names"; export { readModelSelectionProvenance, type ModelSelectionProvenance, diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index 37c8d0a1fd0..ad9b6608ee8 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -1177,7 +1177,8 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ agentRuntime: "openclaw", environmentOrInferenceEndpoint: "Ubuntu; no inference endpoint", profile: "standard", - timeoutMinutes: 90, + // Two bounded 40-minute interactive journeys plus a 20-minute margin. + timeoutMinutes: 100, installMode: "authenticated", restoreCli: true, exposeCliBin: true, From 960799c0ebb0cb04d16095ab3aef6e67525fea01 Mon Sep 17 00:00:00 2001 From: San Dang Date: Thu, 15 Oct 2026 23:31:49 +0700 Subject: [PATCH 5/7] fix(policy): read --policy-tier names from tiers.yaml Make the tier registry the only owner of tier names. Resolve tiers.yaml relative to the policy module instead of through the runner, so command help, session parsing, and create-time planning can read the names without the runner dependency chain. Remove the duplicated literal list and lower the runner fan-in budget to the measured value. Document that --fresh starts a new onboarding session and that a Personal sandbox cannot move to another tier in place. Refs #13180 Signed-off-by: San Dang --- ci/source-architecture-budget.json | 2 +- docs/reference/commands.mdx | 4 ++- src/lib/actions/onboard.ts | 4 +-- src/lib/domain/policy-tier-names.ts | 15 --------- src/lib/onboard/command-policy-tier.test.ts | 6 ++-- src/lib/onboard/command-support.test.ts | 2 -- src/lib/onboard/command-support.ts | 20 +++++++++-- src/lib/onboard/sandbox-create-plan.ts | 9 ++--- src/lib/policy/tiers.ts | 33 +++++++++++++++++-- .../onboard-session/selection-provenance.ts | 2 +- 10 files changed, 59 insertions(+), 38 deletions(-) delete mode 100644 src/lib/domain/policy-tier-names.ts diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index d903a85ea49..432ad1d2e49 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -27,7 +27,7 @@ "src/lib/messaging/channels/index.ts": 23, "src/lib/onboard/gateway-binding.ts": 49, "src/lib/platform.ts": 20, - "src/lib/runner.ts": 73, + "src/lib/runner.ts": 72, "src/lib/sandbox-name-contract.ts": 20, "src/lib/security/redact.ts": 50, "src/lib/state/mcp-lifecycle-lock.ts": 17, diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 970bda13cd0..c8ecda0757c 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -694,7 +694,9 @@ Select the network policy tier for this onboarding run: `restricted`, `balanced` In interactive mode, the wizard skips the tier prompt and still shows the preset review screen. The flag works in interactive and non-interactive mode and takes precedence over `NEMOCLAW_POLICY_TIER`, which is then not used or validated. NemoClaw records the tier with the onboarding session, so a resumed session keeps it. -When you pass `--policy-tier` while resuming, it must match the recorded tier; start with `--fresh` to choose a different tier. +When you pass `--policy-tier` while resuming, it must match the recorded tier. +To choose a different tier, run `$$nemoclaw onboard --fresh`, which starts a new onboarding session. +A sandbox that already uses the Personal tier cannot move to another tier in place, because Personal replaces overlapping web routes; create a new sandbox with the other tier instead. For tier details, refer to [Network Policies](network-policies#policy-tiers). ```bash diff --git a/src/lib/actions/onboard.ts b/src/lib/actions/onboard.ts index d8e55b8a30c..3df1eabc416 100644 --- a/src/lib/actions/onboard.ts +++ b/src/lib/actions/onboard.ts @@ -4,9 +4,9 @@ import { loadServingCatalog } from "../inference/serving/catalog-loader"; import type { GooglechatTunnelRuntimeDeps } from "../messaging/channels/googlechat/hooks/tunnel-runtime"; import { type OnboardCommandOptions, runOnboardCommand } from "../onboard/command"; -import { POLICY_TIER_NAMES } from "../domain/policy-tier-names"; import { type OnboardFlags, readAgentRegistryNames } from "../onboard/command-support"; import { resolveOnboardResumeIntent } from "../onboard/session-bootstrap"; +import { listPolicyTierNames } from "../policy/tiers"; import { loadOnboardCommandResumeSession } from "../onboard/sandbox-registration"; import type { OnboardOptions } from "../onboard/types"; @@ -32,7 +32,7 @@ function buildOnboardCommandDeps(flags: OnboardFlags, runtimeDeps: OnboardAction env: process.env, runOnboard: (options: OnboardCommandOptions) => runOnboard(options, runtimeDeps), listAgents: () => [...readAgentRegistryNames()], - listPolicyTiers: () => POLICY_TIER_NAMES, + listPolicyTiers: () => listPolicyTierNames(), loadServingCatalog, loadSession: loadOnboardCommandResumeSession, resolveResumeIntent: resolveOnboardResumeIntent, diff --git a/src/lib/domain/policy-tier-names.ts b/src/lib/domain/policy-tier-names.ts deleted file mode 100644 index 3312da26090..00000000000 --- a/src/lib/domain/policy-tier-names.ts +++ /dev/null @@ -1,15 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -/** - * Canonical policy tier names. Mirrors nemoclaw-blueprint/policies/tiers.yaml - * without loading the runtime tier registry, so command help, session parsing, - * and create-time planning can share it. A unit test keeps the two aligned. - */ -export const POLICY_TIER_NAMES = ["restricted", "balanced", "open", "personal"] as const; - -export type PolicyTierName = (typeof POLICY_TIER_NAMES)[number]; - -export function isPolicyTierName(value: unknown): value is PolicyTierName { - return typeof value === "string" && (POLICY_TIER_NAMES as readonly string[]).includes(value); -} diff --git a/src/lib/onboard/command-policy-tier.test.ts b/src/lib/onboard/command-policy-tier.test.ts index b77187a7c51..30d6ad9096b 100644 --- a/src/lib/onboard/command-policy-tier.test.ts +++ b/src/lib/onboard/command-policy-tier.test.ts @@ -4,7 +4,7 @@ import { describe, expect, it } from "vitest"; import { resolveOnboardOptions, runOnboardCommand } from "./command"; -import { POLICY_TIER_NAMES } from "../domain/policy-tier-names"; +import { listPolicyTierNames } from "../policy/tiers"; import type { OnboardFlags } from "./command-support"; function exitWithCode(code: number): never { @@ -19,7 +19,7 @@ function resolve( env: {}, error: () => {}, exit: exitWithCode, - listPolicyTiers: () => POLICY_TIER_NAMES, + listPolicyTiers: listPolicyTierNames, ...overrides, }); } @@ -49,7 +49,7 @@ describe("onboard --policy-tier (#13180)", () => { await runOnboardCommand({ flags: { "policy-tier": "restricted" }, env, - listPolicyTiers: () => POLICY_TIER_NAMES, + listPolicyTiers: listPolicyTierNames, runOnboard: async (options) => { seen.push(options.requestedPolicyTier); expect(env.NEMOCLAW_POLICY_TIER).toBe("open"); diff --git a/src/lib/onboard/command-support.test.ts b/src/lib/onboard/command-support.test.ts index 681c0e114fd..90e5469b468 100644 --- a/src/lib/onboard/command-support.test.ts +++ b/src/lib/onboard/command-support.test.ts @@ -3,7 +3,6 @@ import { afterEach, describe, expect, it } from "vitest"; -import { POLICY_TIER_NAMES } from "../domain/policy-tier-names"; import { listTiers } from "../policy/tiers"; import { buildOnboardFlags, onboardUsage, setAgentRegistryReaderForTest } from "./command-support"; @@ -63,7 +62,6 @@ describe("buildOnboardFlags --policy-tier help (#13180)", () => { const flags = buildOnboardFlags(); expect(flags["policy-tier"].options).toEqual(listTiers().map((tier) => tier.name)); - expect([...POLICY_TIER_NAMES]).toEqual(listTiers().map((tier) => tier.name)); expect(onboardUsage.join(" ")).toContain("--policy-tier "); }); }); diff --git a/src/lib/onboard/command-support.ts b/src/lib/onboard/command-support.ts index 93f9b7c2f3c..611df8c86a2 100644 --- a/src/lib/onboard/command-support.ts +++ b/src/lib/onboard/command-support.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { Flags } from "@oclif/core"; -import { POLICY_TIER_NAMES } from "../domain/policy-tier-names"; +import { listPolicyTierNames } from "../policy/tiers"; import { TOOL_DISCLOSURE_VALUES, type ToolDisclosure } from "../tool-disclosure"; import { describeAgentFlag } from "./agent-flag-help"; import { PORTABLE_EXPERIMENTAL_PROFILE } from "./docker-driver-platform"; @@ -47,8 +47,22 @@ function agentFlagDescription(): string { } } +// Resolve the tier names from tiers.yaml for `--policy-tier` help. If the tier +// file cannot be read, the flag accepts any value and onboarding validates it. +function policyTierFlagOptions(): string[] | undefined { + try { + return listPolicyTierNames(); + } catch { + return undefined; + } +} + +function policyTierUsage(): string { + return policyTierFlagOptions()?.join("|") ?? "tier"; +} + export const onboardUsage = [ - `onboard [--profile ] [--non-interactive] [--resume | --fresh] [--recreate-sandbox] [--apf-interceptor] [--gpu | --no-gpu] [--from | --from-image ] [--name ] [--host-mount ] [--sandbox-gpu | --no-sandbox-gpu] [--sandbox-gpu-device ] [--vllm-gpu-device ] [--agent ] [--agents ] [--tool-disclosure ] [--policy-tier ] [--observability | --no-observability] [--control-ui-port ] [--events=jsonl] [--yes | -y] [--no-ollama-autostart] [${NOTICE_ACCEPT_FLAG}]`, + `onboard [--profile ] [--non-interactive] [--resume | --fresh] [--recreate-sandbox] [--apf-interceptor] [--gpu | --no-gpu] [--from | --from-image ] [--name ] [--host-mount ] [--sandbox-gpu | --no-sandbox-gpu] [--sandbox-gpu-device ] [--vllm-gpu-device ] [--agent ] [--agents ] [--tool-disclosure ] [--policy-tier <${policyTierUsage()}>] [--observability | --no-observability] [--control-ui-port ] [--events=jsonl] [--yes | -y] [--no-ollama-autostart] [${NOTICE_ACCEPT_FLAG}]`, ]; export const onboardExamples = [ @@ -168,7 +182,7 @@ export function buildOnboardFlags(options: { includeEvents?: boolean } = {}): Re "policy-tier": Flags.string({ description: "Select the network policy tier without the tier prompt (overrides NEMOCLAW_POLICY_TIER)", - options: [...POLICY_TIER_NAMES], + options: policyTierFlagOptions(), }), observability: Flags.boolean({ allowNo: true, diff --git a/src/lib/onboard/sandbox-create-plan.ts b/src/lib/onboard/sandbox-create-plan.ts index ff8d3979699..52f10cd8279 100644 --- a/src/lib/onboard/sandbox-create-plan.ts +++ b/src/lib/onboard/sandbox-create-plan.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { POLICY_TIER_NAMES } from "../domain/policy-tier-names"; +import { isPolicyTierName } from "../policy/tiers"; export { resolvePrimaryMessagingCredentialEnvKeys, @@ -22,11 +22,6 @@ export { validateSandboxCreateIntentBindings, } from "./sandbox-create-plan-materialization"; -// Validate the env value against the lightweight canonical tier names, not -// `../policy/tiers` (which transitively requires `runner.ts` and breaks vitest -// source resolution for this module's tests). -const KNOWN_POLICY_TIER_NAMES: ReadonlySet = new Set(POLICY_TIER_NAMES); - export function resolveSandboxCreatePolicyTier(requestedPolicyTier?: string | null): string | null { if (requestedPolicyTier !== undefined) return requestedPolicyTier; // Only trust the env value in non-interactive mode. Interactive flows let the @@ -40,5 +35,5 @@ export function resolveSandboxCreatePolicyTier(requestedPolicyTier?: string | nu const raw = process.env.NEMOCLAW_POLICY_TIER; if (typeof raw !== "string") return null; const trimmed = raw.trim().toLowerCase(); - return KNOWN_POLICY_TIER_NAMES.has(trimmed) ? trimmed : null; + return isPolicyTierName(trimmed) ? trimmed : null; } diff --git a/src/lib/policy/tiers.ts b/src/lib/policy/tiers.ts index 18caf6a871c..5ab55e64e44 100644 --- a/src/lib/policy/tiers.ts +++ b/src/lib/policy/tiers.ts @@ -15,9 +15,19 @@ import path from "node:path"; import YAML from "yaml"; import { isObjectRecord } from "../core/json-types"; -import { ROOT } from "../runner"; -const TIERS_FILE = path.join(ROOT, "nemoclaw-blueprint", "policies", "tiers.yaml"); +// src/lib/policy and dist/lib/policy both sit three levels below the +// repository root. Resolve it locally so loading tier names does not pull in +// the runner dependency chain. +const TIERS_FILE = path.resolve( + __dirname, + "..", + "..", + "..", + "nemoclaw-blueprint", + "policies", + "tiers.yaml", +); export const PERSONAL_POLICY_TIER_NAME = "personal"; export const PERSONAL_OPEN_INTERNET_PRESET_NAME = "personal-open-internet"; const ALLOWED_ACCESS: ReadonlySet = new Set(["read", "read-write"]); @@ -128,6 +138,16 @@ function listTiers(): TierDefinition[] { return parseTierDocument(content).tiers; } +/** Return the tier names defined in tiers.yaml, in file order. */ +function listPolicyTierNames(): string[] { + return listTiers().map((tier) => tier.name); +} + +/** Return whether a value names a tier defined in tiers.yaml. */ +function isPolicyTierName(value: unknown): value is string { + return typeof value === "string" && listPolicyTierNames().includes(value); +} + /** * Return a single tier definition by name. * Returns null if the tier does not exist. @@ -173,4 +193,11 @@ function resolveTierPresets( return presets; } -export { getTier, listTiers, resolveTierPresets, TIERS_FILE }; +export { + getTier, + isPolicyTierName, + listPolicyTierNames, + listTiers, + resolveTierPresets, + TIERS_FILE, +}; diff --git a/src/lib/state/onboard-session/selection-provenance.ts b/src/lib/state/onboard-session/selection-provenance.ts index 83491268395..0c5f905777c 100644 --- a/src/lib/state/onboard-session/selection-provenance.ts +++ b/src/lib/state/onboard-session/selection-provenance.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 /** Shared validation for operator selections persisted in an onboard session. */ -export { isPolicyTierName } from "../../domain/policy-tier-names"; +export { isPolicyTierName } from "../../policy/tiers"; export { readModelSelectionProvenance, type ModelSelectionProvenance, From e8beb59186e938502e98c0fb25722f732f05104e Mon Sep 17 00:00:00 2001 From: San Dang Date: Fri, 16 Oct 2026 00:53:21 +0700 Subject: [PATCH 6/7] fix(onboard): reconcile resumed policy against the recorded tier Pass the recorded --policy-tier to resume preparation, so a resumed Restricted session keeps suppressing agent-required presets and a Personal session keeps its required route before the handler decides to skip reconciliation. Keep --policy-tier to exact tier names. The CLI parser already rejects other values, so remove the resolver's unreachable trimming and case folding. Refs #13180 Signed-off-by: San Dang --- src/lib/onboard/command-policy-tier.test.ts | 6 ++++-- src/lib/onboard/command.ts | 7 ++++--- src/lib/onboard/machine/handlers/policies.test.ts | 11 +++++++++++ src/lib/onboard/machine/handlers/policies.ts | 6 ++++-- 4 files changed, 23 insertions(+), 7 deletions(-) diff --git a/src/lib/onboard/command-policy-tier.test.ts b/src/lib/onboard/command-policy-tier.test.ts index 30d6ad9096b..84322ee2774 100644 --- a/src/lib/onboard/command-policy-tier.test.ts +++ b/src/lib/onboard/command-policy-tier.test.ts @@ -25,13 +25,14 @@ function resolve( } describe("onboard --policy-tier (#13180)", () => { - it("normalizes --policy-tier and rejects unknown or Portable use (#13180)", () => { - expect(resolve({ "policy-tier": " Restricted " }).requestedPolicyTier).toBe("restricted"); + it("accepts exact --policy-tier names and rejects unknown or Portable use (#13180)", () => { + expect(resolve({ "policy-tier": "restricted" }).requestedPolicyTier).toBe("restricted"); expect(resolve({}).requestedPolicyTier).toBeNull(); const errors: string[] = []; const error = (message?: string) => errors.push(String(message)); expect(() => resolve({ "policy-tier": "locked" }, { error })).toThrow("exit:1"); + expect(() => resolve({ "policy-tier": " Restricted " }, { error })).toThrow("exit:1"); expect(() => resolve({ "policy-tier": "open", "experimental-profile": "portable" }, { error }), ).toThrow("exit:1"); @@ -39,6 +40,7 @@ describe("onboard --policy-tier (#13180)", () => { expect(resolve({ "policy-tier": "open", resume: true }).requestedPolicyTier).toBe("open"); expect(errors).toEqual([ " Unknown policy tier: locked. Valid: restricted, balanced, open, personal", + " Unknown policy tier: Restricted . Valid: restricted, balanced, open, personal", " --policy-tier cannot be used with the Portable profile.", ]); }); diff --git a/src/lib/onboard/command.ts b/src/lib/onboard/command.ts index 8772eac6c37..dc797f41097 100644 --- a/src/lib/onboard/command.ts +++ b/src/lib/onboard/command.ts @@ -481,13 +481,14 @@ function resolveRequestedPolicyTier( deps: ResolveOnboardOptionsDeps, ): string | null { if (requested === undefined) return null; - const name = requested.trim().toLowerCase(); + // The CLI parser already limits the flag to exact tier names; this check + // covers direct callers with the same exact-match contract. const knownTiers = deps.listPolicyTiers?.() ?? []; - if (knownTiers.length > 0 && !knownTiers.includes(name)) { + if (knownTiers.length > 0 && !knownTiers.includes(requested)) { fail(deps, ` Unknown policy tier: ${requested}. Valid: ${knownTiers.join(", ")}`); } if (experimentalProfile) fail(deps, " --policy-tier cannot be used with the Portable profile."); - return name; + return requested; } function resolveExternalImageReference( diff --git a/src/lib/onboard/machine/handlers/policies.test.ts b/src/lib/onboard/machine/handlers/policies.test.ts index b8e99c37ae1..c5afe521db1 100644 --- a/src/lib/onboard/machine/handlers/policies.test.ts +++ b/src/lib/onboard/machine/handlers/policies.test.ts @@ -63,6 +63,17 @@ describe("policy state handler", () => { ); }); + it("reconciles a resumed session against its recorded --policy-tier (#13180)", async () => { + const { deps, calls } = createPolicyHandlerDeps({ + loadSession: () => createSession({ policyTier: "restricted" }), + }); + await handlePoliciesState({ ...basePolicyHandlerOptions(deps), resume: true }); + expect(calls.prepareResume).toHaveBeenCalledWith( + "my-assistant", + expect.objectContaining({ tierName: "restricted" }), + ); + }); + it("passes a recorded --policy-tier to policy selection (#13180)", async () => { const { deps, calls } = createPolicyHandlerDeps({ loadSession: () => createSession({ policyTier: "open" }), diff --git a/src/lib/onboard/machine/handlers/policies.ts b/src/lib/onboard/machine/handlers/policies.ts index fac2d79292c..c845fcbfc31 100644 --- a/src/lib/onboard/machine/handlers/policies.ts +++ b/src/lib/onboard/machine/handlers/policies.ts @@ -148,6 +148,7 @@ export async function handlePoliciesState({ deps, }: PoliciesStateOptions): Promise { const latestSession = deps.loadSession(); + const recordedPolicyTier = latestSession?.policyTier ?? null; const observabilityEnabled = latestSession?.observabilityEnabled === true; const recordedMessagingChannels = getActiveChannelsFromPlan(latestSession?.messagingPlan); const activeSandbox = deps.getActiveSandbox(sandboxName); @@ -236,7 +237,8 @@ export async function handlePoliciesState({ webSearchConfig, webSearchConfigChanged, webSearchSupported, - tierName: null, + // A recorded `--policy-tier` governs resume reconciliation too (#13180). + tierName: recordedPolicyTier, }); const livePolicyPresetsForSupport = policyResumeSelection.policyPresets; const staleLocalInferencePolicy = @@ -286,7 +288,7 @@ export async function handlePoliciesState({ agent: normalizeAgentNameForResumeState((agent as { name?: string } | null)?.name), observabilityEnabled, // A recorded `--policy-tier` replaces the tier prompt. - tierName: latestSession?.policyTier ?? null, + tierName: recordedPolicyTier, webSearchSupported, hermesToolGateways, onSelection: () => undefined, From b7204775b915e3c2f590fede8f0f7d5f51bc9a93 Mon Sep 17 00:00:00 2001 From: San Dang Date: Fri, 16 Oct 2026 02:10:19 +0700 Subject: [PATCH 7/7] test(e2e): bound the --policy-tier journey inside the trusted budget Pre-merge E2E dispatch uses the trusted main catalogue, which gives the policy preset sequencing target 60 minutes. Bound the second interactive journey at 15 minutes so both journeys (40 + 15) fit that budget, and set the candidate target to 75 minutes to keep its 20-minute margin after merge. Refs #13180 Signed-off-by: San Dang --- test/e2e/live/onboard-policy-preset-sequencing.test.ts | 9 +++++++-- tools/e2e/target-catalogue.mts | 4 ++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/test/e2e/live/onboard-policy-preset-sequencing.test.ts b/test/e2e/live/onboard-policy-preset-sequencing.test.ts index afff3ded387..0c943bd8ed9 100644 --- a/test/e2e/live/onboard-policy-preset-sequencing.test.ts +++ b/test/e2e/live/onboard-policy-preset-sequencing.test.ts @@ -33,6 +33,11 @@ validateSandboxName(SANDBOX_NAME); const POLICY_TIER_FLAG_SANDBOX_NAME = "e2e-policy-tier"; validateSandboxName(POLICY_TIER_FLAG_SANDBOX_NAME); const ONBOARD_TIMEOUT_MS = 40 * 60_000; +// The #13180 journey runs second, on the gateway the first journey started, +// and finishes in about a minute. Bounding it at 15 minutes keeps both +// journeys (40 + 15) inside the trusted 60-minute target budget that +// pre-merge E2E dispatch uses. +const POLICY_TIER_FLAG_TIMEOUT_MS = 15 * 60_000; const MODEL = "test-model"; // A Docker network namespace cannot reach host loopback directly; bind the // fake endpoint on all interfaces and advertise the OpenShell host alias so @@ -199,7 +204,7 @@ test( test( "interactive onboard applies --policy-tier over NEMOCLAW_POLICY_TIER without the tier prompt (#13180)", { - timeout: ONBOARD_TIMEOUT_MS, + timeout: POLICY_TIER_FLAG_TIMEOUT_MS, meta: { e2ePhases: [ "start the local compatible-endpoint fake server", @@ -265,7 +270,7 @@ test( // The preset review still runs with the flag's tier defaults. { trigger: "Presets (", response: "\r" }, ], - timeoutMs: ONBOARD_TIMEOUT_MS - 5 * 60_000, + timeoutMs: POLICY_TIER_FLAG_TIMEOUT_MS - 3 * 60_000, }); await artifacts.writeText("onboard-policy-tier-flag-transcript.txt", result.output); diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index ad9b6608ee8..9b65ba2d88e 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -1177,8 +1177,8 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ agentRuntime: "openclaw", environmentOrInferenceEndpoint: "Ubuntu; no inference endpoint", profile: "standard", - // Two bounded 40-minute interactive journeys plus a 20-minute margin. - timeoutMinutes: 100, + // Bounded 40- and 15-minute interactive journeys plus a 20-minute margin. + timeoutMinutes: 75, installMode: "authenticated", restoreCli: true, exposeCliBin: true,