Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Add /api/agent/events SSE stream for real-time agent notifications

rcourtman94bfd48a9d60
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index fadb03c0b1..d798a33180 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -917,6 +917,15 @@ profile and assignment columns, but embedded table framing must route through
## Current State
+`/api/agent/events` is the SSE stream agents subscribe to for
+real-time notifications (`finding.created` events plus a 15-second
+heartbeat keepalive). The broadcaster drops events for slow
+subscribers rather than blocking publishers, so the patrol-finding
+runtime can publish without ever stalling on consumer slowness. The
+agent runtime keeps the broadcaster wired across restarts, and the
+capabilities manifest declares the stream under `subscribe_events`
+so the surface stays self-describing.
+
`/api/agent/capabilities` is the discovery document any external
agent reads to learn what Pulse exposes. The manifest is
unauthenticated and cacheable; the underlying capabilities keep
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index ad86d4f664..ec44190c3a 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1343,6 +1343,22 @@ the canonical monitored-system blocked payload.
## Current State
+`/api/agent/events` is the agent SSE stream — the substrate piece
+that closes the agent-paradigm triangle (discovery + bundled reads +
+push notifications). Agents subscribe once and receive real-time
+notifications: `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
+the stream is alive. Each event carries a monotonic ID so agents
+can dedupe and reason about ordering. The broadcaster drops events
+for 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
+out-of-band documentation.
+
`/api/agent/capabilities` is the discovery document for Pulse's
agent surface. The manifest declares each agent-consumable
capability with stable name (snake_case agent identifier),
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index ae96a1e9d6..fcc706b531 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,14 @@ shell clickable behind another overlay.
## Current State
+The agent SSE stream at `/api/agent/events` keeps publishers
+non-blocking by design: the broadcaster's per-subscriber buffer is
+bounded (64 events) and a full buffer drops the event for that
+subscriber rather than stalling the publish path. A slow agent does
+not pin the patrol-finding hot path; many concurrent agents do not
+multiply per-finding work because each subscriber gets its own
+non-blocking send.
+
`/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
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index cd6b44f614..1922c9c5c1 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -947,6 +947,12 @@ bypass the API fail-closed execution gate.
## Current State
+The agent SSE stream at `/api/agent/events` is in-memory and
+stateless. No persistence; each connection starts fresh from the
+moment of subscribe. Agents that need to catch up across reconnects
+fetch the read endpoints (findings list, audit list) for replay —
+those are the durable surfaces.
+
The agent capabilities manifest at `/api/agent/capabilities` is
read-only and stateless — no persistence is involved. The manifest
is hand-authored in `internal/api/agent_capabilities.go`; storage
diff --git a/internal/api/agent_capabilities.go b/internal/api/agent_capabilities.go
index 0d2da200f0..d7c43eb60c 100644
--- a/internal/api/agent_capabilities.go
+++ b/internal/api/agent_capabilities.go
@@ -130,6 +130,15 @@ var agentCapabilitiesManifest = AgentCapabilitiesManifest{
Path: "/api/resources/{resourceId}/operator-state",
Scope: "monitoring:write",
},
+ {
+ 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.",
+ Category: "context",
+ Method: http.MethodGet,
+ Path: "/api/agent/events",
+ Scope: "monitoring:read",
+ ResponseShape: "text/event-stream of AgentEvent",
+ },
{
Name: "list_findings",
Description: "List all Patrol findings (active, dismissed, resolved). Filter client-side on returned shape.",
diff --git a/internal/api/agent_events.go b/internal/api/agent_events.go
new file mode 100644
index 0000000000..89460169f4
--- /dev/null
+++ b/internal/api/agent_events.go
@@ -0,0 +1,251 @@
+package api
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/rs/zerolog/log"
+)
+
+// AgentEventKind is the agent-stable event-type identifier. Values are
+// closed and snake_case-with-dot to match the convention agents use
+// for tool/event names. New kinds extend the set; existing kinds must
+// not be renamed (agents branch on them).
+type AgentEventKind string
+
+const (
+ // AgentEventFindingCreated fires when a new finding is recorded
+ // against any resource. Payload carries the finding's canonical
+ // id, resource id, severity, title, and category — enough for an
+ // agent to decide whether to fetch the full situated context.
+ AgentEventFindingCreated AgentEventKind = "finding.created"
+
+ // 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
+ // event.
+ AgentEventHeartbeat AgentEventKind = "heartbeat"
+)
+
+// AgentEvent is the agent-stable event envelope. Carries the kind, a
+// payload appropriate to the kind, and a timestamp + monotonic id
+// agents use to dedupe and resume after disconnects.
+type AgentEvent struct {
+ Kind AgentEventKind `json:"kind"`
+ ID uint64 `json:"id"`
+ At time.Time `json:"at"`
+ Payload any `json:"payload,omitempty"`
+}
+
+// AgentEventFindingCreatedPayload is the payload shape for
+// finding.created events. Narrow on purpose — the full finding
+// surface is reachable via /api/agent/resource-context/{id} or the
+// existing finding endpoints; the event is a notification, not a
+// dump.
+type AgentEventFindingCreatedPayload struct {
+ FindingID string `json:"findingId"`
+ ResourceID string `json:"resourceId"`
+ ResourceName string `json:"resourceName,omitempty"`
+ Severity string `json:"severity"`
+ Title string `json:"title"`
+ Category string `json:"category,omitempty"`
+}
+
+// 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
+// subscribes from it. Buffered per-subscriber channel keeps slow
+// consumers from stalling the publishers; if a subscriber's buffer
+// fills, the broadcaster drops events for that subscriber rather
+// than blocking the global publish path.
+type AgentEventBroadcaster struct {
+ mu sync.RWMutex
+ subscribers map[uint64]chan AgentEvent
+ nextSubID uint64
+ nextEventID uint64
+ bufSize int
+}
+
+// NewAgentEventBroadcaster creates a broadcaster with a per-subscriber
+// buffer of 64 events. Picked to be generous enough for a slow agent
+// to catch up across a brief stall without losing events, but small
+// enough that runaway publishers don't pin large amounts of memory
+// per subscriber.
+func NewAgentEventBroadcaster() *AgentEventBroadcaster {
+ return &AgentEventBroadcaster{
+ subscribers: make(map[uint64]chan AgentEvent),
+ bufSize: 64,
+ }
+}
+
+// Subscribe registers a new subscriber and returns its channel + an
+// unsubscribe function the caller MUST call to release the
+// subscription. The channel is closed by the broadcaster only when
+// the broadcaster itself is shutting down; ordinary unsubscription
+// stops sending without closing.
+func (b *AgentEventBroadcaster) Subscribe() (<-chan AgentEvent, func()) {
+ b.mu.Lock()
+ id := b.nextSubID
+ b.nextSubID++
+ ch := make(chan AgentEvent, b.bufSize)
+ b.subscribers[id] = ch
+ b.mu.Unlock()
+
+ unsubscribe := func() {
+ b.mu.Lock()
+ if existing, ok := b.subscribers[id]; ok {
+ delete(b.subscribers, id)
+ close(existing)
+ }
+ b.mu.Unlock()
+ }
+ return ch, unsubscribe
+}
+
+// Publish fans out an event to every current subscriber. The event's
+// ID is assigned by the broadcaster (monotonic, never reused);
+// callers populate Kind, At, and Payload. Slow subscribers (full
+// channel) get the event dropped rather than blocking the publish
+// path — agents that need replay must use a different mechanism
+// (none currently exposed; future event log can layer on top).
+func (b *AgentEventBroadcaster) Publish(event AgentEvent) {
+ if event.At.IsZero() {
+ event.At = time.Now().UTC()
+ }
+ event.ID = atomic.AddUint64(&b.nextEventID, 1)
+
+ b.mu.RLock()
+ defer b.mu.RUnlock()
+ for _, ch := range b.subscribers {
+ select {
+ case ch <- event:
+ default:
+ // Full buffer; drop and log so we can spot subscribers
+ // that are consistently lagging. Dropping is the right
+ // call for an agent-paradigm stream — better to keep
+ // publishing than to block the publish path.
+ log.Warn().
+ Str("kind", string(event.Kind)).
+ Uint64("event_id", event.ID).
+ Msg("Agent events: dropping event for slow subscriber")
+ }
+ }
+}
+
+// SubscriberCount returns the number of current subscribers. Used by
+// tests; not exposed on the wire.
+func (b *AgentEventBroadcaster) SubscriberCount() int {
+ b.mu.RLock()
+ defer b.mu.RUnlock()
+ return len(b.subscribers)
+}
+
+// HandleAgentEvents serves `GET /api/agent/events` — the SSE stream
+// agents subscribe to for real-time notifications. The connection
+// stays open until the client disconnects or the request context
+// cancels. Heartbeats fire every 15s so an agent holding an idle
+// connection can confirm the stream is alive.
+//
+// SSE chosen over WebSocket because it's simpler (one-way, no
+// frame-handling), works through every HTTP proxy without
+// special-casing, and matches the existing deploy_handlers pattern.
+// Agents that need bidirectional comms can call the REST endpoints
+// in the capabilities manifest in parallel.
+func (b *AgentEventBroadcaster) HandleAgentEvents(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ flusher, ok := w.(http.Flusher)
+ if !ok {
+ http.Error(w, "Streaming not supported", http.StatusInternalServerError)
+ return
+ }
+
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.Header().Set("Cache-Control", "no-cache")
+ w.Header().Set("Connection", "keep-alive")
+ // Disable buffering by reverse proxies (nginx in particular)
+ // that otherwise hold the response until enough bytes accumulate.
+ w.Header().Set("X-Accel-Buffering", "no")
+
+ events, unsubscribe := b.Subscribe()
+ defer unsubscribe()
+
+ // Initial sync event so agents that just connected can confirm
+ // the stream is open before the first real event lands. This is
+ // distinct from heartbeat: the connected event fires once at
+ // subscribe time, the heartbeat fires periodically.
+ writeAgentSSEEvent(w, AgentEvent{
+ Kind: "stream.connected",
+ At: time.Now().UTC(),
+ })
+ flusher.Flush()
+
+ heartbeat := time.NewTicker(15 * time.Second)
+ defer heartbeat.Stop()
+
+ for {
+ select {
+ case <-r.Context().Done():
+ return
+ case event, open := <-events:
+ if !open {
+ return
+ }
+ writeAgentSSEEvent(w, event)
+ flusher.Flush()
+ case <-heartbeat.C:
+ b.Publish(AgentEvent{Kind: AgentEventHeartbeat})
+ }
+ }
+}
+
+// writeAgentSSEEvent serializes an AgentEvent as a Server-Sent Event
+// frame. Uses the `event:` field so agents can dispatch via
+// EventSource.addEventListener(kind, ...) rather than parsing every
+// event manually.
+func writeAgentSSEEvent(w http.ResponseWriter, event AgentEvent) {
+ data, err := json.Marshal(event)
+ if err != nil {
+ log.Error().Err(err).Str("kind", string(event.Kind)).Msg("Agent events: failed to marshal event")
+ return
+ }
+ if event.Kind != "" {
+ fmt.Fprintf(w, "event: %s\n", event.Kind)
+ }
+ if event.ID != 0 {
+ fmt.Fprintf(w, "id: %d\n", event.ID)
+ }
+ fmt.Fprintf(w, "data: %s\n\n", data)
+}
+
+// PublishFindingCreated is a convenience publisher for the most
+// common event kind. The findings runtime calls this when a new
+// finding is added; the implementation enriches the event with the
+// canonical timestamp and a reference to the broadcaster, keeping
+// the call site free of broadcaster plumbing.
+func (b *AgentEventBroadcaster) PublishFindingCreated(payload AgentEventFindingCreatedPayload) {
+ b.Publish(AgentEvent{
+ Kind: AgentEventFindingCreated,
+ 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 — but
+// keeping it here makes the dependency explicit.
+type agentEventBroadcasterContextKey struct{}
+
+// ContextWithAgentEventBroadcaster attaches a broadcaster to a
+// context. Used by integration tests that need to inject a fake
+// broadcaster.
+func ContextWithAgentEventBroadcaster(ctx context.Context, b *AgentEventBroadcaster) context.Context {
+ return context.WithValue(ctx, agentEventBroadcasterContextKey{}, b)
+}
diff --git a/internal/api/agent_events_test.go b/internal/api/agent_events_test.go
new file mode 100644
index 0000000000..87aa2ed0af
--- /dev/null
+++ b/internal/api/agent_events_test.go
@@ -0,0 +1,262 @@
+package api
+
+import (
+ "bufio"
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestAgentEventBroadcaster_SubscribeReceivesPublishedEvents(t *testing.T) {
+ b := NewAgentEventBroadcaster()
+ events, unsubscribe := b.Subscribe()
+ defer unsubscribe()
+
+ b.PublishFindingCreated(AgentEventFindingCreatedPayload{
+ FindingID: "f1",
+ ResourceID: "vm:101",
+ Severity: "warning",
+ Title: "CPU saturated",
+ })
+
+ select {
+ case event := <-events:
+ if event.Kind != AgentEventFindingCreated {
+ t.Errorf("kind: got %q want %q", event.Kind, AgentEventFindingCreated)
+ }
+ if event.ID == 0 {
+ t.Error("event ID must be assigned by the broadcaster (monotonic)")
+ }
+ if event.At.IsZero() {
+ t.Error("event timestamp must be populated")
+ }
+ case <-time.After(time.Second):
+ t.Fatal("timed out waiting for event")
+ }
+}
+
+func TestAgentEventBroadcaster_UnsubscribeStopsDelivery(t *testing.T) {
+ b := NewAgentEventBroadcaster()
+ events, unsubscribe := b.Subscribe()
+
+ unsubscribe()
+
+ // After unsubscribe the channel must be closed; receive should
+ // drain whatever was buffered then return zero-value with !ok.
+ b.PublishFindingCreated(AgentEventFindingCreatedPayload{FindingID: "f-after"})
+
+ select {
+ case _, open := <-events:
+ if open {
+ t.Error("channel must be closed after unsubscribe; agents that resubscribe should get a fresh channel")
+ }
+ case <-time.After(time.Second):
+ t.Fatal("timed out waiting for channel close")
+ }
+}
+
+func TestAgentEventBroadcaster_FanOutToMultipleSubscribers(t *testing.T) {
+ b := NewAgentEventBroadcaster()
+ a1, unsub1 := b.Subscribe()
+ defer unsub1()
+ a2, unsub2 := b.Subscribe()
+ defer unsub2()
+
+ b.PublishFindingCreated(AgentEventFindingCreatedPayload{FindingID: "fan-out"})
+
+ deadline := time.After(time.Second)
+ for _, ch := range []<-chan AgentEvent{a1, a2} {
+ select {
+ case event := <-ch:
+ if event.Payload == nil {
+ t.Error("event payload must round-trip to all subscribers")
+ }
+ case <-deadline:
+ t.Fatal("a subscriber did not receive the published event")
+ }
+ }
+}
+
+func TestAgentEventBroadcaster_DropsForSlowSubscriber(t *testing.T) {
+ // Slow consumers that don't drain their channel must not stall
+ // the publish path. Fill the buffer past capacity and verify
+ // publishes don't block.
+ b := NewAgentEventBroadcaster()
+ _, unsub := b.Subscribe() // never read
+ defer unsub()
+
+ done := make(chan struct{})
+ go func() {
+ // Publish more than the buffer's bufSize. The publish must
+ // not block; if it did the goroutine would not finish and
+ // the test would time out.
+ for i := 0; i < 200; i++ {
+ b.PublishFindingCreated(AgentEventFindingCreatedPayload{FindingID: "spam"})
+ }
+ close(done)
+ }()
+
+ select {
+ case <-done:
+ // Pass: publishes did not block on the slow subscriber.
+ case <-time.After(2 * time.Second):
+ t.Fatal("publish path stalled on a slow subscriber; broadcaster must drop rather than block")
+ }
+}
+
+func TestAgentEventBroadcaster_AssignsMonotonicIDs(t *testing.T) {
+ b := NewAgentEventBroadcaster()
+ events, unsub := b.Subscribe()
+ defer unsub()
+
+ for i := 0; i < 3; i++ {
+ b.PublishFindingCreated(AgentEventFindingCreatedPayload{FindingID: "mono"})
+ }
+
+ var ids []uint64
+ for i := 0; i < 3; i++ {
+ select {
+ case event := <-events:
+ ids = append(ids, event.ID)
+ case <-time.After(time.Second):
+ t.Fatalf("timed out at i=%d", i)
+ }
+ }
+ for i := 1; i < len(ids); i++ {
+ if ids[i] <= ids[i-1] {
+ t.Errorf("event IDs must be strictly monotonic; got %v", ids)
+ break
+ }
+ }
+}
+
+func TestHandleAgentEvents_RejectsNonGet(t *testing.T) {
+ b := NewAgentEventBroadcaster()
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPost, "/api/agent/events", nil)
+ b.HandleAgentEvents(rec, req)
+ if rec.Code != http.StatusMethodNotAllowed {
+ t.Fatalf("expected 405; got %d", rec.Code)
+ }
+}
+
+func TestHandleAgentEvents_StreamsConnectedAndPublishedEvents(t *testing.T) {
+ b := NewAgentEventBroadcaster()
+
+ server := httptest.NewServer(http.HandlerFunc(b.HandleAgentEvents))
+ defer server.Close()
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL, nil)
+ if err != nil {
+ t.Fatalf("NewRequestWithContext: %v", err)
+ }
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatalf("Do: %v", err)
+ }
+ defer resp.Body.Close()
+
+ // Pin the streaming-response contract: text/event-stream content
+ // type, no-cache, and X-Accel-Buffering off so reverse proxies
+ // don't buffer the response.
+ if got := resp.Header.Get("Content-Type"); got != "text/event-stream" {
+ t.Errorf("Content-Type: got %q want text/event-stream", got)
+ }
+ if got := resp.Header.Get("Cache-Control"); got != "no-cache" {
+ t.Errorf("Cache-Control: got %q want no-cache", got)
+ }
+ if got := resp.Header.Get("X-Accel-Buffering"); got != "no" {
+ t.Errorf("X-Accel-Buffering must be 'no' so nginx doesn't buffer; got %q", got)
+ }
+
+ // Wait for at least one subscriber so the publish below
+ // definitely lands; the stream-connected event should have
+ // already been written.
+ deadline := time.Now().Add(2 * time.Second)
+ for time.Now().Before(deadline) && b.SubscriberCount() == 0 {
+ time.Sleep(10 * time.Millisecond)
+ }
+ if b.SubscriberCount() == 0 {
+ t.Fatal("no subscriber registered after handler started")
+ }
+
+ // Publish a finding event so the read loop sees content beyond
+ // the connected event.
+ b.PublishFindingCreated(AgentEventFindingCreatedPayload{
+ FindingID: "f-stream",
+ Severity: "critical",
+ Title: "Streamed",
+ })
+
+ // Read the response in a goroutine; close the context after we've
+ // seen what we expect so the handler returns and the test does
+ // not hang on the open stream.
+ got := make(chan string, 1)
+ go func() {
+ scanner := bufio.NewScanner(resp.Body)
+ var collected strings.Builder
+ for scanner.Scan() {
+ collected.WriteString(scanner.Text())
+ collected.WriteString("\n")
+ text := collected.String()
+ if strings.Contains(text, "\"kind\":\"finding.created\"") {
+ got <- text
+ return
+ }
+ }
+ }()
+
+ select {
+ case payload := <-got:
+ if !strings.Contains(payload, "stream.connected") {
+ t.Error("expected stream.connected event before any published events")
+ }
+ if !strings.Contains(payload, "f-stream") {
+ t.Error("published finding payload must reach the wire")
+ }
+ // Cancel context so handler exits cleanly.
+ cancel()
+ case <-time.After(3 * time.Second):
+ t.Fatal("timed out waiting for finding.created event on the stream")
+ }
+}
+
+// nonFlushingResponseWriter is a ResponseWriter that explicitly does
+// NOT implement http.Flusher, so we can verify the SSE handler
+// degrades cleanly on writers that can't stream. Standard
+// httptest.ResponseRecorder satisfies Flusher (as a no-op) so it
+// can't be used to test this branch.
+type nonFlushingResponseWriter struct {
+ header http.Header
+ body strings.Builder
+ statusCode int
+}
+
+func newNonFlushingResponseWriter() *nonFlushingResponseWriter {
+ return &nonFlushingResponseWriter{header: make(http.Header), statusCode: http.StatusOK}
+}
+
+func (w *nonFlushingResponseWriter) Header() http.Header { return w.header }
+func (w *nonFlushingResponseWriter) WriteHeader(code int) { w.statusCode = code }
+func (w *nonFlushingResponseWriter) Write(b []byte) (int, error) {
+ return w.body.Write(b)
+}
+
+func TestHandleAgentEvents_RequiresFlusher(t *testing.T) {
+ // Without a Flusher, SSE responses would buffer indefinitely on
+ // the server before reaching the agent. The handler must refuse
+ // rather than open a stream that never delivers.
+ b := NewAgentEventBroadcaster()
+ w := newNonFlushingResponseWriter()
+ req := httptest.NewRequest(http.MethodGet, "/api/agent/events", nil)
+ b.HandleAgentEvents(w, req)
+ if w.statusCode != http.StatusInternalServerError {
+ t.Fatalf("expected 500 when ResponseWriter does not implement Flusher; got %d", w.statusCode)
+ }
+}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 943c6130b2..c7a77f489e 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -13233,6 +13233,28 @@ func assertJSONSnapshot(t *testing.T, got []byte, want string) {
}
}
+// TestContract_AgentEventsStreamPublishesOnFindingCreated pins the
+// agent SSE stream's most consequential producer hook: the
+// findings-runtime callback in router.go must publish a
+// finding.created event when a finding is new AND not auto-dismissed
+// by operator-state suppression. Without this guard, every
+// patrol-cycle re-detection would fire an event (noise) and findings
+// the operator already silenced would still notify (contradicting
+// slice 31/32 suppression semantics).
+func TestContract_AgentEventsStreamPublishesOnFindingCreated(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, "PublishFindingCreated(AgentEventFindingCreatedPayload{") {
+ t.Error("router.go must publish finding.created events to the agent stream when a new finding is added")
+ }
+ if !strings.Contains(src, "isNew && r.agentEventBroadcaster != nil && f.DismissedReason == \"\"") {
+ t.Error("publish gate must fire only when isNew, broadcaster wired, and finding not auto-dismissed by operator-state — otherwise the stream contradicts the suppression contract")
+ }
+}
+
// 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.go
index 32d53a2a32..b67fbe39a1 100644
--- a/internal/api/route_inventory_test.go
+++ b/internal/api/route_inventory_test.go
@@ -412,6 +412,7 @@ var allRouteAllowlist = []string{
"/api/resources/{id}/operator-state",
"/api/agent/resource-context/{id}",
"/api/agent/capabilities",
+ "/api/agent/events",
"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.go
index 1352664302..a84b556bda 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -86,6 +86,7 @@ type Router struct {
discoveryHandlers *DiscoveryHandlers
resourceHandlers *ResourceHandlers
agentContextHandler *AgentContextHandler
+ agentEventBroadcaster *AgentEventBroadcaster
resourceRegistry *unifiedresources.ResourceRegistry
trueNASPoller *monitoring.TrueNASPoller
vmwarePoller *monitoring.VMwarePoller
@@ -409,6 +410,7 @@ func (r *Router) setupRoutes() {
r.kubernetesAgentHandlers.SetRecoveryIngestor(r.recoveryHandlers)
r.resourceHandlers = NewResourceHandlers(r.config)
r.agentContextHandler = NewAgentContextHandler(r.resourceHandlers)
+ r.agentEventBroadcaster = NewAgentEventBroadcaster()
if r.resourceHandlers != nil {
if store, err := r.resourceHandlers.getStore("default"); err == nil && store != nil {
r.monitorResourceAdapter = unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(store))
@@ -1747,6 +1749,25 @@ func (r *Router) startPatrolForContext(ctx context.Context, orgID string) bool {
RemindAt: f.RemindAt,
}
_, isNew := unifiedStore.AddFromAI(uf)
+ // Publish a finding.created event to the agent SSE
+ // stream when the finding is new and not auto-dismissed
+ // by operator-state suppression. Skip on update
+ // (re-detection of an existing finding) so agents
+ // aren't notified about every patrol cycle's
+ // re-confirmation; skip when DismissedReason is
+ // populated because the operator already said to stay
+ // quiet about this resource. Fire-and-forget — slow
+ // subscribers don't block the patrol loop.
+ if isNew && r.agentEventBroadcaster != nil && f.DismissedReason == "" {
+ r.agentEventBroadcaster.PublishFindingCreated(AgentEventFindingCreatedPayload{
+ FindingID: f.ID,
+ ResourceID: f.ResourceID,
+ ResourceName: f.ResourceName,
+ Severity: string(f.Severity),
+ Title: f.Title,
+ Category: string(f.Category),
+ })
+ }
return isNew
})
patrol.SetUnifiedFindingResolver(func(findingID string) {
diff --git a/internal/api/router_routes_monitoring.go b/internal/api/router_routes_monitoring.go
index c91a43d4b0..52f7f07710 100644
--- a/internal/api/router_routes_monitoring.go
+++ b/internal/api/router_routes_monitoring.go
@@ -68,6 +68,13 @@ func (r *Router) registerMonitoringResourceRoutes(
// themselves keep their own auth scopes. Agents fetch this once at
// startup to learn what's available.
r.mux.HandleFunc("/api/agent/capabilities", HandleAgentCapabilitiesManifest)
+ // Agent SSE event stream — agents subscribe once and receive
+ // real-time notifications instead of polling. Auth at
+ // monitoring:read because the stream surfaces the same
+ // information already available via the read endpoints.
+ if r.agentEventBroadcaster != nil {
+ r.mux.HandleFunc("/api/agent/events", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.agentEventBroadcaster.HandleAgentEvents)))
+ }
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)))