Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

Audit unified AI exports

rcourtmane864682e33da
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 7c9ea1bf42..62010acff3 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -52,6 +52,7 @@ runtime cost control, and shared AI transport surfaces.
1. Update this contract when canonical AI runtime or transport entry points move
2. Keep AI runtime and shared API proof routing aligned in `registry.json`
3. Preserve explicit coverage for chat, Patrol, remediation, and cost-control behavior when AI runtime changes
+4. Preserve auditability for outbound model-bound context exports and keep the export record aligned with the prompt boundary that actually reaches the provider
## Current State
@@ -126,3 +127,8 @@ That same requirement includes `pulse_query action=config`: guest-config
payloads must carry canonical resource policy metadata, and config-fact
extraction must not persist raw guest hostnames when governed redaction covers
hostname or platform identity fields.
+Outbound model-bound context exports now also belong to this runtime
+boundary. When the AI service assembles unified-resource context for a model
+request, it must record a durable export audit with the active destination
+model and governed redaction decision instead of treating the prompt boundary
+as a transient formatting step.
diff --git a/internal/ai/kubernetes_analysis.go b/internal/ai/kubernetes_analysis.go
index 38137adb59..ca6b9d6135 100644
--- a/internal/ai/kubernetes_analysis.go
+++ b/internal/ai/kubernetes_analysis.go
@@ -54,7 +54,7 @@ func (s *Service) AnalyzeKubernetesCluster(ctx context.Context, clusterID string
Prompt: prompt,
TargetType: "k8s-cluster",
TargetID: clusterSourceID,
- })
+ }, "")
systemPrompt += "\n\n## Kubernetes Cluster Telemetry\n"
systemPrompt += buildK8sClusterContext(cluster, rs)
systemPrompt += "\n\nUse the telemetry above only. Do not request kubectl output."
diff --git a/internal/ai/resource_context.go b/internal/ai/resource_context.go
index 7310a25183..db019ec4cf 100644
--- a/internal/ai/resource_context.go
+++ b/internal/ai/resource_context.go
@@ -41,6 +41,12 @@ func (s *Service) SetUnifiedResourceProvider(urp UnifiedResourceProvider) {
// buildUnifiedResourceContext creates AI context from the unified resource model.
// This provides a cleaner, deduplicated view of infrastructure.
func (s *Service) buildUnifiedResourceContext() string {
+ return s.buildUnifiedResourceContextForModel("")
+}
+
+// buildUnifiedResourceContextForModel creates AI context from the unified resource
+// model and records an export audit when the outbound model is known.
+func (s *Service) buildUnifiedResourceContextForModel(destinationModel string) string {
s.mu.RLock()
urp := s.unifiedResourceProvider
ap := s.alertProvider
@@ -99,9 +105,11 @@ func (s *Service) buildUnifiedResourceContext() string {
for _, resource := range allResources {
byResourceID[resource.ID] = resource
}
+ sensitivityCounts := make(map[unifiedresources.ResourceSensitivity]int)
+ localOnlyCount := 0
+ var redactionHints []unifiedresources.ResourceRedactionHint
+ redactionHintSet := make(map[unifiedresources.ResourceRedactionHint]struct{})
if len(allResources) > 0 {
- sensitivityCounts := make(map[unifiedresources.ResourceSensitivity]int)
- localOnlyCount := 0
for _, resource := range allResources {
if resource.Policy == nil {
continue
@@ -110,6 +118,18 @@ func (s *Service) buildUnifiedResourceContext() string {
if resource.Policy.Routing.Scope == unifiedresources.ResourceRoutingScopeLocalOnly {
localOnlyCount++
}
+ for _, hint := range resource.Policy.Routing.Redact {
+ redactionHintSet[hint] = struct{}{}
+ }
+ }
+ if len(redactionHintSet) > 0 {
+ redactionHints = make([]unifiedresources.ResourceRedactionHint, 0, len(redactionHintSet))
+ for hint := range redactionHintSet {
+ redactionHints = append(redactionHints, hint)
+ }
+ sort.Slice(redactionHints, func(i, j int) bool {
+ return redactionHints[i] < redactionHints[j]
+ })
}
if len(sensitivityCounts) > 0 {
sections = append(sections, "\n### Data Governance")
@@ -509,6 +529,10 @@ func (s *Service) buildUnifiedResourceContext() string {
result = result[:maxContextSize] + "\n\n[... Context truncated ...]"
}
+ if strings.TrimSpace(destinationModel) != "" {
+ s.recordUnifiedResourceExport(destinationModel, result, stats, sensitivityCounts, localOnlyCount, redactionHints)
+ }
+
log.Debug().Int("unified_resource_context_size", len(result)).Msg("built unified resource context")
return result
}
diff --git a/internal/ai/resource_export.go b/internal/ai/resource_export.go
new file mode 100644
index 0000000000..0fbeda5dca
--- /dev/null
+++ b/internal/ai/resource_export.go
@@ -0,0 +1,171 @@
+package ai
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+ unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rs/zerolog/log"
+)
+
+type unifiedResourceExportDigest struct {
+ OrgID string `json:"orgId"`
+ DestinationModel string `json:"destinationModel"`
+ Summary string `json:"summary"`
+ ResourceCount int `json:"resourceCount"`
+ InfrastructureCount int `json:"infrastructureCount"`
+ WorkloadCount int `json:"workloadCount"`
+ SensitivityFloor unifiedresources.DataSensitivity `json:"sensitivityFloor"`
+ RouteDecision unifiedresources.ModelRouteDecision `json:"routeDecision"`
+}
+
+func (s *Service) recordUnifiedResourceExport(destinationModel, summary string, stats unifiedresources.ResourceStats, sensitivityCounts map[unifiedresources.ResourceSensitivity]int, localOnlyCount int, redactionHints []unifiedresources.ResourceRedactionHint) {
+ destinationModel = strings.TrimSpace(destinationModel)
+ summary = strings.TrimSpace(summary)
+ if s == nil || destinationModel == "" || summary == "" {
+ return
+ }
+
+ s.mu.RLock()
+ store := s.resourceExportStore
+ orgID := strings.TrimSpace(s.orgID)
+ storeOrgID := strings.TrimSpace(s.resourceExportStoreOrgID)
+ s.mu.RUnlock()
+
+ if store == nil || (storeOrgID != "" && storeOrgID != orgID) {
+ return
+ }
+
+ redactions := make([]string, 0, len(redactionHints))
+ for _, hint := range redactionHints {
+ redaction := strings.TrimSpace(string(hint))
+ if redaction == "" {
+ continue
+ }
+ redactions = append(redactions, redaction)
+ }
+ sort.Strings(redactions)
+ redactions = uniqueStrings(redactions)
+
+ sensitivityFloor := unifiedResourceExportSensitivityFloor(sensitivityCounts)
+ decision, reason := unifiedResourceExportDecision(sensitivityFloor, localOnlyCount, len(redactions))
+
+ infraCount := stats.ByType[unifiedresources.ResourceTypeAgent] +
+ stats.ByType[unifiedresources.ResourceTypeK8sCluster] +
+ stats.ByType[unifiedresources.ResourceTypeK8sNode]
+ workloadCount := stats.ByType[unifiedresources.ResourceTypeVM] +
+ stats.ByType[unifiedresources.ResourceTypeSystemContainer] +
+ stats.ByType[unifiedresources.ResourceTypeAppContainer] +
+ stats.ByType[unifiedresources.ResourceTypePod] +
+ stats.ByType[unifiedresources.ResourceTypeK8sDeployment]
+
+ envelope := unifiedresources.ExportEnvelope{
+ DestinationModel: destinationModel,
+ DataPayload: map[string]any{
+ "summary": summary,
+ "resourceCount": stats.Total,
+ "infrastructureCount": infraCount,
+ "workloadCount": workloadCount,
+ "localOnlyCount": localOnlyCount,
+ },
+ RouteDecision: unifiedresources.ModelRouteDecision{
+ ResourceID: "unified-resource-context",
+ OriginalExport: unifiedresources.ExportAllowed,
+ FinalDecision: decision,
+ AppliedRedactions: redactions,
+ RoutingReason: reason,
+ },
+ SensitivityFloor: sensitivityFloor,
+ }
+
+ hashInput := unifiedResourceExportDigest{
+ OrgID: orgID,
+ DestinationModel: envelope.DestinationModel,
+ Summary: summary,
+ ResourceCount: stats.Total,
+ InfrastructureCount: infraCount,
+ WorkloadCount: workloadCount,
+ SensitivityFloor: envelope.SensitivityFloor,
+ RouteDecision: envelope.RouteDecision,
+ }
+ payload, err := json.Marshal(hashInput)
+ if err != nil {
+ log.Warn().
+ Err(err).
+ Str("orgID", orgID).
+ Str("destinationModel", destinationModel).
+ Msg("failed to hash unified resource export envelope")
+ return
+ }
+
+ sum := sha256.Sum256(payload)
+ record := unifiedresources.ExportAuditRecord{
+ ID: uuid.NewString(),
+ Timestamp: time.Now().UTC(),
+ Actor: fmt.Sprintf("ai-service:%s", orgID),
+ EnvelopeHash: hex.EncodeToString(sum[:]),
+ Decision: decision,
+ Destination: destinationModel,
+ Redactions: redactions,
+ }
+ if err := store.RecordExportAudit(record); err != nil {
+ log.Warn().
+ Err(err).
+ Str("orgID", orgID).
+ Str("destinationModel", destinationModel).
+ Msg("failed to persist unified resource export audit")
+ }
+}
+
+func unifiedResourceExportSensitivityFloor(counts map[unifiedresources.ResourceSensitivity]int) unifiedresources.DataSensitivity {
+ if counts == nil {
+ return unifiedresources.SensitivityPublic
+ }
+ if counts[unifiedresources.ResourceSensitivityRestricted] > 0 {
+ return unifiedresources.SensitivityRestricted
+ }
+ if counts[unifiedresources.ResourceSensitivitySensitive] > 0 {
+ return unifiedresources.SensitivitySensitive
+ }
+ if counts[unifiedresources.ResourceSensitivityInternal] > 0 {
+ return unifiedresources.SensitivityInternal
+ }
+ return unifiedresources.SensitivityPublic
+}
+
+func unifiedResourceExportDecision(sensitivityFloor unifiedresources.DataSensitivity, localOnlyCount int, redactionCount int) (unifiedresources.ExportDecision, string) {
+ if localOnlyCount > 0 || redactionCount > 0 {
+ return unifiedresources.ExportRedacted, "governed unified resource context exported in redacted form"
+ }
+
+ switch sensitivityFloor {
+ case unifiedresources.SensitivityRestricted, unifiedresources.SensitivitySensitive:
+ return unifiedresources.ExportRedacted, "governed unified resource context exported in redacted form"
+ case unifiedresources.SensitivityInternal:
+ return unifiedresources.ExportRequiresConsent, "internal unified resource context requires export consent"
+ default:
+ return unifiedresources.ExportAllowed, "public unified resource context"
+ }
+}
+
+func uniqueStrings(values []string) []string {
+ if len(values) <= 1 {
+ return values
+ }
+ out := make([]string, 0, len(values))
+ last := ""
+ for _, value := range values {
+ if value == "" || value == last {
+ continue
+ }
+ out = append(out, value)
+ last = value
+ }
+ return out
+}
diff --git a/internal/ai/service.go b/internal/ai/service.go
index b33dedf867..de7df5763b 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -166,23 +166,25 @@ type PatrolStreamResponse struct {
// Service orchestrates AI interactions
type Service struct {
- mu sync.RWMutex
- orgID string
- persistence *config.ConfigPersistence
- provider providers.Provider
- cfg *config.AIConfig
- agentServer AgentServer
- policy CommandPolicy
- stateProvider StateProvider
- readState unifiedresources.ReadState
- alertProvider AlertProvider
- knowledgeStore *knowledge.Store
- costStore *cost.Store
- unifiedResourceProvider UnifiedResourceProvider
- patrolService *PatrolService // Background AI monitoring service
- metadataProvider MetadataProvider // Enables AI to update resource URLs
- incidentStore *memory.IncidentStore // Incident timelines for alert memory
- chatService ChatServiceProvider // Chat service for investigation orchestrator
+ mu sync.RWMutex
+ orgID string
+ persistence *config.ConfigPersistence
+ provider providers.Provider
+ cfg *config.AIConfig
+ agentServer AgentServer
+ policy CommandPolicy
+ stateProvider StateProvider
+ readState unifiedresources.ReadState
+ alertProvider AlertProvider
+ knowledgeStore *knowledge.Store
+ costStore *cost.Store
+ unifiedResourceProvider UnifiedResourceProvider
+ resourceExportStore unifiedresources.ResourceStore
+ resourceExportStoreOrgID string
+ patrolService *PatrolService // Background AI monitoring service
+ metadataProvider MetadataProvider // Enables AI to update resource URLs
+ incidentStore *memory.IncidentStore // Incident timelines for alert memory
+ chatService ChatServiceProvider // Chat service for investigation orchestrator
// Infrastructure discovery service - detects apps running on hosts
infraDiscoveryService *infradiscovery.Service
@@ -280,7 +282,7 @@ func NewService(persistence *config.ConfigPersistence, agentServer AgentServer)
}
}
- return &Service{
+ svc := &Service{
orgID: "default",
persistence: persistence,
agentServer: agentServer,
@@ -297,17 +299,67 @@ func NewService(persistence *config.ConfigPersistence, agentServer AgentServer)
providers: make(map[string]providerModelsEntry),
},
}
+
+ if persistence != nil {
+ if store, err := unifiedresources.NewSQLiteResourceStore(persistence.DataDir(), svc.orgID); err != nil {
+ log.Warn().Err(err).Str("orgID", svc.orgID).Msg("failed to initialize unified resource export store")
+ } else {
+ svc.resourceExportStore = store
+ svc.resourceExportStoreOrgID = svc.orgID
+ }
+ }
+
+ return svc
}
// SetOrgID sets the org scope used when creating approval records.
func (s *Service) SetOrgID(orgID string) {
- s.mu.Lock()
- defer s.mu.Unlock()
normalized := strings.TrimSpace(orgID)
if normalized == "" {
normalized = "default"
}
+
+ s.mu.Lock()
+ if s.orgID == normalized && s.resourceExportStore != nil {
+ s.mu.Unlock()
+ return
+ }
+
+ oldStore := s.resourceExportStore
+ persistence := s.persistence
s.orgID = normalized
+ s.resourceExportStore = nil
+ s.resourceExportStoreOrgID = ""
+ s.mu.Unlock()
+
+ if oldStore != nil {
+ if err := oldStore.Close(); err != nil {
+ log.Warn().Err(err).Str("orgID", normalized).Msg("failed to close previous unified resource export store")
+ }
+ }
+
+ if persistence == nil {
+ return
+ }
+
+ store, err := unifiedresources.NewSQLiteResourceStore(persistence.DataDir(), normalized)
+ if err != nil {
+ log.Warn().Err(err).Str("orgID", normalized).Msg("failed to initialize unified resource export store for org")
+ return
+ }
+
+ s.mu.Lock()
+ if s.orgID == normalized && s.resourceExportStore == nil {
+ s.resourceExportStore = store
+ s.resourceExportStoreOrgID = normalized
+ s.mu.Unlock()
+ return
+ }
+ s.mu.Unlock()
+
+ if err := store.Close(); err != nil {
+ log.Warn().Err(err).Str("orgID", normalized).Msg("failed to close unused unified resource export store")
+ }
}
// GetOrgID returns the org scope associated with this service instance.
@@ -949,6 +1001,9 @@ func (s *Service) Stop() {
s.StopPatrol()
s.mu.Lock()
+ store := s.resourceExportStore
+ s.resourceExportStore = nil
+ s.resourceExportStoreOrgID = ""
defer s.mu.Unlock()
if s.infraDiscoveryCancel != nil {
@@ -958,6 +1013,12 @@ func (s *Service) Stop() {
if s.discoveryService != nil {
s.discoveryService.Stop()
}
+
+ if store != nil {
+ if err := store.Close(); err != nil {
+ log.Warn().Err(err).Msg("failed to close unified resource export store")
+ }
+ }
}
// ReconfigurePatrol updates the patrol configuration without restarting
@@ -1698,7 +1759,7 @@ func (s *Service) GetDebugContext(req ExecuteRequest) map[string]interface{} {
}
// Build and include the system prompt
- systemPrompt := s.buildSystemPrompt(req)
+ systemPrompt := s.buildSystemPrompt(req, "")
result["system_prompt_length"] = len(systemPrompt)
result["system_prompt"] = systemPrompt
@@ -1877,7 +1938,7 @@ func (s *Service) Execute(ctx context.Context, req ExecuteRequest) (*ExecuteResp
// Build the system prompt
systemPrompt := req.SystemPrompt
if systemPrompt == "" {
- systemPrompt = s.buildSystemPrompt(req)
+ systemPrompt = s.buildSystemPrompt(req, modelString)
}
// Check if agent is available for this target
@@ -2077,7 +2138,7 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
// Build the system prompt
systemPrompt := req.SystemPrompt
if systemPrompt == "" {
- systemPrompt = s.buildSystemPrompt(req)
+ systemPrompt = s.buildSystemPrompt(req, modelString)
}
// Debug log the system prompt length and key sections
@@ -3838,7 +3899,7 @@ func (s *Service) RunCommand(ctx context.Context, req RunCommandRequest) (*RunCo
}
// buildSystemPrompt creates the system prompt based on the request context
-func (s *Service) buildSystemPrompt(req ExecuteRequest) string {
+func (s *Service) buildSystemPrompt(req ExecuteRequest, destinationModel string) string {
prompt := `You are Pulse's diagnostic assistant for Proxmox, Docker, and Kubernetes homelabs.
## Command Approval
@@ -3895,7 +3956,11 @@ Latest version: https://api.github.com/repos/rcourtman/Pulse/releases/latest`
s.mu.RUnlock()
if hasUnifiedResourceProvider {
- prompt += s.buildUnifiedResourceContext()
+ if strings.TrimSpace(destinationModel) != "" {
+ prompt += s.buildUnifiedResourceContextForModel(destinationModel)
+ } else {
+ prompt += s.buildUnifiedResourceContext()
+ }
} else {
log.Warn().Msg("AI context: unified resource provider not available, infrastructure context will be limited")
}
diff --git a/internal/ai/service_extended_test.go b/internal/ai/service_extended_test.go
index 7f7458f48d..cd20ed589a 100644
--- a/internal/ai/service_extended_test.go
+++ b/internal/ai/service_extended_test.go
@@ -2874,7 +2874,7 @@ func TestService_FindingContextInSystemPrompt(t *testing.T) {
svc.enrichRequestFromFinding(&req)
// Build the system prompt
- prompt := svc.buildSystemPrompt(req)
+ prompt := svc.buildSystemPrompt(req, "")
// Verify the prompt includes routing context
if !strings.Contains(prompt, "minipc") {
diff --git a/internal/ai/service_test.go b/internal/ai/service_test.go
index 35e5ed80c8..9cf4d5d369 100644
--- a/internal/ai/service_test.go
+++ b/internal/ai/service_test.go
@@ -7,6 +7,7 @@ import (
"os"
"strings"
"testing"
+ "time"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
@@ -600,6 +601,34 @@ func TestService_ExecuteStream(t *testing.T) {
persistence := config.NewConfigPersistence(tmpDir)
svc := NewService(persistence, nil)
svc.cfg = &config.AIConfig{Enabled: true}
+ if svc.resourceExportStore != nil {
+ _ = svc.resourceExportStore.Close()
+ }
+ svc.resourceExportStore = unifiedresources.NewMemoryStore()
+ svc.resourceExportStoreOrgID = svc.orgID
+
+ resource := unifiedresources.Resource{
+ ID: "node-1",
+ Name: "test-node",
+ Type: unifiedresources.ResourceTypeAgent,
+ Status: unifiedresources.StatusOnline,
+ }
+ svc.unifiedResourceProvider = &mockUnifiedResourceProvider{
+ getAllFunc: func() []unifiedresources.Resource {
+ return []unifiedresources.Resource{resource}
+ },
+ getInfrastructureFunc: func() []unifiedresources.Resource {
+ return []unifiedresources.Resource{resource}
+ },
+ getStatsFunc: func() unifiedresources.ResourceStats {
+ return unifiedresources.ResourceStats{
+ Total: 1,
+ ByType: map[unifiedresources.ResourceType]int{
+ unifiedresources.ResourceTypeAgent: 1,
+ },
+ }
+ },
+ }
mockP := &mockProvider{
chatFunc: func(ctx context.Context, req providers.ChatRequest) (*providers.ChatResponse, error) {
@@ -639,6 +668,20 @@ func TestService_ExecuteStream(t *testing.T) {
if !foundContent {
t.Error("Expected content event in stream")
}
+
+ audits, err := svc.resourceExportStore.GetExportAudits(time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetExportAudits failed: %v", err)
+ }
+ if len(audits) != 1 {
+ t.Fatalf("expected 1 export audit, got %d", len(audits))
+ }
+ if audits[0].Destination != "anthropic:test-model" {
+ t.Fatalf("expected destination anthropic:test-model, got %q", audits[0].Destination)
+ }
+ if audits[0].EnvelopeHash == "" {
+ t.Fatal("expected export envelope hash to be recorded")
+ }
}
func TestService_Execute_WithTool(t *testing.T) {