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
Drop redundant policy gates in resource-link routing
rcourtman52669128e6ae
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 825a4871ef..4361d33138 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -591,6 +591,23 @@ call (active maintenance window plus the `IntentionallyOffline`flag) so adding new signals later does not multiply round-trips perfinding.+The approval store exposes `SetOnApprovalCreated(cb)` so the API+layer can install a fire-and-forget callback that runs after every+successful `CreateApproval` (the approval is already persisted at+that point). The callback is invoked on its own goroutine against+a snapshot of the request, keeping the approval hot path off any+consumer's slowness and avoiding any chance of the consumer+reentering the store under the held write lock. This is the seam+the agent SSE stream uses to publish `approval.pending` events+without coupling the approval store to the api package.+`ApprovalRequest.CanonicalResourceID()` is the helper the bridge+uses to stamp `resourceId` on those events, derived from+`(TargetType, TargetID, TargetName)` via the same rule the store+uses internally for preflight context normalization — Plan-less+approvals (the common shape on the approval hot path) still carry+a canonical resource id agents can match against the rest of+Pulse.+The investigation runtime now hands the orchestrator a Findingpre-enriched with operator-set state and operational memory.`MaybeInvestigateFinding` (in `internal/ai/patrol_findings.go`)diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 77e1f7d5c7..0c60870416 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -1359,17 +1359,39 @@ that closes the agent-paradigm triangle (discovery + bundled reads +push notifications). Agents subscribe once and receive real-timenotifications: `finding.created` when a new finding is raised(suppressed when the finding was auto-dismissed by operator-state),-and `heartbeat` every 15 seconds so an idle connection can confirm+`approval.pending` when a remediation request enters+`StatusPending` and is waiting on operator decision (carries+`approvalId`, `resourceId`, target tuple, `command`, `riskLevel`,+`requestedBy`, `requestedAt`, `expiresAt` — full detail stays+behind `/api/approvals/{id}`, the event is a doorbell), and+`heartbeat` every 15 seconds so an idle connection can confirmthe stream is alive. Each event carries a monotonic ID so agentscan dedupe and reason about ordering. The broadcaster drops eventsfor slow subscribers rather than blocking the publish path —-publishers (the patrol findings runtime, future approval/action-hooks) cannot stall on consumer slowness. The stream sits behind-`monitoring:read` and runs through the same auth path as the rest-of the agent surface; the capabilities manifest declares the stream-under `subscribe_events` so external agents discover it without+publishers (the patrol findings runtime, the approval store's+post-create callback, future action-completion hooks) cannot stall+on consumer slowness. The stream sits behind `monitoring:read` and+runs through the same auth path as the rest of the agent surface;+the capabilities manifest declares the stream under+`subscribe_events` so external agents discover it withoutout-of-band documentation.+The approval store exposes `SetOnApprovalCreated(cb)` so the API+layer can install a fire-and-forget callback that runs after every+successful `CreateApproval`. The callback fires on its own+goroutine against a snapshot of the request, keeping the approval+hot path off any consumer's slowness and avoiding any chance of the+consumer reentering the store under the held write lock. The router+wires the callback through `AIHandler.SetApprovalCreatedCallback`,+which both installs the callback on the active store and re-installs+it whenever `ensureApprovalStore` builds a new store for a different+data dir. `ApprovalRequest.CanonicalResourceID()` returns the+canonical `type:id` form the agent SSE bridge stamps on+`approval.pending` events, derived from `(TargetType, TargetID,+TargetName)` via the same rule the store uses internally — agents+match the result against canonical resource ids elsewhere in Pulse+without depending on a `Plan` being populated.+`/api/agent/capabilities` is the discovery document for Pulse'sagent surface. The manifest declares each agent-consumablecapability with stable name (snake_case agent identifier),diff --git a/internal/ai/approval/store.go b/internal/ai/approval/store.goindex 96140085d6..a8471e3c38 100644--- a/internal/ai/approval/store.go+++ b/internal/ai/approval/store.go@@ -184,6 +184,25 @@ type Store struct {persist boolsaveTimer *time.TimersavePending bool+ // onApprovalCreated fires after a successful CreateApproval, with+ // the approval already in StatusPending. Wired by the API layer+ // at startup so the agent SSE stream can publish approval.pending+ // events. nil is safe — the callback is fire-and-forget. Callers+ // must not block on it; the store dispatches it on its own+ // goroutine to keep the approval hot path off any consumer's+ // slowness.+ onApprovalCreated func(*ApprovalRequest)+}++// SetOnApprovalCreated installs a fire-and-forget callback that+// runs after CreateApproval places the approval in StatusPending.+// Pass nil to disable. Used by the API layer to bridge approval+// creation into the agent event stream without coupling the+// approval store to the api package.+func (s *Store) SetOnApprovalCreated(cb func(*ApprovalRequest)) {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.onApprovalCreated = cb}// StoreConfig configures the approval store.@@ -316,6 +335,21 @@ func (s *Store) CreateApproval(req *ApprovalRequest) error {Str("risk", string(req.RiskLevel)).Msg("Created approval request")+ // Fire the post-create callback on its own goroutine. The+ // approval is already persisted at this point, so the callback+ // is fire-and-forget — a panic or stall on the consumer side+ // must not back up the approval hot path. Spawning a goroutine+ // also avoids any chance of the consumer reentering the store+ // under our held write lock.+ if cb := s.onApprovalCreated; cb != nil {+ // Snapshot the request struct so the consumer reads a+ // stable view. Subsequent state mutations on the live+ // pointer happen under s.mu and would otherwise race with+ // a consumer that reads fields off the goroutine.+ snapshot := *req+ go cb(&snapshot)+ }+return nil}@@ -983,6 +1017,20 @@ func isUnsupportedApprovalTargetType(targetType string) bool {return unifiedresources.IsUnsupportedLegacyResourceTypeAlias(normalizeApprovalTargetType(targetType))}+// CanonicalResourceID returns the canonical "type:id" resource+// identifier this approval targets, derived from the approval's+// (TargetType, TargetID, TargetName) tuple via the same rule the+// store uses internally when normalizing preflight context. Used by+// callers that need the resource id without depending on the plan+// being populated — notably the agent SSE bridge that publishes+// approval.pending events.+func (req *ApprovalRequest) CanonicalResourceID() string {+ if req == nil {+ return ""+ }+ return approvalResourceID(req.TargetType, req.TargetID, req.TargetName)+}+func approvalResourceID(targetType, targetID, targetName string) string {targetType = strings.TrimSpace(targetType)targetID = strings.TrimSpace(targetID)diff --git a/internal/ai/approval/store_test.go b/internal/ai/approval/store_test.goindex 2a7d165e5b..ce3ccf021b 100644--- a/internal/ai/approval/store_test.go+++ b/internal/ai/approval/store_test.go@@ -113,6 +113,133 @@ func TestCreateApproval(t *testing.T) {}}+func TestSetOnApprovalCreated_FiresAfterCreate(t *testing.T) {+ // The post-create callback is the seam the API layer uses to+ // bridge approval creation into the agent SSE stream+ // (approval.pending events). Pin the contract: the callback fires+ // once per CreateApproval, sees a fully populated request, and+ // runs without blocking the caller — fire-and-forget.+ tmpDir, err := os.MkdirTemp("", "approval-cb-test-*")+ if err != nil {+ t.Fatalf("Failed to create temp dir: %v", err)+ }+ defer os.RemoveAll(tmpDir)++ store, _ := NewStore(StoreConfig{+ DataDir: tmpDir,+ DefaultTimeout: 1 * time.Minute,+ })++ got := make(chan *ApprovalRequest, 1)+ store.SetOnApprovalCreated(func(req *ApprovalRequest) {+ got <- req+ })++ req := &ApprovalRequest{+ ExecutionID: "exec-cb",+ ToolID: "tool-cb",+ Command: "systemctl restart nginx",+ TargetType: "agent",+ TargetID: "host-cb",+ TargetName: "web-cb",+ Context: "callback test",+ }+ if err := store.CreateApproval(req); err != nil {+ t.Fatalf("CreateApproval: %v", err)+ }++ select {+ case received := <-got:+ if received == nil {+ t.Fatal("callback received nil request")+ }+ if received.ID == "" {+ t.Error("callback request must have ID populated")+ }+ if received.Status != StatusPending {+ t.Errorf("callback request status = %v, want %v", received.Status, StatusPending)+ }+ if received.RequestedAt.IsZero() {+ t.Error("callback request must have RequestedAt populated")+ }+ if received.RiskLevel == "" {+ t.Error("callback request must have RiskLevel assessed")+ }+ case <-time.After(2 * time.Second):+ t.Fatal("post-create callback did not fire within 2s")+ }+}++func TestSetOnApprovalCreated_NilCallbackIsSafe(t *testing.T) {+ // Disabling the callback (or never installing one) must not+ // break the create path. This is the default state and the most+ // common shape in tests.+ tmpDir, err := os.MkdirTemp("", "approval-cb-nil-*")+ if err != nil {+ t.Fatalf("Failed to create temp dir: %v", err)+ }+ defer os.RemoveAll(tmpDir)++ store, _ := NewStore(StoreConfig{+ DataDir: tmpDir,+ DefaultTimeout: 1 * time.Minute,+ })+ store.SetOnApprovalCreated(nil)++ req := &ApprovalRequest{+ ExecutionID: "exec-nil",+ ToolID: "tool-nil",+ Command: "systemctl restart nginx",+ TargetType: "agent",+ TargetID: "host-nil",+ TargetName: "web-nil",+ Context: "nil callback test",+ }+ if err := store.CreateApproval(req); err != nil {+ t.Fatalf("CreateApproval with nil callback: %v", err)+ }+}++func TestApprovalRequest_CanonicalResourceID(t *testing.T) {+ // CanonicalResourceID is the helper the agent SSE bridge uses to+ // stamp resourceId on approval.pending events without depending+ // on a Plan being populated. Pin the format so agents can match+ // the result against canonical resource ids elsewhere in Pulse.+ cases := []struct {+ name string+ req *ApprovalRequest+ want string+ }{+ {+ name: "type and id compose with colon",+ req: &ApprovalRequest{TargetType: "container", TargetID: "web-1", TargetName: "web-1"},+ want: "container:web-1",+ },+ {+ name: "id already canonical passes through",+ req: &ApprovalRequest{TargetType: "container", TargetID: "container:web-2"},+ want: "container:web-2",+ },+ {+ name: "missing id falls back to name",+ req: &ApprovalRequest{TargetType: "vm", TargetName: "alpine"},+ want: "vm:alpine",+ },+ {+ name: "nil receiver returns empty",+ req: nil,+ want: "",+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := tc.req.CanonicalResourceID(); got != tc.want {+ t.Fatalf("CanonicalResourceID() = %q, want %q", got, tc.want)+ }+ })+ }+}+func TestCreateApproval_PreservesActionPlanAndContextConfidence(t *testing.T) {tmpDir, err := os.MkdirTemp("", "approval-test-*")if err != nil {diff --git a/internal/api/agent_capabilities.go b/internal/api/agent_capabilities.goindex d7c43eb60c..75f5dcc383 100644--- a/internal/api/agent_capabilities.go+++ b/internal/api/agent_capabilities.go@@ -132,7 +132,7 @@ var agentCapabilitiesManifest = AgentCapabilitiesManifest{},{Name: "subscribe_events",- Description: "Subscribe to the SSE event stream for real-time notifications: finding.created when a new finding is raised, heartbeat every 15s. Long-lived connection; agents listen instead of polling.",+ Description: "Subscribe to the SSE event stream for real-time notifications: finding.created when a new finding is raised, approval.pending when a remediation request enters StatusPending and waits on operator decision, heartbeat every 15s. Long-lived connection; agents listen instead of polling.",Category: "context",Method: http.MethodGet,Path: "/api/agent/events",diff --git a/internal/api/agent_events.go b/internal/api/agent_events.goindex 89460169f4..1e5f98f173 100644--- a/internal/api/agent_events.go+++ b/internal/api/agent_events.go@@ -25,6 +25,15 @@ const (// agent to decide whether to fetch the full situated context.AgentEventFindingCreated AgentEventKind = "finding.created"+ // AgentEventApprovalPending fires when a remediation request enters+ // StatusPending and is waiting on an operator (or operator-acting+ // agent) to approve, reject, or cancel. Payload carries the+ // approval id, the resource it targets, the command, the assessed+ // risk level, who requested it, and when it expires — enough for+ // an agent that holds approval authority to decide whether to act,+ // fetch full context via the approval endpoints, or escalate.+ AgentEventApprovalPending AgentEventKind = "approval.pending"+// AgentEventHeartbeat is a keepalive that fires at a fixed// interval. Agents that hold an open SSE connection use it to// confirm the stream is healthy without waiting for a real@@ -56,6 +65,26 @@ type AgentEventFindingCreatedPayload struct {Category string `json:"category,omitempty"`}+// AgentEventApprovalPendingPayload is the payload shape for+// approval.pending events. Carries the agent-decision-relevant+// fields: which approval, against which resource, what command,+// what risk, who requested it, and when it expires. Full request+// detail (preflight, plan, raw context) stays behind the existing+// /api/approvals/{id} endpoint — the event is a doorbell, not the+// approval itself.+type AgentEventApprovalPendingPayload struct {+ ApprovalID string `json:"approvalId"`+ ResourceID string `json:"resourceId,omitempty"`+ TargetType string `json:"targetType,omitempty"`+ TargetID string `json:"targetId,omitempty"`+ TargetName string `json:"targetName,omitempty"`+ Command string `json:"command"`+ RiskLevel string `json:"riskLevel"`+ RequestedBy string `json:"requestedBy,omitempty"`+ RequestedAt time.Time `json:"requestedAt"`+ ExpiresAt time.Time `json:"expiresAt"`+}+// AgentEventBroadcaster is a thread-safe pub/sub for AgentEvents. A// single broadcaster instance lives at the api-package level; the// findings store and action broker publish to it, the SSE handler@@ -237,6 +266,17 @@ func (b *AgentEventBroadcaster) PublishFindingCreated(payload AgentEventFindingC})}+// PublishApprovalPending is the convenience publisher the approval+// store's post-create hook routes through. Wraps the payload in the+// canonical envelope and forwards to Publish — the broadcaster+// stamps the timestamp and event id.+func (b *AgentEventBroadcaster) PublishApprovalPending(payload AgentEventApprovalPendingPayload) {+ b.Publish(AgentEvent{+ Kind: AgentEventApprovalPending,+ Payload: payload,+ })+}+// AgentEventBroadcasterContextKey is the context key used to plumb// the broadcaster into request-scoped middleware where needed. Most// call sites don't need this — they hold a direct reference — butdiff --git a/internal/api/agent_events_test.go b/internal/api/agent_events_test.goindex 87aa2ed0af..497419bb6d 100644--- a/internal/api/agent_events_test.go+++ b/internal/api/agent_events_test.go@@ -260,3 +260,72 @@ func TestHandleAgentEvents_RequiresFlusher(t *testing.T) {t.Fatalf("expected 500 when ResponseWriter does not implement Flusher; got %d", w.statusCode)}}++func TestAgentEventBroadcaster_PublishApprovalPendingDelivers(t *testing.T) {+ // approval.pending is the second event kind the broadcaster+ // publishes (after finding.created). Pin the contract: kind name,+ // payload round-trip with the agent-decision-relevant fields,+ // monotonic id assignment shared across kinds.+ b := NewAgentEventBroadcaster()+ events, unsub := b.Subscribe()+ defer unsub()++ expires := time.Now().Add(5 * time.Minute).UTC()+ requested := time.Now().UTC()+ b.PublishApprovalPending(AgentEventApprovalPendingPayload{+ ApprovalID: "appr-1",+ ResourceID: "container:web-1",+ TargetType: "container",+ TargetID: "web-1",+ TargetName: "web-1",+ Command: "docker restart web-1",+ RiskLevel: "medium",+ RequestedBy: "ai:patrol",+ RequestedAt: requested,+ ExpiresAt: expires,+ })++ select {+ case event := <-events:+ if event.Kind != AgentEventApprovalPending {+ t.Fatalf("kind: got %q want %q", event.Kind, AgentEventApprovalPending)+ }+ if event.ID == 0 {+ t.Error("event id must be assigned")+ }+ if event.At.IsZero() {+ t.Error("event timestamp must be populated")+ }+ payload, ok := event.Payload.(AgentEventApprovalPendingPayload)+ if !ok {+ t.Fatalf("payload type: got %T want AgentEventApprovalPendingPayload", event.Payload)+ }+ if payload.ApprovalID != "appr-1" {+ t.Errorf("ApprovalID: got %q want %q", payload.ApprovalID, "appr-1")+ }+ if payload.ResourceID != "container:web-1" {+ t.Errorf("ResourceID: got %q want %q", payload.ResourceID, "container:web-1")+ }+ if payload.Command != "docker restart web-1" {+ t.Errorf("Command did not round-trip: got %q", payload.Command)+ }+ if payload.RiskLevel != "medium" {+ t.Errorf("RiskLevel did not round-trip: got %q", payload.RiskLevel)+ }+ if !payload.ExpiresAt.Equal(expires) {+ t.Errorf("ExpiresAt did not round-trip: got %v want %v", payload.ExpiresAt, expires)+ }+ case <-time.After(time.Second):+ t.Fatal("timed out waiting for approval.pending event")+ }+}++func TestAgentEventApprovalPendingKindIsStable(t *testing.T) {+ // Pin the wire-stable kind string. Renaming it breaks every agent+ // that branches on the event type; the constant is part of the+ // contract, not an implementation detail.+ if AgentEventApprovalPending != "approval.pending" {+ t.Fatalf("AgentEventApprovalPending changed: got %q want %q",+ AgentEventApprovalPending, "approval.pending")+ }+}diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.goindex d5840fa0d5..f08836da01 100644--- a/internal/api/ai_handler.go+++ b/internal/api/ai_handler.go@@ -82,30 +82,35 @@ type patrolRunHandoffProvider func(context.Context, string) (airuntime.PatrolRun// AIHandler handles all AI endpoints using direct AI integrationtype AIHandler struct {- stateMu sync.RWMutex- approvalStoreMu sync.Mutex- mtPersistence *config.MultiTenantPersistence- mtMonitor *monitoring.MultiTenantMonitor- defaultConfig *config.Config- defaultPersistence AIPersistence- hostedMode bool- defaultService AIService- agentServer *agentexec.Server- services map[string]AIService- servicesMu sync.RWMutex- serviceInitMu sync.RWMutex- serviceInit func(ctx context.Context, svc AIService)- defaultMonitor *monitoring.Monitor- unifiedStoreMu sync.RWMutex- unifiedStore *unified.UnifiedStore- unifiedStores map[string]*unified.UnifiedStore- readState unifiedresources.ReadState- recoveryManager *recoverymanager.Manager- approvalStore *approval.Store- approvalStoreDir string- approvalStoreStop context.CancelFunc- controlLevelResolver func(context.Context, *config.AIConfig) string- patrolRunProvider patrolRunHandoffProvider+ stateMu sync.RWMutex+ approvalStoreMu sync.Mutex+ mtPersistence *config.MultiTenantPersistence+ mtMonitor *monitoring.MultiTenantMonitor+ defaultConfig *config.Config+ defaultPersistence AIPersistence+ hostedMode bool+ defaultService AIService+ agentServer *agentexec.Server+ services map[string]AIService+ servicesMu sync.RWMutex+ serviceInitMu sync.RWMutex+ serviceInit func(ctx context.Context, svc AIService)+ defaultMonitor *monitoring.Monitor+ unifiedStoreMu sync.RWMutex+ unifiedStore *unified.UnifiedStore+ unifiedStores map[string]*unified.UnifiedStore+ readState unifiedresources.ReadState+ recoveryManager *recoverymanager.Manager+ approvalStore *approval.Store+ approvalStoreDir string+ approvalStoreStop context.CancelFunc+ // approvalCreatedCallback is registered via SetApprovalCreatedCallback+ // before the first approval store is built. ensureApprovalStore+ // re-installs it on every freshly created store so multi-tenant+ // re-keying or data-dir changes keep the agent SSE stream wired.+ approvalCreatedCallback func(*approval.ApprovalRequest)+ controlLevelResolver func(context.Context, *config.AIConfig) string+ patrolRunProvider patrolRunHandoffProvider}// newChatService is the factory function for creating the AI service.@@ -585,6 +590,22 @@ func (h *AIHandler) SetMultiTenantMonitor(mtm *monitoring.MultiTenantMonitor) {h.mtMonitor = mtm}+// SetApprovalCreatedCallback registers a fire-and-forget callback that+// runs after every successful approval creation. The callback is+// installed on the active approval store and re-installed on any+// future store rebuilt by ensureApprovalStore. Pass nil to clear.+//+// This is the seam the router uses to bridge approval creation into+// the agent SSE stream — see AgentEventBroadcaster.PublishApprovalPending.+func (h *AIHandler) SetApprovalCreatedCallback(cb func(*approval.ApprovalRequest)) {+ h.approvalStoreMu.Lock()+ defer h.approvalStoreMu.Unlock()+ h.approvalCreatedCallback = cb+ if h.approvalStore != nil {+ h.approvalStore.SetOnApprovalCreated(cb)+ }+}+func (h *AIHandler) ensureApprovalStore(dataDir string) {if strings.TrimSpace(dataDir) == "" {return@@ -622,6 +643,9 @@ func (h *AIHandler) ensureApprovalStore(dataDir string) {h.approvalStore = approvalStoreh.approvalStoreDir = dataDirh.approvalStoreStop = cleanupCancel+ if h.approvalCreatedCallback != nil {+ approvalStore.SetOnApprovalCreated(h.approvalCreatedCallback)+ }log.Info().Str("data_dir", dataDir).Msg("Approval store initialized")}diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 306061ab5c..d91613f51c 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -13273,6 +13273,90 @@ func TestContract_AgentEventsStreamPublishesOnFindingCreated(t *testing.T) {}}+// TestContract_AgentEventsStreamPublishesOnApprovalPending pins the+// agent SSE stream's governance-aware producer hook: the approval+// store's post-create callback must publish an approval.pending+// event so an agent holding /api/agent/events open hears about new+// pending approvals in real time without polling. The callback is+// installed via AIHandler.SetApprovalCreatedCallback so it survives+// the AIHandler's lazy approval-store rebuilds. Drift here means+// the only signal an agent has that an operator decision is needed+// is poll-based — losing the substrate's push-notification+// guarantee for governance state.+func TestContract_AgentEventsStreamPublishesOnApprovalPending(t *testing.T) {+ source, err := os.ReadFile("router.go")+ if err != nil {+ t.Fatalf("read router.go: %v", err)+ }+ src := string(source)+ if !strings.Contains(src, "r.aiHandler.SetApprovalCreatedCallback(") {+ t.Error("router.go must install the approval-created callback on AIHandler so the agent SSE stream is wired before the first approval lands")+ }+ if !strings.Contains(src, "broadcaster.PublishApprovalPending(AgentEventApprovalPendingPayload{") {+ t.Error("router.go must bridge approval creation into PublishApprovalPending — drift means agents lose the push-notification path for governance state")+ }+ if !strings.Contains(src, "ApprovalID: req.ID") {+ t.Error("approval.pending payload must carry the approval id so agents can correlate the event with /api/approvals/{id}")+ }+ if !strings.Contains(src, "ResourceID: req.CanonicalResourceID()") {+ t.Error("approval.pending payload must derive the canonical resourceId via CanonicalResourceID so agents can match it against the rest of Pulse")+ }+}++// TestContract_ApprovalStorePostCreateCallback pins the seam the+// SSE bridge depends on. The approval store must expose a+// SetOnApprovalCreated setter and CreateApproval must dispatch the+// callback on its own goroutine after the approval is persisted.+// Removing or in-lining the callback breaks the bridge silently.+func TestContract_ApprovalStorePostCreateCallback(t *testing.T) {+ source, err := os.ReadFile("../ai/approval/store.go")+ if err != nil {+ t.Fatalf("read approval/store.go: %v", err)+ }+ src := string(source)+ if !strings.Contains(src, "func (s *Store) SetOnApprovalCreated(cb func(*ApprovalRequest))") {+ t.Error("approval store must expose SetOnApprovalCreated so the API layer can bridge approval creation into the agent SSE stream")+ }+ if !strings.Contains(src, "if cb := s.onApprovalCreated; cb != nil {") {+ t.Error("CreateApproval must check the post-create callback under lock and dispatch it; drift here drops approval.pending events")+ }+ if !strings.Contains(src, "go cb(&snapshot)") {+ t.Error("post-create callback must run on its own goroutine to keep the approval hot path off any consumer's slowness")+ }+}++// TestContract_AgentEventApprovalPendingKindIsStable pins the+// wire-stable event kind string. Renaming AgentEventApprovalPending+// breaks every agent that branches on the SSE event-type field; the+// constant is part of the contract, not an implementation detail.+func TestContract_AgentEventApprovalPendingKindIsStable(t *testing.T) {+ source, err := os.ReadFile("agent_events.go")+ if err != nil {+ t.Fatalf("read agent_events.go: %v", err)+ }+ src := string(source)+ if !strings.Contains(src, `AgentEventApprovalPending AgentEventKind = "approval.pending"`) {+ t.Error("AgentEventApprovalPending must remain bound to the wire-stable string \"approval.pending\" — renaming it breaks every agent that branches on the SSE event type")+ }+}++// TestContract_SubscribeEventsCapabilityListsApprovalPending pins+// the discovery contract: the capabilities manifest must mention+// approval.pending under subscribe_events so an agent reading the+// manifest learns the kind exists without out-of-band documentation.+// Drift here means external agents miss the event entirely because+// they didn't know to listen for it.+func TestContract_SubscribeEventsCapabilityListsApprovalPending(t *testing.T) {+ source, err := os.ReadFile("agent_capabilities.go")+ if err != nil {+ t.Fatalf("read agent_capabilities.go: %v", err)+ }+ src := string(source)+ if !strings.Contains(src, "approval.pending when a remediation request enters StatusPending") {+ t.Error("subscribe_events description must mention approval.pending so agents discover the kind through the manifest")+ }+}+// TestContract_AgentCapabilitiesManifestVersionIsPinned pins the// manifest's version contract: bumping it is reserved for breaking// shape changes, additive capabilities ship under the same version.diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.goindex b67fbe39a1..c9c353203d 100644--- a/internal/api/route_inventory_test.go+++ b/internal/api/route_inventory_test.go@@ -291,6 +291,7 @@ var publicRouteAllowlist = []string{var bareRouteAllowlist = []string{"/api/agent-deploy/jobs/","/api/agent-deploy/preflights/",+ "/api/agent/capabilities","/api/agent/version","/api/agent/ws","/api/ai/oauth/callback",diff --git a/internal/api/router.go b/internal/api/router.goindex 840126a091..72aeb40bc4 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -28,6 +28,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/ai""github.com/rcourtman/pulse-go-rewrite/internal/ai/adapters"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/approval""github.com/rcourtman/pulse-go-rewrite/internal/ai/baseline""github.com/rcourtman/pulse-go-rewrite/internal/ai/chat""github.com/rcourtman/pulse-go-rewrite/internal/ai/circuit"@@ -579,6 +580,31 @@ func (r *Router) setupRoutes() {r.aiHandler = NewAIHandler(r.multiTenant, r.mtMonitor, r.agentExecServer)r.aiHandler.SetReadState(r.defaultReadState())r.aiHandler.SetRecoveryManager(recoveryManager)+ // Bridge approval creation into the agent SSE stream so an agent+ // holding /api/agent/events open hears about new pending approvals+ // in real time. The callback is fire-and-forget on the approval+ // hot path; PublishApprovalPending drops events for slow+ // subscribers rather than blocking.+ if r.agentEventBroadcaster != nil {+ broadcaster := r.agentEventBroadcaster+ r.aiHandler.SetApprovalCreatedCallback(func(req *approval.ApprovalRequest) {+ if req == nil {+ return+ }+ broadcaster.PublishApprovalPending(AgentEventApprovalPendingPayload{+ ApprovalID: req.ID,+ ResourceID: req.CanonicalResourceID(),+ TargetType: req.TargetType,+ TargetID: req.TargetID,+ TargetName: req.TargetName,+ Command: req.Command,+ RiskLevel: string(req.RiskLevel),+ RequestedBy: req.RequestedBy,+ RequestedAt: req.RequestedAt,+ ExpiresAt: req.ExpiresAt,+ })+ })+ }r.aiHandler.SetControlLevelResolver(func(ctx context.Context, cfg *config.AIConfig) string {return r.aiSettingsHandler.EffectiveControlLevel(ctx, cfg)})