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.

Surface action verification on the action.completed SSE payload

rcourtman8aa22d06054e
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 068024f29c..b6cabd6d04 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -933,7 +933,11 @@ 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.
+prefixes preserved verbatim; successful dispatches carry a
+`verification` block — the agent-stable projection of the
+broker's read-after-write probe — so agents close the
+"did it actually work?" loop without polling /api/actions/{id}),
+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
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index d6001bbce5..5ef35934be 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1368,9 +1368,14 @@ behind `/api/approvals/{id}`, the event is a doorbell),
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
+branch on the prefix rather than parsing human text; successful
+dispatches carry a `verification` block — the agent-stable
+projection of the broker's read-after-write probe — with `ran`,
+`success`, `command`, `note`, `ranAt` so agents close the
+"did it actually work?" loop without a follow-up audit fetch;
+refused dispatches omit `verification` because the probe never
+runs) — 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
@@ -1485,9 +1490,14 @@ expiresAt — same vocabulary as `approval.pending` SSE events so
"what's pending right now" and "what just became pending" agree
on shape), and recent action audits including refused dispatches
with their stable token prefixes (`resource_remediation_locked:`,
-`plan_drift:`) preserved verbatim. The shape is intentionally
-narrower than the full internal types so agents see a stable
-agent-paradigm contract, decoupled from internal type evolution.
+`plan_drift:`) preserved verbatim and the same agent-stable
+`verification` block the SSE `action.completed` payload carries
+(shared `AgentResourceActionVerification` projection, shared
+`projectAgentResourceVerification` helper) so the bundle's depth
+view and the doorbell speak the same vocabulary on probe outcomes.
+The shape is intentionally narrower than the full internal types
+so agents see a stable agent-paradigm contract, decoupled from
+internal type evolution.
Active findings come through the `AgentFindingsProvider` adapter
wired at startup so the api package stays free of an
`internal/ai` import; the patrol service holds the canonical
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 217ba71a87..e5fc6a0641 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -531,6 +531,14 @@ 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.
+The `action.completed` payload's `verification` block is a small
+fixed-shape projection (5 fields, no embedded output) so adding
+it to every successful dispatch event does not materially change
+per-event size. Verification stdout — which can be large for
+some action classes — stays on the audit record and is fetched
+on demand via /api/actions/{id}; the event is the doorbell, not
+the transport for full probe output.
+
`/api/agent/resource-context/{id}` does at most four 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 e16b284e3c..34ea3ba8d4 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -963,7 +963,12 @@ list) for replay — those are the durable surfaces. 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.
+not the source of truth. The verification projection on
+`action.completed` reads from the same persisted
+`ActionAuditRecord.Result.Verification` field that agents would
+recover from /api/actions/{id} after a reconnect — the event
+carries a copy, not the original, so the durable record remains
+the canonical source.
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_execution_test.go b/internal/ai/tools/action_audit_execution_test.go
index 4d8a278cc4..de1fd41b46 100644
--- a/internal/ai/tools/action_audit_execution_test.go
+++ b/internal/ai/tools/action_audit_execution_test.go
@@ -1197,6 +1197,85 @@ func TestSetOnActionCompleted_FiresOnSuccessfulDispatch(t *testing.T) {
}
}
+func TestSetOnActionCompleted_RecordCarriesVerificationResult(t *testing.T) {
+ // Verification is the post-execution read-after-write probe the
+ // broker derives for action classes with a known check command
+ // (systemctl-style service control). Pin the contract: the
+ // callback record's Verification block is populated when the
+ // dispatch class supports it, with the derived command and the
+ // success/failure outcome of running it. Agents reading the
+ // callback (or the SSE event downstream) close the certainty
+ // loop on this field.
+ store := unifiedresources.NewMemoryStore()
+ agentServer := &mockAgentServer{}
+ // First call: the action itself.
+ agentServer.On("ExecuteCommand", mock.Anything, "agent-vrf",
+ mock.MatchedBy(func(p agentexec.ExecuteCommandPayload) bool {
+ return p.Command == "systemctl restart nginx"
+ })).
+ Return(&agentexec.CommandResultPayload{Success: true, Stdout: "", ExitCode: 0}, nil).Once()
+ // Second call: the broker-derived verification probe. The
+ // expected command is `systemctl is-active 'nginx'`.
+ agentServer.On("ExecuteCommand", mock.Anything, "agent-vrf",
+ mock.MatchedBy(func(p agentexec.ExecuteCommandPayload) bool {
+ return strings.HasPrefix(p.Command, "systemctl is-active")
+ })).
+ Return(&agentexec.CommandResultPayload{Success: true, Stdout: "active\n", 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-vrf",
+ "",
+ false,
+ "agent-vrf",
+ agentexec.ExecuteCommandPayload{
+ Command: "systemctl restart nginx",
+ TargetType: "agent",
+ TargetID: "agent-vrf",
+ },
+ "pulse_control",
+ "restart nginx",
+ ); err != nil {
+ t.Fatalf("executeCommandWithAudit: %v", err)
+ }
+
+ select {
+ case received := <-got:
+ if received.Result == nil {
+ t.Fatal("callback record must carry an ExecutionResult")
+ }
+ if received.Result.Verification == nil {
+ t.Fatal("callback record must carry a Verification block for service-restart actions — drift here breaks the certainty loop on action.completed")
+ }
+ v := received.Result.Verification
+ if !v.Ran {
+ t.Error("Verification.Ran must be true after the broker dispatched the probe")
+ }
+ if !v.Success {
+ t.Errorf("Verification.Success: probe returned exit 0, expected Success=true; got %+v", v)
+ }
+ if !strings.Contains(v.Command, "systemctl is-active") {
+ t.Errorf("Verification.Command must surface the derived probe command; got %q", v.Command)
+ }
+ if v.RanAt.IsZero() {
+ t.Error("Verification.RanAt must be populated so agents can reason about probe freshness")
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("post-completion callback did not fire within 2s")
+ }
+ agentServer.AssertExpectations(t)
+}
+
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
diff --git a/internal/api/agent_capabilities.go b/internal/api/agent_capabilities.go
index ab7b25f03d..7e7bc5719b 100644
--- a/internal/api/agent_capabilities.go
+++ b/internal/api/agent_capabilities.go
@@ -141,7 +141,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, 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.",
+ 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; carries a verification block with the read-after-write probe outcome so agents close the certainty loop without polling /api/actions/{id}), 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 e85e1915b7..826ad979f6 100644
--- a/internal/api/agent_events.go
+++ b/internal/api/agent_events.go
@@ -98,23 +98,28 @@ type AgentEventApprovalPendingPayload struct {
// 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.
+// the canonical capability + command, who acted, any error
+// message, and the agent-stable verification projection
+// (read-after-write probe outcome) so the agent can close the
+// "did it actually work?" loop without a follow-up audit fetch.
+// 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; refused dispatches have no Verification by
+// definition (verification only runs after a successful execute).
+// Full audit detail (lifecycle events, preflight, verification
+// stdout) 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"`
+ 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"`
+ Verification *AgentResourceActionVerification `json:"verification,omitempty"`
+ RequestedBy string `json:"requestedBy,omitempty"`
+ CompletedAt time.Time `json:"completedAt"`
}
// AgentEventBroadcaster is a thread-safe pub/sub for AgentEvents. A
diff --git a/internal/api/agent_events_test.go b/internal/api/agent_events_test.go
index f3c16e33b8..5fd050d492 100644
--- a/internal/api/agent_events_test.go
+++ b/internal/api/agent_events_test.go
@@ -432,3 +432,82 @@ func TestAgentEventActionCompletedKindIsStable(t *testing.T) {
AgentEventActionCompleted, "action.completed")
}
}
+
+func TestAgentEventBroadcaster_PublishActionCompletedRoundTripsVerification(t *testing.T) {
+ // The verification block is the agent-stable projection of the
+ // post-execution read-after-write probe. Pin the contract: it
+ // round-trips through the broadcaster with the fields agents
+ // branch on (Ran, Success, Command, Note, RanAt) intact.
+ b := NewAgentEventBroadcaster()
+ events, unsub := b.Subscribe()
+ defer unsub()
+
+ ranAt := time.Now().UTC()
+ b.PublishActionCompleted(AgentEventActionCompletedPayload{
+ ActionID: "action-verify-1",
+ ResourceID: "container:web-1",
+ State: "completed",
+ Success: true,
+ CompletedAt: ranAt,
+ Verification: &AgentResourceActionVerification{
+ Ran: true,
+ Success: true,
+ Command: "docker inspect --format '{{.State.Status}}' web-1",
+ RanAt: ranAt,
+ },
+ })
+
+ select {
+ case event := <-events:
+ payload, ok := event.Payload.(AgentEventActionCompletedPayload)
+ if !ok {
+ t.Fatalf("payload type: got %T", event.Payload)
+ }
+ if payload.Verification == nil {
+ t.Fatal("verification block must round-trip — agents close the certainty loop on this field")
+ }
+ if !payload.Verification.Ran || !payload.Verification.Success {
+ t.Errorf("verification flags lost: ran=%t success=%t", payload.Verification.Ran, payload.Verification.Success)
+ }
+ if payload.Verification.Command == "" {
+ t.Error("verification command must round-trip so agents see what was checked")
+ }
+ case <-time.After(time.Second):
+ t.Fatal("timed out waiting for action.completed event")
+ }
+}
+
+func TestAgentEventBroadcaster_PublishActionCompletedAbsentVerificationOmitsField(t *testing.T) {
+ // Refused-before-dispatch failures have no verification result
+ // (verification only runs after a successful execute). The
+ // payload's Verification must surface as omitted (nil) rather
+ // than an empty struct so agents can branch on field presence
+ // to distinguish "no verification attempted" from "verification
+ // ran with empty result".
+ b := NewAgentEventBroadcaster()
+ events, unsub := b.Subscribe()
+ defer unsub()
+
+ b.PublishActionCompleted(AgentEventActionCompletedPayload{
+ ActionID: "action-refused-1",
+ ResourceID: "vm:db-1",
+ State: "failed",
+ Success: false,
+ ErrorMessage: "resource_remediation_locked: ...",
+ CompletedAt: time.Now().UTC(),
+ // Verification deliberately unset.
+ })
+
+ select {
+ case event := <-events:
+ payload, ok := event.Payload.(AgentEventActionCompletedPayload)
+ if !ok {
+ t.Fatalf("payload type: got %T", event.Payload)
+ }
+ if payload.Verification != nil {
+ t.Errorf("verification must remain nil for refused dispatches; got %+v", payload.Verification)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("timed out waiting for action.completed event")
+ }
+}
diff --git a/internal/api/agent_resource_context.go b/internal/api/agent_resource_context.go
index 2ae8429896..646115fb5d 100644
--- a/internal/api/agent_resource_context.go
+++ b/internal/api/agent_resource_context.go
@@ -31,20 +31,39 @@ type AgentResourceFindingSnapshot struct {
LastSeenAt string `json:"lastSeenAt,omitempty"`
}
+// AgentResourceActionVerification is the agent-stable projection of
+// the post-execution read-after-write probe the broker runs after
+// every successful dispatch. Carries enough for an agent to close
+// the certainty loop ("did it actually work?") without fetching
+// /api/actions/{id} for full output. `Ran` is the existence bit:
+// false means no verification was attempted (the action class has
+// no derivable check, or the dispatch failed before verification
+// could run). Output is intentionally omitted from the projection
+// — verification stdout can be large; agents that need it follow
+// up via the audit endpoint.
+type AgentResourceActionVerification struct {
+ Ran bool `json:"ran"`
+ Success bool `json:"success"`
+ Command string `json:"command,omitempty"`
+ Note string `json:"note,omitempty"`
+ RanAt time.Time `json:"ranAt,omitempty"`
+}
+
// AgentResourceActionSummary is the agent-consumable projection of an
// action audit record. Includes the refusal-reason prefix tokens
// (resource_remediation_locked:, plan_drift:) verbatim so agents can
// branch on them without parsing the human message.
type AgentResourceActionSummary struct {
- ID string `json:"id"`
- CapabilityName string `json:"capabilityName"`
- Command string `json:"command,omitempty"`
- State string `json:"state"`
- Success bool `json:"success"`
- ErrorMessage string `json:"errorMessage,omitempty"`
- RequestedBy string `json:"requestedBy,omitempty"`
- CreatedAt time.Time `json:"createdAt"`
- UpdatedAt time.Time `json:"updatedAt"`
+ ID string `json:"id"`
+ CapabilityName string `json:"capabilityName"`
+ Command string `json:"command,omitempty"`
+ State string `json:"state"`
+ Success bool `json:"success"`
+ ErrorMessage string `json:"errorMessage,omitempty"`
+ Verification *AgentResourceActionVerification `json:"verification,omitempty"`
+ RequestedBy string `json:"requestedBy,omitempty"`
+ CreatedAt time.Time `json:"createdAt"`
+ UpdatedAt time.Time `json:"updatedAt"`
}
// AgentResourceApprovalSummary is the agent-consumable projection of
@@ -489,8 +508,31 @@ func projectAgentResourceActions(
if audit.Result != nil {
summary.Success = audit.Result.Success
summary.ErrorMessage = audit.Result.ErrorMessage
+ if v := projectAgentResourceVerification(audit.Result.Verification); v != nil {
+ summary.Verification = v
+ }
}
out = append(out, summary)
}
return out
}
+
+// projectAgentResourceVerification converts the canonical
+// ActionVerificationResult into the agent-stable projection that
+// both the resource-context bundle and the action.completed SSE
+// payload carry. Returns nil when the source is nil so callers can
+// branch on field presence — absent means "no verification result
+// recorded" (e.g. refused-before-dispatch failures), distinct from
+// "verification was skipped" which surfaces as Ran=false.
+func projectAgentResourceVerification(v *unified.ActionVerificationResult) *AgentResourceActionVerification {
+ if v == nil {
+ return nil
+ }
+ return &AgentResourceActionVerification{
+ Ran: v.Ran,
+ Success: v.Success,
+ Command: v.Command,
+ Note: v.Note,
+ RanAt: v.RanAt,
+ }
+}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 2c75bd168d..2b73e4b02c 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -13623,6 +13623,65 @@ func TestContract_AgentFleetContextEndpointSurfacesStableShape(t *testing.T) {
}
}
+// TestContract_ActionCompletedPayloadCarriesVerification pins that
+// the action.completed SSE payload exposes the verification block
+// — the agent-stable projection of the post-execution probe so
+// agents close the "did it actually work?" loop without a follow-up
+// audit fetch. Drift here forces every agent watching the stream to
+// poll /api/actions/{id} after every dispatch, defeating the
+// substrate's push-notification guarantee for dispatch certainty.
+func TestContract_ActionCompletedPayloadCarriesVerification(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, "Verification *AgentResourceActionVerification `json:\"verification,omitempty\"`") {
+ t.Error("AgentEventActionCompletedPayload must carry Verification as a *AgentResourceActionVerification — agents close the certainty loop on this field")
+ }
+}
+
+// TestContract_RouterBridgesVerificationOntoActionCompleted pins
+// that the router-side bridge actually carries the verification
+// projection from record.Result.Verification onto the SSE payload.
+// The payload field exists is one half of the contract; this is the
+// other half — that the bridge populates it when the underlying
+// audit has a verification result.
+func TestContract_RouterBridgesVerificationOntoActionCompleted(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, "if v := projectAgentResourceVerification(record.Result.Verification); v != nil {") {
+ t.Error("router.go must project record.Result.Verification onto the action.completed payload via projectAgentResourceVerification — drift here means verification reaches the audit store but never the SSE stream")
+ }
+ if !strings.Contains(src, "payload.Verification = v") {
+ t.Error("router.go must assign the projected verification onto payload.Verification")
+ }
+}
+
+// TestContract_AgentResourceActionSummaryCarriesVerification pins
+// that the resource-context bundle's recent-actions surface also
+// carries verification, paralleling the SSE payload. Symmetry
+// here matters: an agent should get the same verification fact
+// whether they read the bundle (depth) or watch the doorbell
+// (push). Drift would let one surface ship a feature the other
+// doesn't.
+func TestContract_AgentResourceActionSummaryCarriesVerification(t *testing.T) {
+ source, err := os.ReadFile("agent_resource_context.go")
+ if err != nil {
+ t.Fatalf("read agent_resource_context.go: %v", err)
+ }
+ src := string(source)
+ if !strings.Contains(src, "Verification *AgentResourceActionVerification `json:\"verification,omitempty\"`") {
+ t.Error("AgentResourceActionSummary must carry Verification so the bundle's recent-actions and the action.completed SSE payload speak the same vocabulary")
+ }
+ if !strings.Contains(src, "func projectAgentResourceVerification(v *unified.ActionVerificationResult)") {
+ t.Error("projectAgentResourceVerification must exist as the shared helper — both the SSE bridge and the bundle's projector route through it so the wire shape cannot drift between surfaces")
+ }
+}
+
// TestContract_OperatorStateWriteServerPopulatesAttribution pins the
// audit-honesty contract for the agent surface's only write loop:
// the PUT handler must populate SetAt and SetBy from the server,
diff --git a/internal/api/router.go b/internal/api/router.go
index a03db603dc..5074eae7cd 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -2533,6 +2533,9 @@ func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service A
if record.Result != nil {
payload.Success = record.Result.Success
payload.ErrorMessage = record.Result.ErrorMessage
+ if v := projectAgentResourceVerification(record.Result.Verification); v != nil {
+ payload.Verification = v
+ }
}
broadcaster.PublishActionCompleted(payload)
})