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.

Let agents read what changed across the fleet

rcourtman32d8fd308e7e
diff --git a/cmd/pulse-mcp/README.md b/cmd/pulse-mcp/README.md
index 034c1010a0..d9c6f36064 100644
--- a/cmd/pulse-mcp/README.md
+++ b/cmd/pulse-mcp/README.md
@@ -260,6 +260,7 @@ the live set.
- `get_resource_context` (Get resource context, `GET /api/agent/resource-context/{resourceId}`, scope `monitoring:read`, mode `read`, approval `scope_only`): Return the situated picture of a resource — identity, operator-set state with maintenance-window-active flag, active findings, pending approvals scoped to this resource, recent actions including refused dispatches. Command fields are redacted for monitoring-read API tokens unless the token also has ai:execute.
- `list_resource_capabilities` (List resource capabilities, `GET /api/agent/resource-capabilities/{resourceId}`, scope `monitoring:read`, mode `read`, approval `scope_only`): Return the structured governed capabilities a resource advertises (name, type, approval level, platform, and full parameter schemas). Companion to get_resource_context, which renders capabilities as count-limited prose; this is the structured surface an agent reads before calling plan_action so it can populate capabilityName and params without guessing. A resource with no advertised capabilities returns an empty array.
- `get_fleet_context` (Get fleet context, `GET /api/agent/fleet-context`, scope `monitoring:read`, mode `read`, approval `scope_only`): Return a thin per-resource triage rollup across every resource visible to the org — identity, operator flags (intentionallyOffline, neverAutoRemediate, maintenanceWindowActive), per-severity finding counts (total/critical/warning/info), and pending-approval count. One read for 'where do I focus?'; follow up via get_resource_context for depth. Optional additive filters (hasFindings, severity, technology, resourceType) narrow the result to a relevant subset so agents triaging a large fleet do not receive or page through healthy resources.
+- `list_recent_changes` (List recent changes, `GET /api/agent/changes`, scope `monitoring:read`, mode `read`, approval `scope_only`): Return what Pulse observed changing across the fleet, newest first: state transitions, restarts, configuration and relationship changes, alerts fired, acknowledged, snoozed and resolved, and commands or runbooks run. One read for 'what happened since last night?'; optional filters (since, before, resourceId, kind, sourceType) narrow it. Only changes Pulse observed are listed, so a gap is not proof that nothing happened. Results are capped, and truncated says when more matched. Command text, output and runbook messages are redacted for monitoring-read API tokens unless the token also has ai:execute.
- `get_patrol_control_status` (Get Patrol work status, `GET /api/agent/patrol-control/status`, scope `monitoring:read`, mode `read`, approval `scope_only`): Return the current content-safe Patrol work status: Patrol issue evidence, pending approvals, governed decisions/actions, verified outcomes, Patrol control outcome evidence, compatibility aliases, and optional MCP readiness. The payload is count-only and deliberately omits finding ids, action ids, prompts, commands, resource names, and output.
**Operator state (per-resource intent):**
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 4529058761..99244550fd 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -2742,6 +2742,13 @@ use their bounded facts, provenance, freshness, and explicit redaction metadata
to understand a resource, but those sections must not be expanded into
provider-local config, raw discovery command output, environment values,
secret-like metadata, install-token scope, or command authority.
+The fleet change timeline at `/api/agent/changes` (`list_recent_changes`) is
+the same read-only boundary. Lifecycle consumers, MCP adapters, and external
+agents may read what changed across the fleet, but `command_executed` and
+`runbook_executed` records reach a monitoring-read token with
+`commandRedacted:true`, the command text, output, and caller details dropped,
+and a command's reason cut to its status. A change record is history, never command
+disclosure, install-token scope, or execution authority.
Agent-facing provisioning capabilities declared by
`/api/agent/capabilities` are also API-owned projections over the canonical
node lifecycle and discovery APIs. Lifecycle and infrastructure onboarding
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 73bcfa0661..0deb2bad8a 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -2073,6 +2073,15 @@ layer forwards non-path GET arguments as URL query parameters so the manifest
contract, not a per-capability adapter, owns query-string transport. The
`resources/list` adapter calls fleet-context with no filters and continues to
receive the full fleet.
+`list_recent_changes` is the manifest-owned change-history read for external
+agents (`GET /api/agent/changes`, `monitoring:read`). It projects the existing
+observed resource change store with since/before/resourceId/kind/sourceType
+filters and a capped limit, and counts as fleet-context external-agent activity
+rather than a new telemetry activity. It must stay read-only over observed
+changes: it does not reconstruct events Pulse did not see, and command, output
+and runbook message content is redacted for tokens without `ai:execute`. Integer
+filters reach the route because the shared projection forwards integral JSON
+numbers as query parameters.
than in `cmd/pulse-mcp` or an MCP-only inventory registry. They must enter
through `ManifestSurfaceResourceCapabilities`,
`ListMCPManifestSurfaceResourcesHTTP`, and
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index e0cfabff18..a0c8b68ab1 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -6733,6 +6733,35 @@ them so agents discover the filters through the capability surface,
and non-path GET arguments are forwarded as query parameters by the
shared projection layer rather than a per-capability adapter.
+`/api/agent/changes` (`list_recent_changes`, scope `monitoring:read`)
+is the agent-consumable "what changed?" read across the fleet. It
+reads the existing `unified.ResourceStore` change history through
+`GetRecentChangesFiltered` and `CountRecentChangesFiltered` and
+records nothing, so it adds no stored data. Optional query
+parameters: `since` (inclusive RFC 3339, default 24 hours ago),
+`before` (exclusive RFC 3339), `resourceId` (canonical id; includes
+related resources, as the per-resource timeline does), `kind` and
+`sourceType` (comma-separated, parsed by the shared
+`ParseResourceChangeFilters` contract), and `limit` (default 50,
+capped at 200). Malformed timestamps, kinds, origins, limits or an
+empty window return 400 with a reason, because an agent reading the
+wrong window silently would answer the wrong question. Changes are
+newest first and always an array; `count` is the total matching and
+`truncated` says more matched than were returned. There is no
+timestamp cursor, because one registry rebuild records many changes
+at the same instant; agents narrow the window, resource or kind
+instead. Each change carries the canonical record plus the
+resource's current `resourceName` and `resourceType` when the
+registry still knows it, so history for a removed resource stays
+readable. 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
+projection layer forwards integral JSON numbers as integer query
+parameters so manifest integer filters such as `limit` reach the
+route; fractional or out-of-range numbers are dropped like objects.
+
`/api/agent/resource-capabilities/{id}` is the agent-consumable
structured capability surface for a single resource: the governed
capabilities it advertises (name, type, approval level, platform, and
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 56791f981f..f25f6714e2 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -4703,6 +4703,15 @@ store and the approval store rehydrate on startup, the fleet view
recovers the same situated picture without any fleet-specific
rehydration step.
+The fleet change timeline at `/api/agent/changes` (`list_recent_changes`)
+introduces no new persistence either. It reads the existing durable
+`resource_changes` table through the store's filtered change read, bounded by
+that table's 30-day retention, and consults the registry only to attach
+resource names. Changes for a resource the registry no longer knows stay
+readable without a name, so the timeline's recovery posture is exactly the
+`resource_changes` table's: whatever survives a restart or restore is what
+agents read, with no timeline-specific rehydration or recovery artifact.
+
The Patrol-control status endpoint at
`/api/agent/patrol-control/status` introduces no new persistence. The legacy
`/api/agent/operations-loop/status` URL remains a compatibility alias. It reads the
diff --git a/internal/agentcapabilities/manifest.go b/internal/agentcapabilities/manifest.go
index 181162c996..7f4dbc3ecc 100644
--- a/internal/agentcapabilities/manifest.go
+++ b/internal/agentcapabilities/manifest.go
@@ -2,7 +2,10 @@ package agentcapabilities
import (
"encoding/json"
+ "fmt"
"net/http"
+ "strings"
+ "time"
"github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
@@ -55,6 +58,56 @@ func fleetContextInputSchema() json.RawMessage {
})
}
+// RecentChangeKinds lists the observed change kinds list_recent_changes
+// accepts in its kind filter. The API test parses each one through the shared
+// resource-change filter contract so this list cannot drift from the store.
+var RecentChangeKinds = []string{
+ "state_transition", "restart", "config_update", "relationship_change",
+ "capability_change", "metric_anomaly", "activity",
+ "alert_fired", "alert_acknowledged", "alert_unacknowledged",
+ "alert_snoozed", "alert_unsnoozed", "alert_resolved",
+ "command_executed", "runbook_executed",
+}
+
+const (
+ // RecentChangesDefaultWindow is the lookback applied when since is omitted.
+ RecentChangesDefaultWindow = 24 * time.Hour
+ // RecentChangesDefaultLimit and RecentChangesMaxLimit bound one read so an
+ // agent cannot pull a month of history into a single response.
+ RecentChangesDefaultLimit = 50
+ RecentChangesMaxLimit = 200
+)
+
+// recentChangesInputSchema declares the optional filters for
+// list_recent_changes, forwarded as URL query parameters for the GET.
+func recentChangesInputSchema() json.RawMessage {
+ return agentObjectInputSchema(nil, map[string]any{
+ "since": dateTimeOption("Inclusive RFC 3339 start of the window. Defaults to 24 hours ago. Pulse keeps 30 days of change history."),
+ "before": dateTimeOption("Exclusive RFC 3339 end of the window. Omit for no upper bound, which also includes provider events stamped ahead of the Pulse clock."),
+ ResourceIDArgumentName: stringOption("Canonical resource id from get_fleet_context. Narrows the result to that resource and its related resources. History stays readable after the resource is gone."),
+ "kind": stringOption("Comma-separated change kinds: " + strings.Join(RecentChangeKinds, ", ") + "."),
+ "sourceType": stringOption("Comma-separated origins: platform_event, pulse_diff, heuristic, user_action, agent_action."),
+ "limit": map[string]any{
+ "type": "integer",
+ "minimum": 1,
+ "maximum": RecentChangesMaxLimit,
+ "description": fmt.Sprintf("Maximum changes to return, newest first. Defaults to %d; values above %d are capped.", RecentChangesDefaultLimit, RecentChangesMaxLimit),
+ },
+ })
+}
+
+func recentChangesOutputSchema() json.RawMessage {
+ return agentObjectOutputSchema([]string{"changes", "count", "truncated", "since", "limit", "generatedAt"}, map[string]any{
+ "changes": objectArrayOption("Observed changes, newest first. Each carries the canonical resourceId plus resourceName and resourceType when the resource is still known, the kind, from/to state, origin, confidence, actor, reason and metadata."),
+ "count": integerOption("Total changes matching the window and filters, which can exceed the number returned."),
+ "truncated": booleanOption("True when count exceeds the returned changes. Narrow the window, resource or kind instead of paging."),
+ "since": dateTimeOption("Effective inclusive window start."),
+ "before": dateTimeOption("Effective exclusive window end, when one was supplied."),
+ "limit": integerOption("Effective result limit after defaulting and capping."),
+ "generatedAt": dateTimeOption("Server timestamp for this read."),
+ })
+}
+
func operationsLoopStatusOutputSchema() json.RawMessage {
return agentObjectOutputSchema([]string{"nextAction", "progressLabel", "steps", "patrolEvidenceCount", "patrolIssueEvidenceCount", "activeFindingCount", "pendingApprovalCount", "governedActionCount", "approvedDecisionCount", "rejectedDecisionCount", "verifiedOutcomeCount", "operationsLoopStarterCount", "assistantOperationsLoopStarterCount", "patrolOperationsLoopStarterCount", "patrolControlOperationsLoopStarterCount", "patrolControlCompletedOperationsLoopCount", "patrolControlResolvedOperationsLoopCount", "patrolControlValueState", "patrolAutonomyOperationsLoopStarterCount", "patrolAutonomyCompletedOperationsLoopCount", "patrolAutonomyResolvedOperationsLoopCount", "patrolAutonomyValueState", "proActivationOperationsLoopStarterCount", "proActivationCompletedOperationsLoopCount", "proActivationResolvedOperationsLoopCount", "proActivationValueProofState", "mcpOperationsLoopStarterCount", "externalAgentReady", "windowStart", "generatedAt"}, map[string]any{
"nextAction": stringEnumOption([]string{"run_patrol", "review_findings", "open_assistant", "review_approvals", "open_mcp", "complete"}, "Next recommended Patrol work action an agent or UI should take."),
@@ -825,6 +878,20 @@ var canonicalManifest = Manifest{
InputSchema: fleetContextInputSchema(),
OutputSchema: fleetContextOutputSchema(),
},
+ {
+ Name: ListRecentChangesCapabilityName,
+ Title: "List recent changes",
+ Description: "Return what Pulse observed changing across the fleet, newest first: state transitions, restarts, configuration and relationship changes, alerts fired, acknowledged, snoozed and resolved, and commands or runbooks run. One read for 'what happened since last night?'; optional filters (since, before, resourceId, kind, sourceType) narrow it. Only changes Pulse observed are listed, so a gap is not proof that nothing happened. Results are capped, and truncated says when more matched. Command text, output and runbook messages are redacted for monitoring-read API tokens unless the token also has ai:execute.",
+ Category: "context",
+ Method: http.MethodGet,
+ Path: RecentChangesCapabilityPath,
+ Scope: agentCapabilityScopeMonitoringRead,
+ ActionMode: agentCapabilityActionModeRead,
+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,
+ ResponseShape: "AgentRecentChanges",
+ InputSchema: recentChangesInputSchema(),
+ OutputSchema: recentChangesOutputSchema(),
+ },
{
Name: OperationsLoopStatusCapabilityName,
Title: "Get Patrol work status",
@@ -1163,6 +1230,7 @@ func canonicalPulseMCPSurfaceToolNames() []string {
ResourceContextCapabilityName,
ListResourceCapabilitiesCapabilityName,
FleetContextCapabilityName,
+ ListRecentChangesCapabilityName,
OperationsLoopStatusCapabilityName,
ListNodesCapabilityName,
AddNodeCapabilityName,
diff --git a/internal/agentcapabilities/projection.go b/internal/agentcapabilities/projection.go
index 96e6839610..424266d684 100644
--- a/internal/agentcapabilities/projection.go
+++ b/internal/agentcapabilities/projection.go
@@ -3,6 +3,7 @@ package agentcapabilities
import (
"encoding/json"
"fmt"
+ "math"
"net/http"
"net/url"
"regexp"
@@ -34,8 +35,14 @@ const (
// ResourceIDArgumentName is the shared path/body argument for canonical
// resource identity in Pulse Intelligence context and action tools.
ResourceIDArgumentName = "resourceId"
+ // ListRecentChangesCapabilityName is the manifest-owned read of observed
+ // resource changes across the fleet: the "what changed?" companion to the
+ // fleet triage and per-resource context reads.
+ ListRecentChangesCapabilityName = "list_recent_changes"
// FleetContextCapabilityPath is the manifest-owned fleet triage route.
FleetContextCapabilityPath = "/api/agent/fleet-context"
+ // RecentChangesCapabilityPath is the manifest-owned fleet change route.
+ RecentChangesCapabilityPath = "/api/agent/changes"
// ResourceContextCapabilityPath is the manifest-owned per-resource context route.
ResourceContextCapabilityPath = "/api/agent/resource-context/{" + ResourceIDArgumentName + "}"
// ListResourceCapabilitiesCapabilityPath is the manifest-owned per-resource
@@ -555,6 +562,15 @@ func ProjectCapabilityCall(cap Capability, args map[string]any) (ProjectedCall,
// JSON-RPC decoding just like string filters. Do not stringify
// arbitrary values such as objects, arrays or null.
query.Set(k, strconv.FormatBool(value))
+ case float64:
+ // JSON-RPC decodes every number as float64. Integer filters
+ // such as limit forward as plain integers; a fractional value
+ // is not a valid integer filter and is dropped like an object.
+ if value == math.Trunc(value) && math.Abs(value) <= 1<<53 {
+ query.Set(k, strconv.FormatInt(int64(value), 10))
+ }
+ case int:
+ query.Set(k, strconv.Itoa(value))
}
}
if len(query) > 0 {
diff --git a/internal/agentcapabilities/projection_test.go b/internal/agentcapabilities/projection_test.go
index c56cd5c73f..429f7d7fbc 100644
--- a/internal/agentcapabilities/projection_test.go
+++ b/internal/agentcapabilities/projection_test.go
@@ -824,7 +824,8 @@ func TestProjectCapabilityCallGETDELETEPreservesTypedFilters(t *testing.T) {
{"legacy_string", map[string]any{"hasFindings": "true"}, "hasFindings=true"},
{"mixed", map[string]any{"hasFindings": true, "technology": "qemu & lxc"}, "hasFindings=true&technology=qemu+%26+lxc"},
{"empty_string", map[string]any{"technology": ""}, "technology="},
- {"unsupported", map[string]any{"null": nil, "number": float64(1), "integer": 1, "array": []any{true}, "object": map[string]any{"x": true}}, ""},
+ {"integers", map[string]any{"limit": float64(25), "count": 3}, "count=3&limit=25"},
+ {"unsupported", map[string]any{"null": nil, "fraction": 1.5, "huge": 1e300, "array": []any{true}, "object": map[string]any{"x": true}}, ""},
{"private_boolean", map[string]any{ApprovalArgumentKey: true}, ""},
{"omitted", nil, ""},
}
diff --git a/internal/api/agent_activity_telemetry.go b/internal/api/agent_activity_telemetry.go
index a3d0ea099f..c5638152a6 100644
--- a/internal/api/agent_activity_telemetry.go
+++ b/internal/api/agent_activity_telemetry.go
@@ -46,7 +46,8 @@ func externalAgentCapabilityActivity(capabilityName string) (string, string, boo
case agentcapabilities.ResourceContextCapabilityName,
agentcapabilities.ListResourceCapabilitiesCapabilityName:
activity = config.ExternalAgentActivityResourceContext
- case agentcapabilities.FleetContextCapabilityName:
+ case agentcapabilities.FleetContextCapabilityName,
+ agentcapabilities.ListRecentChangesCapabilityName:
activity = config.ExternalAgentActivityFleetContext
case agentcapabilities.OperationsLoopStatusCapabilityName:
activity = config.ExternalAgentActivityFleetContext
diff --git a/internal/api/agent_capabilities_test.go b/internal/api/agent_capabilities_test.go
index 3511c4e0ed..f316ca48c3 100644
--- a/internal/api/agent_capabilities_test.go
+++ b/internal/api/agent_capabilities_test.go
@@ -205,6 +205,7 @@ func TestAgentCapabilitiesManifest_ScopesMatchAPIAuthConstants(t *testing.T) {
agentcapabilities.ResourceContextCapabilityName: config.ScopeMonitoringRead,
agentcapabilities.ListResourceCapabilitiesCapabilityName: config.ScopeMonitoringRead,
agentcapabilities.FleetContextCapabilityName: config.ScopeMonitoringRead,
+ agentcapabilities.ListRecentChangesCapabilityName: config.ScopeMonitoringRead,
agentcapabilities.OperationsLoopStatusCapabilityName: config.ScopeMonitoringRead,
"list_nodes": config.ScopeSettingsRead,
"add_node": config.ScopeSettingsWrite,
diff --git a/internal/api/agent_recent_changes.go b/internal/api/agent_recent_changes.go
new file mode 100644
index 0000000000..1e97b05f1f
--- /dev/null
+++ b/internal/api/agent_recent_changes.go
@@ -0,0 +1,200 @@
+package api
+
+import (
+ "encoding/json"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+// AgentRecentChange is one observed resource change as an agent reads it:
+// the canonical change record plus the resource's current name and type,
+// which the store does not keep. ResourceName and ResourceType are empty when
+// the resource is no longer known; the history itself stays readable.
+type AgentRecentChange struct {
+ unified.ResourceChange
+ ResourceName string `json:"resourceName,omitempty"`
+ ResourceType string `json:"resourceType,omitempty"`
+ CommandRedacted bool `json:"commandRedacted,omitempty"`
+}
+
+// AgentRecentChanges is the response for GET /api/agent/changes. Changes is
+// always an array (never null). Count is the total matching the window and
+// filters; Truncated says the agent should narrow the read rather than page,
+// because one registry rebuild records many changes at the same instant and a
+// timestamp cursor would skip some of them.
+type AgentRecentChanges struct {
+ Changes []AgentRecentChange `json:"changes"`
+ Count int `json:"count"`
+ Truncated bool `json:"truncated"`
+ Since time.Time `json:"since"`
+ Before *time.Time `json:"before,omitempty"`
+ Limit int `json:"limit"`
+ 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.
+func (h *AgentContextHandler) HandleRecentChanges(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ if h.resources == nil {
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ now := time.Now().UTC()
+ query, parseError := parseAgentRecentChangesQuery(r, now)
+ if parseError != "" {
+ http.Error(w, parseError, http.StatusBadRequest)
+ return
+ }
+
+ orgID := GetOrgID(r.Context())
+ store, err := h.resources.getStore(orgID)
+ if err != nil {
+ http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
+ return
+ }
+ changes, err := store.GetRecentChangesFiltered(query.resourceID, query.since, query.limit, query.filters)
+ if err != nil {
+ http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
+ return
+ }
+ count, err := store.CountRecentChangesFiltered(query.resourceID, query.since, query.filters)
+ if err != nil {
+ http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
+ return
+ }
+
+ // Names are a convenience; a registry failure must not hide the history.
+ registry, _ := h.resources.buildRegistry(orgID)
+ canReadCommands := requestCanReadAgentCommandPayloads(r)
+ out := AgentRecentChanges{
+ Changes: make([]AgentRecentChange, 0, len(changes)),
+ Count: count,
+ Truncated: count > len(changes),
+ Since: query.since,
+ Before: query.filters.ObservedBefore,
+ Limit: query.limit,
+ GeneratedAt: now,
+ }
+ for _, change := range changes {
+ entry := AgentRecentChange{ResourceChange: change}
+ if registry != nil {
+ if resource, ok := registry.Get(unified.CanonicalResourceID(change.ResourceID)); ok && resource != nil {
+ entry.ResourceName = resource.Name
+ entry.ResourceType = string(resource.Type)
+ }
+ }
+ if !canReadCommands {
+ entry = redactAgentRecentChangeCommand(entry)
+ }
+ out.Changes = append(out.Changes, entry)
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(out)
+}
+
+type agentRecentChangesQuery struct {
+ since time.Time
+ resourceID string
+ limit int
+ filters unified.ResourceChangeFilters
+}
+
+// parseAgentRecentChangesQuery reads the list_recent_changes filters. Unlike
+// fleet-context, malformed values are a 400 with a reason: an agent that sent
+// a bad timestamp or kind should correct it, not silently read the wrong
+// window. An oversized limit is capped rather than refused.
+func parseAgentRecentChangesQuery(r *http.Request, now time.Time) (agentRecentChangesQuery, string) {
+ q := r.URL.Query()
+ query := agentRecentChangesQuery{
+ since: now.Add(-agentcapabilities.RecentChangesDefaultWindow),
+ limit: agentcapabilities.RecentChangesDefaultLimit,
+ }
+ if raw := strings.TrimSpace(q.Get("since")); raw != "" {
+ parsed, err := time.Parse(time.RFC3339, raw)
+ if err != nil {
+ return query, "Invalid since value: use an RFC 3339 timestamp"
+ }
+ query.since = parsed.UTC()
+ }
+ if raw := strings.TrimSpace(q.Get("limit")); raw != "" {
+ parsed, err := strconv.Atoi(raw)
+ if err != nil || parsed <= 0 {
+ return query, "Invalid limit value: use a positive integer"
+ }
+ query.limit = min(parsed, agentcapabilities.RecentChangesMaxLimit)
+ }
+
+ filters, err := unified.ParseResourceChangeFilters(q["kind"], q["sourceType"], nil)
+ if err != nil {
+ return query, err.Error()
+ }
+ if raw := strings.TrimSpace(q.Get("before")); raw != "" {
+ parsed, err := time.Parse(time.RFC3339, raw)
+ if err != nil {
+ return query, "Invalid before value: use an RFC 3339 timestamp"
+ }
+ before := parsed.UTC()
+ if !before.After(query.since) {
+ return query, "Invalid window: before must be later than since"
+ }
+ filters.ObservedBefore = &before
+ }
+ if raw := strings.TrimSpace(q.Get(agentcapabilities.ResourceIDArgumentName)); raw != "" {
+ query.resourceID = unified.CanonicalResourceID(raw)
+ filters.IncludeRelated = true
+ }
+ query.filters = filters
+ return query, ""
+}
+
+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
+ }
+ entry.Metadata = safe
+ if entry.Kind == unified.ChangeCommandExecuted {
+ // The stored reason embeds the command ("Command succeeded: <cmd>").
+ if prefix, _, found := strings.Cut(entry.Reason, ":"); found {
+ entry.Reason = prefix
+ }
+ redacted = true
+ }
+ entry.CommandRedacted = redacted
+ return entry
+}
diff --git a/internal/api/agent_recent_changes_test.go b/internal/api/agent_recent_changes_test.go
new file mode 100644
index 0000000000..5951cab1d3
--- /dev/null
+++ b/internal/api/agent_recent_changes_test.go
@@ -0,0 +1,204 @@
+package api
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "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"
+)
+
+func recentChangesFixture(t *testing.T, resources []unified.Resource, changes []unified.ResourceChange) *AgentContextHandler {
+ t.Helper()
+ h, _, _ := fleetFixtureHandlers(t, resources)
+ req := httptest.NewRequest(http.MethodGet, agentcapabilities.RecentChangesCapabilityPath, nil)
+ store, err := h.resources.getStore(GetOrgID(req.Context()))
+ if err != nil {
+ t.Fatalf("getStore: %v", err)
+ }
+ for _, change := range changes {
+ if err := store.RecordChange(change); err != nil {
+ t.Fatalf("RecordChange(%s): %v", change.ID, err)
+ }
+ }
+ return h
+}
+
+func recentChange(id, resourceID string, kind unified.ChangeKind, observedAt time.Time) unified.ResourceChange {
+ return unified.ResourceChange{
+ ID: id,
+ ObservedAt: observedAt,
+ ResourceID: resourceID,
+ Kind: kind,
+ SourceType: unified.SourcePulseDiff,
+ Confidence: unified.ConfidenceHigh,
+ }
+}
+
+func getRecentChanges(t *testing.T, h *AgentContextHandler, rawQuery string, token *config.APITokenRecord) (*httptest.ResponseRecorder, AgentRecentChanges) {
+ t.Helper()
+ target := agentcapabilities.RecentChangesCapabilityPath
+ if rawQuery != "" {
+ target += "?" + rawQuery
+ }
+ req := httptest.NewRequest(http.MethodGet, target, nil)
+ if token != nil {
+ attachAPITokenRecord(req, token)
+ }
+ rec := httptest.NewRecorder()
+ h.HandleRecentChanges(rec, req)
+ var out AgentRecentChanges
+ if rec.Code == http.StatusOK {
+ if err := json.NewDecoder(rec.Body).Decode(&out); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ }
+ return rec, out
+}
+
+func TestHandleAgentRecentChanges_DefaultWindowNamesAndOrder(t *testing.T) {
+ now := time.Now().UTC()
+ h := recentChangesFixture(t,
+ []unified.Resource{{ID: "vm:101", Type: "vm", Name: "db-01"}},
+ []unified.ResourceChange{
+ recentChange("old", "vm:101", unified.ChangeRestart, now.Add(-30*time.Hour)),
+ recentChange("earlier", "vm:101", unified.ChangeStateTransition, now.Add(-2*time.Hour)),
+ recentChange("latest", "vm:101", unified.ChangeRestart, now.Add(-time.Hour)),
+ recentChange("gone", "vm:999", unified.ChangeStateTransition, now.Add(-90*time.Minute)),
+ })
+
+ rec, out := getRecentChanges(t, h, "", nil)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String())
+ }
+ ids := make([]string, 0, len(out.Changes))
+ for _, change := range out.Changes {
+ ids = append(ids, change.ID)
+ }
+ if got := strings.Join(ids, ","); got != "latest,gone,earlier" {
+ t.Fatalf("changes = %s; want newest first inside the default 24h window", got)
+ }
+ if out.Count != 3 || out.Truncated || out.Limit != agentcapabilities.RecentChangesDefaultLimit {
+ t.Fatalf("count=%d truncated=%v limit=%d", out.Count, out.Truncated, out.Limit)
+ }
+ if out.Changes[0].ResourceName != "db-01" || out.Changes[0].ResourceType != "vm" {
+ t.Fatalf("known resource not named: %+v", out.Changes[0])
+ }
+ if out.Changes[1].ResourceName != "" {
+ t.Fatalf("history for a resource no longer known must stay readable without a name: %+v", out.Changes[1])
+ }
+}
+
+func TestHandleAgentRecentChanges_FiltersWindowResourceAndKind(t *testing.T) {
+ now := time.Now().UTC().Truncate(time.Second)
+ h := recentChangesFixture(t,
+ []unified.Resource{{ID: "vm:101", Type: "vm", Name: "db-01"}, {ID: "vm:102", Type: "vm", Name: "web-01"}},
+ []unified.ResourceChange{
+ recentChange("a", "vm:101", unified.ChangeRestart, now.Add(-5*time.Hour)),
+ recentChange("b", "vm:101", unified.ChangeAlertFired, now.Add(-4*time.Hour)),
+ recentChange("c", "vm:102", unified.ChangeRestart, now.Add(-3*time.Hour)),
+ recentChange("d", "vm:101", unified.ChangeRestart, now.Add(-time.Hour)),
+ })
+
+ since := now.Add(-6 * time.Hour).Format(time.RFC3339)
+ before := now.Add(-2 * time.Hour).Format(time.RFC3339)
+ rec, out := getRecentChanges(t, h, "since="+since+"&before="+before+"&resourceId=vm:101&kind=restart", nil)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String())
+ }
+ if len(out.Changes) != 1 || out.Changes[0].ID != "a" || out.Count != 1 {
+ t.Fatalf("filtered changes = %+v (count %d); want only a", out.Changes, out.Count)
+ }
+ if out.Before == nil || !out.Before.Equal(now.Add(-2*time.Hour)) {
+ t.Fatalf("effective before = %v", out.Before)
+ }
+
+ _, out = getRecentChanges(t, h, "since="+since+"&kind=restart,alert_fired", nil)
+ if out.Count != 4 {
+ t.Fatalf("comma-separated kinds count = %d; want 4", out.Count)
+ }
+}
+
+func TestHandleAgentRecentChanges_CapsLimitAndReportsTruncation(t *testing.T) {
+ now := time.Now().UTC()
+ h := recentChangesFixture(t, nil, []unified.ResourceChange{
+ recentChange("a", "vm:101", unified.ChangeRestart, now.Add(-3*time.Hour)),
+ recentChange("b", "vm:101", unified.ChangeRestart, now.Add(-2*time.Hour)),
+ recentChange("c", "vm:101", unified.ChangeRestart, now.Add(-time.Hour)),
+ })
+
+ _, out := getRecentChanges(t, h, "limit=2", nil)
+ if len(out.Changes) != 2 || out.Count != 3 || !out.Truncated {
+ t.Fatalf("limit=2: len=%d count=%d truncated=%v", len(out.Changes), out.Count, out.Truncated)
+ }
+ _, out = getRecentChanges(t, h, "limit=100000", nil)
+ if out.Limit != agentcapabilities.RecentChangesMaxLimit || out.Truncated {
+ t.Fatalf("oversized limit: effective=%d truncated=%v", out.Limit, out.Truncated)
+ }
+}
+
+func TestHandleAgentRecentChanges_RejectsMalformedFilters(t *testing.T) {
+ h := recentChangesFixture(t, nil, nil)
+ for _, query := range []string{
+ "since=yesterday",
+ "before=soon",
+ "limit=0",
+ "limit=ten",
+ "kind=reboot",
+ "sourceType=rumour",
+ "since=2026-10-28T10:00:00Z&before=2026-10-28T09:00:00Z",
+ } {
+ rec, _ := getRecentChanges(t, h, query, nil)
+ if rec.Code != http.StatusBadRequest {
+ t.Errorf("%s: status = %d; want 400", query, rec.Code)
+ }
+ }
+}
+
+func TestHandleAgentRecentChanges_RedactsCommandsWithoutAIExecute(t *testing.T) {
+ command := unified.BuildCommandExecutionChange("vm:101", "alert-1", "patrol", "systemctl restart nginx", true, "secret output", map[string]any{"script": "cat /etc/shadow"})
+ runbook := unified.BuildRunbookExecutionChange("vm:101", "alert-1", "operator", "rb-1", "Restart web", "succeeded", false, "ran systemctl restart nginx", nil)
+ h := recentChangesFixture(t, []unified.Resource{{ID: "vm:101", Type: "vm", Name: "db-01"}}, []unified.ResourceChange{*command, *runbook})
+
+ _, readOnly := getRecentChanges(t, h, "", &config.APITokenRecord{Scopes: []string{config.ScopeMonitoringRead}})
+ if len(readOnly.Changes) != 2 {
+ t.Fatalf("changes = %d; want 2", len(readOnly.Changes))
+ }
+ body, _ := json.Marshal(readOnly)
+ for _, leaked := range []string{"systemctl", "secret output", "/etc/shadow"} {
+ if strings.Contains(string(body), leaked) {
+ t.Fatalf("monitoring-read response leaked %q: %s", leaked, body)
+ }
+ }
+ for _, change := range readOnly.Changes {
+ if !change.CommandRedacted {
+ t.Fatalf("%s not marked redacted: %+v", change.Kind, change)
+ }
+ if change.Metadata[unified.MetadataAlertIdentifier] != "alert-1" {
+ t.Fatalf("%s lost safe metadata: %+v", change.Kind, change.Metadata)
+ }
+ if change.Kind == unified.ChangeCommandExecuted && change.Reason != "Command succeeded" {
+ t.Fatalf("command reason = %q", change.Reason)
+ }
+ }
+
+ _, executor := getRecentChanges(t, h, "", &config.APITokenRecord{Scopes: []string{config.ScopeMonitoringRead, config.ScopeAIExecute}})
+ body, _ = json.Marshal(executor)
+ if !strings.Contains(string(body), "systemctl restart nginx") || strings.Contains(string(body), `"commandRedacted":true`) {
+ t.Fatalf("ai:execute token must read command payloads: %s", body)
+ }
+}
+
+func TestRecentChangeKindsParseThroughSharedFilterContract(t *testing.T) {
+ for _, kind := range agentcapabilities.RecentChangeKinds {
+ filters, err := unified.ParseResourceChangeFilters([]string{kind}, nil, nil)
+ if err != nil || len(filters.Kinds) != 1 || string(filters.Kinds[0]) != kind {
+ t.Errorf("documented kind %q does not parse: %v %+v", kind, err, filters)
+ }
+ }
+}
diff --git a/internal/api/agent_substrate_e2e_test.go b/internal/api/agent_substrate_e2e_test.go
index c514545277..5f68a234a5 100644
--- a/internal/api/agent_substrate_e2e_test.go
+++ b/internal/api/agent_substrate_e2e_test.go
@@ -182,6 +182,35 @@ func TestAgentSubstrate_DiscoveryToTriageToDepthFlowsThroughHTTPBoundary(t *test
t.Fatalf("operations-loop status must keep external-agent readiness out of steps: %+v", loopStatus.Steps)
}
+ // --- 2b. History: list_recent_changes is reachable at its declared
+ // path behind its declared scope, and an integer filter projected the
+ // way MCP projects tool arguments arrives at the handler intact. ---
+ changesCap := byName[agentcapabilities.ListRecentChangesCapabilityName]
+ if changesCap.Path != agentcapabilities.RecentChangesCapabilityPath || changesCap.Method != http.MethodGet ||
+ changesCap.Scope != config.ScopeMonitoringRead || changesCap.ResponseShape != "AgentRecentChanges" {
+ t.Fatalf("%s manifest entry = %+v", agentcapabilities.ListRecentChangesCapabilityName, changesCap)
+ }
+ req = httptest.NewRequest(http.MethodGet, changesCap.Path, nil)
+ rec = httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("changes GET unauth: status = %d, want 401, body = %s", rec.Code, rec.Body.String())
+ }
+ projectedChanges, err := agentcapabilities.ProjectCapabilityCall(changesCap, map[string]any{"limit": float64(5), "kind": "restart,alert_fired"})
+ if err != nil {
+ t.Fatalf("project %s: %v", changesCap.Name, err)
+ }
+ req = httptest.NewRequest(http.MethodGet, projectedChanges.Path+"?"+projectedChanges.Query.Encode(), nil)
+ req.Header.Set("X-API-Token", rawToken)
+ rec = httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("changes GET auth: status = %d, body = %s", rec.Code, rec.Body.String())
+ }
+ if body := rec.Body.String(); !strings.Contains(body, `"changes":[]`) || !strings.Contains(body, `"limit":5`) {
+ t.Fatalf("changes response must carry an empty array and the projected limit; body = %s", body)
+ }
+
// --- 3. Depth: call the path the manifest declares for the
// per-resource bundle. The manifest also declares the stable
// error code "resource_not_found" — exercise the unknown-id path
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 8ab5975138..1e14be14d1 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -28605,3 +28605,73 @@ func TestContractSSOSAMLDiagnosticConsumer(t *testing.T) {
}
t.Logf("SAML_CONSUMER_FRAMES %s", encoded)
}
+
+// TestContract_AgentRecentChangesJSONSnapshot pins the GET /api/agent/changes
+// payload a monitoring-read agent receives, including the command redaction:
+// command text, output and caller details are dropped, the reason is cut to
+// its status, and commandRedacted tells the agent the record was trimmed.
+func TestContract_AgentRecentChangesJSONSnapshot(t *testing.T) {
+ now := time.Date(2026, 10, 28, 12, 0, 0, 0, time.UTC)
+ since := now.Add(-24 * time.Hour)
+ command := unifiedresources.BuildCommandExecutionChange("vm:101", "alert-1", "patrol", "systemctl restart nginx", true, "secret output", map[string]any{"script": "cat /etc/shadow"})
+ command.ID = "change-1"
+ command.ObservedAt = now.Add(-time.Hour)
+ command.OccurredAt = &command.ObservedAt
+
+ payload := AgentRecentChanges{
+ Changes: []AgentRecentChange{redactAgentRecentChangeCommand(AgentRecentChange{
+ ResourceChange: *command,
+ ResourceName: "db-01",
+ ResourceType: "vm",
+ })},
+ Count: 1,
+ Since: since,
+ Limit: agentcapabilities.RecentChangesDefaultLimit,
+ GeneratedAt: now,
+ }
+ got, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("marshal recent changes: %v", err)
+ }
+
+ const want = `{
+ "changes":[{
+ "id":"change-1",
+ "observedAt":"2026-10-28T11:00:00Z",
+ "occurredAt":"2026-10-28T11:00:00Z",
+ "resourceId":"vm:101",
+ "kind":"command_executed",
+ "sourceType":"agent_action",
+ "confidence":"high",
+ "actor":"patrol",
+ "reason":"Command succeeded",
+ "metadata":{"alert_identifier":"alert-1","success":true},
+ "resourceName":"db-01",
+ "resourceType":"vm",
+ "commandRedacted":true
+ }],
+ "count":1,
+ "truncated":false,
+ "since":"2026-10-27T12:00:00Z",
+ "limit":50,
+ "generatedAt":"2026-10-28T12:00:00Z"
+ }`
+ assertJSONSnapshot(t, got, want)
+}
+
+// TestContract_PulseMCPPublishesRecentChangesAsReadOnlyTool pins that MCP
+// clients see list_recent_changes as a monitoring-read GET on the manifest
+// route, not only the REST surface.
+func TestContract_PulseMCPPublishesRecentChangesAsReadOnlyTool(t *testing.T) {
+ manifest := agentcapabilities.CanonicalManifest()
+ for _, capability := range agentcapabilities.ManifestSurfaceToolCapabilities(manifest, agentcapabilities.SurfaceIDPulseMCP) {
+ if capability.Name != agentcapabilities.ListRecentChangesCapabilityName {
+ continue
+ }
+ if capability.Method != http.MethodGet || capability.Path != agentcapabilities.RecentChangesCapabilityPath || capability.Scope != config.ScopeMonitoringRead {
+ t.Fatalf("list_recent_changes = %s %s (%s); want GET %s (%s)", capability.Method, capability.Path, capability.Scope, agentcapabilities.RecentChangesCapabilityPath, config.ScopeMonitoringRead)
+ }
+ return
+ }
+ t.Fatalf("Pulse MCP surface does not publish %s", agentcapabilities.ListRecentChangesCapabilityName)
+}
diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.go
index 5ab3b8eef5..f940093786 100644
--- a/internal/api/route_inventory_test.go
+++ b/internal/api/route_inventory_test.go
@@ -301,6 +301,7 @@ func sortedKeys(set map[string]struct{}) []string {
var dynamicRouteAllowlist = []string{
"agentcapabilities.OperationsLoopStatusCompatibilityPath",
"agentcapabilities.PatrolControlStatusCapabilityPath",
+ "agentcapabilities.RecentChangesCapabilityPath",
}
var publicRouteAllowlist = []string{
diff --git a/internal/api/router_routes_monitoring.go b/internal/api/router_routes_monitoring.go
index addbbba2a6..bd08cdc6bb 100644
--- a/internal/api/router_routes_monitoring.go
+++ b/internal/api/router_routes_monitoring.go
@@ -120,6 +120,13 @@ func (r *Router) registerMonitoringResourceRoutes(
agentcapabilities.FleetContextCapabilityName,
r.agentContextHandler.HandleFleetContext,
))))
+ // Agent-consumable change history — "what happened?" across the fleet,
+ // read from the existing resource change store. Companion to the fleet
+ // triage view above, which answers "where do I look now?".
+ r.mux.HandleFunc(agentcapabilities.RecentChangesCapabilityPath, RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.withExternalAgentCapabilityActivity(
+ agentcapabilities.ListRecentChangesCapabilityName,
+ r.agentContextHandler.HandleRecentChanges,
+ ))))
// Content-safe Patrol control status: the shared Patrol, Assistant,
// governed action, verification, Patrol control proof, and optional MCP
// readiness projection for native UI and external agents.