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.

Persist action audits through tool executor

rcourtman3c62e8e5f550
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 62010acff3..e661f5eb94 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -132,3 +132,9 @@ boundary. When the AI service assembles unified-resource context for a model
request, it must record a durable export audit with the active destination
model and governed redaction decision instead of treating the prompt boundary
as a transient formatting step.
+
+The same runtime boundary now also owns durable action execution auditing.
+`internal/ai/chat/service.go` initializes the unified-resource audit store on
+startup, and the write-action tool paths under `internal/ai/tools/` persist
+append-only action lifecycle and action audit records through that shared
+store instead of leaving command execution state in memory-only tool helpers.
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 43d31786d6..824199cbdf 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -89,6 +89,9 @@ That same shared store now also persists append-only action lifecycle, action
audit, and export audit records, giving the control-plane verbs a durable home
next to the resource timeline instead of leaving those records isolated in
memory-only models.
+The in-memory store mirrors the durable audit contract by upserting action
+audits on action ID, so tests and runtime callers observe the same current
+record state that SQLite persists for the control-plane execution trail.
The unified resource core is strong and canonical, but monitoring and some
frontend/API consumers are still being tightened around it.
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index b41dd43e3f..334cf677ed 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -81,6 +81,7 @@ type Service struct {
readState unifiedresources.ReadState
agentServer AgentServer
executor *tools.PulseToolExecutor
+ actionAuditStore unifiedresources.ResourceStore
sessions *SessionStore
agenticLoop *AgenticLoop
provider providers.StreamingProvider
@@ -274,6 +275,22 @@ func (s *Service) Start(ctx context.Context) error {
}
s.sessions = store
+ if s.actionAuditStore == nil {
+ actionAuditStore, err := unifiedresources.NewSQLiteResourceStore(dataDir, s.orgID)
+ if err != nil {
+ log.Warn().
+ Err(err).
+ Str("orgID", s.orgID).
+ Str("data_dir", dataDir).
+ Msg("failed to initialize action audit store")
+ } else {
+ s.actionAuditStore = actionAuditStore
+ if s.executor != nil {
+ s.executor.SetActionAuditStore(actionAuditStore)
+ }
+ }
+ }
+
// Create provider
provider, err := s.createProvider()
if err != nil {
@@ -302,6 +319,12 @@ func (s *Service) Stop(ctx context.Context) error {
s.started = false
s.provider = nil
+ if s.actionAuditStore != nil {
+ if err := s.actionAuditStore.Close(); err != nil {
+ log.Warn().Err(err).Msg("failed to close action audit store")
+ }
+ s.actionAuditStore = nil
+ }
log.Info().Msg("pulse AI (direct) stopped")
return nil
}
diff --git a/internal/ai/chat/service_tooling_test.go b/internal/ai/chat/service_tooling_test.go
index 3aeb7a1b0c..6d438be1be 100644
--- a/internal/ai/chat/service_tooling_test.go
+++ b/internal/ai/chat/service_tooling_test.go
@@ -226,3 +226,36 @@ func TestExecuteMCPTool_ErrorsAndSuccess(t *testing.T) {
t.Fatalf("expected success, got output=%q err=%v", output, err)
}
}
+
+func TestService_StartInitializesActionAuditStore(t *testing.T) {
+ svc := NewService(Config{
+ AIConfig: &config.AIConfig{
+ ChatModel: "mock:model",
+ },
+ DataDir: t.TempDir(),
+ OrgID: "org-a",
+ })
+ svc.providerFactory = func(modelStr string) (providers.StreamingProvider, error) {
+ return &mockStreamingProvider{}, nil
+ }
+
+ if err := svc.Start(context.Background()); err != nil {
+ t.Fatalf("start service: %v", err)
+ }
+ if svc.actionAuditStore == nil {
+ t.Fatalf("expected action audit store to be initialized")
+ }
+ if svc.executor == nil {
+ t.Fatalf("expected executor to be initialized")
+ }
+ if svc.executor.GetActionAuditStore() == nil {
+ t.Fatalf("expected executor action audit store to be set")
+ }
+
+ if err := svc.Stop(context.Background()); err != nil {
+ t.Fatalf("stop service: %v", err)
+ }
+ if svc.actionAuditStore != nil {
+ t.Fatalf("expected action audit store to be cleared on stop")
+ }
+}
diff --git a/internal/ai/tools/action_audit.go b/internal/ai/tools/action_audit.go
new file mode 100644
index 0000000000..516cd6dd4f
--- /dev/null
+++ b/internal/ai/tools/action_audit.go
@@ -0,0 +1,192 @@
+package tools
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"
+ unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rs/zerolog/log"
+)
+
+func (e *PulseToolExecutor) executeCommandWithAudit(
+ ctx context.Context,
+ capabilityName string,
+ resourceID string,
+ approvalID string,
+ requiresApproval bool,
+ agentID string,
+ payload agentexec.ExecuteCommandPayload,
+ requestedBy string,
+ reason string,
+) (*agentexec.CommandResultPayload, error) {
+ if e.agentServer == nil {
+ return nil, fmt.Errorf("no agent server available")
+ }
+
+ actionID := uuid.NewString()
+ requestCorrelationID := strings.TrimSpace(approvalID)
+ if requestCorrelationID == "" {
+ requestCorrelationID = actionID
+ }
+
+ now := time.Now().UTC()
+ plan := unifiedresources.ActionPlan{
+ ActionID: actionID,
+ RequestID: requestCorrelationID,
+ Allowed: true,
+ RequiresApproval: requiresApproval,
+ ApprovalPolicy: func() unifiedresources.ActionApprovalLevel {
+ if requiresApproval {
+ return unifiedresources.ApprovalAdmin
+ }
+ return unifiedresources.ApprovalNone
+ }(),
+ PlannedAt: now,
+ ExpiresAt: now.Add(5 * time.Minute),
+ ResourceVersion: "",
+ PolicyVersion: "",
+ GraphVersion: "",
+ PlanHash: actionPlanHash(actionID, requestCorrelationID, capabilityName, resourceID, payload, reason),
+ Message: reason,
+ }
+
+ record := unifiedresources.ActionAuditRecord{
+ ID: actionID,
+ CreatedAt: now,
+ UpdatedAt: now,
+ State: unifiedresources.ActionStateExecuting,
+ Request: unifiedresources.ActionRequest{
+ RequestID: requestCorrelationID,
+ ResourceID: strings.TrimSpace(resourceID),
+ CapabilityName: capabilityName,
+ Params: map[string]any{
+ "command": payload.Command,
+ "targetType": payload.TargetType,
+ "targetId": payload.TargetID,
+ "agentId": agentID,
+ "approvalId": approvalID,
+ "requestedBy": requestedBy,
+ },
+ Reason: reason,
+ RequestedBy: requestedBy,
+ },
+ Plan: plan,
+ }
+
+ if approvalID != "" {
+ if store := approval.GetStore(); store != nil {
+ if req, ok := store.GetApproval(approvalID); ok && req != nil {
+ record.Approvals = append(record.Approvals, unifiedresources.ActionApprovalRecord{
+ Actor: strings.TrimSpace(req.DecidedBy),
+ Method: unifiedresources.MethodAPI,
+ Timestamp: approvalTimestamp(req),
+ Outcome: unifiedresources.OutcomeApproved,
+ Reason: strings.TrimSpace(req.Context),
+ })
+ if req.Status == approval.StatusDenied {
+ record.Approvals[len(record.Approvals)-1].Outcome = unifiedresources.OutcomeRejected
+ }
+ }
+ }
+ }
+
+ e.recordActionLifecycle(actionID, unifiedresources.ActionStatePlanned, requestedBy, reason)
+ e.recordActionLifecycle(actionID, unifiedresources.ActionStateExecuting, requestedBy, fmt.Sprintf("dispatching command to agent %s", agentID))
+ e.recordActionAudit(record)
+
+ result, err := e.agentServer.ExecuteCommand(ctx, agentID, payload)
+ finalState := unifiedresources.ActionStateCompleted
+ finalMessage := "command completed"
+ executionResult := &unifiedresources.ExecutionResult{Success: true}
+
+ if err != nil {
+ finalState = unifiedresources.ActionStateFailed
+ finalMessage = err.Error()
+ executionResult.Success = false
+ executionResult.ErrorMessage = err.Error()
+ } else {
+ output := result.Stdout
+ if strings.TrimSpace(result.Stderr) != "" {
+ if output != "" {
+ output += "\n"
+ }
+ output += result.Stderr
+ }
+ executionResult.Output = output
+ if result.ExitCode != 0 {
+ finalState = unifiedresources.ActionStateFailed
+ finalMessage = fmt.Sprintf("exit code %d", result.ExitCode)
+ executionResult.Success = false
+ executionResult.ErrorMessage = finalMessage
+ }
+ }
+
+ record.State = finalState
+ record.UpdatedAt = time.Now().UTC()
+ record.Result = executionResult
+ e.recordActionAudit(record)
+ e.recordActionLifecycle(actionID, finalState, requestedBy, finalMessage)
+
+ return result, err
+}
+
+func (e *PulseToolExecutor) recordActionAudit(record unifiedresources.ActionAuditRecord) {
+ if e == nil || e.actionAuditStore == nil {
+ return
+ }
+ if err := e.actionAuditStore.RecordActionAudit(record); err != nil {
+ log.Warn().
+ Err(err).
+ Str("action_id", record.ID).
+ Str("resource_id", record.Request.ResourceID).
+ Msg("failed to persist action audit")
+ }
+}
+
+func (e *PulseToolExecutor) recordActionLifecycle(actionID string, state unifiedresources.ActionState, actor, message string) {
+ if e == nil || e.actionAuditStore == nil || strings.TrimSpace(actionID) == "" {
+ return
+ }
+ event := unifiedresources.ActionLifecycleEvent{
+ ActionID: actionID,
+ Timestamp: time.Now().UTC(),
+ State: state,
+ Actor: actor,
+ Message: message,
+ }
+ if err := e.actionAuditStore.RecordActionLifecycleEvent(event); err != nil {
+ log.Warn().
+ Err(err).
+ Str("action_id", actionID).
+ Str("state", string(state)).
+ Msg("failed to persist action lifecycle event")
+ }
+}
+
+func actionPlanHash(actionID, requestID, capabilityName, resourceID string, payload agentexec.ExecuteCommandPayload, reason string) string {
+ sum := sha256.Sum256([]byte(strings.Join([]string{
+ actionID,
+ requestID,
+ capabilityName,
+ strings.TrimSpace(resourceID),
+ payload.Command,
+ payload.TargetType,
+ payload.TargetID,
+ reason,
+ }, "|")))
+ return hex.EncodeToString(sum[:])
+}
+
+func approvalTimestamp(req *approval.ApprovalRequest) time.Time {
+ if req == nil || req.DecidedAt == nil {
+ return time.Now().UTC()
+ }
+ return req.DecidedAt.UTC()
+}
diff --git a/internal/ai/tools/control_run_command_test.go b/internal/ai/tools/control_run_command_test.go
index 92b1cbbf10..0a1e7ea899 100644
--- a/internal/ai/tools/control_run_command_test.go
+++ b/internal/ai/tools/control_run_command_test.go
@@ -5,10 +5,12 @@ import (
"encoding/json"
"strings"
"testing"
+ "time"
"github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
@@ -175,6 +177,7 @@ func TestPulseToolExecutor_ExecuteRunCommand(t *testing.T) {
})
t.Run("ExecuteSuccess", func(t *testing.T) {
+ store := unifiedresources.NewMemoryStore()
agentSrv := &mockAgentServer{}
agentSrv.On("GetConnectedAgents").Return([]agentexec.ConnectedAgent{
{AgentID: "agent1", Hostname: "node1"},
@@ -187,7 +190,10 @@ func TestPulseToolExecutor_ExecuteRunCommand(t *testing.T) {
ExitCode: 0,
}, nil).Once()
- exec := NewPulseToolExecutor(ExecutorConfig{AgentServer: agentSrv})
+ exec := NewPulseToolExecutor(ExecutorConfig{
+ AgentServer: agentSrv,
+ ActionAuditStore: store,
+ })
exec.SetContext("host", "host1", false)
result, err := exec.executeRunCommand(ctx, map[string]interface{}{
@@ -203,6 +209,19 @@ func TestPulseToolExecutor_ExecuteRunCommand(t *testing.T) {
assert.Equal(t, true, v["ok"])
}
agentSrv.AssertExpectations(t)
+
+ audits, err := store.GetActionAudits("", time.Time{}, 10)
+ require.NoError(t, err)
+ require.Len(t, audits, 1)
+ assert.Equal(t, "pulse_control", audits[0].Request.CapabilityName)
+ assert.Contains(t, audits[0].Plan.Message, "run command \"uptime\"")
+
+ events, err := store.GetActionLifecycleEvents(audits[0].ID, time.Time{}, 10)
+ require.NoError(t, err)
+ require.Len(t, events, 3)
+ assert.Equal(t, unifiedresources.ActionStatePlanned, events[2].State)
+ assert.Equal(t, unifiedresources.ActionStateExecuting, events[1].State)
+ assert.Equal(t, unifiedresources.ActionStateCompleted, events[0].State)
})
}
diff --git a/internal/ai/tools/executor.go b/internal/ai/tools/executor.go
index 401b934b99..86115333c7 100644
--- a/internal/ai/tools/executor.go
+++ b/internal/ai/tools/executor.go
@@ -370,6 +370,7 @@ type ExecutorConfig struct {
// Optional providers - unified resources
UnifiedResourceProvider UnifiedResourceProvider
+ ActionAuditStore unifiedresources.ResourceStore
// Optional typed read access to current infrastructure state.
// When provided, tool handlers should prefer this over models.StateSnapshot iteration.
ReadState unifiedresources.ReadState
@@ -421,6 +422,7 @@ type PulseToolExecutor struct {
// Unified resources provider
unifiedResourceProvider UnifiedResourceProvider
+ actionAuditStore unifiedresources.ResourceStore
// Typed state reader. Nil means "legacy-only": tools must fall back to StateSnapshot access.
readState unifiedresources.ReadState
@@ -495,6 +497,7 @@ func NewPulseToolExecutor(cfg ExecutorConfig) *PulseToolExecutor {
knowledgeStoreProvider: cfg.KnowledgeStoreProvider,
discoveryProvider: cfg.DiscoveryProvider,
unifiedResourceProvider: cfg.UnifiedResourceProvider,
+ actionAuditStore: cfg.ActionAuditStore,
readState: cfg.ReadState,
controlLevel: cfg.ControlLevel,
protectedGuests: cfg.ProtectedGuests,
@@ -701,6 +704,16 @@ func (e *PulseToolExecutor) SetUnifiedResourceProvider(provider UnifiedResourceP
e.unifiedResourceProvider = provider
}
+// SetActionAuditStore sets the durable store used to persist action audit and lifecycle events.
+func (e *PulseToolExecutor) SetActionAuditStore(store unifiedresources.ResourceStore) {
+ e.actionAuditStore = store
+}
+
+// GetActionAuditStore returns the durable store used to persist action audit and lifecycle events.
+func (e *PulseToolExecutor) GetActionAuditStore() unifiedresources.ResourceStore {
+ return e.actionAuditStore
+}
+
// SetResolvedContext sets the session-scoped resolved context for resource validation.
// This should be called by the agentic loop before executing tools for a session.
func (e *PulseToolExecutor) SetResolvedContext(ctx ResolvedContextProvider) {
diff --git a/internal/ai/tools/executor_setters_test.go b/internal/ai/tools/executor_setters_test.go
index 19ee058ee1..319d979bcc 100644
--- a/internal/ai/tools/executor_setters_test.go
+++ b/internal/ai/tools/executor_setters_test.go
@@ -87,6 +87,10 @@ func TestPulseToolExecutor_Setters(t *testing.T) {
updatesProvider := &mockUpdatesProvider{}
exec.SetUpdatesProvider(updatesProvider)
assert.Equal(t, updatesProvider, exec.updatesProvider)
+
+ actionAuditStore := unifiedresources.NewMemoryStore()
+ exec.SetActionAuditStore(actionAuditStore)
+ assert.Equal(t, actionAuditStore, exec.actionAuditStore)
}
func TestPulseToolExecutor_ListTools(t *testing.T) {
diff --git a/internal/ai/tools/tools_control.go b/internal/ai/tools/tools_control.go
index 110522c556..50f25b8d68 100644
--- a/internal/ai/tools/tools_control.go
+++ b/internal/ai/tools/tools_control.go
@@ -81,6 +81,8 @@ func (e *PulseToolExecutor) executeControl(ctx context.Context, args map[string]
func (e *PulseToolExecutor) executeRunCommand(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {
command, _ := args["command"].(string)
targetHost, _ := args["target_host"].(string)
+ approvalID, _ := args["_approval_id"].(string)
+ approvalID = strings.TrimSpace(approvalID)
if command == "" {
return NewErrorResult(fmt.Errorf("command is required")), nil
@@ -123,6 +125,8 @@ func (e *PulseToolExecutor) executeRunCommand(ctx context.Context, args map[stri
}
}
+ requiresApproval := !e.isAutonomous && (e.controlLevel == ControlLevelControlled || decision == agentexec.PolicyRequireApproval)
+
if targetHost == "" && e.agentServer != nil {
agents := e.agentServer.GetConnectedAgents()
if len(agents) > 1 {
@@ -182,11 +186,31 @@ func (e *PulseToolExecutor) executeRunCommand(ctx context.Context, args map[stri
Str("target_id", routing.TargetID).
Msg("[pulse_control] Routing command execution")
- result, err := e.agentServer.ExecuteCommand(ctx, routing.AgentID, agentexec.ExecuteCommandPayload{
- Command: command,
- TargetType: routing.TargetType,
- TargetID: routing.TargetID,
- })
+ result, err := e.executeCommandWithAudit(
+ ctx,
+ "pulse_control",
+ func() string {
+ if targetHost != "" {
+ return targetHost
+ }
+ return routing.AgentHostname
+ }(),
+ approvalID,
+ requiresApproval,
+ routing.AgentID,
+ agentexec.ExecuteCommandPayload{
+ Command: command,
+ TargetType: routing.TargetType,
+ TargetID: routing.TargetID,
+ },
+ "pulse_control",
+ fmt.Sprintf("run command %q on %s", command, func() string {
+ if strings.TrimSpace(targetHost) != "" {
+ return strings.TrimSpace(targetHost)
+ }
+ return strings.TrimSpace(routing.AgentHostname)
+ }()),
+ )
if err != nil {
return NewErrorResult(err), nil
}
@@ -250,6 +274,8 @@ func (e *PulseToolExecutor) executeControlGuest(ctx context.Context, args map[st
guestID, _ := args["guest_id"].(string)
action, _ := args["action"].(string)
force, _ := args["force"].(bool)
+ approvalID, _ := args["_approval_id"].(string)
+ approvalID = strings.TrimSpace(approvalID)
if guestID == "" {
return NewErrorResult(fmt.Errorf("guest_id is required")), nil
@@ -350,6 +376,8 @@ func (e *PulseToolExecutor) executeControlGuest(ctx context.Context, args map[st
return NewTextResult(formatControlApprovalNeeded(guest.Name, guest.VMID, action, command, approvalID)), nil
}
+ requiresApproval := !e.isAutonomous && e.controlLevel == ControlLevelControlled
+
if e.agentServer == nil {
return NewErrorResult(fmt.Errorf("no agent server available")), nil
}
@@ -359,11 +387,21 @@ func (e *PulseToolExecutor) executeControlGuest(ctx context.Context, args map[st
return NewErrorResult(fmt.Errorf("no agent available on node '%s'; install Pulse Unified Agent on the node to enable control", guest.Node)), nil
}
- result, err := e.agentServer.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{
- Command: command,
- TargetType: "agent",
- TargetID: "",
- })
+ result, err := e.executeCommandWithAudit(
+ ctx,
+ "pulse_control",
+ fmt.Sprintf("%s:%d", guest.Node, guest.VMID),
+ approvalID,
+ requiresApproval,
+ agentID,
+ agentexec.ExecuteCommandPayload{
+ Command: command,
+ TargetType: "agent",
+ TargetID: "",
+ },
+ "pulse_control",
+ fmt.Sprintf("%s guest %s", action, guest.Name),
+ )
if err != nil {
return NewErrorResult(err), nil
}
diff --git a/internal/ai/tools/tools_docker.go b/internal/ai/tools/tools_docker.go
index 22cf36b530..73b0ef1415 100644
--- a/internal/ai/tools/tools_docker.go
+++ b/internal/ai/tools/tools_docker.go
@@ -98,6 +98,8 @@ func (e *PulseToolExecutor) executeDockerControl(ctx context.Context, args map[s
containerName, _ := args["container"].(string)
hostName, _ := args["host"].(string)
operation, _ := args["operation"].(string)
+ approvalID, _ := args["_approval_id"].(string)
+ approvalID = strings.TrimSpace(approvalID)
if containerName == "" {
return NewErrorResult(fmt.Errorf("container name is required")), nil
@@ -129,6 +131,7 @@ func (e *PulseToolExecutor) executeDockerControl(ctx context.Context, args map[s
// Check if this is a pre-approved execution (validated + single-use).
preApproved := consumeApprovalWithValidation(args, e.orgID, command, "docker", approvalTargetID)
+ requiresApproval := !e.isAutonomous && (e.controlLevel == ControlLevelControlled || (e.policy != nil && e.policy.Evaluate(command) == agentexec.PolicyRequireApproval))
// Get the agent hostname for approval records
agentHostname := e.getAgentHostnameForDockerHost(dockerHost)
@@ -175,11 +178,26 @@ func (e *PulseToolExecutor) executeDockerControl(ctx context.Context, args map[s
Str("target_id", routing.TargetID).
Msg("[pulse_docker] Routing docker command execution")
- result, err := e.agentServer.ExecuteCommand(ctx, routing.AgentID, agentexec.ExecuteCommandPayload{
- Command: command,
- TargetType: routing.TargetType,
- TargetID: routing.TargetID,
- })
+ result, err := e.executeCommandWithAudit(
+ ctx,
+ "pulse_docker",
+ func() string {
+ if dockerHost.ID != "" {
+ return fmt.Sprintf("%s:%s", dockerHost.ID, container.Name)
+ }
+ return fmt.Sprintf("%s:%s", dockerHost.Hostname, container.Name)
+ }(),
+ approvalID,
+ requiresApproval,
+ routing.AgentID,
+ agentexec.ExecuteCommandPayload{
+ Command: command,
+ TargetType: routing.TargetType,
+ TargetID: routing.TargetID,
+ },
+ "pulse_docker",
+ fmt.Sprintf("%s docker container %s", operation, container.Name),
+ )
if err != nil {
return NewErrorResult(err), nil
}
diff --git a/internal/ai/tools/tools_file.go b/internal/ai/tools/tools_file.go
index 6defb50e92..b1e238c238 100644
--- a/internal/ai/tools/tools_file.go
+++ b/internal/ai/tools/tools_file.go
@@ -230,6 +230,8 @@ func (e *PulseToolExecutor) executeFileAppend(ctx context.Context, path, content
if e.agentServer == nil {
return NewErrorResult(fmt.Errorf("no agent server available")), nil
}
+ approvalID, _ := args["_approval_id"].(string)
+ approvalID = strings.TrimSpace(approvalID)
if blocked, reason := safety.IsSensitivePath(path); blocked {
return NewToolResponseResult(NewToolBlockedError(
@@ -279,6 +281,7 @@ func (e *PulseToolExecutor) executeFileAppend(ctx context.Context, path, content
// Check if pre-approved (validated + single-use).
preApproved := consumeApprovalWithValidation(args, e.orgID, approvalCommand, "file", approvalTargetID)
+ requiresApproval := !e.isAutonomous && e.controlLevel == ControlLevelControlled
// Skip approval checks if pre-approved or in autonomous mode
if !preApproved && !e.isAutonomous && e.controlLevel == ControlLevelControlled {
@@ -309,11 +312,26 @@ func (e *PulseToolExecutor) executeFileAppend(ctx context.Context, path, content
command = fmt.Sprintf("echo %s | base64 -d >> %s", shellEscape(encoded), shellEscape(path))
}
- result, err := e.agentServer.ExecuteCommand(ctx, routing.AgentID, agentexec.ExecuteCommandPayload{
- Command: command,
- TargetType: routing.TargetType,
- TargetID: routing.TargetID,
- })
+ result, err := e.executeCommandWithAudit(
+ ctx,
+ "pulse_file_edit",
+ func() string {
+ if dockerContainer != "" {
+ return fmt.Sprintf("%s:%s:%s", targetHost, dockerContainer, path)
+ }
+ return fmt.Sprintf("%s:%s", targetHost, path)
+ }(),
+ approvalID,
+ requiresApproval,
+ routing.AgentID,
+ agentexec.ExecuteCommandPayload{
+ Command: command,
+ TargetType: routing.TargetType,
+ TargetID: routing.TargetID,
+ },
+ "pulse_file_edit",
+ fmt.Sprintf("append %d bytes to %s", len(content), path),
+ )
if err != nil {
return NewErrorResult(fmt.Errorf("failed to append to file: %w", err)), nil
}
@@ -366,6 +384,8 @@ func (e *PulseToolExecutor) executeFileWrite(ctx context.Context, path, content,
if e.agentServer == nil {
return NewErrorResult(fmt.Errorf("no agent server available")), nil
}
+ approvalID, _ := args["_approval_id"].(string)
+ approvalID = strings.TrimSpace(approvalID)
if blocked, reason := safety.IsSensitivePath(path); blocked {
return NewToolResponseResult(NewToolBlockedError(
@@ -415,6 +435,7 @@ func (e *PulseToolExecutor) executeFileWrite(ctx context.Context, path, content,
// Check if pre-approved (validated + single-use).
preApproved := consumeApprovalWithValidation(args, e.orgID, approvalCommand, "file", approvalTargetID)
+ requiresApproval := !e.isAutonomous && e.controlLevel == ControlLevelControlled
// Skip approval checks if pre-approved or in autonomous mode
if !preApproved && !e.isAutonomous && e.controlLevel == ControlLevelControlled {
@@ -445,11 +466,26 @@ func (e *PulseToolExecutor) executeFileWrite(ctx context.Context, path, content,
command = fmt.Sprintf("echo %s | base64 -d > %s", shellEscape(encoded), shellEscape(path))
}
- result, err := e.agentServer.ExecuteCommand(ctx, routing.AgentID, agentexec.ExecuteCommandPayload{
- Command: command,
- TargetType: routing.TargetType,
- TargetID: routing.TargetID,
- })
+ result, err := e.executeCommandWithAudit(
+ ctx,
+ "pulse_file_edit",
+ func() string {
+ if dockerContainer != "" {
+ return fmt.Sprintf("%s:%s:%s", targetHost, dockerContainer, path)
+ }
+ return fmt.Sprintf("%s:%s", targetHost, path)
+ }(),
+ approvalID,
+ requiresApproval,
+ routing.AgentID,
+ agentexec.ExecuteCommandPayload{
+ Command: command,
+ TargetType: routing.TargetType,
+ TargetID: routing.TargetID,
+ },
+ "pulse_file_edit",
+ fmt.Sprintf("write %d bytes to %s", len(content), path),
+ )
if err != nil {
return NewErrorResult(fmt.Errorf("failed to write file: %w", err)), nil
}
diff --git a/internal/ai/tools/tools_kubernetes.go b/internal/ai/tools/tools_kubernetes.go
index 727283042c..d5412e7bc9 100644
--- a/internal/ai/tools/tools_kubernetes.go
+++ b/internal/ai/tools/tools_kubernetes.go
@@ -505,6 +505,8 @@ func (e *PulseToolExecutor) executeKubernetesScale(ctx context.Context, args map
namespace, _ := args["namespace"].(string)
deployment, _ := args["deployment"].(string)
replicas := intArg(args, "replicas", -1)
+ approvalID, _ := args["_approval_id"].(string)
+ approvalID = strings.TrimSpace(approvalID)
if clusterArg == "" {
return NewErrorResult(fmt.Errorf("cluster is required")), nil
@@ -547,6 +549,7 @@ func (e *PulseToolExecutor) executeKubernetesScale(ctx context.Context, args map
// Check if pre-approved (validated + single-use).
preApproved := consumeApprovalWithValidation(args, e.orgID, command, "kubernetes", approvalTargetID)
+ requiresApproval := !e.isAutonomous && e.controlLevel == ControlLevelControlled
// Request approval if needed
if !preApproved && !e.isAutonomous && e.controlLevel == ControlLevelControlled {
@@ -559,11 +562,21 @@ func (e *PulseToolExecutor) executeKubernetesScale(ctx context.Context, args map
return NewErrorResult(fmt.Errorf("no agent server available")), nil
}
- result, err := e.agentServer.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{
- Command: command,
- TargetType: "agent",
- TargetID: "",
- })
+ result, err := e.executeCommandWithAudit(
+ ctx,
+ "pulse_kubernetes",
+ fmt.Sprintf("%s:%s:deployment:%s", clusterScope, namespace, deployment),
+ approvalID,
+ requiresApproval,
+ agentID,
+ agentexec.ExecuteCommandPayload{
+ Command: command,
+ TargetType: "agent",
+ TargetID: "",
+ },
+ "pulse_kubernetes",
+ fmt.Sprintf("scale deployment %s to %d replicas", deployment, replicas),
+ )
if err != nil {
return NewErrorResult(fmt.Errorf("failed to execute kubectl: %w", err)), nil
}
@@ -585,6 +598,8 @@ func (e *PulseToolExecutor) executeKubernetesRestart(ctx context.Context, args m
clusterArg, _ := args["cluster"].(string)
namespace, _ := args["namespace"].(string)
deployment, _ := args["deployment"].(string)
+ approvalID, _ := args["_approval_id"].(string)
+ approvalID = strings.TrimSpace(approvalID)
if clusterArg == "" {
return NewErrorResult(fmt.Errorf("cluster is required")), nil
@@ -624,6 +639,7 @@ func (e *PulseToolExecutor) executeKubernetesRestart(ctx context.Context, args m
// Check if pre-approved (validated + single-use).
preApproved := consumeApprovalWithValidation(args, e.orgID, command, "kubernetes", approvalTargetID)
+ requiresApproval := !e.isAutonomous && e.controlLevel == ControlLevelControlled
// Request approval if needed
if !preApproved && !e.isAutonomous && e.controlLevel == ControlLevelControlled {
@@ -636,11 +652,21 @@ func (e *PulseToolExecutor) executeKubernetesRestart(ctx context.Context, args m
return NewErrorResult(fmt.Errorf("no agent server available")), nil
}
- result, err := e.agentServer.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{
- Command: command,
- TargetType: "agent",
- TargetID: "",
- })
+ result, err := e.executeCommandWithAudit(
+ ctx,
+ "pulse_kubernetes",
+ fmt.Sprintf("%s:%s:deployment:%s", clusterScope, namespace, deployment),
+ approvalID,
+ requiresApproval,
+ agentID,
+ agentexec.ExecuteCommandPayload{
+ Command: command,
+ TargetType: "agent",
+ TargetID: "",
+ },
+ "pulse_kubernetes",
+ fmt.Sprintf("restart deployment %s", deployment),
+ )
if err != nil {
return NewErrorResult(fmt.Errorf("failed to execute kubectl: %w", err)), nil
}
@@ -662,6 +688,8 @@ func (e *PulseToolExecutor) executeKubernetesDeletePod(ctx context.Context, args
clusterArg, _ := args["cluster"].(string)
namespace, _ := args["namespace"].(string)
pod, _ := args["pod"].(string)
+ approvalID, _ := args["_approval_id"].(string)
+ approvalID = strings.TrimSpace(approvalID)
if clusterArg == "" {
return NewErrorResult(fmt.Errorf("cluster is required")), nil
@@ -701,6 +729,7 @@ func (e *PulseToolExecutor) executeKubernetesDeletePod(ctx context.Context, args
// Check if pre-approved (validated + single-use).
preApproved := consumeApprovalWithValidation(args, e.orgID, command, "kubernetes", approvalTargetID)
+ requiresApproval := !e.isAutonomous && e.controlLevel == ControlLevelControlled
// Request approval if needed
if !preApproved && !e.isAutonomous && e.controlLevel == ControlLevelControlled {
@@ -713,11 +742,21 @@ func (e *PulseToolExecutor) executeKubernetesDeletePod(ctx context.Context, args
return NewErrorResult(fmt.Errorf("no agent server available")), nil
}
- result, err := e.agentServer.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{
- Command: command,
- TargetType: "agent",
- TargetID: "",
- })
+ result, err := e.executeCommandWithAudit(
+ ctx,
+ "pulse_kubernetes",
+ fmt.Sprintf("%s:%s:pod:%s", clusterScope, namespace, pod),
+ approvalID,
+ requiresApproval,
+ agentID,
+ agentexec.ExecuteCommandPayload{
+ Command: command,
+ TargetType: "agent",
+ TargetID: "",
+ },
+ "pulse_kubernetes",
+ fmt.Sprintf("delete pod %s", pod),
+ )
if err != nil {
return NewErrorResult(fmt.Errorf("failed to execute kubectl: %w", err)), nil
}
@@ -741,6 +780,8 @@ func (e *PulseToolExecutor) executeKubernetesExec(ctx context.Context, args map[
pod, _ := args["pod"].(string)
container, _ := args["container"].(string)
command, _ := args["command"].(string)
+ approvalID, _ := args["_approval_id"].(string)
+ approvalID = strings.TrimSpace(approvalID)
if clusterArg == "" {
return NewErrorResult(fmt.Errorf("cluster is required")), nil
@@ -788,6 +829,7 @@ func (e *PulseToolExecutor) executeKubernetesExec(ctx context.Context, args map[
// Check if pre-approved (validated + single-use).
preApproved := consumeApprovalWithValidation(args, e.orgID, kubectlCmd, "kubernetes", approvalTargetID)
+ requiresApproval := !e.isAutonomous && e.controlLevel == ControlLevelControlled
// Request approval if needed
if !preApproved && !e.isAutonomous && e.controlLevel == ControlLevelControlled {
@@ -800,11 +842,21 @@ func (e *PulseToolExecutor) executeKubernetesExec(ctx context.Context, args map[
return NewErrorResult(fmt.Errorf("no agent server available")), nil
}
- result, err := e.agentServer.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{
- Command: kubectlCmd,
- TargetType: "agent",
- TargetID: "",
- })
+ result, err := e.executeCommandWithAudit(
+ ctx,
+ "pulse_kubernetes",
+ fmt.Sprintf("%s:%s:pod:%s", clusterScope, namespace, pod),
+ approvalID,
+ requiresApproval,
+ agentID,
+ agentexec.ExecuteCommandPayload{
+ Command: kubectlCmd,
+ TargetType: "agent",
+ TargetID: "",
+ },
+ "pulse_kubernetes",
+ fmt.Sprintf("execute command in pod %s", pod),
+ )
if err != nil {
return NewErrorResult(fmt.Errorf("failed to execute kubectl: %w", err)), nil
}
diff --git a/internal/unifiedresources/store.go b/internal/unifiedresources/store.go
index 8616863436..96cab21bfd 100644
--- a/internal/unifiedresources/store.go
+++ b/internal/unifiedresources/store.go
@@ -848,6 +848,12 @@ func (m *MemoryStore) GetRecentChanges(canonicalID string, since time.Time, limi
func (m *MemoryStore) RecordActionAudit(record ActionAuditRecord) error {
m.mu.Lock()
defer m.mu.Unlock()
+ for i := range m.actionAudits {
+ if m.actionAudits[i].ID == record.ID {
+ m.actionAudits[i] = record
+ return nil
+ }
+ }
m.actionAudits = append(m.actionAudits, record)
return nil
}
diff --git a/internal/unifiedresources/store_test.go b/internal/unifiedresources/store_test.go
index 88560cd457..1ceb55185f 100644
--- a/internal/unifiedresources/store_test.go
+++ b/internal/unifiedresources/store_test.go
@@ -350,6 +350,49 @@ func TestActionAuditRecord_RoundTrip(t *testing.T) {
}
}
+func TestMemoryStore_RecordActionAudit_UpsertsByID(t *testing.T) {
+ store := NewMemoryStore()
+ now := time.Date(2026, 3, 18, 13, 30, 0, 0, time.UTC)
+
+ first := ActionAuditRecord{
+ ID: "action-2",
+ CreatedAt: now,
+ UpdatedAt: now,
+ State: ActionStatePlanned,
+ Request: ActionRequest{
+ RequestID: "req-2",
+ ResourceID: "vm:301",
+ CapabilityName: "restart",
+ RequestedBy: "agent:test",
+ },
+ }
+ second := first
+ second.UpdatedAt = now.Add(2 * time.Minute)
+ second.State = ActionStateCompleted
+ second.Result = &ExecutionResult{Success: true, Output: "done"}
+
+ if err := store.RecordActionAudit(first); err != nil {
+ t.Fatalf("RecordActionAudit(first): %v", err)
+ }
+ if err := store.RecordActionAudit(second); err != nil {
+ t.Fatalf("RecordActionAudit(second): %v", err)
+ }
+
+ results, err := store.GetActionAudits("vm:301", now.Add(-time.Hour), 10)
+ if err != nil {
+ t.Fatalf("GetActionAudits: %v", err)
+ }
+ if len(results) != 1 {
+ t.Fatalf("expected 1 action audit after upsert, got %d", len(results))
+ }
+ if results[0].State != ActionStateCompleted {
+ t.Fatalf("expected latest action state to win, got %q", results[0].State)
+ }
+ if results[0].Result == nil || results[0].Result.Output != "done" {
+ t.Fatalf("expected latest action result to win, got %+v", results[0].Result)
+ }
+}
+
func TestActionLifecycleEvent_RoundTrip(t *testing.T) {
store := newTestStore(t)
now := time.Date(2026, 3, 18, 14, 0, 0, 0, time.UTC)