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.

Run class-derived verification check after successful dispatch

rcourtmana5973218018f
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index d3a1d3549d..479f5dbd58 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -303,6 +303,18 @@ runtime cost control, and shared AI transport surfaces.
action path uses a different hash function (`actionPlanHashForParams`)
so a coherent canonical-hash refactor must precede adding the same
check there.
+ The broker runs a class-derived read-after-write verification check
+ immediately after a successful dispatch. `VerificationCommandForCommand`
+ in `internal/ai/tools/tools_control.go` returns the executable check
+ keyed on the same command class as the preflight authoring (e.g.
+ `systemctl is-active <unit>` after a service-restart). The check
+ runs through the same agent path as the dispatch and the outcome is
+ persisted on `ExecutionResult.Verification` so the audit history
+ shows not only what the action did but whether the read-back
+ confirmed the intended state. Container-class verification is
+ deferred to pulse_docker's existing tool-level `docker inspect`
+ check; classes without a derivable verification command leave
+ `Verification` nil rather than fabricating a verified=true entry.
The approval preflight presented to operators authors per-command-class
safety and verification context on top of the default broker-level
posture. `classifyApprovalCommand` and
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 4a0624422a..fcd49c9e2c 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -511,7 +511,20 @@ AI-only summary payloads, or page-local heuristics.
intentionally narrower than the patrol-failure redactor: arbitrary
URLs are preserved so operators can reference runbooks, ticket
links, and GitHub issues in audit reasons.
-21. Keep governed-action drift refusal canonical in
+21. Keep post-execution verification outcome on the canonical execution
+ result. `ExecutionResult.Verification` carries
+ `ActionVerificationResult` with `Ran`, `Command`, `Output`,
+ `Success`, `RanAt`, and `Note`. The broker runs the
+ class-derived read-after-write check after a successful dispatch
+ and persists the outcome through the existing `result_json`
+ column; no schema migration is required. Verification is
+ best-effort: classes without a derivable check leave
+ `Verification` nil rather than fabricating a verified=true entry,
+ matching the no-fabrication rule used elsewhere in the trust
+ arc. Frontend audit surfaces must surface verification when
+ present (so operators see "Pulse confirmed the action took") and
+ omit it cleanly when nil rather than inventing placeholder copy.
+22. Keep governed-action drift refusal canonical in
`internal/unifiedresources/actions.go`. `ErrActionPlanDrift` is the
error any broker must return when the payload presented at execute
time hashes to anything different than the approval-recorded
diff --git a/internal/ai/tools/action_audit.go b/internal/ai/tools/action_audit.go
index eebc376ede..81bcf72273 100644
--- a/internal/ai/tools/action_audit.go
+++ b/internal/ai/tools/action_audit.go
@@ -165,6 +165,45 @@ func (e *PulseToolExecutor) executeCommandWithAudit(
}
}
+ // Read-after-write verification: if execution succeeded AND the command
+ // class has a derivable verification check, run it via the same agent
+ // path and record the outcome on the audit record. Verification is
+ // best-effort: if no check is derivable, or the check fails to run, we
+ // record that fact rather than fabricating a verified=true.
+ if executionResult.Success {
+ if vCmd, ok := VerificationCommandForCommand(payload.TargetType, payload.Command); ok {
+ vRanAt := time.Now().UTC()
+ vResult, vErr := e.agentServer.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{
+ Command: vCmd,
+ TargetType: payload.TargetType,
+ TargetID: payload.TargetID,
+ })
+ verification := &unifiedresources.ActionVerificationResult{
+ Ran: true,
+ Command: vCmd,
+ RanAt: vRanAt,
+ }
+ if vErr != nil {
+ verification.Success = false
+ verification.Note = fmt.Sprintf("verification check failed to dispatch: %s", vErr.Error())
+ } else {
+ output := strings.TrimSpace(vResult.Stdout)
+ if vResult.Stderr != "" {
+ if output != "" {
+ output += "\n"
+ }
+ output += strings.TrimSpace(vResult.Stderr)
+ }
+ verification.Output = output
+ verification.Success = vResult.ExitCode == 0
+ if !verification.Success {
+ verification.Note = fmt.Sprintf("verification check exit code %d", vResult.ExitCode)
+ }
+ }
+ executionResult.Verification = verification
+ }
+ }
+
e.recordActionExecutionResult(record, executionResult, requestedBy, finalMessage)
return result, err
diff --git a/internal/ai/tools/action_audit_execution_test.go b/internal/ai/tools/action_audit_execution_test.go
index f643603aa1..6bc2b39e3d 100644
--- a/internal/ai/tools/action_audit_execution_test.go
+++ b/internal/ai/tools/action_audit_execution_test.go
@@ -581,6 +581,192 @@ func TestExecuteCommandWithAuditRefusesPayloadDriftAgainstApprovedPlan(t *testin
}
}
+// TestExecuteCommandWithAuditRunsClassDerivedVerificationAfterDispatch
+// covers the read-after-write loop: when a successful dispatch matches a
+// known command class, the broker derives the verification command and
+// runs it via the same agent path. The result is persisted on the audit
+// record's ExecutionResult.Verification so the audit history shows not
+// only what the action did but whether the read-back confirmed it.
+func TestExecuteCommandWithAuditRunsClassDerivedVerificationAfterDispatch(t *testing.T) {
+ actionStore := unifiedresources.NewMemoryStore()
+
+ agentServer := &mockAgentServer{}
+ // Dispatch: systemctl restart nginx — succeeds.
+ agentServer.On("ExecuteCommand", mock.Anything, "agent-1", mock.MatchedBy(func(payload agentexec.ExecuteCommandPayload) bool {
+ return payload.Command == "systemctl restart nginx"
+ })).Return(&agentexec.CommandResultPayload{
+ Success: true,
+ Stdout: "",
+ ExitCode: 0,
+ }, nil).Once()
+ // Verification: systemctl is-active nginx — succeeds with "active".
+ agentServer.On("ExecuteCommand", mock.Anything, "agent-1", mock.MatchedBy(func(payload agentexec.ExecuteCommandPayload) bool {
+ return payload.Command == "systemctl is-active 'nginx'"
+ })).Return(&agentexec.CommandResultPayload{
+ Success: true,
+ Stdout: "active",
+ ExitCode: 0,
+ }, nil).Once()
+
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ AgentServer: agentServer,
+ ActionAuditStore: actionStore,
+ })
+ _, err := executor.executeCommandWithAudit(
+ context.Background(),
+ "pulse_control",
+ "node-1",
+ "",
+ false,
+ "agent-1",
+ agentexec.ExecuteCommandPayload{
+ Command: "systemctl restart nginx",
+ TargetType: "agent",
+ TargetID: "agent-1",
+ },
+ "pulse_control",
+ "restart nginx after Patrol detected stale config",
+ )
+ if err != nil {
+ t.Fatalf("executeCommandWithAudit: %v", err)
+ }
+
+ audits, err := actionStore.GetActionAudits("node-1", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionAudits: %v", err)
+ }
+ if len(audits) != 1 {
+ t.Fatalf("audits len = %d, want 1", len(audits))
+ }
+ verification := audits[0].Result.Verification
+ if verification == nil {
+ t.Fatalf("expected ExecutionResult.Verification to be populated, got nil")
+ }
+ if !verification.Ran {
+ t.Fatalf("expected Verification.Ran=true")
+ }
+ if verification.Command != "systemctl is-active 'nginx'" {
+ t.Fatalf("Verification.Command = %q, want %q", verification.Command, "systemctl is-active 'nginx'")
+ }
+ if !verification.Success {
+ t.Fatalf("expected Verification.Success=true after exit code 0")
+ }
+ if verification.Output != "active" {
+ t.Fatalf("Verification.Output = %q, want %q", verification.Output, "active")
+ }
+ agentServer.AssertExpectations(t)
+}
+
+// TestExecuteCommandWithAuditMarksVerificationFailedWhenReadbackDoesNotConfirm
+// covers the negative case: dispatch succeeded, but the read-after-write
+// check returned a non-zero exit code (e.g. service is "failed" not
+// "active"). Verification.Success must reflect the read-back outcome
+// rather than the dispatch outcome so the audit row honestly shows that
+// Pulse ran the action but couldn't confirm it took.
+func TestExecuteCommandWithAuditMarksVerificationFailedWhenReadbackDoesNotConfirm(t *testing.T) {
+ actionStore := unifiedresources.NewMemoryStore()
+
+ agentServer := &mockAgentServer{}
+ agentServer.On("ExecuteCommand", mock.Anything, "agent-1", mock.MatchedBy(func(payload agentexec.ExecuteCommandPayload) bool {
+ return payload.Command == "systemctl restart workload"
+ })).Return(&agentexec.CommandResultPayload{
+ Success: true,
+ ExitCode: 0,
+ }, nil).Once()
+ agentServer.On("ExecuteCommand", mock.Anything, "agent-1", mock.MatchedBy(func(payload agentexec.ExecuteCommandPayload) bool {
+ return payload.Command == "systemctl is-active 'workload'"
+ })).Return(&agentexec.CommandResultPayload{
+ Success: false,
+ Stdout: "failed",
+ ExitCode: 3,
+ }, nil).Once()
+
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ AgentServer: agentServer,
+ ActionAuditStore: actionStore,
+ })
+ _, err := executor.executeCommandWithAudit(
+ context.Background(),
+ "pulse_control",
+ "node-1",
+ "",
+ false,
+ "agent-1",
+ agentexec.ExecuteCommandPayload{
+ Command: "systemctl restart workload",
+ TargetType: "agent",
+ TargetID: "agent-1",
+ },
+ "pulse_control",
+ "restart workload after backup window",
+ )
+ if err != nil {
+ t.Fatalf("executeCommandWithAudit: %v", err)
+ }
+
+ audits, _ := actionStore.GetActionAudits("node-1", time.Time{}, 10)
+ verification := audits[0].Result.Verification
+ if verification == nil || !verification.Ran {
+ t.Fatalf("expected verification ran, got %#v", verification)
+ }
+ if verification.Success {
+ t.Fatalf("expected Verification.Success=false after exit code 3")
+ }
+ if verification.Output != "failed" {
+ t.Fatalf("Verification.Output = %q, want %q", verification.Output, "failed")
+ }
+ if !strings.Contains(verification.Note, "exit code 3") {
+ t.Fatalf("Verification.Note missing exit code, got: %q", verification.Note)
+ }
+}
+
+// TestExecuteCommandWithAuditSkipsVerificationForUnclassifiedCommands
+// covers the no-fabrication boundary: when no verification command is
+// derivable for the action class, the broker leaves Verification nil
+// rather than recording a fake "verified" entry.
+func TestExecuteCommandWithAuditSkipsVerificationForUnclassifiedCommands(t *testing.T) {
+ actionStore := unifiedresources.NewMemoryStore()
+
+ agentServer := &mockAgentServer{}
+ agentServer.On("ExecuteCommand", mock.Anything, "agent-1", mock.MatchedBy(func(payload agentexec.ExecuteCommandPayload) bool {
+ return payload.Command == "echo hello"
+ })).Return(&agentexec.CommandResultPayload{
+ Success: true,
+ Stdout: "hello",
+ ExitCode: 0,
+ }, nil).Once()
+
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ AgentServer: agentServer,
+ ActionAuditStore: actionStore,
+ })
+ _, err := executor.executeCommandWithAudit(
+ context.Background(),
+ "pulse_control",
+ "node-1",
+ "",
+ false,
+ "agent-1",
+ agentexec.ExecuteCommandPayload{
+ Command: "echo hello",
+ TargetType: "agent",
+ TargetID: "agent-1",
+ },
+ "pulse_control",
+ "echo greeting",
+ )
+ if err != nil {
+ t.Fatalf("executeCommandWithAudit: %v", err)
+ }
+
+ audits, _ := actionStore.GetActionAudits("node-1", time.Time{}, 10)
+ if audits[0].Result.Verification != nil {
+ t.Fatalf("expected nil Verification for unclassified command, got %#v", audits[0].Result.Verification)
+ }
+ // Exactly one ExecuteCommand call expected (no verification dispatch).
+ agentServer.AssertExpectations(t)
+}
+
// TestExecuteCommandWithAuditAllowsMatchingPlanHash covers the positive case:
// when the payload at execute time hashes identically to the approved plan,
// dispatch proceeds normally.
diff --git a/internal/ai/tools/approval_preflight_test.go b/internal/ai/tools/approval_preflight_test.go
index 7ea3db897e..dc5e71ac1f 100644
--- a/internal/ai/tools/approval_preflight_test.go
+++ b/internal/ai/tools/approval_preflight_test.go
@@ -76,6 +76,38 @@ func TestApprovalCommandClassPreflightAdditions_ReturnsEmptyForUnknownClass(t *t
}
}
+func TestVerificationCommandForCommand_DerivesPerClassReadAfterWriteCheck(t *testing.T) {
+ cases := []struct {
+ name string
+ target string
+ command string
+ wantCmd string
+ wantOk bool
+ }{
+ {"systemctl restart", "agent", "systemctl restart nginx", "systemctl is-active 'nginx'", true},
+ {"systemctl reload with .service suffix", "agent", "systemctl reload my.service", "systemctl is-active 'my.service'", true},
+ {"systemctl stop", "agent", "systemctl stop postgres", "systemctl is-active 'postgres'", true},
+ // Docker/podman classes are intentionally excluded from broker-level
+ // verification — pulse_docker runs its own docker inspect check at
+ // the tool layer, so adding a broker-level dispatch would double-run.
+ {"docker restart deferred to tool layer", "docker", "docker restart homepage", "", false},
+ {"podman restart deferred to tool layer", "agent", "podman restart pihole", "", false},
+ {"unknown command", "agent", "echo hello", "", false},
+ {"systemctl with single-quote in unit", "agent", `systemctl restart nasty'name`, "systemctl is-active 'nasty'\\''name'", true},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ cmd, ok := VerificationCommandForCommand(tc.target, tc.command)
+ if ok != tc.wantOk {
+ t.Fatalf("VerificationCommandForCommand(%q, %q) ok = %v, want %v", tc.target, tc.command, ok, tc.wantOk)
+ }
+ if cmd != tc.wantCmd {
+ t.Fatalf("VerificationCommandForCommand(%q, %q) cmd = %q, want %q", tc.target, tc.command, cmd, tc.wantCmd)
+ }
+ })
+ }
+}
+
func TestApprovalPreflight_MergesClassAdditionsIntoSafetyAndVerification(t *testing.T) {
// End-to-end check that approvalPreflight surfaces the per-class
// additions to the operator without losing the default safety /
diff --git a/internal/ai/tools/tools_control.go b/internal/ai/tools/tools_control.go
index 37009496d4..fd52f96d5a 100644
--- a/internal/ai/tools/tools_control.go
+++ b/internal/ai/tools/tools_control.go
@@ -1517,6 +1517,92 @@ func approvalPreflight(req *approval.ApprovalRequest) *approval.ActionPreflight
}
}
+// VerificationCommandForCommand derives the read-after-write check Pulse
+// will run after a successful dispatch. The check is keyed on the same
+// command class as approvalCommandClassPreflightAdditions, so the
+// verification narrative the operator saw at approval time and the
+// verification actually executed stay coherent. Returns "", false for
+// classes without a derivable check; the broker must skip verification
+// rather than fabricate one.
+//
+// Container classes (container-restart, container-stop) are intentionally
+// excluded here: pulse_docker already runs its own per-container
+// `docker inspect` verification at the tool layer, and adding a parallel
+// broker-level dispatch would double-run the same check. If the tool layer
+// stops doing its own verification, this function should grow a docker
+// branch using `extractContainerName`.
+func VerificationCommandForCommand(targetType, command string) (string, bool) {
+ class := classifyApprovalCommand(targetType, command)
+ switch class {
+ case "service-restart", "service-start", "service-reload", "service-stop":
+ unit := extractServiceUnitName(command)
+ if unit == "" {
+ return "", false
+ }
+ return "systemctl is-active " + shellQuoteSingle(unit), true
+ }
+ return "", false
+}
+
+// extractServiceUnitName parses the unit name out of a systemctl/service
+// command. Supports the common shapes:
+//
+// "systemctl restart nginx" -> "nginx"
+// "systemctl reload my.service" -> "my.service"
+// "service restart redis" -> "redis"
+//
+// Returns empty string when the command does not parse cleanly so the
+// caller can decline to verify rather than guess at the unit.
+func extractServiceUnitName(command string) string {
+ fields := strings.Fields(strings.TrimSpace(command))
+ if len(fields) < 3 {
+ return ""
+ }
+ first := strings.ToLower(fields[0])
+ if first != "systemctl" && first != "service" {
+ return ""
+ }
+ // Service action verbs (restart/start/stop/reload) live at index 1 for
+ // "systemctl restart nginx" and at index 2 for "service restart nginx";
+ // the canonical form we recognize puts the action at index 1 and the
+ // unit at index 2.
+ verb := strings.ToLower(fields[1])
+ switch verb {
+ case "restart", "start", "stop", "reload":
+ return fields[2]
+ }
+ return ""
+}
+
+// extractContainerName parses the container name out of a docker/podman
+// command of the form "docker restart <name>" or "podman stop <name>".
+func extractContainerName(command string) string {
+ fields := strings.Fields(strings.TrimSpace(command))
+ if len(fields) < 3 {
+ return ""
+ }
+ first := strings.ToLower(fields[0])
+ if first != "docker" && first != "podman" {
+ return ""
+ }
+ verb := strings.ToLower(fields[1])
+ if verb != "restart" && verb != "stop" && verb != "start" {
+ return ""
+ }
+ return fields[2]
+}
+
+// shellQuoteSingle wraps the value in single quotes and escapes any
+// embedded single quotes for shell-safe inclusion in the verification
+// command. The verification path runs through the same agent dispatch as
+// the original command, so the same shell-escape contract applies.
+func shellQuoteSingle(value string) string {
+ if value == "" {
+ return "''"
+ }
+ return "'" + strings.ReplaceAll(value, "'", `'\''`) + "'"
+}
+
// classifyApprovalCommand maps a (targetType, command) pair to a stable
// class string used by approvalCommandClassPreflightAdditions. Returns
// empty string for commands that do not match a known class — those keep
diff --git a/internal/unifiedresources/actions.go b/internal/unifiedresources/actions.go
index 74e667646b..d56ae9acb7 100644
--- a/internal/unifiedresources/actions.go
+++ b/internal/unifiedresources/actions.go
@@ -93,9 +93,28 @@ type ActionPlan struct {
// ExecutionResult captures the output of the native capability driver.
type ExecutionResult struct {
- Success bool `json:"success"`
- Output string `json:"output,omitempty"`
- ErrorMessage string `json:"errorMessage,omitempty"`
+ Success bool `json:"success"`
+ Output string `json:"output,omitempty"`
+ ErrorMessage string `json:"errorMessage,omitempty"`
+ Verification *ActionVerificationResult `json:"verification,omitempty"`
+}
+
+// ActionVerificationResult records the outcome of a post-execution
+// read-after-write check. The broker derives a class-specific verification
+// command (e.g. `systemctl is-active <unit>` after a service-restart action)
+// and runs it via the same agent path used for the original dispatch. The
+// result is persisted alongside ExecutionResult so the audit history shows
+// not only what the action did but whether the read-back confirmed the
+// intended state. Verification is best-effort: if the agent is unreachable
+// or no verification command is derivable for the action class, Ran is
+// false and the rest of the fields are empty rather than fabricated.
+type ActionVerificationResult struct {
+ Ran bool `json:"ran"`
+ Command string `json:"command,omitempty"`
+ Output string `json:"output,omitempty"`
+ Success bool `json:"success"`
+ RanAt time.Time `json:"ranAt,omitempty"`
+ Note string `json:"note,omitempty"`
}
// ActionAuditRecord tracks the full end-to-end lifecycle of a tool invocation.
diff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.go
index 7dc704a197..ff2378a705 100644
--- a/internal/unifiedresources/code_standards_test.go
+++ b/internal/unifiedresources/code_standards_test.go
@@ -377,6 +377,15 @@ func TestActionExecutionContractStaysAPIOwned(t *testing.T) {
"func RedactAuditText(s string) string",
"func RedactAuditRecord(record ActionAuditRecord) ActionAuditRecord",
},
+ // ActionVerificationResult is the canonical post-execution
+ // read-after-write outcome carrier. The broker writes it onto
+ // ExecutionResult.Verification; pinning the type here keeps the
+ // shape stable across refactors so frontend audit surfaces and
+ // any other consumers can rely on it.
+ filepath.Join(".", "actions.go"): {
+ "type ActionVerificationResult struct",
+ "Verification *ActionVerificationResult `json:\"verification,omitempty\"`",
+ },
filepath.Join("..", "api", "actions.go"): {
"type ActionExecutor interface",
"func (h *ResourceHandlers) HandleExecuteAction(w http.ResponseWriter, r *http.Request)",