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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Keep scoped agent action reads free of execution detail
pulse-triage[bot]7a22ad7fe4ab
diff --git a/cmd/pulse-mcp/action_disclosure_test.go b/cmd/pulse-mcp/action_disclosure_test.gonew file mode 100644index 0000000000..004b766508--- /dev/null+++ b/cmd/pulse-mcp/action_disclosure_test.go@@ -0,0 +1,156 @@+package main++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+ "github.com/rcourtman/pulse-go-rewrite/internal/api"+ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++type mcpDisclosureFlusher struct {+ http.ResponseWriter+ ready chan struct{}+ once sync.Once+}++func (w *mcpDisclosureFlusher) Flush() {+ w.ResponseWriter.(http.Flusher).Flush()+ w.once.Do(func() { close(w.ready) })+}++type mcpDisclosureWriter struct {+ bytes.Buffer+ received chan struct{}+ once sync.Once+}++func (w *mcpDisclosureWriter) Write(p []byte) (int, error) {+ n, err := w.Buffer.Write(p)+ if bytes.Contains(w.Bytes(), []byte(`"method":"notifications/action.completed"`)) {+ w.once.Do(func() { close(w.received) })+ }+ return n, err+}++// Exercise both consuming MCP paths against Pulse's real authenticated HTTP+// handlers. No adapter-side redactor may substitute for server enforcement:+// text and structured tools/call output and live JSON-RPC params must agree.+func TestServer_ActionDisclosureThroughRealAgentHandlers(t *testing.T) {+ const privateDetail = "mcp-synthetic-command-output"+ for _, restricted := range []bool{true, false} {+ name := "action_capable"+ if restricted {+ name = "monitoring_read"+ }+ t.Run(name, func(t *testing.T) {+ scopes := []string{config.ScopeMonitoringRead}+ if !restricted {+ scopes = append(scopes, config.ScopeAIExecute)+ }+ token, err := config.NewAPITokenRecord("fixture-mcp-token", "fixture", scopes)+ if err != nil {+ t.Fatal(err)+ }+ cfg := &config.Config{DataPath: t.TempDir(), APITokens: []config.APITokenRecord{*token}}+ resources := api.NewResourceHandlers(cfg)+ defer resources.CloseStores()+ resources.SetStateProvider(mcpFleetSnapshot{resources: []unified.Resource{{ID: "vm:101", Type: "vm", Name: "fixture-vm"}}})+ handler := api.NewAgentContextHandler(resources)+ store, err := resources.Store("default")+ if err != nil {+ t.Fatal(err)+ }+ now := time.Now().UTC()+ truth := unified.ActionResultV2{+ Version: unified.ActionResultV2Version,+ Execution: unified.ActionExecutionTruth{Status: unified.ActionExecutionFailed, ReasonCode: "execution_failed", Summary: privateDetail},+ Verification: unified.ActionVerificationTruth{Status: unified.ActionVerificationNotAttempted, EvidenceClass: unified.ActionEvidenceNone},+ Compensation: unified.ActionCompensationTruth{Support: unified.ActionCompensationUnavailable, Status: unified.ActionCompensationNotAvailable},+ }+ record := unified.ActionAuditRecord{+ ID: "mcp-action", CreatedAt: now, UpdatedAt: now, State: unified.ActionStateFailed,+ Request: unified.ActionRequest{ResourceID: "vm:101", CapabilityName: "restart", Params: map[string]any{"command": "printf " + privateDetail}},+ Result: &unified.ExecutionResult{ErrorMessage: "plan_drift: " + privateDetail, ActionResultV2: &truth},+ }+ if err := store.RecordActionAudit(record); err != nil {+ t.Fatal(err)+ }+ b := api.NewAgentEventBroadcaster()+ ready := make(chan struct{})+ mux := http.NewServeMux()+ mux.HandleFunc(agentcapabilities.AgentEventsPath, api.RequireAuth(cfg, api.RequireScope(config.ScopeMonitoringRead, func(w http.ResponseWriter, r *http.Request) {+ b.HandleAgentEvents(&mcpDisclosureFlusher{ResponseWriter: w, ready: ready}, r)+ })))+ mux.HandleFunc("/api/agent/resource-context/", api.RequireAuth(cfg, api.RequireScope(config.ScopeMonitoringRead, handler.HandleResourceContext)))+ backend := httptest.NewServer(mux)+ defer backend.Close()+ manifest := agentcapabilities.CanonicalManifest()+ server := &mcpServer{baseURL: backend.URL, token: "fixture-mcp-token", http: backend.Client(), manifest: &manifest}+ var stdout bytes.Buffer+ server.serve(strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_resource_context","arguments":{"resourceId":"vm:101"}}}`+"\n"), &stdout)+ var reply struct {+ Result agentcapabilities.MCPToolResult+ Error any+ }+ if err := json.Unmarshal(stdout.Bytes(), &reply); err != nil {+ t.Fatal(err)+ }+ if reply.Error != nil || reply.Result.IsError || len(reply.Result.Content) != 1 {+ t.Fatalf("MCP tools/call failed: %s", stdout.String())+ }+ structured, err := json.Marshal(reply.Result.StructuredContent)+ if err != nil {+ t.Fatal(err)+ }+ check := func(body []byte) {+ t.Helper()+ if restricted {+ if bytes.Contains(body, []byte(privateDetail)) || bytes.Contains(body, []byte(`"actionResultV2"`)) || !bytes.Contains(body, []byte(`"detailsRedacted":true`)) || !bytes.Contains(body, []byte(`"errorMessage":"plan_drift:"`)) {+ t.Errorf("MCP disclosed restricted action detail or lost safe outcome: %s", body)+ }+ } else if !bytes.Contains(body, []byte(privateDetail)) || !bytes.Contains(body, []byte(`"actionResultV2"`)) || bytes.Contains(body, []byte(`"actionResultSummary"`)) {+ t.Errorf("authorized MCP detail changed: %s", body)+ }+ }+ check([]byte(reply.Result.Content[0].Text))+ check(structured)+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ out := &mcpDisclosureWriter{received: make(chan struct{})}+ server.out = out+ done := make(chan error, 1)+ go func() { done <- server.streamSSEOnce(ctx, agentcapabilities.AgentEventsPath) }()+ select {+ case <-ready:+ case <-ctx.Done():+ t.Fatal("MCP stream never subscribed")+ }+ b.PublishActionCompletedRecord(record)+ select {+ case <-out.received:+ case <-ctx.Done():+ t.Fatal("MCP notification never arrived")+ }+ cancel()+ <-done+ var notification agentcapabilities.JSONRPCRequest+ if err := json.Unmarshal(out.Bytes(), ¬ification); err != nil {+ t.Fatal(err)+ }+ if notification.Method != "notifications/action.completed" {+ t.Fatalf("wrong MCP event: %s", out.String())+ }+ check(notification.Params)+ })+ }+}diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 5b75adf6a9..a6c20a44dd 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -15,6 +15,22 @@## Purpose+### Scoped agent outcome reads do not disclose execution detail++The agent event/resource-context projections preserve validated execution,+verification/evidence-class and compensation axes in an explicitly redacted+`actionResultSummary` for tokens without `ai:execute`. Full canonical evidence,+free-form result/error text and verification notes are withheld rather than+rewritten into new evidence. Known refusal prefixes remain branchable; session+and existing command-capable reads remain unchanged. No stored evidence, agent+command admission, recovery action or recovery-data identity changes.++The ordinary API disclosure/contract tests check legacy and V2 producers,+malformed-digest fallback, stored-evidence preservation and scoped concurrent+streams. The MCP consumer test checks real authenticated tools/call and live+notification readback. A content-free outcome is not independent recovery proof+or permission to replay any stopped operation.+### Image comparison refresh is not container lifecycle authorityDocker/Podman collection can refresh stale registry evidence after a changeddiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 6d6bfaabc8..c72c87797a 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -21,6 +21,33 @@## Purpose+### Agent action details follow command-disclosure authority++The existing agent event and resource-context reads require `monitoring:read`,+but that scope does not disclose command/output detail. API tokens without+`ai:execute` receive no full `actionResultV2`: arbitrary result summaries,+reason strings, evidence identities/references and recovery detail can carry+command or provider output even after credential-pattern redaction. Instead,+`actionResultSummary` explicitly sets `detailsRedacted:true` and preserves only+validated execution status, verification status/evidence class, compensation+support/status and any nested compensation execution/verification axes. This+is a read projection, not a canonical evidence envelope; no evidence is deleted,+re-digested or invented, and a malformed canonical result remains inconclusive.++Restricted legacy errors retain only an exact known refusal prefix (such as+`plan_drift:`), never its arbitrary suffix or an unknown prefix. Verification+notes follow the command redaction rule even when the command is absent.+Session and existing `ai:execute` disclosure are unchanged. Per-request copies+must preserve other subscribers' and stored evidence, auth and tenant boundaries.++Ordinary-suite `agent_action_disclosure_test.go` checks both completion producers,+pointer/value payloads, legacy/V2 records, scoped/session/wildcard callers,+independent outcome axes, malformed digests, durable context HTTP reads and+concurrent authenticated SSE subscribers. `action_disclosure_test.go` in the MCP+adapter runs the real authenticated handlers through tools/call text/structured+output and live JSON-RPC notifications. `TestContract_AgentScopedActionResultIsAnExplicitSummary`+pins the distinction between withheld detail and canonical evidence.+### Admit saved permissions before presenting user access`RBACAPI.getUserPermissions` admits the existing array response only when everydiff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex 9ff68a50a3..4ad5c250f6 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -18,6 +18,33 @@## Purpose+### Agent action details follow command-disclosure authority++The existing agent event and resource-context reads require `monitoring:read`,+but that scope does not disclose command/output detail. API tokens without+`ai:execute` receive no full `actionResultV2`: arbitrary result summaries,+reason strings, evidence identities/references and recovery detail can carry+command or provider output even after credential-pattern redaction. Instead,+`actionResultSummary` explicitly sets `detailsRedacted:true` and preserves only+validated execution status, verification status/evidence class, compensation+support/status and any nested compensation execution/verification axes. This+is a read projection, not a canonical evidence envelope; no evidence is deleted,+re-digested or invented, and a malformed canonical result remains inconclusive.++Restricted legacy errors retain only an exact known refusal prefix (such as+`plan_drift:`), never its arbitrary suffix or an unknown prefix. Verification+notes follow the command redaction rule even when the command is absent.+Session and existing `ai:execute` disclosure are unchanged. Per-request copies+must preserve other subscribers' and stored evidence, auth and tenant boundaries.++Ordinary-suite `agent_action_disclosure_test.go` checks both completion producers,+pointer/value payloads, legacy/V2 records, scoped/session/wildcard callers,+independent outcome axes, malformed digests, durable context HTTP reads and+concurrent authenticated SSE subscribers. `action_disclosure_test.go` in the MCP+adapter runs the real authenticated handlers through tools/call text/structured+output and live JSON-RPC notifications. `TestContract_AgentScopedActionResultIsAnExplicitSummary`+pins the distinction between withheld detail and canonical evidence.+### Unread token inventory is not a safe access postureAPI Access never claims no credentials or no full-access credentials from adiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 8e15447c5f..322515d99c 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -21,6 +21,22 @@## Purpose+### Scoped agent outcome reads do not disclose execution detail++The agent event/resource-context projections preserve validated execution,+verification/evidence-class and compensation axes in an explicitly redacted+`actionResultSummary` for tokens without `ai:execute`. Full canonical evidence,+free-form result/error text and verification notes are withheld rather than+rewritten into new evidence. Known refusal prefixes remain branchable; session+and existing command-capable reads remain unchanged. No stored evidence, agent+command admission, recovery action or recovery-data identity changes.++The ordinary API disclosure/contract tests check legacy and V2 producers,+malformed-digest fallback, stored-evidence preservation and scoped concurrent+streams. The MCP consumer test checks real authenticated tools/call and live+notification readback. A content-free outcome is not independent recovery proof+or permission to replay any stopped operation.+### Datastore discovery cannot turn unread history into absencePBS datastore enumeration uses the same bounded, fully read and closed HTTP 200diff --git a/internal/api/agent_action_disclosure_test.go b/internal/api/agent_action_disclosure_test.gonew file mode 100644index 0000000000..72b252b80e--- /dev/null+++ b/internal/api/agent_action_disclosure_test.go@@ -0,0 +1,302 @@+package api++import (+ "bufio"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "reflect"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++// These strings deliberately match no credential-shaped redactor. Command and+// output privacy must not depend on guessing whether their contents are secrets.+const agentPrivateDetail = "scope-only-private-detail"++func agentDisclosureRecord(t *testing.T, legacy bool) unified.ActionAuditRecord {+ t.Helper()+ now := time.Now().UTC()+ record := unified.ActionAuditRecord{+ ID: "disclosure-action", State: unified.ActionStateFailed, CreatedAt: now, UpdatedAt: now,+ Request: unified.ActionRequest{+ ResourceID: "vm:101", CapabilityName: "restart", RequestedBy: "operator",+ Params: map[string]any{"command": "printf " + agentPrivateDetail},+ },+ Result: &unified.ExecutionResult{+ ErrorMessage: "plan_drift: " + agentPrivateDetail,+ Verification: &unified.ActionVerificationResult{+ Ran: true, Success: false, Command: "check " + agentPrivateDetail,+ Output: agentPrivateDetail, Note: agentPrivateDetail, RanAt: now,+ },+ },+ }+ if legacy {+ return record+ }+ truth := apiActionResultTruth(t, unified.ActionExecutionFailed, unified.ActionVerificationContradicted, unified.ActionEvidenceIndependent)+ truth.Execution.ReasonCode = agentPrivateDetail+ truth.Execution.Summary = agentPrivateDetail+ truth.Verification.ReasonCode = agentPrivateDetail+ truth.Verification.Summary = agentPrivateDetail+ truth.Verification.Evidence[0].ID = agentPrivateDetail+ truth.Verification.Evidence[0].Method = agentPrivateDetail+ truth.Verification.Evidence[0].Summary = agentPrivateDetail+ truth.Verification.Evidence[0].ReasonCode = agentPrivateDetail+ truth.Verification.Evidence[0].Refs = []unified.ActionEvidenceRef{{ID: agentPrivateDetail, Kind: agentPrivateDetail, Digest: "sha256:" + strings.Repeat("b", 64)}}+ truth.Verification.Evidence[0].Digest = ""+ truth.Compensation = unified.ActionCompensationTruth{+ Support: unified.ActionCompensationDeclared, Status: unified.ActionCompensationSucceeded,+ Strategy: agentPrivateDetail, Trigger: agentPrivateDetail, ReasonCode: agentPrivateDetail,+ Summary: agentPrivateDetail, AttemptID: agentPrivateDetail, StepID: agentPrivateDetail,+ StartedAt: &now, CompletedAt: &now,+ Execution: &unified.ActionExecutionTruth{Status: unified.ActionExecutionSucceeded, Summary: agentPrivateDetail},+ Verification: &unified.ActionVerificationTruth{+ Status: unified.ActionVerificationConfirmed, EvidenceClass: unified.ActionEvidenceIndependent,+ Summary: agentPrivateDetail, Evidence: copyAgentActionEvidence(truth.Verification.Evidence),+ },+ Evidence: copyAgentActionEvidence(truth.Verification.Evidence),+ RestoredState: &unified.ActionRestoredStateTruth{+ SubjectID: agentPrivateDetail, ExpectedDigest: "sha256:" + strings.Repeat("a", 64),+ ObservedDigest: "sha256:" + strings.Repeat("a", 64), ObservedAt: now,+ },+ }+ normalized, err := unified.NormalizeActionResultV2(truth)+ if err != nil {+ t.Fatal(err)+ }+ record.Result.ActionResultV2 = &normalized+ return record+}++func assertAgentDisclosureWire(t *testing.T, body []byte, restricted bool) {+ t.Helper()+ if restricted {+ if strings.Contains(string(body), agentPrivateDetail) || strings.Contains(string(body), `"actionResultV2"`) {+ t.Errorf("restricted action response retained command/output details: %s", body)+ }+ for _, want := range []string{`"actionResultSummary":`, `"detailsRedacted":true`, `"commandRedacted":true`, `"errorMessage":"plan_drift:"`} {+ if !strings.Contains(string(body), want) {+ t.Errorf("restricted response lost %s: %s", want, body)+ }+ }+ } else if !strings.Contains(string(body), agentPrivateDetail) || !strings.Contains(string(body), `"actionResultV2"`) || strings.Contains(string(body), `"actionResultSummary"`) {+ t.Errorf("authorized response changed its detail contract: %s", body)+ }+}++func TestAgentActionDisclosureAcrossProducersAndScopes(t *testing.T) {+ for _, legacy := range []bool{false, true} {+ for _, scopes := range [][]string{+ {config.ScopeMonitoringRead},+ {config.ScopeMonitoringRead, config.ScopeActionsPlan},+ {config.ScopeMonitoringRead, config.ScopeActionsApprove},+ {config.ScopeMonitoringRead, config.ScopeAIExecute},+ {"*"}, {}, nil,+ } {+ name := strings.Join(scopes, "+")+ if legacy {+ name = "legacy/" + name+ }+ t.Run(name, func(t *testing.T) {+ record := agentDisclosureRecord(t, legacy)+ before, _ := json.Marshal(record)+ req := httptest.NewRequest(http.MethodGet, "/api/agent/events", nil)+ if scopes != nil {+ attachAPITokenRecord(req, &config.APITokenRecord{Scopes: scopes})+ }+ restricted := !requestCanReadAgentCommandPayloads(req)+ payload, ok := projectAgentActionCompletedPayload(record)+ if !ok {+ t.Fatal("terminal record did not project")+ }+ broadcaster := NewAgentEventBroadcaster()+ events, unsubscribe := broadcaster.Subscribe()+ defer unsubscribe()+ broadcaster.PublishActionCompletedRecord(record)+ for _, event := range []AgentEvent{+ {Kind: AgentEventActionCompleted, Payload: payload},+ {Kind: AgentEventActionCompleted, Payload: &payload},+ <-events,+ } {+ got := redactAgentEventCommandsForRequest(event, req)+ if !restricted && !reflect.DeepEqual(got, event) {+ t.Error("authorized event payload was changed")+ }+ body, err := json.Marshal(got)+ if err != nil {+ t.Fatal(err)+ }+ assertAgentDisclosureWire(t, body, restricted)+ }+ bundle := AgentResourceContext{RecentActions: projectAgentResourceActions([]unified.ActionAuditRecord{record})}+ redactAgentResourceContextCommandsForRequest(&bundle, req)+ body, err := json.Marshal(bundle)+ if err != nil {+ t.Fatal(err)+ }+ assertAgentDisclosureWire(t, body, restricted)+ after, _ := json.Marshal(record)+ if string(before) != string(after) {+ t.Fatal("per-request projection mutated the original action evidence")+ }+ })+ }+ }+}++func TestAgentActionDisclosureRetainsIndependentTruthAxes(t *testing.T) {+ for _, execution := range []unified.ActionExecutionStatus{unified.ActionExecutionNotRun, unified.ActionExecutionSucceeded, unified.ActionExecutionFailed, unified.ActionExecutionInconclusive} {+ for verification, classes := range map[unified.ActionVerificationStatus][]unified.ActionEvidenceClass{+ unified.ActionVerificationNotAttempted: {unified.ActionEvidenceNone},+ unified.ActionVerificationConfirmed: {unified.ActionEvidenceAgentAttested, unified.ActionEvidenceIndependent},+ unified.ActionVerificationContradicted: {unified.ActionEvidenceAgentAttested, unified.ActionEvidenceIndependent},+ unified.ActionVerificationInconclusive: {unified.ActionEvidenceNone, unified.ActionEvidenceAgentAttested, unified.ActionEvidenceIndependent},+ } {+ for _, class := range classes {+ t.Run(string(execution)+"/"+string(verification)+"/"+string(class), func(t *testing.T) {+ truth := apiActionResultTruth(t, execution, verification, class)+ got := summarizeAgentActionResult(&truth)+ if !got.DetailsRedacted || got.Execution.Status != execution || got.Verification.Status != verification || got.Verification.EvidenceClass != class || got.Compensation.Support != truth.Compensation.Support || got.Compensation.Status != truth.Compensation.Status {+ t.Fatalf("truth axes changed: %#v", got)+ }+ })+ }+ }+ }+ truth := agentDisclosureRecord(t, false).Result.ActionResultV2+ got := summarizeAgentActionResult(truth)+ if got.Compensation.Status != unified.ActionCompensationSucceeded || got.Compensation.Execution.Status != unified.ActionExecutionSucceeded || got.Compensation.Verification.Status != unified.ActionVerificationConfirmed || got.Compensation.Verification.EvidenceClass != unified.ActionEvidenceIndependent {+ t.Fatalf("compensation truth collapsed into primary failure: %#v", got)+ }+ if summarizeAgentActionResult(nil) != nil {+ t.Fatal("absent canonical result became a fabricated outcome")+ }+ truth.Verification.Evidence[0].Digest = "sha256:" + strings.Repeat("0", 64)+ got = summarizeAgentActionResult(truth)+ if got.Execution.Status != unified.ActionExecutionInconclusive || got.Verification.Status != unified.ActionVerificationInconclusive || got.Verification.EvidenceClass != unified.ActionEvidenceNone {+ t.Fatalf("invalid stored evidence became a successful summary: %#v", got)+ }+}++func TestAgentActionDisclosureErrorAndNoteWithoutCommand(t *testing.T) {+ for _, message := range []string{+ agentPrivateDetail, agentPrivateDetail + ": failure", "plan_drift_suffix: " + agentPrivateDetail,+ "plan_drift: " + agentPrivateDetail, "resource_remediation_locked: " + agentPrivateDetail,+ "action_plan_expired: " + agentPrivateDetail, "action_dry_run_only: " + agentPrivateDetail,+ } {+ got := redactAgentEventActionCompletedCommand(AgentEventActionCompletedPayload{+ ErrorMessage: message, Verification: &AgentResourceActionVerification{Ran: true, Note: agentPrivateDetail},+ })+ body, _ := json.Marshal(got)+ if strings.Contains(string(body), agentPrivateDetail) || !got.CommandRedacted || !got.Verification.CommandRedacted || !got.Verification.Ran {+ t.Errorf("error or note bypassed command-free redaction: %s", body)+ }+ if strings.HasPrefix(message, "plan_drift:") && got.ErrorMessage != "plan_drift:" {+ t.Errorf("known refusal prefix changed: %q", got.ErrorMessage)+ }+ }+}++func TestAgentActionDisclosureContextHTTPPreservesStoredEvidence(t *testing.T) {+ h, _ := agentContextFixtureHandlers(t, "vm:101")+ store, err := h.resources.getStore("default")+ if err != nil {+ t.Fatal(err)+ }+ record := agentDisclosureRecord(t, false)+ if err := store.RecordActionAudit(record); err != nil {+ t.Fatal(err)+ }+ before, found, err := store.GetActionAudit(record.ID)+ if err != nil || !found {+ t.Fatalf("saved record: %v, %v", found, err)+ }+ // The session read after the scoped read must still have original evidence.+ for _, restricted := range []bool{true, false, true} {+ req := httptest.NewRequest(http.MethodGet, "/api/agent/resource-context/vm:101", nil)+ if restricted {+ attachAPITokenRecord(req, &config.APITokenRecord{Scopes: []string{config.ScopeMonitoringRead}})+ }+ res := httptest.NewRecorder()+ h.HandleResourceContext(res, req)+ if res.Code != http.StatusOK {+ t.Fatalf("context HTTP %d: %s", res.Code, res.Body.String())+ }+ assertAgentDisclosureWire(t, res.Body.Bytes(), restricted)+ }+ after, _, err := store.GetActionAudit(record.ID)+ if err != nil || !reflect.DeepEqual(before, after) {+ t.Fatal("scoped HTTP read rewrote stored canonical evidence", err)+ }+}++func TestAgentActionDisclosureConcurrentSSESubscribers(t *testing.T) {+ b := NewAgentEventBroadcaster()+ readToken := newTokenRecord(t, "fixture-read-token", []string{config.ScopeMonitoringRead}, nil)+ actionToken := newTokenRecord(t, "fixture-action-token", []string{config.ScopeMonitoringRead, config.ScopeAIExecute}, nil)+ cfg := newTestConfigWithTokens(t, readToken, actionToken)+ server := httptest.NewServer(RequireAuth(cfg, RequireScope(config.ScopeMonitoringRead, b.HandleAgentEvents)))+ defer server.Close()+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ type subscriber struct {+ body *http.Response+ reader *bufio.Reader+ restricted bool+ }+ var clients []subscriber+ for _, token := range []string{"fixture-read-token", "fixture-action-token"} {+ req, _ := http.NewRequestWithContext(ctx, http.MethodGet, server.URL, nil)+ req.Header.Set("X-API-Token", token)+ resp, err := server.Client().Do(req)+ if err != nil {+ t.Fatal(err)+ }+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ t.Fatalf("authenticated SSE status %d", resp.StatusCode)+ }+ reader := bufio.NewReader(resp.Body)+ for {+ line, err := reader.ReadString('\n')+ if err != nil {+ t.Fatal(err)+ }+ if line == "\n" {+ break+ }+ }+ clients = append(clients, subscriber{resp, reader, token == "fixture-read-token"})+ }+ if b.SubscriberCount() != 2 {+ t.Fatal("both streams must subscribe before publish")+ }+ record := agentDisclosureRecord(t, false)+ b.PublishActionCompletedRecord(record)+ var wg sync.WaitGroup+ for _, client := range clients {+ wg.Add(1)+ go func() {+ defer wg.Done()+ for {+ line, err := client.reader.ReadString('\n')+ if err != nil {+ t.Error(err)+ return+ }+ if strings.HasPrefix(line, "data: ") {+ assertAgentDisclosureWire(t, []byte(line), client.restricted)+ return+ }+ }+ }()+ }+ wg.Wait()+}diff --git a/internal/api/agent_action_result_summary.go b/internal/api/agent_action_result_summary.gonew file mode 100644index 0000000000..87838763a8--- /dev/null+++ b/internal/api/agent_action_result_summary.go@@ -0,0 +1,84 @@+package api++import unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"++// AgentActionResultSummary is a content-free view of validated action truth.+// It is deliberately not ActionResultV2: withholding evidence must not leave+// an apparently complete canonical envelope with missing or rewritten digests.+// The full result remains behind the existing command-disclosure authority.+type AgentActionResultSummary struct {+ DetailsRedacted bool `json:"detailsRedacted"`+ Execution AgentActionExecutionSummary `json:"execution"`+ Verification AgentActionVerificationSummary `json:"verification"`+ Compensation AgentActionCompensationSummary `json:"compensation"`+}++type AgentActionExecutionSummary struct {+ Status unified.ActionExecutionStatus `json:"status"`+}++type AgentActionVerificationSummary struct {+ Status unified.ActionVerificationStatus `json:"status"`+ EvidenceClass unified.ActionEvidenceClass `json:"evidenceClass"`+}++type AgentActionCompensationSummary struct {+ Support unified.ActionCompensationSupport `json:"support"`+ Status unified.ActionCompensationStatus `json:"status"`+ Execution *AgentActionExecutionSummary `json:"execution,omitempty"`+ Verification *AgentActionVerificationSummary `json:"verification,omitempty"`+}++func summarizeAgentActionResult(result *unified.ActionResultV2) *AgentActionResultSummary {+ if result == nil {+ return nil+ }+ // Normalize a private copy before projecting the closed status vocabulary.+ // Normalization owns nested slices; never let one subscriber rewrite the+ // evidence another subscriber (or the durable store) will receive.+ copy := *result+ copy.Verification = copyAgentActionVerification(result.Verification)+ copy.Compensation.Evidence = copyAgentActionEvidence(result.Compensation.Evidence)+ if result.Compensation.Verification != nil {+ verification := copyAgentActionVerification(*result.Compensation.Verification)+ copy.Compensation.Verification = &verification+ }+ canonical := unified.CanonicalActionResultV2(unified.ActionAuditRecord{+ Result: &unified.ExecutionResult{ActionResultV2: ©},+ })+ summary := &AgentActionResultSummary{+ DetailsRedacted: true,+ Execution: AgentActionExecutionSummary{Status: canonical.Execution.Status},+ Verification: AgentActionVerificationSummary{+ Status: canonical.Verification.Status, EvidenceClass: canonical.Verification.EvidenceClass,+ },+ Compensation: AgentActionCompensationSummary{+ Support: canonical.Compensation.Support, Status: canonical.Compensation.Status,+ },+ }+ if execution := canonical.Compensation.Execution; execution != nil {+ summary.Compensation.Execution = &AgentActionExecutionSummary{Status: execution.Status}+ }+ if verification := canonical.Compensation.Verification; verification != nil {+ summary.Compensation.Verification = &AgentActionVerificationSummary{+ Status: verification.Status, EvidenceClass: verification.EvidenceClass,+ }+ }+ return summary+}++func copyAgentActionVerification(verification unified.ActionVerificationTruth) unified.ActionVerificationTruth {+ verification.Evidence = copyAgentActionEvidence(verification.Evidence)+ return verification+}++func copyAgentActionEvidence(evidence []unified.ActionEvidence) []unified.ActionEvidence {+ if evidence == nil {+ return nil+ }+ copy := append([]unified.ActionEvidence(nil), evidence...)+ for i := range copy {+ copy[i].Refs = append([]unified.ActionEvidenceRef(nil), evidence[i].Refs...)+ }+ return copy+}diff --git a/internal/api/agent_command_redaction.go b/internal/api/agent_command_redaction.goindex 77db04f7b5..214ebdc050 100644--- a/internal/api/agent_command_redaction.go+++ b/internal/api/agent_command_redaction.go@@ -2,8 +2,10 @@ package apiimport ("net/http"+ "strings""github.com/rcourtman/pulse-go-rewrite/internal/config"+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")func requestCanReadAgentCommandPayloads(r *http.Request) bool {@@ -58,6 +60,16 @@ func redactAgentEventApprovalPendingCommand(payload AgentEventApprovalPendingPay}func redactAgentEventActionCompletedCommand(payload AgentEventActionCompletedPayload) AgentEventActionCompletedPayload {+ if payload.ActionResultV2 != nil {+ payload.ActionResultSummary = summarizeAgentActionResult(payload.ActionResultV2)+ payload.ActionResultV2 = nil+ payload.Success = payload.ActionResultSummary.Execution.Status == unified.ActionExecutionSucceeded+ payload.CommandRedacted = true+ }+ if payload.ErrorMessage != "" {+ payload.ErrorMessage = redactAgentActionError(payload.ErrorMessage)+ payload.CommandRedacted = true+ }if payload.Command != "" {payload.Command = ""payload.CommandRedacted = true@@ -79,6 +91,16 @@ func redactAgentResourceApprovalCommand(summary AgentResourceApprovalSummary) Ag}func redactAgentResourceActionCommand(summary AgentResourceActionSummary) AgentResourceActionSummary {+ if summary.ActionResultV2 != nil {+ summary.ActionResultSummary = summarizeAgentActionResult(summary.ActionResultV2)+ summary.ActionResultV2 = nil+ summary.Success = summary.ActionResultSummary.Execution.Status == unified.ActionExecutionSucceeded+ summary.CommandRedacted = true+ }+ if summary.ErrorMessage != "" {+ summary.ErrorMessage = redactAgentActionError(summary.ErrorMessage)+ summary.CommandRedacted = true+ }if summary.Command != "" {summary.Command = ""summary.CommandRedacted = true@@ -92,9 +114,29 @@ func redactAgentResourceActionCommand(summary AgentResourceActionSummary) AgentR}func redactAgentResourceVerificationCommand(verification *AgentResourceActionVerification) {- if verification == nil || verification.Command == "" {+ if verification == nil {return}- verification.Command = ""- verification.CommandRedacted = true+ if verification.Command != "" || verification.Note != "" {+ verification.Command = ""+ verification.Note = ""+ verification.CommandRedacted = true+ }+}++// Error text can echo an arbitrary command or provider output, even after+// known credential patterns have been scrubbed. Keep only the documented,+// closed refusal vocabulary, never the free-form suffix (or an unknown prefix).+func redactAgentActionError(message string) string {+ prefix, _, found := strings.Cut(message, ":")+ if found {+ switch prefix {+ case "resource_remediation_locked", "plan_drift", "action_plan_drift",+ "action_plan_expired", "action_dry_run_only", "action_not_approved",+ "action_already_executing", "action_execution_final",+ "action_execution_unavailable", "action_executor_unavailable":+ return prefix + ":"+ }+ }+ return "[redacted-action-detail]"}diff --git a/internal/api/agent_events.go b/internal/api/agent_events.goindex 179988af36..9fe52d249a 100644--- a/internal/api/agent_events.go+++ b/internal/api/agent_events.go@@ -136,18 +136,19 @@ type AgentEventApprovalPendingPayload struct {// 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"`- CommandRedacted bool `json:"commandRedacted,omitempty"`- State string `json:"state"`- Success bool `json:"success"`- ErrorMessage string `json:"errorMessage,omitempty"`- ActionResultV2 *unifiedresources.ActionResultV2 `json:"actionResultV2,omitempty"`- Verification *AgentResourceActionVerification `json:"verification,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"`+ CommandRedacted bool `json:"commandRedacted,omitempty"`+ State string `json:"state"`+ Success bool `json:"success"`+ ErrorMessage string `json:"errorMessage,omitempty"`+ ActionResultV2 *unifiedresources.ActionResultV2 `json:"actionResultV2,omitempty"`+ ActionResultSummary *AgentActionResultSummary `json:"actionResultSummary,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. Adiff --git a/internal/api/agent_resource_context.go b/internal/api/agent_resource_context.goindex 6e3cd169fa..c88b45f3e8 100644--- a/internal/api/agent_resource_context.go+++ b/internal/api/agent_resource_context.go@@ -66,18 +66,19 @@ type AgentResourceActionVerification struct {// only for session callers or API tokens with action execution scope;// monitoring-read tokens receive commandRedacted instead.type AgentResourceActionSummary struct {- ID string `json:"id"`- CapabilityName string `json:"capabilityName"`- Command string `json:"command,omitempty"`- CommandRedacted bool `json:"commandRedacted,omitempty"`- State string `json:"state"`- Success bool `json:"success"`- ErrorMessage string `json:"errorMessage,omitempty"`- ActionResultV2 *unified.ActionResultV2 `json:"actionResultV2,omitempty"`- Verification *AgentResourceActionVerification `json:"verification,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"`+ CommandRedacted bool `json:"commandRedacted,omitempty"`+ State string `json:"state"`+ Success bool `json:"success"`+ ErrorMessage string `json:"errorMessage,omitempty"`+ ActionResultV2 *unified.ActionResultV2 `json:"actionResultV2,omitempty"`+ ActionResultSummary *AgentActionResultSummary `json:"actionResultSummary,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 ofdiff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 6126e57e78..73e72f7c45 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -22899,6 +22899,33 @@ func TestContract_AgentCommandPayloadsRequireActionScope(t *testing.T) {}}+// The scoped action view is not a canonical result with its evidence removed.+// Keep the explicit summary distinct so consumers cannot mistake withheld+// digests or raw executor text for independently inspectable evidence.+func TestContract_AgentScopedActionResultIsAnExplicitSummary(t *testing.T) {+ record := agentDisclosureRecord(t, false)+ payload, ok := projectAgentActionCompletedPayload(record)+ if !ok {+ t.Fatal("terminal action not projected")+ }+ restricted := redactAgentEventActionCompletedCommand(payload)+ if restricted.ActionResultV2 != nil || restricted.ActionResultSummary == nil || !restricted.ActionResultSummary.DetailsRedacted {+ t.Fatal("restricted canonical details must be withheld, not rewritten")+ }+ encoded, err := json.Marshal(restricted.ActionResultSummary)+ if err != nil {+ t.Fatal(err)+ }+ for _, forbidden := range []string{"digest", "summary", "reasonCode", "method", "subjectId", "refs", agentPrivateDetail} {+ if strings.Contains(string(encoded), forbidden) {+ t.Errorf("content-free summary retained %q: %s", forbidden, encoded)+ }+ }+ if restricted.ActionResultSummary.Execution.Status != record.Result.ActionResultV2.Execution.Status || restricted.ActionResultSummary.Verification.EvidenceClass != record.Result.ActionResultV2.Verification.EvidenceClass {+ t.Fatal("scope projection collapsed execution or evidence-class truth")+ }+}+// TestContract_AgentFleetContextEndpointSurfacesStableShape pins the// agent-paradigm fleet view contract: the endpoint must return a// `resources` array (never null) so agents iterate without