Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Make Assistant controls describe governed action planning
pulse-triage[bot]1927020ba221
diff --git a/docs/AI.md b/docs/AI.mdindex ef56b82eb3..4899253228 100644--- a/docs/AI.md+++ b/docs/AI.md@@ -476,21 +476,26 @@ The assistant enforces multiple safety gates:### Control Levels-| Level | Behavior | Plan |-|-------|----------|---------|-| **Read-only** | AI can observe and query data only | Community |-| **Controlled** | AI asks for approval before executing commands | Community |-| **Autonomous** | AI executes actions without prompting | Pro / hosted Cloud |--### Using Approvals (Controlled Mode)--When control level is **Controlled**, write actions pause for approval:--1. Tool returns `APPROVAL_REQUIRED: { approval_id, command, ... }`-2. Agentic loop emits `approval_needed` SSE event-3. UI shows approval card with the proposed command-4. **Approve** to execute and verify, or **Deny** to cancel-5. Only users with admin privileges can approve/deny+| Mode | Behaviour | Availability |+|------|-----------|--------------|+| **Read-only** | Assistant queries and explains; no infrastructure action planning | Community |+| **Ask first** (`controlled`) | Assistant saves infrastructure action plans to **Actions** for your review | Community |++Assistant chat does not execute these plans. Patrol's own mode and Autopilot+policy are separate; changing Chat action mode grants no Patrol authority.+Older saved `autonomous` preferences display as **Ask first**, not as permission+to execute without approval. The stored preference and its existing entitlement+checks are preserved for older clients.++### Reviewing an Assistant action plan++1. Assistant submits a typed action for a resource advertising that capability.+2. Pulse records the plan in **Actions**; planning is not execution.+3. Open **Actions** to check the target, proposed operation, approval policy and expiry.+4. An authorised operator reviews, approves where required, and runs the plan+ through the existing action controls. Chat mode cannot bypass these checks.+5. Read the recorded execution and independent verification result. A saved plan+ or successful command alone does not establish recovery.---diff --git a/docs/AI_AUTONOMY.md b/docs/AI_AUTONOMY.mdindex 02c8fab836..075bbc2d69 100644--- a/docs/AI_AUTONOMY.md+++ b/docs/AI_AUTONOMY.md@@ -95,31 +95,33 @@ Without the `ai_autofix` capability, the effective Patrol mode is clamped to `mo## Assistant Control Levels-Control levels govern what the interactive Pulse Assistant can do during chat sessions.+Control levels govern interactive Assistant queries and action planning, not+Patrol's autonomy or permission to execute infrastructure work.-| Level | Key | Query | Execute Commands | Plan |-|-------|-----|:-----:|:----------------:|------|+| Mode | Key | Query | Plan infrastructure actions | Availability |+|------|-----|:-----:|:---------------------------:|--------------|| **Read-only** | `read_only` | Yes | No | Community |-| **Controlled** | `controlled` | Yes | With approval | Community |-| **Autonomous** | `autonomous` | Yes | Yes | Pro / legacy Pro+ / Cloud |+| **Ask first** | `controlled` | Yes | For operator review in **Actions** | Community |-- **Read-only** (default): The assistant can query metrics, storage, and resource status but cannot execute any control actions.-- **Controlled**: The assistant can propose commands but pauses for your explicit approval before execution. Each command shows a detailed approval card in the chat UI.-- **Autonomous**: The assistant executes commands without prompting. Requires a Pro, legacy Pro+, or Cloud license.+Assistant chat does not execute the plans it saves. A legacy saved `autonomous`+preference displays as **Ask first** and keeps its stored value and existing+entitlement checks for older clients. It does not bypass approval. An unrelated+settings save does not rewrite that preference. Unknown values fail closed to+read-only. Patrol mode and Autopilot acknowledgements remain separate.### Configuration-**UI:** Settings → Pulse Intelligence → Assistant → Chat command mode+**UI:** Settings → Pulse Intelligence → Assistant → Chat action mode-**API:** This intentionally changes chat command access. Use the same private+**API:** This intentionally changes Assistant action planning access. Use the same privateadministrator header file with `settings:write`; the token must also havepermission to change settings. Prefer the UI for one-off changes, and verify-the saved **Chat command mode** there afterwards. Do not use a write as an+the saved **Chat action mode** there afterwards. Do not use a write as anauthentication test.Use the same `pulse_api` helper defined above, with its private response fileand request limits. Supporting PUT in the helper grants no additional access.-If the response is lost, check the saved **Chat command mode** in the UI before+If the response is lost, check the saved **Chat action mode** in the UI beforedeciding whether another change is needed; do not repeat the write blindly.```bash@@ -128,17 +130,16 @@ pulse_api PUT /api/settings/ai/update <<'JSON'JSON```-### Approval Flow (Controlled Mode)+### Reviewing plans (Ask first)-When control level is `controlled`, write operations follow this flow:--1. The assistant proposes a command (e.g., `qm start 100`).-2. An `APPROVAL_REQUIRED` response is emitted with an `approval_id`.-3. The UI displays an approval card showing the exact command.-4. You click **Approve** or **Deny**.-5. On approval, the command executes and the assistant verifies the result.--Approvals expire after 5 minutes if not acted upon.+1. Assistant requests a typed action for an explicitly identified resource with+ the advertised capability.+2. Pulse saves the canonical plan in **Actions** without requesting execution.+3. Review the target, operation, approval policy and expiry in **Actions**.+4. Use the existing authorised approval and run controls; Chat action mode grants+ no additional access or automatic approval.+5. Read the recorded execution and independent verification outcome before+ concluding that the operation worked. Do not repeat an uncertain operation.---diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex e0fdf6ff73..00492ee4a0 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -15,6 +15,20 @@## Purpose+A legacy client echoing the projected `controlled` mode into an unrelated AI+settings PUT must retain a stored `autonomous` preference and its existing+legacy command-approval selection. `TestAssistantProjectedModeEchoPreservesLegacyPolicy`+uses actual encrypted GET/PUT persistence with and without the entitlement,+then checks explicit read-only opt-out and later opt-in remain possible.++### Assistant control presentation does not change agent authority++AI settings responses project legacy Assistant levels to planning for review;+this grants no agent command, enrolment, identity or transport authority.+Protected guests and authenticated execute authority still govern typed plans.+Existing agent report/command and shared capability vocabularies remain+unchanged, including their separate approval and entitlement enforcement.+### QGA query-eligibility provenance stays internalThe shared VM model's `GuestAgentEvidence` is monitor-owned source-timediff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 30312f3b0c..065b256ae6 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -25,6 +25,26 @@ that same result. Successful reads retain their content and execution provenance## Purpose+A legacy client echoing the projected `controlled` mode into an unrelated AI+settings PUT must retain a stored `autonomous` preference and its existing+legacy command-approval selection. `TestAssistantProjectedModeEchoPreservesLegacyPolicy`+uses actual encrypted GET/PUT persistence with and without the entitlement,+then checks explicit read-only opt-out and later opt-in remain possible.++### Interactive Assistant modes reflect action planning++Interactive Assistant offers Read-only and Ask first (`controlled`).+`config.AssistantControlLevel` projects legacy `autonomous` to controlled only+for interactive responses/tool availability. Saved bytes, shared capability+vocabulary, entitlement checks and legacy `IsAutonomous` approval-admission+remain intact; removing that legacy check would relax command approval.+Chat's control tool saves typed plans to Actions without execution. Scoped+handoff flags, execute authority, policy, protected guests and action lifecycle+review/run/verification remain necessary; Patrol mode/Autopilot is separate.+Unrelated Settings saves compare normalised values and preserve saved legacy+preferences. Runtime, real encrypted-settings roundtrip/API, mounted component+and public-help controls cover this boundary; no installed action is proved.+### Assistant action plans do not guess an installation from session placementAn explicit current canonical resource ID takes precedence over stale sessiondiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 41f3fa8985..f0b562088d 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -20,6 +20,23 @@## Purpose+A legacy client echoing the projected `controlled` mode into an unrelated AI+settings PUT must retain a stored `autonomous` preference and its existing+legacy command-approval selection. `TestAssistantProjectedModeEchoPreservesLegacyPolicy`+uses actual encrypted GET/PUT persistence with and without the entitlement,+then checks explicit read-only opt-out and later opt-in remain possible.++### Assistant control_level is an interactive projection++AI settings GET/PUT responses expose `read_only` or `controlled`: an entitled+legacy `autonomous` preference presents planning for operator review, never+unprompted execution. Existing legacy PUT validation and `ai_autofix` checks+remain; an entitled old client can retain the stored preference, an unentitled+request is refused. Unrelated saves do not rewrite it. Shared external-agent+vocabulary, Patrol settings, protected-guest arrays and authenticated authority+remain unchanged. `TestContract_AssistantSettingsAdvertisePlanningNotExecution`+and the actual persistence/handler tests pin responses and compatibility.+### Optional held-alert breach date consumer`MetricAlertStatus.lastBreachAt?: string` mirrors the existing backend ISOdiff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex 79bb5f2eaa..f753dc894f 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -20,6 +20,17 @@## Purpose+### Existing Assistant control selectors describe planning++Settings and Chat have only Read-only and Ask first options. Legacy+`autonomous`/`suggest` responses render Ask first without a permission warning+or third execution mode; unknown values render Read-only. Settings compares+normalised values before PUT so unrelated saves preserve a legacy preference.+The two-option Chat menu keeps radio semantics, keyboard cycling/Escape/focus+and saved-error recovery. Copy explains infrastructure plans in Actions and+separate Patrol authority; it does not grant approval or execution. Existing+scoped resource/alert/Patrol briefings and compact layouts remain intact.+### Shared alert breach-date presentationExisting attention and alert/history hover copy uses the validateddiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex a7290cc341..b44f941508 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -21,6 +21,20 @@## Purpose+A legacy client echoing the projected `controlled` mode into an unrelated AI+settings PUT must retain a stored `autonomous` preference and its existing+legacy command-approval selection. `TestAssistantProjectedModeEchoPreservesLegacyPolicy`+uses actual encrypted GET/PUT persistence with and without the entitlement,+then checks explicit read-only opt-out and later opt-in remain possible.++### Assistant planning mode grants no recovery execution++The AI settings control projection describes read/query or plans for review in+Actions. It does not authorise a backup, restore, replay or data change; action+approval/run and independent verification remain separate. Stored legacy+preferences, recovery-point access, protected guests and Patrol policy are+preserved. The handler change adds no recovery endpoint or execution route.+### Retained guest identity cannot renew QGA eligibilityThe shared VM's internal `GuestAgentEvidence` bounds eligibility when a freshdiff --git a/frontend-modern/browser-tests/assistant-control-compatibility.cjs b/frontend-modern/browser-tests/assistant-control-compatibility.cjsnew file mode 100644index 0000000000..261770e04d--- /dev/null+++ b/frontend-modern/browser-tests/assistant-control-compatibility.cjs@@ -0,0 +1,164 @@+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const crypto = require('node:crypto');+const { chromium, webkit } = require('playwright');+const root = '/workspace/frontend-modern';+const output = '/workspace/tmp/assistant-controls-proof/browser';+const hash = (f) => crypto.createHash('sha256').update(fs.readFileSync(f)).digest('hex');+(async () => {+ fs.mkdirSync(output, { recursive: true });+ const binding = JSON.parse(fs.readFileSync('/workspace/tmp/assistant-controls-proof/browser-binding.json'));+ for (const [file, digest] of Object.entries(binding.content_sha256)) assert.equal(hash(path.join('/workspace', file)), digest);+ const version = require('playwright/package.json').version;+ assert.equal(version, JSON.parse(fs.readFileSync('/workspace/tests/integration/package-lock.json')).packages['node_modules/@playwright/test'].version);+ process.chdir(root);+ const { createServer } = await import(path.join(root, 'node_modules/vite/dist/node/index.js'));+ const server = await createServer({ root, configFile: path.join(root, 'vite.config.ts'), cacheDir: path.join(output, 'vite-cache'), server: { host: '127.0.0.1', port: 5308, strictPort: true, watch: null } });+ const origin = 'http://127.0.0.1:5308';+ const results = [], screenshots = [];+ let browser, phase = 'server', browserClosed = false, serverClosed = false;+ const result = () => ({ result: 'passed', base_sha: binding.base_sha, content_sha256: binding.content_sha256, playwrightVersion: version, results, screenshots, browserClosed, serverClosed, scope: 'Actual Settings state/save, Chat menus/scoped context and Docs with synthetic local API transport. No model/action/native persistence or deployed/released acceptance.' });+ try {+ await server.listen();+ for (const [name, engine, width, height, dark] of [ ['desktop-light', chromium, 1365, 900, false], ['phone-dark', webkit, 390, 844, true], ['narrow-light', webkit, 320, 740, false] ]) {+ browserClosed = false;+ browser = await engine.launch(engine === chromium ? { headless: true, channel: 'chromium', args: ['--no-sandbox'] } : { headless: true });+ const page = await browser.newPage({ viewport: { width, height }, isMobile: width < 500, hasTouch: width < 500, locale: 'en-GB' });+ page.setDefaultTimeout(8000); page.setDefaultNavigationTimeout(60000);+ const errors = [], offOrigin = [], writes = [], checks = [], reads = [];+ let saved = 'autonomous', failSave = false;+ await page.addInitScript((dark) => { localStorage.clear(); const apply = () => document.documentElement.classList.toggle('dark', dark); if (document.documentElement) apply(); else document.addEventListener('DOMContentLoaded', apply, { once: true }); }, dark);+ page.on('pageerror', (e) => errors.push(e.message));+ await page.routeWebSocket(/.*/, (s) => s.close());+ const settings = () => ({ enabled: true, configured: false, model: '', custom_context: '', control_level: saved, protected_guests: ['vm-101'], patrol_autonomy_level: 'full', patrol_action_emergency_stop: true, configured_providers: [], providers: [], discovery_enabled: false, request_timeout_seconds: 300 });+ await page.route('**/*', async (route) => {+ const req = route.request(), url = new URL(req.url());+ if (url.origin !== origin) { offOrigin.push(url.origin); return route.abort(); }+ if (!url.pathname.startsWith('/api/')) return route.continue();+ if (req.method() !== 'GET') {+ const entry = { method: req.method(), path: url.pathname, payload: req.postDataJSON() }; writes.push(entry);+ if (url.pathname !== '/api/settings/ai/update' || req.method() !== 'PUT') return route.fulfill({ status: 403, json: { error: 'Fixture refuses inference, actions and unrelated writes' } });+ if (failSave) return route.fulfill({ status: 503, json: { error: 'Synthetic save unavailable' } });+ if (Object.hasOwn(entry.payload, 'control_level')) saved = entry.payload.control_level;+ return route.fulfill({ json: { ...settings(), control_level: ['autonomous','suggest'].includes(saved) ? 'controlled' : saved } });+ }+ reads.push(url.pathname);+ if (url.pathname === '/api/settings/ai') return route.fulfill({ json: settings() });+ if (url.pathname === '/api/security/status') return route.fulfill({ json: { hasAuthentication: true, requiresAuth: false, sessionCapabilities: { assistantEnabled: true } } });+ if (url.pathname.includes('license') || url.pathname.includes('runtime-capabilities')) return route.fulfill({ json: { capabilities: [], entitlements: [], limits: [] } });+ if (url.pathname === '/api/ai/models') return route.fulfill({ json: { models: [] } });+ if (url.pathname === '/api/ai/status') return route.fulfill({ json: { enabled: true, configured: false, running: true } });+ if (url.pathname.endsWith('/sessions')) return route.fulfill({ json: { sessions: [] } });+ if (url.pathname === '/api/agent/capabilities') return route.fulfill({ json: { version: 1, capabilities: [], surfaces: [], workflowPrompts: [], mcpAdapter: {}, operatorSurfaces: [] } });+ return route.fulfill({ json: [] });+ });+ const check = async (label, action) => { phase = `${name}: ${label}`; await action(); checks.push({ label, passed: true }); };+ const capture = async (state) => { const file = `${name}-${state}.png`; await page.screenshot({ path: path.join(output, file) }); screenshots.push({ file, sha256: hash(path.join(output, file)), state, viewport: { width, height } }); };+ const load = async (surface) => page.goto(`${origin}/browser-tests/assistant-control-compatibility.html?surface=${surface}`);+ try {+ for (const level of ['autonomous', 'suggest', 'controlled', 'read_only', 'unknown']) {+ saved = level; await load('settings');+ const select = page.getByLabel('Chat action mode', { exact: true });+ const expected = ['autonomous','suggest','controlled'].includes(level) ? 'controlled' : 'read_only';+ await check(`Settings ${level} projects without granting execution`, async () => {+ await select.waitFor(); assert.equal(await select.inputValue(), expected);+ assert.equal(await select.locator('option').count(), 2);+ const text = await page.locator('main').innerText();+ assert.ok(!text.includes('chat-only') && !text.includes('Infrastructure changes stay with Patrol'));+ if (expected === 'controlled') { assert.ok(text.includes('Chat does not execute the plan')); assert.equal(await page.getByLabel('Protected guests').inputValue(), 'vm-101'); }+ assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1));+ });+ if (level === 'autonomous') { await select.scrollIntoViewIfNeeded(); await capture('legacy-settings'); }+ const before = writes.length;+ await page.getByRole('button', { name: 'Save Assistant settings', exact: true }).click();+ await check(`Unrelated save preserves ${level} and scoped policy`, async () => {+ await page.waitForFunction(() => !document.querySelector('button[disabled]')?.textContent?.includes('Saving'));+ for (let i = 0; writes.length === before && i < 20; i++) await page.waitForTimeout(50);+ assert.equal(writes.length, before + 1);+ for (const key of ['control_level','protected_guests','patrol_autonomy_level','patrol_action_emergency_stop']) assert.ok(!Object.hasOwn(writes.at(-1).payload, key));+ assert.equal(saved, level);+ });+ }+ saved = 'autonomous'; await load('chat');+ const trigger = page.getByRole('button', { name: 'Assistant chat action mode: Ask first', exact: true });+ await check('Legacy Chat has two modes and keyboard-safe review-only copy', async () => {+ await trigger.waitFor(); assert.equal(await page.getByRole('status', { name: 'Assistant chat actions warning' }).count(), 0);+ await trigger.focus(); await page.keyboard.press('ArrowDown');+ const modes = page.getByRole('menuitemradio'); assert.equal(await modes.count(), 2);+ const ask = page.getByRole('menuitemradio', { name: /Plans actions for your review/ });+ assert.equal(await ask.getAttribute('aria-checked'), 'true');+ await page.keyboard.press('Home'); assert.ok(await modes.first().evaluate((el) => el === document.activeElement));+ await page.keyboard.press('ArrowUp'); assert.ok(await ask.evaluate((el) => el === document.activeElement));+ await capture('chat-menu');+ await page.keyboard.press('Escape'); await page.waitForFunction(() => document.activeElement?.getAttribute('aria-label') === 'Assistant chat action mode: Ask first');+ assert.equal(await page.getByRole('menu').count(), 0);+ });+ await check('Scoped alert attachment keeps identity and approval boundary', async () => {+ await page.evaluate(() => window.__assistantProof.scoped());+ await page.getByText('Approval required before any action.', { exact: true }).waitFor();+ assert.equal(await page.evaluate(() => window.__assistantProof.context().autonomousMode), false);+ assert.equal(await page.evaluate(() => window.__assistantProof.context().handoffResources[0].id), 'vm:lab:101');+ assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1));+ await capture('scoped-chat');+ });+ await check('Chat mode save failure retains current mode', async () => {+ failSave = true; await trigger.click();+ await page.getByRole('menuitemradio', { name: /Read-only/ }).click();+ await trigger.waitFor(); assert.equal(saved, 'autonomous'); failSave = false;+ });+ await check('Explicit Chat opt-out changes only the mode', async () => {+ await trigger.click(); await page.getByRole('menuitemradio', { name: /Read-only/ }).click();+ await page.getByRole('button', { name: 'Assistant chat action mode: Read-only', exact: true }).waitFor();+ assert.deepEqual(writes.at(-1).payload, { control_level: 'read_only' });+ assert.equal(saved, 'read_only');+ });+ saved = 'controlled'; await load('settings');+ await page.getByLabel('Chat action mode', { exact: true }).waitFor();+ for (const [link, heading, state] of [ ['Read Assistant modes','Control Levels','help-modes'], ['Read control guide','Assistant Control Levels','help-guide'] ]) {+ if (state === 'help-guide') { await load('settings'); await page.getByLabel('Chat action mode', { exact: true }).waitFor(); }+ await check(`Actual Docs ${heading} describes planning and independent verification`, async () => {+ await page.getByRole('link', { name: link, exact: true }).click();+ const h = page.getByRole('heading', { name: heading, exact: true }); await h.waitFor(); await h.scrollIntoViewIfNeeded();+ const text = await page.locator('article').innerText(); assert.ok(text.includes('Assistant chat does not execute'));+ assert.ok(text.includes('stored') && text.includes('entitlement') && text.includes('independent verification'));+ assert.ok(!text.includes('executes actions without prompting') && !text.includes('executes commands without prompting'));+ assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1));+ await capture(state);+ const tableScroll = await page.locator('article').evaluate((article) => {+ const table = [...article.querySelectorAll('table')].find((t) => t.innerText.includes('Availability') && t.innerText.includes('Ask first'));+ if (!table) return { found: false };+ const wrapper = table.parentElement;+ const overflows = wrapper.scrollWidth > wrapper.clientWidth + 1;+ const overflowX = getComputedStyle(wrapper).overflowX;+ if (overflows) wrapper.scrollLeft = wrapper.scrollWidth;+ const lastCell = table.querySelector('thead tr').lastElementChild;+ return { found: true, overflows, overflowX, scrollLeft: wrapper.scrollLeft, lastCellRight: lastCell.getBoundingClientRect().right, wrapperRight: wrapper.getBoundingClientRect().right };+ });+ assert.equal(tableScroll.found, true);+ if (tableScroll.overflows) {+ assert.equal(tableScroll.overflowX, 'auto'); assert.ok(tableScroll.scrollLeft > 0);+ assert.ok(tableScroll.lastCellRight <= tableScroll.wrapperRight + 1);+ await capture(`${state}-table-end`);+ }+ });+ }+ assert.deepEqual(errors, []); assert.deepEqual(offOrigin, []);+ assert.ok(writes.every((r) => r.method === 'PUT' && r.path === '/api/settings/ai/update'));+ results.push({ name, viewport: { width, height }, dark, checks, writes, errors, offOrigin });+ } catch (error) {+ fs.writeFileSync(path.join(output, 'debug.json'), JSON.stringify({ phase, errors, reads, body: await page.locator('body').innerText(), buttons: await page.getByRole('button').allTextContents() }, null, 2));+ await page.screenshot({ path: path.join(output, 'failed-view.png') });+ throw error;+ } finally { await page.close(); await browser.close(); browser = null; browserClosed = true; }+ }+ } catch (error) {+ fs.writeFileSync(path.join(output, 'failure.json'), JSON.stringify({ phase, error: error.message, results, screenshots }, null, 2));+ throw error;+ } finally {+ if (browser) { await browser.close(); browserClosed = true; }+ await server.close(); serverClosed = true;+ }+ fs.writeFileSync(path.join(output, 'result.json'), JSON.stringify(result(), null, 2) + '\n');+ console.log(JSON.stringify({ result: 'passed', groups: results.reduce((n,r) => n + r.checks.length, 0), screenshots: screenshots.length, browserClosed, serverClosed }));+})().catch((e) => { console.error(e); process.exitCode = 1; });diff --git a/frontend-modern/browser-tests/assistant-control-compatibility.html b/frontend-modern/browser-tests/assistant-control-compatibility.htmlnew file mode 100644index 0000000000..d4b85c5f7f--- /dev/null+++ b/frontend-modern/browser-tests/assistant-control-compatibility.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Existing Assistant controls verification</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="./assistant-control-compatibility.tsx"></script>+ </body>+</html>diff --git a/frontend-modern/browser-tests/assistant-control-compatibility.tsx b/frontend-modern/browser-tests/assistant-control-compatibility.tsxnew file mode 100644index 0000000000..d975c298e0--- /dev/null+++ b/frontend-modern/browser-tests/assistant-control-compatibility.tsx@@ -0,0 +1,59 @@+// Actual existing Settings/Chat/Docs surfaces, not a shipped route. Synthetic+// API responses and local settings saves only; no model/action/backend calls.+import { render } from 'solid-js/web';+import { A, Route, Router } from '@solidjs/router';+import { AIAssistantSettings } from '../src/components/Settings/AISettings';+import { AIChat } from '../src/components/AI/Chat';+import Docs from '../src/pages/Docs';+import { aiChatStore } from '../src/stores/aiChat';+import '../src/index.css';+const params = new URLSearchParams(location.search);+window.history.replaceState(+ {},+ '',+ params.get('surface') === 'chat' ? '/proof-chat' : '/settings/ai/assistant',+);+aiChatStore.setEnabled(true);+(window as any).__assistantProof = {+ scoped: () =>+ aiChatStore.setContext({+ autonomousMode: false,+ briefing: {+ sourceLabel: 'Pulse Alerts',+ title: 'Synthetic alert investigation attached',+ subject: 'lab-vm',+ },+ handoffResources: [{ id: 'vm:lab:101', name: 'lab-vm', type: 'vm', node: 'lab' }],+ context: { alertIdentifier: 'synthetic-alert-1' },+ }),+ context: () => aiChatStore.context,+};+function SettingsFixture() {+ return (+ <main class="mx-auto max-w-4xl bg-surface text-base-content p-4">+ <AIAssistantSettings />+ <nav class="space-x-3 mt-4">+ <A href="/docs/AI#control-levels">Read Assistant modes</A>+ <A href="/docs/AI_AUTONOMY#assistant-control-levels">Read control guide</A>+ </nav>+ </main>+ );+}+function ChatFixture() {+ aiChatStore.open();+ return (+ <div class="mx-auto max-w-3xl h-screen bg-surface text-base-content">+ <AIChat onClose={() => aiChatStore.close()} />+ </div>+ );+}+render(+ () => (+ <Router>+ <Route path="/settings/ai/assistant" component={SettingsFixture} />+ <Route path="/proof-chat" component={ChatFixture} />+ <Route path="/docs/*docPath" component={Docs} />+ </Router>+ ),+ document.getElementById('root')!,+);diff --git a/frontend-modern/browser-verification/10b6f941aca7d1ed.json b/frontend-modern/browser-verification/10b6f941aca7d1ed.jsonnew file mode 100644index 0000000000..afdc70612a--- /dev/null+++ b/frontend-modern/browser-verification/10b6f941aca7d1ed.json@@ -0,0 +1,55 @@+{+ "version": 1,+ "base_sha": "3d95193086fec4a67be03416b6f8c97065d4bc39",+ "result": "passed",+ "verified_at": "2026-10-09T23:24:34Z",+ "changed_paths": [+ "frontend-modern/src/components/AI/Chat/index.tsx",+ "frontend-modern/src/components/Settings/AIRuntimeControlsSection.tsx",+ "frontend-modern/src/components/Settings/useAISettingsState.ts",+ "frontend-modern/src/utils/aiChatPresentation.ts",+ "frontend-modern/src/utils/aiControlLevelPresentation.ts"+ ],+ "content_sha256": {+ "frontend-modern/src/components/AI/Chat/index.tsx": "113b1c6cb830937ebe6a7e7ea04f49b7a39ac773d62a0ab892e7d9afb4334de2",+ "frontend-modern/src/components/Settings/AIRuntimeControlsSection.tsx": "4a4aa69d0f77e8038b789856db8a9481d6a0f0149c69bbff20bc5d6f9f772d90",+ "frontend-modern/src/components/Settings/useAISettingsState.ts": "f09a682962332c2c69e2e5907c590c9bcd71f28af6c9b9a95ca21e009ee00e8b",+ "frontend-modern/src/utils/aiChatPresentation.ts": "15de18883e31ecf4f618788c55ffa7fcc0a33cb97943878f739452cfd5f0379d",+ "frontend-modern/src/utils/aiControlLevelPresentation.ts": "a665545de89aa885e556c5ddb7f5da875d38ea76227549b22f34a2fb83e4771a"+ },+ "routes": [+ "Existing AIAssistantSettings and AIChat in local /browser-tests/assistant-control-compatibility.html fixture",+ "/settings/ai/assistant",+ "/docs/AI#control-levels",+ "/docs/AI_AUTONOMY#assistant-control-levels"+ ],+ "states": [+ "Saved autonomous/suggest/controlled/read_only/unknown: truthful two-mode projection",+ "Protected guest and Patrol policy preservation on unrelated save",+ "Scoped alert attachment with explicit approval boundary",+ "503 settings save failure retains displayed mode",+ "Desktop light and WebKit phone dark/narrow light",+ "Existing Docs with locally scrollable wide table"+ ],+ "interactions": [+ "48 assertion groups: saved-config projection, no unrelated control/policy rewrites, keyboard menu wrap/Home/Escape/focus restoration",+ "Explicit opt-out writes only control_level",+ "Open real Docs from fixture links and read rendered planning/approval/verification guidance",+ "16 screenshots visually inspected; table end reachable at 320px"+ ],+ "viewports": [+ {+ "width": 1365,+ "height": 900+ },+ {+ "width": 390,+ "height": 844+ },+ {+ "width": 320,+ "height": 740+ }+ ],+ "notes": "Actual existing components and help, synthetic local API transport. No model/action execution, native saved-config persistence or release/deployment claim. Backend synthetic encrypted-persistence and access tests are a separate source proof."+}diff --git a/frontend-modern/public/docs/AI.md b/frontend-modern/public/docs/AI.mdindex ef56b82eb3..4899253228 100644--- a/frontend-modern/public/docs/AI.md+++ b/frontend-modern/public/docs/AI.md@@ -476,21 +476,26 @@ The assistant enforces multiple safety gates:### Control Levels-| Level | Behavior | Plan |-|-------|----------|---------|-| **Read-only** | AI can observe and query data only | Community |-| **Controlled** | AI asks for approval before executing commands | Community |-| **Autonomous** | AI executes actions without prompting | Pro / hosted Cloud |--### Using Approvals (Controlled Mode)--When control level is **Controlled**, write actions pause for approval:--1. Tool returns `APPROVAL_REQUIRED: { approval_id, command, ... }`-2. Agentic loop emits `approval_needed` SSE event-3. UI shows approval card with the proposed command-4. **Approve** to execute and verify, or **Deny** to cancel-5. Only users with admin privileges can approve/deny+| Mode | Behaviour | Availability |+|------|-----------|--------------|+| **Read-only** | Assistant queries and explains; no infrastructure action planning | Community |+| **Ask first** (`controlled`) | Assistant saves infrastructure action plans to **Actions** for your review | Community |++Assistant chat does not execute these plans. Patrol's own mode and Autopilot+policy are separate; changing Chat action mode grants no Patrol authority.+Older saved `autonomous` preferences display as **Ask first**, not as permission+to execute without approval. The stored preference and its existing entitlement+checks are preserved for older clients.++### Reviewing an Assistant action plan++1. Assistant submits a typed action for a resource advertising that capability.+2. Pulse records the plan in **Actions**; planning is not execution.+3. Open **Actions** to check the target, proposed operation, approval policy and expiry.+4. An authorised operator reviews, approves where required, and runs the plan+ through the existing action controls. Chat mode cannot bypass these checks.+5. Read the recorded execution and independent verification result. A saved plan+ or successful command alone does not establish recovery.---diff --git a/frontend-modern/public/docs/AI_AUTONOMY.md b/frontend-modern/public/docs/AI_AUTONOMY.mdindex 02c8fab836..075bbc2d69 100644--- a/frontend-modern/public/docs/AI_AUTONOMY.md+++ b/frontend-modern/public/docs/AI_AUTONOMY.md@@ -95,31 +95,33 @@ Without the `ai_autofix` capability, the effective Patrol mode is clamped to `mo## Assistant Control Levels-Control levels govern what the interactive Pulse Assistant can do during chat sessions.+Control levels govern interactive Assistant queries and action planning, not+Patrol's autonomy or permission to execute infrastructure work.-| Level | Key | Query | Execute Commands | Plan |-|-------|-----|:-----:|:----------------:|------|+| Mode | Key | Query | Plan infrastructure actions | Availability |+|------|-----|:-----:|:---------------------------:|--------------|| **Read-only** | `read_only` | Yes | No | Community |-| **Controlled** | `controlled` | Yes | With approval | Community |-| **Autonomous** | `autonomous` | Yes | Yes | Pro / legacy Pro+ / Cloud |+| **Ask first** | `controlled` | Yes | For operator review in **Actions** | Community |-- **Read-only** (default): The assistant can query metrics, storage, and resource status but cannot execute any control actions.-- **Controlled**: The assistant can propose commands but pauses for your explicit approval before execution. Each command shows a detailed approval card in the chat UI.-- **Autonomous**: The assistant executes commands without prompting. Requires a Pro, legacy Pro+, or Cloud license.+Assistant chat does not execute the plans it saves. A legacy saved `autonomous`+preference displays as **Ask first** and keeps its stored value and existing+entitlement checks for older clients. It does not bypass approval. An unrelated+settings save does not rewrite that preference. Unknown values fail closed to+read-only. Patrol mode and Autopilot acknowledgements remain separate.### Configuration-**UI:** Settings → Pulse Intelligence → Assistant → Chat command mode+**UI:** Settings → Pulse Intelligence → Assistant → Chat action mode-**API:** This intentionally changes chat command access. Use the same private+**API:** This intentionally changes Assistant action planning access. Use the same privateadministrator header file with `settings:write`; the token must also havepermission to change settings. Prefer the UI for one-off changes, and verify-the saved **Chat command mode** there afterwards. Do not use a write as an+the saved **Chat action mode** there afterwards. Do not use a write as anauthentication test.Use the same `pulse_api` helper defined above, with its private response fileand request limits. Supporting PUT in the helper grants no additional access.-If the response is lost, check the saved **Chat command mode** in the UI before+If the response is lost, check the saved **Chat action mode** in the UI beforedeciding whether another change is needed; do not repeat the write blindly.```bash@@ -128,17 +130,16 @@ pulse_api PUT /api/settings/ai/update <<'JSON'JSON```-### Approval Flow (Controlled Mode)+### Reviewing plans (Ask first)-When control level is `controlled`, write operations follow this flow:--1. The assistant proposes a command (e.g., `qm start 100`).-2. An `APPROVAL_REQUIRED` response is emitted with an `approval_id`.-3. The UI displays an approval card showing the exact command.-4. You click **Approve** or **Deny**.-5. On approval, the command executes and the assistant verifies the result.--Approvals expire after 5 minutes if not acted upon.+1. Assistant requests a typed action for an explicitly identified resource with+ the advertised capability.+2. Pulse saves the canonical plan in **Actions** without requesting execution.+3. Review the target, operation, approval policy and expiry in **Actions**.+4. Use the existing authorised approval and run controls; Chat action mode grants+ no additional access or automatic approval.+5. Read the recorded execution and independent verification outcome before+ concluding that the operation worked. Do not repeat an uncertain operation.---diff --git a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsxindex 28452427b6..70090706bf 100644--- a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx+++ b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx@@ -3572,8 +3572,9 @@ describe('AIChat', () => {);expect(screen.getByText('Default control mode')).toBeInTheDocument();expect(screen.getByText('Observes only')).toBeInTheDocument();- expect(screen.getByText('Asks before chat-only actions')).toBeInTheDocument();- expect(screen.getByText('Eligible chat-only actions')).toBeInTheDocument();+ expect(screen.getByText('Plans actions for your review')).toBeInTheDocument();+ expect(screen.queryByText('Eligible chat-only actions')).not.toBeInTheDocument();+ expect(screen.getAllByRole('menuitemradio')).toHaveLength(2);await waitFor(() => {expect(document.activeElement).toBe(screen.getByRole('menuitemradio', { name: /Read-only/ }),@@ -3615,7 +3616,6 @@ describe('AIChat', () => {fireEvent.click(controlButton);const readOnlyOption = screen.getByRole('menuitemradio', { name: /Read-only/ });const askFirstOption = screen.getByRole('menuitemradio', { name: /Ask first/ });- const chatActionsOption = screen.getByRole('menuitemradio', { name: /Chat actions/ });await waitFor(() => {expect(document.activeElement).toBe(readOnlyOption);});@@ -3624,15 +3624,15 @@ describe('AIChat', () => {expect(document.activeElement).toBe(askFirstOption);fireEvent.keyDown(askFirstOption, { key: 'End' });- expect(document.activeElement).toBe(chatActionsOption);+ expect(document.activeElement).toBe(askFirstOption);- fireEvent.keyDown(chatActionsOption, { key: 'Home' });+ fireEvent.keyDown(askFirstOption, { key: 'Home' });expect(document.activeElement).toBe(readOnlyOption);fireEvent.keyDown(readOnlyOption, { key: 'ArrowUp' });- expect(document.activeElement).toBe(chatActionsOption);+ expect(document.activeElement).toBe(askFirstOption);- fireEvent.keyDown(chatActionsOption, { key: 'Escape' });+ fireEvent.keyDown(askFirstOption, { key: 'Escape' });await waitFor(() => {expect(@@ -5701,45 +5701,29 @@ describe('AIChat', () => {// ── Autonomous warning ───────────────────────────────────────────────describe('autonomous warning', () => {- it('shows autonomous warning in the activity dock when control level is autonomous', async () => {- mockAIAPI.getSettings.mockResolvedValue({- model: 'gpt-4',- chat_model: '',- control_level: 'autonomous',- autonomous_mode: true,- discovery_enabled: true,- });- renderChat();- await waitFor(() => {- const warning = screen.getByRole('status', {- name: 'Assistant chat actions warning',+ it.each(['autonomous', 'suggest', 'controlled'])(+ 'shows saved %s as planning for review without a misleading execution warning',+ async (level) => {+ mockAIAPI.getSettings.mockResolvedValue({+ model: 'gpt-4',+ control_level: level,+ discovery_enabled: true,});- expect(screen.getByTestId('assistant-activity-dock')).toContainElement(warning);- expect(warning).toHaveTextContent('Chat-only actions are allowed.');- });- });-- it('shows Switch to Ask first button in autonomous warning row', async () => {- mockAIAPI.getSettings.mockResolvedValue({- model: 'gpt-4',- chat_model: '',- control_level: 'autonomous',- autonomous_mode: true,- discovery_enabled: true,- });- renderChat();- await waitFor(() => {- expect(- screen.getByRole('status', { name: 'Assistant chat actions warning' }),- ).toBeInTheDocument();+ renderChat();+ await waitFor(() => expect(screen.getByText('Chat: Ask first')).toBeInTheDocument());expect(- screen.getByRole('button', { name: 'Switch Assistant chat actions to Ask first' }),- ).toBeInTheDocument();+ screen.queryByRole('status', { name: 'Assistant chat actions warning' }),+ ).not.toBeInTheDocument();+ fireEvent.click(+ screen.getByRole('button', { name: 'Assistant chat action mode: Ask first' }),+ );+ expect(screen.getAllByRole('menuitemradio')).toHaveLength(2);expect(- screen.getByRole('button', { name: 'Dismiss chat actions warning' }),- ).toBeInTheDocument();- });- });+ screen.getByRole('menuitemradio', { name: /Plans actions for your review/ }),+ ).toHaveAttribute('aria-checked', 'true');+ expect(mockAIAPI.updateSettings).not.toHaveBeenCalled();+ },+ );it('keeps scoped dashboard handoffs approval-required without showing the autonomous warning', async () => {mockAIAPI.getSettings.mockResolvedValue({@@ -6485,7 +6469,7 @@ describe('AIChat', () => {expect(screen.getByText('1 follow-up queued')).toBeInTheDocument();});- it('keeps autonomous warning alongside active assistant streaming status', async () => {+ it('keeps active streaming status without a retired autonomous warning', async () => {mockAIAPI.getSettings.mockResolvedValue({model: 'gpt-4',chat_model: '',@@ -6511,9 +6495,12 @@ describe('AIChat', () => {expect(activityDock).toContainElement(screen.getByLabelText('Assistant active turn status'),);- expect(activityDock).toContainElement(- screen.getByRole('status', { name: 'Assistant chat actions warning' }),- );+ expect(+ screen.queryByRole('status', { name: 'Assistant chat actions warning' }),+ ).not.toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: 'Assistant chat action mode: Ask first' }),+ ).toBeInTheDocument();});});diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsxindex c246d3c5f9..08638e7730 100644--- a/frontend-modern/src/components/AI/Chat/index.tsx+++ b/frontend-modern/src/components/AI/Chat/index.tsx@@ -67,7 +67,6 @@ import {} from '@/stores/aiRuntimeState';import { logger } from '@/utils/logger';import {- AI_CHAT_AUTONOMOUS_WARNING_DISMISS_LABEL,AI_CHAT_COLLAPSE_TITLE,AI_CHAT_CLOSE_LABEL,AI_CHAT_COMMAND_HELP_BUTTON_LABEL,@@ -114,7 +113,6 @@ import {AI_CHAT_SESSION_SEARCH_LOADING_STATE,AI_CHAT_SESSION_SEARCH_PLACEHOLDER,AI_CHAT_SESSION_SEARCH_TITLE,- AI_CHAT_SWITCH_TO_APPROVAL_LABEL,AI_CHAT_TRANSCRIPT_FALLBACK_CLOSE_LABEL,AI_CHAT_TRANSCRIPT_FALLBACK_DOWNLOAD_LABEL,AI_CHAT_TRANSCRIPT_FALLBACK_TEXTAREA_LABEL,@@ -243,7 +241,7 @@ const AI_CHAT_SESSION_SEARCH_LIMIT = 30;const STRUCTURED_PATROL_CONTEXT_TARGETS = new Set(['patrol-configuration', 'patrol-run']);const STRUCTURED_RESOURCE_CONTEXT_HANDOFF_KINDS = new Set(['resource_context']);const AI_CHAT_CYCLE_RECENT_MODEL_LABEL = 'Cycle recent Assistant model';-const AI_CHAT_CONTROL_LEVEL_ORDER: AIControlLevel[] = ['read_only', 'controlled', 'autonomous'];+const AI_CHAT_CONTROL_LEVEL_ORDER: AIControlLevel[] = ['read_only', 'controlled'];const AI_CHAT_COMPACT_SESSION_LABEL = 'Compact session';const AI_CHAT_COMPACT_SESSION_EMPTY_MESSAGE = 'No Assistant session to compact';const AI_CHAT_COMPACT_SESSION_LOADING_MESSAGE =@@ -746,7 +744,6 @@ export const AIChat: Component<AIChatProps> = (props) => {createSignal<TranscriptCopyFallback | null>(null);const [discoveryEnabled, setDiscoveryEnabled] = createSignal<boolean | null>(null); // null = loadingconst [discoveryHintDismissed, setDiscoveryHintDismissed] = createSignal(false);- const [autonomousBannerDismissed, setAutonomousBannerDismissed] = createSignal(false);const [workflowPrompts, setWorkflowPrompts] = createSignal<AgentWorkflowPrompt[]>([]);const [renderingWorkflowStarterId, setRenderingWorkflowStarterId] = createSignal('');const wsStore = getGlobalWebSocketStore();@@ -2352,7 +2349,7 @@ export const AIChat: Component<AIChatProps> = (props) => {setDiscoveryEnabled(settings?.discovery_enabled ?? false);});- const updateControlLevel = async (nextLevel: 'read_only' | 'controlled' | 'autonomous') => {+ const updateControlLevel = async (nextLevel: AIControlLevel) => {if (controlSaving() || nextLevel === controlLevel()) {setShowControlMenu(false);return;@@ -2364,7 +2361,6 @@ export const AIChat: Component<AIChatProps> = (props) => {const resolved = normalizeAIControlLevel(updated.control_level || nextLevel);syncAIRuntimeSettings(updated);setControlLevel(resolved);- if (resolved === 'autonomous') setAutonomousBannerDismissed(false);notificationStore.success(`Assistant chat action mode set to ${getAIChatControlLevelPresentation(resolved).label}`,2000,@@ -2596,17 +2592,7 @@ export const AIChat: Component<AIChatProps> = (props) => {const contextBriefing = createMemo(() => aiChatStore.context.briefing);const hasScopedApprovalHandoff = createMemo(() => aiChatStore.context.autonomousMode === false);- const controlPresentation = createMemo(() =>- getAIChatControlLevelPresentation(- hasScopedApprovalHandoff() && controlLevel() === 'autonomous' ? 'controlled' : controlLevel(),- ),- );- const autonomousWarningVisible = createMemo(- () =>- controlLevel() === 'autonomous' &&- !autonomousBannerDismissed() &&- !hasScopedApprovalHandoff(),- );+ const controlPresentation = createMemo(() => getAIChatControlLevelPresentation(controlLevel()));const contextBriefingTitle = createMemo(() => {const briefing = contextBriefing();if (!briefing) return '';@@ -5023,13 +5009,7 @@ export const AIChat: Component<AIChatProps> = (props) => {{/* Input */}<div class="border-t border-border bg-surface px-4 py-3">- <Show- when={- currentStatus() ||- autonomousWarningVisible() ||- activityDockQueuedFollowUpCount() > 0- }- >+ <Show when={currentStatus() || activityDockQueuedFollowUpCount() > 0}><divclass="mb-2 overflow-hidden rounded-md border border-border bg-surface-alt text-base-content shadow-xs"data-testid="assistant-activity-dock"@@ -5101,48 +5081,9 @@ export const AIChat: Component<AIChatProps> = (props) => {</ActionIconButton></div></Show>- <Show when={autonomousWarningVisible()}>- <div- class={`flex min-h-8 min-w-0 items-center gap-2 px-2.5 py-1.5 text-xs text-red-700 dark:text-red-200 ${- currentStatus() ? 'border-t border-border/70' : ''- }`}- role="status"- aria-label="Assistant chat actions warning"- aria-live="polite"- >- <span- class="h-1.5 w-1.5 shrink-0 rounded-full bg-red-500 dark:bg-red-300"- aria-hidden="true"- />- <span class="min-w-0 flex-1 font-medium leading-4 sm:truncate">- Chat-only actions are allowed.- </span>- <button- type="button"- onClick={() => updateControlLevel('controlled')}- class="inline-flex shrink-0 items-center rounded-md border border-red-200 bg-surface px-2 py-1 text-[10px] font-medium text-red-700 transition-colors hover:bg-red-50 hover:text-red-900 dark:border-red-800 dark:bg-surface dark:text-red-200 dark:hover:bg-red-950/40"- aria-label={AI_CHAT_SWITCH_TO_APPROVAL_LABEL}- >- Switch to Ask first- </button>- <ActionIconButton- onClick={() => setAutonomousBannerDismissed(true)}- tone="danger"- size="xs"- title={AI_CHAT_AUTONOMOUS_WARNING_DISMISS_LABEL}- label={AI_CHAT_AUTONOMOUS_WARNING_DISMISS_LABEL}- >- <XIcon class="h-3.5 w-3.5" aria-hidden="true" />- </ActionIconButton>- </div>- </Show><Show when={activityDockQueuedFollowUpCount() > 0}><div- class={`px-2.5 py-1.5 ${- currentStatus() || autonomousWarningVisible()- ? 'border-t border-border/70'- : ''- }`}+ class={`px-2.5 py-1.5 ${currentStatus() ? 'border-t border-border/70' : ''}`}role="status"aria-label="Queued follow-up messages">@@ -5593,24 +5534,6 @@ export const AIChat: Component<AIChatProps> = (props) => {{getAIChatControlLevelPresentation('controlled').description}</div></button>- <button- type="button"- ref={(button) => {- controlModeOptionRefs.set('autonomous', button);- }}- role="menuitemradio"- aria-checked={controlLevel() === 'autonomous'}- class={`w-full text-left px-3 py-2.5 text-xs hover:bg-surface-hover transition-colors ${controlLevel() === 'autonomous' ? getAIChatControlLevelPresentation('autonomous').selectedClassName : ''}`}- onKeyDown={(event) => handleControlModeOptionKeyDown(event, 'autonomous')}- onClick={() => updateControlLevel('autonomous')}- >- <div class="font-medium text-base-content">- {getAIChatControlLevelPresentation('autonomous').label}- </div>- <div class="text-[11px] text-muted">- {getAIChatControlLevelPresentation('autonomous').description}- </div>- </button></div></Show></div>diff --git a/frontend-modern/src/components/Settings/AIRuntimeControlsSection.tsx b/frontend-modern/src/components/Settings/AIRuntimeControlsSection.tsxindex 97007862f1..dcd2474854 100644--- a/frontend-modern/src/components/Settings/AIRuntimeControlsSection.tsx+++ b/frontend-modern/src/components/Settings/AIRuntimeControlsSection.tsx@@ -2,12 +2,9 @@ import { Component, Show } from 'solid-js';import RefreshCwIcon from 'lucide-solid/icons/refresh-cw';import type { AIControlLevel } from '@/utils/aiControlLevelPresentation';import type { AISettingsState } from '@/components/Settings/useAISettingsState';-import { ExternalTextLink } from '@/components/shared/ExternalTextLink';import { HelpIcon } from '@/components/shared/HelpIcon';import { FormSelect } from '@/components/shared/FormSelect';-import { UpgradeLink } from '@/components/shared/UpgradeLink';import { Toggle } from '@/components/shared/Toggle';-import { TERMS_DOC_URL } from '@/utils/docsLinks';import {getAIControlLevelBadgeClass,getAIControlLevelDescription,@@ -18,7 +15,6 @@ import {getAISettingsWorkloadDiscoveryHelpContent,getAISettingsWorkloadDiscoverySummary,} from '@/utils/aiSettingsPresentation';-import { UPGRADE_ACTION_LABEL } from '@/utils/upgradePresentation';interface AIRuntimeControlsSectionProps {state: AISettingsState;@@ -271,13 +267,6 @@ export const AIAssistantCommandAccessSection: Component<AIRuntimeControlsSectionprops,) => {const { state } = props;- const showAutonomousControlOption = () =>- !state.autoFixLocked() ||- state.showUpgradePrompts() ||- state.form.controlLevel === 'autonomous';- const assistantCommandAccessBadgeLabel = () =>- state.form.controlLevel === 'autonomous' ? 'Allowed' : 'Ask first';-return (<><div@@ -304,13 +293,12 @@ export const AIAssistantCommandAccessSection: Component<AIRuntimeControlsSection<spanclass={`px-1.5 py-0.5 text-[10px] font-medium rounded-sm ${getAIControlLevelBadgeClass(state.form.controlLevel)}`}>- {assistantCommandAccessBadgeLabel()}+ Ask first</span></Show></div><p class="text-[10px] text-muted">- This controls actions started from Assistant chat only. Patrol handles infrastructure work- from the Patrol page.+ This sets what Assistant chat may plan. Patrol's own mode is set on the Patrol page.</p><FormSelect@@ -324,46 +312,12 @@ export const AIAssistantCommandAccessSection: Component<AIRuntimeControlsSectionlabelClass="text-xs font-medium text-muted sm:w-28 sm:shrink-0"selectBaseClass="w-full min-w-0 min-h-10 px-2 py-2 text-sm border border-border rounded-sm bg-surface sm:min-h-9 sm:flex-1">- <option value="read_only">Observe only - Assistant cannot take chat actions</option>- <option value="controlled">Ask first - Assistant asks before chat-only actions</option>- <Show when={showAutonomousControlOption()}>- <option value="autonomous">- Allow chat-only actions - Assistant may take eligible chat actions- </option>- </Show>+ <option value="read_only">Read-only - Assistant queries and explains only</option>+ <option value="controlled">Ask first - Assistant plans actions for your review</option></FormSelect><p class="text-[10px] text-muted sm:ml-30">{getAIControlLevelDescription(state.form.controlLevel)}</p>- <Show when={state.form.controlLevel === 'autonomous'}>- <div class="p-2 bg-amber-100 dark:bg-amber-900/25 rounded-sm border border-amber-200 dark:border-amber-800 text-[10px] text-amber-800 dark:text-amber-200">- <strong>Important:</strong> Assistant may take eligible chat-only actions from this- mode. Infrastructure changes stay with Patrol mode. Keep protected guests set for- anything Assistant must not touch. See{' '}- <ExternalTextLink href={TERMS_DOC_URL} variant="compactInherit">- Terms of Service- </ExternalTextLink>- .- </div>- </Show>- <Show- when={- state.form.controlLevel === 'autonomous' &&- state.autoFixLocked() &&- state.showUpgradePrompts()- }- >- <p class="text-xs text-muted">- <UpgradeLink- class="text-blue-600 dark:text-blue-400 font-medium hover:underline"- destination={state.upgradeAutofixDestination()}- >- {UPGRADE_ACTION_LABEL}- </UpgradeLink>{' '}- to review eligible chat action options.- </p>- </Show>-<Show when={state.form.controlLevel !== 'read_only'}><div class="flex items-start gap-3 pt-2 border-t border-blue-200 dark:border-blue-700"><label@@ -383,7 +337,7 @@ export const AIAssistantCommandAccessSection: Component<AIRuntimeControlsSectiondisabled={state.saving()}/><p class="text-[10px] text-muted mt-1">- Comma-separated VMIDs or names Assistant cannot touch when chat actions are allowed.+ Comma-separated VMIDs or names excluded from Assistant action planning.</p></div></div>diff --git a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsxindex b950800dcb..ca03538383 100644--- a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx@@ -244,14 +244,14 @@ describe('AISettings model loading error states', () => {expect(await screen.findByText('Assistant chat actions')).toBeInTheDocument();expect(- screen.getByText('This controls actions started from Assistant chat only', { exact: false }),+ screen.getByText('This sets what Assistant chat may plan', { exact: false }),).toBeInTheDocument();const chatActionMode = screen.getByLabelText('Chat action mode');expect(chatActionMode).toBeInTheDocument();expect(chatActionMode).toHaveClass('w-full', 'min-w-0', 'sm:flex-1');expect(chatActionMode.parentElement).toHaveClass('flex-col', 'sm:flex-row');expect(- screen.getByText('Assistant asks before chat-only actions.', { exact: false }),+ screen.getByText('Assistant can plan infrastructure actions', { exact: false }),).toHaveClass('sm:ml-30');expect(screen.getByRole('option', { name: /Ask first/i })).toBeInTheDocument();expect(screen.getByRole('button', { name: /Save Assistant settings/i })).toBeInTheDocument();@@ -883,7 +883,7 @@ describe('AISettings model loading error states', () => {).not.toBeInTheDocument();});- it('keeps an existing autonomous setting visible even when upgrade prompts are hidden', async () => {+ it('presents an existing autonomous preference as Ask first even without upgrade prompts', async () => {hasFeatureMock.mockImplementation((feature: string) => feature !== 'ai_autofix');presentationPolicyHidesUpgradePromptsMock.mockReturnValue(true);getSettingsMock.mockResolvedValue({@@ -897,11 +897,69 @@ describe('AISettings model loading error states', () => {expect(getSettingsMock).toHaveBeenCalledTimes(1);});- expect(screen.getByRole('option', { name: /Allow chat-only actions/i })).toBeInTheDocument();+ expect(+ screen.queryByRole('option', { name: /Allow chat-only actions/i }),+ ).not.toBeInTheDocument();+ expect(screen.getByLabelText('Chat action mode')).toHaveValue('controlled');expect(screen.queryByText('(Pro)')).not.toBeInTheDocument();});});+describe('Assistant saved-control compatibility', () => {+ beforeEach(() => {+ resetAllMocks();+ setupDefaultMocks();+ });+ afterEach(() => {+ cleanup();+ });++ it.each(['autonomous', 'suggest', 'controlled', 'read_only', 'unknown'])(+ 'does not rewrite the saved %s preference on an unrelated save',+ async (level) => {+ const saved = {+ ...baseSettings(),+ control_level: level,+ protected_guests: ['vm-101'],+ patrol_autonomy_level: 'full',+ };+ getSettingsMock.mockResolvedValue(saved);+ updateSettingsMock.mockResolvedValue(saved);+ renderComponent('assistant');+ const mode = await screen.findByLabelText('Chat action mode');+ await waitFor(() =>+ expect(mode).toHaveValue(+ ['autonomous', 'suggest', 'controlled'].includes(level) ? 'controlled' : 'read_only',+ ),+ );+ expect(within(mode).getAllByRole('option')).toHaveLength(2);+ fireEvent.click(screen.getByRole('button', { name: /Save Assistant settings/i }));+ await waitFor(() => expect(updateSettingsMock).toHaveBeenCalledTimes(1));+ expect(updateSettingsMock.mock.calls[0][0]).not.toHaveProperty('control_level');+ expect(updateSettingsMock.mock.calls[0][0]).not.toHaveProperty('protected_guests');+ expect(updateSettingsMock.mock.calls[0][0]).not.toHaveProperty('patrol_autonomy_level');+ },+ );++ it('explicitly opts out of legacy action planning without changing Patrol', async () => {+ const saved = { ...baseSettings(), control_level: 'autonomous', protected_guests: ['vm-101'] };+ getSettingsMock.mockResolvedValue(saved);+ updateSettingsMock.mockImplementation(async (payload: Record<string, unknown>) => ({+ ...saved,+ ...payload,+ }));+ renderComponent('assistant');+ const mode = await screen.findByLabelText('Chat action mode');+ await waitFor(() => expect(mode).toHaveValue('controlled'));+ fireEvent.change(mode, { target: { value: 'read_only' } });+ fireEvent.click(screen.getByRole('button', { name: /Save Assistant settings/i }));+ await waitFor(() => expect(updateSettingsMock).toHaveBeenCalledTimes(1));+ expect(updateSettingsMock.mock.calls[0][0]).toHaveProperty('control_level', 'read_only');+ expect(updateSettingsMock.mock.calls[0][0]).not.toHaveProperty('protected_guests');+ expect(updateSettingsMock.mock.calls[0][0]).not.toHaveProperty('patrol_autonomy_level');+ });+});+describe('AISettings load failure error state', () => {beforeEach(() => {resetAllMocks();diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.tsindex 226f053d19..44694dcdfb 100644--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts@@ -570,18 +570,18 @@ describe('settings architecture guardrails', () => {'Reporting is locked for this session. The report builder appears when advanced reporting is available.',);expect(reportingPanelSource).not.toContain('Advanced Reporting (Pro)');- expect(aiRuntimeControlsSectionSource).toContain('showAutonomousControlOption');- expect(aiRuntimeControlsSectionSource).toContain("state.form.controlLevel === 'autonomous'");- expect(aiRuntimeControlsSectionSource).toContain(- 'Ask first - Assistant asks before chat-only actions',+ expect(aiRuntimeControlsSectionSource).not.toContain('showAutonomousControlOption');+ expect(aiRuntimeControlsSectionSource).not.toContain(+ "state.form.controlLevel === 'autonomous'",);expect(aiRuntimeControlsSectionSource).toContain(- 'Allow chat-only actions - Assistant may take eligible chat actions',+ 'Ask first - Assistant plans actions for your review',);- expect(aiRuntimeControlsSectionSource).toContain(- 'This controls actions started from Assistant chat only',+ expect(aiRuntimeControlsSectionSource).not.toContain(+ 'Allow chat-only actions - Assistant may take eligible chat actions',);- expect(aiRuntimeControlsSectionSource).toContain('Patrol handles infrastructure');+ expect(aiRuntimeControlsSectionSource).toContain('This sets what Assistant chat may plan');+ expect(aiRuntimeControlsSectionSource).toContain("Patrol's own mode is set on the Patrol page");expect(aiRuntimeControlsSectionSource).not.toContain('Command auto-run');expect(aiRuntimeControlsSectionSource).not.toContain('without per-command approval');expect(aiRuntimeControlsSectionSource).not.toContain('Legal Disclaimer');diff --git a/frontend-modern/src/components/Settings/useAISettingsState.ts b/frontend-modern/src/components/Settings/useAISettingsState.tsindex 90e5ab21a8..27d1112b70 100644--- a/frontend-modern/src/components/Settings/useAISettingsState.ts+++ b/frontend-modern/src/components/Settings/useAISettingsState.ts@@ -1204,7 +1204,7 @@ export const useAISettingsState = (options: AISettingsStateOptions = {}) => {if (form.requestTimeoutSeconds !== (settings()?.request_timeout_seconds ?? 300)) {payload.request_timeout_seconds = form.requestTimeoutSeconds;}- if (form.controlLevel !== (settings()?.control_level || 'read_only')) {+ if (form.controlLevel !== normalizeAIControlLevel(settings()?.control_level)) {payload.control_level = form.controlLevel;}diff --git a/frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts b/frontend-modern/src/utils/__tests__/aiChatPresentation.test.tsindex 46290cac86..327cebc9bd 100644--- a/frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts+++ b/frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts@@ -1,7 +1,6 @@import { describe, expect, it } from 'vitest';import {AI_CHAT_ASSISTANT_MESSAGE_LABEL,- AI_CHAT_AUTONOMOUS_WARNING_DISMISS_LABEL,AI_CHAT_CONTEXT_USED_LABEL,AI_CHAT_CLOSE_LABEL,AI_CHAT_COMMAND_HELP_BUTTON_LABEL,@@ -49,7 +48,6 @@ import {AI_CHAT_SESSION_SEARCH_LOADING_STATE,AI_CHAT_SESSION_SEARCH_PLACEHOLDER,AI_CHAT_SESSION_SEARCH_TITLE,- AI_CHAT_SWITCH_TO_APPROVAL_LABEL,AI_CHAT_UNDO_LAST_TURN_EMPTY_MESSAGE,AI_CHAT_UNDO_LAST_TURN_ERROR_MESSAGE,AI_CHAT_UNDO_LAST_TURN_LABEL,@@ -94,11 +92,9 @@ describe('aiChatPresentation', () => {expect(AI_CHAT_LAUNCHER_ARIA_LABEL).toBe('Ask Pulse Assistant about this view');expect(AI_CHAT_CLOSE_LABEL).toBe('Close Pulse Assistant');expect(AI_CHAT_SESSION_MENU_TITLE).toBe('Pulse Assistant sessions');- expect(AI_CHAT_AUTONOMOUS_WARNING_DISMISS_LABEL).toBe('Dismiss chat actions warning');expect(AI_CHAT_DISCOVERY_HINT_DISMISS_LABEL).toBe('Dismiss discovery context warning');expect(AI_CHAT_CONTROL_MODE_LABEL).toBe('Assistant chat action mode');expect(AI_CHAT_CONTROL_MODE_MENU_LABEL).toBe('Assistant chat action options');- expect(AI_CHAT_SWITCH_TO_APPROVAL_LABEL).toBe('Switch Assistant chat actions to Ask first');expect(AI_CHAT_COMMAND_HELP_TITLE).toBe('Assistant commands');expect(AI_CHAT_COMMAND_HELP_BUTTON_LABEL).toBe('Open Assistant commands');expect(AI_CHAT_COMMAND_HELP_CLOSE_LABEL).toBe('Close Assistant commands');diff --git a/frontend-modern/src/utils/__tests__/aiControlLevelPresentation.test.ts b/frontend-modern/src/utils/__tests__/aiControlLevelPresentation.test.tsindex 38a4468a7f..d2de0cc261 100644--- a/frontend-modern/src/utils/__tests__/aiControlLevelPresentation.test.ts+++ b/frontend-modern/src/utils/__tests__/aiControlLevelPresentation.test.ts@@ -11,7 +11,7 @@ describe('aiControlLevelPresentation', () => {it('normalizes legacy and unknown control levels', () => {expect(normalizeAIControlLevel('read_only')).toBe('read_only');expect(normalizeAIControlLevel('controlled')).toBe('controlled');- expect(normalizeAIControlLevel('autonomous')).toBe('autonomous');+ expect(normalizeAIControlLevel('autonomous')).toBe('controlled');expect(normalizeAIControlLevel('suggest')).toBe('controlled');expect(normalizeAIControlLevel('unexpected')).toBe('read_only');expect(normalizeAIControlLevel(undefined)).toBe('read_only');@@ -19,15 +19,11 @@ describe('aiControlLevelPresentation', () => {it('returns canonical panel, badge, and description presentation', () => {expect(getAIControlLevelPanelClass('read_only')).toContain('border-blue-200');- expect(getAIControlLevelPanelClass('autonomous')).toContain('border-amber-200');+ expect(getAIControlLevelPanelClass('controlled')).toContain('border-blue-200');expect(getAIControlLevelBadgeClass('controlled')).toContain('bg-amber-100');- expect(getAIControlLevelBadgeClass('autonomous')).toContain('bg-red-100');expect(getAIControlLevelDescription('read_only')).toContain('Assistant can query and explain');- expect(getAIControlLevelDescription('controlled')).toContain('asks before chat-only actions');- expect(getAIControlLevelDescription('autonomous')).toContain('eligible chat-only actions');- expect(getAIControlLevelDescription('autonomous')).toContain(- 'Infrastructure work stays with Patrol mode',- );+ expect(getAIControlLevelDescription('controlled')).toContain('saves each plan to Actions');+ expect(getAIControlLevelDescription('controlled')).toContain('Chat does not execute the plan');});it('returns canonical chat control-level presentation', () => {@@ -38,13 +34,8 @@ describe('aiControlLevelPresentation', () => {});expect(getAIChatControlLevelPresentation('controlled')).toMatchObject({label: 'Ask first',- description: 'Asks before chat-only actions',+ description: 'Plans actions for your review',dotClassName: 'bg-amber-500',});- expect(getAIChatControlLevelPresentation('autonomous')).toMatchObject({- label: 'Chat actions',- description: 'Eligible chat-only actions',- dotClassName: 'bg-red-500',- });});});diff --git a/frontend-modern/src/utils/aiChatPresentation.ts b/frontend-modern/src/utils/aiChatPresentation.tsindex d17fa4b145..9573c0e448 100644--- a/frontend-modern/src/utils/aiChatPresentation.ts+++ b/frontend-modern/src/utils/aiChatPresentation.ts@@ -42,11 +42,9 @@ export const AI_CHAT_TRANSCRIPT_FALLBACK_CLOSE_LABEL = 'Close Assistant transcriexport const AI_CHAT_TRANSCRIPT_FALLBACK_DOWNLOAD_LABEL = 'Download Assistant transcript';export const AI_CHAT_TRANSCRIPT_FALLBACK_TEXTAREA_LABEL = 'Assistant transcript';export const AI_CHAT_TRANSCRIPT_FALLBACK_TITLE = 'Transcript ready';-export const AI_CHAT_AUTONOMOUS_WARNING_DISMISS_LABEL = 'Dismiss chat actions warning';export const AI_CHAT_DISCOVERY_HINT_DISMISS_LABEL = 'Dismiss discovery context warning';export const AI_CHAT_CONTROL_MODE_LABEL = 'Assistant chat action mode';export const AI_CHAT_CONTROL_MODE_MENU_LABEL = 'Assistant chat action options';-export const AI_CHAT_SWITCH_TO_APPROVAL_LABEL = 'Switch Assistant chat actions to Ask first';export const AI_CHAT_COMMAND_HELP_TITLE = 'Assistant commands';export const AI_CHAT_COMMAND_HELP_BUTTON_LABEL = 'Open Assistant commands';export const AI_CHAT_COMMAND_HELP_CLOSE_LABEL = 'Close Assistant commands';diff --git a/frontend-modern/src/utils/aiControlLevelPresentation.ts b/frontend-modern/src/utils/aiControlLevelPresentation.tsindex 49bac30ddc..6dfb7b0e50 100644--- a/frontend-modern/src/utils/aiControlLevelPresentation.ts+++ b/frontend-modern/src/utils/aiControlLevelPresentation.ts@@ -1,4 +1,4 @@-export type AIControlLevel = 'read_only' | 'controlled' | 'autonomous';+export type AIControlLevel = 'read_only' | 'controlled';export interface AIChatControlLevelPresentation {label: string;@@ -8,26 +8,21 @@ export interface AIChatControlLevelPresentation {selectedClassName: string;}+// Legacy saved values still mean action planning, never permission to execute.+// Mirror the server's interactive projection without rewriting the preference.export function normalizeAIControlLevel(value?: string): AIControlLevel {- if (value === 'controlled' || value === 'autonomous' || value === 'read_only') {- return value;- }- if (value === 'suggest') {+ if (value === 'controlled' || value === 'suggest' || value === 'autonomous') {return 'controlled';}return 'read_only';}-export function getAIControlLevelPanelClass(level: AIControlLevel): string {- return level === 'autonomous'- ? 'border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/25'- : 'border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-900/25';+export function getAIControlLevelPanelClass(_level: AIControlLevel): string {+ return 'border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-900/25';}export function getAIControlLevelBadgeClass(level: AIControlLevel): string {switch (level) {- case 'autonomous':- return 'bg-red-100 dark:bg-red-900/25 text-red-700 dark:text-red-300';case 'controlled':return 'bg-amber-100 dark:bg-amber-900/25 text-amber-700 dark:text-amber-300';default:@@ -38,11 +33,9 @@ export function getAIControlLevelBadgeClass(level: AIControlLevel): string {export function getAIControlLevelDescription(level: AIControlLevel): string {switch (level) {case 'controlled':- return 'Assistant asks before chat-only actions. Infrastructure work stays with Patrol mode.';- case 'autonomous':- return 'Assistant may take eligible chat-only actions allowed by policy. Infrastructure work stays with Patrol mode.';+ return 'Assistant can plan infrastructure actions and saves each plan to Actions for you to review and run. Chat does not execute the plan.';default:- return 'Assistant can query and explain only. Infrastructure work stays with Patrol mode.';+ return 'Assistant can query and explain only; it cannot plan infrastructure actions.';}}@@ -50,19 +43,10 @@ export function getAIChatControlLevelPresentation(level: AIControlLevel,): AIChatControlLevelPresentation {switch (level) {- case 'autonomous':- return {- label: 'Chat actions',- description: 'Eligible chat-only actions',- pillClassName:- 'border-red-200 text-red-700 bg-red-50 dark:border-red-800 dark:text-red-200 dark:bg-red-900/25',- dotClassName: 'bg-red-500',- selectedClassName: 'bg-red-50 dark:bg-red-900/25',- };case 'controlled':return {label: 'Ask first',- description: 'Asks before chat-only actions',+ description: 'Plans actions for your review',pillClassName:'border-amber-200 text-amber-700 bg-amber-50 dark:border-amber-800 dark:text-amber-200 dark:bg-amber-900/25',dotClassName: 'bg-amber-500',diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.goindex b7a4edc7f1..16ca353206 100644--- a/internal/ai/chat/service.go+++ b/internal/ai/chat/service.go@@ -205,13 +205,13 @@ func resolveEffectiveControlLevel() tools.ControlLevel {if resolver != nil {if resolved := strings.TrimSpace(resolver(cfg)); config.IsValidControlLevel(resolved) {- return tools.ControlLevel(resolved)+ return tools.ControlLevel(config.AssistantControlLevel(resolved))}}if cfg == nil {return tools.ControlLevelReadOnly}- return tools.ControlLevel(cfg.GetControlLevel())+ return tools.ControlLevel(config.AssistantControlLevel(cfg.GetControlLevel()))}func controlLevelForRequestAutonomousMode(level tools.ControlLevel, requested *bool) tools.ControlLevel {@@ -4440,10 +4440,9 @@ func (s *Service) filterToolsForPatrol(providerTools []providers.Tool) []providefunc (s *Service) isAutonomousModeEnabled() bool {s.mu.RLock()defer s.mu.RUnlock()- if s.autonomousMode {- return true- }- return s.cfg != nil && s.cfg.IsAutonomous()+ // Non-interactive investigation mode is core-owned, not inherited from a+ // legacy saved Assistant preference. Match the public chat turn posture.+ return s.autonomousMode}// ExecuteAssistantTool executes a native Assistant registry tool directly bydiff --git a/internal/ai/chat/service_tooling_test.go b/internal/ai/chat/service_tooling_test.goindex 35d974c0be..a10af4e225 100644--- a/internal/ai/chat/service_tooling_test.go+++ b/internal/ai/chat/service_tooling_test.go@@ -1409,3 +1409,42 @@ func TestInvestigationRunRequiresIdentityBeforeStarting(t *testing.T) {t.Fatalf("expected identity precondition error, got %v", err)}}++func TestAssistantRuntimeProjectsLegacyLevelAfterResolver(t *testing.T) {+ for _, saved := range []string{config.ControlLevelReadOnly, config.ControlLevelControlled, config.ControlLevelAutonomous, "unknown"} {+ for _, resolved := range []string{"", config.ControlLevelReadOnly, config.ControlLevelControlled, config.ControlLevelAutonomous} {+ t.Run(saved+"/resolver-"+resolved, func(t *testing.T) {+ cfg := &config.AIConfig{ControlLevel: saved, ProtectedGuests: []string{"vm-101"}}+ var resolver func(*config.AIConfig) string+ if resolved != "" {+ resolver = func(*config.AIConfig) string { return resolved }+ }+ service := NewService(Config{AIConfig: cfg, ControlLevelResolver: resolver})+ selected := saved+ if resolved != "" {+ selected = resolved+ }+ want := tools.ControlLevelReadOnly+ if selected == config.ControlLevelControlled || selected == config.ControlLevelAutonomous {+ want = tools.ControlLevelControlled+ }+ if got := service.effectiveControlLevelLocked(); got != want {+ t.Fatalf("interactive resolved level %s; want %s", got, want)+ }+ if cfg.ControlLevel != saved {+ t.Fatal("runtime projection rewrote saved config")+ }+ if service.isAutonomousModeEnabled() {+ t.Fatal("saved Assistant preference removed interactive question tools")+ }+ // A request flag may tighten but never widen the projected level.+ for _, flag := range []*bool{nil, boolPtrProjection(false), boolPtrProjection(true)} {+ if got := controlLevelForRequestAutonomousMode(service.effectiveControlLevelLocked(), flag); got != want {+ t.Fatalf("request flag widened level: %s", got)+ }+ }+ })+ }+ }+}+func boolPtrProjection(v bool) *bool { return &v }diff --git a/internal/ai/tools/control_resource_test.go b/internal/ai/tools/control_resource_test.goindex 68e615e73c..df8d77a813 100644--- a/internal/ai/tools/control_resource_test.go+++ b/internal/ai/tools/control_resource_test.go@@ -6,6 +6,7 @@ import ("strings""testing"+ "github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")@@ -204,3 +205,57 @@ func TestPulseControlAvailabilityUsesPlanner(t *testing.T) {})}}++func TestAssistantProjectedModesStillOnlyPlanAndRespectExecuteAuthority(t *testing.T) {+ for _, raw := range []string{config.ControlLevelReadOnly, config.ControlLevelControlled, config.ControlLevelAutonomous} {+ for _, authority := range []bool{false, true} {+ t.Run(raw+map[bool]string{true: "/authorised", false: "/unauthorised"}[authority], func(t *testing.T) {+ provider := newTrueNASUnifiedQueryProvider(t)+ native := &stubAppContainerActionProvider{}+ planned := 0+ executor := NewPulseToolExecutor(ExecutorConfig{+ UnifiedResourceProvider: provider, ReadState: provider.ResourceRegistry,+ AppContainerActionProvider: native,+ ControlLevel: ControlLevel(config.AssistantControlLevel(raw)),+ TypedActionPlanner: typedActionPlannerFunc(func(_ context.Context, org string, req unifiedresources.ActionRequest) (*unifiedresources.ActionPlan, error) {+ planned+++ if org != "lab" || req.ResourceID != "app-container:truenas-main:nextcloud" {+ t.Fatalf("plan lost scope: %q/%s", org, req.ResourceID)+ }+ return &unifiedresources.ActionPlan{ActionID: "synthetic-action", Allowed: true, RequiresApproval: true, ApprovalPolicy: unifiedresources.ApprovalAdmin, PlanHash: "synthetic-plan"}, nil+ }),+ })+ executor.SetOrgID("lab")+ executor.ApplyExecutionProfile(ProfileInteractiveAssistant)+ executor.SetExecuteAuthority(authority)+ result, err := executor.ExecuteTool(context.Background(), "pulse_control", map[string]interface{}{"type": "resource", "resource_id": "Nextcloud", "action": "restart"})+ wantPlan := raw != config.ControlLevelReadOnly && authority+ if wantPlan {+ if err != nil || result.IsError {+ t.Fatalf("expected plan: %v / %+v", err, result)+ }+ var payload map[string]any+ if err := json.Unmarshal([]byte(result.Content[0].Text), &payload); err != nil {+ t.Fatal(err)+ }+ if payload["execution_requested"] != false || payload["requires_approval"] != true || payload["approval_policy"] != string(unifiedresources.ApprovalAdmin) {+ t.Fatalf("plan granted execution: %+v", payload)+ }+ if planned != 1 {+ t.Fatalf("plans=%d", planned)+ }+ } else {+ if err == nil && !result.IsError {+ t.Fatalf("unauthorised/read-only plan accepted: %+v", result)+ }+ if planned != 0 {+ t.Fatalf("unauthorised plans=%d", planned)+ }+ }+ if len(native.calls) != 0 {+ t.Fatal("Assistant plan executed against native provider")+ }+ })+ }+ }+}diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.goindex 0986b24b6d..f05affd4b5 100644--- a/internal/api/ai_handlers.go+++ b/internal/api/ai_handlers.go@@ -1849,15 +1849,14 @@ func (h *AISettingsHandler) SetOnControlSettingsChange(callback func()) {h.onControlSettingsChange = callback}-// EffectiveControlLevel returns the Assistant control level that should be-// exposed or enforced for the current entitlement state. The stored setting can-// remain autonomous so it comes back if the entitlement returns, but runtime-// execution without ai_autofix must stay in approval mode.+// EffectiveControlLevel returns the interactive planning posture after existing+// entitlement checks. Saved preferences stay intact, but no entitlement grants+// Assistant chat approval or execution authority.func (h *AISettingsHandler) EffectiveControlLevel(ctx context.Context, settings *config.AIConfig) string {if settings == nil {return config.ControlLevelReadOnly}- return settings.GetEffectiveControlLevel(+ return settings.GetAssistantControlLevel(h.GetAIService(ctx).HasLicenseFeature(ai.FeatureAIAutoFix),)}@@ -2342,7 +2341,7 @@ type AISettingsResponse struct {// Request timeout (seconds) - for slow hardware running local modelsRequestTimeoutSeconds int `json:"request_timeout_seconds,omitempty"`// Infrastructure control settings- ControlLevel string `json:"control_level"` // "read_only", "controlled", "autonomous"+ ControlLevel string `json:"control_level"` // "read_only" or "controlled" (interactive projection)ProtectedGuests []string `json:"protected_guests"` // VMIDs/names that AI cannot control// Discovery settingsDiscoveryEnabled bool `json:"discovery_enabled"` // true if discovery is enabled@@ -2678,7 +2677,7 @@ func (h *AISettingsHandler) HandleGetAISettings(w http.ResponseWriter, r *http.RProviders: aiProviderDefinitionResponses(settings),CostBudgetUSD30d: settings.CostBudgetUSD30d,RequestTimeoutSeconds: settings.RequestTimeoutSeconds,- ControlLevel: settings.GetEffectiveControlLevel(hasAutoFixFeature),+ ControlLevel: settings.GetAssistantControlLevel(hasAutoFixFeature),ProtectedGuests: settings.GetProtectedGuests(),DiscoveryEnabled: settings.IsDiscoveryEnabled(),DiscoveryIntervalHours: settings.DiscoveryIntervalHours,@@ -3070,7 +3069,12 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *httreturn}}- settings.ControlLevel = level+ // Older clients may echo the projected GET value on an unrelated save.+ // Keep a legacy preference when the interactive mode did not change:+ // rewriting it can alter the legacy service's raw-command approval gate.+ if !(level == config.ControlLevelControlled && settings.GetControlLevel() == config.ControlLevelAutonomous) {+ settings.ControlLevel = level+ }}// Handle protected guests (nil = don't update)@@ -3232,7 +3236,7 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *httConfiguredProviders: settings.GetConfiguredProviders(),Providers: aiProviderDefinitionResponses(settings),RequestTimeoutSeconds: settings.RequestTimeoutSeconds,- ControlLevel: settings.GetEffectiveControlLevel(hasAutoFixFeature),+ ControlLevel: settings.GetAssistantControlLevel(hasAutoFixFeature),ProtectedGuests: settings.GetProtectedGuests(),DiscoveryEnabled: settings.DiscoveryEnabled,DiscoveryIntervalHours: settings.DiscoveryIntervalHours,diff --git a/internal/api/ai_handlers_test.go b/internal/api/ai_handlers_test.goindex 8382f7eae0..77e51219c9 100644--- a/internal/api/ai_handlers_test.go+++ b/internal/api/ai_handlers_test.go@@ -3821,3 +3821,135 @@ func TestOrchestratorAndChatAdaptersMapTheirMessageContracts(t *testing.T) {t.Error("chatServiceAdapter.GetMessages must route through adaptChatMessage")}}++func TestAssistantSettingsProjectionAndUnrelatedSave(t *testing.T) {+ for _, level := range []string{config.ControlLevelReadOnly, config.ControlLevelControlled, config.ControlLevelAutonomous, "suggest", "unknown"} {+ for _, licensed := range []bool{false, true} {+ name := level + map[bool]string{true: "/entitled", false: "/unentitled"}[licensed]+ t.Run(name, func(t *testing.T) {+ tmp := t.TempDir()+ persistence := config.NewConfigPersistence(tmp)+ cfg := config.NewDefaultAIConfig()+ cfg.ControlLevel = level+ cfg.ProtectedGuests = []string{"vm-101"}+ cfg.PatrolAutonomyLevel = config.PatrolAutonomyFull+ cfg.PatrolActionEmergencyStop = true+ cfg.PatrolAutoFix = true+ require.NoError(t, persistence.SaveAIConfig(*cfg))+ handler := newTestAISettingsHandler(&config.Config{DataPath: tmp}, persistence, nil)+ handler.defaultAIService.SetLicenseChecker(stubLicenseChecker{allow: licensed})+ refreshes := 0+ handler.SetOnControlSettingsChange(func() { refreshes++ })+ want := config.ControlLevelReadOnly+ if level == config.ControlLevelControlled || level == config.ControlLevelAutonomous || level == "suggest" {+ want = config.ControlLevelControlled+ }+ for _, method := range []string{http.MethodGet, http.MethodPut} {+ rec := httptest.NewRecorder()+ if method == http.MethodGet {+ handler.HandleGetAISettings(rec, newLoopbackRequest(method, "/api/settings/ai", nil))+ } else {+ handler.HandleUpdateAISettings(rec, newLoopbackRequest(method, "/api/settings/ai/update", bytes.NewBufferString(`{"request_timeout_seconds":120}`)))+ }+ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())+ var response AISettingsResponse+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &response))+ require.Equal(t, want, response.ControlLevel, "interactive response must not advertise execution authority")+ persisted, err := persistence.LoadAIConfig()+ require.NoError(t, err)+ wantStored := level+ if level == "suggest" {+ wantStored = config.ControlLevelControlled+ }+ require.Equal(t, wantStored, persisted.ControlLevel, "unrelated save must preserve preference")+ require.Equal(t, []string{"vm-101"}, persisted.ProtectedGuests)+ require.Equal(t, config.PatrolAutonomyFull, persisted.PatrolAutonomyLevel)+ require.True(t, persisted.PatrolActionEmergencyStop)+ require.True(t, persisted.PatrolAutoFix)+ require.Zero(t, refreshes)+ }+ })+ }+ }+}++func TestAssistantLegacyClientUpdateKeepsEntitlementAndPreference(t *testing.T) {+ for _, licensed := range []bool{false, true} {+ t.Run(map[bool]string{true: "entitled", false: "unentitled"}[licensed], func(t *testing.T) {+ tmp := t.TempDir()+ persistence := config.NewConfigPersistence(tmp)+ cfg := config.NewDefaultAIConfig()+ cfg.ControlLevel = config.ControlLevelReadOnly+ cfg.ProtectedGuests = []string{"vm-101"}+ cfg.PatrolAutonomyLevel = config.PatrolAutonomyMonitor+ require.NoError(t, persistence.SaveAIConfig(*cfg))+ handler := newTestAISettingsHandler(&config.Config{DataPath: tmp}, persistence, nil)+ handler.defaultAIService.SetLicenseChecker(stubLicenseChecker{allow: licensed})+ rec := httptest.NewRecorder()+ handler.HandleUpdateAISettings(rec, newLoopbackRequest(http.MethodPut, "/api/settings/ai/update", bytes.NewBufferString(`{"control_level":"autonomous"}`)))+ if licensed {+ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())+ var response AISettingsResponse+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &response))+ require.Equal(t, config.ControlLevelControlled, response.ControlLevel)+ } else {+ require.Equal(t, http.StatusPaymentRequired, rec.Code, rec.Body.String())+ }+ persisted, err := persistence.LoadAIConfig()+ require.NoError(t, err)+ want := config.ControlLevelReadOnly+ if licensed {+ want = config.ControlLevelAutonomous+ }+ require.Equal(t, want, persisted.ControlLevel)+ require.Equal(t, []string{"vm-101"}, persisted.ProtectedGuests)+ require.Equal(t, config.PatrolAutonomyMonitor, persisted.PatrolAutonomyLevel)+ })+ }+}++func TestAssistantProjectedModeEchoPreservesLegacyPolicy(t *testing.T) {+ for _, licensed := range []bool{false, true} {+ t.Run(map[bool]string{true: "entitled", false: "unentitled"}[licensed], func(t *testing.T) {+ tmp := t.TempDir()+ persistence := config.NewConfigPersistence(tmp)+ cfg := config.NewDefaultAIConfig()+ cfg.ControlLevel = config.ControlLevelAutonomous+ cfg.ProtectedGuests = []string{"vm-101"}+ cfg.PatrolAutonomyLevel = config.PatrolAutonomyFull+ cfg.PatrolActionEmergencyStop = true+ require.NoError(t, persistence.SaveAIConfig(*cfg))+ handler := newTestAISettingsHandler(&config.Config{DataPath: tmp}, persistence, nil)+ handler.defaultAIService.SetLicenseChecker(stubLicenseChecker{allow: licensed})+ get := httptest.NewRecorder()+ handler.HandleGetAISettings(get, newLoopbackRequest(http.MethodGet, "/api/settings/ai", nil))+ require.Equal(t, http.StatusOK, get.Code)+ var response AISettingsResponse+ require.NoError(t, json.Unmarshal(get.Body.Bytes(), &response))+ require.Equal(t, config.ControlLevelControlled, response.ControlLevel)+ body, err := json.Marshal(AISettingsUpdateRequest{ControlLevel: &response.ControlLevel, RequestTimeoutSeconds: ptr(120)})+ require.NoError(t, err)+ rec := httptest.NewRecorder()+ handler.HandleUpdateAISettings(rec, newLoopbackRequest(http.MethodPut, "/api/settings/ai/update", bytes.NewReader(body)))+ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())+ persisted, err := persistence.LoadAIConfig()+ require.NoError(t, err)+ require.Equal(t, config.ControlLevelAutonomous, persisted.ControlLevel, "a mode echo must not change legacy command admission")+ require.Equal(t, licensed, handler.defaultAIService.IsAutonomous(), "legacy entitlement/approval selection is unchanged")+ require.Equal(t, 120, persisted.RequestTimeoutSeconds)+ require.Equal(t, []string{"vm-101"}, persisted.ProtectedGuests)+ require.Equal(t, config.PatrolAutonomyFull, persisted.PatrolAutonomyLevel)+ require.True(t, persisted.PatrolActionEmergencyStop)+ // Explicit opt-out and a later opt-in remain real mode changes.+ for _, level := range []string{config.ControlLevelReadOnly, config.ControlLevelControlled} {+ rec = httptest.NewRecorder()+ handler.HandleUpdateAISettings(rec, newLoopbackRequest(http.MethodPut, "/api/settings/ai/update", bytes.NewBufferString(`{"control_level":"`+level+`"}`)))+ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())+ persisted, err = persistence.LoadAIConfig()+ require.NoError(t, err)+ require.Equal(t, level, persisted.ControlLevel)+ require.False(t, handler.defaultAIService.IsAutonomous())+ }+ })+ }+}diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 023121c4bd..5f9d67b9f6 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -27073,3 +27073,32 @@ func TestContract_PMGFalseScopeIsExplicitOnWire(t *testing.T) {}}}++func TestContract_AssistantSettingsAdvertisePlanningNotExecution(t *testing.T) {+ for _, entitled := range []bool{false, true} {+ tmp := t.TempDir()+ persistence := config.NewConfigPersistence(tmp)+ cfg := config.NewDefaultAIConfig()+ cfg.ControlLevel = config.ControlLevelAutonomous+ if err := persistence.SaveAIConfig(*cfg); err != nil {+ t.Fatal(err)+ }+ handler := newTestAISettingsHandler(&config.Config{DataPath: tmp}, persistence, nil)+ handler.defaultAIService.SetLicenseChecker(stubLicenseChecker{allow: entitled})+ rec := httptest.NewRecorder()+ handler.HandleGetAISettings(rec, newLoopbackRequest(http.MethodGet, "/api/settings/ai", nil))+ if rec.Code != http.StatusOK {+ t.Fatalf("status %d", rec.Code)+ }+ var payload map[string]json.RawMessage+ if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {+ t.Fatal(err)+ }+ if string(payload["control_level"]) != `"controlled"` {+ t.Fatalf("interactive control_level %s", payload["control_level"])+ }+ if string(payload["protected_guests"]) != "[]" {+ t.Fatalf("protected_guests must remain an explicit array: %s", payload["protected_guests"])+ }+ }+}diff --git a/internal/config/ai.go b/internal/config/ai.goindex 53a224ad6b..02ed985f99 100644--- a/internal/config/ai.go+++ b/internal/config/ai.go@@ -1005,6 +1005,26 @@ func (c *AIConfig) GetEffectiveControlLevel(autonomousAllowed bool) string {return EffectiveControlLevelForEntitlement(c.GetControlLevel(), autonomousAllowed)}+// AssistantControlLevel projects an interactive Assistant setting to the two+// supported behaviours: read/query or canonical action planning. A legacy+// autonomous preference never grants approval or execution authority here.+// Keep the shared vocabulary and stored value intact: legacy command admission+// uses IsAutonomous to REQUIRE approval, and Patrol has its own policy.+func AssistantControlLevel(level string) string {+ switch agentcapabilities.NormalizeControlLevel(level) {+ case agentcapabilities.ControlLevelControlled, agentcapabilities.ControlLevelAutonomous:+ return ControlLevelControlled+ default:+ return ControlLevelReadOnly+ }+}++// GetAssistantControlLevel returns the truthful interactive level after the+// existing entitlement check, without migrating or persisting any preference.+func (c *AIConfig) GetAssistantControlLevel(autonomousAllowed bool) string {+ return AssistantControlLevel(c.GetEffectiveControlLevel(autonomousAllowed))+}+// IsControlEnabled returns true if AI has any control capability beyond read-onlyfunc (c *AIConfig) IsControlEnabled() bool {return agentcapabilities.ControlLevelAllowsControlTools(agentcapabilities.ControlLevel(c.GetControlLevel()))diff --git a/internal/config/ai_config_test.go b/internal/config/ai_config_test.goindex c27f120702..706e6f9ddf 100644--- a/internal/config/ai_config_test.go+++ b/internal/config/ai_config_test.go@@ -2,6 +2,7 @@ package configimport ("encoding/json"+ "reflect""strings""testing""time"@@ -1401,3 +1402,43 @@ func TestAIConfigPatrolInvestigationBudgetIsAnEvidenceCallBudget(t *testing.T) {t.Fatalf("AI config lost investigation evidence budget: %s", payload)}}++func TestAssistantControlProjectionPreservesSavedPolicy(t *testing.T) {+ for _, level := range []string{ControlLevelReadOnly, ControlLevelControlled, ControlLevelAutonomous, "", "unknown"} {+ for _, allowed := range []bool{false, true} {+ t.Run(level+map[bool]string{true: "/entitled", false: "/unentitled"}[allowed], func(t *testing.T) {+ cfg := NewDefaultAIConfig()+ cfg.ControlLevel = level+ cfg.PatrolAutonomyLevel = PatrolAutonomyFull+ cfg.PatrolActionEmergencyStop = true+ cfg.ProtectedGuests = []string{"vm-101"}+ before := *cfg+ want := ControlLevelReadOnly+ if level == ControlLevelControlled || level == ControlLevelAutonomous {+ want = ControlLevelControlled+ }+ if got := cfg.GetAssistantControlLevel(allowed); got != want {+ t.Fatalf("interactive level = %s; want %s", got, want)+ }+ if !reflect.DeepEqual(before, *cfg) {+ t.Fatal("projection mutated saved policy")+ }+ if cfg.IsAutonomous() != (level == ControlLevelAutonomous) {+ t.Fatal("legacy approval-admission posture changed")+ }+ if cfg.GetPatrolAutonomyLevel() != PatrolAutonomyFull {+ t.Fatal("Assistant projection changed Patrol mode")+ }+ })+ }+ }+ var nilConfig *AIConfig+ if nilConfig.GetAssistantControlLevel(true) != ControlLevelReadOnly {+ t.Fatal("nil config must be read-only")+ }+ for _, unknown := range []string{"suggest", "AUTONOMOUS", " autonomous ", "not-a-mode"} {+ if AssistantControlLevel(unknown) != ControlLevelReadOnly {+ t.Fatalf("unmigrated input %q did not fail closed", unknown)+ }+ }+}diff --git a/scripts/release_control/ai_runtime_docs_policy_test.py b/scripts/release_control/ai_runtime_docs_policy_test.pyindex 3d324a2bc4..1ebcc3ef8a 100644--- a/scripts/release_control/ai_runtime_docs_policy_test.py+++ b/scripts/release_control/ai_runtime_docs_policy_test.py@@ -323,5 +323,19 @@ class AIRuntimeDocsPolicyTest(unittest.TestCase):self.assertNotIn("Patrol Autonomy Level", control_doc)+ def test_existing_help_matches_planning_boundary(self):+ for name in ("AI.md", "AI_AUTONOMY.md"):+ with self.subTest(name=name):+ text = read_repo_text("docs/" + name)+ self.assertEqual(text, read_repo_text("frontend-modern/public/docs/" + name))+ start = text.index("## Assistant Control Levels" if name == "AI_AUTONOMY.md" else "### Control Levels")+ end = text.index("\n---", start)+ section = " ".join(text[start:end].split())+ for retained in ("Read-only", "Ask first", "Actions", "does not execute", "stored", "entitlement", "Patrol", "verification"):+ self.assertIn(retained, section)+ for retired in ("executes commands without prompting", "AI executes actions without prompting", "APPROVAL_REQUIRED", "Approve** to execute"):+ self.assertNotIn(retired, section)++if __name__ == "__main__":unittest.main()