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
Add Patrol model readiness advisor
rcourtmaned84c92da3a9
diff --git a/docs/AI.md b/docs/AI.mdindex d11ab87ad5..f44281a279 100644--- a/docs/AI.md+++ b/docs/AI.md@@ -475,6 +475,23 @@ You can set separate models for:- Patrol (`patrol_model`)- Patrol fix model (`auto_fix_model`, retained as the compatibility settings key)+### Patrol model readiness advisor++Open **Settings → Pulse Intelligence → Patrol → Model readiness** and select+**Check Patrol model** to evaluate the exact provider, model, and local runtime.+The advisor uses synthetic data only and never calls infrastructure tools. It+checks provider connectivity, exact typed streaming tool calls, two+Patrol-shaped context fixtures, a multi-turn tool-result continuation, and+projected loop latency. Provider calls respect the configured cost budget and+their token counts are recorded under the `patrol_readiness` usage category.++Results are reported separately for **Watch only** and **Ask first**. A short+synthetic evaluation never certifies **Safe auto-fix** or **Autopilot**; those+modes remain `not_assessed` until an extended governed canary is available.+Changing the selected model, provider credentials or endpoint, or relevant+timeout settings invalidates the cached result. Slow evaluations can be+cancelled from the UI without replacing the last completed evidence.+### StorageAI settings are stored encrypted at rest in `ai.enc` under the Pulse config directory. Related files:@@ -484,6 +501,7 @@ AI settings are stored encrypted at rest in `ai.enc` under the Pulse config dire| `ai.enc` | Encrypted AI configuration and credentials || `ai_findings.json` | Patrol findings || `ai_patrol_runs.json` | Patrol run history |+| `ai_patrol_model_readiness.json` | Last versioned Patrol model-readiness result; contains outcomes and timings, not prompts, credentials, or tool transcripts || `ai_usage_history.json` | Token usage data || `ai_chat_sessions.json` | Legacy chat sessions (UI sync) || `baselines.json` | Learned resource baselines |@@ -495,6 +513,7 @@ Config directory: `/etc/pulse` (systemd) or `/data` (Docker/Kubernetes)### Testing- Test provider connectivity: `POST /api/ai/test` and `POST /api/ai/test/{provider}`+- Evaluate Patrol model readiness: `POST /api/ai/patrol/readiness`- List available models: `GET /api/ai/models`---diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 44cc86f7ee..5ea5d2d916 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -1947,6 +1947,12 @@ Agent` secondary handoff against the live setup wizard instead of relyingcarrier-grade NAT addresses. Any unresolved, public, or mixed public/localanswer must keep requiring HTTPS/WSS.+19. Keep the Patrol model-readiness advisor outside the agent command+ lifecycle. `POST /api/ai/patrol/readiness` may exercise only synthetic+ provider tools and in-memory tool results under settings-write authority;+ it must not request `agent:exec`, dispatch an agent command, inspect agent+ inventory, or turn a successful model probe into command authority.+## Current StateShared `internal/api/ai_handlers.go` now projects separate Patrol investigationdiff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 298dd996d4..fc41798efe 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -3885,6 +3885,20 @@ Assistant receives a selected attention item only after the operator opens it.The handoff is explanation-only and cannot infer a capability, approve anaction, or replace evidence and lifecycle truth.+### Patrol model-readiness evidence++Keep the Patrol model-readiness advisor provider-neutral and evidence-based.+`POST /api/ai/patrol/readiness` must use synthetic, read-only streaming+scenarios to distinguish provider connectivity, typed tool-call protocol,+context selection quality, continuation behavior, and latency rather than+treating a successful model-list or chat request as proof of autonomy+suitability. Apply the shared cost budget and record probe token usage under+`patrol_readiness`. Persist only sanitized scores, timings, and model metadata;+invalidate evidence when the selected provider, model, credential, endpoint, or+relevant timeout budget changes. Monitor/Watch and Approval/Ask First may be+verified independently, while Safe auto-fix and Autopilot remain explicitly+unassessed until deterministic remediation evals exist.+## Current StateFirst-session assistant discoverability is now a contract concern. Successfuldiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 47ba08bc23..99ca4249ca 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -3488,6 +3488,16 @@ proof lives in `internal/api/attention_handlers_test.go`,`frontend-modern/src/api/__tests__/patrolAttention.test.ts`, and`internal/api/route_inventory_test.go`.+### Patrol model-readiness transport++Keep the Patrol model-readiness API and settings snapshot symmetric.+`POST /api/ai/patrol/readiness` returns explicit connectivity, tool-call,+context-quality, and latency dimensions plus per-autonomy-mode suitability;+`/api/settings/ai` exposes the latest compatible snapshot as+`patrol_model_readiness`. Advisor execution must remain cancellable, use the+same settings-write permission boundary as other AI diagnostics, and avoid+returning prompts, tool transcripts, credentials, or infrastructure data.+## Current StateThe public Patrol investigation boundary now carries independentdiff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex 4024584b86..13246f0782 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -2350,6 +2350,14 @@ not a detached element reference. Browser proof covers desktop andrequest, and focus restoration for both confirmed and contradictedverification.+41. Keep the Patrol model-readiness panel on the canonical AI settings state+ and shared model-selection surface. The panel must render connectivity,+ tool protocol, context quality, latency, and per-mode suitability as+ separate accessible evidence, support request cancellation, hydrate the+ latest compatible snapshot, and label failed or stale runs as evaluations+ rather than verified results. Safe auto-fix and Autopilot remain visibly+ `not_assessed` until their governed canaries exist.+## Current StateAssistant availability in the app shell is derived from thediff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex c1d535c959..02383ed84b 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -1828,6 +1828,14 @@ If no subject-linked posture exists, the UI says protection is unknown ratherthan unprotected. The summary-only navigation path does not query recoveryhistory.+### Patrol model-readiness isolation++Keep Patrol model-readiness context fixtures synthetic and isolated from+storage/recovery state. The advisor may model backup failure and storage+pressure to assess context selection, but it must not read live backup records,+invoke recovery APIs, mutate storage, or treat a synthetic pass as evidence+that Safe auto-fix or Autopilot remediation is verified.+## Current StateShared `internal/api/ai_handlers.go` now projects separate Patrol investigationdiff --git a/frontend-modern/src/api/__tests__/patrolPreflight.test.ts b/frontend-modern/src/api/__tests__/patrolPreflight.test.tsindex 0e55e66310..9d63efa078 100644--- a/frontend-modern/src/api/__tests__/patrolPreflight.test.ts+++ b/frontend-modern/src/api/__tests__/patrolPreflight.test.ts@@ -1,5 +1,5 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { runPatrolPreflight } from '../patrol';+import { runPatrolModelReadiness, runPatrolPreflight } from '../patrol';import { apiFetchJSON } from '@/utils/apiClient';vi.mock('@/utils/apiClient', () => ({@@ -179,3 +179,48 @@ describe('runPatrolPreflight', () => {expect(result.recommendation).toContain('real Patrol');});});++describe('runPatrolModelReadiness', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('runs the multi-scenario advisor through its explicit endpoint', async () => {+ const controller = new AbortController();+ vi.mocked(apiFetchJSON).mockResolvedValueOnce({+ probe_version: 'patrol-readiness/v1',+ success: true,+ status: 'pass',+ provider: 'ollama',+ model: 'qwen3:8b',+ duration_ms: 12_000,+ max_verified_mode: 'monitor',+ summary: 'Verified for Watch only on this install.',+ dimensions: {+ connectivity: { status: 'pass', summary: 'Connected.' },+ tool_protocol: { status: 'pass', summary: 'Passed.', attempts: 3, passed: 3 },+ context_quality: { status: 'pass', summary: 'Passed.', attempts: 2, passed: 2 },+ latency: { status: 'pass', summary: 'Passed.' },+ },+ modes: {+ monitor: { status: 'verified', summary: 'Verified.' },+ approval: { status: 'not_suitable', summary: 'Continuation failed.' },+ assisted: { status: 'not_assessed', summary: 'Extended canary required.' },+ full: { status: 'not_assessed', summary: 'Governed canary required.' },+ },+ recorded_at: '2026-07-13T08:00:00Z',+ recorded_at_unix: 1783929600,+ });++ const result = await runPatrolModelReadiness({ model: 'ollama:qwen3:8b' }, controller.signal);++ expect(apiFetchJSON).toHaveBeenCalledWith('/api/ai/patrol/readiness', {+ method: 'POST',+ body: JSON.stringify({ model: 'ollama:qwen3:8b' }),+ headers: { 'Content-Type': 'application/json' },+ signal: controller.signal,+ });+ expect(result.max_verified_mode).toBe('monitor');+ expect(result.dimensions.tool_protocol.passed).toBe(3);+ });+});diff --git a/frontend-modern/src/api/patrol.ts b/frontend-modern/src/api/patrol.tsindex 1d41eff9c2..9cf008877f 100644--- a/frontend-modern/src/api/patrol.ts+++ b/frontend-modern/src/api/patrol.ts@@ -8,6 +8,7 @@ import { arrayOrEmpty, promoteLegacyAlertIdentifier } from './responseUtils';import type { InvestigationRecord } from './ai';import type { ResourceCriticality } from './resourceOperatorState';import type { PatrolActionReference } from '@/types/actionAudit';+import type { PatrolModelReadinessSnapshot } from '@/types/ai';export type FindingSeverity = 'info' | 'watch' | 'warning' | 'critical';export type FindingCategory =@@ -911,3 +912,28 @@ export async function runPatrolPreflight(headers: { 'Content-Type': 'application/json' },});}++export interface PatrolModelReadinessRequest {+ provider?: string;+ model?: string;+}++export type PatrolModelReadinessResponse = PatrolModelReadinessSnapshot;++/**+ * Run the explicit Patrol model readiness advisor. The request exercises the+ * streaming tool path with typed arguments, context fixtures, and a synthetic+ * tool-result continuation. Passing an AbortSignal cancels the server-side+ * provider request through the HTTP request context.+ */+export async function runPatrolModelReadiness(+ body: PatrolModelReadinessRequest = {},+ signal?: AbortSignal,+): Promise<PatrolModelReadinessResponse> {+ return apiFetchJSON<PatrolModelReadinessResponse>('/api/ai/patrol/readiness', {+ method: 'POST',+ body: JSON.stringify(body),+ headers: { 'Content-Type': 'application/json' },+ signal,+ });+}diff --git a/frontend-modern/src/components/Settings/AIModelSelectionSection.tsx b/frontend-modern/src/components/Settings/AIModelSelectionSection.tsxindex 197bcdda95..8e331ea9b9 100644--- a/frontend-modern/src/components/Settings/AIModelSelectionSection.tsx+++ b/frontend-modern/src/components/Settings/AIModelSelectionSection.tsx@@ -1,5 +1,5 @@import { A } from '@solidjs/router';-import { Component, Show } from 'solid-js';+import { Component, For, Show } from 'solid-js';import { AIProviderConfigurationSection } from '@/components/Settings/AIProviderConfigurationSection';import { isModelProviderConfigured } from '@/components/Settings/aiSettingsModel';import { settingsTabPath } from '@/components/Settings/settingsNavigationModel';@@ -58,16 +58,14 @@ const stripModelProvider = (modelId: string) => {return colon === -1 ? trimmed : trimmed.slice(colon + 1);};-export const PatrolPreflightControl: Component<{ state: AISettingsState }> = (controlProps) => {+export const PatrolModelReadinessControl: Component<{ state: AISettingsState }> = (+ controlProps,+) => {const { state } = controlProps;- const result = state.patrolPreflightResult;+ const result = state.patrolModelReadinessResult;- // The cached result may be for a model the operator already moved away- // from in the form (e.g. they changed the dropdown but haven't clicked- // Check Patrol model yet). When that happens, surface a hint so the green- // "verified" badge doesn't silently mislead. The backend reads the- // form's pending patrolModel on Check Patrol model click, so refreshing- // resolves the staleness.+ // A persisted result is valid only for the model that was evaluated. The+ // backend additionally invalidates on endpoint and timeout changes.const pendingFormModel = () => stripModelProvider(state.form.patrolModel || '');const cachedResultModel = () => result()?.model?.trim() || '';const isStaleAgainstFormSelection = () => {@@ -80,8 +78,8 @@ export const PatrolPreflightControl: Component<{ state: AISettingsState }> = (coconst r = result();if (!r) return 'idle';if (isStaleAgainstFormSelection()) return 'warning';- if (r.success) return 'success';- if (r.cause === 'model_tool_support_unverified') return 'warning';+ if (r.status === 'pass') return 'success';+ if (r.status === 'warning') return 'warning';return 'error';};@@ -102,15 +100,12 @@ export const PatrolPreflightControl: Component<{ state: AISettingsState }> = (coconst r = result();if (!r) return '';if (isStaleAgainstFormSelection()) {- return `Verified result is for ${cachedResultModel()}, your current selection is ${pendingFormModel()}`;+ return `Evaluation result is for ${cachedResultModel()}, your current selection is ${pendingFormModel()}`;}- if (r.success) {- return 'Patrol model ready';- }- if (r.cause === 'model_tool_support_unverified') {- return 'Patrol model needs a real run to confirm';- }- return r.message || 'Patrol model check failed';+ if (r.max_verified_mode === 'approval') return 'Verified for Watch only and Ask first';+ if (r.max_verified_mode === 'monitor') return 'Verified for Watch only';+ if (r.status === 'warning') return 'Patrol model needs attention';+ return 'Patrol model not verified';};const detail = () => {@@ -119,16 +114,72 @@ export const PatrolPreflightControl: Component<{ state: AISettingsState }> = (coif (isStaleAgainstFormSelection()) {return 'Click Check Patrol model to test the pending selection.';}- if (r.success) {- return 'The selected model can run Patrol work on this install.';+ return r.summary || '';+ };++ const dimensionRows = () => {+ const r = result();+ if (!r) return [];+ return [+ { label: 'Connectivity', value: r.dimensions.connectivity },+ { label: 'Tool protocol', value: r.dimensions.tool_protocol },+ { label: 'Context quality', value: r.dimensions.context_quality },+ { label: 'Latency', value: r.dimensions.latency },+ ];+ };++ const modeRows = () => {+ const r = result();+ if (!r) return [];+ return [+ { label: 'Watch only', value: r.modes.monitor },+ { label: 'Ask first', value: r.modes.approval },+ { label: 'Safe auto-fix', value: r.modes.assisted },+ { label: 'Autopilot', value: r.modes.full },+ ];+ };++ const statusLabel = (status: string) => {+ switch (status) {+ case 'pass':+ case 'verified':+ return 'Passed';+ case 'warning':+ return 'Caution';+ case 'fail':+ case 'not_suitable':+ return 'Failed';+ default:+ return 'Not assessed';}- if (r.cause === 'model_tool_support_unverified') {- return 'Run Patrol once to confirm this model works correctly in practice.';+ };++ const modeStatusLabel = (status: string) => {+ switch (status) {+ case 'verified':+ return 'Verified';+ case 'warning':+ return 'Caution';+ case 'not_suitable':+ return 'Not suitable';+ default:+ return 'Not assessed';+ }+ };++ const readinessStatusTextClass = (status: string) => {+ switch (status) {+ case 'pass':+ case 'verified':+ return 'text-green-700 dark:text-green-300';+ case 'warning':+ return 'text-amber-700 dark:text-amber-300';+ case 'fail':+ case 'not_suitable':+ return 'text-red-700 dark:text-red-300';+ default:+ return 'text-muted';}- // Summary and message are often the same string on config-level- // failures; don't render the headline twice.- const fallback = r.summary || r.message || '';- return fallback === headline() ? '' : fallback;};const formatDuration = (ms: number) => {@@ -154,17 +205,31 @@ export const PatrolPreflightControl: Component<{ state: AISettingsState }> = (co<div class="mt-2 flex flex-col gap-2"><div class="flex items-center justify-between gap-2"><p class="text-[11px] text-muted">- Check that this model can run Patrol work, not just connect to the provider.+ Evaluate connectivity, streaming tools, context handling, latency, and suitable Patrol+ modes. Uses synthetic data only and may take up to two minutes.</p><buttontype="button"- onClick={() => void state.runPatrolToolPreflight()}- disabled={state.patrolPreflightRunning() || state.saving()}- class="inline-flex min-h-9 items-center rounded-md px-3 py-1.5 text-sm bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 hover:bg-blue-200 dark:hover:bg-blue-800 disabled:opacity-50 whitespace-nowrap"+ onClick={() =>+ state.patrolModelReadinessRunning()+ ? state.cancelPatrolModelReadinessAdvisor()+ : void state.runPatrolModelReadinessAdvisor()+ }+ disabled={state.saving()}+ class={`inline-flex min-h-9 items-center rounded-md px-3 py-1.5 text-sm disabled:opacity-50 whitespace-nowrap ${+ state.patrolModelReadinessRunning()+ ? 'bg-amber-100 dark:bg-amber-900 text-amber-700 dark:text-amber-300 hover:bg-amber-200 dark:hover:bg-amber-800'+ : 'bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 hover:bg-blue-200 dark:hover:bg-blue-800'+ }`}>- {state.patrolPreflightRunning() ? 'Checking...' : 'Check Patrol model'}+ {state.patrolModelReadinessRunning() ? 'Cancel check' : 'Check Patrol model'}</button></div>+ <Show when={state.patrolModelReadinessRunning()}>+ <p class="text-[11px] text-muted" role="status">+ Running synthetic streaming scenarios. Pulse will not call infrastructure tools.+ </p>+ </Show><Show when={result()}>{(r) => (<div class={`rounded border px-3 py-2 ${toneClasses()}`}>@@ -177,9 +242,62 @@ export const PatrolPreflightControl: Component<{ state: AISettingsState }> = (co<Show when={detail()}><p class="text-[11px] mt-1 opacity-90">{detail()}</p></Show>+ <div class="mt-2 grid gap-1 sm:grid-cols-2">+ <For each={dimensionRows()}>+ {(dimension) => (+ <div class="rounded bg-white/40 px-2 py-1 dark:bg-black/10">+ <div class="flex items-center justify-between gap-2">+ <span class="text-[11px]">{dimension.label}</span>+ <span+ class={`text-[11px] font-medium ${readinessStatusTextClass(dimension.value.status)}`}+ >+ {dimension.value.attempts+ ? `${dimension.value.passed ?? 0}/${dimension.value.attempts} · `+ : ''}+ {statusLabel(dimension.value.status)}+ </span>+ </div>+ <p class="mt-0.5 text-[10px] opacity-75">{dimension.value.summary}</p>+ </div>+ )}+ </For>+ </div>+ <div class="mt-2 border-t border-current/15 pt-2">+ <p class="text-[11px] font-medium mb-1">Autonomy suitability</p>+ <div class="grid gap-1 sm:grid-cols-2">+ <For each={modeRows()}>+ {(mode) => (+ <div>+ <div class="flex items-center justify-between gap-2">+ <span class="text-[11px]">{mode.label}</span>+ <span+ class={`text-[11px] font-medium ${readinessStatusTextClass(mode.value.status)}`}+ >+ {modeStatusLabel(mode.value.status)}+ </span>+ </div>+ <p class="text-[10px] opacity-75">{mode.value.summary}</p>+ </div>+ )}+ </For>+ </div>+ </div><Show when={r().recommendation}><p class="text-[11px] mt-1 opacity-90">{r().recommendation}</p></Show>+ <Show when={r().metadata?.context_window || r().metadata?.quantization_level}>+ <p class="text-[11px] mt-1 opacity-70">+ <Show when={r().metadata?.context_window}>+ Context {r().metadata?.context_window?.toLocaleString()} tokens+ </Show>+ <Show when={r().metadata?.context_window && r().metadata?.quantization_level}>+ {' · '}+ </Show>+ <Show when={r().metadata?.quantization_level}>+ {r().metadata?.quantization_level}+ </Show>+ </p>+ </Show><Show when={r().provider || r().model || r().recorded_at_unix}><p class="text-[11px] mt-1 opacity-70">{r().provider}@@ -187,7 +305,7 @@ export const PatrolPreflightControl: Component<{ state: AISettingsState }> = (co{r().model}<Show when={r().recorded_at_unix}>{(r().provider || r().model ? ' · ' : '') +- 'last verified ' ++ 'last evaluated ' +formatRecordedAt(r().recorded_at_unix)}</Show></p>@@ -202,7 +320,7 @@ export const PatrolPreflightControl: Component<{ state: AISettingsState }> = (coexport const AIModelOverrideField: Component<{state: AISettingsState;kind: AIModelOverrideKind;- includePatrolPreflight?: boolean;+ includePatrolReadiness?: boolean;}> = (props) => {const { state } = props;const config = () => MODEL_OVERRIDE_CONFIG[props.kind];@@ -303,8 +421,8 @@ export const AIModelOverrideField: Component<{to be configured. Add an API key on Provider & Models or select a different model.</p></Show>- <Show when={props.includePatrolPreflight}>- <PatrolPreflightControl state={state} />+ <Show when={props.includePatrolReadiness}>+ <PatrolModelReadinessControl state={state} /></Show></div>);diff --git a/frontend-modern/src/components/Settings/AISettings.tsx b/frontend-modern/src/components/Settings/AISettings.tsxindex de7e5ee56f..d95f948bcd 100644--- a/frontend-modern/src/components/Settings/AISettings.tsx+++ b/frontend-modern/src/components/Settings/AISettings.tsx@@ -297,7 +297,7 @@ const PatrolSettingsContent: Component<{ state: ReturnType<typeof useAISettingsS<div class="space-y-3"><h3 class="text-sm font-semibold text-base-content">Model readiness</h3>- <AIModelOverrideField state={props.state} kind="patrol" includePatrolPreflight />+ <AIModelOverrideField state={props.state} kind="patrol" includePatrolReadiness /></div></div>);diff --git a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsxindex 23db35c08c..862b23ddab 100644--- a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx@@ -19,6 +19,7 @@ const getModelsMock = vi.fn();const testProviderMock = vi.fn();const testConnectionMock = vi.fn();const runDiscoveryRefreshMock = vi.fn();+const runPatrolModelReadinessMock = vi.fn();const fetchAgentCapabilitiesManifestMock = vi.fn();const listSessionsMock = vi.fn();const summarizeSessionMock = vi.fn();@@ -56,6 +57,10 @@ vi.mock('@/api/discovery', () => ({runDiscoveryRefresh: (...args: unknown[]) => runDiscoveryRefreshMock(...args),}));+vi.mock('@/api/patrol', () => ({+ runPatrolModelReadiness: (...args: unknown[]) => runPatrolModelReadinessMock(...args),+}));+vi.mock('@/api/agentCapabilities', async (importOriginal) => {const actual = await importOriginal<typeof import('@/api/agentCapabilities')>();return {@@ -151,6 +156,7 @@ const resetAllMocks = () => {testProviderMock.mockReset();testConnectionMock.mockReset();runDiscoveryRefreshMock.mockReset();+ runPatrolModelReadinessMock.mockReset();fetchAgentCapabilitiesManifestMock.mockReset();listSessionsMock.mockReset();summarizeSessionMock.mockReset();@@ -1089,6 +1095,89 @@ describe('AISettings provider save failure context', () => {expect(message).not.toContain('OpenRouter provider');expect(message).not.toContain('openrouter:deepseek/deepseek-r1');});++ it('renders dimensioned model readiness without certifying higher autonomy', async () => {+ getSettingsMock.mockResolvedValue({+ ...baseSettings(),+ enabled: true,+ configured: true,+ model: 'ollama:qwen3:8b',+ patrol_model: 'ollama:qwen3:8b',+ ollama_configured: true,+ configured_providers: ['ollama'],+ });+ runPatrolModelReadinessMock.mockResolvedValue({+ probe_version: 'patrol-readiness/v1',+ success: true,+ status: 'pass',+ provider: 'ollama',+ model: 'qwen3:8b',+ duration_ms: 9_100,+ max_verified_mode: 'monitor',+ summary: 'Verified for Watch only on this install.',+ recommendation: 'Keep higher autonomy disabled until an extended canary passes.',+ dimensions: {+ connectivity: { status: 'pass', summary: 'Connected.' },+ tool_protocol: { status: 'pass', summary: 'Passed.', attempts: 3, passed: 3 },+ context_quality: { status: 'pass', summary: 'Passed.', attempts: 2, passed: 2 },+ latency: { status: 'pass', summary: 'Passed.', warm_p50_ms: 1_000 },+ },+ modes: {+ monitor: { status: 'verified', summary: 'Verified.' },+ approval: { status: 'not_suitable', summary: 'Continuation failed.' },+ assisted: { status: 'not_assessed', summary: 'Extended canary required.' },+ full: { status: 'not_assessed', summary: 'Governed canary required.' },+ },+ metadata: { context_window: 32768, quantization_level: 'Q4_K_M' },+ recorded_at: '2026-07-13T08:00:00Z',+ recorded_at_unix: 1783929600,+ });++ renderComponent('patrol');+ const button = await screen.findByRole('button', { name: 'Check Patrol model' });+ fireEvent.click(button);++ expect(await screen.findByText('Verified for Watch only')).toBeInTheDocument();+ expect(screen.getByText('Tool protocol')).toBeInTheDocument();+ expect(screen.getByText('Context quality')).toBeInTheDocument();+ expect(screen.getByText('Autonomy suitability')).toBeInTheDocument();+ expect(screen.getByText('Safe auto-fix')).toBeInTheDocument();+ expect(screen.getByText('Autopilot')).toBeInTheDocument();+ expect(screen.getAllByText('Not assessed')).toHaveLength(2);+ expect(screen.getByText(/Context 32,768 tokens/)).toBeInTheDocument();+ expect(runPatrolModelReadinessMock).toHaveBeenCalledWith(+ { model: 'ollama:qwen3:8b' },+ expect.anything(),+ );+ });++ it('cancels an in-flight local model readiness evaluation', async () => {+ getSettingsMock.mockResolvedValue({+ ...baseSettings(),+ enabled: true,+ configured: true,+ model: 'ollama:qwen3:8b',+ patrol_model: 'ollama:qwen3:8b',+ ollama_configured: true,+ configured_providers: ['ollama'],+ });+ runPatrolModelReadinessMock.mockImplementation(+ (_body: unknown, signal: AbortSignal) =>+ new Promise((_resolve, reject) => {+ signal.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')));+ }),+ );++ renderComponent('patrol');+ fireEvent.click(await screen.findByRole('button', { name: 'Check Patrol model' }));+ const cancelButton = await screen.findByRole('button', { name: 'Cancel check' });+ fireEvent.click(cancelButton);++ await waitFor(() => {+ expect(notificationInfoMock).toHaveBeenCalledWith('Patrol model evaluation cancelled.');+ });+ expect(await screen.findByRole('button', { name: 'Check Patrol model' })).toBeInTheDocument();+ });});describe('AISettings provider setup flow', () => {diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.tsindex 1d570b8bce..ff9ab6c13a 100644--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts@@ -810,21 +810,16 @@ describe('settings architecture guardrails', () => {expect(aiSettingsDialogsSource).not.toContain('Session file changes');});- it('keeps Patrol tool-call preflight wired through the canonical settings state', () => {- // The Check Patrol model button must drive the canonical- // /api/ai/patrol/preflight endpoint via the typed runPatrolPreflight- // client and surface the result through state, not via inline fetch- // calls in the section component.- expect(aiSettingsStateSource).toContain('runPatrolPreflight');- expect(aiSettingsStateSource).toContain('runPatrolToolPreflight');- expect(aiSettingsStateSource).toContain('patrolPreflightResult');- expect(aiSettingsStateSource).toContain('patrolPreflightRunning');- expect(aiModelSelectionSectionSource).toContain('PatrolPreflightControl');- expect(aiModelSelectionSectionSource).toContain('runPatrolToolPreflight');- // The amber soft-warning tone is the operator's signal that the- // provider accepted the request but the model did not call the tool.- expect(aiModelSelectionSectionSource).toContain('model_tool_support_unverified');- expect(aiModelSelectionSectionSource).not.toContain("fetch('/api/ai/patrol/preflight");+ it('keeps the Patrol model readiness advisor wired through canonical settings state', () => {+ expect(aiSettingsStateSource).toContain('runPatrolModelReadiness');+ expect(aiSettingsStateSource).toContain('runPatrolModelReadinessAdvisor');+ expect(aiSettingsStateSource).toContain('patrolModelReadinessResult');+ expect(aiSettingsStateSource).toContain('patrolModelReadinessRunning');+ expect(aiSettingsStateSource).toContain('AbortController');+ expect(aiModelSelectionSectionSource).toContain('PatrolModelReadinessControl');+ expect(aiModelSelectionSectionSource).toContain('runPatrolModelReadinessAdvisor');+ expect(aiModelSelectionSectionSource).toContain('Autonomy suitability');+ expect(aiModelSelectionSectionSource).not.toContain("fetch('/api/ai/patrol/readiness");});it('keeps service context manual refresh on the canonical settings state', () => {@@ -851,27 +846,21 @@ describe('settings architecture guardrails', () => {expect(aiRuntimeControlsSectionSource).not.toContain("fetch('/api/discovery/run");});- it('hydrates the Patrol preflight panel from the cached settings snapshot', () => {- // The cached preflight outcome arrives on /api/settings/ai as- // patrol_preflight; loadSettings and updateSettings must project it- // back into the inline result panel so the "last verified" state- // survives page reloads without forcing a re-click.- expect(aiSettingsStateSource).toContain('hydratePatrolPreflightFromSettings');- expect(aiSettingsStateSource).toContain('patrol_preflight');- expect(aiSettingsStateSource).toContain('recorded_at_unix');+ it('hydrates the Patrol readiness advisor from the persisted settings snapshot', () => {+ expect(aiSettingsStateSource).toContain('hydratePatrolModelReadinessFromSettings');+ expect(aiSettingsStateSource).toContain('patrol_model_readiness');expect(aiModelSelectionSectionSource).toContain('formatRecordedAt');- expect(aiModelSelectionSectionSource).toContain('last verified');+ expect(aiModelSelectionSectionSource).toContain('last evaluated');});- it("passes the form's pending patrolModel to runPatrolPreflight so the model check tests the unsaved selection", () => {+ it("passes the form's pending patrolModel to the advisor so the model check tests the unsaved selection", () => {// Without this, clicking Check Patrol model after changing the model// dropdown silently tested the previously-saved model and the// operator would believe their pending selection was verified.expect(aiSettingsStateSource).toContain('form.patrolModel');expect(aiSettingsStateSource).toContain('pendingModel');- expect(aiSettingsStateSource).toContain(- 'runPatrolPreflight(pendingModel ? { model: pendingModel } : {})',- );+ expect(aiSettingsStateSource).toContain('runPatrolModelReadiness(');+ expect(aiSettingsStateSource).toContain('pendingModel ? { model: pendingModel } : {}');});it("flags the inline preflight panel as stale when the cached result is for a different model than the form's current selection", () => {@@ -882,7 +871,7 @@ describe('settings architecture guardrails', () => {expect(aiModelSelectionSectionSource).toContain('isStaleAgainstFormSelection');expect(aiModelSelectionSectionSource).toContain('pendingFormModel');expect(aiModelSelectionSectionSource).toContain('cachedResultModel');- expect(aiModelSelectionSectionSource).toContain('Verified result is for');+ expect(aiModelSelectionSectionSource).toContain('Evaluation result is for');expect(aiModelSelectionSectionSource).toContain('Click Check Patrol model to test the pending selection',);@@ -1130,7 +1119,7 @@ describe('settings architecture guardrails', () => {'<AIModelOverrideField state={props.state} kind="assistant" />',);expect(aiSettingsSource).toContain(- '<AIModelOverrideField state={props.state} kind="patrol" includePatrolPreflight />',+ '<AIModelOverrideField state={props.state} kind="patrol" includePatrolReadiness />',);expect(aiSettingsSource).toContain('<AIModelOverrideField state={props.state} kind="discovery" />',diff --git a/frontend-modern/src/components/Settings/useAISettingsState.ts b/frontend-modern/src/components/Settings/useAISettingsState.tsindex 54aabd6cdf..4d1da774f7 100644--- a/frontend-modern/src/components/Settings/useAISettingsState.ts+++ b/frontend-modern/src/components/Settings/useAISettingsState.ts@@ -1,9 +1,9 @@-import { createMemo, createSignal, onMount } from 'solid-js';+import { createMemo, createSignal, onCleanup, onMount } from 'solid-js';import { createStore } from 'solid-js/store';import { AIAPI } from '@/api/ai';import { AIChatAPI, type ChatSession } from '@/api/aiChat';import { runDiscoveryRefresh } from '@/api/discovery';-import { runPatrolPreflight, type PatrolPreflightResponse } from '@/api/patrol';+import { runPatrolModelReadiness, type PatrolModelReadinessResponse } from '@/api/patrol';import {AI_PROVIDERS,createInitialProviderHealth,@@ -260,36 +260,14 @@ export const useAISettingsState = (options: AISettingsStateOptions = {}) => {);const [preflightRunning, setPreflightRunning] = createSignal(false);const [preflightLastCheckedAt, setPreflightLastCheckedAt] = createSignal<number | null>(null);- const [patrolPreflightRunning, setPatrolPreflightRunning] = createSignal(false);- const [patrolPreflightResult, setPatrolPreflightResult] =- createSignal<PatrolPreflightResponse | null>(null);+ const [patrolModelReadinessRunning, setPatrolModelReadinessRunning] = createSignal(false);+ const [patrolModelReadinessResult, setPatrolModelReadinessResult] =+ createSignal<PatrolModelReadinessResponse | null>(null);+ let patrolModelReadinessAbortController: AbortController | null = null;const [discoveryRunRunning, setDiscoveryRunRunning] = createSignal(false);- // hydratePatrolPreflightFromSettings projects the cached preflight- // snapshot from /api/settings/ai into the same response shape the- // manual Check Patrol model button writes, so the inline result panel can- // render the most-recent outcome on page load without forcing a- // re-click. Returns null when preflight has never run on the- // current Pulse instance.- const hydratePatrolPreflightFromSettings = (data: AISettingsType | null) => {- const snapshot = data?.patrol_preflight;- if (!snapshot) {- setPatrolPreflightResult(null);- return;- }- setPatrolPreflightResult({- success: snapshot.success,- provider: snapshot.provider,- model: snapshot.model,- tool_call_observed: snapshot.tool_call_observed,- duration_ms: snapshot.duration_ms,- message: snapshot.title || snapshot.summary || '',- cause: snapshot.cause,- summary: snapshot.summary,- recommendation: snapshot.recommendation,- recorded_at: snapshot.recorded_at,- recorded_at_unix: snapshot.recorded_at_unix,- });+ const hydratePatrolModelReadinessFromSettings = (data: AISettingsType | null) => {+ setPatrolModelReadinessResult(data?.patrol_model_readiness ?? null);};const [showSetupModal, setShowSetupModal] = createSignal(false);@@ -698,38 +676,70 @@ export const useAISettingsState = (options: AISettingsStateOptions = {}) => {}};- // runPatrolToolPreflight verifies the configured Patrol provider+model- // can actually call tools end-to-end. Distinct from runProviderPreflight,- // which only confirms each provider's model catalog is reachable.- //- // Passes the form's pending patrolModel as a model override so clicking- // Check Patrol model after changing the dropdown actually tests the operator's- // pending selection, not whatever was previously saved. Empty form value- // means "use the shared default" — the backend handles the fallback.- const runPatrolToolPreflight = async () => {- setPatrolPreflightRunning(true);+ // Run the heavier advisor only on explicit operator action. It uses the+ // pending model selection, the same streaming transport as Patrol, and an+ // AbortSignal so slow local models can be cancelled without leaving a+ // provider request running in the backend.+ const runPatrolModelReadinessAdvisor = async () => {+ const controller = new AbortController();+ patrolModelReadinessAbortController?.abort();+ patrolModelReadinessAbortController = controller;+ setPatrolModelReadinessRunning(true);try {const pendingModel = form.patrolModel.trim();- const result = await runPatrolPreflight(pendingModel ? { model: pendingModel } : {});- setPatrolPreflightResult(result);+ const result = await runPatrolModelReadiness(+ pendingModel ? { model: pendingModel } : {},+ controller.signal,+ );+ setPatrolModelReadinessResult(result);} catch (error) {+ const errorName =+ typeof error === 'object' && error !== null && 'name' in error+ ? String(error.name)+ : '';+ if (errorName === 'AbortError') {+ notificationStore.info('Patrol model evaluation cancelled.');+ return;+ }const message =error instanceof Error && error.message? error.message- : 'Pulse could not run the Patrol tool-call preflight.';- setPatrolPreflightResult({+ : 'Pulse could not run the Patrol model readiness evaluation.';+ setPatrolModelReadinessResult({+ probe_version: 'patrol-readiness/v1',success: false,- tool_call_observed: false,+ status: 'fail',duration_ms: 0,- message,- summary:- 'Pulse could not reach the preflight endpoint. Check that the backend is running and you have settings-write permission.',+ summary: message,+ recommendation:+ 'Check that the backend is running and that you have settings-write permission, then retry.',+ dimensions: {+ connectivity: { status: 'fail', summary: message },+ tool_protocol: { status: 'not_assessed', summary: 'Not assessed.' },+ context_quality: { status: 'not_assessed', summary: 'Not assessed.' },+ latency: { status: 'not_assessed', summary: 'Not assessed.' },+ },+ modes: {+ monitor: { status: 'not_assessed', summary: 'Not assessed.' },+ approval: { status: 'not_assessed', summary: 'Not assessed.' },+ assisted: { status: 'not_assessed', summary: 'Extended verification required.' },+ full: { status: 'not_assessed', summary: 'Governed canary required.' },+ },+ recorded_at: new Date().toISOString(),+ recorded_at_unix: Math.floor(Date.now() / 1000),});} finally {- setPatrolPreflightRunning(false);+ if (patrolModelReadinessAbortController === controller) {+ patrolModelReadinessAbortController = null;+ setPatrolModelReadinessRunning(false);+ }}};+ const cancelPatrolModelReadinessAdvisor = () => {+ patrolModelReadinessAbortController?.abort();+ };+const loadSettings = async () => {setLoading(true);setLoadError(false);@@ -738,7 +748,7 @@ export const useAISettingsState = (options: AISettingsStateOptions = {}) => {setSettings(data);resetForm(data);syncModelCatalogForSettings(data);- hydratePatrolPreflightFromSettings(data);+ hydratePatrolModelReadinessFromSettings(data);void runProviderPreflight(data);} catch (error) {logger.error('[AISettings] Failed to load settings:', error);@@ -749,7 +759,7 @@ export const useAISettingsState = (options: AISettingsStateOptions = {}) => {setModelsError('');setProviderHealth(createInitialProviderHealth());setPreflightLastCheckedAt(null);- setPatrolPreflightResult(null);+ setPatrolModelReadinessResult(null);} finally {setLoading(false);}@@ -844,7 +854,7 @@ export const useAISettingsState = (options: AISettingsStateOptions = {}) => {setForm('enabled', true);resetForm(updated);syncModelCatalogForSettings(updated);- hydratePatrolPreflightFromSettings(updated);+ hydratePatrolModelReadinessFromSettings(updated);void runProviderPreflight(updated);handleCloseSetupModal();// First-time configuration is the moment of maximum intent:@@ -1100,7 +1110,7 @@ export const useAISettingsState = (options: AISettingsStateOptions = {}) => {setSettings(updated);resetForm(updated);syncModelCatalogForSettings(updated);- hydratePatrolPreflightFromSettings(updated);+ hydratePatrolModelReadinessFromSettings(updated);void runProviderPreflight(updated);void aiChatStore.refreshEnabledFromServer();const savedLabel = options.savedLabel ?? 'Provider & Models settings saved';@@ -1339,6 +1349,8 @@ export const useAISettingsState = (options: AISettingsStateOptions = {}) => {void loadSettings();});+ onCleanup(() => patrolModelReadinessAbortController?.abort());+return {alertAnalysisLocked,autoFixLocked,@@ -1368,8 +1380,8 @@ export const useAISettingsState = (options: AISettingsStateOptions = {}) => {loadSettings,modelsError,modelsLoading,- patrolPreflightResult,- patrolPreflightRunning,+ patrolModelReadinessResult,+ patrolModelReadinessRunning,preflightLastCheckedAt,preflightRunning,providerHealth,@@ -1377,7 +1389,8 @@ export const useAISettingsState = (options: AISettingsStateOptions = {}) => {providerTestResult,resetForm,runProviderPreflight,- runPatrolToolPreflight,+ runPatrolModelReadinessAdvisor,+ cancelPatrolModelReadinessAdvisor,saving,selectedChatSession,selectedSessionId,diff --git a/frontend-modern/src/types/ai.ts b/frontend-modern/src/types/ai.tsindex 4a01bd5410..5075eb405f 100644--- a/frontend-modern/src/types/ai.ts+++ b/frontend-modern/src/types/ai.ts@@ -140,6 +140,8 @@ export interface AISettings {// operators to re-run preflight on every page load. Absent when// preflight has never run on this Pulse instance.patrol_preflight?: PatrolPreflightSnapshot;+ // Most recent explicit multi-scenario Patrol model readiness evaluation.+ patrol_model_readiness?: PatrolModelReadinessSnapshot;}export interface PatrolPreflightSnapshot {@@ -156,6 +158,62 @@ export interface PatrolPreflightSnapshot {recorded_at_unix: number;}+export type PatrolModelReadinessStatus = 'pass' | 'warning' | 'fail' | 'not_assessed';+export type PatrolModeSuitabilityStatus = 'verified' | 'warning' | 'not_suitable' | 'not_assessed';++export interface PatrolModelReadinessDimension {+ status: PatrolModelReadinessStatus;+ summary: string;+ attempts?: number;+ passed?: number;+ duration_ms?: number;+ first_response_ms?: number;+ warm_p50_ms?: number;+ projected_watch_ms?: number;+ projected_approval_ms?: number;+ continuation_observed?: boolean;+}++export interface PatrolModeSuitability {+ status: PatrolModeSuitabilityStatus;+ summary: string;+}++export interface PatrolModelReadinessSnapshot {+ probe_version: string;+ success: boolean;+ status: PatrolModelReadinessStatus;+ provider?: string;+ model?: string;+ duration_ms: number;+ max_verified_mode?: 'monitor' | 'approval';+ cause?: string;+ summary: string;+ recommendation?: string;+ metadata?: {+ fingerprint?: string;+ family?: string;+ parameter_size?: string;+ quantization_level?: string;+ context_window?: number;+ capabilities?: string[];+ };+ dimensions: {+ connectivity: PatrolModelReadinessDimension;+ tool_protocol: PatrolModelReadinessDimension;+ context_quality: PatrolModelReadinessDimension;+ latency: PatrolModelReadinessDimension;+ };+ modes: {+ monitor: PatrolModeSuitability;+ approval: PatrolModeSuitability;+ assisted: PatrolModeSuitability;+ full: PatrolModeSuitability;+ };+ recorded_at: string;+ recorded_at_unix: number;+}+export interface AISettingsUpdateRequest {enabled?: boolean;model?: string;diff --git a/internal/ai/manual_ollama_preflight_test.go b/internal/ai/manual_ollama_preflight_test.goindex 04255a297b..7fe5734eef 100644--- a/internal/ai/manual_ollama_preflight_test.go+++ b/internal/ai/manual_ollama_preflight_test.go@@ -10,6 +10,12 @@ package ai// PULSE_MANUAL_OLLAMA_PREFLIGHT_MODEL=<candidate> \// go test ./internal/ai -run TestManualOllamaBlessedModelPreflight -v -count=1//+// Run the full dimensioned advisor before blessing a model:+//+// PULSE_MANUAL_OLLAMA_PREFLIGHT_URL=http://127.0.0.1:11434 \+// PULSE_MANUAL_OLLAMA_PREFLIGHT_MODEL=<candidate> \+// go test ./internal/ai -run TestManualOllamaPatrolModelReadiness -v -count=1+//// Run it several times: qwen3:4b passed connectivity but emitted a tool// call in 0 of 4 preflight runs, which is why only qwen3:8b is blessed.@@ -45,3 +51,47 @@ func TestManualOllamaBlessedModelPreflight(t *testing.T) {t.Fatalf("blessed model %q failed Patrol preflight: %+v", model, res)}}++func TestManualOllamaPatrolModelReadiness(t *testing.T) {+ base := os.Getenv("PULSE_MANUAL_OLLAMA_PREFLIGHT_URL")+ if base == "" {+ t.Skip("manual readiness advisor: set PULSE_MANUAL_OLLAMA_PREFLIGHT_URL")+ }+ model := os.Getenv("PULSE_MANUAL_OLLAMA_PREFLIGHT_MODEL")+ if model == "" {+ model = config.OllamaSuggestedPatrolModel+ }++ svc := NewService(nil, nil)+ svc.cfg = &config.AIConfig{+ Enabled: true,+ PatrolModel: config.AIProviderOllama + ":" + model,+ OllamaBaseURL: base,+ RequestTimeoutSeconds: 180,+ PatrolInvestigationBudget: config.DefaultPatrolInvestigationBudget,+ PatrolInvestigationTimeoutSec: config.DefaultPatrolInvestigationTimeoutSec,+ }++ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)+ defer cancel()+ result := svc.RunPatrolModelReadiness(ctx, config.AIProviderOllama, model)+ t.Logf("provider=%s model=%s success=%v status=%s maxMode=%s durationMs=%d cause=%q tool=%d/%d context=%d/%d continuation=%v warmP50Ms=%d summary=%q",+ result.Provider,+ result.Model,+ result.Success,+ result.Status,+ result.MaxVerifiedMode,+ result.DurationMs,+ result.Cause,+ result.Dimensions.ToolProtocol.Passed,+ result.Dimensions.ToolProtocol.Attempts,+ result.Dimensions.ContextQuality.Passed,+ result.Dimensions.ContextQuality.Attempts,+ result.Dimensions.ToolProtocol.ContinuationObserved,+ result.Dimensions.Latency.WarmP50Ms,+ result.Summary,+ )+ if !result.Success || result.MaxVerifiedMode == "" {+ t.Fatalf("candidate model %q failed Patrol readiness advisor: %+v", model, result)+ }+}diff --git a/internal/ai/patrol_model_readiness.go b/internal/ai/patrol_model_readiness.gonew file mode 100644index 0000000000..2c5f362f1f--- /dev/null+++ b/internal/ai/patrol_model_readiness.go@@ -0,0 +1,982 @@+package ai++import (+ "context"+ "crypto/rand"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "sync"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/ai/cost"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"+ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rs/zerolog/log"+)++const (+ PatrolModelReadinessProbeVersion = "patrol-readiness/v1"++ PatrolModelReadinessPass = "pass"+ PatrolModelReadinessWarning = "warning"+ PatrolModelReadinessFail = "fail"+ PatrolModelReadinessNotAssessed = "not_assessed"++ PatrolModeVerified = "verified"+ PatrolModeWarning = "warning"+ PatrolModeNotSuitable = "not_suitable"+ PatrolModeNotAssessed = "not_assessed"++ patrolModelReadinessCacheFilename = "ai_patrol_model_readiness.json"+ patrolReadinessObservationTool = "readiness_record_observation"+ patrolReadinessInventoryTool = "readiness_list_inventory"+ patrolReadinessChangeTool = "readiness_apply_change"+ patrolReadinessReceiptTool = "readiness_confirm_result"+ patrolReadinessMinimumContext = 8192+ patrolReadinessWatchEnvelope = 4 * time.Minute+)++// PatrolModelReadinessDimension is one independently reported piece of+// evidence. Readiness is deliberately not reduced to a single blended score:+// a fast model that emits malformed tools is still unsuitable for Patrol.+type PatrolModelReadinessDimension struct {+ Status string `json:"status"`+ Summary string `json:"summary"`+ Attempts int `json:"attempts,omitempty"`+ Passed int `json:"passed,omitempty"`+ DurationMs int64 `json:"duration_ms,omitempty"`+ FirstResponseMs int64 `json:"first_response_ms,omitempty"`+ WarmP50Ms int64 `json:"warm_p50_ms,omitempty"`+ ProjectedWatchMs int64 `json:"projected_watch_ms,omitempty"`+ ProjectedApprovalMs int64 `json:"projected_approval_ms,omitempty"`+ ContinuationObserved bool `json:"continuation_observed,omitempty"`+}++type PatrolModelReadinessDimensions struct {+ Connectivity PatrolModelReadinessDimension `json:"connectivity"`+ ToolProtocol PatrolModelReadinessDimension `json:"tool_protocol"`+ ContextQuality PatrolModelReadinessDimension `json:"context_quality"`+ Latency PatrolModelReadinessDimension `json:"latency"`+}++type PatrolModeSuitability struct {+ Status string `json:"status"`+ Summary string `json:"summary"`+}++type PatrolModelReadinessModes struct {+ Monitor PatrolModeSuitability `json:"monitor"`+ Approval PatrolModeSuitability `json:"approval"`+ Assisted PatrolModeSuitability `json:"assisted"`+ Full PatrolModeSuitability `json:"full"`+}++type PatrolModelReadinessMetadata struct {+ Fingerprint string `json:"fingerprint,omitempty"`+ Family string `json:"family,omitempty"`+ ParameterSize string `json:"parameter_size,omitempty"`+ QuantizationLevel string `json:"quantization_level,omitempty"`+ ContextWindow int `json:"context_window,omitempty"`+ Capabilities []string `json:"capabilities,omitempty"`+}++// PatrolModelReadinessResult is the versioned evidence produced by an+// operator-triggered advisor run. CacheKey is local-only invalidation state and+// is intentionally excluded from every API response.+type PatrolModelReadinessResult struct {+ ProbeVersion string `json:"probe_version"`+ Success bool `json:"success"`+ Status string `json:"status"`+ Provider string `json:"provider,omitempty"`+ Model string `json:"model,omitempty"`+ DurationMs int64 `json:"duration_ms"`+ MaxVerifiedMode string `json:"max_verified_mode,omitempty"`+ Cause PatrolFailureCause `json:"cause,omitempty"`+ Summary string `json:"summary"`+ Recommendation string `json:"recommendation,omitempty"`+ Metadata *PatrolModelReadinessMetadata `json:"metadata,omitempty"`+ Dimensions PatrolModelReadinessDimensions `json:"dimensions"`+ Modes PatrolModelReadinessModes `json:"modes"`+ CacheKey string `json:"-"`+ inputTokens int+ outputTokens int+ providerCalls int+}++type patrolModelReadinessCache struct {+ mu sync.RWMutex+ result *PatrolModelReadinessResult+ recordedAt time.Time+}++type persistedPatrolModelReadiness struct {+ Result PatrolModelReadinessResult `json:"result"`+ CacheKey string `json:"cache_key"`+ RecordedAt time.Time `json:"recorded_at"`+}++func emptyPatrolModelReadinessResult() PatrolModelReadinessResult {+ notAssessed := PatrolModelReadinessDimension{Status: PatrolModelReadinessNotAssessed, Summary: "Not assessed."}+ return PatrolModelReadinessResult{+ ProbeVersion: PatrolModelReadinessProbeVersion,+ Status: PatrolModelReadinessFail,+ Cause: PatrolFailureCauseNone,+ Dimensions: PatrolModelReadinessDimensions{+ Connectivity: notAssessed,+ ToolProtocol: notAssessed,+ ContextQuality: notAssessed,+ Latency: notAssessed,+ },+ Modes: PatrolModelReadinessModes{+ Monitor: PatrolModeSuitability{Status: PatrolModeNotAssessed, Summary: "Not assessed."},+ Approval: PatrolModeSuitability{Status: PatrolModeNotAssessed, Summary: "Not assessed."},+ Assisted: PatrolModeSuitability{Status: PatrolModeNotAssessed, Summary: "Requires an extended remediation and verification canary."},+ Full: PatrolModeSuitability{Status: PatrolModeNotAssessed, Summary: "Requires an extended governed Autopilot canary."},+ },+ }+}++func clonePatrolModelReadinessResult(result *PatrolModelReadinessResult) *PatrolModelReadinessResult {+ if result == nil {+ return nil+ }+ clone := *result+ if result.Metadata != nil {+ metadata := *result.Metadata+ metadata.Capabilities = append([]string(nil), result.Metadata.Capabilities...)+ clone.Metadata = &metadata+ }+ return &clone+}++// CachedPatrolModelReadiness returns the most recent result only when it still+// matches the current provider/model/transport configuration.+func (s *Service) CachedPatrolModelReadiness() (*PatrolModelReadinessResult, time.Time) {+ if s == nil {+ return nil, time.Time{}+ }+ s.patrolModelReadinessCache.mu.RLock()+ result := clonePatrolModelReadinessResult(s.patrolModelReadinessCache.result)+ recordedAt := s.patrolModelReadinessCache.recordedAt+ s.patrolModelReadinessCache.mu.RUnlock()+ if result == nil || recordedAt.IsZero() {+ return nil, time.Time{}+ }++ s.mu.RLock()+ cfg := s.cfg+ s.mu.RUnlock()+ if cfg == nil {+ return nil, time.Time{}+ }+ selectedProvider, selectedModel := config.ParseModelString(cfg.GetPatrolModel())+ if !strings.EqualFold(selectedProvider, result.Provider) || selectedModel != result.Model ||+ result.CacheKey != patrolModelReadinessCacheKey(cfg, result.Provider, result.Model) {+ return nil, time.Time{}+ }+ return result, recordedAt+}++func (s *Service) recordPatrolModelReadiness(result PatrolModelReadinessResult, at time.Time) {+ if s == nil {+ return+ }+ s.patrolModelReadinessCache.mu.Lock()+ if !s.patrolModelReadinessCache.recordedAt.IsZero() && at.Before(s.patrolModelReadinessCache.recordedAt) {+ s.patrolModelReadinessCache.mu.Unlock()+ return+ }+ s.patrolModelReadinessCache.result = clonePatrolModelReadinessResult(&result)+ s.patrolModelReadinessCache.recordedAt = at+ s.patrolModelReadinessCache.mu.Unlock()+ if err := s.persistPatrolModelReadiness(result, at); err != nil {+ log.Warn().Err(err).Msg("failed to persist Patrol model readiness evidence")+ }+}++// InvalidatePatrolModelReadiness removes evidence after a settings change that+// can alter provider transport or model behaviour.+func (s *Service) InvalidatePatrolModelReadiness() {+ if s == nil {+ return+ }+ s.patrolModelReadinessCache.mu.Lock()+ s.patrolModelReadinessCache.result = nil+ s.patrolModelReadinessCache.recordedAt = time.Time{}+ s.patrolModelReadinessCache.mu.Unlock()+ if path := s.patrolModelReadinessPath(); path != "" {+ if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {+ log.Warn().Err(err).Msg("failed to remove stale Patrol model readiness evidence")+ }+ }+}++func (s *Service) patrolModelReadinessPath() string {+ if s == nil || s.persistence == nil {+ return ""+ }+ return filepath.Join(s.persistence.DataDir(), patrolModelReadinessCacheFilename)+}++func (s *Service) persistPatrolModelReadiness(result PatrolModelReadinessResult, at time.Time) error {+ path := s.patrolModelReadinessPath()+ if path == "" {+ return nil+ }+ payload, err := json.MarshalIndent(persistedPatrolModelReadiness{+ Result: result,+ CacheKey: result.CacheKey,+ RecordedAt: at.UTC(),+ }, "", " ")+ if err != nil {+ return err+ }+ tmp := path + ".tmp"+ if err := os.WriteFile(tmp, payload, 0o600); err != nil {+ return err+ }+ if err := os.Rename(tmp, path); err != nil {+ _ = os.Remove(tmp)+ return err+ }+ return nil+}++func (s *Service) loadPatrolModelReadiness() {+ path := s.patrolModelReadinessPath()+ if path == "" {+ return+ }+ payload, err := os.ReadFile(path)+ if errors.Is(err, os.ErrNotExist) {+ return+ }+ if err != nil {+ log.Warn().Err(err).Msg("failed to read Patrol model readiness evidence")+ return+ }+ var persisted persistedPatrolModelReadiness+ if err := json.Unmarshal(payload, &persisted); err != nil {+ log.Warn().Err(err).Msg("ignored invalid Patrol model readiness evidence")+ return+ }+ if persisted.Result.ProbeVersion != PatrolModelReadinessProbeVersion || persisted.RecordedAt.IsZero() {+ return+ }+ persisted.Result.CacheKey = persisted.CacheKey+ s.patrolModelReadinessCache.result = clonePatrolModelReadinessResult(&persisted.Result)+ s.patrolModelReadinessCache.recordedAt = persisted.RecordedAt+}++func patrolModelReadinessCacheKey(cfg *config.AIConfig, providerName, model string) string {+ if cfg == nil {+ return ""+ }+ providerName = strings.ToLower(strings.TrimSpace(providerName))+ endpoint := ""+ switch providerName {+ case config.AIProviderOllama:+ endpoint = strings.TrimSpace(cfg.OllamaBaseURL)+ case config.AIProviderOpenAI:+ endpoint = strings.TrimSpace(cfg.OpenAIBaseURL)+ case config.AIProviderZai:+ endpoint = strings.TrimSpace(cfg.ZaiBaseURL)+ }+ credentialMaterial := cfg.GetAPIKeyForProvider(providerName)+ if providerName == config.AIProviderOllama {+ credentialMaterial = cfg.OllamaUsername + "\n" + cfg.OllamaPassword+ }+ credentialFingerprint := sha256.Sum256([]byte(credentialMaterial))+ material := fmt.Sprintf("%s\n%s\n%s\n%x\n%d\n%d\n%d",+ providerName,+ strings.TrimSpace(model),+ endpoint,+ credentialFingerprint,+ cfg.GetRequestTimeout().Milliseconds(),+ cfg.GetPatrolInvestigationBudget(),+ cfg.GetPatrolInvestigationTimeout().Milliseconds(),+ )+ sum := sha256.Sum256([]byte(material))+ return hex.EncodeToString(sum[:])+}++// RunPatrolModelReadiness evaluates the exact configured or overridden model+// through the streaming transport used by Patrol. It uses only synthetic+// fixtures and in-memory tool results; no infrastructure tools are executed.+func (s *Service) RunPatrolModelReadiness(ctx context.Context, providerName, model string) PatrolModelReadinessResult {+ started := time.Now()+ result := emptyPatrolModelReadinessResult()++ s.mu.RLock()+ cfg := s.cfg+ s.mu.RUnlock()+ finish := func() PatrolModelReadinessResult {+ result.DurationMs = time.Since(started).Milliseconds()+ if cfg != nil && result.Provider != "" && result.Model != "" {+ result.CacheKey = patrolModelReadinessCacheKey(cfg, result.Provider, result.Model)+ }+ // Cancellation is an operator action or request-budget boundary, not new+ // evidence about the model. Preserve the last completed evaluation.+ if ctx.Err() == nil {+ s.recordPatrolModelReadiness(result, time.Now())+ }+ s.recordPatrolModelReadinessUsage(result)+ return result+ }++ if cfg == nil {+ result.Cause = PatrolFailureCauseSettingsPersistence+ result.Summary = "Pulse Intelligence settings could not be loaded."+ result.Recommendation = "Confirm settings persistence is healthy, then run the advisor again."+ return finish()+ }+ if !cfg.Enabled {+ result.Cause = PatrolFailureCauseAssistantDisabled+ result.Summary = "Pulse Intelligence is turned off."+ result.Recommendation = "Turn on Pulse Intelligence, then run the advisor again."+ return finish()+ }++ modelString := strings.TrimSpace(model)+ if modelString == "" {+ modelString = strings.TrimSpace(cfg.GetPatrolModel())+ }+ if modelString == "" {+ result.Cause = PatrolFailureCauseModelNotSelected+ result.Summary = "No Patrol model is selected."+ result.Recommendation = "Select a Patrol model, then run the advisor again."+ return finish()+ }+ if overrideProvider := strings.TrimSpace(providerName); overrideProvider != "" {+ _, bare := config.ParseModelString(modelString)+ if bare == "" {+ bare = modelString+ }+ modelString = overrideProvider + ":" + bare+ }+ result.Provider, result.Model = config.ParseModelString(modelString)+ if err := ctx.Err(); err != nil {+ result.Cause = PatrolFailureCauseProviderConnection+ result.Summary = "The Patrol model readiness evaluation was cancelled."+ result.Recommendation = "Run the advisor again when you are ready."+ return finish()+ }++ if IsDemoMode() {+ result.Provider = DemoPatrolProvider+ result.Model = DemoPatrolModel+ result.Success = true+ result.Status = PatrolModelReadinessPass+ result.MaxVerifiedMode = config.PatrolAutonomyApproval+ result.Summary = "Demo mode simulated a successful Patrol readiness evaluation."+ result.Dimensions.Connectivity = PatrolModelReadinessDimension{Status: PatrolModelReadinessPass, Summary: "Demo provider available."}+ result.Dimensions.ToolProtocol = PatrolModelReadinessDimension{Status: PatrolModelReadinessPass, Summary: "Demo tool protocol simulated.", Attempts: 3, Passed: 3, ContinuationObserved: true}+ result.Dimensions.ContextQuality = PatrolModelReadinessDimension{Status: PatrolModelReadinessPass, Summary: "Demo context fixtures simulated.", Attempts: 2, Passed: 2}+ result.Dimensions.Latency = PatrolModelReadinessDimension{Status: PatrolModelReadinessPass, Summary: "Demo latency simulated."}+ result.Modes.Monitor = PatrolModeSuitability{Status: PatrolModeVerified, Summary: "Verified for Watch only in demo mode."}+ result.Modes.Approval = PatrolModeSuitability{Status: PatrolModeVerified, Summary: "Verified for Ask first in demo mode."}+ return finish()+ }+ if err := s.enforceBudget("patrol"); err != nil {+ result.Cause = PatrolFailureCauseProviderBilling+ result.Summary = "The configured Pulse Intelligence cost budget has been reached."+ result.Recommendation = "Raise the cost budget or wait for the rolling usage window to clear before running the advisor."+ return finish()+ }++ releaseSlot, err := s.acquireExecutionSlot(ctx, "patrol")+ if err != nil {+ failure := patrolRuntimeFailureFromError(err)+ result.Cause = failure.Cause+ result.Summary = "Patrol is already using the selected model."+ result.Recommendation = "Wait for the active Patrol work to finish, then run the advisor again."+ return finish()+ }+ defer releaseSlot()++ provider, err := providers.NewForModel(cfg, modelString)+ if err != nil {+ failure := patrolRuntimeFailureFromError(err)+ result.Cause = failure.Cause+ result.Summary = failure.Summary+ result.Recommendation = failure.Recommendation+ return finish()+ }+ result = runPatrolModelReadinessWithProvider(ctx, cfg, result.Provider, result.Model, modelString, provider)+ return finish()+}++type patrolReadinessScenario struct {+ name string+ prompt string+ nonce string+ resourceID string+ category string+ severity string+ evidenceToken string+ context bool+}++type patrolReadinessProbeOutcome struct {+ toolCalls []providers.ToolCall+ duration time.Duration+ firstResponse time.Duration+ inputTokens int+ outputTokens int+ completionEvent bool+}++func runPatrolModelReadinessWithProvider(ctx context.Context, cfg *config.AIConfig, providerName, model, modelString string, provider providers.Provider) PatrolModelReadinessResult {+ result := emptyPatrolModelReadinessResult()+ result.Provider = providerName+ result.Model = model+ started := time.Now()++ connectionStarted := time.Now()+ if err := provider.TestConnection(ctx); err != nil {+ failure := patrolRuntimeFailureFromError(err)+ result.Cause = failure.Cause+ result.Status = PatrolModelReadinessFail+ result.Summary = failure.Summary+ result.Recommendation = failure.Recommendation+ result.Dimensions.Connectivity = PatrolModelReadinessDimension{+ Status: PatrolModelReadinessFail,+ Summary: failure.Summary,+ DurationMs: time.Since(connectionStarted).Milliseconds(),+ }+ result.Modes.Monitor = PatrolModeSuitability{Status: PatrolModeNotSuitable, Summary: "The selected model is not reachable."}+ result.Modes.Approval = PatrolModeSuitability{Status: PatrolModeNotSuitable, Summary: "The selected model is not reachable."}+ result.DurationMs = time.Since(started).Milliseconds()+ return result+ }+ connectionSummary := "Provider and selected model are reachable."+ if diagnosticsProvider, ok := provider.(providers.ModelDiagnosticsProvider); ok {+ if diagnostics, err := diagnosticsProvider.InspectModel(ctx, model); err == nil && diagnostics != nil {+ result.Metadata = &PatrolModelReadinessMetadata{+ Fingerprint: diagnostics.Fingerprint,+ Family: diagnostics.Family,+ ParameterSize: diagnostics.ParameterSize,+ QuantizationLevel: diagnostics.QuantizationLevel,+ ContextWindow: diagnostics.ContextWindow,+ Capabilities: append([]string(nil), diagnostics.Capabilities...),+ }+ } else if err != nil {+ connectionSummary = "Provider and selected model are reachable; runtime model metadata was unavailable."+ }+ }+ result.Dimensions.Connectivity = PatrolModelReadinessDimension{+ Status: PatrolModelReadinessPass,+ Summary: connectionSummary,+ DurationMs: time.Since(connectionStarted).Milliseconds(),+ }++ streamingProvider, ok := provider.(providers.StreamingProvider)+ if !ok {+ result.Cause = PatrolFailureCauseModelUnsupportedTools+ result.Status = PatrolModelReadinessFail+ result.Summary = "The selected provider does not expose Patrol's streaming transport."+ result.Recommendation = "Choose a provider and model that support streaming tool calls."+ result.Dimensions.ToolProtocol = PatrolModelReadinessDimension{Status: PatrolModelReadinessFail, Summary: result.Summary}+ result.Modes.Monitor = PatrolModeSuitability{Status: PatrolModeNotSuitable, Summary: result.Summary}+ result.Modes.Approval = PatrolModeSuitability{Status: PatrolModeNotSuitable, Summary: result.Summary}+ result.DurationMs = time.Since(started).Milliseconds()+ return result+ }++ scenarios := patrolReadinessScenarios()+ tools := patrolReadinessTools()+ durations := make([]time.Duration, 0, len(scenarios)+1)+ firstResponses := make([]time.Duration, 0, len(scenarios)+1)+ toolPassed := 0+ contextPassed := 0+ var continuationSource patrolReadinessProbeOutcome+ var continuationScenario patrolReadinessScenario+ var probeErr error++ for _, scenario := range scenarios {+ req := providers.ChatRequest{+ Model: modelString,+ System: "You are running a synthetic Pulse Patrol readiness evaluation. " ++ "Use exactly one appropriate readiness tool. Never call readiness_apply_change. " ++ "Do not answer in prose. Copy identifiers and the nonce exactly from the fixture.",+ Messages: []providers.Message{{Role: "user", Content: scenario.prompt}},+ Tools: tools,+ MaxTokens: 256,+ Temperature: 0,+ }+ if providerName == config.AIProviderGemini {+ req.ToolChoice = &providers.ToolChoice{Type: providers.ToolChoiceRequired}+ }+ result.providerCalls+++ outcome, err := runPatrolReadinessStreamProbe(ctx, streamingProvider, req)+ result.inputTokens += outcome.inputTokens+ result.outputTokens += outcome.outputTokens+ if err != nil {+ probeErr = err+ break+ }+ durations = append(durations, outcome.duration)+ firstResponses = append(firstResponses, outcome.firstResponse)+ if validatePatrolReadinessProtocol(outcome.toolCalls, scenario.nonce) == nil {+ toolPassed+++ }+ if scenario.context && validatePatrolReadinessCall(outcome.toolCalls, scenario) == nil {+ contextPassed+++ }+ if scenario.name == "storage-pressure" {+ continuationSource = outcome+ continuationScenario = scenario+ }+ }++ continuationObserved := false+ if probeErr == nil && validatePatrolReadinessProtocol(continuationSource.toolCalls, continuationScenario.nonce) == nil {+ call := continuationSource.toolCalls[0]+ findingID := "synthetic-finding-" + continuationScenario.nonce+ toolResult, _ := json.Marshal(map[string]interface{}{+ "accepted": true,+ "finding_id": findingID,+ "nonce": continuationScenario.nonce,+ })+ followup := providers.ChatRequest{+ Model: modelString,+ System: "Continue the synthetic readiness evaluation. Call readiness_confirm_result exactly once " ++ "with the accepted tool result. Do not answer in prose.",+ Messages: []providers.Message{+ {Role: "user", Content: continuationScenario.prompt},+ {Role: "assistant", ToolCalls: []providers.ToolCall{call}},+ {Role: "user", ToolResult: &providers.ToolResult{ToolUseID: call.ID, Content: string(toolResult)}},+ },+ Tools: []providers.Tool{patrolReadinessReceiptDefinition()},+ MaxTokens: 128,+ Temperature: 0,+ }+ if providerName == config.AIProviderGemini {+ followup.ToolChoice = &providers.ToolChoice{Type: providers.ToolChoiceRequired}+ }+ result.providerCalls+++ outcome, err := runPatrolReadinessStreamProbe(ctx, streamingProvider, followup)+ result.inputTokens += outcome.inputTokens+ result.outputTokens += outcome.outputTokens+ if err != nil {+ probeErr = err+ } else {+ durations = append(durations, outcome.duration)+ firstResponses = append(firstResponses, outcome.firstResponse)+ continuationObserved = validatePatrolReadinessReceipt(outcome.toolCalls, continuationScenario.nonce, findingID) == nil+ }+ }++ toolDuration := sumDurations(durations)+ toolStatus := PatrolModelReadinessFail+ toolSummary := fmt.Sprintf("Exact tool protocol passed %d/%d scenarios.", toolPassed, len(scenarios))+ if toolPassed == len(scenarios) {+ toolStatus = PatrolModelReadinessPass+ if continuationObserved {+ toolSummary += " Multi-turn tool-result continuation also passed."+ } else {+ toolSummary += " Initial tool use passed, but multi-turn continuation was not verified."+ }+ }+ if probeErr != nil {+ failure := patrolRuntimeFailureFromError(probeErr)+ result.Cause = failure.Cause+ toolSummary = failure.Summary+ result.Recommendation = failure.Recommendation+ }+ result.Dimensions.ToolProtocol = PatrolModelReadinessDimension{+ Status: toolStatus,+ Summary: toolSummary,+ Attempts: len(scenarios),+ Passed: toolPassed,+ DurationMs: toolDuration.Milliseconds(),+ ContinuationObserved: continuationObserved,+ }++ contextStatus := PatrolModelReadinessFail+ contextSummary := fmt.Sprintf("Patrol-shaped context fixtures passed %d/2 scenarios.", contextPassed)+ if contextPassed == 2 {+ contextStatus = PatrolModelReadinessPass+ contextSummary = "Both Patrol-shaped fixtures selected the actionable resource without flagging healthy decoys."+ }+ if result.Metadata != nil && result.Metadata.ContextWindow > 0 && result.Metadata.ContextWindow < patrolReadinessMinimumContext {+ contextStatus = PatrolModelReadinessFail+ contextSummary = fmt.Sprintf("The runtime reports a %d-token context window; Patrol readiness requires at least %d tokens.", result.Metadata.ContextWindow, patrolReadinessMinimumContext)+ }+ result.Dimensions.ContextQuality = PatrolModelReadinessDimension{+ Status: contextStatus,+ Summary: contextSummary,+ Attempts: 2,+ Passed: contextPassed,+ }++ warmP50 := medianDuration(durations)+ if len(durations) > 1 {+ warmP50 = medianDuration(durations[1:])+ }+ firstResponse := medianDuration(firstResponses)+ projectedWatch := warmP50 * 8+ projectedApproval := warmP50 * time.Duration(cfg.GetPatrolInvestigationBudget())+ latencyStatus := PatrolModelReadinessPass+ latencySummary := fmt.Sprintf("Warm median %s; projected 8-turn Watch-only loop %s.", formatReadinessDuration(warmP50), formatReadinessDuration(projectedWatch))+ if len(durations) == 0 || probeErr != nil {+ latencyStatus = PatrolModelReadinessFail+ latencySummary = "Latency could not be measured because the streaming probe did not complete."+ } else if projectedWatch > patrolReadinessWatchEnvelope {+ latencyStatus = PatrolModelReadinessWarning+ latencySummary = fmt.Sprintf("Projected 8-turn Watch-only loop is %s, above the four-minute readiness envelope.", formatReadinessDuration(projectedWatch))+ }+ result.Dimensions.Latency = PatrolModelReadinessDimension{+ Status: latencyStatus,+ Summary: latencySummary,+ DurationMs: toolDuration.Milliseconds(),+ FirstResponseMs: firstResponse.Milliseconds(),+ WarmP50Ms: warmP50.Milliseconds(),+ ProjectedWatchMs: projectedWatch.Milliseconds(),+ ProjectedApprovalMs: projectedApproval.Milliseconds(),+ }++ watchVerified := toolStatus == PatrolModelReadinessPass && contextStatus == PatrolModelReadinessPass && latencyStatus == PatrolModelReadinessPass+ approvalVerified := watchVerified && continuationObserved && projectedApproval <= cfg.GetPatrolInvestigationTimeout()+ if watchVerified {+ result.Modes.Monitor = PatrolModeSuitability{Status: PatrolModeVerified, Summary: "Verified for Watch only on this provider, model, and runtime."}+ } else if latencyStatus == PatrolModelReadinessWarning {+ result.Modes.Monitor = PatrolModeSuitability{Status: PatrolModeWarning, Summary: "Core protocol passed, but projected Watch-only latency exceeds the readiness envelope."}+ } else {+ result.Modes.Monitor = PatrolModeSuitability{Status: PatrolModeNotSuitable, Summary: "The model did not pass the minimum Watch-only protocol and context checks."}+ }+ if approvalVerified {+ result.Modes.Approval = PatrolModeSuitability{Status: PatrolModeVerified, Summary: "Verified for Ask first, including multi-turn tool-result continuation."}+ } else if watchVerified {+ if !continuationObserved {+ result.Modes.Approval = PatrolModeSuitability{Status: PatrolModeNotSuitable, Summary: "Ask first requires a correct multi-turn tool-result continuation."}+ } else {+ result.Modes.Approval = PatrolModeSuitability{Status: PatrolModeWarning, Summary: "Projected investigation latency exceeds the configured investigation timeout."}+ }+ } else {+ result.Modes.Approval = PatrolModeSuitability{Status: PatrolModeNotSuitable, Summary: "Ask first requires all Watch-only checks to pass first."}+ }++ result.Success = watchVerified+ result.Status = PatrolModelReadinessFail+ result.Cause = PatrolFailureCauseModelToolSupportUnverified+ result.Summary = "The selected model did not pass Patrol's tool protocol evaluation."+ result.Recommendation = "Choose a model with reliable streaming tool use, or lower the model's workload and retry."+ if contextStatus == PatrolModelReadinessFail && toolStatus == PatrolModelReadinessPass {+ result.Cause = PatrolFailureCauseContextQualityFailed+ result.Summary = "The selected model did not pass Patrol's context-quality evaluation."+ result.Recommendation = "Choose a model with stronger context handling or a larger runtime context window."+ }+ if latencyStatus == PatrolModelReadinessWarning && toolStatus == PatrolModelReadinessPass && contextStatus == PatrolModelReadinessPass {+ result.Status = PatrolModelReadinessWarning+ result.Cause = PatrolFailureCauseLatencyUnsuitable+ result.Summary = "The selected model passed protocol and context checks but is too slow for the Watch-only readiness envelope."+ result.Recommendation = "Increase available local compute, reduce model size, or select a faster model."+ }+ if watchVerified {+ result.Status = PatrolModelReadinessPass+ result.Cause = PatrolFailureCauseNone+ result.MaxVerifiedMode = config.PatrolAutonomyMonitor+ result.Summary = "Verified for Watch only on this install."+ result.Recommendation = "Keep Safe auto-fix and Autopilot disabled until an extended governed canary has passed."+ if approvalVerified {+ result.MaxVerifiedMode = config.PatrolAutonomyApproval+ result.Summary = "Verified for Watch only and Ask first on this install."+ }+ }+ result.DurationMs = time.Since(started).Milliseconds()+ return result+}++func patrolReadinessScenarios() []patrolReadinessScenario {+ protocolNonce := newPatrolReadinessNonce()+ backupNonce := newPatrolReadinessNonce()+ storageNonce := newPatrolReadinessNonce()+ return []patrolReadinessScenario{+ {+ name: "typed-tool",+ nonce: protocolNonce,+ resourceID: "node-protocol",+ category: "reliability",+ severity: "warning",+ evidenceToken: "protocol-" + protocolNonce,+ prompt: fmt.Sprintf("Record exactly this synthetic observation: resource_id=node-protocol, category=reliability, severity=warning, evidence_token=protocol-%s, nonce=%s.", protocolNonce, protocolNonce),+ },+ newPatrolContextScenario("backup-failure", backupNonce, "pbs-lab-a", "backup", "critical", "backup-failed-201"),+ newPatrolContextScenario("storage-pressure", storageNonce, "storage-lab-b", "capacity", "warning", "storage-91-percent"),+ }+}++func newPatrolContextScenario(name, nonce, resourceID, category, severity, evidenceToken string) patrolReadinessScenario {+ var fixture strings.Builder+ fixture.Grow(32 * 1024)+ fixture.WriteString("Synthetic Patrol snapshot. Record the single actionable observation. Ignore healthy decoys. Evaluation nonce: ")+ fixture.WriteString(nonce)+ fixture.WriteString("\n")+ actionPosition := 47+ if name == "storage-pressure" {+ actionPosition = 233+ }+ for i := 0; i < 280; i++ {+ if i == actionPosition {+ if name == "backup-failure" {+ fmt.Fprintf(&fixture, "ACTIONABLE resource_id=%s type=pbs category=%s severity=%s last_job=failed evidence_token=%s\n", resourceID, category, severity, evidenceToken)+ } else {+ fmt.Fprintf(&fixture, "ACTIONABLE resource_id=%s type=storage category=%s severity=%s usage=91%% evidence_token=%s\n", resourceID, category, severity, evidenceToken)+ }+ }+ fmt.Fprintf(&fixture, "healthy-decoy-%03d type=vm status=running cpu=%d%% memory=%d%% backup=ok evidence=healthy-%03d\n", i, 10+i%30, 20+i%40, i)+ }+ return patrolReadinessScenario{+ name: name,+ prompt: fixture.String(),+ nonce: nonce,+ resourceID: resourceID,+ category: category,+ severity: severity,+ evidenceToken: evidenceToken,+ context: true,+ }+}++func patrolReadinessTools() []providers.Tool {+ return []providers.Tool{+ {+ Name: patrolReadinessObservationTool,+ Description: "Record the one actionable observation from a synthetic Patrol fixture.",+ InputSchema: map[string]interface{}{+ "type": "object",+ "properties": map[string]interface{}{+ "resource_id": map[string]interface{}{"type": "string"},+ "category": map[string]interface{}{"type": "string", "enum": []string{"reliability", "backup", "capacity"}},+ "severity": map[string]interface{}{"type": "string", "enum": []string{"warning", "critical"}},+ "evidence_token": map[string]interface{}{"type": "string"},+ "nonce": map[string]interface{}{"type": "string"},+ },+ "required": []string{"resource_id", "category", "severity", "evidence_token", "nonce"},+ "additionalProperties": false,+ },+ },+ {+ Name: patrolReadinessInventoryTool,+ Description: "List inventory only when the fixture contains no resource records. Readiness fixtures always contain records.",+ InputSchema: map[string]interface{}{"type": "object", "properties": map[string]interface{}{}, "additionalProperties": false},+ },+ {+ Name: patrolReadinessChangeTool,+ Description: "Synthetic change tool. Never call this during a readiness evaluation.",+ InputSchema: map[string]interface{}{+ "type": "object",+ "properties": map[string]interface{}{"nonce": map[string]interface{}{"type": "string"}},+ "required": []string{"nonce"},+ },+ },+ }+}++func patrolReadinessReceiptDefinition() providers.Tool {+ return providers.Tool{+ Name: patrolReadinessReceiptTool,+ Description: "Confirm the synthetic observation result returned by the readiness evaluator.",+ InputSchema: map[string]interface{}{+ "type": "object",+ "properties": map[string]interface{}{+ "accepted": map[string]interface{}{"type": "boolean"},+ "finding_id": map[string]interface{}{"type": "string"},+ "nonce": map[string]interface{}{"type": "string"},+ },+ "required": []string{"accepted", "finding_id", "nonce"},+ "additionalProperties": false,+ },+ }+}++func runPatrolReadinessStreamProbe(ctx context.Context, provider providers.StreamingProvider, req providers.ChatRequest) (patrolReadinessProbeOutcome, error) {+ started := time.Now()+ var outcome patrolReadinessProbeOutcome+ var starts []providers.ToolCall+ err := provider.ChatStream(ctx, req, func(event providers.StreamEvent) {+ if outcome.firstResponse == 0 {+ outcome.firstResponse = time.Since(started)+ }+ switch event.Type {+ case "tool_start":+ if data, ok := event.Data.(providers.ToolStartEvent); ok {+ starts = append(starts, providers.ToolCall{ID: data.ID, Name: data.Name, Input: data.Input})+ } else if data, ok := event.Data.(*providers.ToolStartEvent); ok && data != nil {+ starts = append(starts, providers.ToolCall{ID: data.ID, Name: data.Name, Input: data.Input})+ }+ case "done":+ if data, ok := event.Data.(providers.DoneEvent); ok {+ outcome.toolCalls = append([]providers.ToolCall(nil), data.ToolCalls...)+ outcome.inputTokens = data.InputTokens+ outcome.outputTokens = data.OutputTokens+ outcome.completionEvent = true+ } else if data, ok := event.Data.(*providers.DoneEvent); ok && data != nil {+ outcome.toolCalls = append([]providers.ToolCall(nil), data.ToolCalls...)+ outcome.inputTokens = data.InputTokens+ outcome.outputTokens = data.OutputTokens+ outcome.completionEvent = true+ }+ }+ })+ outcome.duration = time.Since(started)+ if err != nil {+ return outcome, err+ }+ if err := ctx.Err(); err != nil {+ return outcome, err+ }+ if !outcome.completionEvent {+ return outcome, fmt.Errorf("stream ended without a completion event")+ }+ if len(outcome.toolCalls) == 0 {+ outcome.toolCalls = starts+ }+ return outcome, nil+}++func validatePatrolReadinessCall(calls []providers.ToolCall, scenario patrolReadinessScenario) error {+ if err := validatePatrolReadinessProtocol(calls, scenario.nonce); err != nil {+ return err+ }+ call := calls[0]+ expected := map[string]string{+ "resource_id": scenario.resourceID,+ "category": scenario.category,+ "severity": scenario.severity,+ "evidence_token": scenario.evidenceToken,+ "nonce": scenario.nonce,+ }+ for key, value := range expected {+ actual, _ := call.Input[key].(string)+ if actual != value {+ return fmt.Errorf("argument %s did not match", key)+ }+ }+ return nil+}++func validatePatrolReadinessProtocol(calls []providers.ToolCall, nonce string) error {+ if len(calls) != 1 {+ return fmt.Errorf("expected exactly one tool call, got %d", len(calls))+ }+ call := calls[0]+ if call.Name != patrolReadinessObservationTool {+ return fmt.Errorf("expected tool %s, got %s", patrolReadinessObservationTool, call.Name)+ }+ if strings.TrimSpace(call.ID) == "" {+ return fmt.Errorf("tool call did not include an id for continuation")+ }+ required := []string{"resource_id", "category", "severity", "evidence_token", "nonce"}+ if len(call.Input) != len(required) {+ return fmt.Errorf("expected %d typed arguments, got %d", len(required), len(call.Input))+ }+ for _, key := range required {+ if _, ok := call.Input[key].(string); !ok {+ return fmt.Errorf("argument %s was not a string", key)+ }+ }+ if call.Input["nonce"] != nonce {+ return fmt.Errorf("nonce did not match")+ }+ category := call.Input["category"].(string)+ if category != "reliability" && category != "backup" && category != "capacity" {+ return fmt.Errorf("category was outside the tool schema")+ }+ severity := call.Input["severity"].(string)+ if severity != "warning" && severity != "critical" {+ return fmt.Errorf("severity was outside the tool schema")+ }+ return nil+}++func validatePatrolReadinessReceipt(calls []providers.ToolCall, nonce, findingID string) error {+ if len(calls) != 1 || calls[0].Name != patrolReadinessReceiptTool {+ return fmt.Errorf("expected exactly one %s call", patrolReadinessReceiptTool)+ }+ input := calls[0].Input+ if len(input) != 3 {+ return fmt.Errorf("unexpected receipt argument count")+ }+ accepted, ok := input["accepted"].(bool)+ if !ok || !accepted {+ return fmt.Errorf("receipt was not accepted")+ }+ receiptNonce, nonceOK := input["nonce"].(string)+ receiptFindingID, findingIDOK := input["finding_id"].(string)+ if !nonceOK || !findingIDOK || receiptNonce != nonce || receiptFindingID != findingID {+ return fmt.Errorf("receipt identifiers did not match")+ }+ return nil+}++func newPatrolReadinessNonce() string {+ buf := make([]byte, 8)+ if _, err := rand.Read(buf); err != nil {+ return fmt.Sprintf("%x", time.Now().UnixNano())+ }+ return hex.EncodeToString(buf)+}++func sumDurations(values []time.Duration) time.Duration {+ var total time.Duration+ for _, value := range values {+ total += value+ }+ return total+}++func medianDuration(values []time.Duration) time.Duration {+ if len(values) == 0 {+ return 0+ }+ ordered := append([]time.Duration(nil), values...)+ sort.Slice(ordered, func(i, j int) bool { return ordered[i] < ordered[j] })+ middle := len(ordered) / 2+ if len(ordered)%2 == 1 {+ return ordered[middle]+ }+ return (ordered[middle-1] + ordered[middle]) / 2+}++func formatReadinessDuration(value time.Duration) string {+ if value < time.Second {+ return fmt.Sprintf("%dms", value.Milliseconds())+ }+ return value.Round(100 * time.Millisecond).String()+}++func modelStringForReadinessResult(result PatrolModelReadinessResult) string {+ if result.Provider == "" {+ return result.Model+ }+ return config.FormatModelString(result.Provider, result.Model)+}++func (s *Service) recordPatrolModelReadinessUsage(result PatrolModelReadinessResult) {+ if s == nil || result.providerCalls == 0 {+ return+ }+ s.mu.RLock()+ costStore := s.costStore+ s.mu.RUnlock()+ if costStore == nil {+ return+ }+ costStore.Record(cost.UsageEvent{+ Timestamp: time.Now(),+ Provider: result.Provider,+ RequestModel: modelStringForReadinessResult(result),+ UseCase: "patrol_readiness",+ InputTokens: result.inputTokens,+ OutputTokens: result.outputTokens,+ })+}diff --git a/internal/ai/patrol_model_readiness_test.go b/internal/ai/patrol_model_readiness_test.gonew file mode 100644index 0000000000..4e49753af1--- /dev/null+++ b/internal/ai/patrol_model_readiness_test.go@@ -0,0 +1,341 @@+package ai++import (+ "context"+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "regexp"+ "strings"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"+ "github.com/rcourtman/pulse-go-rewrite/internal/config"+)++type scriptedReadinessProvider struct {+ connectionErr error+ wrongProtocol bool+ wrongContext bool+ skipContinuation bool+ waitForCancellation bool+ contextWindow int+ calls int+}++func (p *scriptedReadinessProvider) Chat(context.Context, providers.ChatRequest) (*providers.ChatResponse, error) {+ return nil, errors.New("readiness evaluator must use the streaming provider path")+}++func (p *scriptedReadinessProvider) TestConnection(context.Context) error { return p.connectionErr }+func (p *scriptedReadinessProvider) Name() string { return "scripted" }+func (p *scriptedReadinessProvider) ListModels(context.Context) ([]providers.ModelInfo, error) {+ return []providers.ModelInfo{{ID: "test-model"}}, nil+}+func (p *scriptedReadinessProvider) SupportsThinking(string) bool { return false }+func (p *scriptedReadinessProvider) InspectModel(context.Context, string) (*providers.ModelDiagnostics, error) {+ return &providers.ModelDiagnostics{+ Fingerprint: "sha256:test-model",+ Family: "test",+ ParameterSize: "8B",+ QuantizationLevel: "Q4_K_M",+ ContextWindow: p.contextWindow,+ Capabilities: []string{"completion", "tools"},+ }, nil+}++var readinessArgumentPattern = regexp.MustCompile(`(?m)(resource_id|category|severity|evidence_token|nonce)=([^,\s.]+)`)+var readinessNoncePattern = regexp.MustCompile(`Evaluation nonce: ([a-f0-9]+)`)++func readinessArgumentsFromPrompt(prompt string) map[string]interface{} {+ input := make(map[string]interface{})+ for _, match := range readinessArgumentPattern.FindAllStringSubmatch(prompt, -1) {+ input[match[1]] = match[2]+ }+ if _, ok := input["nonce"]; !ok {+ if match := readinessNoncePattern.FindStringSubmatch(prompt); len(match) == 2 {+ input["nonce"] = match[1]+ }+ }+ return input+}++func (p *scriptedReadinessProvider) ChatStream(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {+ p.calls+++ if p.waitForCancellation {+ <-ctx.Done()+ return ctx.Err()+ }++ last := req.Messages[len(req.Messages)-1]+ if last.ToolResult != nil {+ if p.skipContinuation {+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{StopReason: "end_turn", InputTokens: 100, OutputTokens: 10}})+ return nil+ }+ var result map[string]interface{}+ if err := json.Unmarshal([]byte(last.ToolResult.Content), &result); err != nil {+ return err+ }+ call := providers.ToolCall{+ ID: "receipt-call",+ Name: patrolReadinessReceiptTool,+ Input: map[string]interface{}{+ "accepted": true,+ "finding_id": result["finding_id"],+ "nonce": result["nonce"],+ },+ }+ callback(providers.StreamEvent{Type: "tool_start", Data: providers.ToolStartEvent{ID: call.ID, Name: call.Name, Input: call.Input}})+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{StopReason: "tool_use", ToolCalls: []providers.ToolCall{call}, InputTokens: 100, OutputTokens: 10}})+ return nil+ }++ input := readinessArgumentsFromPrompt(req.Messages[0].Content)+ if p.wrongContext && strings.Contains(req.Messages[0].Content, "ACTIONABLE") {+ input["resource_id"] = "healthy-decoy-001"+ }+ call := providers.ToolCall{ID: "observation-call", Name: patrolReadinessObservationTool, Input: input}+ if p.wrongProtocol {+ call.Name = patrolReadinessInventoryTool+ }+ callback(providers.StreamEvent{Type: "tool_start", Data: providers.ToolStartEvent{ID: call.ID, Name: call.Name, Input: call.Input}})+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{StopReason: "tool_use", ToolCalls: []providers.ToolCall{call}, InputTokens: 100, OutputTokens: 10}})+ return nil+}++func readinessTestConfig() *config.AIConfig {+ return &config.AIConfig{+ Enabled: true,+ Model: "ollama:test-model",+ PatrolModel: "ollama:test-model",+ OllamaBaseURL: "http://localhost:11434",+ RequestTimeoutSeconds: 300,+ PatrolInvestigationBudget: 15,+ PatrolInvestigationTimeoutSec: 600,+ }+}++func TestRunPatrolModelReadinessWithProvider_VerifiesMonitorAndApproval(t *testing.T) {+ provider := &scriptedReadinessProvider{contextWindow: 32768}+ result := runPatrolModelReadinessWithProvider(+ context.Background(), readinessTestConfig(), config.AIProviderOllama, "test-model", "ollama:test-model", provider,+ )++ if !result.Success || result.Status != PatrolModelReadinessPass {+ t.Fatalf("expected successful readiness evaluation, got %+v", result)+ }+ if result.MaxVerifiedMode != config.PatrolAutonomyApproval {+ t.Fatalf("max verified mode = %q, want approval", result.MaxVerifiedMode)+ }+ if result.Dimensions.ToolProtocol.Passed != 3 || result.Dimensions.ToolProtocol.Attempts != 3 {+ t.Fatalf("unexpected tool evidence: %+v", result.Dimensions.ToolProtocol)+ }+ if !result.Dimensions.ToolProtocol.ContinuationObserved {+ t.Fatal("expected multi-turn continuation to pass")+ }+ if result.Dimensions.ContextQuality.Passed != 2 {+ t.Fatalf("unexpected context evidence: %+v", result.Dimensions.ContextQuality)+ }+ if result.Modes.Assisted.Status != PatrolModeNotAssessed || result.Modes.Full.Status != PatrolModeNotAssessed {+ t.Fatalf("higher autonomy must remain unassessed: %+v", result.Modes)+ }+ if provider.calls != 4 {+ t.Fatalf("stream calls = %d, want 4", provider.calls)+ }+ if result.providerCalls != 4 || result.inputTokens != 400 || result.outputTokens != 40 {+ t.Fatalf("unexpected usage accounting: calls=%d input=%d output=%d", result.providerCalls, result.inputTokens, result.outputTokens)+ }+}++func TestPatrolReadinessContextFixturesDoNotPutEvidenceAtTheRecencyEdge(t *testing.T) {+ scenarios := patrolReadinessScenarios()+ for _, scenario := range scenarios {+ if !scenario.context {+ continue+ }+ action := strings.Index(scenario.prompt, "ACTIONABLE ")+ firstDecoy := strings.Index(scenario.prompt, "healthy-decoy-000")+ lastDecoy := strings.Index(scenario.prompt, "healthy-decoy-279")+ if action <= firstDecoy || action >= lastDecoy {+ t.Fatalf("scenario %q placed actionable evidence at a context edge", scenario.name)+ }+ }+}++func TestRunPatrolModelReadinessWithProvider_SeparatesProtocolFromContextQuality(t *testing.T) {+ provider := &scriptedReadinessProvider{contextWindow: 32768, wrongContext: true}+ result := runPatrolModelReadinessWithProvider(+ context.Background(), readinessTestConfig(), config.AIProviderOllama, "test-model", "ollama:test-model", provider,+ )++ if result.Dimensions.ToolProtocol.Status != PatrolModelReadinessPass || result.Dimensions.ToolProtocol.Passed != 3 {+ t.Fatalf("typed tool protocol should pass independently, got %+v", result.Dimensions.ToolProtocol)+ }+ if result.Dimensions.ContextQuality.Status != PatrolModelReadinessFail || result.Dimensions.ContextQuality.Passed != 0 {+ t.Fatalf("context quality should fail, got %+v", result.Dimensions.ContextQuality)+ }+ if result.Cause != PatrolFailureCauseContextQualityFailed || result.Success {+ t.Fatalf("expected context-quality failure, got %+v", result)+ }+}++func TestRunPatrolModelReadinessWithProvider_ProtocolFailureIsHardFailure(t *testing.T) {+ provider := &scriptedReadinessProvider{contextWindow: 32768, wrongProtocol: true}+ result := runPatrolModelReadinessWithProvider(+ context.Background(), readinessTestConfig(), config.AIProviderOllama, "test-model", "ollama:test-model", provider,+ )++ if result.Dimensions.ToolProtocol.Passed != 0 || result.Success {+ t.Fatalf("expected hard protocol failure, got %+v", result)+ }+ if result.Modes.Monitor.Status != PatrolModeNotSuitable {+ t.Fatalf("Watch only should be unsuitable, got %+v", result.Modes.Monitor)+ }+}++func TestRunPatrolModelReadinessWithProvider_ContinuationCapsAtMonitor(t *testing.T) {+ provider := &scriptedReadinessProvider{contextWindow: 32768, skipContinuation: true}+ result := runPatrolModelReadinessWithProvider(+ context.Background(), readinessTestConfig(), config.AIProviderOllama, "test-model", "ollama:test-model", provider,+ )++ if !result.Success || result.MaxVerifiedMode != config.PatrolAutonomyMonitor {+ t.Fatalf("expected Watch-only verification, got %+v", result)+ }+ if result.Modes.Approval.Status != PatrolModeNotSuitable {+ t.Fatalf("Ask first should require continuation, got %+v", result.Modes.Approval)+ }+}++func TestRunPatrolModelReadinessWithProvider_CancellationStopsStreamingProbe(t *testing.T) {+ provider := &scriptedReadinessProvider{contextWindow: 32768, waitForCancellation: true}+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ started := time.Now()+ result := runPatrolModelReadinessWithProvider(+ ctx, readinessTestConfig(), config.AIProviderOllama, "test-model", "ollama:test-model", provider,+ )+ if time.Since(started) > time.Second {+ t.Fatal("cancelled readiness evaluation did not stop promptly")+ }+ if result.Success || result.Dimensions.ToolProtocol.Status != PatrolModelReadinessFail {+ t.Fatalf("cancelled evaluation should not pass, got %+v", result)+ }+}++func TestPatrolModelReadinessCachePersistsAndInvalidates(t *testing.T) {+ persistence := config.NewConfigPersistence(t.TempDir())+ cfg := readinessTestConfig()+ first := NewService(persistence, nil)+ first.cfg = cfg+ result := emptyPatrolModelReadinessResult()+ result.Provider = config.AIProviderOllama+ result.Model = "test-model"+ result.Success = true+ result.Status = PatrolModelReadinessPass+ result.CacheKey = patrolModelReadinessCacheKey(cfg, result.Provider, result.Model)+ first.recordPatrolModelReadiness(result, time.Now())++ reloaded := NewService(persistence, nil)+ reloaded.cfg = cfg+ cached, recordedAt := reloaded.CachedPatrolModelReadiness()+ if cached == nil || recordedAt.IsZero() || !cached.Success {+ t.Fatalf("expected persisted readiness evidence, got result=%+v at=%v", cached, recordedAt)+ }+ cfg.PatrolModel = "ollama:another-model"+ if cached, _ := reloaded.CachedPatrolModelReadiness(); cached != nil {+ t.Fatalf("evidence for a different selected model must not be reused: %+v", cached)+ }+ cfg.PatrolModel = "ollama:test-model"+ cfg.OllamaPassword = "rotated-password"+ if cached, _ := reloaded.CachedPatrolModelReadiness(); cached != nil {+ t.Fatalf("evidence must be invalidated after provider credentials change: %+v", cached)+ }+ cfg.OllamaPassword = ""++ reloaded.InvalidatePatrolModelReadiness()+ if cached, _ := reloaded.CachedPatrolModelReadiness(); cached != nil {+ t.Fatalf("expected invalidated cache, got %+v", cached)+ }+ if _, err := os.Stat(filepath.Join(persistence.DataDir(), patrolModelReadinessCacheFilename)); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("expected persisted readiness file removed, got %v", err)+ }+}++func TestRunPatrolModelReadinessCancellationPreservesCompletedEvidence(t *testing.T) {+ cfg := readinessTestConfig()+ service := NewService(nil, nil)+ service.cfg = cfg+ completed := emptyPatrolModelReadinessResult()+ completed.Provider = config.AIProviderOllama+ completed.Model = "test-model"+ completed.Success = true+ completed.Status = PatrolModelReadinessPass+ completed.Summary = "completed evidence"+ completed.CacheKey = patrolModelReadinessCacheKey(cfg, completed.Provider, completed.Model)+ service.recordPatrolModelReadiness(completed, time.Now())++ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ result := service.RunPatrolModelReadiness(ctx, "", "")+ if result.Summary != "The Patrol model readiness evaluation was cancelled." {+ t.Fatalf("unexpected cancellation result: %+v", result)+ }+ cached, _ := service.CachedPatrolModelReadiness()+ if cached == nil || cached.Summary != completed.Summary {+ t.Fatalf("cancellation replaced completed evidence: %+v", cached)+ }+}++func TestPatrolModelReadinessUsageIsRecordedWithoutProbeContent(t *testing.T) {+ service := NewService(nil, nil)+ result := emptyPatrolModelReadinessResult()+ result.Provider = config.AIProviderOllama+ result.Model = "qwen3:8b"+ result.providerCalls = 4+ result.inputTokens = 1200+ result.outputTokens = 80+ service.recordPatrolModelReadinessUsage(result)++ events := service.ListCostEvents(1)+ if len(events) != 1 {+ t.Fatalf("usage event count = %d, want 1", len(events))+ }+ event := events[0]+ if event.UseCase != "patrol_readiness" || event.RequestModel != "ollama:qwen3:8b" || event.InputTokens != 1200 || event.OutputTokens != 80 {+ t.Fatalf("unexpected readiness usage event: %+v", event)+ }+ if event.TargetID != "" || event.FindingID != "" || event.SessionID != "" {+ t.Fatalf("synthetic readiness usage must not carry infrastructure or transcript identifiers: %+v", event)+ }+}++func TestPatrolRuntimeReadinessUsesAdvisorForSelectedAutonomyMode(t *testing.T) {+ cfg := readinessTestConfig()+ cfg.PatrolAutonomyLevel = config.PatrolAutonomyApproval+ service := &Service{cfg: cfg}+ result := emptyPatrolModelReadinessResult()+ result.Provider = config.AIProviderOllama+ result.Model = "test-model"+ result.Cause = PatrolFailureCauseModelToolSupportUnverified+ result.CacheKey = patrolModelReadinessCacheKey(cfg, result.Provider, result.Model)+ result.Modes.Monitor = PatrolModeSuitability{Status: PatrolModeVerified, Summary: "Watch only verified."}+ result.Modes.Approval = PatrolModeSuitability{Status: PatrolModeNotSuitable, Summary: "Continuation failed."}+ service.recordPatrolModelReadiness(result, time.Now())++ readiness := service.PatrolRuntimeReadiness()+ if readiness.Ready || readiness.Status != PatrolReadinessNotReady {+ t.Fatalf("selected Ask-first mode should be blocked by failed continuation: %+v", readiness)+ }++ cfg.PatrolAutonomyLevel = config.PatrolAutonomyAssisted+ result.CacheKey = patrolModelReadinessCacheKey(cfg, result.Provider, result.Model)+ service.recordPatrolModelReadiness(result, time.Now().Add(time.Millisecond))+ readiness = service.PatrolRuntimeReadiness()+ if !readiness.Ready || readiness.Status != PatrolReadinessWarning {+ t.Fatalf("unassessed higher autonomy should remain advisory in the MVP: %+v", readiness)+ }+}diff --git a/internal/ai/patrol_readiness.go b/internal/ai/patrol_readiness.goindex 2da87ba6ed..541bc89903 100644--- a/internal/ai/patrol_readiness.go+++ b/internal/ai/patrol_readiness.go@@ -30,6 +30,8 @@ const (PatrolFailureCauseMalformedToolHistory PatrolFailureCause = "malformed_tool_history"PatrolFailureCauseModelUnavailable PatrolFailureCause = "model_unavailable"PatrolFailureCauseContextWindowTooSmall PatrolFailureCause = "context_window_too_small"+ PatrolFailureCauseContextQualityFailed PatrolFailureCause = "context_quality_failed"+ PatrolFailureCauseLatencyUnsuitable PatrolFailureCause = "latency_unsuitable"PatrolFailureCauseProviderBilling PatrolFailureCause = "provider_billing"PatrolFailureCauseProviderRateLimited PatrolFailureCause = "provider_rate_limited"PatrolFailureCauseProviderAuth PatrolFailureCause = "provider_auth"@@ -170,5 +172,38 @@ func (s *Service) PatrolRuntimeReadiness() PatrolConfigReadiness {s.mu.RLock()cfg := s.cfgs.mu.RUnlock()- return EvaluatePatrolConfigReadiness(cfg)+ base := EvaluatePatrolConfigReadiness(cfg)+ if !base.Ready || cfg == nil {+ return base+ }+ advisor, _ := s.CachedPatrolModelReadiness()+ if advisor == nil {+ return base+ }++ selectedMode := cfg.GetPatrolAutonomyLevel()+ var suitability PatrolModeSuitability+ switch selectedMode {+ case config.PatrolAutonomyApproval:+ suitability = advisor.Modes.Approval+ case config.PatrolAutonomyAssisted:+ suitability = advisor.Modes.Assisted+ case config.PatrolAutonomyFull:+ suitability = advisor.Modes.Full+ default:+ suitability = advisor.Modes.Monitor+ }++ switch suitability.Status {+ case PatrolModeVerified:+ return patrolConfigReadiness(advisor.Provider, advisor.Model, PatrolReadinessReady, PatrolFailureCauseNone, suitability.Summary)+ case PatrolModeWarning, PatrolModeNotAssessed:+ return patrolConfigReadiness(advisor.Provider, advisor.Model, PatrolReadinessWarning, advisor.Cause, suitability.Summary)+ default:+ cause := advisor.Cause+ if cause == PatrolFailureCauseNone || cause == "" {+ cause = PatrolFailureCauseModelToolSupportUnverified+ }+ return patrolConfigReadiness(advisor.Provider, advisor.Model, PatrolReadinessNotReady, cause, suitability.Summary)+ }}diff --git a/internal/ai/providers/ollama.go b/internal/ai/providers/ollama.goindex df3019d299..c86345a09b 100644--- a/internal/ai/providers/ollama.go+++ b/internal/ai/providers/ollama.go@@ -3,10 +3,12 @@ package providersimport ("bytes""context"+ "crypto/sha256""encoding/json""fmt""io""net/http"+ "sort""strconv""strings""time"@@ -617,6 +619,92 @@ func (c *OllamaClient) TestConnection(ctx context.Context) error {return nil}+type ollamaShowResponse struct {+ ModifiedAt string `json:"modified_at"`+ Details ollamaShowDetails `json:"details"`+ ModelInfo map[string]interface{} `json:"model_info"`+ Capabilities []string `json:"capabilities"`+}++type ollamaShowDetails struct {+ Family string `json:"family"`+ ParameterSize string `json:"parameter_size"`+ QuantizationLevel string `json:"quantization_level"`+}++// InspectModel reads Ollama's local model metadata. This binds readiness+// evidence to a concrete model build and replaces the unsafe generic context+// assumption for local models. It deliberately does not treat a declared+// "tools" capability as proof; the readiness advisor still runs streaming,+// multi-turn tool probes.+func (c *OllamaClient) InspectModel(ctx context.Context, model string) (*ModelDiagnostics, error) {+ model = normalizeOllamaModelRef(model)+ if model == "" {+ model = normalizeOllamaModelRef(c.model)+ }+ if model == "" {+ return nil, fmt.Errorf("no model specified")+ }++ body, err := json.Marshal(map[string]string{"model": model})+ if err != nil {+ return nil, fmt.Errorf("marshal Ollama model inspection request: %w", err)+ }+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/api/show", bytes.NewReader(body))+ if err != nil {+ return nil, fmt.Errorf("create Ollama model inspection request: %w", err)+ }+ req.Header.Set("Content-Type", "application/json")+ c.applyAuth(req)++ resp, err := c.client.Do(req)+ if err != nil {+ return nil, fmt.Errorf("inspect Ollama model: %w", err)+ }+ defer resp.Body.Close()+ responseBody, err := io.ReadAll(io.LimitReader(resp.Body, 2<<20))+ if err != nil {+ return nil, fmt.Errorf("read Ollama model inspection response: %w", err)+ }+ if resp.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("Ollama model inspection failed (%d): %s", resp.StatusCode, strings.TrimSpace(string(responseBody)))+ }++ var inspected ollamaShowResponse+ if err := json.Unmarshal(responseBody, &inspected); err != nil {+ return nil, fmt.Errorf("parse Ollama model inspection response: %w", err)+ }+ contextWindow := 0+ for key, value := range inspected.ModelInfo {+ if !strings.HasSuffix(strings.ToLower(key), ".context_length") {+ continue+ }+ if n, ok := value.(float64); ok && int(n) > contextWindow {+ contextWindow = int(n)+ }+ }++ capabilities := append([]string(nil), inspected.Capabilities...)+ sort.Strings(capabilities)+ fingerprintPayload, _ := json.Marshal(struct {+ Model string `json:"model"`+ ModifiedAt string `json:"modified_at"`+ Details ollamaShowDetails `json:"details"`+ ModelInfo map[string]interface{} `json:"model_info"`+ Capabilities []string `json:"capabilities"`+ }{model, inspected.ModifiedAt, inspected.Details, inspected.ModelInfo, capabilities})+ fingerprint := sha256.Sum256(fingerprintPayload)++ return &ModelDiagnostics{+ Fingerprint: fmt.Sprintf("sha256:%x", fingerprint[:]),+ Family: inspected.Details.Family,+ ParameterSize: inspected.Details.ParameterSize,+ QuantizationLevel: inspected.Details.QuantizationLevel,+ ContextWindow: contextWindow,+ Capabilities: capabilities,+ }, nil+}+func normalizeOllamaModelRef(model string) string {model = strings.TrimSpace(model)if strings.HasPrefix(model, "ollama:") {diff --git a/internal/ai/providers/ollama_test.go b/internal/ai/providers/ollama_test.goindex 5d0beb08ff..2278f29a8b 100644--- a/internal/ai/providers/ollama_test.go+++ b/internal/ai/providers/ollama_test.go@@ -406,3 +406,36 @@ func TestOllamaClient_TestConnection_ModelUnavailable(t *testing.T) {require.Error(t, err)assert.Contains(t, err.Error(), `model "llama3" is not available`)}++func TestOllamaClient_InspectModel_ReturnsRuntimeDiagnostics(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ assert.Equal(t, "/api/show", r.URL.Path)+ assert.Equal(t, http.MethodPost, r.Method)+ var body map[string]string+ require.NoError(t, json.NewDecoder(r.Body).Decode(&body))+ assert.Equal(t, "qwen3:8b", body["model"])+ _ = json.NewEncoder(w).Encode(map[string]interface{}{+ "modified_at": "2026-07-13T08:00:00Z",+ "details": map[string]interface{}{+ "family": "qwen3",+ "parameter_size": "8.2B",+ "quantization_level": "Q4_K_M",+ },+ "model_info": map[string]interface{}{+ "qwen3.context_length": 32768,+ },+ "capabilities": []string{"completion", "tools"},+ })+ }))+ defer server.Close()++ client := newTestOllamaClient(t, "qwen3:8b", server.URL, "", "", 0)+ diagnostics, err := client.InspectModel(context.Background(), "ollama:qwen3:8b")+ require.NoError(t, err)+ require.NotNil(t, diagnostics)+ assert.Equal(t, "qwen3", diagnostics.Family)+ assert.Equal(t, "Q4_K_M", diagnostics.QuantizationLevel)+ assert.Equal(t, 32768, diagnostics.ContextWindow)+ assert.Equal(t, []string{"completion", "tools"}, diagnostics.Capabilities)+ assert.Contains(t, diagnostics.Fingerprint, "sha256:")+}diff --git a/internal/ai/providers/provider.go b/internal/ai/providers/provider.goindex d5e4307b9c..21c745783a 100644--- a/internal/ai/providers/provider.go+++ b/internal/ai/providers/provider.go@@ -150,6 +150,27 @@ type ModelInfo struct {Provider string `json:"provider,omitempty"`}+// ModelDiagnostics captures optional runtime-owned metadata for a concrete+// model. Providers that can inspect a locally installed model (currently+// Ollama) expose this in addition to the ordinary model catalogue so Patrol+// readiness can bind evidence to the model build that was actually tested.+// Capability metadata is advisory; callers must still exercise the real chat+// and tool-call transport before declaring the model ready.+type ModelDiagnostics struct {+ Fingerprint string `json:"fingerprint,omitempty"`+ Family string `json:"family,omitempty"`+ ParameterSize string `json:"parameter_size,omitempty"`+ QuantizationLevel string `json:"quantization_level,omitempty"`+ ContextWindow int `json:"context_window,omitempty"`+ Capabilities []string `json:"capabilities,omitempty"`+}++// ModelDiagnosticsProvider is implemented by providers that can inspect the+// exact installed model build without sending a chat completion.+type ModelDiagnosticsProvider interface {+ InspectModel(ctx context.Context, model string) (*ModelDiagnostics, error)+}+// Provider defines the interface for AI providerstype Provider interface {// Chat sends a chat request and returns the responsediff --git a/internal/ai/service.go b/internal/ai/service.goindex 5c9c89f7b3..4becf2fb7a 100644--- a/internal/ai/service.go+++ b/internal/ai/service.go@@ -274,6 +274,10 @@ type Service struct {// were last verified without re-running the call.patrolPreflightCache patrolPreflightCache+ // patrolModelReadinessCache holds the explicit, multi-scenario advisor+ // evidence separately from the lightweight startup preflight.+ patrolModelReadinessCache patrolModelReadinessCache+// License checker for Pro feature gatinglicenseChecker LicenseChecker}@@ -372,6 +376,8 @@ func NewService(persistence *config.ConfigPersistence, agentServer AgentServer)}}+ svc.loadPatrolModelReadiness()+return svc}diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.goindex e31ec36353..a2da74afe0 100644--- a/internal/api/ai_handlers.go+++ b/internal/api/ai_handlers.go@@ -2402,6 +2402,10 @@ type AISettingsResponse struct {// to re-click Verify Patrol on every page load. nil when preflight// has never run on this service instance.PatrolPreflight *PatrolPreflightSnapshot `json:"patrol_preflight,omitempty"`+ // Most recent explicit multi-scenario model readiness evaluation. This is+ // separate from the lightweight startup preflight and persists across+ // restarts while the provider/model configuration remains unchanged.+ PatrolModelReadiness *PatrolModelReadinessSnapshot `json:"patrol_model_readiness,omitempty"`}// AIProviderDefinitionResponse exposes provider metadata without credentials.@@ -2446,6 +2450,15 @@ type PatrolPreflightSnapshot struct {RecordedAtUnix int64 `json:"recorded_at_unix"`}+// PatrolModelReadinessSnapshot adds recording time to the versioned advisor+// result. The embedded result contains no credentials, endpoint URLs, prompts,+// or tool transcripts.+type PatrolModelReadinessSnapshot struct {+ *ai.PatrolModelReadinessResult+ RecordedAt string `json:"recorded_at"`+ RecordedAtUnix int64 `json:"recorded_at_unix"`+}+func EmptyAISettingsResponse() AISettingsResponse {return AISettingsResponse{}.NormalizeCollections()}@@ -2712,6 +2725,7 @@ func (h *AISettingsHandler) HandleGetAISettings(w http.ResponseWriter, r *http.RDiscoveryEnabled: settings.IsDiscoveryEnabled(),DiscoveryIntervalHours: settings.DiscoveryIntervalHours,PatrolPreflight: cachedPatrolPreflightSnapshot(aiService),+ PatrolModelReadiness: cachedPatrolModelReadinessSnapshot(aiService),PatrolReadiness: ptrToPatrolReadiness(h.buildPatrolReadiness(ctx, aiService, h.getPatrolService(ctx) != nil)),}.NormalizeCollections()@@ -3135,6 +3149,7 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *htt// poll via patrol_preflight. Routine saves that don't touch Patrol// transport skip this entirely so they don't burn provider tokens.if aiSettingsUpdateRequiresPatrolPreflight(&originalSettings, settings) {+ h.GetAIService(r.Context()).InvalidatePatrolModelReadiness()h.GetAIService(r.Context()).TriggerPatrolPreflightAsync("", "")}@@ -3229,6 +3244,7 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *httDiscoveryIntervalHours: settings.DiscoveryIntervalHours,PatrolReadiness: ptrToPatrolReadiness(patrolReadiness),PatrolPreflight: cachedPatrolPreflightSnapshot(aiService),+ PatrolModelReadiness: cachedPatrolModelReadinessSnapshot(aiService),}.NormalizeCollections()if err := utils.WriteJSONResponse(w, response); err != nil {@@ -3262,6 +3278,25 @@ func cachedPatrolPreflightSnapshot(aiService *ai.Service) *PatrolPreflightSnapsh}}+func patrolModelReadinessSnapshot(result *ai.PatrolModelReadinessResult, recordedAt time.Time) *PatrolModelReadinessSnapshot {+ if result == nil || recordedAt.IsZero() {+ return nil+ }+ return &PatrolModelReadinessSnapshot{+ PatrolModelReadinessResult: result,+ RecordedAt: recordedAt.UTC().Format(time.RFC3339),+ RecordedAtUnix: recordedAt.Unix(),+ }+}++func cachedPatrolModelReadinessSnapshot(aiService *ai.Service) *PatrolModelReadinessSnapshot {+ if aiService == nil {+ return nil+ }+ result, recordedAt := aiService.CachedPatrolModelReadiness()+ return patrolModelReadinessSnapshot(result, recordedAt)+}+// HandleTestAIConnection tests the AI provider connection (POST /api/ai/test)// Auth is enforced by RequirePermission middleware at route registration; with// default authorizer, non-admin proxy users are hard-denied (with RBAC, deferred@@ -5094,6 +5129,50 @@ func (h *AISettingsHandler) buildPatrolReadiness(ctx context.Context, aiServicetoolStatus, toolCause, toolMessage, toolAction := resolvePatrolToolsCheck(aiService, provider, model)addCheck("tools", toolStatus, toolCause, "Patrol tools", toolMessage, toolAction)+ if advisor, recordedAt := aiService.CachedPatrolModelReadiness(); advisor != nil && !recordedAt.IsZero() {+ _, bareModel := config.ParseModelString(model)+ if strings.EqualFold(advisor.Provider, provider) && advisor.Model == bareModel {+ contextStatus := patrolReadinessWarning+ contextCause := advisor.Cause+ contextAction := ""+ switch advisor.Dimensions.ContextQuality.Status {+ case ai.PatrolModelReadinessPass:+ contextStatus = patrolReadinessReady+ contextCause = ai.PatrolFailureCauseNone+ case ai.PatrolModelReadinessFail:+ contextStatus = patrolReadinessNotReady+ contextCause = ai.PatrolFailureCauseContextQualityFailed+ contextAction = "open_provider_settings"+ default:+ if contextCause == ai.PatrolFailureCauseNone || contextCause == "" {+ contextCause = ai.PatrolFailureCauseModelToolSupportUnverified+ }+ }+ addCheck("context_quality", contextStatus, contextCause, "Patrol context quality", advisor.Dimensions.ContextQuality.Summary, contextAction)++ latencyStatus := patrolReadinessWarning+ latencyCause := advisor.Cause+ latencyAction := ""+ switch advisor.Dimensions.Latency.Status {+ case ai.PatrolModelReadinessPass:+ latencyStatus = patrolReadinessReady+ latencyCause = ai.PatrolFailureCauseNone+ case ai.PatrolModelReadinessWarning:+ latencyStatus = patrolReadinessWarning+ latencyCause = ai.PatrolFailureCauseLatencyUnsuitable+ latencyAction = "open_provider_settings"+ case ai.PatrolModelReadinessFail:+ latencyStatus = patrolReadinessNotReady+ latencyCause = ai.PatrolFailureCauseLatencyUnsuitable+ latencyAction = "open_provider_settings"+ default:+ if latencyCause == ai.PatrolFailureCauseNone || latencyCause == "" {+ latencyCause = ai.PatrolFailureCauseModelToolSupportUnverified+ }+ }+ addCheck("latency", latencyStatus, latencyCause, "Patrol model latency", advisor.Dimensions.Latency.Summary, latencyAction)+ }+ }return summarizePatrolReadiness(provider, model, checks)}@@ -5116,6 +5195,22 @@ func resolvePatrolToolsCheck(aiService *ai.Service, provider, model string) (staif aiService == nil {return staticStatus, staticCause, staticMessage, staticAction}+ if advisor, recordedAt := aiService.CachedPatrolModelReadiness(); advisor != nil && !recordedAt.IsZero() {+ _, bareModel := config.ParseModelString(model)+ if strings.EqualFold(advisor.Provider, provider) && advisor.Model == bareModel {+ age := formatPatrolPreflightAge(time.Since(recordedAt))+ if advisor.Dimensions.ToolProtocol.Status == ai.PatrolModelReadinessPass {+ return patrolReadinessReady, ai.PatrolFailureCauseNone,+ fmt.Sprintf("Exact streaming tool protocol passed %d/%d scenarios %s.", advisor.Dimensions.ToolProtocol.Passed, advisor.Dimensions.ToolProtocol.Attempts, age), ""+ }+ cause := advisor.Cause+ if cause == ai.PatrolFailureCauseNone || cause == "" {+ cause = ai.PatrolFailureCauseModelToolSupportUnverified+ }+ return patrolReadinessNotReady, cause,+ fmt.Sprintf("%s (last readiness evaluation %s).", advisor.Dimensions.ToolProtocol.Summary, age), "open_provider_settings"+ }+ }cached, recordedAt := aiService.CachedPatrolPreflight()if cached == nil || recordedAt.IsZero() {return staticStatus, staticCause, staticMessage, staticAction@@ -5964,6 +6059,54 @@ func (h *AISettingsHandler) HandlePatrolPreflight(w http.ResponseWriter, r *http}}+// HandlePatrolModelReadiness runs the explicit, multi-scenario Patrol model+// advisor. Unlike the startup preflight, this uses Patrol's streaming+// transport, exact typed arguments, two context fixtures, and a multi-turn tool+// result. The request context makes the evaluation cancellable from the UI.+func (h *AISettingsHandler) HandlePatrolModelReadiness(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }+ if !ensureSettingsWriteScope(h.getConfig(r.Context()), w, r) {+ return+ }+ aiService := h.GetAIService(r.Context())+ if aiService == nil {+ writePatrolServiceUnavailableResponse(w)+ return+ }++ var body aiPatrolPreflightRequest+ if r.ContentLength > 0 {+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ http.Error(w, `{"error":"Invalid JSON body"}`, http.StatusBadRequest)+ return+ }+ }+ if body.Provider != "" {+ if len(body.Provider) > 64 || !isValidProviderName(body.Provider) {+ http.Error(w, `{"error":"Invalid provider name"}`, http.StatusBadRequest)+ return+ }+ }+ if len(body.Model) > 256 {+ http.Error(w, `{"error":"Model id too long"}`, http.StatusBadRequest)+ return+ }++ // An advisor run contains four streaming turns. Keep a firm total budget so+ // slow local hardware cannot pin an HTTP handler indefinitely; provider-level+ // request timeouts still apply inside this envelope.+ ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)+ defer cancel()+ result := aiService.RunPatrolModelReadiness(ctx, body.Provider, body.Model)+ response := patrolModelReadinessSnapshot(&result, time.Now())+ if err := utils.WriteJSONResponse(w, response); err != nil {+ log.Error().Err(err).Msg("Failed to write Patrol model readiness response")+ }+}+// HandleAcknowledgeFinding acknowledges a finding (POST /api/ai/patrol/acknowledge)// This marks the finding as seen but keeps it visible (dimmed). Auto-resolve removes it when condition clears.// This matches alert acknowledgement behavior for UI consistency.diff --git a/internal/api/ai_handlers_test.go b/internal/api/ai_handlers_test.goindex a1b69fe594..df90718c1c 100644--- a/internal/api/ai_handlers_test.go+++ b/internal/api/ai_handlers_test.go@@ -3535,6 +3535,57 @@ func TestAISettingsHandler_PatrolPreflight_DelegatesDeadlineToAIRuntime(t *testirequire.NotContains(t, body, "context.WithTimeout")}+func TestAISettingsHandler_PatrolModelReadiness_MethodNotAllowed(t *testing.T) {+ t.Parallel()++ tmp := t.TempDir()+ handler := newTestAISettingsHandler(&config.Config{DataPath: tmp}, config.NewConfigPersistence(tmp), nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/patrol/readiness", nil)+ rec := httptest.NewRecorder()+ handler.HandlePatrolModelReadiness(rec, req)++ assert.Equal(t, http.StatusMethodNotAllowed, rec.Code)+}++func TestAISettingsHandler_PatrolModelReadiness_AssistantDisabledReturnsDimensionedResult(t *testing.T) {+ t.Parallel()++ tmp := t.TempDir()+ persistence := config.NewConfigPersistence(tmp)+ aiCfg := config.NewDefaultAIConfig()+ aiCfg.Enabled = false+ require.NoError(t, persistence.SaveAIConfig(*aiCfg))+ handler := newTestAISettingsHandler(&config.Config{DataPath: tmp}, persistence, nil)++ req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/readiness", nil)+ rec := httptest.NewRecorder()+ handler.HandlePatrolModelReadiness(rec, req)+ require.Equal(t, http.StatusOK, rec.Code)++ var response PatrolModelReadinessSnapshot+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &response))+ require.NotNil(t, response.PatrolModelReadinessResult)+ assert.False(t, response.Success)+ assert.Equal(t, ai.PatrolModelReadinessProbeVersion, response.ProbeVersion)+ assert.Equal(t, ai.PatrolFailureCauseAssistantDisabled, response.Cause)+ assert.Equal(t, ai.PatrolModelReadinessNotAssessed, response.Dimensions.ToolProtocol.Status)+ assert.Equal(t, ai.PatrolModeNotAssessed, response.Modes.Assisted.Status)+ assert.NotZero(t, response.RecordedAtUnix)+}++func TestAISettingsHandler_PatrolModelReadiness_RejectsInvalidProviderName(t *testing.T) {+ t.Parallel()++ tmp := t.TempDir()+ handler := newTestAISettingsHandler(&config.Config{DataPath: tmp}, config.NewConfigPersistence(tmp), nil)+ req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/readiness",+ bytes.NewReader([]byte(`{"provider":"../etc/passwd"}`)))+ rec := httptest.NewRecorder()+ handler.HandlePatrolModelReadiness(rec, req)++ assert.Equal(t, http.StatusBadRequest, rec.Code)+}+// TestOrchestratorAndChatAdaptersMapTheSameMessageFields keeps the deliberate// GetMessages mirror between orchestratorChatAdapter (ai_handlers.go) and// chatServiceAdapter (chat_service_adapter.go) honest: both convert the samediff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.goindex 163445fbee..0b1547c3f4 100644--- a/internal/api/route_inventory_test.go+++ b/internal/api/route_inventory_test.go@@ -626,6 +626,7 @@ var allRouteAllowlist = []string{"/api/ai/patrol/history","/api/ai/patrol/run","/api/ai/patrol/preflight",+ "/api/ai/patrol/readiness","/api/ai/patrol/acknowledge","/api/ai/patrol/dismiss","/api/ai/patrol/findings/note",diff --git a/internal/api/router_routes_ai_relay.go b/internal/api/router_routes_ai_relay.goindex d621610341..e8f87cdbdb 100644--- a/internal/api/router_routes_ai_relay.go+++ b/internal/api/router_routes_ai_relay.go@@ -121,6 +121,10 @@ func (r *Router) registerAIRelayRoutesGroup() {// provider+model actually supports tool calling. Distinct from /api/ai/test// (which only lists models) so a green test cannot mask a 100%-failing Patrol.r.mux.HandleFunc("/api/ai/patrol/preflight", RequirePermission(r.config, r.authorizer, auth.ActionWrite, auth.ResourceSettings, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandlePatrolPreflight)))+ // Explicit multi-scenario model readiness advisor. Kept separate from the+ // lightweight preflight because it is operator-triggered and may take longer+ // on local hardware.+ r.mux.HandleFunc("/api/ai/patrol/readiness", RequirePermission(r.config, r.authorizer, auth.ActionWrite, auth.ResourceSettings, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandlePatrolModelReadiness)))// SECURITY: AI Patrol mutation endpoints - require ai:execute scope to prevent low-privilege tokens from// dismissing, suppressing, or otherwise hiding findings. This prevents attackers from blinding AI Patrol.r.mux.HandleFunc("/api/ai/patrol/acknowledge", RequireAuth(r.config, requireRelayMobileRuntimeRoute(diff --git a/scripts/release_control/ai_runtime_docs_policy_test.py b/scripts/release_control/ai_runtime_docs_policy_test.pyindex a743f77e1e..733a849177 100644--- a/scripts/release_control/ai_runtime_docs_policy_test.py+++ b/scripts/release_control/ai_runtime_docs_policy_test.py@@ -223,6 +223,20 @@ class AIRuntimeDocsPolicyTest(unittest.TestCase):self.assertIn("Maximum evidence-tool calls per investigation", normalized_control)self.assertIn("separate model-response safety ceiling", normalized_control)+ def test_public_ai_overview_describes_dimensioned_patrol_model_readiness(self) -> None:+ content = read_repo_text("docs/AI.md")+ normalized_content = " ".join(content.split())++ self.assertIn("### Patrol model readiness advisor", content)+ self.assertIn("synthetic data only and never calls infrastructure tools", normalized_content)+ self.assertIn("provider connectivity, exact typed streaming tool calls", normalized_content)+ self.assertIn("Patrol-shaped context fixtures", normalized_content)+ self.assertIn("projected loop latency", normalized_content)+ self.assertIn("never certifies **Safe auto-fix** or **Autopilot**", normalized_content)+ self.assertIn("without replacing the last completed evidence", normalized_content)+ self.assertIn("`patrol_readiness` usage category", normalized_content)+ self.assertNotIn("Patrol model ready", content)+def test_public_ai_docs_use_current_surface_naming(self) -> None:for doc_path in PUBLIC_AI_DOC_PATHS:with self.subTest(doc_path=doc_path):