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
fix(release): align api and hostagent rc contracts
rcourtman8916bc066959
diff --git a/internal/ai/approval/store_test.go b/internal/ai/approval/store_test.goindex 3a0e58b904..14b8211e83 100644--- a/internal/ai/approval/store_test.go+++ b/internal/ai/approval/store_test.go@@ -2,6 +2,7 @@ package approvalimport ("context"+ "fmt""os""path/filepath""testing"@@ -651,7 +652,12 @@ func TestExecutionStatePersistence_NormalizesLoadedCollections(t *testing.T) {}defer os.RemoveAll(tmpDir)- raw := `[{"id":"exec-1","createdAt":"2026-03-15T10:00:00Z","expiresAt":"2026-03-15T11:00:00Z"}]`+ now := time.Now().UTC()+ raw := fmt.Sprintf(+ `[{"id":"exec-1","createdAt":"%s","expiresAt":"%s"}]`,+ now.Add(-1*time.Minute).Format(time.RFC3339),+ now.Add(1*time.Hour).Format(time.RFC3339),+ )if err := os.WriteFile(filepath.Join(tmpDir, "ai_executions.json"), []byte(raw), 0o600); err != nil {t.Fatalf("write executions file: %v", err)}diff --git a/internal/ai/chat/agentic_test.go b/internal/ai/chat/agentic_test.goindex 634afb8c54..d4e0c22e4e 100644--- a/internal/ai/chat/agentic_test.go+++ b/internal/ai/chat/agentic_test.go@@ -240,7 +240,8 @@ func TestAgenticLoop(t *testing.T) {require.NoError(t, err)require.NotEmpty(t, secondSystem)assert.Contains(t, secondSystem, "## Known Facts")- assert.Contains(t, secondSystem, "vm-one")+ assert.Contains(t, secondSystem, "vm:node1:100:status")+ assert.Contains(t, secondSystem, "virtual machine resource")})}diff --git a/internal/ai/chat/context_prefetch.go b/internal/ai/chat/context_prefetch.goindex 29ec037d91..6622f264d5 100644--- a/internal/ai/chat/context_prefetch.go+++ b/internal/ai/chat/context_prefetch.go@@ -56,6 +56,10 @@ func NewContextPrefetcher(readState unifiedresources.ReadState, discoveryProvide}}+func resourceMentionGovernance(resource *unifiedresources.Resource) (*unifiedresources.ResourcePolicy, string) {+ return unifiedresources.CanonicalGovernanceMetadata(resource)+}+// Prefetch analyzes a user message and proactively gathers relevant context.// When structuredMentions are provided (from the frontend @ autocomplete), they are used// directly instead of fuzzy-matching resource names from the message text.@@ -186,14 +190,15 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMeif !seen[nameLower] {seen[nameLower] = trueresolved := unifiedresources.ResolveResourceContext(rs, name)+ policy, aiSafeSummary := resourceMentionGovernance(resolved.Resource)mentions = append(mentions, ResourceMention{Name: name,ResourceType: "vm",ResourceID: fmt.Sprintf("%d", vm.VMID()),TargetID: vm.Node(),MatchedText: name,- Policy: unifiedresources.CloneResourcePolicy(resolved.Resource.Policy),- AISafeSummary: strings.TrimSpace(resolved.Resource.AISafeSummary),+ Policy: policy,+ AISafeSummary: aiSafeSummary,})}}@@ -212,14 +217,15 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMeif !seen[nameLower] {seen[nameLower] = trueresolved := unifiedresources.ResolveResourceContext(rs, name)+ policy, aiSafeSummary := resourceMentionGovernance(resolved.Resource)mentions = append(mentions, ResourceMention{Name: name,ResourceType: "system-container",ResourceID: fmt.Sprintf("%d", ct.VMID()),TargetID: ct.Node(),MatchedText: name,- Policy: unifiedresources.CloneResourcePolicy(resolved.Resource.Policy),- AISafeSummary: strings.TrimSpace(resolved.Resource.AISafeSummary),+ Policy: policy,+ AISafeSummary: aiSafeSummary,})}}@@ -268,6 +274,7 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMe// Use the authoritative unified-resource resolver for routing plus policy.resolved := unifiedresources.ResolveResourceContext(rs, name)+ policy, aiSafeSummary := resourceMentionGovernance(resolved.Resource)loc := resolved.Locationmentions = append(mentions, ResourceMention{@@ -276,8 +283,8 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMeResourceID: container.ContainerID(),TargetID: hostID,MatchedText: name,- Policy: unifiedresources.CloneResourcePolicy(resolved.Resource.Policy),- AISafeSummary: strings.TrimSpace(resolved.Resource.AISafeSummary),+ Policy: policy,+ AISafeSummary: aiSafeSummary,BindMounts: mounts,DockerHostName: loc.DockerHostName,DockerHostType: loc.DockerHostType,@@ -302,6 +309,7 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMeif !seen[nameLower] {seen[nameLower] = trueresolved := unifiedresources.ResolveResourceContext(rs, name)+ policy, aiSafeSummary := resourceMentionGovernance(resolved.Resource)loc := resolved.Locationmentions = append(mentions, ResourceMention{Name: name,@@ -309,8 +317,8 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMeResourceID: name,TargetID: name,MatchedText: name,- Policy: unifiedresources.CloneResourcePolicy(resolved.Resource.Policy),- AISafeSummary: strings.TrimSpace(resolved.Resource.AISafeSummary),+ Policy: policy,+ AISafeSummary: aiSafeSummary,TargetHost: loc.TargetHost,})}@@ -330,6 +338,7 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMeif !seen[nameLower] {seen[nameLower] = trueresolved := unifiedresources.ResolveResourceContext(rs, hostname)+ policy, aiSafeSummary := resourceMentionGovernance(resolved.Resource)loc := resolved.Location// Use AgentID which maps to the original models.Host.IDhostID := host.AgentID()@@ -339,8 +348,8 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMeResourceID: hostID,TargetID: hostID,MatchedText: hostname,- Policy: unifiedresources.CloneResourcePolicy(resolved.Resource.Policy),- AISafeSummary: strings.TrimSpace(resolved.Resource.AISafeSummary),+ Policy: policy,+ AISafeSummary: aiSafeSummary,TargetHost: loc.TargetHost,})}@@ -365,6 +374,7 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMeif !seen[clusterLower] {seen[clusterLower] = trueresolved := unifiedresources.ResolveResourceContext(rs, clusterName)+ policy, aiSafeSummary := resourceMentionGovernance(resolved.Resource)loc := resolved.LocationclusterSourceID := cluster.ClusterID()mentions = append(mentions, ResourceMention{@@ -373,8 +383,8 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMeResourceID: clusterSourceID,TargetID: clusterSourceID,MatchedText: clusterName,- Policy: unifiedresources.CloneResourcePolicy(resolved.Resource.Policy),- AISafeSummary: strings.TrimSpace(resolved.Resource.AISafeSummary),+ Policy: policy,+ AISafeSummary: aiSafeSummary,TargetHost: loc.TargetHost,})}@@ -392,6 +402,7 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMeif !seen[podLower] {seen[podLower] = trueresolved := unifiedresources.ResolveResourceContext(rs, podName)+ policy, aiSafeSummary := resourceMentionGovernance(resolved.Resource)loc := resolved.LocationhostID := k8sClusterSourceIDs[pod.ParentID()]if hostID == "" {@@ -403,8 +414,8 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMeResourceID: podName,TargetID: hostID,MatchedText: podName,- Policy: unifiedresources.CloneResourcePolicy(resolved.Resource.Policy),- AISafeSummary: strings.TrimSpace(resolved.Resource.AISafeSummary),+ Policy: policy,+ AISafeSummary: aiSafeSummary,TargetHost: loc.TargetHost,})}@@ -422,6 +433,7 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMeif !seen[deployLower] {seen[deployLower] = trueresolved := unifiedresources.ResolveResourceContext(rs, deployName)+ policy, aiSafeSummary := resourceMentionGovernance(resolved.Resource)loc := resolved.LocationhostID := k8sClusterSourceIDs[deploy.ParentID()]if hostID == "" {@@ -433,8 +445,8 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMeResourceID: deployName,TargetID: hostID,MatchedText: deployName,- Policy: unifiedresources.CloneResourcePolicy(resolved.Resource.Policy),- AISafeSummary: strings.TrimSpace(resolved.Resource.AISafeSummary),+ Policy: policy,+ AISafeSummary: aiSafeSummary,TargetHost: loc.TargetHost,})}@@ -470,6 +482,7 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMen// Use the canonical unified-resource resolver for routing plus policy metadata.resolved := unifiedresources.ResolveResourceContext(rs, sm.Name)+ policy, aiSafeSummary := resourceMentionGovernance(resolved.Resource)loc := resolved.Locationswitch resourceType {@@ -486,8 +499,8 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMenResourceID: vmID,TargetID: node,MatchedText: sm.Name,- Policy: unifiedresources.CloneResourcePolicy(resolved.Resource.Policy),- AISafeSummary: strings.TrimSpace(resolved.Resource.AISafeSummary),+ Policy: policy,+ AISafeSummary: aiSafeSummary,TargetHost: loc.TargetHost,})@@ -504,8 +517,8 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMenResourceID: vmID,TargetID: node,MatchedText: sm.Name,- Policy: unifiedresources.CloneResourcePolicy(resolved.Resource.Policy),- AISafeSummary: strings.TrimSpace(resolved.Resource.AISafeSummary),+ Policy: policy,+ AISafeSummary: aiSafeSummary,TargetHost: loc.TargetHost,})@@ -539,8 +552,8 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMenResourceID: containerID,TargetID: hostID,MatchedText: sm.Name,- Policy: unifiedresources.CloneResourcePolicy(resolved.Resource.Policy),- AISafeSummary: strings.TrimSpace(resolved.Resource.AISafeSummary),+ Policy: policy,+ AISafeSummary: aiSafeSummary,BindMounts: mounts,DockerHostName: loc.DockerHostName,DockerHostType: loc.DockerHostType,@@ -556,8 +569,8 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMenResourceID: sm.Name,TargetID: sm.Name,MatchedText: sm.Name,- Policy: unifiedresources.CloneResourcePolicy(resolved.Resource.Policy),- AISafeSummary: strings.TrimSpace(resolved.Resource.AISafeSummary),+ Policy: policy,+ AISafeSummary: aiSafeSummary,TargetHost: loc.TargetHost,})@@ -572,8 +585,8 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMenResourceID: hostID,TargetID: hostID,MatchedText: sm.Name,- Policy: unifiedresources.CloneResourcePolicy(resolved.Resource.Policy),- AISafeSummary: strings.TrimSpace(resolved.Resource.AISafeSummary),+ Policy: policy,+ AISafeSummary: aiSafeSummary,TargetHost: loc.TargetHost,})@@ -595,8 +608,8 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMenResourceID: sm.ID,TargetID: sm.Node,MatchedText: sm.Name,- Policy: unifiedresources.CloneResourcePolicy(resolved.Resource.Policy),- AISafeSummary: strings.TrimSpace(resolved.Resource.AISafeSummary),+ Policy: policy,+ AISafeSummary: aiSafeSummary,TargetHost: loc.TargetHost,})}diff --git a/internal/ai/tools/tools_query.go b/internal/ai/tools/tools_query.goindex 892b41ad00..b56151e12c 100644--- a/internal/ai/tools/tools_query.go+++ b/internal/ai/tools/tools_query.go@@ -2198,15 +2198,10 @@ func (r *governedQueryMetadataResolver) Resolve(candidates ...string) GovernedRe}func governedQueryMetadataFromResolvedResource(resource *unifiedresources.Resource) GovernedResourceMetadata {- if resource == nil {- return GovernedResourceMetadata{}- }-- resourceCopy := *resource- unifiedresources.RefreshPolicyMetadata(&resourceCopy)+ policy, aiSafeSummary := unifiedresources.CanonicalGovernanceMetadata(resource)return GovernedResourceMetadata{- Policy: unifiedresources.CloneResourcePolicy(resourceCopy.Policy),- AISafeSummary: strings.TrimSpace(resourceCopy.AISafeSummary),+ Policy: policy,+ AISafeSummary: aiSafeSummary,}}diff --git a/internal/api/ai_handler_test.go b/internal/api/ai_handler_test.goindex 61768e59c4..767c352044 100644--- a/internal/api/ai_handler_test.go+++ b/internal/api/ai_handler_test.go@@ -1165,6 +1165,13 @@ func TestGetService_MultiTenantAppliesServiceInitializerOnCreate(t *testing.T) {mtp := config.NewMultiTenantPersistence(tempDir)mtm := monitoring.NewMultiTenantMonitor(&config.Config{}, mtp, nil)t.Cleanup(mtm.Stop)+ tenantPersistence, err := mtp.GetPersistence("acme")+ if err != nil {+ t.Fatalf("tenant persistence: %v", err)+ }+ if err := tenantPersistence.SaveAIConfig(config.AIConfig{Enabled: true}); err != nil {+ t.Fatalf("save tenant AI config: %v", err)+ }tenantMonitor := &monitoring.Monitor{}setUnexportedField(t, mtm, "monitors", map[string]*monitoring.Monitor{"acme": tenantMonitor})@@ -1188,7 +1195,7 @@ func TestGetService_MultiTenantAppliesServiceInitializerOnCreate(t *testing.T) {ctx := context.WithValue(context.Background(), OrgIDContextKey, "acme")svc := h.GetService(ctx)- assert.Same(t, mockSvc, svc)+ assert.True(t, svc == mockSvc, "expected tenant initializer to receive the created tenant service")if calls != 1 {t.Fatalf("expected initializer called once for tenant service, got %d", calls)}diff --git a/internal/api/ai_hosted_runtime.go b/internal/api/ai_hosted_runtime.goindex 0ac8bc9da7..6098083c40 100644--- a/internal/api/ai_hosted_runtime.go+++ b/internal/api/ai_hosted_runtime.go@@ -6,7 +6,6 @@ import ("strings""github.com/rcourtman/pulse-go-rewrite/internal/config"- pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing")func loadHostedAwareAIConfig(hostedMode bool, billingBaseDir, orgID string, persistence *config.ConfigPersistence) (*config.AIConfig, error) {@@ -77,7 +76,7 @@ func hostedAIAutoBootstrapEligible(state *billingState) bool {return false}switch state.SubscriptionState {- case subscriptionStateActiveValue, subscriptionStateGraceValue, pkglicensing.SubStateTrial:+ case subscriptionStateActiveValue, subscriptionStateGraceValue, subscriptionStateTrialValue:default:return false}diff --git a/internal/api/ai_intelligence_handlers_additional_test.go b/internal/api/ai_intelligence_handlers_additional_test.goindex af79c829db..6af9042353 100644--- a/internal/api/ai_intelligence_handlers_additional_test.go+++ b/internal/api/ai_intelligence_handlers_additional_test.go@@ -54,7 +54,7 @@ func TestHandleGetRecentChanges_NoChangeDetector(t *testing.T) {if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {t.Fatalf("decode response: %v", err)}- if payload["message"] != "Change detector not initialized" {+ if payload["message"] != "Recent changes not initialized" {t.Fatalf("unexpected message: %#v", payload["message"])}}diff --git a/internal/api/code_standards_test.go b/internal/api/code_standards_test.goindex 566cbb288e..60aa71399d 100644--- a/internal/api/code_standards_test.go+++ b/internal/api/code_standards_test.go@@ -205,6 +205,15 @@ func TestPaidDomainBoundaryAudit(t *testing.T) {"enterprise_extension_sso_admin.go": true,}+ // These reporting files are intentionally public shared surfaces rather than+ // paid-domain implementations: the catalog route is public product metadata,+ // and the VM inventory export handler is the default shared implementation+ // behind the reporting admin extension boundary.+ knownPublicReportingFiles := map[string]bool{+ "reporting_catalog_handlers.go": true,+ "reporting_inventory_handlers.go": true,+ }+for name := range goFiles {// Skip already-tracked files.if _, tracked := paidDomainFiles[name]; tracked {@@ -215,6 +224,9 @@ func TestPaidDomainBoundaryAudit(t *testing.T) {if knownBinderFiles[name] {continue}+ if knownPublicReportingFiles[name] {+ continue+ }// Flag unknown enterprise_extension_ files (not in the exact allowlist).if strings.HasPrefix(name, "enterprise_extension_") {diff --git a/internal/api/config_handlers_setup_script_test.go b/internal/api/config_handlers_setup_script_test.goindex b32fa291b4..960ba55b5b 100644--- a/internal/api/config_handlers_setup_script_test.go+++ b/internal/api/config_handlers_setup_script_test.go@@ -229,8 +229,17 @@ func TestPVESetupScript_UsesFailFastRetryGuidance(t *testing.T) {}script := rr.Body.String()- if !containsString(script, `echo " curl -fsSL \"$SETUP_SCRIPT_URL\" | { if [ \"$(id -u)\" -eq 0 ]; then PULSE_SETUP_TOKEN=\"$PULSE_SETUP_TOKEN\" bash; elif command -v sudo >/dev/null 2>&1; then sudo env PULSE_SETUP_TOKEN=\"$PULSE_SETUP_TOKEN\" bash; else echo \"Root privileges required. Run as root (su -) and retry.\" >&2; exit 1; fi; }"`) {- t.Fatalf("expected fail-fast retry guidance in setup script, got: %s", truncate(script, 700))+ if !containsString(script, `PULSE_BOOTSTRAP_COMMAND_WITH_ENV='curl -fsSL '"'"'http://sentinel-url:7656/api/setup-script?host=http%3A%2F%2Fsentinel-host%3A8006&pulse_url=http%3A%2F%2Fsentinel-url%3A7656&type=pve'"'"' | `) {+ t.Fatalf("expected canonical bootstrap command owner in setup script, got: %s", truncate(script, 700))+ }+ if !containsString(script, `echo " $PULSE_BOOTSTRAP_COMMAND_WITH_ENV"`) {+ t.Fatalf("expected canonical bootstrap-command retry guidance in setup script, got: %s", truncate(script, 700))+ }+ if !containsString(script, `SETUP_SCRIPT_URL="http://sentinel-url:7656/api/setup-script?host=http%3A%2F%2Fsentinel-host%3A8006&pulse_url=http%3A%2F%2Fsentinel-url%3A7656&type=pve"`) {+ t.Fatalf("expected canonical encoded retry URL in setup script, got: %s", truncate(script, 700))+ }+ if !containsString(script, `PULSE_SETUP_TOKEN="${PULSE_SETUP_TOKEN:-`) {+ t.Fatalf("expected canonical embedded setup token initialization before retry guidance, got: %s", truncate(script, 700))}if !containsString(script, `echo "Root privileges required. Run as root (su -) and retry."`) {t.Fatalf("expected canonical root requirement guidance in setup script, got: %s", truncate(script, 700))@@ -244,9 +253,6 @@ func TestPVESetupScript_UsesFailFastRetryGuidance(t *testing.T) {if containsString(script, `echo "Manual setup steps:"`) || containsString(script, `echo " 2. In Pulse: Settings → Nodes → Add Node (enter token from above)"`) {t.Fatalf("expected stale off-host manual token flow to be removed from setup script, got: %s", truncate(script, 900))}- if containsString(script, `echo "Please run this script as root"`) {- t.Fatalf("expected stale root-only setup script guidance to be removed, got: %s", truncate(script, 900))- }}func TestPVESetupScript_PreservesEncodedRerunURLAndBackupPerms(t *testing.T) {diff --git a/internal/api/licensing_bridge.go b/internal/api/licensing_bridge.goindex 405255e044..1f391f0c3d 100644--- a/internal/api/licensing_bridge.go+++ b/internal/api/licensing_bridge.go@@ -71,6 +71,7 @@ const (subscriptionStateExpiredValue = pkglicensing.SubStateExpiredsubscriptionStateGraceValue = pkglicensing.SubStateGracesubscriptionStateCanceledValue = pkglicensing.SubStateCanceled+ subscriptionStateTrialValue = pkglicensing.SubStateTrialactivationKeyPrefixValue = pkglicensing.ActivationKeyPrefix// Conversion event type constants for backend-emitted events.diff --git a/internal/api/router_csrf_skip_routes_test.go b/internal/api/router_csrf_skip_routes_test.goindex 9eb4e78bfc..9ec686ef23 100644--- a/internal/api/router_csrf_skip_routes_test.go+++ b/internal/api/router_csrf_skip_routes_test.go@@ -82,7 +82,7 @@ func TestCSRFSkippedForSetupScriptURL(t *testing.T) {sessionToken := generateSessionToken()GetSessionStore().CreateSession(sessionToken, time.Hour, "agent", "127.0.0.1", "admin")- body := `{"type":"pve"}`+ body := `{"type":"pve","host":"https://pve.local:8006"}`req := httptest.NewRequest(http.MethodPost, "/api/setup-script-url", strings.NewReader(body))req.AddCookie(&http.Cookie{Name: "pulse_session", Value: sessionToken})req.Header.Set("Content-Type", "application/json")diff --git a/internal/api/router_helpers_more_test.go b/internal/api/router_helpers_more_test.goindex 90f2d84b6e..0943b569c9 100644--- a/internal/api/router_helpers_more_test.go+++ b/internal/api/router_helpers_more_test.go@@ -358,6 +358,8 @@ func TestStartPatrolForContext_DoesNotOverwriteOtherTenantPatrolComponents(t *tedefaultMonitor, _, _ := newTestMonitor(t)tenantOneMonitor, _, _ := newTestMonitor(t)tenantTwoMonitor, _, _ := newTestMonitor(t)+ tenantOneMonitor.SetResourceStore(unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(nil)))+ tenantTwoMonitor.SetResourceStore(unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(nil)))mtm := &monitoring.MultiTenantMonitor{}setUnexportedField(t, mtm, "monitors", map[string]*monitoring.Monitor{diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.goindex bef0d1c23d..8b31416034 100644--- a/internal/api/security_regression_test.go+++ b/internal/api/security_regression_test.go@@ -1967,7 +1967,7 @@ func TestAutoRegisterRequiresAuth(t *testing.T) {}}-func TestAutoRegisterRejectsTokenMissingRequiredScope(t *testing.T) {+func TestAutoRegisterRejectsAPITokenWithoutSetupToken(t *testing.T) {rawToken := "auto-register-token-123.12345678"record := newTokenRecord(t, rawToken, []string{config.ScopeMonitoringRead}, nil)cfg := newTestConfigWithTokens(t, record)@@ -1978,12 +1978,15 @@ func TestAutoRegisterRejectsTokenMissingRequiredScope(t *testing.T) {req.Header.Set("X-API-Token", rawToken)rec := httptest.NewRecorder()router.Handler().ServeHTTP(rec, req)- if rec.Code != http.StatusForbidden {- t.Fatalf("expected 403 for missing required scope, got %d", rec.Code)+ if rec.Code != http.StatusUnauthorized {+ t.Fatalf("expected 401 when API token is provided without a Pulse setup token, got %d", rec.Code)+ }+ if !strings.Contains(rec.Body.String(), "Pulse setup token required") {+ t.Fatalf("expected setup-token requirement guidance, got %q", rec.Body.String())}}-func TestAutoRegisterAcceptsAgentToken(t *testing.T) {+func TestAutoRegisterRejectsAgentTokenWithoutSetupToken(t *testing.T) {stubAutoRegisterNetworkDeps(t)rawToken := "agent-register-token-123.12345678"@@ -1997,9 +2000,11 @@ func TestAutoRegisterAcceptsAgentToken(t *testing.T) {req.Header.Set("X-API-Token", rawToken)rec := httptest.NewRecorder()router.Handler().ServeHTTP(rec, req)- // Should not be 401 — the agent token has agent:report which is accepted- if rec.Code == http.StatusUnauthorized {- t.Fatalf("expected agent token with agent:report to be accepted, got 401")+ if rec.Code != http.StatusUnauthorized {+ t.Fatalf("expected 401 when agent API token is provided without a Pulse setup token, got %d", rec.Code)+ }+ if !strings.Contains(rec.Body.String(), "Pulse setup token required") {+ t.Fatalf("expected setup-token requirement guidance, got %q", rec.Body.String())}}@@ -3951,18 +3956,18 @@ func TestSSHKeyGenerationBlockedInContainer(t *testing.T) {}}-func TestSetupScriptRejectsInvalidAuthToken(t *testing.T) {+func TestSetupScriptRejectsInvalidSetupToken(t *testing.T) {cfg := newTestConfigWithTokens(t)router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")- req := httptest.NewRequest(http.MethodGet, "/api/setup-script?type=pve&host=https://example.com&pulse_url=https://pulse.example.com&auth_token=not-hex", nil)+ req := httptest.NewRequest(http.MethodGet, "/api/setup-script?type=pve&host=https://example.com&pulse_url=https://pulse.example.com&setup_token=not-hex", nil)rec := httptest.NewRecorder()router.Handler().ServeHTTP(rec, req)if rec.Code != http.StatusBadRequest {- t.Fatalf("expected 400 for invalid auth_token, got %d", rec.Code)+ t.Fatalf("expected 400 for invalid setup_token, got %d", rec.Code)}- if !strings.Contains(rec.Body.String(), "Invalid auth_token parameter") {- t.Fatalf("expected invalid auth_token error, got %q", rec.Body.String())+ if !strings.Contains(rec.Body.String(), "Invalid setup_token parameter") {+ t.Fatalf("expected invalid setup_token error, got %q", rec.Body.String())}}diff --git a/internal/hostagent/proxmox_setup_test.go b/internal/hostagent/proxmox_setup_test.goindex dda099d24c..5ca12db22c 100644--- a/internal/hostagent/proxmox_setup_test.go+++ b/internal/hostagent/proxmox_setup_test.go@@ -401,12 +401,26 @@ func TestGetIPThatReachesPulse_IPv6Target(t *testing.T) {func TestProxmoxSetup_RunForType(t *testing.T) {mc := &mockCollector{}+ var expectedTokenID stringserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusOK)+ switch r.URL.Path {+ case "/api/setup-script-url":+ publicURL := "http://" + r.Host+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(canonicalSetupScriptURLResponseJSON(publicURL, "pve", "https://10.0.0.1:8006", "setup-token-run-for-type")))+ case "/api/auto-register":+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(fmt.Sprintf(`{"status":"success","message":"Node node-1 registered successfully at https://10.0.0.1:8006","action":"use_token","type":"pve","source":"agent","host":"https://10.0.0.1:8006","nodeId":"node-1","nodeName":"node-1","tokenId":"%s","tokenValue":"my-token"}`, expectedTokenID)))+ default:+ t.Fatalf("unexpected path %s", r.URL.Path)+ }}))defer server.Close()p := NewProxmoxSetup(zerolog.Nop(), server.Client(), mc, server.URL, "token", "pve", "host", "", "", false)+ p.retryBackoffs = []time.Duration{}+ expectedTokenID = fmt.Sprintf("%s!%s", proxmoxUserPVE, p.monitorTokenName())t.Run("skips if already registered", func(t *testing.T) {mc.statFn = func(name string) (os.FileInfo, error) { return nil, nil } // exists@@ -570,7 +584,44 @@ func TestProxmoxSetup_RunAll(t *testing.T) {mc := &mockCollector{}t.Run("detects both and runs both", func(t *testing.T) {- p := NewProxmoxSetup(zerolog.Nop(), http.DefaultClient, mc, "https://pulse", "token", "", "host", "", "", false)+ var expectedPVETokenID string+ var expectedPBSTokenID string+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/api/setup-script-url":+ var payload map[string]any+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {+ t.Fatalf("decode setup token payload: %v", err)+ }+ publicURL := "http://" + r.Host+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(canonicalSetupScriptURLResponseJSON(publicURL, payload["type"].(string), payload["host"].(string), "setup-token-"+payload["type"].(string))))+ case "/api/auto-register":+ var payload map[string]any+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {+ t.Fatalf("decode auto-register payload: %v", err)+ }+ regType := payload["type"].(string)+ tokenID := expectedPVETokenID+ tokenValue := "v1"+ if regType == "pbs" {+ tokenID = expectedPBSTokenID+ tokenValue = "v2"+ }+ host := payload["host"].(string)+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(fmt.Sprintf(`{"status":"success","message":"Node node-1 registered successfully at %s","action":"use_token","type":"%s","source":"agent","host":"%s","nodeId":"node-1","nodeName":"node-1","tokenId":"%s","tokenValue":"%s"}`, host, regType, host, tokenID, tokenValue)))+ default:+ t.Fatalf("unexpected path %s", r.URL.Path)+ }+ }))+ defer server.Close()++ p := NewProxmoxSetup(zerolog.Nop(), server.Client(), mc, server.URL, "token", "", "host", "", "", false)+ p.retryBackoffs = []time.Duration{}+ expectedPVETokenID = fmt.Sprintf("%s!%s", proxmoxUserPVE, p.monitorTokenName())+ expectedPBSTokenID = fmt.Sprintf("%s!%s", proxmoxUserPBS, p.monitorTokenName())mc.lookPathFn = func(file string) (string, error) { return "/bin/" + file, nil }mc.statFn = func(name string) (os.FileInfo, error) { return nil, os.ErrNotExist }mc.commandCombinedOutputFn = func(ctx context.Context, name string, arg ...string) (string, error) {@@ -590,9 +641,6 @@ func TestProxmoxSetup_RunAll(t *testing.T) {return &mockConn{localAddr: &net.UDPAddr{IP: net.ParseIP("10.0.0.1")}}, nil}- hc := &http.Client{Transport: &mockTransport{statusCode: 200}}- p.httpClient = hc-results, err := p.RunAll(context.Background())if err != nil || len(results) != 2 {t.Errorf("expected 2 results, got %d (err: %v)", len(results), err)@@ -796,14 +844,41 @@ func TestProxmoxSetup_MarkTypeAsRegistered_EnforcesPrivatePermissions(t *testing}func TestProxmoxSetup_Run_TopLevel(t *testing.T) {- mc := &mockCollector{}- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusOK)- }))- defer server.Close()+ newTopLevelCollector := func() *mockCollector {+ mc := &mockCollector{}+ mc.statFn = func(name string) (os.FileInfo, error) { return nil, os.ErrNotExist }+ mc.mkdirAllFn = func(path string, perm os.FileMode) error { return nil }+ mc.writeFileFn = func(filename string, data []byte, perm os.FileMode) error { return nil }+ mc.dialTimeoutFn = func(network, address string, timeout time.Duration) (net.Conn, error) {+ return &mockConn{localAddr: &net.UDPAddr{IP: net.ParseIP("10.0.0.1")}}, nil+ }+ return mc+ }t.Run("auto-detects and runs", func(t *testing.T) {+ mc := newTopLevelCollector()+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/api/setup-script-url":+ publicURL := "http://" + r.Host+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(canonicalSetupScriptURLResponseJSON(publicURL, "pve", "https://10.0.0.1:8006", "setup-token-top-level")))+ case "/api/auto-register":+ var payload autoRegisterRequest+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {+ t.Fatalf("decode payload: %v", err)+ }+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(fmt.Sprintf(`{"status":"success","message":"Node node-1 registered successfully at %s","action":"use_token","type":"%s","source":"agent","host":"%s","nodeId":"node-1","nodeName":"node-1","tokenId":"%s","tokenValue":"%s"}`, payload.Host, payload.Type, payload.Host, payload.TokenID, payload.TokenValue)))+ default:+ t.Fatalf("unexpected path %s", r.URL.Path)+ }+ }))+ defer server.Close()+p := NewProxmoxSetup(zerolog.Nop(), server.Client(), mc, server.URL, "token", "", "host", "", "", false)+ p.retryBackoffs = []time.Duration{}mc.lookPathFn = func(file string) (string, error) {if file == "pvesh" {return "/bin/pvesh", nil@@ -817,11 +892,6 @@ func TestProxmoxSetup_Run_TopLevel(t *testing.T) {}return "", nil}- mc.mkdirAllFn = func(p string, m os.FileMode) error { return nil }- mc.writeFileFn = func(f string, d []byte, m os.FileMode) error { return nil }- mc.dialTimeoutFn = func(n, a string, d time.Duration) (net.Conn, error) {- return &mockConn{localAddr: &net.UDPAddr{IP: net.ParseIP("10.0.0.1")}}, nil- }res, err := p.Run(context.Background())if err != nil || res == nil || !res.Registered || res.ProxmoxType != "pve" {@@ -830,6 +900,12 @@ func TestProxmoxSetup_Run_TopLevel(t *testing.T) {})t.Run("invalid pulse URL fails fast", func(t *testing.T) {+ mc := newTopLevelCollector()+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusOK)+ }))+ defer server.Close()+p := NewProxmoxSetup(zerolog.Nop(), server.Client(), mc, "not-a-url", "token", "", "host", "", "", false)if _, err := p.Run(context.Background()); err == nil || !strings.Contains(err.Error(), "invalid pulse URL") {t.Fatalf("expected pulse URL validation error, got %v", err)@@ -837,6 +913,7 @@ func TestProxmoxSetup_Run_TopLevel(t *testing.T) {})t.Run("missing token still registers when auth is optional", func(t *testing.T) {+ mc := newTopLevelCollector()var gotPayload autoRegisterRequestrequestCount := 0noTokenServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {@@ -848,12 +925,14 @@ func TestProxmoxSetup_Run_TopLevel(t *testing.T) {}publicURL := "http://" + r.Hostw.Header().Set("Content-Type", "application/json")- _, _ = w.Write([]byte(canonicalSetupScriptURLResponseJSON(publicURL, "pve", "https://10.0.0.4:8006", "setup-token-optional")))+ _, _ = w.Write([]byte(canonicalSetupScriptURLResponseJSON(publicURL, "pve", "https://10.0.0.1:8006", "setup-token-optional")))case "/api/auto-register":if err := json.NewDecoder(r.Body).Decode(&gotPayload); err != nil {t.Fatalf("decode payload: %v", err)}+ w.Header().Set("Content-Type", "application/json")w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(fmt.Sprintf(`{"status":"success","message":"Node node-1 registered successfully at %s","action":"use_token","type":"%s","source":"agent","host":"%s","nodeId":"node-1","nodeName":"node-1","tokenId":"%s","tokenValue":"%s"}`, gotPayload.Host, gotPayload.Type, gotPayload.Host, gotPayload.TokenID, gotPayload.TokenValue)))default:t.Fatalf("unexpected path %s", r.URL.Path)}@@ -861,6 +940,19 @@ func TestProxmoxSetup_Run_TopLevel(t *testing.T) {defer noTokenServer.Close()p := NewProxmoxSetup(zerolog.Nop(), noTokenServer.Client(), mc, noTokenServer.URL, " ", "", "host", "", "", false)+ p.retryBackoffs = []time.Duration{}+ mc.lookPathFn = func(file string) (string, error) {+ if file == "pvesh" {+ return "/bin/pvesh", nil+ }+ return "", os.ErrNotExist+ }+ mc.commandCombinedOutputFn = func(ctx context.Context, name string, arg ...string) (string, error) {+ if name == "pveum" && len(arg) > 2 && arg[1] == "token" {+ return "│ value │ optional-token │", nil+ }+ return "", nil+ }res, err := p.Run(context.Background())if err != nil {t.Fatalf("Run: %v", err)@@ -877,6 +969,12 @@ func TestProxmoxSetup_Run_TopLevel(t *testing.T) {})t.Run("invalid proxmox type fails fast", func(t *testing.T) {+ mc := newTopLevelCollector()+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusOK)+ }))+ defer server.Close()+p := NewProxmoxSetup(zerolog.Nop(), server.Client(), mc, server.URL, "token", "bad", "host", "", "", false)if _, err := p.Run(context.Background()); err == nil || !strings.Contains(err.Error(), "invalid proxmox type") {t.Fatalf("expected proxmox type validation error, got %v", err)diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex 6c058d1a9d..939469334f 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -2648,16 +2648,23 @@ func isTransientError(err error) bool {}func (m *Monitor) GetState() models.StateSnapshot {+ if m == nil {+ return models.StateSnapshot{}+ }+// Check if mock mode is enabledif mock.IsMockEnabled() {state := mock.GetMockState()- if state.ActiveAlerts == nil {+ if state.ActiveAlerts == nil && m.alertManager != nil {// Populate snapshot lazily if the cache hasn't been filled yet.mock.UpdateAlertSnapshots(m.alertManager.GetActiveAlerts(), m.alertManager.GetRecentlyResolved())state = mock.GetMockState()}return state}+ if m.state == nil {+ return models.StateSnapshot{}+ }return m.state.GetSnapshot()}diff --git a/internal/monitoring/monitor_full_coverage_test.go b/internal/monitoring/monitor_full_coverage_test.goindex 2632e39b76..844d74203d 100644--- a/internal/monitoring/monitor_full_coverage_test.go+++ b/internal/monitoring/monitor_full_coverage_test.go@@ -742,6 +742,14 @@ func TestMonitor_GetState(t *testing.T) {}}+func TestMonitor_GetState_NilStateReturnsEmptySnapshot(t *testing.T) {+ m := &Monitor{}+ s := m.GetState()+ if s.Nodes != nil {+ t.Errorf("expected nil nodes for empty snapshot, got %#v", s.Nodes)+ }+}+func TestPollPVEInstance(t *testing.T) {// Setup Monitorm := &Monitor{diff --git a/internal/unifiedresources/adapters.go b/internal/unifiedresources/adapters.goindex eacb88100f..4f4a1e1306 100644--- a/internal/unifiedresources/adapters.go+++ b/internal/unifiedresources/adapters.go@@ -1015,9 +1015,10 @@ func resourceFromPMGInstance(instance models.PMGInstance) (Resource, ResourceIde}func resourceFromVM(vm models.VM) (Resource, ResourceIdentity) {+ sourceID := proxmoxVMSourceID(vm)metrics := metricsFromVM(vm)proxmox := &ProxmoxData{- SourceID: vm.ID,+ SourceID: sourceID,NodeName: vm.Node,Pool: vm.Pool,Instance: vm.Instance,@@ -1056,9 +1057,10 @@ func resourceFromVM(vm models.VM) (Resource, ResourceIdentity) {}func resourceFromContainer(ct models.Container) (Resource, ResourceIdentity) {+ sourceID := proxmoxContainerSourceID(ct)metrics := metricsFromContainer(ct)proxmox := &ProxmoxData{- SourceID: ct.ID,+ SourceID: sourceID,NodeName: ct.Node,Pool: ct.Pool,Instance: ct.Instance,diff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.goindex cfbad1db19..4f911779c7 100644--- a/internal/unifiedresources/code_standards_test.go+++ b/internal/unifiedresources/code_standards_test.go@@ -337,9 +337,9 @@ func TestResourcePolicyCloneHelperUsedByAIConsumers(t *testing.T) {filepath.Join(".", "policy_metadata.go"),}requiredSnippets := map[string]string{- filepath.Join("..", "ai", "chat", "context_prefetch.go"): "unifiedresources.CloneResourcePolicy(resolved.Resource.Policy)",- filepath.Join("..", "ai", "tools", "tools_query.go"): "unifiedresources.CloneResourcePolicy(resourceCopy.Policy)",- filepath.Join(".", "policy_metadata.go"): "func CloneResourcePolicy(policy *ResourcePolicy) *ResourcePolicy",+ filepath.Join("..", "ai", "chat", "context_prefetch.go"): "unifiedresources.CanonicalGovernanceMetadata(resource)",+ filepath.Join("..", "ai", "tools", "tools_query.go"): "unifiedresources.CanonicalGovernanceMetadata(resource)",+ filepath.Join(".", "policy_metadata.go"): "func CanonicalGovernanceMetadata(resource *Resource) (*ResourcePolicy, string)",}for _, name := range requiredFiles {data, err := os.ReadFile(name)diff --git a/internal/unifiedresources/policy_metadata.go b/internal/unifiedresources/policy_metadata.goindex adabe20764..86322d49d4 100644--- a/internal/unifiedresources/policy_metadata.go+++ b/internal/unifiedresources/policy_metadata.go@@ -58,6 +58,19 @@ func CloneResourcePolicy(policy *ResourcePolicy) *ResourcePolicy {return ©Policy}+// CanonicalGovernanceMetadata returns cloned policy metadata and AI-safe+// summary for a resolved resource, tolerating callers that only have routing+// location data when a full Resource record is not available.+func CanonicalGovernanceMetadata(resource *Resource) (*ResourcePolicy, string) {+ if resource == nil {+ return nil, ""+ }++ resourceCopy := *resource+ RefreshPolicyMetadata(&resourceCopy)+ return CloneResourcePolicy(resourceCopy.Policy), strings.TrimSpace(resourceCopy.AISafeSummary)+}+// RefreshPolicyMetadata derives canonical sensitivity, routing, and AI-safe summary data.func RefreshPolicyMetadata(resource *Resource) {if resource == nil {diff --git a/internal/unifiedresources/registry.go b/internal/unifiedresources/registry.goindex 9fe1ca6e78..95c79df7bb 100644--- a/internal/unifiedresources/registry.go+++ b/internal/unifiedresources/registry.go@@ -570,6 +570,7 @@ func (rr *ResourceRegistry) ingestPMGInstance(instance models.PMGInstance) {func (rr *ResourceRegistry) ingestVM(vm models.VM, clusterByInstance map[string]string) {resource, identity := resourceFromVM(vm)+ sourceID := proxmoxVMSourceID(vm)parentSourceID := proxmoxNodeSourceID(vm.Instance, vm.Node)if parentID, ok := rr.bySource[SourceProxmox][parentSourceID]; ok {resource.ParentID = &parentID@@ -577,11 +578,12 @@ func (rr *ResourceRegistry) ingestVM(vm models.VM, clusterByInstance map[string]if clusterName := clusterByInstance[vm.Instance]; clusterName != "" && resource.Proxmox != nil {resource.Proxmox.ClusterName = clusterName}- rr.ingest(SourceProxmox, vm.ID, resource, identity)+ rr.ingest(SourceProxmox, sourceID, resource, identity)}func (rr *ResourceRegistry) ingestContainer(ct models.Container, clusterByInstance map[string]string) {resource, identity := resourceFromContainer(ct)+ sourceID := proxmoxContainerSourceID(ct)parentSourceID := proxmoxNodeSourceID(ct.Instance, ct.Node)if parentID, ok := rr.bySource[SourceProxmox][parentSourceID]; ok {resource.ParentID = &parentID@@ -589,7 +591,7 @@ func (rr *ResourceRegistry) ingestContainer(ct models.Container, clusterByInstanif clusterName := clusterByInstance[ct.Instance]; clusterName != "" && resource.Proxmox != nil {resource.Proxmox.ClusterName = clusterName}- rr.ingest(SourceProxmox, ct.ID, resource, identity)+ rr.ingest(SourceProxmox, sourceID, resource, identity)}func (rr *ResourceRegistry) ingestStorage(storage models.Storage) {@@ -1338,6 +1340,41 @@ func proxmoxNodeSourceID(instance, nodeName string) string {return fmt.Sprintf("%s-%s", instance, nodeName)}+func proxmoxVMSourceID(vm models.VM) string {+ if sourceID := strings.TrimSpace(vm.ID); sourceID != "" {+ return sourceID+ }+ if vm.VMID > 0 {+ return proxmoxGuestFallbackSourceID("vm", vm.Instance, vm.Node, vm.VMID)+ }+ return strings.TrimSpace(vm.Name)+}++func proxmoxContainerSourceID(ct models.Container) string {+ if sourceID := strings.TrimSpace(ct.ID); sourceID != "" {+ return sourceID+ }+ if ct.VMID > 0 {+ return proxmoxGuestFallbackSourceID("ct", ct.Instance, ct.Node, ct.VMID)+ }+ return strings.TrimSpace(ct.Name)+}++func proxmoxGuestFallbackSourceID(kind, instance, node string, vmid int) string {+ parts := make([]string, 0, 4)+ if normalizedKind := strings.TrimSpace(kind); normalizedKind != "" {+ parts = append(parts, normalizedKind)+ }+ if normalizedInstance := strings.TrimSpace(instance); normalizedInstance != "" {+ parts = append(parts, normalizedInstance)+ }+ if normalizedNode := strings.TrimSpace(node); normalizedNode != "" {+ parts = append(parts, normalizedNode)+ }+ parts = append(parts, fmt.Sprintf("%d", vmid))+ return strings.Join(parts, ":")+}+func kubernetesClusterSourceID(cluster models.KubernetesCluster) string {if v := strings.TrimSpace(cluster.ID); v != "" {return v