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.

Canonicalize incident timeline events

rcourtmanabc4b1a62aa3
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 7fc764177e..a84febc221 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -258,6 +258,15 @@ incident memory first, canonical resource timeline second.
The same runtime boundary now also owns durable action execution auditing.
`internal/ai/chat/service.go` initializes the unified-resource audit store on
startup, and the write-action tool paths under `internal/ai/tools/` persist
+AI incident handling must now also write durable resource-history facts
+through the canonical unified-resource change store when a concrete resource
+target is known. Command executions and runbook executions triggered during an
+alert investigation may remain visible inside `internal/ai/memory/incidents.go`
+as operator-facing incident projection entries, but the durable backend truth
+for those events now belongs to canonical `ResourceChange` kinds such as
+`command_executed` and `runbook_executed`, keyed by canonical resource ID and
+linked back to the alert through metadata instead of being stored only in AI
+memory.
append-only action lifecycle and action audit records through that shared
store instead of leaving command execution state in memory-only tool helpers.
The patrol-local `memory.ChangeDetector.GetChangesSummary` path now also
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 55336cf3c3..b49c20ed6b 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -69,6 +69,14 @@ rebuilds and supplemental ingest into the unified-resource timeline. That means
monitoring no longer just materializes state snapshots for consumers; it also
emits durable `ResourceChange` history through the shared resource store so
live monitoring updates and historical inspection stay aligned.
+That same ownership now includes alert-lifecycle facts emitted by monitoring.
+When an alert is fired, acknowledged, unacknowledged, or resolved for a
+canonical resource, the monitoring runtime must write the corresponding durable
+resource-history event into the unified-resource change store instead of
+leaving that lifecycle only inside alert-scoped incident memory. Incident
+timelines may still project those breadcrumbs for operator flow, but the
+durable backend truth for alert lifecycle now lives on the canonical resource
+timeline.
The registry proof map now treats provider discovery and metrics history as
their own governed runtime surfaces instead of leaving them folded into a
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index c74ba6a432..d0dbb498df 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -90,6 +90,15 @@ assembly branch.
This subsystem now sits under the dedicated core monitoring runtime lane so
canonical resource identity, discovery normalization, and platform-runtime
coverage stay governed as a first-class Pulse product surface.
+The canonical resource timeline now also owns durable incident-response facts
+that materially changed resource investigation state. `ResourceChange` kinds
+such as `alert_fired`, `alert_acknowledged`, `alert_unacknowledged`,
+`alert_resolved`, `command_executed`, and `runbook_executed` are part of the
+canonical history contract, not optional AI-local annotations. Alert-scoped
+incident memory may still project those events for one investigation thread,
+but the durable source of truth for resource-affecting alert lifecycle and
+remediation activity now belongs to unified-resource history keyed by
+canonical resource ID.
Kubernetes node identity enrichment remains intentionally hostname-based when
the API cannot supply machine-level identity signals; the code may borrow
machine-id and MAC evidence from a uniquely matched host agent, but duplicate
diff --git a/frontend-modern/src/types/__tests__/resource.test.ts b/frontend-modern/src/types/__tests__/resource.test.ts
index 3b5da4b3b3..afa44c3d56 100644
--- a/frontend-modern/src/types/__tests__/resource.test.ts
+++ b/frontend-modern/src/types/__tests__/resource.test.ts
@@ -9,6 +9,7 @@ import {
getCpuPercent,
getMemoryPercent,
getDiskPercent,
+ type ResourceChangeKind,
type Resource,
type ResourceType,
} from '@/types/resource';
@@ -206,6 +207,26 @@ describe('Resource Helper Functions', () => {
});
describe('Resource Interface', () => {
+ it('supports canonical incident timeline change kinds', () => {
+ const kinds: ResourceChangeKind[] = [
+ 'alert_fired',
+ 'alert_acknowledged',
+ 'alert_unacknowledged',
+ 'alert_resolved',
+ 'command_executed',
+ 'runbook_executed',
+ ];
+
+ expect(kinds).toEqual([
+ 'alert_fired',
+ 'alert_acknowledged',
+ 'alert_unacknowledged',
+ 'alert_resolved',
+ 'command_executed',
+ 'runbook_executed',
+ ]);
+ });
+
it('allows all valid resource types', () => {
const types: ResourceType[] = [
'agent',
diff --git a/frontend-modern/src/types/resource.ts b/frontend-modern/src/types/resource.ts
index de3ff34bc1..c50487a5a5 100644
--- a/frontend-modern/src/types/resource.ts
+++ b/frontend-modern/src/types/resource.ts
@@ -149,7 +149,13 @@ export type ResourceChangeKind =
| 'config_update'
| 'metric_anomaly'
| 'relationship_change'
- | 'capability_change';
+ | 'capability_change'
+ | 'alert_fired'
+ | 'alert_acknowledged'
+ | 'alert_unacknowledged'
+ | 'alert_resolved'
+ | 'command_executed'
+ | 'runbook_executed';
export type ResourceChangeSourceType =
| 'platform_event'
| 'pulse_diff'
diff --git a/frontend-modern/src/utils/__tests__/resourceChangePresentation.test.ts b/frontend-modern/src/utils/__tests__/resourceChangePresentation.test.ts
index 99b820229c..d276804ded 100644
--- a/frontend-modern/src/utils/__tests__/resourceChangePresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/resourceChangePresentation.test.ts
@@ -15,6 +15,8 @@ describe('resourceChangePresentation utils', () => {
expect(formatResourceChangeKind('config_update')).toBe('Config update');
expect(formatResourceChangeKind('metric_anomaly')).toBe('Metric anomaly');
expect(formatResourceChangeKind('relationship_change')).toBe('Relationship change');
+ expect(formatResourceChangeKind('alert_fired')).toBe('Alert fired');
+ expect(formatResourceChangeKind('runbook_executed')).toBe('Runbook executed');
});
it('formats canonical resource change headlines', () => {
@@ -45,6 +47,10 @@ describe('resourceChangePresentation utils', () => {
label: 'Restart',
plural: 'Restarts',
});
+ expect(getResourceChangeKindPresentation('alert_resolved')).toMatchObject({
+ label: 'Alert resolved',
+ plural: 'Alerts resolved',
+ });
expect(getResourceChangeSourceTypePresentation('platform_event')).toMatchObject({
label: 'Platform event',
plural: 'Platform events',
diff --git a/frontend-modern/src/utils/resourceChangePresentation.ts b/frontend-modern/src/utils/resourceChangePresentation.ts
index 5580941e3f..9061e19c16 100644
--- a/frontend-modern/src/utils/resourceChangePresentation.ts
+++ b/frontend-modern/src/utils/resourceChangePresentation.ts
@@ -15,6 +15,12 @@ export const RESOURCE_CHANGE_KIND_ORDER: ResourceChangeKind[] = [
'metric_anomaly',
'relationship_change',
'capability_change',
+ 'alert_fired',
+ 'alert_acknowledged',
+ 'alert_unacknowledged',
+ 'alert_resolved',
+ 'command_executed',
+ 'runbook_executed',
];
const RESOURCE_CHANGE_KIND_PRESENTATIONS: Record<
@@ -51,6 +57,36 @@ const RESOURCE_CHANGE_KIND_PRESENTATIONS: Record<
plural: 'Capability changes',
className: 'bg-cyan-100 text-cyan-700 dark:bg-cyan-900 dark:text-cyan-300',
},
+ alert_fired: {
+ label: 'Alert fired',
+ plural: 'Alerts fired',
+ className: 'bg-rose-100 text-rose-700 dark:bg-rose-900 dark:text-rose-300',
+ },
+ alert_acknowledged: {
+ label: 'Alert acknowledged',
+ plural: 'Alerts acknowledged',
+ className: 'bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300',
+ },
+ alert_unacknowledged: {
+ label: 'Alert unacknowledged',
+ plural: 'Alerts unacknowledged',
+ className: 'bg-orange-100 text-orange-700 dark:bg-orange-900 dark:text-orange-300',
+ },
+ alert_resolved: {
+ label: 'Alert resolved',
+ plural: 'Alerts resolved',
+ className: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900 dark:text-emerald-300',
+ },
+ command_executed: {
+ label: 'Command executed',
+ plural: 'Commands executed',
+ className: 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300',
+ },
+ runbook_executed: {
+ label: 'Runbook executed',
+ plural: 'Runbooks executed',
+ className: 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900 dark:text-indigo-300',
+ },
};
type ResourceChangeSourceType =
@@ -148,7 +184,10 @@ const fallbackResourceChangePresentation = (value: string): ResourceChangeLabelP
export function getResourceChangeKindPresentation(
kind: ResourceChangeKind | string,
): ResourceChangeLabelPresentation {
- return RESOURCE_CHANGE_KIND_PRESENTATIONS[kind as ResourceChangeKind] ?? fallbackResourceChangePresentation(String(kind));
+ return (
+ RESOURCE_CHANGE_KIND_PRESENTATIONS[kind as ResourceChangeKind] ??
+ fallbackResourceChangePresentation(String(kind))
+ );
}
export function getResourceChangeSourceTypePresentation(
@@ -183,6 +222,18 @@ export function formatResourceChangeKind(kind: ResourceChange['kind']): string {
return 'Relationship change';
case 'capability_change':
return 'Capability change';
+ case 'alert_fired':
+ return 'Alert fired';
+ case 'alert_acknowledged':
+ return 'Alert acknowledged';
+ case 'alert_unacknowledged':
+ return 'Alert unacknowledged';
+ case 'alert_resolved':
+ return 'Alert resolved';
+ case 'command_executed':
+ return 'Command executed';
+ case 'runbook_executed':
+ return 'Runbook executed';
default:
return humanizeToken(String(kind), { fallback: String(kind) });
}
diff --git a/internal/ai/service.go b/internal/ai/service.go
index 9a3841f3d7..0dce6ec496 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -3102,24 +3102,32 @@ func (s *Service) executeTool(ctx context.Context, req ExecuteRequest, tc provid
result, err := s.executeOnAgent(ctx, execReq, command)
recordIncident := func(success bool, output string) {
alertIdentifier := extractAlertIdentifier(req.Context)
- if alertIdentifier == "" {
- return
- }
- s.mu.RLock()
- incidentStore := s.incidentStore
- s.mu.RUnlock()
- if incidentStore == nil {
- return
- }
- details := map[string]interface{}{
- "resource_id": req.TargetID,
+ resourceID := extractIncidentResourceIdentifier(req.TargetID, req.Context)
+ details := map[string]any{
+ "resource_id": resourceID,
"resource_type": req.TargetType,
"run_on_host": runOnHost,
}
if targetHost != "" {
details["target_host"] = targetHost
}
- incidentStore.RecordCommand(alertIdentifier, command, success, output, details)
+ if alertIdentifier != "" {
+ s.mu.RLock()
+ incidentStore := s.incidentStore
+ s.mu.RUnlock()
+ if incidentStore != nil {
+ incidentStore.RecordCommand(alertIdentifier, command, success, output, details)
+ }
+ }
+ s.recordCanonicalResourceChange(unifiedresources.BuildCommandExecutionChange(
+ resourceID,
+ alertIdentifier,
+ "agent:pulse-assistant",
+ command,
+ success,
+ output,
+ details,
+ ))
}
if err != nil {
recordIncident(false, result)
@@ -4541,17 +4549,34 @@ func (s *Service) RecordIncidentAnalysis(alertIdentifier, summary string, detail
}
// RecordIncidentRunbook stores a runbook execution event for an alert.
-func (s *Service) RecordIncidentRunbook(alertIdentifier, runbookID, title string, outcome memory.Outcome, automatic bool, message string) {
+func (s *Service) RecordIncidentRunbook(resourceID, alertIdentifier, runbookID, title string, outcome memory.Outcome, automatic bool, message string) {
if alertIdentifier == "" || runbookID == "" {
return
}
s.mu.RLock()
store := s.incidentStore
s.mu.RUnlock()
- if store == nil {
- return
+ if store != nil {
+ store.RecordRunbook(alertIdentifier, runbookID, title, string(outcome), automatic, message)
+ }
+ if resourceID == "" {
+ resourceID = s.lookupIncidentResourceIdentifier(alertIdentifier)
}
- store.RecordRunbook(alertIdentifier, runbookID, title, string(outcome), automatic, message)
+ actor := ""
+ if automatic {
+ actor = "agent:pulse-patrol"
+ }
+ s.recordCanonicalResourceChange(unifiedresources.BuildRunbookExecutionChange(
+ resourceID,
+ alertIdentifier,
+ actor,
+ runbookID,
+ title,
+ string(outcome),
+ automatic,
+ message,
+ nil,
+ ))
}
func extractAlertIdentifier(ctx map[string]interface{}) string {
@@ -4564,6 +4589,65 @@ func extractAlertIdentifier(ctx map[string]interface{}) string {
return ""
}
+func extractIncidentResourceIdentifier(targetID string, ctx map[string]interface{}) string {
+ targetID = strings.TrimSpace(targetID)
+ if targetID != "" {
+ return targetID
+ }
+ if ctx == nil {
+ return ""
+ }
+ for _, key := range []string{"resourceID", "resource_id", "resourceId"} {
+ if value, ok := ctx[key].(string); ok && strings.TrimSpace(value) != "" {
+ return strings.TrimSpace(value)
+ }
+ }
+ return ""
+}
+
+func (s *Service) lookupIncidentResourceIdentifier(alertIdentifier string) string {
+ if strings.TrimSpace(alertIdentifier) == "" {
+ return ""
+ }
+ s.mu.RLock()
+ store := s.incidentStore
+ s.mu.RUnlock()
+ if store == nil {
+ return ""
+ }
+ timeline := store.GetTimelineByAlertIdentifier(alertIdentifier)
+ if timeline == nil {
+ return ""
+ }
+ return strings.TrimSpace(timeline.ResourceID)
+}
+
+func (s *Service) recordCanonicalResourceChange(change *unifiedresources.ResourceChange) {
+ if s == nil || change == nil {
+ return
+ }
+
+ s.mu.RLock()
+ store := s.resourceExportStore
+ orgID := strings.TrimSpace(s.orgID)
+ storeOrgID := strings.TrimSpace(s.resourceExportStoreOrgID)
+ s.mu.RUnlock()
+
+ if store == nil {
+ return
+ }
+ if storeOrgID != "" && orgID != "" && storeOrgID != orgID {
+ return
+ }
+ if err := store.RecordChange(*change); err != nil {
+ log.Warn().
+ Err(err).
+ Str("resource_id", change.ResourceID).
+ Str("kind", string(change.Kind)).
+ Msg("failed to record canonical incident timeline change")
+ }
+}
+
func (s *Service) buildRecentResourceChangesContext(resourceID string) string {
resourceID = strings.TrimSpace(resourceID)
if resourceID == "" {
diff --git a/internal/ai/service_coverage_imp_test.go b/internal/ai/service_coverage_imp_test.go
index c74b1d9870..671f6d38e7 100644
--- a/internal/ai/service_coverage_imp_test.go
+++ b/internal/ai/service_coverage_imp_test.go
@@ -4,11 +4,13 @@ import (
"context"
"strings"
"testing"
+ "time"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/cost"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/memory"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
+ unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
func TestService_QuickAnalysis(t *testing.T) {
@@ -141,17 +143,20 @@ func TestService_AnalyzeForDiscovery(t *testing.T) {
func TestService_RecordIncidentRunbook(t *testing.T) {
svc := NewService(nil, nil)
+ canonicalStore := unifiedresources.NewMemoryStore()
+ svc.resourceExportStore = canonicalStore
+ svc.resourceExportStoreOrgID = svc.orgID
// Case 1: No store -> should safe return
- svc.RecordIncidentRunbook("alert1", "rb1", "title", memory.OutcomeResolved, true, "msg")
+ svc.RecordIncidentRunbook("vm-1", "alert1", "rb1", "title", memory.OutcomeResolved, true, "msg")
// Case 2: Invalid inputs -> should safe return
svc.incidentStore = memory.NewIncidentStore(memory.IncidentStoreConfig{})
- svc.RecordIncidentRunbook("", "rb1", "title", memory.OutcomeResolved, true, "msg")
- svc.RecordIncidentRunbook("alert1", "", "title", memory.OutcomeResolved, true, "msg")
+ svc.RecordIncidentRunbook("vm-1", "", "rb1", "title", memory.OutcomeResolved, true, "msg")
+ svc.RecordIncidentRunbook("vm-1", "alert1", "", "title", memory.OutcomeResolved, true, "msg")
// Case 3: Valid
- svc.RecordIncidentRunbook("alert1", "rb1", "title", memory.OutcomeResolved, true, "msg")
+ svc.RecordIncidentRunbook("vm-1", "alert1", "rb1", "title", memory.OutcomeResolved, true, "msg")
timeline := svc.incidentStore.GetTimelineByAlertIdentifier("alert1")
if timeline == nil {
@@ -173,6 +178,17 @@ func TestService_RecordIncidentRunbook(t *testing.T) {
if !found {
t.Fatalf("expected runbook event to be recorded, got %d events", len(timeline.Events))
}
+
+ changes, err := canonicalStore.GetRecentChanges("vm-1", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetRecentChanges: %v", err)
+ }
+ if len(changes) == 0 {
+ t.Fatal("expected canonical runbook change")
+ }
+ if changes[0].Kind != unifiedresources.ChangeRunbookExecuted {
+ t.Fatalf("Kind = %q, want %q", changes[0].Kind, unifiedresources.ChangeRunbookExecuted)
+ }
}
func TestAbsFloat(t *testing.T) {
diff --git a/internal/ai/service_extended_test.go b/internal/ai/service_extended_test.go
index cd20ed589a..3bf918885a 100644
--- a/internal/ai/service_extended_test.go
+++ b/internal/ai/service_extended_test.go
@@ -1129,6 +1129,9 @@ func TestService_ExecuteTool_RunCommand_WithTargetHost(t *testing.T) {
}
svc := NewService(nil, mockServer)
svc.policy = &mockPolicy{decision: agentexec.PolicyAllow}
+ canonicalStore := unifiedresources.NewMemoryStore()
+ svc.resourceExportStore = canonicalStore
+ svc.resourceExportStoreOrgID = svc.orgID
tc := providers.ToolCall{
Name: "run_command",
@@ -1143,7 +1146,8 @@ func TestService_ExecuteTool_RunCommand_WithTargetHost(t *testing.T) {
TargetType: "vm",
TargetID: "vm-100",
Context: map[string]interface{}{
- "node": "original-node",
+ "node": "original-node",
+ "alertIdentifier": "alert-123",
},
}
@@ -1154,6 +1158,20 @@ func TestService_ExecuteTool_RunCommand_WithTargetHost(t *testing.T) {
if exec.Input != "[target-node] uptime" {
t.Errorf("Expected input to show target-node, got: %s", exec.Input)
}
+
+ changes, err := canonicalStore.GetRecentChanges("vm-100", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetRecentChanges: %v", err)
+ }
+ if len(changes) != 1 {
+ t.Fatalf("expected 1 canonical command change, got %d", len(changes))
+ }
+ if changes[0].Kind != unifiedresources.ChangeCommandExecuted {
+ t.Fatalf("Kind = %q, want %q", changes[0].Kind, unifiedresources.ChangeCommandExecuted)
+ }
+ if got := changes[0].Metadata["alert_identifier"]; got != "alert-123" {
+ t.Fatalf("alert_identifier = %#v, want alert-123", got)
+ }
}
func TestService_HasAgentForTarget_WithUnifiedResourceProvider(t *testing.T) {
diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.go
index 46bb1c6f89..d3e02ce8fe 100644
--- a/internal/monitoring/canonical_guardrails_test.go
+++ b/internal/monitoring/canonical_guardrails_test.go
@@ -6,6 +6,10 @@ import (
"regexp"
"strings"
"testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+ unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
var bannedSnapshotResourceAccessPatterns = []struct {
@@ -84,3 +88,33 @@ func TestLegacyMemorySourceAliasesRemainCanonicalized(t *testing.T) {
})
}
}
+
+func TestAlertLifecycleCanonicalChangesRemainWritable(t *testing.T) {
+ store := unifiedresources.NewMemoryStore()
+ monitor := &Monitor{
+ resourceStore: unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(store)),
+ }
+
+ startedAt := time.Date(2026, 3, 20, 9, 0, 0, 0, time.UTC)
+ alert := &alerts.Alert{
+ ID: "alert-guardrail-1",
+ Type: "cpu",
+ Level: alerts.AlertLevelCritical,
+ ResourceID: "vm-guardrail",
+ Message: "CPU threshold exceeded",
+ StartTime: startedAt,
+ }
+
+ monitor.handleAlertFired(alert)
+
+ changes, err := store.GetRecentChanges("vm-guardrail", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetRecentChanges: %v", err)
+ }
+ if len(changes) != 1 {
+ t.Fatalf("expected 1 canonical alert change, got %d", len(changes))
+ }
+ if changes[0].Kind != unifiedresources.ChangeAlertFired {
+ t.Fatalf("Kind = %q, want %q", changes[0].Kind, unifiedresources.ChangeAlertFired)
+ }
+}
diff --git a/internal/monitoring/monitor_alert_handling_test.go b/internal/monitoring/monitor_alert_handling_test.go
index 7795d737fd..46409fe9fe 100644
--- a/internal/monitoring/monitor_alert_handling_test.go
+++ b/internal/monitoring/monitor_alert_handling_test.go
@@ -8,6 +8,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/notifications"
+ unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
"github.com/rcourtman/pulse-go-rewrite/internal/websocket"
)
@@ -42,6 +43,52 @@ func TestMonitor_HandleAlertFired_Extra(t *testing.T) {
// NotificationMgr might spin up goroutine.
}
+func TestMonitor_HandleAlertLifecycle_WritesCanonicalChanges(t *testing.T) {
+ store := unifiedresources.NewMemoryStore()
+ m := &Monitor{
+ resourceStore: unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(store)),
+ }
+
+ startedAt := time.Date(2026, 3, 20, 9, 0, 0, 0, time.UTC)
+ ackAt := startedAt.Add(2 * time.Minute)
+ alert := &alerts.Alert{
+ ID: "alert-canonical-1",
+ Type: "cpu",
+ Level: alerts.AlertLevelCritical,
+ ResourceID: "vm-1",
+ Message: "CPU threshold exceeded",
+ Value: 93.4,
+ Threshold: 80,
+ StartTime: startedAt,
+ AckTime: &ackAt,
+ }
+
+ m.handleAlertFired(alert)
+ m.handleAlertAcknowledged(alert, "admin")
+ m.handleAlertUnacknowledged(alert, "admin")
+
+ changes, err := store.GetRecentChanges("vm-1", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetRecentChanges: %v", err)
+ }
+ if len(changes) != 3 {
+ t.Fatalf("expected 3 canonical changes, got %d", len(changes))
+ }
+ wantKinds := []unifiedresources.ChangeKind{
+ unifiedresources.ChangeAlertUnacknowledged,
+ unifiedresources.ChangeAlertAcknowledged,
+ unifiedresources.ChangeAlertFired,
+ }
+ for idx, want := range wantKinds {
+ if changes[idx].Kind != want {
+ t.Fatalf("changes[%d].Kind = %q, want %q", idx, changes[idx].Kind, want)
+ }
+ }
+ if got := changes[2].Metadata["alert_identifier"]; got != "alert-canonical-1" {
+ t.Fatalf("alert_identifier = %#v, want alert-canonical-1", got)
+ }
+}
+
func TestMonitor_HandleAlertResolved_Detailed_Extra(t *testing.T) {
// 1. With Hub and NotificationMgr and Resolve Notify ON
hub := websocket.NewHub(nil)
diff --git a/internal/monitoring/monitor_alerts.go b/internal/monitoring/monitor_alerts.go
index b6d36557d6..eea65821a2 100644
--- a/internal/monitoring/monitor_alerts.go
+++ b/internal/monitoring/monitor_alerts.go
@@ -2,13 +2,19 @@ package monitoring
import (
"context"
+ "time"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/memory"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
"github.com/rcourtman/pulse-go-rewrite/internal/mock"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
"github.com/rs/zerolog/log"
)
+type canonicalResourceChangeRecorder interface {
+ RecordChange(change unifiedresources.ResourceChange) error
+}
+
// GetAlertManager returns the alert manager
func (m *Monitor) GetAlertManager() *alerts.Manager {
return m.alertManager
@@ -60,6 +66,7 @@ func (m *Monitor) handleAlertFired(alert *alerts.Alert) {
if m.incidentStore != nil {
m.incidentStore.RecordAlertFired(alert)
}
+ m.recordAlertTimelineChange(alert, unifiedresources.ChangeAlertFired, alert.StartTime, "")
// Trigger AI analysis if callback is configured
if m.alertTriggeredAICallback != nil {
@@ -90,6 +97,12 @@ func (m *Monitor) handleAlertResolved(alertID string) {
m.incidentStore.RecordAlertResolved(resolvedAlert.Alert, resolvedAlert.ResolvedTime)
}
}
+ if resolvedAlert == nil && m.alertManager != nil {
+ resolvedAlert = m.alertManager.GetResolvedAlert(alertID)
+ }
+ if resolvedAlert != nil && resolvedAlert.Alert != nil {
+ m.recordAlertTimelineChange(resolvedAlert.Alert, unifiedresources.ChangeAlertResolved, resolvedAlert.ResolvedTime, "")
+ }
// Always trigger AI callback, regardless of notification suppression.
if m.alertResolvedAICallback != nil {
@@ -129,16 +142,57 @@ func (m *Monitor) handleAlertResolved(alertID string) {
func (m *Monitor) handleAlertAcknowledged(alert *alerts.Alert, user string) {
if m.incidentStore == nil || alert == nil {
- return
+ if alert == nil {
+ return
+ }
+ } else {
+ m.incidentStore.RecordAlertAcknowledged(alert, user)
+ }
+ occurredAt := time.Now()
+ if alert.AckTime != nil {
+ occurredAt = *alert.AckTime
}
- m.incidentStore.RecordAlertAcknowledged(alert, user)
+ m.recordAlertTimelineChange(alert, unifiedresources.ChangeAlertAcknowledged, occurredAt, user)
}
func (m *Monitor) handleAlertUnacknowledged(alert *alerts.Alert, user string) {
- if m.incidentStore == nil || alert == nil {
+ if alert == nil {
return
}
- m.incidentStore.RecordAlertUnacknowledged(alert, user)
+ if m.incidentStore != nil {
+ m.incidentStore.RecordAlertUnacknowledged(alert, user)
+ }
+ m.recordAlertTimelineChange(alert, unifiedresources.ChangeAlertUnacknowledged, time.Now(), user)
+}
+
+func (m *Monitor) recordAlertTimelineChange(alert *alerts.Alert, kind unifiedresources.ChangeKind, occurredAt time.Time, actor string) {
+ if alert == nil || m == nil {
+ return
+ }
+ recorder, ok := m.resourceStore.(canonicalResourceChangeRecorder)
+ if !ok || recorder == nil {
+ return
+ }
+
+ change := unifiedresources.BuildAlertTimelineChange(alert.ResourceID, kind, occurredAt, actor, unifiedresources.AlertTimelineChange{
+ AlertIdentifier: alert.ID,
+ AlertType: alert.Type,
+ AlertLevel: string(alert.Level),
+ AlertMessage: alert.Message,
+ AlertValue: alert.Value,
+ AlertThreshold: alert.Threshold,
+ })
+ if change == nil {
+ return
+ }
+ if err := recorder.RecordChange(*change); err != nil {
+ log.Warn().
+ Err(err).
+ Str("resource_id", alert.ResourceID).
+ Str("alert_id", alert.ID).
+ Str("kind", string(kind)).
+ Msg("failed to record canonical alert timeline change")
+ }
}
// broadcastStateUpdate sends an immediate state update to all WebSocket clients.
diff --git a/internal/unifiedresources/change_filters.go b/internal/unifiedresources/change_filters.go
index f9009b1377..3f4076d4de 100644
--- a/internal/unifiedresources/change_filters.go
+++ b/internal/unifiedresources/change_filters.go
@@ -59,6 +59,18 @@ func parseResourceChangeKinds(values []string) ([]ChangeKind, error) {
parsed = append(parsed, ChangeRelationship)
case string(ChangeCapability):
parsed = append(parsed, ChangeCapability)
+ case string(ChangeAlertFired):
+ parsed = append(parsed, ChangeAlertFired)
+ case string(ChangeAlertAcknowledged):
+ parsed = append(parsed, ChangeAlertAcknowledged)
+ case string(ChangeAlertUnacknowledged):
+ parsed = append(parsed, ChangeAlertUnacknowledged)
+ case string(ChangeAlertResolved):
+ parsed = append(parsed, ChangeAlertResolved)
+ case string(ChangeCommandExecuted):
+ parsed = append(parsed, ChangeCommandExecuted)
+ case string(ChangeRunbookExecuted):
+ parsed = append(parsed, ChangeRunbookExecuted)
default:
return nil, fmt.Errorf("invalid kind value %q", normalized)
}
diff --git a/internal/unifiedresources/change_filters_test.go b/internal/unifiedresources/change_filters_test.go
index f64f592497..cde9b22a2f 100644
--- a/internal/unifiedresources/change_filters_test.go
+++ b/internal/unifiedresources/change_filters_test.go
@@ -7,7 +7,7 @@ import (
func TestParseResourceChangeFilters(t *testing.T) {
filters, err := ParseResourceChangeFilters(
- []string{" state_transition,RESTART ", "config_update"},
+ []string{" state_transition,RESTART ", "config_update", "alert_fired,command_executed"},
[]string{" platform_event ", "pulse_diff, HEURISTIC"},
[]string{" docker_adapter ", "proxmox_adapter,agent:ops-helper"},
)
@@ -15,10 +15,10 @@ func TestParseResourceChangeFilters(t *testing.T) {
t.Fatalf("ParseResourceChangeFilters() error = %v", err)
}
- if got, want := len(filters.Kinds), 3; got != want {
+ if got, want := len(filters.Kinds), 5; got != want {
t.Fatalf("kinds length = %d, want %d", got, want)
}
- if filters.Kinds[0] != ChangeStateTransition || filters.Kinds[1] != ChangeRestart || filters.Kinds[2] != ChangeConfigUpdate {
+ if filters.Kinds[0] != ChangeStateTransition || filters.Kinds[1] != ChangeRestart || filters.Kinds[2] != ChangeConfigUpdate || filters.Kinds[3] != ChangeAlertFired || filters.Kinds[4] != ChangeCommandExecuted {
t.Fatalf("unexpected parsed kinds: %#v", filters.Kinds)
}
if got, want := len(filters.SourceTypes), 3; got != want {
diff --git a/internal/unifiedresources/change_presentation.go b/internal/unifiedresources/change_presentation.go
index 90d2b8323f..b3b414ebfe 100644
--- a/internal/unifiedresources/change_presentation.go
+++ b/internal/unifiedresources/change_presentation.go
@@ -38,6 +38,18 @@ func ChangeKindLabel(kind ChangeKind) string {
return "Relationship change"
case ChangeCapability:
return "Capability change"
+ case ChangeAlertFired:
+ return "Alert fired"
+ case ChangeAlertAcknowledged:
+ return "Alert acknowledged"
+ case ChangeAlertUnacknowledged:
+ return "Alert unacknowledged"
+ case ChangeAlertResolved:
+ return "Alert resolved"
+ case ChangeCommandExecuted:
+ return "Command executed"
+ case ChangeRunbookExecuted:
+ return "Runbook executed"
default:
raw := strings.TrimSpace(strings.ReplaceAll(string(kind), "_", " "))
if raw == "" {
diff --git a/internal/unifiedresources/change_presentation_test.go b/internal/unifiedresources/change_presentation_test.go
index 80d3e85f4c..4bdca59d02 100644
--- a/internal/unifiedresources/change_presentation_test.go
+++ b/internal/unifiedresources/change_presentation_test.go
@@ -16,6 +16,12 @@ func TestChangeKindLabel(t *testing.T) {
ChangeAnomaly: "Metric anomaly",
ChangeRelationship: "Relationship change",
ChangeCapability: "Capability change",
+ ChangeAlertFired: "Alert fired",
+ ChangeAlertAcknowledged: "Alert acknowledged",
+ ChangeAlertUnacknowledged: "Alert unacknowledged",
+ ChangeAlertResolved: "Alert resolved",
+ ChangeCommandExecuted: "Command executed",
+ ChangeRunbookExecuted: "Runbook executed",
ChangeKind("custom_kind"): "Custom kind",
ChangeKind(""): "Change",
}
@@ -139,6 +145,20 @@ func TestFormatResourceChangeSummary(t *testing.T) {
"just now",
},
},
+ {
+ name: "alert fired",
+ change: ResourceChange{
+ Kind: ChangeAlertFired,
+ SourceType: SourceHeuristic,
+ Reason: "CPU usage exceeded threshold",
+ ObservedAt: time.Now().Add(-15 * time.Minute),
+ },
+ wants: []string{
+ "**Alert fired**",
+ "heuristic",
+ "CPU usage exceeded threshold",
+ },
+ },
}
for _, tc := range cases {
@@ -158,6 +178,59 @@ func TestFormatResourceChangeSummary(t *testing.T) {
}
}
+func TestBuildIncidentTimelineChanges(t *testing.T) {
+ alertChange := BuildAlertTimelineChange("vm-1", ChangeAlertResolved, time.Date(2026, 3, 20, 12, 0, 0, 0, time.UTC), "ops-user", AlertTimelineChange{
+ AlertIdentifier: "alert-1",
+ AlertType: "cpu",
+ AlertLevel: "critical",
+ AlertMessage: "CPU normalized",
+ AlertValue: 91.4,
+ AlertThreshold: 80,
+ })
+ if alertChange == nil {
+ t.Fatal("expected alert change")
+ }
+ if alertChange.Kind != ChangeAlertResolved {
+ t.Fatalf("Kind = %q, want %q", alertChange.Kind, ChangeAlertResolved)
+ }
+ if alertChange.SourceType != SourceHeuristic {
+ t.Fatalf("SourceType = %q, want %q", alertChange.SourceType, SourceHeuristic)
+ }
+ if got := alertChange.Metadata[metadataAlertIdentifier]; got != "alert-1" {
+ t.Fatalf("alert_identifier = %#v, want alert-1", got)
+ }
+
+ commandChange := BuildCommandExecutionChange("vm-1", "alert-1", "agent:pulse-assistant", "systemctl restart nginx", true, strings.Repeat("x", 700), map[string]any{
+ "resource_type": "vm",
+ })
+ if commandChange == nil {
+ t.Fatal("expected command change")
+ }
+ if commandChange.Kind != ChangeCommandExecuted {
+ t.Fatalf("Kind = %q, want %q", commandChange.Kind, ChangeCommandExecuted)
+ }
+ if commandChange.SourceType != SourceAgentAction {
+ t.Fatalf("SourceType = %q, want %q", commandChange.SourceType, SourceAgentAction)
+ }
+ if got := commandChange.Metadata[metadataOutputExcerpt].(string); len(got) <= resourceChangeOutputExcerptLimit {
+ t.Fatalf("expected truncated output excerpt to include ellipsis, got length %d", len(got))
+ }
+
+ runbookChange := BuildRunbookExecutionChange("vm-1", "alert-1", "agent:pulse-patrol", "rb-1", "Restart service", "resolved", true, "Recovered", nil)
+ if runbookChange == nil {
+ t.Fatal("expected runbook change")
+ }
+ if runbookChange.Kind != ChangeRunbookExecuted {
+ t.Fatalf("Kind = %q, want %q", runbookChange.Kind, ChangeRunbookExecuted)
+ }
+ if runbookChange.SourceType != SourceAgentAction {
+ t.Fatalf("SourceType = %q, want %q", runbookChange.SourceType, SourceAgentAction)
+ }
+ if got := runbookChange.Metadata[metadataRunbookID]; got != "rb-1" {
+ t.Fatalf("runbook_id = %#v, want rb-1", got)
+ }
+}
+
func TestFormatResourceRecentChangesContext(t *testing.T) {
changes := []ResourceChange{
{
diff --git a/internal/unifiedresources/changes.go b/internal/unifiedresources/changes.go
index 88f91a124b..abd936658e 100644
--- a/internal/unifiedresources/changes.go
+++ b/internal/unifiedresources/changes.go
@@ -17,12 +17,18 @@ const (
type ChangeKind string
const (
- ChangeStateTransition ChangeKind = "state_transition"
- ChangeRestart ChangeKind = "restart"
- ChangeConfigUpdate ChangeKind = "config_update"
- ChangeAnomaly ChangeKind = "metric_anomaly"
- ChangeRelationship ChangeKind = "relationship_change"
- ChangeCapability ChangeKind = "capability_change"
+ ChangeStateTransition ChangeKind = "state_transition"
+ ChangeRestart ChangeKind = "restart"
+ ChangeConfigUpdate ChangeKind = "config_update"
+ ChangeAnomaly ChangeKind = "metric_anomaly"
+ ChangeRelationship ChangeKind = "relationship_change"
+ ChangeCapability ChangeKind = "capability_change"
+ ChangeAlertFired ChangeKind = "alert_fired"
+ ChangeAlertAcknowledged ChangeKind = "alert_acknowledged"
+ ChangeAlertUnacknowledged ChangeKind = "alert_unacknowledged"
+ ChangeAlertResolved ChangeKind = "alert_resolved"
+ ChangeCommandExecuted ChangeKind = "command_executed"
+ ChangeRunbookExecuted ChangeKind = "runbook_executed"
)
// ChangeSourceType defines the high-level origin of a change.
diff --git a/internal/unifiedresources/incident_changes.go b/internal/unifiedresources/incident_changes.go
new file mode 100644
index 0000000000..81de24242c
--- /dev/null
+++ b/internal/unifiedresources/incident_changes.go
@@ -0,0 +1,218 @@
+package unifiedresources
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+const (
+ metadataAlertIdentifier = "alert_identifier"
+ metadataAlertType = "alert_type"
+ metadataAlertLevel = "alert_level"
+ metadataAlertMessage = "alert_message"
+ metadataAlertValue = "alert_value"
+ metadataAlertThreshold = "alert_threshold"
+ metadataCommand = "command"
+ metadataSuccess = "success"
+ metadataOutputExcerpt = "output_excerpt"
+ metadataRunbookID = "runbook_id"
+ metadataOutcome = "outcome"
+ metadataAutomatic = "automatic"
+ metadataMessage = "message"
+)
+
+const resourceChangeOutputExcerptLimit = 500
+
+// AlertTimelineChange captures the alert-lifecycle details that should be
+// durable in the canonical resource history rather than only incident memory.
+type AlertTimelineChange struct {
+ AlertIdentifier string
+ AlertType string
+ AlertLevel string
+ AlertMessage string
+ AlertValue float64
+ AlertThreshold float64
+}
+
+// BuildAlertTimelineChange constructs a canonical resource change for alert
+// lifecycle events tied to a specific resource.
+func BuildAlertTimelineChange(resourceID string, kind ChangeKind, occurredAt time.Time, actor string, alert AlertTimelineChange) *ResourceChange {
+ resourceID = strings.TrimSpace(resourceID)
+ if resourceID == "" {
+ return nil
+ }
+
+ observedAt := occurredAt.UTC()
+ if observedAt.IsZero() {
+ observedAt = time.Now().UTC()
+ }
+
+ change := &ResourceChange{
+ ID: uuid.NewString(),
+ ObservedAt: observedAt,
+ ResourceID: resourceID,
+ Kind: kind,
+ SourceType: SourceHeuristic,
+ Confidence: ConfidenceHigh,
+ Actor: strings.TrimSpace(actor),
+ Reason: alertChangeReason(kind, alert),
+ Metadata: map[string]any{
+ metadataAlertIdentifier: strings.TrimSpace(alert.AlertIdentifier),
+ metadataAlertType: strings.TrimSpace(alert.AlertType),
+ metadataAlertLevel: strings.TrimSpace(alert.AlertLevel),
+ metadataAlertMessage: strings.TrimSpace(alert.AlertMessage),
+ metadataAlertValue: alert.AlertValue,
+ metadataAlertThreshold: alert.AlertThreshold,
+ },
+ }
+ if !occurredAt.IsZero() {
+ change.OccurredAt = cloneTimePtr(&occurredAt)
+ }
+ return change
+}
+
+// BuildCommandExecutionChange constructs a canonical resource change for a
+// command that was executed against a resource in response to an incident.
+func BuildCommandExecutionChange(resourceID, alertIdentifier, actor, command string, success bool, output string, details map[string]any) *ResourceChange {
+ resourceID = strings.TrimSpace(resourceID)
+ command = strings.TrimSpace(command)
+ if resourceID == "" || command == "" {
+ return nil
+ }
+
+ observedAt := time.Now().UTC()
+ change := &ResourceChange{
+ ID: uuid.NewString(),
+ ObservedAt: observedAt,
+ OccurredAt: cloneTimePtr(&observedAt),
+ ResourceID: resourceID,
+ Kind: ChangeCommandExecuted,
+ SourceType: SourceAgentAction,
+ Confidence: ConfidenceHigh,
+ Actor: strings.TrimSpace(actor),
+ Reason: commandExecutionReason(command, success),
+ Metadata: cloneChangeMetadata(details),
+ }
+ change.Metadata[metadataAlertIdentifier] = strings.TrimSpace(alertIdentifier)
+ change.Metadata[metadataCommand] = command
+ change.Metadata[metadataSuccess] = success
+ if excerpt := truncateResourceChangeOutput(output, resourceChangeOutputExcerptLimit); excerpt != "" {
+ change.Metadata[metadataOutputExcerpt] = excerpt
+ }
+ return change
+}
+
+// BuildRunbookExecutionChange constructs a canonical resource change for a
+// runbook that was executed against a resource in response to an incident.
+func BuildRunbookExecutionChange(resourceID, alertIdentifier, actor, runbookID, title, outcome string, automatic bool, message string, details map[string]any) *ResourceChange {
+ resourceID = strings.TrimSpace(resourceID)
+ runbookID = strings.TrimSpace(runbookID)
+ if resourceID == "" || runbookID == "" {
+ return nil
+ }
+
+ observedAt := time.Now().UTC()
+ change := &ResourceChange{
+ ID: uuid.NewString(),
+ ObservedAt: observedAt,
+ OccurredAt: cloneTimePtr(&observedAt),
+ ResourceID: resourceID,
+ Kind: ChangeRunbookExecuted,
+ SourceType: SourceUserAction,
+ Confidence: ConfidenceHigh,
+ Actor: strings.TrimSpace(actor),
+ Reason: runbookExecutionReason(title, outcome),
+ Metadata: cloneChangeMetadata(details),
+ }
+ if automatic {
+ change.SourceType = SourceAgentAction
+ }
+ change.Metadata[metadataAlertIdentifier] = strings.TrimSpace(alertIdentifier)
+ change.Metadata[metadataRunbookID] = runbookID
+ change.Metadata[metadataOutcome] = strings.TrimSpace(outcome)
+ change.Metadata[metadataAutomatic] = automatic
+ if trimmedTitle := strings.TrimSpace(title); trimmedTitle != "" {
+ change.Metadata["title"] = trimmedTitle
+ }
+ if trimmedMessage := strings.TrimSpace(message); trimmedMessage != "" {
+ change.Metadata[metadataMessage] = trimmedMessage
+ }
+ return change
+}
+
+func alertChangeReason(kind ChangeKind, alert AlertTimelineChange) string {
+ message := strings.TrimSpace(alert.AlertMessage)
+ switch kind {
+ case ChangeAlertFired:
+ if message != "" {
+ return message
+ }
+ return "Alert fired"
+ case ChangeAlertAcknowledged:
+ if message != "" {
+ return fmt.Sprintf("Alert acknowledged: %s", message)
+ }
+ return "Alert acknowledged"
+ case ChangeAlertUnacknowledged:
+ if message != "" {
+ return fmt.Sprintf("Alert unacknowledged: %s", message)
+ }
+ return "Alert unacknowledged"
+ case ChangeAlertResolved:
+ if message != "" {
+ return fmt.Sprintf("Alert resolved: %s", message)
+ }
+ return "Alert resolved"
+ default:
+ if message != "" {
+ return message
+ }
+ return "Alert event recorded"
+ }
+}
+
+func commandExecutionReason(command string, success bool) string {
+ status := "failed"
+ if success {
+ status = "succeeded"
+ }
+ return fmt.Sprintf("Command %s: %s", status, command)
+}
+
+func runbookExecutionReason(title, outcome string) string {
+ title = strings.TrimSpace(title)
+ if title == "" {
+ title = "runbook"
+ }
+ outcome = strings.TrimSpace(outcome)
+ if outcome == "" {
+ return fmt.Sprintf("Runbook %s executed", title)
+ }
+ return fmt.Sprintf("Runbook %s (%s)", title, outcome)
+}
+
+func cloneChangeMetadata(details map[string]any) map[string]any {
+ if len(details) == 0 {
+ return make(map[string]any)
+ }
+ cloned := make(map[string]any, len(details))
+ for key, value := range details {
+ cloned[key] = value
+ }
+ return cloned
+}
+
+func truncateResourceChangeOutput(output string, limit int) string {
+ output = strings.TrimSpace(output)
+ if output == "" || limit <= 0 {
+ return ""
+ }
+ runes := []rune(output)
+ if len(runes) <= limit {
+ return output
+ }
+ return string(runes[:limit]) + "..."
+}
diff --git a/internal/unifiedresources/monitor_adapter.go b/internal/unifiedresources/monitor_adapter.go
index 913078cd89..e7fde68c52 100644
--- a/internal/unifiedresources/monitor_adapter.go
+++ b/internal/unifiedresources/monitor_adapter.go
@@ -41,6 +41,16 @@ func (a *MonitorAdapter) currentRegistry() *ResourceRegistry {
return registry
}
+// RecordChange forwards canonical resource-history events into the underlying
+// resource store when monitoring has a durable store attached.
+func (a *MonitorAdapter) RecordChange(change ResourceChange) error {
+ registry := a.currentRegistry()
+ if registry == nil || registry.store == nil {
+ return nil
+ }
+ return registry.store.RecordChange(change)
+}
+
func (a *MonitorAdapter) replaceRegistry(snapshot models.StateSnapshot, recordsBySource map[DataSource][]IngestRecord) {
registry := a.currentRegistry()
if registry == nil {
diff --git a/internal/unifiedresources/monitor_adapter_read_state_test.go b/internal/unifiedresources/monitor_adapter_read_state_test.go
index 0f82ce694c..97a118dd32 100644
--- a/internal/unifiedresources/monitor_adapter_read_state_test.go
+++ b/internal/unifiedresources/monitor_adapter_read_state_test.go
@@ -209,3 +209,33 @@ func TestMonitorAdapterRecordsSupplementalChangeTimeline(t *testing.T) {
t.Fatalf("expected latest change to be a state transition, got %q", changes[0].Kind)
}
}
+
+func TestMonitorAdapterRecordChangeForwardsToStore(t *testing.T) {
+ store := NewMemoryStore()
+ adapter := NewMonitorAdapter(NewRegistry(store))
+ observedAt := time.Date(2026, 3, 20, 12, 0, 0, 0, time.UTC)
+
+ if err := adapter.RecordChange(ResourceChange{
+ ID: "alert-change-1",
+ ResourceID: "vm-1",
+ ObservedAt: observedAt,
+ OccurredAt: &observedAt,
+ Kind: ChangeAlertFired,
+ SourceType: SourceHeuristic,
+ Confidence: ConfidenceHigh,
+ Reason: "CPU threshold exceeded",
+ }); err != nil {
+ t.Fatalf("RecordChange: %v", err)
+ }
+
+ changes, err := store.GetRecentChanges("vm-1", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetRecentChanges: %v", err)
+ }
+ if len(changes) != 1 {
+ t.Fatalf("expected 1 forwarded change, got %d", len(changes))
+ }
+ if changes[0].Kind != ChangeAlertFired {
+ t.Fatalf("Kind = %q, want %q", changes[0].Kind, ChangeAlertFired)
+ }
+}
diff --git a/internal/unifiedresources/store_test.go b/internal/unifiedresources/store_test.go
index a59a3290e3..00792fb946 100644
--- a/internal/unifiedresources/store_test.go
+++ b/internal/unifiedresources/store_test.go
@@ -732,6 +732,62 @@ func TestCountRecentChangesByKind_RespectsFilters(t *testing.T) {
}
}
+func TestStorePersistsCanonicalIncidentTimelineKinds(t *testing.T) {
+ store := newTestStore(t)
+ base := time.Date(2026, 3, 20, 12, 0, 0, 0, time.UTC)
+ changes := []ResourceChange{
+ {
+ ID: "incident-kind-1",
+ ResourceID: "vm:incident",
+ ObservedAt: base.Add(-3 * time.Minute),
+ Kind: ChangeAlertFired,
+ SourceType: SourceHeuristic,
+ Confidence: ConfidenceHigh,
+ },
+ {
+ ID: "incident-kind-2",
+ ResourceID: "vm:incident",
+ ObservedAt: base.Add(-2 * time.Minute),
+ Kind: ChangeCommandExecuted,
+ SourceType: SourceAgentAction,
+ Confidence: ConfidenceHigh,
+ },
+ {
+ ID: "incident-kind-3",
+ ResourceID: "vm:incident",
+ ObservedAt: base.Add(-time.Minute),
+ Kind: ChangeRunbookExecuted,
+ SourceType: SourceAgentAction,
+ Confidence: ConfidenceHigh,
+ },
+ }
+ for _, change := range changes {
+ if err := store.RecordChange(change); err != nil {
+ t.Fatalf("RecordChange(%s): %v", change.ID, err)
+ }
+ }
+
+ results, err := store.GetRecentChangesFiltered("vm:incident", base.Add(-10*time.Minute), 10, ResourceChangeFilters{
+ Kinds: []ChangeKind{ChangeAlertFired, ChangeCommandExecuted, ChangeRunbookExecuted},
+ })
+ if err != nil {
+ t.Fatalf("GetRecentChangesFiltered: %v", err)
+ }
+ if len(results) != 3 {
+ t.Fatalf("expected 3 incident timeline changes, got %d", len(results))
+ }
+
+ counts, err := store.CountRecentChangesByKind("vm:incident", base.Add(-10*time.Minute))
+ if err != nil {
+ t.Fatalf("CountRecentChangesByKind: %v", err)
+ }
+ for _, kind := range []ChangeKind{ChangeAlertFired, ChangeCommandExecuted, ChangeRunbookExecuted} {
+ if counts[kind] != 1 {
+ t.Fatalf("CountRecentChangesByKind[%q] = %d, want 1", kind, counts[kind])
+ }
+ }
+}
+
func TestCountRecentChangesBySourceType_RespectsFilters(t *testing.T) {
store := newTestStore(t)
base := time.Date(2026, 3, 18, 12, 0, 0, 0, time.UTC)