diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index 3717e8a8a38..e4d91edf2ca 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": 1260, - "matcherAssertions": 1239, + "expectCalls": 1263, + "matcherAssertions": 1242, "nodeAssertions": 104, "namedAssertionHelpers": 417, "failCalls": 0, "throwGuards": 50, "objectFieldAssertions": 177, - "assertionPoints": 1987, + "assertionPoints": 1990, "generatedProbeBlocks": 86, "generatedProbeConditions": 215 }, "unique": { - "expectCalls": 1683, - "matcherAssertions": 1657, + "expectCalls": 1686, + "matcherAssertions": 1660, "nodeAssertions": 127, "namedAssertionHelpers": 661, "failCalls": 1, "throwGuards": 526, "objectFieldAssertions": 254, - "assertionPoints": 3226, + "assertionPoints": 3229, "generatedProbeBlocks": 208, "generatedProbeConditions": 720 }, @@ -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 9b44751989d..4c9b23fe66a 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": [ { @@ -46,6 +46,10 @@ { "pullRequest": 13064, "changeSha256": "68c1ed04adc264f0030f864b9a3e9d4f51fe352c9da9e41d000eac6d20206cb8" + }, + { + "pullRequest": 13244, + "changeSha256": "ee325f45fb2d97779f14e3bed8b4e3798b4058e46d6e8b91817de420595c8da8" } ] } 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/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/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 c9c42bccf48..edb79dce36a 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 ] [--dcode-auto-approval ] [--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 ] [--dcode-auto-approval ] [--observability | --no-observability] [--control-ui-port ] [--events=jsonl] [--yes | -y] [--no-ollama-autostart] [--yes-i-accept-third-party-software] ``` @@ -689,6 +689,21 @@ $$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`, 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. +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 +$$nemoclaw onboard --policy-tier restricted +``` + #### `--dcode-auto-approval ` @@ -886,13 +901,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`; 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. @@ -3765,7 +3786,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 `, `--dcode-auto-approval `, `--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 `, `--dcode-auto-approval `, `--observability` / `--no-observability`, `--control-ui-port`, `--yes` / `-y`, `--no-ollama-autostart`, `--yes-i-accept-third-party-software`. ```bash $$nemoclaw setup @@ -3778,7 +3799,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 `, `--dcode-auto-approval `, `--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 `, `--dcode-auto-approval `, `--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..5c2e084a518 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`; 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.test.ts b/src/lib/actions/onboard.test.ts index 4085f1e87ff..eeb7150f16c 100644 --- a/src/lib/actions/onboard.test.ts +++ b/src/lib/actions/onboard.test.ts @@ -39,4 +39,27 @@ describe("onboard action runtime composition", () => { googlechatTunnelRuntime, }); }); + + 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: deps.flags["policy-tier"] }); + }, + ); + const ambient = process.env.NEMOCLAW_POLICY_TIER; + + await runOnboardAction({ "policy-tier": "restricted" }); + await runOnboardAction({ "policy-tier": "open" }); + + 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 9beb40d57d8..3df1eabc416 100644 --- a/src/lib/actions/onboard.ts +++ b/src/lib/actions/onboard.ts @@ -6,6 +6,7 @@ import type { GooglechatTunnelRuntimeDeps } from "../messaging/channels/googlech import { type OnboardCommandOptions, runOnboardCommand } from "../onboard/command"; 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"; @@ -31,6 +32,7 @@ function buildOnboardCommandDeps(flags: OnboardFlags, runtimeDeps: OnboardAction env: process.env, runOnboard: (options: OnboardCommandOptions) => runOnboard(options, runtimeDeps), listAgents: () => [...readAgentRegistryNames()], + listPolicyTiers: () => listPolicyTierNames(), loadServingCatalog, loadSession: loadOnboardCommandResumeSession, resolveResumeIntent: resolveOnboardResumeIntent, diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index a0bd185746a..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, 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..84322ee2774 --- /dev/null +++ b/src/lib/onboard/command-policy-tier.test.ts @@ -0,0 +1,73 @@ +// 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 { listPolicyTierNames } from "../policy/tiers"; +import 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: listPolicyTierNames, + ...overrides, + }); +} + +describe("onboard --policy-tier (#13180)", () => { + 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"); + // 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", + " Unknown policy tier: Restricted . Valid: restricted, balanced, open, personal", + " --policy-tier cannot be used with the Portable profile.", + ]); + }); + + it("carries --policy-tier on the run options without mutating the environment (#13180)", async () => { + const env: NodeJS.ProcessEnv = { NEMOCLAW_POLICY_TIER: "open" }; + const seen: Array = []; + await runOnboardCommand({ + flags: { "policy-tier": "restricted" }, + env, + listPolicyTiers: listPolicyTierNames, + runOnboard: async (options) => { + seen.push(options.requestedPolicyTier); + expect(env.NEMOCLAW_POLICY_TIER).toBe("open"); + }, + }); + expect(seen).toEqual(["restricted"]); + expect(env).toEqual({ NEMOCLAW_POLICY_TIER: "open" }); + }); + + 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..90e5469b468 100644 --- a/src/lib/onboard/command-support.test.ts +++ b/src/lib/onboard/command-support.test.ts @@ -3,6 +3,7 @@ import { afterEach, describe, expect, it } from "vitest"; +import { listTiers } from "../policy/tiers"; import { buildOnboardFlags, onboardUsage, setAgentRegistryReaderForTest } from "./command-support"; afterEach(() => { @@ -56,6 +57,15 @@ 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(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 aec0722b2cd..27b36940b97 100644 --- a/src/lib/onboard/command-support.ts +++ b/src/lib/onboard/command-support.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { Flags } from "@oclif/core"; +import { listPolicyTierNames } from "../policy/tiers"; import { TOOL_DISCLOSURE_VALUES, type ToolDisclosure } from "../tool-disclosure"; import { DCODE_AUTO_APPROVAL_MODES, type DcodeAutoApprovalMode } from "./dcode-auto-approval"; import { describeAgentFlag } from "./agent-flag-help"; @@ -47,8 +48,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 ] [--dcode-auto-approval ] [--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()}>] [--dcode-auto-approval ] [--observability | --no-observability] [--control-ui-port ] [--events=jsonl] [--yes | -y] [--no-ollama-autostart] [${NOTICE_ACCEPT_FLAG}]`, ]; export const onboardExamples = [ @@ -61,6 +76,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}`, ]; @@ -86,6 +102,7 @@ export type OnboardFlags = { agent?: string; agents?: string; "tool-disclosure"?: ToolDisclosure; + "policy-tier"?: string; "dcode-auto-approval"?: DcodeAutoApprovalMode; observability?: boolean; "control-ui-port"?: number; @@ -164,6 +181,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: policyTierFlagOptions(), + }), "dcode-auto-approval": Flags.string({ description: "Choose the managed Deep Agents Code capability; thread-opt-in permits explicit per-thread activation without activating auto-approval", diff --git a/src/lib/onboard/command.test.ts b/src/lib/onboard/command.test.ts index 319fd46ee02..a9852040a39 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, dcodeAutoApprovalMode: null, observabilityEnabled: true, controlUiPort: 18790, @@ -354,6 +355,7 @@ describe("onboard command options", () => { agent: null, agentsManifest: null, toolDisclosure: null, + requestedPolicyTier: null, dcodeAutoApprovalMode: null, observabilityEnabled: null, controlUiPort: null, diff --git a/src/lib/onboard/command.ts b/src/lib/onboard/command.ts index 3f38856927a..befbc85971c 100644 --- a/src/lib/onboard/command.ts +++ b/src/lib/onboard/command.ts @@ -85,6 +85,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; dcodeAutoApprovalMode: DcodeAutoApprovalMode | null; observabilityEnabled: boolean | null; controlUiPort: number | null; @@ -106,6 +108,7 @@ export interface ResolveOnboardOptionsDeps { arch?: NodeJS.Architecture; runtimeProviders?: import("./runtime-provider/access").RuntimeProviderBundleRegistry; listAgents?: () => string[]; + listPolicyTiers?: () => readonly string[]; listServingProfiles?: () => ServingProfileListEntry[]; loadServingCatalog?: () => CompiledServingCatalog; loadSession?: () => { @@ -474,6 +477,22 @@ function resolveOnboardToolDisclosure( } } +function resolveRequestedPolicyTier( + requested: string | undefined, + experimentalProfile: ExperimentalOnboardProfile | null, + deps: ResolveOnboardOptionsDeps, +): string | null { + if (requested === undefined) return null; + // 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(requested)) { + fail(deps, ` Unknown policy tier: ${requested}. Valid: ${knownTiers.join(", ")}`); + } + if (experimentalProfile) fail(deps, " --policy-tier cannot be used with the Portable profile."); + return requested; +} + function resolveExternalImageReference( value: string | undefined, deps: ResolveOnboardOptionsDeps, @@ -505,6 +524,11 @@ 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, + deps, + ); return { tempManagedRuntime: flags["temp-managed-runtime"] === true, tempManagedRuntimeCatalog: resolveFileOption( @@ -530,6 +554,7 @@ export function resolveOnboardOptions( agent, agentsManifest: resolveAgentsManifest(flags.agents, agent, deps), toolDisclosure, + requestedPolicyTier, dcodeAutoApprovalMode: flags["dcode-auto-approval"] ?? null, observabilityEnabled: typeof flags.observability === "boolean" ? flags.observability : null, controlUiPort: flags["control-ui-port"] ?? null, diff --git a/src/lib/onboard/machine/handlers/policies.test.ts b/src/lib/onboard/machine/handlers/policies.test.ts index 8b6eab155d0..c5afe521db1 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,6 +63,35 @@ 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" }), + }); + await handlePoliciesState(basePolicyHandlerOptions(deps)); + 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..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 = @@ -285,7 +287,8 @@ export async function handlePoliciesState({ // Hermes runs keep their own name. agent: normalizeAgentNameForResumeState((agent as { name?: string } | null)?.name), observabilityEnabled, - tierName: null, + // A recorded `--policy-tier` replaces the tier prompt. + tierName: recordedPolicyTier, 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..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,6 +299,18 @@ describe("sandbox create intent machine boundary", () => { }, ); + 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" }); + + 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..c56443d1e94 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -1931,6 +1931,7 @@ class SandboxStateFlow< staleExtraProviders, hostMounts: this.options.hostMounts, ...(reuseRegisteredCredentials ? { reuseRegisteredCredentials: true } : {}), + ...requestedPolicyTierIntent(state.session), }); const recreate = requiresSandboxRecreation(decision, this.options.recreateSandbox(false)); return { @@ -1973,6 +1974,7 @@ class SandboxStateFlow< ...(this.options.rebuildPolicySourcePath ? { rebuildPolicySourcePath: this.options.rebuildPolicySourcePath } : {}), + ...requestedPolicyTierIntent(state.session), extraProviders, }; } @@ -2768,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-prompts.test.ts b/src/lib/onboard/policy-selection-prompts.test.ts index f07d2969460..6b47954a2ce 100644 --- a/src/lib/onboard/policy-selection-prompts.test.ts +++ b/src/lib/onboard/policy-selection-prompts.test.ts @@ -67,17 +67,20 @@ function createHarness({ stdinTTY = true, stdoutTTY = true, promptReplies = [], + envTier = null, }: { tiers?: TierDefinition[]; stdinTTY?: boolean; stdoutTTY?: boolean; promptReplies?: string[]; + envTier?: string | null; } = {}) { 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 +88,11 @@ function createHarness({ getTier: (name) => tiers.find((tier) => tier.name === name) ?? null, }, policyTierEnv: { - resolvePolicyTierFromEnv: () => "balanced", + resolvePolicyTierFromEnv: () => envTier ?? "balanced", + readPolicyTierPreselectionFromEnv: () => envTier, }, isNonInteractive: () => false, - note: vi.fn(), + note, prompt, selectFromNumberedMenuOrExit, makeOnboardCancelExit: (rollback, cleanup, exit) => () => { @@ -103,7 +107,7 @@ function createHarness({ processEvents, }); - return { helpers, markCancelled, processEvents, prompt, stdin, stdout }; + return { helpers, markCancelled, note, processEvents, prompt, stdin, stdout }; } afterEach(() => { @@ -134,6 +138,45 @@ 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("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..18e116b4a3d 100644 --- a/src/lib/onboard/policy-selection-prompts.ts +++ b/src/lib/onboard/policy-selection-prompts.ts @@ -34,6 +34,7 @@ export interface PolicySelectionPromptDeps { }; policyTierEnv: { resolvePolicyTierFromEnv(): string; + readPolicyTierPreselectionFromEnv(): string | null; }; isNonInteractive(): boolean; note(message: string): void; @@ -124,13 +125,14 @@ 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). * 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."); } @@ -140,6 +142,19 @@ export function createPolicySelectionPromptHelpers(deps: PolicySelectionPromptDe 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-selection.ts b/src/lib/onboard/policy-selection.ts index 4fce6bd043c..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, }; } @@ -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.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 5e7471a8818..3609f875101 100644 --- a/src/lib/onboard/policy-tier-env.ts +++ b/src/lib/onboard/policy-tier-env.ts @@ -26,6 +26,48 @@ export function resolvePolicyTierFromEnv(): string { return name; } +/** + * 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; +} + +/** + * 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 b7ab1ac59f8..9ecf6d752de 100644 --- a/src/lib/onboard/runtime-control-flow.test.ts +++ b/src/lib/onboard/runtime-control-flow.test.ts @@ -21,17 +21,20 @@ 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, }); }); @@ -45,6 +48,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..535dcab0e95 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,7 @@ export function applyOnboardRuntimeControlRequests( requestedDcodeAutoApprovalMode: isDcodeAutoApprovalMode(opts.dcodeAutoApprovalMode) ? opts.dcodeAutoApprovalMode : null, + requestedPolicyTier: opts.requestedPolicyTier ?? null, }; } diff --git a/src/lib/onboard/sandbox-create-plan.ts b/src/lib/onboard/sandbox-create-plan.ts index 3f8c51da58a..52f10cd8279 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 { isPolicyTierName } from "../policy/tiers"; + export { resolvePrimaryMessagingCredentialEnvKeys, resolveSandboxCreateIntent, @@ -20,14 +22,6 @@ 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"]); - 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 @@ -41,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/onboard/session-bootstrap.test.ts b/src/lib/onboard/session-bootstrap.test.ts index 2a13990f4fe..1c19e7e06d5 100644 --- a/src/lib/onboard/session-bootstrap.test.ts +++ b/src/lib/onboard/session-bootstrap.test.ts @@ -319,6 +319,7 @@ describe("prepareOnboardSession", () => { nonInteractive: true, requestedToolDisclosure: "direct", requestedObservabilityEnabled: true, + requestedPolicyTier: "restricted", apfInterceptorRequested: true, requestedHostMounts: [ { source: "/srv/project", target: "/sandbox/project", readOnly: true }, @@ -338,6 +339,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 a19f6dfbacb..6a5285e5acf 100644 --- a/src/lib/onboard/session-bootstrap.ts +++ b/src/lib/onboard/session-bootstrap.ts @@ -487,6 +487,7 @@ export interface OnboardSessionBootstrapInput { envAgent?: string | null; requestedToolDisclosure?: ToolDisclosure | null; requestedObservabilityEnabled?: boolean | null; + requestedPolicyTier?: string | null; requestedDcodeAutoApprovalMode?: DcodeAutoApprovalMode | null; apfInterceptorRequested?: boolean | null; stationExpressIntent?: StationExpressResumeIntent | null; @@ -514,6 +515,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; }, @@ -668,6 +670,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( @@ -770,6 +780,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, }); @@ -826,6 +837,7 @@ function prepareFreshSession( input.requestedDcodeAutoApprovalMode, ), 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/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/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-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 cd20f67f501..6ea753850a7 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -14,6 +14,7 @@ import path from "node:path"; import { readModelSelectionProvenance, type ModelSelectionProvenance, + isPolicyTierName, parseServingProfileProvenance, type ServingProfileProvenance, } from "./onboard-session/selection-provenance"; @@ -332,6 +333,8 @@ export interface Session { dcodeAutoApprovalRequestedExplicitly: 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. */ @@ -1047,6 +1050,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) ?? [], @@ -1098,6 +1102,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, ); @@ -1189,6 +1200,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..0c5f905777c 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 "../../policy/tiers"; export { readModelSelectionProvenance, type ModelSelectionProvenance, diff --git a/test/e2e/live/onboard-policy-preset-sequencing.test.ts b/test/e2e/live/onboard-policy-preset-sequencing.test.ts index a141ccfe832..0c943bd8ed9 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,7 +30,14 @@ 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; +// 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 @@ -51,6 +59,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 +147,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 +194,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: POLICY_TIER_FLAG_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: POLICY_TIER_FLAG_TIMEOUT_MS - 3 * 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/e2e/mock-parity.json b/test/e2e/mock-parity.json index 21256f07a43..cc8aae4173f 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -459,7 +459,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" ] }, { diff --git a/test/onboarding/presets-checkbox.test.ts b/test/onboarding/presets-checkbox.test.ts index 05bb74390ef..b54d68d290b 100644 --- a/test/onboarding/presets-checkbox.test.ts +++ b/test/onboarding/presets-checkbox.test.ts @@ -51,6 +51,7 @@ async function runCheckboxSelector( }, policyTierEnv: { resolvePolicyTierFromEnv: () => "balanced", + readPolicyTierPreselectionFromEnv: () => 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..25973fd5e51 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"), @@ -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 8da00cbb04f..a0f7c5a5bf0 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: 60, + // Bounded 40- and 15-minute interactive journeys plus a 20-minute margin. + timeoutMinutes: 75, installMode: "authenticated", restoreCli: true, exposeCliBin: true,