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.

Author per-command-class preflight context for approval review

rcourtman2dca0004164f
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 67a54399a9..d3a1d3549d 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -303,6 +303,21 @@ 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 approval preflight presented to operators authors per-command-class
+ safety and verification context on top of the default broker-level
+ posture. `classifyApprovalCommand` and
+ `approvalCommandClassPreflightAdditions` in
+ `internal/ai/tools/tools_control.go` bucket common Pulse remediation
+ actions (service-restart, service-stop, service-start, service-reload,
+ container-restart, container-stop, k8s-rollout-restart) and return
+ hand-authored operational copy: what the command actually touches,
+ how Pulse will read back success. The additions append onto the
+ default safety/verification arrays rather than replacing them, so
+ the broker's structural posture (org scope, hash match, single-use
+ approval) remains visible alongside the class-specific copy.
+ Unknown command classes must return empty additions rather than
+ fabricated padding — operators see only the default content, not
+ invented assertions about what an unrecognized command will do.
Drift refusal must also persist a Failed audit record with the
Request, Plan, and Approvals snapshots intact and a Result whose
ErrorMessage is prefixed `plan_drift:` so the audit trail shows
diff --git a/internal/ai/tools/approval_preflight_test.go b/internal/ai/tools/approval_preflight_test.go
new file mode 100644
index 0000000000..7ea3db897e
--- /dev/null
+++ b/internal/ai/tools/approval_preflight_test.go
@@ -0,0 +1,111 @@
+package tools
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"
+)
+
+func TestClassifyApprovalCommand_BucketsKnownCommandShapes(t *testing.T) {
+ cases := []struct {
+ name string
+ target string
+ command string
+ want string
+ }{
+ {"systemctl restart canonical", "agent", "systemctl restart nginx", "service-restart"},
+ {"service restart legacy", "agent", "service nginx restart", ""},
+ {"service restart canonical", "agent", "service restart nginx", "service-restart"},
+ {"systemctl stop", "agent", "systemctl stop postgres", "service-stop"},
+ {"systemctl start", "agent", "systemctl start redis", "service-start"},
+ {"systemctl reload", "agent", "systemctl reload nginx", "service-reload"},
+ {"docker restart", "docker", "docker restart homepage", "container-restart"},
+ {"podman restart", "agent", "podman restart pihole", "container-restart"},
+ {"docker stop", "docker", "docker stop oldcontainer", "container-stop"},
+ {"kubectl rollout restart", "kubernetes", "kubectl rollout restart deployment/api", "k8s-rollout-restart"},
+ {"unknown free-form command", "agent", "echo hello world", ""},
+ {"empty command", "agent", "", ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := classifyApprovalCommand(tc.target, tc.command)
+ if got != tc.want {
+ t.Fatalf("classifyApprovalCommand(%q, %q) = %q, want %q", tc.target, tc.command, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestApprovalCommandClassPreflightAdditions_AuthorsConcreteContextForKnownClasses(t *testing.T) {
+ cases := []struct {
+ name string
+ command string
+ safetyToken string // must appear somewhere in safety checks
+ verifyToken string // must appear somewhere in verification steps
+ }{
+ {"service-restart names systemctl is-active", "systemctl restart nginx", "briefly unavailable", "systemctl is-active"},
+ {"service-stop warns dependent services", "systemctl stop postgres", "dependent services", "inactive"},
+ {"container-restart names docker inspect", "docker restart homepage", "briefly unavailable", "docker inspect"},
+ {"k8s rollout names rollout status", "kubectl rollout restart deployment/api", "PodDisruptionBudget", "rollout status"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ safety, verify := approvalCommandClassPreflightAdditions("agent", tc.command)
+ if len(safety) == 0 || len(verify) == 0 {
+ t.Fatalf("expected non-empty preflight additions for %q, got safety=%v verify=%v", tc.command, safety, verify)
+ }
+ joinedSafety := strings.Join(safety, " ")
+ if !strings.Contains(joinedSafety, tc.safetyToken) {
+ t.Fatalf("safety checks missing token %q for %q: %v", tc.safetyToken, tc.command, safety)
+ }
+ joinedVerify := strings.Join(verify, " ")
+ if !strings.Contains(joinedVerify, tc.verifyToken) {
+ t.Fatalf("verification steps missing token %q for %q: %v", tc.verifyToken, tc.command, verify)
+ }
+ })
+ }
+}
+
+func TestApprovalCommandClassPreflightAdditions_ReturnsEmptyForUnknownClass(t *testing.T) {
+ // Unknown command shapes must not be padded with fabricated safety or
+ // verification copy. Default preflight content stands on its own.
+ safety, verify := approvalCommandClassPreflightAdditions("agent", "echo hello world")
+ if safety != nil || verify != nil {
+ t.Fatalf("expected nil additions for unknown command, got safety=%v verify=%v", safety, verify)
+ }
+}
+
+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 /
+ // verification content.
+ req := &approval.ApprovalRequest{
+ ID: "approval-systemctl-restart",
+ Command: "systemctl restart nginx",
+ TargetType: "agent",
+ TargetID: "agent-1",
+ TargetName: "edge-1",
+ Context: "restart nginx after Patrol detected stale config",
+ }
+ preflight := approvalPreflight(req)
+ if preflight == nil {
+ t.Fatalf("expected preflight, got nil")
+ }
+
+ joinedSafety := strings.Join(preflight.SafetyChecks, " | ")
+ if !strings.Contains(joinedSafety, "Approval is scoped to the current organization") {
+ t.Fatalf("default safety check missing: %v", preflight.SafetyChecks)
+ }
+ if !strings.Contains(joinedSafety, "briefly unavailable") {
+ t.Fatalf("class-specific safety check missing: %v", preflight.SafetyChecks)
+ }
+
+ joinedVerify := strings.Join(preflight.VerificationSteps, " | ")
+ if !strings.Contains(joinedVerify, "Persist unified action audit lifecycle") {
+ t.Fatalf("default verification step missing: %v", preflight.VerificationSteps)
+ }
+ if !strings.Contains(joinedVerify, "systemctl is-active") {
+ t.Fatalf("class-specific verification step missing: %v", preflight.VerificationSteps)
+ }
+}
diff --git a/internal/ai/tools/tools_control.go b/internal/ai/tools/tools_control.go
index fd4a1d6222..37009496d4 100644
--- a/internal/ai/tools/tools_control.go
+++ b/internal/ai/tools/tools_control.go
@@ -1484,26 +1484,133 @@ func approvalPreflight(req *approval.ApprovalRequest) *approval.ActionPreflight
dryRunSummary = "Provider dry-run semantics are available for this action class before execution."
}
+ // Default safety / verification copy applies to every action. Per-command
+ // class additions enrich it with concrete operational context the
+ // operator needs before approving (what "restart this service" actually
+ // touches, how Pulse will read back success).
+ safetyChecks := []string{
+ "Approval is scoped to the current organization.",
+ "Command hash must match before execution.",
+ "Approval can be consumed only once.",
+ "Target type and identifier must match the planned action.",
+ }
+ verificationSteps := []string{
+ "Persist unified action audit lifecycle.",
+ "Dispatch only after approval is granted.",
+ "Capture command result or execution error.",
+ "Require Assistant read-after-write verification before final response.",
+ }
+ if extraSafety, extraVerify := approvalCommandClassPreflightAdditions(req.TargetType, req.Command); len(extraSafety) > 0 || len(extraVerify) > 0 {
+ safetyChecks = append(safetyChecks, extraSafety...)
+ verificationSteps = append(verificationSteps, extraVerify...)
+ }
+
return &approval.ActionPreflight{
- Target: target,
- CurrentState: fmt.Sprintf("Resolved approval target: %s.", target),
- IntendedChange: intendedChange,
- DryRunAvailable: dryRunAvailable,
- DryRunSummary: dryRunSummary,
- SafetyChecks: []string{
- "Approval is scoped to the current organization.",
- "Command hash must match before execution.",
- "Approval can be consumed only once.",
- "Target type and identifier must match the planned action.",
- },
- VerificationSteps: []string{
- "Persist unified action audit lifecycle.",
- "Dispatch only after approval is granted.",
- "Capture command result or execution error.",
- "Require Assistant read-after-write verification before final response.",
- },
- GeneratedAt: time.Now().UTC(),
+ Target: target,
+ CurrentState: fmt.Sprintf("Resolved approval target: %s.", target),
+ IntendedChange: intendedChange,
+ DryRunAvailable: dryRunAvailable,
+ DryRunSummary: dryRunSummary,
+ SafetyChecks: safetyChecks,
+ VerificationSteps: verificationSteps,
+ GeneratedAt: time.Now().UTC(),
+ }
+}
+
+// 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
+// the default preflight content rather than getting fabricated extras.
+func classifyApprovalCommand(targetType, command string) string {
+ cmd := strings.ToLower(strings.TrimSpace(command))
+ if cmd == "" {
+ return ""
+ }
+ switch {
+ case strings.Contains(cmd, "systemctl restart"), strings.Contains(cmd, "service restart"):
+ return "service-restart"
+ case strings.Contains(cmd, "systemctl stop"), strings.Contains(cmd, "service stop"):
+ return "service-stop"
+ case strings.Contains(cmd, "systemctl start"), strings.Contains(cmd, "service start"):
+ return "service-start"
+ case strings.Contains(cmd, "systemctl reload"):
+ return "service-reload"
+ case strings.Contains(cmd, "docker restart"), strings.Contains(cmd, "podman restart"):
+ return "container-restart"
+ case strings.Contains(cmd, "docker stop"), strings.Contains(cmd, "podman stop"):
+ return "container-stop"
+ case strings.HasPrefix(cmd, "kubectl rollout restart"):
+ return "k8s-rollout-restart"
+ }
+ return ""
+}
+
+// approvalCommandClassPreflightAdditions returns hand-authored safety and
+// verification additions for known command classes. The text is concrete
+// operational context the operator wants before approving — what the
+// command actually touches, how Pulse will read back success — rather
+// than generic boilerplate. Unknown classes return empty slices so the
+// default preflight is not padded with fabricated assertions.
+func approvalCommandClassPreflightAdditions(targetType, command string) (safetyChecks []string, verificationSteps []string) {
+ switch classifyApprovalCommand(targetType, command) {
+ case "service-restart":
+ return []string{
+ "Service will be briefly unavailable during the systemctl restart; no other unit dependencies are altered.",
+ "Restart applies only to the named unit on the named host; no fleet-wide propagation.",
+ }, []string{
+ "Read back `systemctl is-active <unit>` after dispatch.",
+ "Tail recent journal entries for the unit to confirm a clean restart and no crash loop.",
+ }
+ case "service-stop":
+ return []string{
+ "Service will remain stopped after dispatch; restart requires a follow-up approved action.",
+ "Stopping the unit may impact dependent services; verify the dependency tree before approving.",
+ }, []string{
+ "Read back `systemctl is-active <unit>` and confirm `inactive`.",
+ "Check journal for any auto-restart triggered by Restart=always policy.",
+ }
+ case "service-start":
+ return []string{
+ "Start applies only to the named unit; no other state changes.",
+ "Unit will run with the configuration currently on disk; uncommitted config drift will take effect.",
+ }, []string{
+ "Read back `systemctl is-active <unit>` and confirm `active`.",
+ "Tail journal for startup errors before the first request lands.",
+ }
+ case "service-reload":
+ return []string{
+ "Reload reads new configuration without dropping in-flight requests when supported by the unit.",
+ "Units without reload semantics fall back to restart; check unit type before approving.",
+ }, []string{
+ "Read back `systemctl status <unit>` and confirm `Active: active (running)` post-reload.",
+ "Tail recent journal entries for configuration parse errors.",
+ }
+ case "container-restart":
+ return []string{
+ "Container will be briefly unavailable during the restart; image and volume mounts are unchanged.",
+ "Restart applies only to the named container; no compose-stack-wide propagation.",
+ }, []string{
+ "Read back container state via `docker inspect` (or podman) and confirm `Status: running`.",
+ "Tail recent container logs for crash patterns or startup errors.",
+ }
+ case "container-stop":
+ return []string{
+ "Container will remain stopped after dispatch; image and volume mounts persist for next start.",
+ "Stopping a container may impact dependent containers in the same compose stack.",
+ }, []string{
+ "Read back container state and confirm `Status: exited`.",
+ "Check for any restart policy that may auto-restart the container.",
+ }
+ case "k8s-rollout-restart":
+ return []string{
+ "Pods are rolled in waves per the deployment strategy; service availability is preserved when readiness probes pass.",
+ "PodDisruptionBudget and HPA-driven scaling continue to apply during the rollout.",
+ }, []string{
+ "Watch `kubectl rollout status` until the deployment converges.",
+ "Verify pod readiness with `kubectl get pods -l <selector>` after rollout.",
+ }
}
+ return nil, nil
}
func approvalPreflightTarget(req *approval.ApprovalRequest) string {