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
Pin Patrol qualification routes per suite
rcourtmana717790e90a2
diff --git a/cmd/patrol-qualify/main.go b/cmd/patrol-qualify/main.goindex 9b5d0816e4..c555ef7a13 100644--- a/cmd/patrol-qualify/main.go+++ b/cmd/patrol-qualify/main.go@@ -6,6 +6,7 @@ package mainimport ("context""encoding/json"+ "errors""flag""fmt""os"@@ -27,7 +28,7 @@ func main() {username := flag.String("user", "admin", "Pulse API username")password := flag.String("password", "", "Pulse API password (prefer --password-env)")passwordEnv := flag.String("password-env", "PULSE_QUALIFY_PASSWORD", "environment variable containing the Pulse password")- model := flag.String("model", "", "optional Patrol model override, restored after every run")+ model := flag.String("model", "", "optional Patrol model override, pinned for and restored after the complete live suite")expectedPulseVersion := flag.String("expected-pulse-version", "", "optional exact /api/version identity required from the tested Pulse runtime")dockerContext := flag.String("docker-context", "", "explicit Docker context for disposable resources")dockerSSHHost := flag.String("docker-ssh-host", "", "explicit SSH host whose Docker daemon holds disposable resources")@@ -84,42 +85,16 @@ func main() {ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)defer stop()gitSHA, dirty := qualification.GitEnvironment(ctx, nil, ".")- failed := false- liveLoop:- for _, manifest := range manifests {- repeatCount, err := liveRepeatCount(manifest, *repeats, *repeatProfile)- if err != nil {- fatal(err)- }- if manifest.Track == qualification.TrackRemediation && manifest.Remediation != nil &&- manifest.Remediation.Decision != "observe" && !*authorizeRemediation {- fatal(fmt.Errorf("scenario %q requires the separate --authorize-remediation gate", manifest.ID))- }- for i := 0; i < repeatCount; i++ {- runner, err := qualification.NewRunner(qualification.RunnerConfig{- Manifest: manifest, Lab: lab, Client: client, ArtifactRoot: *artifactRoot,- ModelOverride: *model, GitSHA: gitSHA, GitDirty: dirty,- AuthorizeRemediation: *authorizeRemediation,- ExpectedPulseVersion: *expectedPulseVersion,- ChallengeNonce: *communityChallenge,- })- if err != nil {- fatal(err)- }- report, runErr := runner.Run(ctx)- verdict := "PASS"- if !report.Passed || runErr != nil {- verdict = "FAIL"- failed = true- }- fmt.Printf("[%s] %s scenario=%s model=%s recall=%.1f%% fp=%d artifacts=%s\n", verdict, report.RunID, manifest.ID, report.Environment.Model, report.Score.Recall*100, report.Score.FalsePositives, filepath.Join(*artifactRoot, report.RunID))- if runErr != nil {- fmt.Fprintf(os.Stderr, " error: %v\n", runErr)- }- if ctx.Err() != nil {- break liveLoop- }- }+ failed, err := runLiveQualification(ctx, liveQualificationConfig{+ Manifests: manifests, Client: client, Lab: lab,+ Model: *model, Repeats: *repeats, RepeatProfile: *repeatProfile,+ ArtifactRoot: *artifactRoot, GitSHA: gitSHA, GitDirty: dirty,+ AuthorizeRemediation: *authorizeRemediation,+ ExpectedPulseVersion: *expectedPulseVersion,+ ChallengeNonce: *communityChallenge,+ })+ if err != nil {+ fatal(err)}if failed {os.Exit(1)@@ -209,6 +184,85 @@ func main() {}}+type liveQualificationConfig struct {+ Manifests []qualification.Manifest+ Client *qualification.PulseClient+ Lab *qualification.DockerLab+ Model string+ Repeats int+ RepeatProfile string+ ArtifactRoot string+ GitSHA string+ GitDirty bool+ AuthorizeRemediation bool+ ExpectedPulseVersion string+ ChallengeNonce string+}++func runLiveQualification(ctx context.Context, config liveQualificationConfig) (failed bool, terminalErr error) {+ repeatCounts := make(map[string]int, len(config.Manifests))+ requiresRealModel := false+ for _, manifest := range config.Manifests {+ count, err := liveRepeatCount(manifest, config.Repeats, config.RepeatProfile)+ if err != nil {+ return false, err+ }+ repeatCounts[manifest.ID] = count+ requiresRealModel = requiresRealModel || manifest.Patrol.RequireRealModel+ if manifest.Track == qualification.TrackRemediation && manifest.Remediation != nil &&+ manifest.Remediation.Decision != "observe" && !config.AuthorizeRemediation {+ return false, fmt.Errorf("scenario %q requires the separate --authorize-remediation gate", manifest.ID)+ }+ }++ expectedModel := ""+ var lease *qualification.PatrolModelSuiteLease+ if requiresRealModel || strings.TrimSpace(config.Model) != "" {+ var err error+ lease, err = config.Client.AcquirePatrolModelSuite(ctx, config.Model, 45*time.Second, 250*time.Millisecond)+ if err != nil {+ return false, fmt.Errorf("establish Patrol qualification suite route: %w", err)+ }+ expectedModel = lease.Model+ defer func() {+ restoreCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ if err := lease.Close(restoreCtx); err != nil {+ terminalErr = errors.Join(terminalErr, fmt.Errorf("restore Patrol qualification suite route: %w", err))+ }+ }()+ }++ for _, manifest := range config.Manifests {+ for i := 0; i < repeatCounts[manifest.ID]; i++ {+ runner, err := qualification.NewRunner(qualification.RunnerConfig{+ Manifest: manifest, Lab: config.Lab, Client: config.Client, ArtifactRoot: config.ArtifactRoot,+ ExpectedModel: expectedModel, GitSHA: config.GitSHA, GitDirty: config.GitDirty,+ AuthorizeRemediation: config.AuthorizeRemediation,+ ExpectedPulseVersion: config.ExpectedPulseVersion,+ ChallengeNonce: config.ChallengeNonce,+ })+ if err != nil {+ return failed, err+ }+ report, runErr := runner.Run(ctx)+ verdict := "PASS"+ if !report.Passed || runErr != nil {+ verdict = "FAIL"+ failed = true+ }+ fmt.Printf("[%s] %s scenario=%s model=%s recall=%.1f%% fp=%d artifacts=%s\n", verdict, report.RunID, manifest.ID, report.Environment.Model, report.Score.Recall*100, report.Score.FalsePositives, filepath.Join(config.ArtifactRoot, report.RunID))+ if runErr != nil {+ fmt.Fprintf(os.Stderr, " error: %v\n", runErr)+ }+ if ctx.Err() != nil {+ return failed, ctx.Err()+ }+ }+ }+ return failed, nil+}+func selectLiveManifests(catalog qualification.Catalog, mode, scenarioID string, track qualification.Track) ([]qualification.Manifest, error) {switch strings.ToLower(strings.TrimSpace(mode)) {case "live":diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 65bb2d62be..bbcb05e09f 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -636,7 +636,14 @@ component-local required-scope list.Patrol model qualification extends only through`internal/ai/qualification/`, `cmd/patrol-qualify/`, and reviewed manifestsunder `tests/qualification/patrol/`. `live-suite` may sequence every manifest-for one explicit track, but it must retain the existing live-fault and separate+for one explicit track, but it must acquire and freshly preflight one exact+provider/model route before provisioning any scenario, retain that route for+every repetition, and restore it once after the complete suite. Scenario+runners assert the leased route and must not rewrite model settings or trigger+their own provider preflights. A fresh suite preflight failure aborts setup once+as qualification-infrastructure evidence; cached failure state must never be+recounted as multiple model or scenario failures without independent provider+invocations. `live-suite` must retain the existing live-fault and separateremediation authorization gates for every run. Voluntary community evidencemust be a local, mode-0600, allowlist-only derivation: it may carry aggregatescores, safety booleans, cost/latency, exact model/provider, scenario and@@ -3101,14 +3108,20 @@ Qualification floor: Patrol model launch and product-claim qualification must usmust never manufacture faults in production infrastructure.Patrol autonomous-loop floor: Watch must preserve model-owned investigation- while requiring an accepted structured outcome for every active finding the- run presents or returns. New issues use `patrol_report_finding`; existing+while requiring an accepted structured outcome for every active finding the+run presents or returns. New issues use `patrol_report_finding`; existingissues use `patrol_assess_finding` with exactly one `present`, `resolved`, or`uncertain` verdict. Missing verdicts are run errors, not absence-based- resolution or all-clear evidence. `present` refreshes durable evidence and- run ownership, `resolved` remains behind deterministic fail-closed- verification, and `uncertain` keeps the finding active. Scoped Patrol must- resolve canonical/source IDs and unique aliases before collection, reject+resolution or all-clear evidence. `present` refreshes durable evidence and+run ownership, `resolved` remains behind deterministic fail-closed+verification, and `uncertain` keeps the finding active. Scoped Patrol must+use its trigger as the initial clue rather than an artificial reasoning+boundary: within read-only authority the model may iteratively inspect related+canonical resources, relationships, metrics, timelines, changes, and other+governed evidence needed to test hypotheses. Governance constrains mutation+authority, data policy, and resource access; it must not add approval-shaped+friction to each safe investigative step. Scoped Patrol must still+resolve canonical/source IDs and unique aliases before collection, rejectambiguous or unmatched API identities synchronously, persist an error runfor runtime zero-match races, record requested and effective identities,and summarize only findings within the effective scope. Watch may mutatediff --git a/internal/ai/qualification/client.go b/internal/ai/qualification/client.goindex 2c38fe8884..34c5b00f7d 100644--- a/internal/ai/qualification/client.go+++ b/internal/ai/qualification/client.go@@ -11,6 +11,7 @@ import ("net/url""sort""strings"+ "sync""time""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"@@ -48,13 +49,63 @@ func NewPulseClient(config ClientConfig) (*PulseClient, error) {}type AISettings struct {- Enabled bool `json:"enabled"`- Model string `json:"model"`- PatrolModel string `json:"patrol_model"`- PatrolEnabled bool `json:"patrol_enabled"`- CodexSubscriptionEnabled bool `json:"codex_subscription_enabled"`- ClaudeSubscriptionEnabled bool `json:"claude_subscription_enabled"`- ZaiBaseURL string `json:"zai_base_url"`+ Enabled bool `json:"enabled"`+ Model string `json:"model"`+ PatrolModel string `json:"patrol_model"`+ PatrolEnabled bool `json:"patrol_enabled"`+ CodexSubscriptionEnabled bool `json:"codex_subscription_enabled"`+ ClaudeSubscriptionEnabled bool `json:"claude_subscription_enabled"`+ ZaiBaseURL string `json:"zai_base_url"`+ PatrolPreflight *PatrolPreflightSnapshot `json:"patrol_preflight,omitempty"`+}++type PatrolPreflightSnapshot struct {+ Success bool `json:"success"`+ Provider string `json:"provider"`+ Model string `json:"model"`+ ToolCallObserved bool `json:"tool_call_observed"`+ DurationMs int64 `json:"duration_ms"`+ Cause string `json:"cause"`+ Title string `json:"title"`+ Summary string `json:"summary"`+ Recommendation string `json:"recommendation"`+ RecordedAt string `json:"recorded_at"`+ RecordedAtUnix int64 `json:"recorded_at_unix"`+}++type PatrolPreflightResult struct {+ Success bool `json:"success"`+ Provider string `json:"provider"`+ Model string `json:"model"`+ ToolCallObserved bool `json:"tool_call_observed"`+ DurationMs int64 `json:"duration_ms"`+ Message string `json:"message"`+ Cause string `json:"cause"`+ Summary string `json:"summary"`+ Recommendation string `json:"recommendation"`+}++// PatrolModelSuiteLease pins one configured Patrol route for a complete live+// qualification suite. Individual scenario runners only observe and assert+// this route; they never rewrite settings or retrigger provider preflight.+type PatrolModelSuiteLease struct {+ Model string+ Preflight PatrolPreflightResult+ restore func(context.Context) error+ closeOnce sync.Once+ closeErr error+}++func (l *PatrolModelSuiteLease) Close(ctx context.Context) error {+ if l == nil {+ return nil+ }+ l.closeOnce.Do(func() {+ if l.restore != nil {+ l.closeErr = l.restore(ctx)+ }+ })+ return l.closeErr}type PulseVersion struct {@@ -266,17 +317,21 @@ func (c *PulseClient) OverridePatrolModel(ctx context.Context, model string) (fu}previous := settings.PatrolModelprovider, _ := splitModel(model)- payload := map[string]any{"patrol_model": model}- restorePayload := map[string]any{"patrol_model": previous}- if provider == "codex-subscription" {+ payload := make(map[string]any)+ restorePayload := make(map[string]any)+ if previous != model {+ payload["patrol_model"] = model+ restorePayload["patrol_model"] = previous+ }+ if provider == "codex-subscription" && !settings.CodexSubscriptionEnabled {payload["codex_subscription_enabled"] = truerestorePayload["codex_subscription_enabled"] = settings.CodexSubscriptionEnabled}- if provider == "claude-subscription" {+ if provider == "claude-subscription" && !settings.ClaudeSubscriptionEnabled {payload["claude_subscription_enabled"] = truerestorePayload["claude_subscription_enabled"] = settings.ClaudeSubscriptionEnabled}- if previous == model && len(payload) == 1 {+ if len(payload) == 0 {return func(context.Context) error { return nil }, nil}if err := c.request(ctx, http.MethodPut, "/api/settings/ai/update", payload, nil); err != nil {@@ -287,6 +342,163 @@ func (c *PulseClient) OverridePatrolModel(ctx context.Context, model string) (fu}, nil}+// AcquirePatrolModelSuite pins model for an entire live suite and obtains one+// fresh tool-call preflight result before any scenario is provisioned. A model+// change already triggers Pulse's asynchronous preflight, so acquisition waits+// for that exact new cache record instead of issuing a duplicate provider call.+// When the requested route is already configured, acquisition performs one+// synchronous preflight to ensure the suite never relies on stale cache state.+func (c *PulseClient) AcquirePatrolModelSuite(ctx context.Context, model string, timeout, poll time.Duration) (*PatrolModelSuiteLease, error) {+ if timeout <= 0 {+ timeout = 45 * time.Second+ }+ if poll <= 0 {+ poll = 250 * time.Millisecond+ }++ before, err := c.Settings(ctx)+ if err != nil {+ return nil, err+ }+ target := strings.TrimSpace(model)+ if target == "" {+ target = before.EffectivePatrolModel()+ }+ provider, bareModel := splitModel(target)+ if provider == "" || bareModel == "" {+ return nil, fmt.Errorf("Patrol qualification requires a concrete provider:model route, got %q", target)+ }++ routeChanged := before.EffectivePatrolModel() != target ||+ (provider == "codex-subscription" && !before.CodexSubscriptionEnabled) ||+ (provider == "claude-subscription" && !before.ClaudeSubscriptionEnabled)+ previousPreflightUnix := int64(0)+ previousPreflightWasTarget := false+ if before.PatrolPreflight != nil {+ previousPreflightUnix = before.PatrolPreflight.RecordedAtUnix+ previousPreflightWasTarget = strings.EqualFold(before.PatrolPreflight.Provider, provider) && before.PatrolPreflight.Model == bareModel+ }+ if routeChanged && previousPreflightWasTarget {+ freshnessDeadline := time.Now().Add(timeout)+ for time.Now().Unix() <= previousPreflightUnix {+ if time.Now().After(freshnessDeadline) {+ return nil, fmt.Errorf("Patrol qualification could not establish a fresh preflight clock boundary after %s", time.Unix(previousPreflightUnix, 0).UTC().Format(time.RFC3339))+ }+ select {+ case <-ctx.Done():+ return nil, ctx.Err()+ case <-time.After(50 * time.Millisecond):+ }+ }+ }++ restore, err := c.OverridePatrolModel(ctx, model)+ if err != nil {+ return nil, err+ }+ restoreOnError := func(acquireErr error) (*PatrolModelSuiteLease, error) {+ restoreCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ return nil, errors.Join(acquireErr, restore(restoreCtx))+ }++ var preflight PatrolPreflightResult+ if routeChanged {+ preflight, err = c.waitForPatrolPreflight(ctx, provider, bareModel, previousPreflightUnix, previousPreflightWasTarget, timeout, poll)+ } else {+ preflight, err = c.RunPatrolPreflight(ctx)+ }+ if err != nil {+ return restoreOnError(err)+ }+ if err := validatePatrolPreflight(target, preflight); err != nil {+ return restoreOnError(err)+ }++ settings, err := c.Settings(ctx)+ if err != nil {+ return restoreOnError(err)+ }+ status, err := c.Status(ctx)+ if err != nil {+ return restoreOnError(err)+ }+ if err := validatePatrolRoute(target, settings, status); err != nil {+ return restoreOnError(err)+ }++ return &PatrolModelSuiteLease{Model: target, Preflight: preflight, restore: restore}, nil+}++func (c *PulseClient) RunPatrolPreflight(ctx context.Context) (PatrolPreflightResult, error) {+ var result PatrolPreflightResult+ err := c.request(ctx, http.MethodPost, "/api/ai/patrol/preflight", map[string]any{}, &result)+ return result, err+}++func (c *PulseClient) waitForPatrolPreflight(ctx context.Context, provider, model string, afterUnix int64, requireNewer bool, timeout, poll time.Duration) (PatrolPreflightResult, error) {+ deadline := time.Now().Add(timeout)+ for {+ settings, err := c.Settings(ctx)+ if err == nil && settings.PatrolPreflight != nil {+ snapshot := settings.PatrolPreflight+ fresh := !requireNewer || snapshot.RecordedAtUnix > afterUnix+ if fresh && strings.EqualFold(snapshot.Provider, provider) && snapshot.Model == model {+ return PatrolPreflightResult{+ Success: snapshot.Success, Provider: snapshot.Provider, Model: snapshot.Model,+ ToolCallObserved: snapshot.ToolCallObserved, DurationMs: snapshot.DurationMs,+ Message: snapshot.Summary, Cause: snapshot.Cause, Summary: snapshot.Title,+ Recommendation: snapshot.Recommendation,+ }, nil+ }+ }+ if time.Now().After(deadline) {+ return PatrolPreflightResult{}, fmt.Errorf("Patrol qualification preflight did not publish fresh evidence for %s:%s before %s", provider, model, deadline.UTC().Format(time.RFC3339))+ }+ select {+ case <-ctx.Done():+ return PatrolPreflightResult{}, ctx.Err()+ case <-time.After(poll):+ }+ }+}++func validatePatrolPreflight(target string, result PatrolPreflightResult) error {+ provider, model := splitModel(target)+ if !strings.EqualFold(result.Provider, provider) || result.Model != model {+ return fmt.Errorf("Patrol qualification preflight resolved %s:%s, expected %s", result.Provider, result.Model, target)+ }+ if result.Success && result.ToolCallObserved {+ return nil+ }+ summary := strings.TrimSpace(result.Message)+ if summary == "" {+ summary = strings.TrimSpace(result.Summary)+ }+ if summary == "" {+ summary = "provider did not complete the tool-call preflight"+ }+ if cause := strings.TrimSpace(result.Cause); cause != "" {+ return fmt.Errorf("Patrol qualification preflight failed for %s (%s): %s", target, cause, summary)+ }+ return fmt.Errorf("Patrol qualification preflight failed for %s: %s", target, summary)+}++func validatePatrolRoute(expected string, settings AISettings, status PatrolStatus) error {+ expected = strings.TrimSpace(expected)+ if actual := settings.EffectivePatrolModel(); actual != expected {+ return fmt.Errorf("configured Patrol model %q does not match qualification suite route %q", actual, expected)+ }+ provider, model := splitModel(expected)+ if !strings.EqualFold(status.Readiness.Provider, provider) || status.Readiness.Model != expected && status.Readiness.Model != model {+ return fmt.Errorf("Patrol readiness resolved %s:%s, expected %s", status.Readiness.Provider, status.Readiness.Model, expected)+ }+ if !status.Readiness.Ready || strings.EqualFold(status.Readiness.Provider, "demo") {+ return fmt.Errorf("Patrol qualification suite route is not ready: %s", status.Readiness.Summary)+ }+ return nil+}+func (c *PulseClient) Resources(ctx context.Context) ([]Resource, error) {var response struct {Data []Resource `json:"data"`diff --git a/internal/ai/qualification/client_test.go b/internal/ai/qualification/client_test.goindex e05b433139..a949ea22ef 100644--- a/internal/ai/qualification/client_test.go+++ b/internal/ai/qualification/client_test.go@@ -7,6 +7,7 @@ import ("io""net/http""net/http/httptest"+ "strings""sync/atomic""testing""time"@@ -162,6 +163,219 @@ func TestOverridePatrolModelTemporarilyEnablesAndRestoresSubscriptionRoute(t *te}}+func TestAcquirePatrolModelSuitePinsOneRouteAndUsesFreshAsyncPreflight(t *testing.T) {+ currentModel := "ollama:qwen3:8b"+ codexEnabled := false+ preflight := map[string]any{+ "success": true, "provider": "ollama", "model": "qwen3:8b", "tool_call_observed": true,+ "summary": "old preflight", "recorded_at_unix": int64(100),+ }+ var updates []map[string]any+ preflightPosts := 0+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/api/settings/ai":+ _ = json.NewEncoder(w).Encode(map[string]any{+ "enabled": true, "model": "ollama:qwen3:8b", "patrol_model": currentModel,+ "patrol_enabled": true, "codex_subscription_enabled": codexEnabled,+ "patrol_preflight": preflight,+ })+ case r.Method == http.MethodPut && r.URL.Path == "/api/settings/ai/update":+ var body map[string]any+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Fatal(err)+ }+ updates = append(updates, body)+ if value, ok := body["patrol_model"].(string); ok {+ currentModel = value+ }+ if value, ok := body["codex_subscription_enabled"].(bool); ok {+ codexEnabled = value+ }+ if currentModel == "codex-subscription:gpt-5.6-sol" {+ preflight = map[string]any{+ "success": true, "provider": "codex-subscription", "model": "gpt-5.6-sol", "tool_call_observed": true,+ "summary": "tool calling verified", "recorded_at_unix": int64(200),+ }+ }+ _, _ = w.Write([]byte(`{}`))+ case r.Method == http.MethodPost && r.URL.Path == "/api/ai/patrol/preflight":+ preflightPosts+++ _, _ = w.Write([]byte(`{"success":true,"provider":"codex-subscription","model":"gpt-5.6-sol","tool_call_observed":true}`))+ case r.Method == http.MethodGet && r.URL.Path == "/api/ai/patrol/status":+ _ = json.NewEncoder(w).Encode(map[string]any{"readiness": map[string]any{+ "ready": true, "provider": "codex-subscription", "model": "codex-subscription:gpt-5.6-sol",+ }})+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()+ client, err := NewPulseClient(ClientConfig{BaseURL: server.URL})+ if err != nil {+ t.Fatal(err)+ }+ lease, err := client.AcquirePatrolModelSuite(context.Background(), "codex-subscription:gpt-5.6-sol", time.Second, time.Millisecond)+ if err != nil {+ t.Fatal(err)+ }+ if lease.Model != "codex-subscription:gpt-5.6-sol" || preflightPosts != 0 {+ t.Fatalf("lease = %+v, synchronous preflight posts = %d", lease, preflightPosts)+ }+ if len(updates) != 1 {+ t.Fatalf("route updates before close = %#v", updates)+ }+ if err := lease.Close(context.Background()); err != nil {+ t.Fatal(err)+ }+ if len(updates) != 2 || updates[1]["patrol_model"] != "ollama:qwen3:8b" || updates[1]["codex_subscription_enabled"] != false {+ t.Fatalf("route updates after close = %#v", updates)+ }+}++func TestAcquirePatrolModelSuitePreflightsConfiguredRouteOnceWithoutSettingsWrite(t *testing.T) {+ updates := 0+ preflightPosts := 0+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/api/settings/ai":+ _, _ = w.Write([]byte(`{"enabled":true,"model":"codex-subscription:gpt-5.6-sol","patrol_model":"codex-subscription:gpt-5.6-sol","patrol_enabled":true,"codex_subscription_enabled":true}`))+ case r.Method == http.MethodPut && r.URL.Path == "/api/settings/ai/update":+ updates+++ _, _ = w.Write([]byte(`{}`))+ case r.Method == http.MethodPost && r.URL.Path == "/api/ai/patrol/preflight":+ preflightPosts+++ _, _ = w.Write([]byte(`{"success":true,"provider":"codex-subscription","model":"gpt-5.6-sol","tool_call_observed":true,"message":"verified"}`))+ case r.Method == http.MethodGet && r.URL.Path == "/api/ai/patrol/status":+ _, _ = w.Write([]byte(`{"readiness":{"ready":true,"provider":"codex-subscription","model":"codex-subscription:gpt-5.6-sol"}}`))+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()+ client, err := NewPulseClient(ClientConfig{BaseURL: server.URL})+ if err != nil {+ t.Fatal(err)+ }+ lease, err := client.AcquirePatrolModelSuite(context.Background(), "", time.Second, time.Millisecond)+ if err != nil {+ t.Fatal(err)+ }+ if updates != 0 || preflightPosts != 1 {+ t.Fatalf("settings updates = %d, preflight posts = %d", updates, preflightPosts)+ }+ if err := lease.Close(context.Background()); err != nil {+ t.Fatal(err)+ }+ if updates != 0 {+ t.Fatalf("no-op lease close wrote settings %d time(s)", updates)+ }+}++func TestAcquirePatrolModelSuiteRequiresFreshEvidenceWhenEnablingSameSubscriptionRoute(t *testing.T) {+ codexEnabled := false+ preflightSuccess := false+ updates := 0+ oldRecordedAt := time.Now().Add(-time.Second).Unix()+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/api/settings/ai":+ _ = json.NewEncoder(w).Encode(map[string]any{+ "enabled": true, "model": "codex-subscription:gpt-5.6-sol", "patrol_model": "codex-subscription:gpt-5.6-sol",+ "patrol_enabled": true, "codex_subscription_enabled": codexEnabled,+ "patrol_preflight": map[string]any{+ "success": preflightSuccess, "provider": "codex-subscription", "model": "gpt-5.6-sol",+ "tool_call_observed": preflightSuccess, "summary": "fresh result",+ "recorded_at_unix": map[bool]int64{false: oldRecordedAt, true: time.Now().Unix()}[preflightSuccess],+ },+ })+ case r.Method == http.MethodPut && r.URL.Path == "/api/settings/ai/update":+ updates+++ var body map[string]any+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Fatal(err)+ }+ if value, ok := body["codex_subscription_enabled"].(bool); ok {+ codexEnabled = value+ preflightSuccess = value+ }+ _, _ = w.Write([]byte(`{}`))+ case r.Method == http.MethodGet && r.URL.Path == "/api/ai/patrol/status":+ _, _ = w.Write([]byte(`{"readiness":{"ready":true,"provider":"codex-subscription","model":"codex-subscription:gpt-5.6-sol"}}`))+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()+ client, err := NewPulseClient(ClientConfig{BaseURL: server.URL})+ if err != nil {+ t.Fatal(err)+ }+ lease, err := client.AcquirePatrolModelSuite(context.Background(), "codex-subscription:gpt-5.6-sol", time.Second, time.Millisecond)+ if err != nil {+ t.Fatal(err)+ }+ if !lease.Preflight.Success || updates != 1 {+ t.Fatalf("lease preflight = %+v, updates = %d", lease.Preflight, updates)+ }+ if err := lease.Close(context.Background()); err != nil {+ t.Fatal(err)+ }+ if updates != 2 || codexEnabled {+ t.Fatalf("restored updates = %d, codex enabled = %t", updates, codexEnabled)+ }+}++func TestAcquirePatrolModelSuiteReturnsOneFreshFailureAndRestoresRoute(t *testing.T) {+ currentModel := "ollama:qwen3:8b"+ updates := 0+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/api/settings/ai":+ response := map[string]any{+ "enabled": true, "model": "ollama:qwen3:8b", "patrol_model": currentModel,+ "patrol_enabled": true, "codex_subscription_enabled": currentModel == "codex-subscription:gpt-5.6-sol",+ }+ if currentModel == "codex-subscription:gpt-5.6-sol" {+ response["patrol_preflight"] = map[string]any{+ "success": false, "provider": "codex-subscription", "model": "gpt-5.6-sol",+ "cause": "provider_connection", "summary": "Provider connection issue",+ "recorded_at_unix": int64(200),+ }+ }+ _ = json.NewEncoder(w).Encode(response)+ case r.Method == http.MethodPut && r.URL.Path == "/api/settings/ai/update":+ updates+++ var body map[string]any+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Fatal(err)+ }+ if value, ok := body["patrol_model"].(string); ok {+ currentModel = value+ }+ _, _ = w.Write([]byte(`{}`))+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()+ client, err := NewPulseClient(ClientConfig{BaseURL: server.URL})+ if err != nil {+ t.Fatal(err)+ }+ _, err = client.AcquirePatrolModelSuite(context.Background(), "codex-subscription:gpt-5.6-sol", time.Second, time.Millisecond)+ if err == nil || !strings.Contains(err.Error(), "Provider connection issue") {+ t.Fatalf("acquire error = %v", err)+ }+ if updates != 2 || currentModel != "ollama:qwen3:8b" {+ t.Fatalf("updates = %d, current model = %q", updates, currentModel)+ }+}+func TestDecideActionBindsExactPlanHash(t *testing.T) {server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if r.URL.Path != "/api/actions/action-1/decision" || r.Method != http.MethodPost {diff --git a/internal/ai/qualification/manifest_test.go b/internal/ai/qualification/manifest_test.goindex 50a3a8ad91..5582dab35e 100644--- a/internal/ai/qualification/manifest_test.go+++ b/internal/ai/qualification/manifest_test.go@@ -134,7 +134,7 @@ func TestRunnerBindsOnlyValidCommunityChallenge(t *testing.T) {}runner, err := NewRunner(RunnerConfig{Manifest: manifest, Lab: lab, Client: client,- ModelOverride: "provider:model", ChallengeNonce: " challenge-1234567890 ",+ ExpectedModel: "provider:model", ChallengeNonce: " challenge-1234567890 ",})if err != nil {t.Fatal(err)diff --git a/internal/ai/qualification/runner.go b/internal/ai/qualification/runner.goindex 4f3956b831..a048d1c6fb 100644--- a/internal/ai/qualification/runner.go+++ b/internal/ai/qualification/runner.go@@ -22,7 +22,7 @@ type RunnerConfig struct {Client *PulseClientArtifactRoot stringRunID string- ModelOverride string+ ExpectedModel stringGitSHA stringGitDirty boolExpectedPulseVersion string@@ -89,15 +89,7 @@ func (r *QualificationRunner) Run(ctx context.Context) (report RunReport, termin}artifactDir := filepath.Join(r.config.ArtifactRoot, r.config.RunID)var prepared *PreparedLab- var restoreModel func(context.Context) errorfinish := func() {- if restoreModel != nil {- restoreCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)- defer cancel()- if restoreErr := restoreModel(restoreCtx); restoreErr != nil {- report.Errors = append(report.Errors, "restore Patrol model: "+restoreErr.Error())- }- }if prepared != nil {cleanupCtx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)defer cancel()@@ -147,22 +139,9 @@ func (r *QualificationRunner) Run(ctx context.Context) (report RunReport, terminif expected := strings.TrimSpace(manifest.Patrol.Mode); expected != "" && !strings.EqualFold(expected, autonomy.Effective()) {return fmt.Errorf("scenario requires Patrol mode %q, effective mode is %q", expected, autonomy.Effective())}- var overrideErr error- restoreModel, overrideErr = r.config.Client.OverridePatrolModel(ctx, r.config.ModelOverride)- if overrideErr != nil {- return overrideErr- }- if r.config.ModelOverride != "" {- settings, settingsErr = r.config.Client.Settings(ctx)- if settingsErr != nil {- return settingsErr- }- status, statusErr = r.config.Client.Status(ctx)- if statusErr != nil {- return statusErr- }- if !status.Readiness.Ready || strings.EqualFold(status.Readiness.Provider, "demo") {- return fmt.Errorf("overridden Patrol model is not ready: %s", status.Readiness.Summary)+ if expected := strings.TrimSpace(r.config.ExpectedModel); expected != "" {+ if err := validatePatrolRoute(expected, settings, status); err != nil {+ return err}}model := settings.EffectivePatrolModel()@@ -438,7 +417,7 @@ func (r *QualificationRunner) Run(ctx context.Context) (report RunReport, termin}func (r *QualificationRunner) initialEnvironment() Environment {- provider, _ := splitModel(r.config.ModelOverride)+ provider, _ := splitModel(r.config.ExpectedModel)dockerTarget := ""if r.config.Lab != nil {dockerTarget = dockerTargetLabel(r.config.Lab.target)@@ -448,7 +427,7 @@ func (r *QualificationRunner) initialEnvironment() Environment {GitDirty: r.config.GitDirty,PulseBaseURL: r.config.Client.config.BaseURL,DockerTarget: dockerTarget,- Model: strings.TrimSpace(r.config.ModelOverride),+ Model: strings.TrimSpace(r.config.ExpectedModel),Provider: provider,InferenceRoute: inferenceRouteForProvider(provider),ChallengeNonce: r.config.ChallengeNonce,