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 execution text out of monitoring-readable change history
pulse-triage[bot]b3c1016e8f75
diff --git a/cmd/pulse-mcp/recent_changes_disclosure_test.go b/cmd/pulse-mcp/recent_changes_disclosure_test.gonew file mode 100644index 0000000000..b2b5b91700--- /dev/null+++ b/cmd/pulse-mcp/recent_changes_disclosure_test.go@@ -0,0 +1,151 @@+package main++import (+ "bytes"+ "context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "reflect"+ "strings"+ "sync/atomic"+ "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"+)++// The actual MCP stdio consumer must not regain execution details through+// either text content or structuredContent. Only the collected history is a+// fixture; discovery, auth, scope, store read and projection are production code.+func TestServer_RecentChangesDisclosureThroughRealHandler(t *testing.T) {+ t.Setenv("PULSE_AUTH_BYPASS", "false")+ const private = "fixture-execution-detail-not-for-monitoring"+ for _, tc := range []struct {+ name string+ scopes []string+ private bool+ }{+ {"monitoring", []string{config.ScopeMonitoringRead}, false},+ {"executor", []string{config.ScopeMonitoringRead, config.ScopeAIExecute}, true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ const token = "mcp-history-fixture-token-123.12345678"+ record, err := config.NewAPITokenRecord(token, "history fixture", tc.scopes)+ if err != nil {+ t.Fatal(err)+ }+ cfg := &config.Config{DataPath: t.TempDir(), APITokens: []config.APITokenRecord{*record}, AuthUser: "admin", AuthPass: "fixture-nonempty-hash"}+ resources := api.NewResourceHandlers(cfg)+ defer resources.CloseStores()+ resources.SetStateProvider(mcpFleetSnapshot{resources: []unified.Resource{{ID: "vm:101", Type: "vm", Name: "db-01"}}})+ store, err := resources.Store("default")+ if err != nil {+ t.Fatal(err)+ }+ for _, change := range []*unified.ResourceChange{+ unified.BuildCommandExecutionChange("vm:101", "alert-1", "operator", private, true, private, map[string]any{"title": private, unified.MetadataAutomatic: map[string]any{"output": private}}),+ unified.BuildRunbookExecutionChange("vm:101", "alert-1", "operator", "rb-1", private, "resolved", false, private, nil),+ } {+ if err := store.RecordChange(*change); err != nil {+ t.Fatal(err)+ }+ }+ before, err := store.GetRecentChangesFiltered("", time.Time{}, 50, unified.ResourceChangeFilters{})+ if err != nil {+ t.Fatal(err)+ }+ original, err := json.Marshal(before)+ if err != nil {+ t.Fatal(err)+ }+ handler := api.NewAgentContextHandler(resources)+ manifest := agentcapabilities.CanonicalManifest()+ protected := api.RequireAuth(cfg, api.RequireScope(config.ScopeMonitoringRead, handler.HandleRecentChanges))+ var calls atomic.Int32+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == agentcapabilities.AgentCapabilitiesPath {+ _ = json.NewEncoder(w).Encode(manifest)+ return+ }+ if r.Method != http.MethodGet || r.URL.Path != agentcapabilities.RecentChangesCapabilityPath || r.URL.RawQuery != "kind=command_executed%2Crunbook_executed&limit=10" {+ t.Errorf("unexpected history request %s %s", r.Method, r.URL.String())+ http.Error(w, "unexpected request", http.StatusNotFound)+ return+ }+ calls.Add(1)+ if r.Header.Get(agentcapabilities.AgentSurfaceHeader) != agentcapabilities.AgentSurfacePulseMCP {+ t.Error("missing MCP surface header")+ }+ protected(w, r)+ }))+ defer backend.Close()+ fetched, err := agentcapabilities.FetchManifest(context.Background(), backend.Client(), backend.URL)+ if err != nil {+ t.Fatal(err)+ }+ server := &mcpServer{baseURL: backend.URL, token: token, manifest: fetched, http: backend.Client()}+ var stdout bytes.Buffer+ server.serve(strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_recent_changes","arguments":{"kind":"command_executed,runbook_executed","limit":10}}}`+"\n"), &stdout)+ var reply struct {+ ID int+ Result agentcapabilities.MCPToolResult+ Error any+ }+ decoder := json.NewDecoder(&stdout)+ if err := decoder.Decode(&reply); err != nil {+ t.Fatal(err)+ }+ if reply.ID != 1 || reply.Error != nil || reply.Result.IsError || len(reply.Result.Content) != 1 {+ t.Fatalf("tools/call: %+v", reply)+ }+ var text api.AgentRecentChanges+ if err := json.Unmarshal([]byte(reply.Result.Content[0].Text), &text); err != nil {+ t.Fatal(err)+ }+ structured, err := json.Marshal(reply.Result.StructuredContent)+ if err != nil {+ t.Fatal(err)+ }+ var parsed api.AgentRecentChanges+ if err := json.Unmarshal(structured, &parsed); err != nil {+ t.Fatal(err)+ }+ if !reflect.DeepEqual(text, parsed) {+ t.Fatal("MCP text and structured content differ")+ }+ if text.Count != 2 || len(text.Changes) != 2 || text.Truncated || text.Limit != 10 {+ t.Fatalf("lost history envelope: %+v", text)+ }+ for _, body := range []string{reply.Result.Content[0].Text, string(structured)} {+ if strings.Contains(body, private) != tc.private {+ t.Error("MCP execution disclosure differs from authority")+ }+ }+ for _, change := range text.Changes {+ if change.CommandRedacted == tc.private || change.Metadata[unified.MetadataAlertIdentifier] != "alert-1" || change.ResourceName != "db-01" {+ t.Errorf("lost scoped history facts: %+v", change)+ }+ }+ if calls.Load() != 1 {+ t.Errorf("history calls = %d, want one read", calls.Load())+ }+ var extra any+ if err := decoder.Decode(&extra); err != io.EOF {+ t.Fatalf("extra stdout: %v", err)+ }+ after, err := store.GetRecentChangesFiltered("", time.Time{}, 50, unified.ResourceChangeFilters{})+ if err != nil {+ t.Fatal(err)+ }+ stored, err := json.Marshal(after)+ if err != nil || string(stored) != string(original) {+ t.Fatal("MCP read rewrote canonical history")+ }+ })+ }+}diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex a6c20a44dd..021893003c 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -15,6 +15,21 @@## Purpose+### Execution history uses a typed read-only projection++The recent-change read keeps kind-specific scalar status facts, not arbitrary+caller metadata that happens to use a familiar key. Runbook titles, stored+reason/From/To text and nested values can contain execution details and are+redacted for monitoring-read callers. Fixed reasons derive only from admitted+boolean command success or the closed incident outcomes; missing or malformed+facts do not establish success or failure. Every execution-history projection+is explicitly marked redacted. Executor/session reads and canonical evidence+are unchanged; this adds no enrollment, token scope or action authority.++Normal-suite typed-fact, authenticated concurrent HTTP, contract and real MCP+consumer regressions cover content visibility and unchanged stored evidence.++### Scoped agent outcome reads do not disclose execution detailThe agent event/resource-context projections preserve validated execution,diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex c72c87797a..5b57c9a0e9 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -21,6 +21,15 @@## Purpose+### Recent-change execution facts are a restricted projection++Monitoring-read history uses kind-specific scalar facts and fixed reasons;+runbook titles and arbitrary stored execution text/metadata stay undisclosed.+The existing response envelope, scopes, filters and canonical history remain+unchanged. The detailed recent-change contract below and normal-suite typed,+HTTP, MCP and JSON snapshot tests own this disclosure boundary.++### Agent action details follow command-disclosure authorityThe existing agent event and resource-context reads require `monitoring:read`,@@ -6883,10 +6892,24 @@ instead. Each change carries the canonical record plus theresource's current `resourceName` and `resourceType` when theregistry still knows it, so history for a removed resource staysreadable. For tokens without `ai:execute`, `command_executed` and-`runbook_executed` changes keep only allowlisted metadata (alert-identifier, success, outcome, automatic, runbook id, title), the-command is cut from the reason, and `commandRedacted` is set, matching-the resource-context and event-stream redaction rule. The shared+`runbook_executed` changes keep only typed, kind-specific facts: a string+alert identifier; a boolean success for commands; a string runbook id,+boolean automatic flag and closed incident outcome (`resolved`, `partial`,+`failed`, `unknown`) for runbooks. Runbook titles, messages, arbitrary caller+details, nested values, unrecognised outcomes and execution From/To text are+not monitoring metadata. Reasons are generated from those admitted facts,+never by trimming stored execution text. Missing or malformed facts do not+become success or failure. `commandRedacted` is always set on these projections,+matching the resource-context and event-stream redaction boundary. Executor+and session reads, canonical stored evidence, non-execution changes, filters,+counts and tenant/authentication rules are unchanged.+`TestAgentRecentChangesExecutionProjectionUsesTypedFacts`,+`TestAgentRecentChangesHTTPPreservesAuthorityAndCanonicalEvidence` and+`TestContract_AgentRecentChangesRunbookProjection` pin this boundary through+canonical producers, stored legacy shapes, concurrent authenticated HTTP reads+and the normal Go test commands. MCP's real `list_recent_changes` consumer must+receive the same redacted text and structured result, without another read or+wider scope. The sharedprojection layer forwards integral JSON numbers as integer queryparameters so manifest integer filters such as `limit` reach theroute; fractional or out-of-range numbers are dropped like objects.diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex 4ad5c250f6..355e3a8d35 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -18,6 +18,24 @@## Purpose+### Execution history metadata is typed, not trusted by its key name++A monitoring-read recent-change response projects command and runbook history+from kind-specific scalar facts only. Command caller details cannot borrow+runbook metadata keys; nested metadata and arbitrary outcome strings are not+safe because their keys look familiar. Runbook titles and stored reason/From/To+text can contain execution details and stay behind the existing `ai:execute`+boundary. Reasons are fixed status summaries derived only from admitted boolean+success or the four incident outcomes; missing/malformed values do not invent a+verdict. Every execution projection is explicitly marked redacted.++This projection never changes canonical records or executor/session output.+Normal-suite typed-fact, contract, authenticated concurrent HTTP and real MCP+consumer tests cover the boundary and evidence preservation. No token scope,+route, event kind, history source, stored retention or execution authority is+added. This is not installed/private-authorizer recovery or release evidence.++### Agent action details follow command-disclosure authorityThe existing agent event and resource-context reads require `monitoring:read`,diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 78a99a42fc..677e1710f6 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -21,6 +21,21 @@## Purpose+### Execution history uses a typed read-only projection++The recent-change read keeps kind-specific scalar status facts, not arbitrary+caller metadata that happens to use a familiar key. Runbook titles, stored+reason/From/To text and nested values can contain execution details and are+redacted for monitoring-read callers. Fixed reasons derive only from admitted+boolean command success or the closed incident outcomes; missing or malformed+facts do not establish success or failure. Every execution-history projection+is explicitly marked redacted. Executor/session reads and canonical evidence+are unchanged; this adds no enrollment, token scope or action authority.++Normal-suite typed-fact, authenticated concurrent HTTP, contract and real MCP+consumer regressions cover content visibility and unchanged stored evidence.++### Coverage provider outcomes are not backup job resultsProvider evidence identifies the source of each scoped assessment: PBS/PVEdiff --git a/internal/api/agent_recent_changes.go b/internal/api/agent_recent_changes.goindex 1e97b05f1f..ea929dabea 100644--- a/internal/api/agent_recent_changes.go+++ b/internal/api/agent_recent_changes.go@@ -37,19 +37,6 @@ type AgentRecentChanges struct {GeneratedAt time.Time `json:"generatedAt"`}-// agentRecentChangeSafeMetadata is the metadata a monitoring-read token keeps-// on command and runbook changes. Everything else on those records (command-// text, output excerpts, runbook messages and caller-supplied details) can-// carry command payloads and is dropped unless the token has ai:execute.-var agentRecentChangeSafeMetadata = map[string]bool{- unified.MetadataAlertIdentifier: true,- unified.MetadataSuccess: true,- unified.MetadataOutcome: true,- unified.MetadataAutomatic: true,- unified.MetadataRunbookID: true,- "title": true,-}-// HandleRecentChanges serves `GET /api/agent/changes`: what Pulse observed// changing across the fleet, newest first, read from the existing resource// change store. It records nothing, so it adds no disk writes.@@ -172,29 +159,52 @@ func parseAgentRecentChangesQuery(r *http.Request, now time.Time) (agentRecentChreturn query, ""}+// redactAgentRecentChangeCommand projects execution history, not arbitrary+// stored metadata. A familiar key does not make its value safe: command details+// can supply runbook keys, nested objects, or free text under any key.func redactAgentRecentChangeCommand(entry AgentRecentChange) AgentRecentChange {switch entry.Kind {case unified.ChangeCommandExecuted, unified.ChangeRunbookExecuted:default:return entry}- safe := make(map[string]any, len(entry.Metadata))- redacted := false- for key, value := range entry.Metadata {- if agentRecentChangeSafeMetadata[key] {- safe[key] = value- continue- }- redacted = true++ safe := make(map[string]any)+ if id, ok := entry.Metadata[unified.MetadataAlertIdentifier].(string); ok {+ safe[unified.MetadataAlertIdentifier] = id}- entry.Metadata = safeif entry.Kind == unified.ChangeCommandExecuted {- // The stored reason embeds the command ("Command succeeded: <cmd>").- if prefix, _, found := strings.Cut(entry.Reason, ":"); found {- entry.Reason = prefix+ entry.Reason = "Command executed"+ if success, ok := entry.Metadata[unified.MetadataSuccess].(bool); ok {+ safe[unified.MetadataSuccess] = success+ entry.Reason = "Command failed"+ if success {+ entry.Reason = "Command succeeded"+ }+ }+ } else {+ entry.Reason = "Runbook executed"+ if id, ok := entry.Metadata[unified.MetadataRunbookID].(string); ok {+ safe[unified.MetadataRunbookID] = id+ }+ if automatic, ok := entry.Metadata[unified.MetadataAutomatic].(bool); ok {+ safe[unified.MetadataAutomatic] = automatic+ }+ // These are the incident memory's closed outcome values. Unknown or+ // malformed stored values stay undisclosed, never a guessed success.+ if outcome, ok := entry.Metadata[unified.MetadataOutcome].(string); ok {+ switch outcome {+ case "resolved", "partial", "failed", "unknown":+ safe[unified.MetadataOutcome] = outcome+ entry.Reason += " (" + outcome + ")"+ }}- redacted = true}- entry.CommandRedacted = redacted+ // The canonical builders do not use From/To for execution records. Do+ // not expose free-text legacy values or derive a reason from stored text.+ entry.From = ""+ entry.To = ""+ entry.Metadata = safe+ entry.CommandRedacted = truereturn entry}diff --git a/internal/api/agent_recent_changes_disclosure_test.go b/internal/api/agent_recent_changes_disclosure_test.gonew file mode 100644index 0000000000..7e1fa63748--- /dev/null+++ b/internal/api/agent_recent_changes_disclosure_test.go@@ -0,0 +1,196 @@+package api++import (+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "reflect"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++const recentChangePrivateText = "fixture-execution-detail-not-for-monitoring"++func TestAgentRecentChangesExecutionProjectionUsesTypedFacts(t *testing.T) {+ command := unified.BuildCommandExecutionChange("vm:101", "alert-1", "operator", recentChangePrivateText, true, recentChangePrivateText, map[string]any{+ "title": recentChangePrivateText,+ unified.MetadataOutcome: map[string]any{"output": recentChangePrivateText},+ unified.MetadataAutomatic: recentChangePrivateText,+ unified.MetadataRunbookID: []string{recentChangePrivateText},+ })+ runbook := unified.BuildRunbookExecutionChange("vm:101", "alert-1", "operator", "rb-1", recentChangePrivateText, "resolved", false, recentChangePrivateText, nil)+ cases := []struct {+ name string+ change unified.ResourceChange+ reason string+ metadata map[string]any+ }{+ {"command_builder", *command, "Command succeeded", map[string]any{unified.MetadataAlertIdentifier: "alert-1", unified.MetadataSuccess: true}},+ {"runbook_builder", *runbook, "Runbook executed (resolved)", map[string]any{unified.MetadataAlertIdentifier: "alert-1", unified.MetadataRunbookID: "rb-1", unified.MetadataOutcome: "resolved", unified.MetadataAutomatic: false}},+ {"failed_command_untrusted_reason", unified.ResourceChange{Kind: unified.ChangeCommandExecuted, Reason: recentChangePrivateText, Metadata: map[string]any{unified.MetadataSuccess: false}}, "Command failed", map[string]any{unified.MetadataSuccess: false}},+ {"missing_command_status", unified.ResourceChange{Kind: unified.ChangeCommandExecuted, Reason: recentChangePrivateText}, "Command executed", map[string]any{}},+ {"malformed_command_status", unified.ResourceChange{Kind: unified.ChangeCommandExecuted, Reason: recentChangePrivateText, From: recentChangePrivateText, To: recentChangePrivateText, Metadata: map[string]any{unified.MetadataSuccess: "true", unified.MetadataAlertIdentifier: map[string]any{"output": recentChangePrivateText}}}, "Command executed", map[string]any{}},+ {"malformed_runbook_metadata", unified.ResourceChange{Kind: unified.ChangeRunbookExecuted, Reason: recentChangePrivateText, From: recentChangePrivateText, To: recentChangePrivateText, Metadata: map[string]any{unified.MetadataAlertIdentifier: []string{recentChangePrivateText}, unified.MetadataRunbookID: map[string]any{"output": recentChangePrivateText}, unified.MetadataAutomatic: "false", unified.MetadataOutcome: recentChangePrivateText, "title": recentChangePrivateText, unified.MetadataSuccess: true}}, "Runbook executed", map[string]any{}},+ {"empty_runbook", unified.ResourceChange{Kind: unified.ChangeRunbookExecuted}, "Runbook executed", map[string]any{}},+ }+ for _, outcome := range []string{"partial", "failed", "unknown"} {+ cases = append(cases, struct {+ name string+ change unified.ResourceChange+ reason string+ metadata map[string]any+ }{outcome, unified.ResourceChange{Kind: unified.ChangeRunbookExecuted, Metadata: map[string]any{unified.MetadataOutcome: outcome, unified.MetadataAutomatic: true}}, "Runbook executed (" + outcome + ")", map[string]any{unified.MetadataOutcome: outcome, unified.MetadataAutomatic: true}})+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ original, err := json.Marshal(tc.change)+ if err != nil {+ t.Fatal(err)+ }+ entry := AgentRecentChange{ResourceChange: tc.change, ResourceName: "db-01", ResourceType: "vm"}+ got := redactAgentRecentChangeCommand(entry)+ if got.Reason != tc.reason || !reflect.DeepEqual(got.Metadata, tc.metadata) || !got.CommandRedacted || got.From != "" || got.To != "" {+ t.Fatalf("projection differs: %+v, want reason %q and metadata %+v", got, tc.reason, tc.metadata)+ }+ body, err := json.Marshal(got)+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(string(body), recentChangePrivateText) {+ t.Fatal("execution detail survived the projection")+ }+ if got.ResourceName != entry.ResourceName || got.ResourceType != entry.ResourceType {+ t.Fatal("resource attribution changed")+ }+ if !reflect.DeepEqual(got, redactAgentRecentChangeCommand(got)) {+ t.Fatal("projection is not idempotent")+ }+ got.Metadata["probe"] = true+ after, err := json.Marshal(tc.change)+ if err != nil || string(after) != string(original) {+ t.Fatal("projection mutated canonical evidence")+ }+ })+ }+}++func TestAgentRecentChangesNonExecutionEvidenceIsUnchanged(t *testing.T) {+ entry := AgentRecentChange{ResourceChange: unified.ResourceChange{Kind: unified.ChangeRestart, Reason: "uptime reset", From: "3600", To: "10", Metadata: map[string]any{"previousUptime": 3600}}, ResourceName: "db-01"}+ if got := redactAgentRecentChangeCommand(entry); !reflect.DeepEqual(got, entry) {+ t.Fatal("non-execution evidence changed")+ }+}++// Exercise the registered route, real token authentication, scope enforcement,+// persistent store and JSON consumer together. Concurrent readers must neither+// disclose details to monitoring nor redact the stored executor's evidence.+func TestAgentRecentChangesHTTPPreservesAuthorityAndCanonicalEvidence(t *testing.T) {+ t.Setenv("PULSE_AUTH_BYPASS", "false")+ const readToken = "history-read-fixture-token-123.12345678"+ const execToken = "history-exec-fixture-token-123.12345678"+ const otherToken = "history-other-fixture-token-123.12345678"+ cfg := newTestConfigWithTokens(t,+ newTokenRecord(t, readToken, []string{config.ScopeMonitoringRead}, nil),+ newTokenRecord(t, execToken, []string{config.ScopeMonitoringRead, config.ScopeAIExecute}, nil),+ newTokenRecord(t, otherToken, []string{config.ScopeSettingsRead}, nil),+ )+ cfg.AuthUser = "admin"+ cfg.AuthPass = "fixture-nonempty-hash"+ router := NewRouter(cfg, nil, nil, nil, nil, "test")+ t.Cleanup(func() { _ = router.resourceHandlers.CloseStores() })+ store, err := router.resourceHandlers.getStore("default")+ if err != nil {+ t.Fatal(err)+ }+ changes := []unified.ResourceChange{+ *unified.BuildCommandExecutionChange("vm:101", "alert-1", "operator", recentChangePrivateText, false, recentChangePrivateText, map[string]any{"title": recentChangePrivateText, unified.MetadataOutcome: map[string]any{"output": recentChangePrivateText}}),+ *unified.BuildRunbookExecutionChange("vm:101", "alert-1", "operator", "rb-1", recentChangePrivateText, "partial", true, recentChangePrivateText, nil),+ }+ for _, change := range changes {+ if err := store.RecordChange(change); err != nil {+ t.Fatal(err)+ }+ }+ before, err := store.GetRecentChangesFiltered("", time.Time{}, 50, unified.ResourceChangeFilters{})+ if err != nil {+ t.Fatal(err)+ }+ original, err := json.Marshal(before)+ if err != nil {+ t.Fatal(err)+ }+ server := httptest.NewServer(router.Handler())+ defer server.Close()+ read := func(token string, want int, private bool) {+ t.Helper()+ req, err := http.NewRequest(http.MethodGet, server.URL+agentcapabilities.RecentChangesCapabilityPath, nil)+ if err != nil {+ t.Error(err)+ return+ }+ if token != "" {+ req.Header.Set("Authorization", "Bearer "+token)+ }+ resp, err := server.Client().Do(req)+ if err != nil {+ t.Error(err)+ return+ }+ defer resp.Body.Close()+ body, err := io.ReadAll(resp.Body)+ if err != nil {+ t.Error(err)+ return+ }+ if resp.StatusCode != want {+ t.Errorf("status %d, want %d: %s", resp.StatusCode, want, body)+ return+ }+ if want != http.StatusOK {+ return+ }+ var got AgentRecentChanges+ if err := json.Unmarshal(body, &got); err != nil {+ t.Error(err)+ return+ }+ if got.Count != 2 || len(got.Changes) != 2 || got.Truncated {+ t.Errorf("lost history envelope: %+v", got)+ }+ if strings.Contains(string(body), recentChangePrivateText) != private {+ t.Error("execution detail visibility differs from token authority")+ }+ for _, change := range got.Changes {+ if change.CommandRedacted == private {+ t.Error("redaction marker differs from token authority")+ }+ if change.Metadata[unified.MetadataAlertIdentifier] != "alert-1" {+ t.Error("lost safe identity")+ }+ }+ }+ read("", http.StatusUnauthorized, false)+ read(otherToken, http.StatusForbidden, false)+ var wg sync.WaitGroup+ for i := 0; i < 6; i++ {+ wg.Add(2)+ go func() { defer wg.Done(); read(readToken, http.StatusOK, false) }()+ go func() { defer wg.Done(); read(execToken, http.StatusOK, true) }()+ }+ wg.Wait()+ after, err := store.GetRecentChangesFiltered("", time.Time{}, 50, unified.ResourceChangeFilters{})+ if err != nil {+ t.Fatal(err)+ }+ stored, err := json.Marshal(after)+ if err != nil || string(stored) != string(original) {+ t.Fatal("HTTP reads rewrote canonical history")+ }+}diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex d30dce8f93..6457fc9439 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -28805,3 +28805,15 @@ func TestContract_AgentChangeEventsStayInsideTheirOrganization(t *testing.T) {t.Fatal("timed out waiting for the stream")}}++// Runbook titles and reasons are execution-authored text, not safe monitoring+// metadata. The history envelope and typed outcome remain useful without them.+func TestContract_AgentRecentChangesRunbookProjection(t *testing.T) {+ change := unifiedresources.BuildRunbookExecutionChange("vm:101", "alert-1", "operator", "rb-1", "fixture-private-title", "partial", false, "fixture-private-output", nil)+ projected := redactAgentRecentChangeCommand(AgentRecentChange{ResourceChange: *change})+ got, err := json.Marshal(map[string]any{"reason": projected.Reason, "metadata": projected.Metadata, "commandRedacted": projected.CommandRedacted})+ if err != nil {+ t.Fatal(err)+ }+ assertJSONSnapshot(t, got, `{"reason":"Runbook executed (partial)","metadata":{"alert_identifier":"alert-1","runbook_id":"rb-1","outcome":"partial","automatic":false},"commandRedacted":true}`)+}