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
Hydrate Assistant resource state context
rcourtman8db5bd39f791
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex aae0e35f06..b2db89ad12 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -202,6 +202,12 @@ runtime cost control, and shared AI transport surfaces.unified-resource resolution and policy presentation helpers that governmention prefetch and provider-bound redaction; that context remainsmodel-only handling guidance, not saved user text or disclosure authority.+ Assistant runtime may also hydrate current canonical resource-state context+ for those handoff resources, including compact status, freshness,+ source-health, metric, incident, and governed-capability summaries from the+ unified-resource model. That state snapshot remains model-only read-only+ infrastructure context, must honor the same policy/redaction boundary before+ provider transport, and must not grant approval or execution authority.Assistant runtime may also hydrate canonicalrelationship context for those handoff resources through`FormatResourceRelationshipContext(...)` and canonical parent-edge synthesis,diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 9df3f1d036..4d767c9738 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -773,7 +773,12 @@ the canonical monitored-system blocked payload.resolution and shared policy presentation helpers, but the resulting handlingguidance is read-only, model-only context and must not become saved user text,disclosure authority, or action authority. Chat execution may also hydrate- canonical relationship context for those resources through shared+ current canonical resource-state context for those resources, including+ compact status, freshness, source-health, metric, incident, and+ governed-capability summaries from the unified-resource model, but that+ snapshot is model-only read-only infrastructure context and must not become+ saved user text, disclosure authority, or action authority. Chat execution+ may also hydrate canonical relationship context for those resources through sharedunified-resource relationship presentation and parent-edge synthesis, buttopology context is read-only and must not become saved user text or actionauthority. Chat execution may also hydrate recent changes for those handoffdiff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.mdindex 7e4b45afed..cd713747bb 100644--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md@@ -114,10 +114,12 @@ Patrol-specific presentation helpers.posture, and terminal success/failure without treating approval as executionauthority or exposing raw command/execution payloads. Assistant may alsoenrich that same handoff with refreshed unified finding and- investigation-record state, canonical resource-policy guidance, canonical+ investigation-record state, canonical resource-policy guidance, current+ canonical resource-state and capability context, canonicalresource-relationship context, and recent canonical resource-timeline changes- for explanation; Assistant resolves those timeline lookups through the- current canonical unified-resource model before falling back to handoff IDs.+ for explanation; Assistant resolves those state, topology, and timeline+ lookups through the current canonical unified-resource model before falling+ back to handoff IDs where compatibility requires it.If the referenced finding is no longer current,Assistant must drop the stored handoff instead of continuing from stalePatrol context. Assistant handoff context must also carry the unifieddiff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex a1ab2b9093..cae7e5127f 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -153,7 +153,7 @@ controls as normal product settings.behavior changes. Hosted commercial URL overrides must remain absoluteHTTP(S) URLs, with plain HTTP limited to loopback development origins.8. Keep the Data Handling settings surface neutral and non-commercial: it may show resource policy posture, local-only counts, and redaction coverage, but it must not advertise trials, upgrades, paid plans, or monitoring limits.-9. Keep operator-facing Data Handling posture aligned with runtime AI/context enforcement: `local-only` resource details must not be sent to external model prompts, and sensitive free-form alert, tool-result, investigation, handoff context, and any retained legacy managed-model compatibility text must use the shared resource-policy redaction helper before leaving the local trust boundary. Assistant handoffs may surface canonical policy handling guidance for product-originated resources, but that guidance is model-only context and must not become disclosure authority. All provider-bound AI requests to non-local models must use the shared resource-policy sanitizer immediately before transport so later agentic turns cannot bypass the advertised handling posture.+9. Keep operator-facing Data Handling posture aligned with runtime AI/context enforcement: `local-only` resource details must not be sent to external model prompts, and sensitive free-form alert, tool-result, investigation, handoff context, and any retained legacy managed-model compatibility text must use the shared resource-policy redaction helper before leaving the local trust boundary. Assistant handoffs may surface canonical policy handling guidance and current resource-state summaries for product-originated resources, but that guidance and state are model-only context and must not become disclosure authority. All provider-bound AI requests to non-local models must use the shared resource-policy sanitizer immediately before transport so later agentic turns cannot bypass the advertised handling posture.10. Keep the canonical and frontend-served privacy disclosures aligned withthe actual AI transport boundary: self-managed installs must describe localproviders as staying on the operator network, non-local providers as directdiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 374d8565ef..d6a3b8199b 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -426,7 +426,11 @@ bypass the API fail-closed execution gate.approval references carried by that handoff are also adjacent AI/runtimereview metadata only. Unified finding lifecycle facts carried by the samehandoff remain Patrol/AI review metadata and must not become backup recency,- restore support, or storage-local lifecycle state.+ restore support, or storage-local lifecycle state. Current resource-state,+ source-health, incident, metric, and capability summaries carried by that+ handoff are also adjacent AI/runtime context and must not become backup+ freshness, restore eligibility, recovery execution authority, or+ storage-local capability truth.storage and recovery surfaces must not reinterpret approval IDs, action IDs,action lifecycle state, fix IDs, risk, or target labels as restore support,backup freshness, recovery execution authority, or a storage-local approvaldiff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex 4d8b6db775..c96e86c67d 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -1000,6 +1000,14 @@ canonical parent edge through `ResourceRelationshipsWithCanonicalParent(...)`,and call `FormatResourceRelationshipContext(...)` rather than rebuildingrelationship markdown in chat or Patrol-local helpers. The resulting topologyblock remains model-only explanation context, not action authority.+Assistant finding handoffs are also part of the canonical resource-state+contract: when the AI runtime needs current state for a product-originated+handoff resource, it should resolve the canonical unified resource and summarize+the owned status, freshness, source-health, metrics, incidents, and governed+capabilities from `unifiedresources.Resource` instead of rebuilding a+Patrol-local or chat-local resource model. That state block remains model-only+read-only infrastructure context, and capability names or approval policies in+that snapshot do not grant execution authority.Assistant finding handoffs are also part of the canonical resource-timelinecontract: when recent-change context is hydrated for a handoff resource, chatexecution should resolve the resource through the current unified-resourcediff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.goindex 924d9a7a6a..324072bfe7 100644--- a/internal/ai/chat/service.go+++ b/internal/ai/chat/service.go@@ -534,6 +534,7 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbachandoffResourceProvider := s.unifiedResourceProviders.mu.RUnlock()handoffContext = mergeHandoffResourcePolicyContext(handoffContext, handoffResources, handoffResourceProvider)+ handoffContext = mergeHandoffResourceStateContext(handoffContext, handoffResources, handoffResourceProvider)handoffContext = mergeHandoffResourceRelationshipContext(handoffContext, handoffResources, handoffResourceProvider)handoffContext = mergeHandoffResourceTimelineContext(handoffContext, handoffResources, handoffResourceProvider, s.actionAuditStore, time.Now())handoffContext = mergeHandoffActionContext(handoffContext, handoffActions)@@ -865,28 +866,14 @@ func mergeHandoffResourcePolicyContext(handoffContext string, handoffResources [}func buildHandoffResourcePolicyContext(handoffResources []HandoffResource, provider tools.UnifiedResourceProvider) string {- resources := normalizeHandoffResources(handoffResources)- if len(resources) == 0 || provider == nil {+ resources := canonicalHandoffResources(handoffResources, provider)+ if len(resources) == 0 {return ""}var b strings.Builder- seen := make(map[string]struct{}, len(resources))count := 0- for _, handoffResource := range resources {- resource, ok := tools.CanonicalHandoffUnifiedResource(provider, handoffResource.ID, handoffResource.Name, handoffResource.Type, handoffResource.Node)- if !ok {- continue- }- key := strings.ToLower(strings.TrimSpace(string(resource.Type)) + "\x00" + strings.TrimSpace(resource.ID))- if key == "\x00" {- continue- }- if _, ok := seen[key]; ok {- continue- }- seen[key] = struct{}{}-+ for _, resource := range resources {policy, aiSafeSummary := unifiedresources.CanonicalGovernanceMetadata(&resource)if policy == nil && strings.TrimSpace(aiSafeSummary) == "" {continue@@ -930,6 +917,61 @@ func buildHandoffResourcePolicyContext(handoffResources []HandoffResource, provireturn strings.TrimSpace(b.String())}+func mergeHandoffResourceStateContext(handoffContext string, handoffResources []HandoffResource, provider tools.UnifiedResourceProvider) string {+ stateContext := buildHandoffResourceStateContext(handoffResources, provider)+ switch {+ case strings.TrimSpace(handoffContext) == "":+ return stateContext+ case stateContext == "":+ return strings.TrimSpace(handoffContext)+ default:+ return strings.TrimSpace(handoffContext) + "\n\n" + stateContext+ }+}++func buildHandoffResourceStateContext(handoffResources []HandoffResource, provider tools.UnifiedResourceProvider) string {+ resources := canonicalHandoffResources(handoffResources, provider)+ if len(resources) == 0 {+ return ""+ }++ var b strings.Builder+ b.WriteString("[Resource State Context]")+ for idx, resource := range resources {+ labelPrefix := "Resource State"+ if len(resources) > 1 {+ labelPrefix = fmt.Sprintf("Resource State %d", idx+1)+ }+ policy, aiSafeSummary := unifiedresources.CanonicalGovernanceMetadata(&resource)+ label := unifiedresources.ResourcePolicyLabel(resource.Name, aiSafeSummary, policy)+ if label == "" {+ label = "resource"+ }+ resourceType := strings.TrimSpace(string(unifiedresources.ContractResourceType(resource)))+ if resourceType == "" {+ resourceType = strings.TrimSpace(string(resource.Type))+ }++ appendHandoffContextLine(&b, labelPrefix, label)+ appendHandoffContextLine(&b, labelPrefix+" ID", formatHandoffResourceID(resource, policy))+ appendHandoffContextLine(&b, labelPrefix+" Type", resourceType)+ appendHandoffContextLine(&b, labelPrefix+" Status", string(resource.Status))+ appendHandoffContextLine(&b, labelPrefix+" Last Seen At", formatHandoffContextTime(resource.LastSeen))+ appendHandoffContextLine(&b, labelPrefix+" Updated At", formatHandoffContextTime(resource.UpdatedAt))+ appendHandoffContextLine(&b, labelPrefix+" Sources", formatHandoffResourceSources(resource))+ appendHandoffContextLine(&b, labelPrefix+" Source Health", formatHandoffResourceSourceStatus(resource))+ appendHandoffContextLine(&b, labelPrefix+" Metrics", formatHandoffResourceMetrics(resource.Metrics))+ appendHandoffContextLine(&b, labelPrefix+" Parent", formatHandoffResourceParent(resource, policy))+ if resource.ChildCount > 0 {+ appendHandoffContextLine(&b, labelPrefix+" Child Count", fmt.Sprintf("%d", resource.ChildCount))+ }+ appendHandoffContextLine(&b, labelPrefix+" Incident Summary", formatHandoffResourceIncidentSummary(resource, policy))+ appendHandoffContextLine(&b, labelPrefix+" Capabilities", formatHandoffResourceCapabilities(resource, policy, 4))+ }+ appendHandoffContextLine(&b, "Resource State Boundary", "Current resource state, source health, incidents, metrics, and capabilities are read-only canonical infrastructure context; they are not approval or execution authority.")+ return strings.TrimSpace(b.String())+}+func mergeHandoffResourceRelationshipContext(handoffContext string, handoffResources []HandoffResource, provider tools.UnifiedResourceProvider) string {relationshipContext := buildHandoffResourceRelationshipContext(handoffResources, provider)switch {@@ -943,28 +985,14 @@ func mergeHandoffResourceRelationshipContext(handoffContext string, handoffResou}func buildHandoffResourceRelationshipContext(handoffResources []HandoffResource, provider tools.UnifiedResourceProvider) string {- resources := normalizeHandoffResources(handoffResources)- if len(resources) == 0 || provider == nil {+ resources := canonicalHandoffResources(handoffResources, provider)+ if len(resources) == 0 {return ""}var b strings.Builder- seen := make(map[string]struct{}, len(resources))count := 0- for _, handoffResource := range resources {- resource, ok := tools.CanonicalHandoffUnifiedResource(provider, handoffResource.ID, handoffResource.Name, handoffResource.Type, handoffResource.Node)- if !ok {- continue- }- key := strings.ToLower(strings.TrimSpace(string(resource.Type)) + "\x00" + strings.TrimSpace(resource.ID))- if key == "\x00" {- continue- }- if _, ok := seen[key]; ok {- continue- }- seen[key] = struct{}{}-+ for _, resource := range resources {resource.Relationships = unifiedresources.ResourceRelationshipsWithCanonicalParent(resource)relationshipContext := strings.TrimSpace(unifiedresources.FormatResourceRelationshipContext(&resource, 3))if relationshipContext == "" {@@ -1105,6 +1133,32 @@ func canonicalHandoffTimelineResourceIDs(handoffResources []HandoffResource, proreturn ids}+func canonicalHandoffResources(handoffResources []HandoffResource, provider tools.UnifiedResourceProvider) []unifiedresources.Resource {+ resources := normalizeHandoffResources(handoffResources)+ if len(resources) == 0 || provider == nil {+ return nil+ }++ out := make([]unifiedresources.Resource, 0, len(resources))+ seen := make(map[string]struct{}, len(resources))+ for _, handoffResource := range resources {+ resource, ok := tools.CanonicalHandoffUnifiedResource(provider, handoffResource.ID, handoffResource.Name, handoffResource.Type, handoffResource.Node)+ if !ok {+ continue+ }+ key := strings.ToLower(strings.TrimSpace(string(resource.Type)) + "\x00" + strings.TrimSpace(resource.ID))+ if key == "\x00" {+ continue+ }+ if _, ok := seen[key]; ok {+ continue+ }+ seen[key] = struct{}{}+ out = append(out, resource)+ }+ return out+}+func handoffResourceTimelineChangeKey(change unifiedresources.ResourceChange) string {if id := strings.TrimSpace(change.ID); id != "" {return id@@ -1285,12 +1339,266 @@ func hydrateHandoffActionAudit(action *HandoffAction, store unifiedresources.Res}func formatHandoffActionTime(value time.Time) string {+ return formatHandoffContextTime(value)+}++func formatHandoffContextTime(value time.Time) string {if value.IsZero() {return ""}return value.UTC().Format(time.RFC3339)}+func formatHandoffResourceSources(resource unifiedresources.Resource) string {+ seen := make(map[string]struct{}, len(resource.Sources)+len(resource.SourceStatus))+ sources := make([]string, 0, len(resource.Sources)+len(resource.SourceStatus))+ for _, source := range resource.Sources {+ name := strings.TrimSpace(string(source))+ if name == "" {+ continue+ }+ key := strings.ToLower(name)+ if _, ok := seen[key]; ok {+ continue+ }+ seen[key] = struct{}{}+ sources = append(sources, name)+ }+ for source := range resource.SourceStatus {+ name := strings.TrimSpace(string(source))+ if name == "" {+ continue+ }+ key := strings.ToLower(name)+ if _, ok := seen[key]; ok {+ continue+ }+ seen[key] = struct{}{}+ sources = append(sources, name)+ }+ sort.Strings(sources)+ return strings.Join(sources, ", ")+}++func formatHandoffResourceSourceStatus(resource unifiedresources.Resource) string {+ if len(resource.SourceStatus) == 0 {+ return ""+ }++ sources := make([]string, 0, len(resource.SourceStatus))+ for source := range resource.SourceStatus {+ if name := strings.TrimSpace(string(source)); name != "" {+ sources = append(sources, name)+ }+ }+ sort.Strings(sources)++ parts := make([]string, 0, len(sources))+ for _, sourceName := range sources {+ status := resource.SourceStatus[unifiedresources.DataSource(sourceName)]+ state := strings.TrimSpace(status.Status)+ if state == "" && status.LastSeen.IsZero() {+ continue+ }+ if state == "" {+ state = "reported"+ }+ part := sourceName + ": " + state+ if lastSeen := formatHandoffContextTime(status.LastSeen); lastSeen != "" {+ part += " (last seen " + lastSeen + ")"+ }+ parts = append(parts, part)+ }+ return strings.Join(parts, "; ")+}++func formatHandoffResourceMetrics(metrics *unifiedresources.ResourceMetrics) string {+ if metrics == nil {+ return ""+ }+ values := []struct {+ label string+ value *unifiedresources.MetricValue+ }{+ {label: "cpu", value: metrics.CPU},+ {label: "memory", value: metrics.Memory},+ {label: "disk", value: metrics.Disk},+ {label: "network in", value: metrics.NetIn},+ {label: "network out", value: metrics.NetOut},+ }++ parts := make([]string, 0, len(values))+ for _, item := range values {+ if formatted := formatHandoffMetricValue(item.value); formatted != "" {+ parts = append(parts, item.label+" "+formatted)+ }+ }+ return strings.Join(parts, ", ")+}++func formatHandoffMetricValue(value *unifiedresources.MetricValue) string {+ if value == nil {+ return ""+ }+ if value.Percent > 0 {+ return trimHandoffFloat(value.Percent) + "%"+ }+ unit := strings.TrimSpace(value.Unit)+ if value.Value != 0 {+ if unit != "" {+ return trimHandoffFloat(value.Value) + " " + unit+ }+ return trimHandoffFloat(value.Value)+ }+ if value.Used != nil && value.Total != nil && *value.Total > 0 {+ return fmt.Sprintf("%d/%d", *value.Used, *value.Total)+ }+ return ""+}++func trimHandoffFloat(value float64) string {+ return strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.1f", value), "0"), ".")+}++func formatHandoffResourceParent(resource unifiedresources.Resource, policy *unifiedresources.ResourcePolicy) string {+ parent := strings.TrimSpace(resource.ParentName)+ if parent != "" {+ return unifiedresources.ResourcePolicyRedactedValue(parent, policy,+ unifiedresources.ResourceRedactionHostname,+ unifiedresources.ResourceRedactionAlias,+ unifiedresources.ResourceRedactionPlatformID,+ )+ }+ parentID := ""+ if resource.ParentID != nil {+ parentID = strings.TrimSpace(*resource.ParentID)+ }+ if parentID == "" {+ return ""+ }+ return unifiedresources.ResourcePolicyRedactedValue(parentID, policy,+ unifiedresources.ResourceRedactionAlias,+ unifiedresources.ResourceRedactionPlatformID,+ unifiedresources.ResourceRedactionPath,+ )+}++func formatHandoffResourceID(resource unifiedresources.Resource, policy *unifiedresources.ResourcePolicy) string {+ return unifiedresources.ResourcePolicyRedactedValue(resource.ID, policy,+ unifiedresources.ResourceRedactionAlias,+ unifiedresources.ResourceRedactionHostname,+ unifiedresources.ResourceRedactionPlatformID,+ unifiedresources.ResourceRedactionPath,+ )+}++func formatHandoffResourceIncidentSummary(resource unifiedresources.Resource, policy *unifiedresources.ResourcePolicy) string {+ parts := make([]string, 0, 4)+ if resource.IncidentCount > 0 {+ parts = append(parts, fmt.Sprintf("count %d", resource.IncidentCount))+ }+ if severity := strings.TrimSpace(string(resource.IncidentSeverity)); severity != "" {+ parts = append(parts, "severity "+severity)+ }+ if summary := strings.TrimSpace(resource.IncidentSummary); summary != "" {+ if safeSummary := formatHandoffResourceFreeText(summary, resource, policy); safeSummary != "" {+ parts = append(parts, safeSummary)+ }+ }+ if action := strings.TrimSpace(resource.IncidentAction); action != "" {+ if safeAction := formatHandoffResourceFreeText(action, resource, policy); safeAction != "" {+ parts = append(parts, "action "+safeAction)+ }+ }+ for idx, incident := range resource.Incidents {+ if idx >= 2 {+ break+ }+ summary := strings.TrimSpace(incident.Summary)+ if summary == "" && strings.TrimSpace(incident.Code) == "" {+ continue+ }+ item := formatHandoffResourceFreeText(summary, resource, policy)+ if item == "" {+ item = strings.TrimSpace(incident.Code)+ } else if code := strings.TrimSpace(incident.Code); code != "" {+ item += " (" + code + ")"+ }+ if severity := strings.TrimSpace(string(incident.Severity)); severity != "" {+ item += " severity " + severity+ }+ parts = append(parts, item)+ }+ return strings.Join(parts, "; ")+}++func formatHandoffResourceCapabilities(resource unifiedresources.Resource, policy *unifiedresources.ResourcePolicy, limit int) string {+ if len(resource.Capabilities) == 0 {+ return ""+ }+ if limit <= 0 {+ limit = len(resource.Capabilities)+ }++ seen := make(map[string]struct{}, len(resource.Capabilities))+ parts := make([]string, 0, min(limit, len(resource.Capabilities)))+ for _, capability := range resource.Capabilities {+ name := strings.TrimSpace(capability.Name)+ if name == "" {+ continue+ }+ key := strings.ToLower(name + "\x00" + strings.TrimSpace(string(capability.Type)))+ if _, ok := seen[key]; ok {+ continue+ }+ seen[key] = struct{}{}++ qualifiers := make([]string, 0, 2)+ if capabilityType := strings.TrimSpace(string(capability.Type)); capabilityType != "" {+ qualifiers = append(qualifiers, capabilityType)+ }+ if approvalLevel := strings.TrimSpace(string(capability.MinimumApprovalLevel)); approvalLevel != "" {+ qualifiers = append(qualifiers, "approval "+approvalLevel)+ }++ part := name+ if len(qualifiers) > 0 {+ part += " (" + strings.Join(qualifiers, "; ") + ")"+ }+ if description := strings.TrimSpace(capability.Description); description != "" {+ if safeDescription := formatHandoffResourceFreeText(description, resource, policy); safeDescription != "" {+ part += ": " + safeDescription+ }+ }+ parts = append(parts, part)+ if len(parts) >= limit {+ break+ }+ }+ if len(parts) == 0 {+ return ""+ }+ if remaining := len(resource.Capabilities) - len(parts); remaining > 0 {+ parts = append(parts, fmt.Sprintf("%d more", remaining))+ }+ return strings.Join(parts, "; ")+}++func formatHandoffResourceFreeText(value string, resource unifiedresources.Resource, policy *unifiedresources.ResourcePolicy) string {+ value = strings.TrimSpace(value)+ if value == "" {+ return ""+ }+ redacted := strings.TrimSpace(unifiedresources.ResourcePolicyRedactedText(value, resource))+ if redacted == "" {+ return ""+ }+ if unifiedresources.ResourcePolicyRequiresGovernedSummary(policy) && redacted == value {+ return ""+ }+ return redacted+}+func appendHandoffContextLine(b *strings.Builder, label, value string) {value = strings.TrimSpace(value)if value == "" {diff --git a/internal/ai/chat/service_execute_additional_test.go b/internal/ai/chat/service_execute_additional_test.goindex 0394796ba1..0296e5266a 100644--- a/internal/ai/chat/service_execute_additional_test.go+++ b/internal/ai/chat/service_execute_additional_test.go@@ -219,7 +219,38 @@ func TestService_ExecuteStream_HandoffContextIsModelOnly(t *testing.T) {t.Fatalf("RecordChange failed: %v", err)}- executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})+ unifiedProvider := handoffUnifiedProvider{resources: map[unifiedresources.ResourceType][]unifiedresources.Resource{+ unifiedresources.ResourceTypeVM: {{+ ID: "vm-100",+ Type: unifiedresources.ResourceTypeVM,+ Name: "web-server",+ Status: unifiedresources.StatusWarning,+ LastSeen: actionNow.Add(-5 * time.Minute),+ UpdatedAt: actionNow.Add(-2 * time.Minute),+ Sources: []unifiedresources.DataSource{unifiedresources.SourceProxmox, unifiedresources.SourceAgent},+ SourceStatus: map[unifiedresources.DataSource]unifiedresources.SourceStatus{+ unifiedresources.SourceAgent: {Status: "online", LastSeen: actionNow.Add(-5 * time.Minute)},+ unifiedresources.SourceProxmox: {Status: "stale", LastSeen: actionNow.Add(-20 * time.Minute), Error: "raw provider endpoint unavailable"},+ },+ Metrics: &unifiedresources.ResourceMetrics{+ CPU: &unifiedresources.MetricValue{Percent: 91.4},+ Memory: &unifiedresources.MetricValue{Percent: 88},+ },+ ParentName: "pve-1",+ ChildCount: 1,+ IncidentCount: 1,+ IncidentSummary: "CPU saturation after backup job",+ Capabilities: []unifiedresources.ResourceCapability{{+ Name: "restart",+ Type: unifiedresources.CapabilityTypeCommon,+ Description: "Restart the workload service",+ MinimumApprovalLevel: unifiedresources.ApprovalAdmin,+ InternalHandler: "internal-restart-handler",+ }},+ }},+ }}++ executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{UnifiedResourceProvider: unifiedProvider})var capturedMessages []providers.Messageprovider := &stubServiceProvider{streamFn: func(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {@@ -238,13 +269,14 @@ func TestService_ExecuteStream_HandoffContextIsModelOnly(t *testing.T) {loop := NewAgenticLoop(provider, executor, "system")svc := &Service{- cfg: &config.AIConfig{ChatModel: "openai:test"},- sessions: store,- executor: executor,- agenticLoop: loop,- provider: provider,- started: true,- actionAuditStore: timelineStore,+ cfg: &config.AIConfig{ChatModel: "openai:test"},+ sessions: store,+ executor: executor,+ agenticLoop: loop,+ provider: provider,+ started: true,+ actionAuditStore: timelineStore,+ unifiedResourceProvider: unifiedProvider,}req := ExecuteRequest{@@ -295,6 +327,9 @@ func TestService_ExecuteStream_HandoffContextIsModelOnly(t *testing.T) {if strings.Contains(stored[0].Content, "Recent Changes Across Infrastructure") {t.Fatalf("stored user message should not include timeline context: %q", stored[0].Content)}+ if strings.Contains(stored[0].Content, "Resource State Context") {+ t.Fatalf("stored user message should not include resource state context: %q", stored[0].Content)+ }storedFindingID, err := store.GetModelHandoffFindingID("sess-handoff")if err != nil {t.Fatalf("GetModelHandoffFindingID failed: %v", err)@@ -322,6 +357,27 @@ func TestService_ExecuteStream_HandoffContextIsModelOnly(t *testing.T) {if !strings.Contains(modelUserContent, "Action Reference Approval Status: pending") {t.Fatalf("model user content missing approval status: %q", modelUserContent)}+ if !strings.Contains(modelUserContent, "[Resource State Context]") {+ t.Fatalf("model user content missing resource state context: %q", modelUserContent)+ }+ if !strings.Contains(modelUserContent, "Resource State Status: warning") {+ t.Fatalf("model user content missing current resource status: %q", modelUserContent)+ }+ if !strings.Contains(modelUserContent, "Resource State Source Health: agent: online") {+ t.Fatalf("model user content missing canonical source health: %q", modelUserContent)+ }+ if !strings.Contains(modelUserContent, "Resource State Metrics: cpu 91.4%, memory 88%") {+ t.Fatalf("model user content missing canonical metric summary: %q", modelUserContent)+ }+ if !strings.Contains(modelUserContent, "Resource State Incident Summary: count 1") {+ t.Fatalf("model user content missing resource incident summary: %q", modelUserContent)+ }+ if !strings.Contains(modelUserContent, "Resource State Capabilities: restart (common; approval admin)") {+ t.Fatalf("model user content missing governed capability summary: %q", modelUserContent)+ }+ if !strings.Contains(modelUserContent, "Resource State Boundary: Current resource state, source health, incidents, metrics, and capabilities are read-only canonical infrastructure context") {+ t.Fatalf("model user content missing resource state boundary: %q", modelUserContent)+ }if !strings.Contains(modelUserContent, "Action Reference Action ID: act-handoff-123") {t.Fatalf("model user content missing canonical action id: %q", modelUserContent)}@@ -352,7 +408,7 @@ func TestService_ExecuteStream_HandoffContextIsModelOnly(t *testing.T) {if !strings.Contains(modelUserContent, "### Recent Changes Across Infrastructure") {t.Fatalf("model user content missing timeline context: %q", modelUserContent)}- if !strings.Contains(modelUserContent, "vm-100: **State transition** running") {+ if !strings.Contains(modelUserContent, "redacted by policy: **State transition** running") {t.Fatalf("model user content missing canonical timeline summary: %q", modelUserContent)}if !strings.Contains(modelUserContent, "Timeline Boundary: Recent changes are read-only canonical resource timeline context") {@@ -361,6 +417,9 @@ func TestService_ExecuteStream_HandoffContextIsModelOnly(t *testing.T) {if strings.Contains(modelUserContent, "systemctl restart workload.service") {t.Fatalf("model user content must not infer raw command text: %q", modelUserContent)}+ if strings.Contains(modelUserContent, "internal-restart-handler") || strings.Contains(modelUserContent, "raw provider endpoint unavailable") {+ t.Fatalf("model user content leaked raw provider execution detail: %q", modelUserContent)+ }}func TestService_ExecuteStream_HandoffResourcePolicyContextIsModelOnly(t *testing.T) {@@ -782,6 +841,91 @@ func TestService_ExecuteStream_ReusesModelHandoffContextAcrossFollowUps(t *testi}}+func TestBuildHandoffResourceStateContextUsesCanonicalResourceState(t *testing.T) {+ now := time.Date(2026, 5, 6, 14, 0, 0, 0, time.UTC)+ parentID := "cluster:production"+ provider := handoffUnifiedProvider{resources: map[unifiedresources.ResourceType][]unifiedresources.Resource{+ unifiedresources.ResourceTypeAgent: {{+ ID: "agent:pve-1",+ Type: unifiedresources.ResourceTypeAgent,+ Name: "pve-1",+ Status: unifiedresources.StatusWarning,+ LastSeen: now.Add(-3 * time.Minute),+ UpdatedAt: now.Add(-1 * time.Minute),+ Sources: []unifiedresources.DataSource{unifiedresources.SourceAgent, unifiedresources.SourceProxmox},+ SourceStatus: map[unifiedresources.DataSource]unifiedresources.SourceStatus{+ unifiedresources.SourceAgent: {Status: "online", LastSeen: now.Add(-3 * time.Minute)},+ unifiedresources.SourceProxmox: {Status: "stale", LastSeen: now.Add(-15 * time.Minute), Error: "ssh://[email protected]/private"},+ },+ Metrics: &unifiedresources.ResourceMetrics{+ CPU: &unifiedresources.MetricValue{Percent: 92.5},+ Memory: &unifiedresources.MetricValue{Percent: 81},+ Disk: &unifiedresources.MetricValue{Percent: 71.2},+ },+ ParentID: &parentID,+ ParentName: "production-cluster",+ ChildCount: 2,+ IncidentCount: 1,+ IncidentSummary: "pve-1 is saturated after backup traffic",+ Incidents: []unifiedresources.ResourceIncident{{+ NativeID: "native-secret-incident",+ Code: "cpu_saturation",+ Summary: "CPU saturation remains elevated",+ }},+ Capabilities: []unifiedresources.ResourceCapability{{+ Name: "restart",+ Type: unifiedresources.CapabilityTypeCommon,+ Description: "Restart the workload",+ MinimumApprovalLevel: unifiedresources.ApprovalAdmin,+ InternalHandler: "internal-restart-handler",+ Params: []unifiedresources.CapabilityParam{{+ Name: "token",+ Type: "string",+ IsSensitive: true,+ DefaultValue: "secret-token",+ }},+ }},+ }},+ }}++ contextText := buildHandoffResourceStateContext([]HandoffResource{{+ Name: "pve-1",+ Type: "agent",+ }}, provider)+ for _, expected := range []string{+ "[Resource State Context]",+ "Resource State: pve-1",+ "Resource State ID: agent:pve-1",+ "Resource State Type: agent",+ "Resource State Status: warning",+ "Resource State Last Seen At: 2026-05-06T13:57:00Z",+ "Resource State Updated At: 2026-05-06T13:59:00Z",+ "Resource State Sources: agent, proxmox",+ "Resource State Source Health: agent: online",+ "proxmox: stale",+ "Resource State Metrics: cpu 92.5%, memory 81%, disk 71.2%",+ "Resource State Parent: production-cluster",+ "Resource State Child Count: 2",+ "Resource State Incident Summary: count 1; pve-1 is saturated after backup traffic; CPU saturation remains elevated (cpu_saturation)",+ "Resource State Capabilities: restart (common; approval admin): Restart the workload",+ "Resource State Boundary: Current resource state, source health, incidents, metrics, and capabilities are read-only canonical infrastructure context",+ } {+ if !strings.Contains(contextText, expected) {+ t.Fatalf("resource state context missing %q: %q", expected, contextText)+ }+ }+ for _, forbidden := range []string{+ "internal-restart-handler",+ "secret-token",+ "native-secret-incident",+ "ssh://[email protected]/private",+ } {+ if strings.Contains(contextText, forbidden) {+ t.Fatalf("resource state context leaked raw execution/provider detail %q: %q", forbidden, contextText)+ }+ }+}+func TestBuildHandoffResourceTimelineContextUsesRelatedCanonicalChanges(t *testing.T) {now := time.Now()store := unifiedresources.NewMemoryStore()diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 6eb7d78968..ab3d18d019 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -193,6 +193,7 @@ func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {"sessions.GetModelHandoffActions(session.ID)","refreshHandoffActionStatus(handoffActions, s.orgID, s.actionAuditStore)","mergeHandoffResourcePolicyContext(handoffContext, handoffResources, handoffResourceProvider)",+ "mergeHandoffResourceStateContext(handoffContext, handoffResources, handoffResourceProvider)","mergeHandoffResourceRelationshipContext(handoffContext, handoffResources, handoffResourceProvider)","mergeHandoffResourceTimelineContext(handoffContext, handoffResources, handoffResourceProvider, s.actionAuditStore, time.Now())","handoffContext = mergeHandoffActionContext(handoffContext, handoffActions)",@@ -205,6 +206,10 @@ func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {"injectHandoffContextIntoLatestUserMessage(messages, handoffContext)","Resource Policy Context","Policy Boundary",+ "Resource State Context",+ "labelPrefix+\" Status\"",+ "labelPrefix+\" Capabilities\"",+ "Resource State Boundary","Resource Relationship Context","Relationship Boundary","Timeline Boundary",