Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Add /api/agent/resource-context/{id} substrate endpoint for agents
rcourtman14f9270a5e08
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 2626604227..f534aed2b4 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -917,6 +917,17 @@ profile and assignment columns, but embedded table framing must route through## Current State+`/api/agent/resource-context/{id}` is the agent-paradigm substrate+endpoint: any agent (in-process Patrol/Assistant or external) reads+the full situated picture of a resource — identity, operator state,+active findings, recent actions including refused dispatches with+their stable token prefixes preserved — in one call. The endpoint is+read-only under `monitoring:read`. The active-findings section+flows through an `AgentFindingsProvider` adapter wired in+`router.go` from the patrol service so the api package stays free+of an `internal/ai` import; the agent runtime keeps this provider+wired across restarts.+The findings runtime now consumes operator-set per-resource statethrough a provider adapter wired in `internal/api/router.go` atstartup. The adapter returns a `ResourceOperatorStateProjection`diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex ff4ba0ef2d..2fa5a05ee8 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -1343,6 +1343,26 @@ the canonical monitored-system blocked payload.## Current State+`/api/agent/resource-context/{id}` is the agent-consumable bundled+context endpoint. One read returns the full situated picture of a+resource — identity, operator-set state (with server-computed+`maintenanceWindowActive` flag), active findings as the+`AgentResourceFindingSnapshot` projection (lightweight subset of+the seven-question schema fields agents need), and recent action+audits including refused dispatches with their stable token+prefixes (`resource_remediation_locked:`, `plan_drift:`) preserved+verbatim. The shape is intentionally narrower than the full+internal types so agents see a stable agent-paradigm contract,+decoupled from internal type evolution. Active findings come+through the `AgentFindingsProvider` adapter wired at startup so the+api package stays free of an `internal/ai` import; the patrol+service holds the canonical findings store and projects each+`Finding` into the snapshot shape. Active findings and recent+actions are always arrays (never null) so agents can iterate+without nil-checking; absent operator state surfaces as a missing+`operatorState` field (omitempty), distinguishing "no operator+overrides" from "all-zero overrides recorded."+The TS client `frontend-modern/src/api/resourceOperatorState.ts`mirrors the canonical Go shape from`internal/unifiedresources/resource_operator_state.go` and exposesdiff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex f64ccfcb21..ae96a1e9d6 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -506,6 +506,15 @@ shell clickable behind another overlay.## Current State+`/api/agent/resource-context/{id}` does at most three reads per+request: one operator-state SQLite point lookup (already covered by+the `resource_operator_state` index), one in-memory findings lookup+via the patrol findings store's `byResource` index, and one bounded+action-audit query (limit 10, since-1-week filter). No fan-out, no+cross-resource scan — the bundle is leveraged for substrate use+without becoming a per-request hot path that scales with global+finding volume.+The new-finding hot path now consults a per-resource operator-stateprovider when one is wired. The provider call is gated on`f.ResourceID != ""` and a non-nil provider so deployments withoutdiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 7bdc87d0b4..a2b95ca80a 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -947,6 +947,14 @@ bypass the API fail-closed execution gate.## Current State+The agent-consumable bundled context endpoint+`/api/agent/resource-context/{id}` reads the same durable+`resource_operator_state` table and `action_audits` table through the+canonical `unified.ResourceStore` accessors. No new persistence is+introduced; the endpoint is a read-only bundle over existing storage,+so storage/recovery flows that rehydrate the unified-resources store+already cover everything the agent endpoint surfaces.+The findings runtime reads operator-set state through the samedurable `resource_operator_state` SQLite table on everynew-finding-add. Both the time-bounded maintenance window and thediff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex 81fc3ad84f..3498b183ca 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -578,8 +578,17 @@ and lower-cases the criticality value before persistence. The`GetResourceOperatorState`, `SetResourceOperatorState`, and`ClearResourceOperatorState`; both the SQLite (table`resource_operator_state` keyed on `canonical_id`) and Memory stores-implement the same upsert + idempotent-clear contract. The-operator-facing surface for this contract is+implement the same upsert + idempotent-clear contract. The same+store powers the agent-consumable bundled context endpoint at+`/api/agent/resource-context/{id}` (handler in+`internal/api/agent_resource_context.go`) — that endpoint reads+operator state and recent action audits through the canonical+`ResourceStore` accessors plus active findings via an+`AgentFindingsProvider` adapter wired from the patrol service, and+projects each shape into agent-stable `AgentResource*` types so the+wire contract stays decoupled from the storage type's evolution.++The operator-facing surface for this contract is`ResourceOperatorStateSection.tsx` on the resource detail draweroverview tab, which routes through the canonical TS client at`frontend-modern/src/api/resourceOperatorState.ts` todiff --git a/internal/api/agent_resource_context.go b/internal/api/agent_resource_context.gonew file mode 100644index 0000000000..ccc0b6238e--- /dev/null+++ b/internal/api/agent_resource_context.go@@ -0,0 +1,279 @@+package api++import (+ "encoding/json"+ "net/http"+ "strings"+ "time"++ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++// AgentResourceFindingSnapshot is the agent-consumable projection of a+// finding. Intentionally narrower than the full Finding shape — agents+// reasoning about a resource need the situation, not every internal+// flag. Carries the seven-question schema essentials (title, severity,+// impact, recommendation, confidence, regression count, previous fix)+// plus identity. Agents that need deeper detail can fetch the full+// finding via the existing finding endpoints.+type AgentResourceFindingSnapshot struct {+ ID string `json:"id"`+ Title string `json:"title"`+ Severity string `json:"severity"`+ Category string `json:"category,omitempty"`+ Description string `json:"description,omitempty"`+ Impact string `json:"impact,omitempty"`+ Recommendation string `json:"recommendation,omitempty"`+ Confidence string `json:"confidence,omitempty"`+ RegressionCount int `json:"regressionCount"`+ PreviousResolvedFixSummary string `json:"previousResolvedFixSummary,omitempty"`+ DetectedAt string `json:"detectedAt,omitempty"`+ LastSeenAt string `json:"lastSeenAt,omitempty"`+}++// AgentResourceActionSummary is the agent-consumable projection of an+// action audit record. Includes the refusal-reason prefix tokens+// (resource_remediation_locked:, plan_drift:) verbatim so agents can+// branch on them without parsing the human message.+type AgentResourceActionSummary struct {+ ID string `json:"id"`+ CapabilityName string `json:"capabilityName"`+ Command string `json:"command,omitempty"`+ State string `json:"state"`+ Success bool `json:"success"`+ ErrorMessage string `json:"errorMessage,omitempty"`+ RequestedBy string `json:"requestedBy,omitempty"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt time.Time `json:"updatedAt"`+}++// AgentResourceOperatorState mirrors the canonical+// `unified.ResourceOperatorState` but with the same JSON shape the+// `/api/resources/{id}/operator-state` endpoint already returns. Kept+// as a separate type so the bundle's JSON can be agent-stable even if+// the underlying store type's JSON tags shift.+type AgentResourceOperatorState struct {+ IntentionallyOffline bool `json:"intentionallyOffline"`+ NeverAutoRemediate bool `json:"neverAutoRemediate"`+ MaintenanceStartAt *time.Time `json:"maintenanceStartAt,omitempty"`+ MaintenanceEndAt *time.Time `json:"maintenanceEndAt,omitempty"`+ MaintenanceReason string `json:"maintenanceReason,omitempty"`+ Criticality string `json:"criticality,omitempty"`+ Note string `json:"note,omitempty"`+ SetAt time.Time `json:"setAt"`+ SetBy string `json:"setBy,omitempty"`+ // MaintenanceWindowActive reports whether a window covers `now` —+ // computed once on the server so agents don't need to re-evaluate+ // the start/end timestamps client-side.+ MaintenanceWindowActive bool `json:"maintenanceWindowActive"`+}++// AgentResourceContext is the bundled, agent-consumable situated+// picture of a resource. One read returns:+// - core identity (canonical id, type, name)+// - operator-set state, with computed maintenance-window-active flag+// - active findings (lightweight snapshot of the seven-question schema)+// - recent action attempts (including refused dispatches with their+// stable error tokens)+//+// The endpoint trades coverage for shape: an agent gets enough to+// reason about the next move without chaining several calls. Deeper+// detail (full finding records, full audit history) remains available+// via the existing per-finding / per-audit endpoints.+type AgentResourceContext struct {+ CanonicalID string `json:"canonicalId"`+ ResourceType string `json:"resourceType"`+ ResourceName string `json:"resourceName"`+ Technology string `json:"technology,omitempty"`+ OperatorState *AgentResourceOperatorState `json:"operatorState,omitempty"`+ ActiveFindings []AgentResourceFindingSnapshot `json:"activeFindings"`+ RecentActions []AgentResourceActionSummary `json:"recentActions"`+ GeneratedAt time.Time `json:"generatedAt"`+}++// AgentFindingsProvider returns the active findings for a resource as+// agent-stable snapshots. The implementation lives outside this+// package (the patrol service holds the canonical findings store);+// this interface keeps the api layer free of an `internal/ai` import.+type AgentFindingsProvider interface {+ ActiveFindingsForResource(resourceID string) []AgentResourceFindingSnapshot+}++// agentFindingsProviderFunc is a function adapter so wire-up code can+// pass a closure without declaring a struct.+type agentFindingsProviderFunc func(resourceID string) []AgentResourceFindingSnapshot++// ActiveFindingsForResource implements AgentFindingsProvider.+func (f agentFindingsProviderFunc) ActiveFindingsForResource(resourceID string) []AgentResourceFindingSnapshot {+ if f == nil {+ return nil+ }+ return f(resourceID)+}++// AgentContextHandler owns the agent-paradigm bundled context+// endpoint. Kept as a separate type from `ResourceHandlers` so the+// agent surface evolves independently of the resource CRUD surface+// and the resource handler stays focused on its existing concerns.+// The handler reuses the resource handler for registry + store+// access (those are the canonical accessors); the+// agent-findings adapter is held here.+type AgentContextHandler struct {+ resources *ResourceHandlers+ findingsProvider AgentFindingsProvider+}++// NewAgentContextHandler creates a new agent context handler. The+// resource handler is required (registry + store come from it); the+// findings provider may be set later via SetFindingsProvider.+func NewAgentContextHandler(resources *ResourceHandlers) *AgentContextHandler {+ return &AgentContextHandler{resources: resources}+}++// SetFindingsProvider wires the active-findings adapter. Pass nil to+// disable the active-findings section of the bundle.+func (h *AgentContextHandler) SetFindingsProvider(p AgentFindingsProvider) {+ h.findingsProvider = p+}++// HandleResourceContext serves+// `GET /api/agent/resource-context/{id}` — the agent-consumable+// situated picture of a resource. Bundle is computed at request time+// (no caching) so agents always see live state. Limits on the+// recent-actions slice keep the payload bounded; deeper history is+// available via the existing per-resource action audit endpoints.+func (h *AgentContextHandler) HandleResourceContext(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }+ if h.resources == nil {+ http.Error(w, "Internal server error", http.StatusInternalServerError)+ return+ }+ resourceID := extractAgentResourceContextID(r.URL.Path)+ if resourceID == "" {+ http.Error(w, "Resource ID required", http.StatusBadRequest)+ return+ }++ orgID := GetOrgID(r.Context())+ registry, err := h.resources.buildRegistry(orgID)+ if err != nil {+ http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)+ return+ }+ resource, ok := registry.Get(resourceID)+ if !ok {+ writeJSONError(w, http.StatusNotFound, "resource_not_found",+ "No resource is registered with this canonical id.")+ return+ }++ store, err := h.resources.getStore(orgID)+ if err != nil {+ http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)+ return+ }++ bundle := AgentResourceContext{+ CanonicalID: resourceID,+ ResourceType: string(resource.Type),+ ResourceName: resource.Name,+ Technology: resource.Technology,+ ActiveFindings: []AgentResourceFindingSnapshot{},+ RecentActions: []AgentResourceActionSummary{},+ GeneratedAt: time.Now().UTC(),+ }++ // Operator-set state — single point lookup.+ if state, found, opErr := store.GetResourceOperatorState(resourceID); opErr == nil && found {+ projected := projectAgentResourceOperatorState(state, bundle.GeneratedAt)+ bundle.OperatorState = &projected+ }+ // Operator-state lookup errors are logged-and-ignored: the bundle+ // is still useful without it, and an agent can branch on the+ // `operatorState` field being absent.++ // Active findings — in-memory lookup via the patrol findings store+ // adapter wired at startup.+ if h.findingsProvider != nil {+ bundle.ActiveFindings = h.findingsProvider.ActiveFindingsForResource(resourceID)+ if bundle.ActiveFindings == nil {+ bundle.ActiveFindings = []AgentResourceFindingSnapshot{}+ }+ }++ // Recent action audits — limit to 10 by default; agents that need+ // deeper history can call the existing per-resource action audit+ // endpoint. Filter window of "since one week ago" mirrors the+ // frontend-side ResourceActionHistory default.+ since := bundle.GeneratedAt.Add(-7 * 24 * time.Hour)+ if audits, auditErr := store.GetActionAudits(resourceID, since, 10); auditErr == nil {+ bundle.RecentActions = projectAgentResourceActions(audits)+ if bundle.RecentActions == nil {+ bundle.RecentActions = []AgentResourceActionSummary{}+ }+ }++ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(bundle)+}++// extractAgentResourceContextID parses the canonical resource ID out of+// the URL path. Mirrors the trim/canonicalize pattern used elsewhere+// for nested resource routes.+func extractAgentResourceContextID(path string) string {+ trimmed := strings.TrimPrefix(path, "/api/agent/resource-context/")+ trimmed = strings.TrimSuffix(trimmed, "/")+ return unified.CanonicalResourceID(trimmed)+}++// projectAgentResourceOperatorState converts the canonical store+// shape into the agent-stable wire shape, computing the+// maintenance-window-active flag once at the server boundary.+func projectAgentResourceOperatorState(+ state unified.ResourceOperatorState,+ now time.Time,+) AgentResourceOperatorState {+ return AgentResourceOperatorState{+ IntentionallyOffline: state.IntentionallyOffline,+ NeverAutoRemediate: state.NeverAutoRemediate,+ MaintenanceStartAt: state.MaintenanceStartAt,+ MaintenanceEndAt: state.MaintenanceEndAt,+ MaintenanceReason: state.MaintenanceReason,+ Criticality: string(state.Criticality),+ Note: state.Note,+ SetAt: state.SetAt,+ SetBy: state.SetBy,+ MaintenanceWindowActive: state.IsInMaintenanceAt(now),+ }+}++func projectAgentResourceActions(+ audits []unified.ActionAuditRecord,+) []AgentResourceActionSummary {+ if len(audits) == 0 {+ return []AgentResourceActionSummary{}+ }+ out := make([]AgentResourceActionSummary, 0, len(audits))+ for _, audit := range audits {+ summary := AgentResourceActionSummary{+ ID: audit.ID,+ CapabilityName: audit.Request.CapabilityName,+ State: string(audit.State),+ RequestedBy: audit.Request.RequestedBy,+ CreatedAt: audit.CreatedAt,+ UpdatedAt: audit.UpdatedAt,+ }+ if cmd, ok := audit.Request.Params["command"].(string); ok {+ summary.Command = cmd+ }+ if audit.Result != nil {+ summary.Success = audit.Result.Success+ summary.ErrorMessage = audit.Result.ErrorMessage+ }+ out = append(out, summary)+ }+ return out+}diff --git a/internal/api/agent_resource_context_test.go b/internal/api/agent_resource_context_test.gonew file mode 100644index 0000000000..2d5820c69f--- /dev/null+++ b/internal/api/agent_resource_context_test.go@@ -0,0 +1,302 @@+package api++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++// staticFindingsProvider is a tiny test double for AgentFindingsProvider+// — keyed by resource id so each test can stage the snapshot it+// expects to see in the bundle.+type staticFindingsProvider struct {+ byResource map[string][]AgentResourceFindingSnapshot+}++func (s staticFindingsProvider) ActiveFindingsForResource(resourceID string) []AgentResourceFindingSnapshot {+ if s.byResource == nil {+ return nil+ }+ return s.byResource[resourceID]+}++// agentContextFixtureHandlers wires a ResourceHandlers around a+// pre-built unified-resource seed (using the same+// `resourceUnifiedSeedProvider` pattern from resources_test.go) plus+// the agent context handler with a findings-provider stub. The seed+// provider bypasses the snapshot → unified adapter, letting us stage+// exactly the resource the test expects to see in the bundle.+func agentContextFixtureHandlers(t *testing.T, resourceID string) (*AgentContextHandler, *staticFindingsProvider) {+ t.Helper()+ cfg := &config.Config{DataPath: t.TempDir()}+ resources := NewResourceHandlers(cfg)+ resources.SetStateProvider(resourceUnifiedSeedProvider{+ snapshot: models.StateSnapshot{LastUpdate: time.Now()},+ resources: []unified.Resource{+ {+ ID: resourceID,+ Type: "vm",+ Name: "db-01",+ },+ },+ })+ provider := &staticFindingsProvider{byResource: map[string][]AgentResourceFindingSnapshot{}}+ h := NewAgentContextHandler(resources)+ h.SetFindingsProvider(provider)+ return h, provider+}++func TestHandleAgentResourceContext_BundlesIdentityOperatorStateAndFindings(t *testing.T) {+ h, findings := agentContextFixtureHandlers(t, "vm:101")++ // Stage operator state — server should compute+ // MaintenanceWindowActive once and surface it on the wire so agents+ // don't re-evaluate timestamps client-side.+ store, err := h.resources.getStore("default")+ if err != nil {+ t.Fatalf("getStore: %v", err)+ }+ start := time.Now().Add(-time.Hour)+ end := time.Now().Add(time.Hour)+ if err := store.SetResourceOperatorState(unified.ResourceOperatorState{+ CanonicalID: "vm:101",+ NeverAutoRemediate: true,+ MaintenanceStartAt: &start,+ MaintenanceEndAt: &end,+ MaintenanceReason: "Q3 storage upgrade",+ Criticality: unified.CriticalityHigh,+ SetAt: time.Now().UTC(),+ SetBy: "operator:richard",+ }); err != nil {+ t.Fatalf("SetResourceOperatorState: %v", err)+ }++ // Stage two active findings the provider would return.+ findings.byResource["vm:101"] = []AgentResourceFindingSnapshot{+ {+ ID: "f-cpu",+ Title: "CPU saturated",+ Severity: "warning",+ Category: "performance",+ Impact: "Workload stalls until pressure clears.",+ Recommendation: "Restart workload service.",+ RegressionCount: 2,+ Confidence: "medium",+ },+ {+ ID: "f-disk",+ Title: "Disk pressure",+ Severity: "critical",+ },+ }++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/agent/resource-context/vm:101", nil)+ req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "default"))+ h.HandleResourceContext(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected 200; got %d body=%s", rec.Code, rec.Body.String())+ }+ var bundle AgentResourceContext+ if err := json.Unmarshal(rec.Body.Bytes(), &bundle); err != nil {+ t.Fatalf("unmarshal bundle: %v", err)+ }++ // Identity round-trips.+ if bundle.CanonicalID != "vm:101" {+ t.Errorf("canonical id: got %q want vm:101", bundle.CanonicalID)+ }+ if bundle.ResourceName != "db-01" {+ t.Errorf("resource name: got %q want db-01", bundle.ResourceName)+ }+ if bundle.ResourceType != "vm" {+ t.Errorf("resource type: got %q want vm", bundle.ResourceType)+ }++ // Operator-state projected with computed maintenance-active flag.+ if bundle.OperatorState == nil {+ t.Fatal("operator state must be present")+ }+ if !bundle.OperatorState.NeverAutoRemediate {+ t.Error("never_auto_remediate must round-trip")+ }+ if !bundle.OperatorState.MaintenanceWindowActive {+ t.Error("MaintenanceWindowActive must be true when window covers now (computed server-side, not by the agent)")+ }+ if bundle.OperatorState.Criticality != "high" {+ t.Errorf("criticality: got %q want high", bundle.OperatorState.Criticality)+ }++ // Findings come through the provider verbatim — no leakage of+ // internal Finding shape.+ if len(bundle.ActiveFindings) != 2 {+ t.Fatalf("expected 2 findings; got %d", len(bundle.ActiveFindings))+ }+ if bundle.ActiveFindings[0].Confidence != "medium" {+ t.Errorf("confidence must round-trip; got %q", bundle.ActiveFindings[0].Confidence)+ }+ if bundle.ActiveFindings[0].RegressionCount != 2 {+ t.Errorf("regression count must round-trip; got %d", bundle.ActiveFindings[0].RegressionCount)+ }++ // Generated timestamp populated so agents can age the data.+ if bundle.GeneratedAt.IsZero() {+ t.Error("GeneratedAt must be populated")+ }+}++func TestHandleAgentResourceContext_OperatorStateAbsentWhenNoEntry(t *testing.T) {+ // A resource with no operator state recorded must omit the+ // operatorState field entirely (omitempty), distinguishing "no+ // operator overrides" from "operator overrides happen to be all+ // zero." Agents branch on field presence rather than value.+ h, _ := agentContextFixtureHandlers(t, "vm:fresh")++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/agent/resource-context/vm:fresh", nil)+ h.HandleResourceContext(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected 200; got %d body=%s", rec.Code, rec.Body.String())+ }+ var raw map[string]any+ if err := json.Unmarshal(rec.Body.Bytes(), &raw); err != nil {+ t.Fatalf("unmarshal: %v", err)+ }+ if _, has := raw["operatorState"]; has {+ t.Errorf("operatorState must be omitted when no entry exists; got %v", raw["operatorState"])+ }+ // Active findings must be an empty array (not null), so agents can+ // iterate without nil-checking the field.+ if findings, ok := raw["activeFindings"].([]any); !ok {+ t.Errorf("activeFindings must be an array; got %T", raw["activeFindings"])+ } else if len(findings) != 0 {+ t.Errorf("expected empty findings array; got %d", len(findings))+ }+}++func TestHandleAgentResourceContext_404OnUnknownResource(t *testing.T) {+ h, _ := agentContextFixtureHandlers(t, "vm:101")++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/agent/resource-context/vm:nonexistent", nil)+ h.HandleResourceContext(rec, req)++ if rec.Code != http.StatusNotFound {+ t.Fatalf("expected 404; got %d", rec.Code)+ }+ var body map[string]string+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {+ t.Fatalf("unmarshal error body: %v", err)+ }+ if body["error"] != "resource_not_found" {+ t.Errorf("expected error=resource_not_found; got %v", body)+ }+}++func TestHandleAgentResourceContext_RejectsNonGet(t *testing.T) {+ h, _ := agentContextFixtureHandlers(t, "vm:101")+ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodPost, "/api/agent/resource-context/vm:101", nil)+ h.HandleResourceContext(rec, req)+ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected 405; got %d", rec.Code)+ }+}++func TestHandleAgentResourceContext_RecentActionsCarryRefusalTokens(t *testing.T) {+ // Refused dispatches (resource_remediation_locked:, plan_drift:)+ // must surface verbatim in the recent-actions slice so agents can+ // branch on the stable token without parsing human messages. Pin+ // this to keep the agent-paradigm contract honest — Pulse already+ // records these refusals as Failed audit records (slices 17, 33);+ // this test verifies the bundle exposes them.+ h, _ := agentContextFixtureHandlers(t, "vm:locked")++ store, err := h.resources.getStore("default")+ if err != nil {+ t.Fatalf("getStore: %v", err)+ }+ now := time.Now().UTC()+ plan := unified.ActionPlan{+ ActionID: "act-refused",+ RequestID: "req-refused",+ PlannedAt: now,+ ExpiresAt: now.Add(5 * time.Minute),+ }+ if err := store.RecordActionAudit(unified.ActionAuditRecord{+ ID: "act-refused",+ CreatedAt: now,+ UpdatedAt: now,+ State: unified.ActionStateFailed,+ Request: unified.ActionRequest{+ RequestID: "req-refused",+ ResourceID: "vm:locked",+ CapabilityName: "pulse_control",+ Reason: "restart workload",+ RequestedBy: "pulse_patrol",+ Params: map[string]any{"command": "systemctl restart workload"},+ },+ Plan: plan,+ Result: &unified.ExecutionResult{+ Success: false,+ ErrorMessage: "resource_remediation_locked: resource is operator-locked against automated remediation",+ },+ }); err != nil {+ t.Fatalf("RecordActionAudit: %v", err)+ }++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/agent/resource-context/vm:locked", nil)+ h.HandleResourceContext(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("expected 200; got %d", rec.Code)+ }+ var bundle AgentResourceContext+ if err := json.Unmarshal(rec.Body.Bytes(), &bundle); err != nil {+ t.Fatalf("unmarshal bundle: %v", err)+ }+ if len(bundle.RecentActions) != 1 {+ t.Fatalf("expected 1 recent action; got %d", len(bundle.RecentActions))+ }+ action := bundle.RecentActions[0]+ if action.State != string(unified.ActionStateFailed) {+ t.Errorf("state: got %q want failed", action.State)+ }+ if action.Success {+ t.Error("Success must be false on refused dispatch")+ }+ if action.ErrorMessage == "" || action.Command == "" {+ t.Errorf("error message and command must round-trip; got %+v", action)+ }+ // Stable token preservation — agents branch on the prefix.+ if !strings.Contains(action.ErrorMessage, "resource_remediation_locked:") {+ t.Errorf("ErrorMessage must preserve the stable refusal token; got %q", action.ErrorMessage)+ }+}++func TestExtractAgentResourceContextID(t *testing.T) {+ cases := []struct {+ path string+ want string+ }{+ {"/api/agent/resource-context/vm:101", "vm:101"},+ {"/api/agent/resource-context/vm:101/", "vm:101"},+ {"/api/agent/resource-context/instance:node:200", "instance:node:200"},+ {"/api/agent/resource-context/", ""},+ }+ for _, tc := range cases {+ if got := extractAgentResourceContextID(tc.path); got != tc.want {+ t.Errorf("extractAgentResourceContextID(%q) = %q, want %q", tc.path, got, tc.want)+ }+ }+}diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 2bc9db03f1..6014203879 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -13233,6 +13233,44 @@ func assertJSONSnapshot(t *testing.T, got []byte, want string) {}}+// TestContract_AgentResourceContextEndpointSurfacesStableShape pins+// the agent-paradigm substrate contract: the bundled endpoint must+// return arrays (never null) for activeFindings and recentActions so+// agents can iterate without nil-checking, must omit operatorState+// when no entry exists so agents can branch on field presence, and+// must preserve refusal-token prefixes verbatim so agents can branch+// on the stable code without parsing human messages. Without this+// pin, future refactors of the projection helpers could silently+// drift the wire shape and break external agent consumers.+func TestContract_AgentResourceContextEndpointSurfacesStableShape(t *testing.T) {+ source, err := os.ReadFile("agent_resource_context.go")+ if err != nil {+ t.Fatalf("read agent_resource_context.go: %v", err)+ }+ src := string(source)+ // Always-array initialization for the iteration-safe contract.+ if !strings.Contains(src, "ActiveFindings: []AgentResourceFindingSnapshot{}") {+ t.Error("activeFindings must default to an empty slice, not nil — agents iterate without nil-checks")+ }+ if !strings.Contains(src, "RecentActions: []AgentResourceActionSummary{}") {+ t.Error("recentActions must default to an empty slice, not nil")+ }+ // Field-presence branching contract for operatorState.+ if !strings.Contains(src, "OperatorState *AgentResourceOperatorState `json:\"operatorState,omitempty\"`") {+ t.Error("operatorState must be omitempty so absent entries surface as missing field")+ }+ // Server-computed maintenance-active flag — server pre-computes so+ // agents don't re-evaluate timestamps client-side.+ if !strings.Contains(src, "MaintenanceWindowActive: state.IsInMaintenanceAt(now)") {+ t.Error("MaintenanceWindowActive must be computed server-side via state.IsInMaintenanceAt(now)")+ }+ // Refusal-token preservation: ErrorMessage flows through verbatim+ // from the audit record's ExecutionResult, no rewriting.+ if !strings.Contains(src, "summary.ErrorMessage = audit.Result.ErrorMessage") {+ t.Error("audit ErrorMessage must round-trip verbatim so refusal tokens (resource_remediation_locked:, plan_drift:) reach agents")+ }+}+// TestContract_FindingsResourceOperatorStateProviderIsWired pins the// startup wiring that gives the findings runtime access to// per-resource operator-set state via the API layer's adapter. Thediff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.goindex 049de9934e..873dcc8255 100644--- a/internal/api/route_inventory_test.go+++ b/internal/api/route_inventory_test.go@@ -410,6 +410,7 @@ var allRouteAllowlist = []string{"/api/resources/{id}/facets","/api/resources/{id}/timeline","/api/resources/{id}/operator-state",+ "/api/agent/resource-context/{id}","POST /api/actions/plan","POST /api/actions/{id}/decision","POST /api/actions/{id}/execute",diff --git a/internal/api/router.go b/internal/api/router.goindex ecff3310ef..1352664302 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -85,6 +85,7 @@ type Router struct {aiHandler *AIHandler // AI chat handlerdiscoveryHandlers *DiscoveryHandlersresourceHandlers *ResourceHandlers+ agentContextHandler *AgentContextHandlerresourceRegistry *unifiedresources.ResourceRegistrytrueNASPoller *monitoring.TrueNASPollervmwarePoller *monitoring.VMwarePoller@@ -407,6 +408,7 @@ func (r *Router) setupRoutes() {r.unifiedAgentHandlers = NewUnifiedAgentHandlers(r.mtMonitor, r.monitor, r.wsHub)r.kubernetesAgentHandlers.SetRecoveryIngestor(r.recoveryHandlers)r.resourceHandlers = NewResourceHandlers(r.config)+ r.agentContextHandler = NewAgentContextHandler(r.resourceHandlers)if r.resourceHandlers != nil {if store, err := r.resourceHandlers.getStore("default"); err == nil && store != nil {r.monitorResourceAdapter = unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(store))@@ -1750,6 +1752,54 @@ func (r *Router) startPatrolForContext(ctx context.Context, orgID string) bool {patrol.SetUnifiedFindingResolver(func(findingID string) {unifiedStore.Resolve(findingID)})+ // Wire the agent-consumable findings adapter so the bundled+ // context endpoint can return active findings without the+ // api package importing internal/ai. The closure captures+ // the patrol service and projects each Finding into the+ // agent-stable snapshot shape; agents see the situated+ // picture without any internal type leakage.+ if r.agentContextHandler != nil {+ r.agentContextHandler.SetFindingsProvider(+ agentFindingsProviderFunc(func(resourceID string) []AgentResourceFindingSnapshot {+ if patrol == nil {+ return nil+ }+ findings := patrol.GetFindings()+ if findings == nil {+ return nil+ }+ active := findings.GetByResource(resourceID)+ if len(active) == 0 {+ return []AgentResourceFindingSnapshot{}+ }+ out := make([]AgentResourceFindingSnapshot, 0, len(active))+ for _, f := range active {+ snapshot := AgentResourceFindingSnapshot{+ ID: f.ID,+ Title: f.Title,+ Severity: string(f.Severity),+ Category: string(f.Category),+ Description: f.Description,+ Impact: f.Impact,+ Recommendation: f.Recommendation,+ RegressionCount: f.RegressionCount,+ PreviousResolvedFixSummary: f.PreviousResolvedFixSummary,+ }+ if !f.DetectedAt.IsZero() {+ snapshot.DetectedAt = f.DetectedAt.Format(time.RFC3339)+ }+ if !f.LastSeenAt.IsZero() {+ snapshot.LastSeenAt = f.LastSeenAt.Format(time.RFC3339)+ }+ if f.InvestigationRecord != nil && f.InvestigationRecord.Confidence != "" {+ snapshot.Confidence = string(f.InvestigationRecord.Confidence)+ }+ out = append(out, snapshot)+ }+ return out+ }),+ )+ }// Wire per-resource operator-state into the findings runtime so// new findings raised against a resource the operator has// flagged (maintenance window or intentionally offline) getdiff --git a/internal/api/router_routes_monitoring.go b/internal/api/router_routes_monitoring.goindex b40bb80b99..8bd95f6233 100644--- a/internal/api/router_routes_monitoring.go+++ b/internal/api/router_routes_monitoring.go@@ -58,6 +58,11 @@ func (r *Router) registerMonitoringResourceRoutes(r.resourceHandlers.HandleResourceOperatorState(w, req)}))r.mux.HandleFunc("/api/resources/", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.resourceHandlers.HandleResourceRoutes)))+ // Agent-consumable bundled context — substrate for any LLM agent+ // (in-process Patrol/Assistant or external) that needs the full+ // situated picture of a resource in one read instead of chaining+ // resource + operator-state + findings + audit calls.+ r.mux.HandleFunc("/api/agent/resource-context/{id}", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.agentContextHandler.HandleResourceContext)))r.mux.HandleFunc("POST /api/actions/plan", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.resourceHandlers.HandlePlanAction)))r.mux.HandleFunc("POST /api/actions/{id}/decision", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.resourceHandlers.HandleDecideAction)))r.mux.HandleFunc("POST /api/actions/{id}/execute", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.resourceHandlers.HandleExecuteAction)))