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.

Use cursor-help on TagBadges hover-only +N indicator

rcourtman7fe9b1c49227
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 3f95181918..3e956dce18 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -927,13 +927,20 @@ enforces downstream — no possible drift between "what Patrol
proposes" and "what the broker accepts."
`/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.
+real-time notifications: `finding.created` when a new finding is
+raised, `approval.pending` when a remediation request enters
+StatusPending and waits on operator decision, `action.completed`
+when an action audit reaches a terminal state (Completed,
+runtime-Failed, or refused-before-dispatch with stable
+`plan_drift:` / `resource_remediation_locked:` error-token
+prefixes preserved verbatim), and a 15-second heartbeat keepalive.
+The broadcaster drops events for slow subscribers rather than
+blocking publishers, so the patrol-finding runtime, the approval
+store's post-create callback, and the executor's post-completion
+callback 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
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 4361d33138..b2861dcc92 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -608,6 +608,20 @@ approvals (the common shape on the approval hot path) still carry
a canonical resource id agents can match against the rest of
Pulse.
+`PulseToolExecutor` exposes `SetOnActionCompleted(cb)` as the
+parallel seam for action-audit terminal states. The action-audit
+hot path in `internal/ai/tools/action_audit.go` routes every
+terminal-state record (Completed, runtime-Failed, plan-drift
+refusal, operator-lock refusal, recovery-branch fail) through a
+single helper `publishActionCompleted(record)` which guards on
+nil callback, defensively filters non-terminal states, and fires
+the callback on its own goroutine after the audit record has
+been persisted. Refused-before-dispatch failures preserve the
+canonical `plan_drift:` and `resource_remediation_locked:`
+error-token prefixes on `record.Result.ErrorMessage` so the agent
+SSE stream's `action.completed` payload carries them verbatim —
+agents branch on the prefix rather than parsing human text.
+
The investigation runtime now hands the orchestrator a Finding
pre-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.md
index 0c60870416..f1c31bf0f6 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1363,17 +1363,22 @@ notifications: `finding.created` when a new finding is raised
`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
+behind `/api/approvals/{id}`, the event is a doorbell),
+`action.completed` when an action audit reaches a terminal state —
+Completed, runtime-Failed, or refused-before-dispatch (refusals
+carry the stable error-token prefix `plan_drift:` or
+`resource_remediation_locked:` verbatim on `errorMessage` so agents
+branch on the prefix rather than parsing human text) — 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, 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 without
+post-create callback, the executor's post-completion callback)
+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.
The approval store exposes `SetOnApprovalCreated(cb)` so the API
@@ -1392,6 +1397,25 @@ 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.
+`PulseToolExecutor` exposes `SetOnActionCompleted(cb)` as the
+parallel seam for action-audit terminal states. Every dispatch
+that reaches `ActionStateCompleted` or `ActionStateFailed` —
+including refused-before-dispatch refusals routed through the
+plan-drift and operator-lock guards in `executeCommandWithAudit`,
+the per-execution result lane shared by `executeCommandWithAudit`
+and `executeNativeActionWithAudit`, and the recovery branch when
+state-machine normalization fails — calls
+`publishActionCompleted(record)`, which dispatches the callback on
+its own goroutine after the audit record has already been
+persisted. The callback is installed once per chat-service per
+org through `wireAIChatDependenciesForService` against
+`chatService.GetExecutor()`, so multi-tenant chat-service rebuilds
+re-wire the bridge without coupling the tools package to the api
+package. `action.completed` payloads preserve the canonical
+refusal-token prefixes (`plan_drift:`, `resource_remediation_locked:`)
+on `errorMessage` verbatim so agents branch on the stable code
+without parsing human messages.
+
`/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 736d5f41a0..05ee069b26 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -521,7 +521,15 @@ 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.
+non-blocking send. The same guarantee extends to the governance and
+action-audit producers wired through the same broadcaster:
+`approval.pending` events fire from the approval store's post-create
+callback on its own goroutine after the approval is persisted, and
+`action.completed` events fire from `PulseToolExecutor`'s
+post-completion callback on its own goroutine after the audit
+record is persisted. Goroutine dispatch keeps the approval and
+dispatch hot paths independent of consumer drain rate; per-event
+cost is one channel send per subscriber.
`/api/agent/resource-context/{id}` does at most three reads per
request: one operator-state SQLite point lookup (already covered by
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 37e5412ef9..be7edcb5c9 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -957,8 +957,13 @@ through the same provider over the same durable table.
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.
+fetch the read endpoints (findings list, approvals list, audit
+list) for replay — those are the durable surfaces. The
+`approval.pending` and `action.completed` events fire after the
+canonical record (approval row or action-audit row) has already
+been persisted, so a missed event is recoverable by reading the
+backing endpoint; the stream is a doorbell for recent activity,
+not the source of truth.
The agent capabilities manifest at `/api/agent/capabilities` is
read-only and stateless — no persistence is involved. The manifest
diff --git a/internal/ai/tools/action_audit.go b/internal/ai/tools/action_audit.go
index 58e270bfac..d4ccdceabe 100644
--- a/internal/ai/tools/action_audit.go
+++ b/internal/ai/tools/action_audit.go
@@ -131,6 +131,7 @@ func (e *PulseToolExecutor) executeCommandWithAudit(
}
e.recordActionAudit(record)
e.recordActionLifecycle(record.ID, unifiedresources.ActionStateFailed, requestedBy, "plan drift refused")
+ e.publishActionCompleted(record)
return nil, driftErr
}
}
@@ -161,6 +162,7 @@ func (e *PulseToolExecutor) executeCommandWithAudit(
}
e.recordActionAudit(record)
e.recordActionLifecycle(record.ID, unifiedresources.ActionStateFailed, requestedBy, "resource remediation lock refused")
+ e.publishActionCompleted(record)
return nil, unifiedresources.ErrResourceRemediationLocked
}
@@ -495,12 +497,14 @@ func (e *PulseToolExecutor) recordActionExecutionResult(record unifiedresources.
}
e.recordActionAudit(record)
e.recordActionLifecycle(record.ID, record.State, actor, message)
+ e.publishActionCompleted(record)
return record
}
if strings.TrimSpace(message) != "" {
event.Message = strings.TrimSpace(message)
}
if e == nil || e.actionAuditStore == nil {
+ e.publishActionCompleted(completed)
return completed
}
if err := e.actionAuditStore.RecordActionExecutionResult(completed, event); err != nil {
@@ -510,6 +514,7 @@ func (e *PulseToolExecutor) recordActionExecutionResult(record unifiedresources.
Str("state", string(completed.State)).
Msg("failed to persist action execution result")
}
+ e.publishActionCompleted(completed)
return completed
}
@@ -526,6 +531,30 @@ func (e *PulseToolExecutor) recordActionAudit(record unifiedresources.ActionAudi
}
}
+// publishActionCompleted dispatches the executor's post-completion
+// callback, if installed. Fire-and-forget on its own goroutine: the
+// callback runs after the audit record has already been persisted,
+// so a panic or stall on the consumer side must not back up the
+// dispatch hot path. Snapshots the record by value so the consumer
+// reads a stable view independent of any subsequent record
+// mutations on the originating goroutine.
+func (e *PulseToolExecutor) publishActionCompleted(record unifiedresources.ActionAuditRecord) {
+ if e == nil {
+ return
+ }
+ cb := e.onActionCompleted
+ if cb == nil {
+ return
+ }
+ if record.State != unifiedresources.ActionStateCompleted && record.State != unifiedresources.ActionStateFailed {
+ // Defensive — only Completed/Failed are terminal states the
+ // agent SSE stream surfaces. Any other state would confuse
+ // agents that branch on "this action is done."
+ return
+ }
+ go cb(record)
+}
+
func (e *PulseToolExecutor) recordActionLifecycle(actionID string, state unifiedresources.ActionState, actor, message string) {
if e == nil || e.actionAuditStore == nil || strings.TrimSpace(actionID) == "" {
return
diff --git a/internal/ai/tools/action_audit_execution_test.go b/internal/ai/tools/action_audit_execution_test.go
index 0c22a32c57..4d8a278cc4 100644
--- a/internal/ai/tools/action_audit_execution_test.go
+++ b/internal/ai/tools/action_audit_execution_test.go
@@ -1137,3 +1137,153 @@ func TestExecuteCommandWithAuditAllowsDispatchWhenResourceUnlocked(t *testing.T)
}
agentServer.AssertCalled(t, "ExecuteCommand", mock.Anything, "agent-allowed", mock.Anything)
}
+
+func TestSetOnActionCompleted_FiresOnSuccessfulDispatch(t *testing.T) {
+ // The post-completion callback is the seam the API layer uses to
+ // bridge action audits into the agent SSE stream
+ // (action.completed events). Pin the contract: the callback
+ // fires once per terminal-state record, sees the persisted
+ // audit, and runs without blocking the dispatch caller —
+ // fire-and-forget on its own goroutine.
+ store := unifiedresources.NewMemoryStore()
+ agentServer := &mockAgentServer{}
+ agentServer.On("ExecuteCommand", mock.Anything, "agent-cb", mock.Anything).
+ Return(&agentexec.CommandResultPayload{Success: true, Stdout: "ok", ExitCode: 0}, nil).Once()
+
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ AgentServer: agentServer,
+ ActionAuditStore: store,
+ })
+
+ got := make(chan unifiedresources.ActionAuditRecord, 1)
+ executor.SetOnActionCompleted(func(rec unifiedresources.ActionAuditRecord) {
+ got <- rec
+ })
+
+ if _, err := executor.executeCommandWithAudit(
+ context.Background(),
+ "pulse_control",
+ "agent-cb",
+ "",
+ false,
+ "agent-cb",
+ agentexec.ExecuteCommandPayload{
+ Command: "uptime",
+ TargetType: "agent",
+ TargetID: "agent-cb",
+ },
+ "pulse_control",
+ "run uptime",
+ ); err != nil {
+ t.Fatalf("executeCommandWithAudit: %v", err)
+ }
+
+ select {
+ case received := <-got:
+ if received.State != unifiedresources.ActionStateCompleted {
+ t.Errorf("callback record state = %q, want %q", received.State, unifiedresources.ActionStateCompleted)
+ }
+ if received.ID == "" {
+ t.Error("callback record must carry the canonical action id")
+ }
+ if received.Request.ResourceID != "agent-cb" {
+ t.Errorf("callback resource id = %q, want %q", received.Request.ResourceID, "agent-cb")
+ }
+ if received.Result == nil || !received.Result.Success {
+ t.Errorf("callback result must surface success: %#v", received.Result)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("post-completion callback did not fire within 2s")
+ }
+}
+
+func TestSetOnActionCompleted_FiresOnPlanDriftRefusal(t *testing.T) {
+ // Plan-drift refusal lands in the audit store as Failed with the
+ // stable `plan_drift:` prefix; the callback must surface that
+ // terminal state so agents can branch on the refusal token
+ // without polling.
+ now := time.Date(2026, 5, 9, 9, 30, 0, 0, time.UTC)
+ approvedPlan := unifiedresources.ActionPlan{
+ ActionID: "drift-action",
+ RequestID: "appr-drift",
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: unifiedresources.ApprovalAdmin,
+ PlannedAt: now,
+ ExpiresAt: now.Add(5 * time.Minute),
+ PlanHash: "approved-but-drifted",
+ Message: "approved reason",
+ }
+ approvedReq := &approval.ApprovalRequest{
+ ID: "appr-drift",
+ Command: "approved-cmd",
+ TargetType: "agent",
+ TargetID: "agent-drift",
+ TargetName: "agent-drift",
+ Status: approval.StatusApproved,
+ Plan: &approvedPlan,
+ RequestedAt: now,
+ ExpiresAt: now.Add(5 * time.Minute),
+ }
+ approvalStoreOriginal := approval.GetStore()
+ defer approval.SetStore(approvalStoreOriginal)
+ memStore := unifiedresources.NewMemoryStore()
+ approvalStoreLocal, err := approval.NewStore(approval.StoreConfig{
+ DataDir: t.TempDir(),
+ DefaultTimeout: 5 * time.Minute,
+ DisablePersistence: true,
+ })
+ if err != nil {
+ t.Fatalf("approval.NewStore: %v", err)
+ }
+ if err := approvalStoreLocal.CreateApproval(approvedReq); err != nil {
+ t.Fatalf("CreateApproval: %v", err)
+ }
+ approval.SetStore(approvalStoreLocal)
+
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ AgentServer: &mockAgentServer{},
+ ActionAuditStore: memStore,
+ })
+
+ got := make(chan unifiedresources.ActionAuditRecord, 1)
+ executor.SetOnActionCompleted(func(rec unifiedresources.ActionAuditRecord) {
+ got <- rec
+ })
+
+ // Submit a payload whose hash will not match the approved plan.
+ if _, dispatchErr := executor.executeCommandWithAudit(
+ context.Background(),
+ "pulse_control",
+ "agent-drift",
+ "appr-drift",
+ true,
+ "agent-drift",
+ agentexec.ExecuteCommandPayload{
+ Command: "different-cmd",
+ TargetType: "agent",
+ TargetID: "agent-drift",
+ },
+ "pulse_control",
+ "different reason",
+ ); dispatchErr == nil {
+ t.Fatal("expected plan-drift refusal; got nil error")
+ } else if !strings.Contains(dispatchErr.Error(), "plan") {
+ // Defensive: the validator's exact error wording can evolve;
+ // just confirm we got an error from the drift path rather
+ // than from somewhere else.
+ t.Logf("drift error: %v", dispatchErr)
+ }
+
+ select {
+ case received := <-got:
+ if received.State != unifiedresources.ActionStateFailed {
+ t.Errorf("refusal state = %q, want %q", received.State, unifiedresources.ActionStateFailed)
+ }
+ if received.Result == nil || !strings.HasPrefix(received.Result.ErrorMessage, "plan_drift:") {
+ t.Errorf("refusal must carry plan_drift: prefix on ErrorMessage; got %#v", received.Result)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("plan-drift callback did not fire within 2s")
+ }
+}
diff --git a/internal/ai/tools/executor.go b/internal/ai/tools/executor.go
index b07eeb9fb7..a6fd573635 100644
--- a/internal/ai/tools/executor.go
+++ b/internal/ai/tools/executor.go
@@ -532,6 +532,14 @@ type PulseToolExecutor struct {
appContainerActionProvider AppContainerActionProvider
appContainerReadProvider AppContainerReadProvider
actionAuditStore unifiedresources.ResourceStore
+ // onActionCompleted fires after a terminal-state action audit
+ // (Completed or Failed, including refused-before-dispatch
+ // failures) is persisted. Wired by the API layer through the
+ // per-org chat-service init so the agent SSE stream can publish
+ // action.completed events. nil is safe — the callback is
+ // fire-and-forget on its own goroutine to keep the dispatch hot
+ // path off any consumer's slowness.
+ onActionCompleted func(unifiedresources.ActionAuditRecord)
// Typed state reader. Nil means "legacy-only": tools must fall back to StateSnapshot access.
readState unifiedresources.ReadState
@@ -889,6 +897,22 @@ func (e *PulseToolExecutor) SetActionAuditStore(store unifiedresources.ResourceS
e.actionAuditStore = store
}
+// SetOnActionCompleted installs a fire-and-forget callback that runs
+// after every terminal-state action audit is persisted (Completed or
+// Failed, including refused-before-dispatch failures with stable
+// `plan_drift:` / `resource_remediation_locked:` error prefixes).
+// Pass nil to disable. Used by the API layer to bridge action
+// completion into the agent SSE stream without coupling the tools
+// package to the api package. The callback runs on its own
+// goroutine; consumers must not assume immediate or in-order
+// delivery relative to subsequent dispatches.
+func (e *PulseToolExecutor) SetOnActionCompleted(cb func(unifiedresources.ActionAuditRecord)) {
+ if e == nil {
+ return
+ }
+ e.onActionCompleted = cb
+}
+
// GetActionAuditStore returns the durable store used to persist action audit and lifecycle events.
func (e *PulseToolExecutor) GetActionAuditStore() unifiedresources.ResourceStore {
return e.actionAuditStore
diff --git a/internal/api/agent_capabilities.go b/internal/api/agent_capabilities.go
index 75f5dcc383..fa00749e36 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, approval.pending when a remediation request enters StatusPending and waits on operator decision, 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, action.completed when an action audit reaches a terminal state (Completed or Failed, including refused-before-dispatch failures with stable error-token prefixes), 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.go
index 1e5f98f173..e85e1915b7 100644
--- a/internal/api/agent_events.go
+++ b/internal/api/agent_events.go
@@ -34,6 +34,16 @@ const (
// fetch full context via the approval endpoints, or escalate.
AgentEventApprovalPending AgentEventKind = "approval.pending"
+ // AgentEventActionCompleted fires when an action audit reaches a
+ // terminal state — Completed (executed and verified) or Failed
+ // (refused before dispatch with a stable error-token prefix, or
+ // errored during execution). Payload carries the canonical action
+ // id, the resource it targeted, the capability and command, the
+ // outcome (success bool + optional error message), who acted,
+ // and the completion timestamp — enough for an agent to close
+ // the dispatch loop without polling the audit endpoint.
+ AgentEventActionCompleted AgentEventKind = "action.completed"
+
// 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
@@ -85,6 +95,28 @@ type AgentEventApprovalPendingPayload struct {
ExpiresAt time.Time `json:"expiresAt"`
}
+// AgentEventActionCompletedPayload is the payload shape for
+// action.completed events. Carries the dispatch outcome agents
+// branch on: success/failure, the resource the action ran against,
+// the canonical capability + command, who acted, and any error
+// message. Refused-before-dispatch failures carry the stable
+// error-token prefix (`plan_drift:`, `resource_remediation_locked:`)
+// in ErrorMessage so agents branch on the prefix rather than
+// parsing human text. Full audit detail (lifecycle events,
+// preflight, verification result) stays behind the existing
+// /api/actions/{id} endpoint.
+type AgentEventActionCompletedPayload struct {
+ ActionID string `json:"actionId"`
+ ResourceID string `json:"resourceId,omitempty"`
+ CapabilityName string `json:"capabilityName,omitempty"`
+ Command string `json:"command,omitempty"`
+ State string `json:"state"`
+ Success bool `json:"success"`
+ ErrorMessage string `json:"errorMessage,omitempty"`
+ RequestedBy string `json:"requestedBy,omitempty"`
+ CompletedAt time.Time `json:"completedAt"`
+}
+
// 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
@@ -277,6 +309,17 @@ func (b *AgentEventBroadcaster) PublishApprovalPending(payload AgentEventApprova
})
}
+// PublishActionCompleted is the convenience publisher the executor's
+// post-completion 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) PublishActionCompleted(payload AgentEventActionCompletedPayload) {
+ b.Publish(AgentEvent{
+ Kind: AgentEventActionCompleted,
+ 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
diff --git a/internal/api/agent_events_test.go b/internal/api/agent_events_test.go
index 497419bb6d..f3c16e33b8 100644
--- a/internal/api/agent_events_test.go
+++ b/internal/api/agent_events_test.go
@@ -329,3 +329,106 @@ func TestAgentEventApprovalPendingKindIsStable(t *testing.T) {
AgentEventApprovalPending, "approval.pending")
}
}
+
+func TestAgentEventBroadcaster_PublishActionCompletedDelivers(t *testing.T) {
+ // action.completed is the third event kind the broadcaster
+ // publishes (alongside finding.created and approval.pending).
+ // Pin the contract: kind name, full payload round-trip with
+ // dispatch-outcome fields agents branch on, monotonic id
+ // assignment shared across kinds.
+ b := NewAgentEventBroadcaster()
+ events, unsub := b.Subscribe()
+ defer unsub()
+
+ completed := time.Now().UTC()
+ b.PublishActionCompleted(AgentEventActionCompletedPayload{
+ ActionID: "action-1",
+ ResourceID: "container:web-1",
+ CapabilityName: "pulse_docker",
+ Command: "docker restart web-1",
+ State: "completed",
+ Success: true,
+ RequestedBy: "ai:patrol",
+ CompletedAt: completed,
+ })
+
+ select {
+ case event := <-events:
+ if event.Kind != AgentEventActionCompleted {
+ t.Fatalf("kind: got %q want %q", event.Kind, AgentEventActionCompleted)
+ }
+ 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.(AgentEventActionCompletedPayload)
+ if !ok {
+ t.Fatalf("payload type: got %T want AgentEventActionCompletedPayload", event.Payload)
+ }
+ if payload.ActionID != "action-1" {
+ t.Errorf("ActionID: got %q want %q", payload.ActionID, "action-1")
+ }
+ if payload.ResourceID != "container:web-1" {
+ t.Errorf("ResourceID: got %q want %q", payload.ResourceID, "container:web-1")
+ }
+ if payload.State != "completed" {
+ t.Errorf("State: got %q want %q", payload.State, "completed")
+ }
+ if !payload.Success {
+ t.Error("Success did not round-trip")
+ }
+ if !payload.CompletedAt.Equal(completed) {
+ t.Errorf("CompletedAt did not round-trip: got %v want %v", payload.CompletedAt, completed)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("timed out waiting for action.completed event")
+ }
+}
+
+func TestAgentEventBroadcaster_PublishActionCompletedPreservesRefusalToken(t *testing.T) {
+ // Refused-before-dispatch failures carry a stable error-token
+ // prefix in ErrorMessage (`plan_drift:` /
+ // `resource_remediation_locked:`) that agents branch on. The
+ // broadcaster must round-trip it verbatim — drift here breaks
+ // the contract that lets agents distinguish "the action was
+ // refused due to operator state" from "the action errored".
+ b := NewAgentEventBroadcaster()
+ events, unsub := b.Subscribe()
+ defer unsub()
+
+ b.PublishActionCompleted(AgentEventActionCompletedPayload{
+ ActionID: "action-refused",
+ ResourceID: "vm:db-1",
+ State: "failed",
+ Success: false,
+ ErrorMessage: "resource_remediation_locked: resource has been locked by the operator",
+ CompletedAt: time.Now().UTC(),
+ })
+
+ select {
+ case event := <-events:
+ payload, ok := event.Payload.(AgentEventActionCompletedPayload)
+ if !ok {
+ t.Fatalf("payload type: got %T", event.Payload)
+ }
+ if payload.Success {
+ t.Error("refused dispatches must not surface as Success=true")
+ }
+ if !strings.HasPrefix(payload.ErrorMessage, "resource_remediation_locked:") {
+ t.Errorf("ErrorMessage prefix lost: got %q", payload.ErrorMessage)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("timed out waiting for action.completed event")
+ }
+}
+
+func TestAgentEventActionCompletedKindIsStable(t *testing.T) {
+ // Pin the wire-stable kind string. Renaming it breaks every
+ // agent that branches on the event type.
+ if AgentEventActionCompleted != "action.completed" {
+ t.Fatalf("AgentEventActionCompleted changed: got %q want %q",
+ AgentEventActionCompleted, "action.completed")
+ }
+}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index d91613f51c..91e3dc493a 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -13357,6 +13357,110 @@ func TestContract_SubscribeEventsCapabilityListsApprovalPending(t *testing.T) {
}
}
+// TestContract_AgentEventsStreamPublishesOnActionCompleted pins the
+// agent SSE stream's third producer hook: the executor's
+// post-completion callback must publish action.completed events for
+// every terminal-state audit so an agent holding /api/agent/events
+// open closes the dispatch loop without polling. The bridge lives in
+// wireAIChatDependenciesForService so the callback is re-installed
+// on every per-org chat-service init. Drift here means agents lose
+// the push-notification path for dispatch outcomes — including the
+// refused-before-dispatch failures that carry stable error tokens.
+func TestContract_AgentEventsStreamPublishesOnActionCompleted(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, "executor.SetOnActionCompleted(func(record unifiedresources.ActionAuditRecord)") {
+ t.Error("router.go must install the post-completion callback on the executor returned from chatService.GetExecutor() so the agent SSE stream is wired per-org")
+ }
+ if !strings.Contains(src, "broadcaster.PublishActionCompleted(payload)") {
+ t.Error("router.go must bridge action completion into PublishActionCompleted — drift means agents lose the push-notification path for dispatch outcomes")
+ }
+ if !strings.Contains(src, "ActionID: record.ID") {
+ t.Error("action.completed payload must carry the canonical action id so agents can correlate the event with /api/actions/{id}")
+ }
+ if !strings.Contains(src, "ResourceID: record.Request.ResourceID") {
+ t.Error("action.completed payload must carry the canonical resource id so agents can match it against the rest of Pulse")
+ }
+}
+
+// TestContract_ExecutorPostCompletionCallback pins the seam the SSE
+// bridge depends on. The executor must expose SetOnActionCompleted
+// and the action_audit hot path must dispatch the callback for every
+// terminal-state record (success, runtime fail, plan-drift refusal,
+// remediation-lock refusal). Removing or in-lining the callback
+// breaks the bridge silently.
+func TestContract_ExecutorPostCompletionCallback(t *testing.T) {
+ executor, err := os.ReadFile("../ai/tools/executor.go")
+ if err != nil {
+ t.Fatalf("read executor.go: %v", err)
+ }
+ executorSrc := string(executor)
+ if !strings.Contains(executorSrc, "func (e *PulseToolExecutor) SetOnActionCompleted(cb func(unifiedresources.ActionAuditRecord))") {
+ t.Error("executor must expose SetOnActionCompleted so the API layer can bridge action completion into the agent SSE stream")
+ }
+
+ audit, err := os.ReadFile("../ai/tools/action_audit.go")
+ if err != nil {
+ t.Fatalf("read action_audit.go: %v", err)
+ }
+ auditSrc := string(audit)
+ if !strings.Contains(auditSrc, "func (e *PulseToolExecutor) publishActionCompleted(record unifiedresources.ActionAuditRecord)") {
+ t.Error("action_audit.go must define publishActionCompleted helper so terminal-state writers route through one bridge point")
+ }
+ if !strings.Contains(auditSrc, "go cb(record)") {
+ t.Error("post-completion callback must run on its own goroutine to keep the dispatch hot path off any consumer's slowness")
+ }
+ // Pin that all four terminal sites call publishActionCompleted.
+ terminalSites := []string{
+ `e.recordActionLifecycle(record.ID, unifiedresources.ActionStateFailed, requestedBy, "plan drift refused")
+ e.publishActionCompleted(record)`,
+ `e.recordActionLifecycle(record.ID, unifiedresources.ActionStateFailed, requestedBy, "resource remediation lock refused")
+ e.publishActionCompleted(record)`,
+ `e.recordActionLifecycle(record.ID, record.State, actor, message)
+ e.publishActionCompleted(record)`,
+ }
+ for _, site := range terminalSites {
+ if !strings.Contains(auditSrc, site) {
+ t.Errorf("action_audit.go must call publishActionCompleted at every terminal-state site; missing block:\n%s", site)
+ }
+ }
+}
+
+// TestContract_AgentEventActionCompletedKindIsStable pins the
+// wire-stable event kind string. Renaming AgentEventActionCompleted
+// breaks every agent that branches on the SSE event-type field; the
+// constant is part of the contract, not an implementation detail.
+func TestContract_AgentEventActionCompletedKindIsStable(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, `AgentEventActionCompleted AgentEventKind = "action.completed"`) {
+ t.Error("AgentEventActionCompleted must remain bound to the wire-stable string \"action.completed\" — renaming it breaks every agent that branches on the SSE event type")
+ }
+}
+
+// TestContract_SubscribeEventsCapabilityListsActionCompleted pins
+// the discovery contract: the capabilities manifest must mention
+// action.completed 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_SubscribeEventsCapabilityListsActionCompleted(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, "action.completed when an action audit reaches a terminal state") {
+ t.Error("subscribe_events description must mention action.completed 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/router.go b/internal/api/router.go
index 72aeb40bc4..d7b0e58b17 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -2466,6 +2466,39 @@ func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service A
log.Info().Str("org_id", orgID).Msg("Chat service wired to AI service for patrol and investigation")
}
+ // Bridge action-audit completion into the agent SSE stream so an
+ // agent holding /api/agent/events open hears about every dispatch
+ // outcome — Completed, Failed, or refused-before-dispatch with the
+ // stable `plan_drift:` / `resource_remediation_locked:` token —
+ // without polling the audit endpoint. Independent of aiService
+ // availability: the executor exists per-org regardless of whether
+ // the patrol/investigation surface is wired up. The callback is
+ // fire-and-forget on the dispatch hot path; PublishActionCompleted
+ // drops events for slow subscribers rather than blocking.
+ if chatService != nil && r.agentEventBroadcaster != nil {
+ if executor := chatService.GetExecutor(); executor != nil {
+ broadcaster := r.agentEventBroadcaster
+ executor.SetOnActionCompleted(func(record unifiedresources.ActionAuditRecord) {
+ payload := AgentEventActionCompletedPayload{
+ ActionID: record.ID,
+ ResourceID: record.Request.ResourceID,
+ CapabilityName: record.Request.CapabilityName,
+ State: string(record.State),
+ RequestedBy: record.Request.RequestedBy,
+ CompletedAt: record.UpdatedAt,
+ }
+ if cmd, ok := record.Request.Params["command"].(string); ok {
+ payload.Command = cmd
+ }
+ if record.Result != nil {
+ payload.Success = record.Result.Success
+ payload.ErrorMessage = record.Result.ErrorMessage
+ }
+ broadcaster.PublishActionCompleted(payload)
+ })
+ }
+ }
+
// Wire alert provider
if monitor != nil {
if alertManager := monitor.GetAlertManager(); alertManager != nil {