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.

Project incident timelines from canonical history

rcourtmanda20a171ddc8
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index a84febc221..96729d084f 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -193,6 +193,12 @@ projection only: it may retain notes, analysis, command executions, runbooks,
and alert lifecycle breadcrumbs for one incident, but it must not become a
parallel source of truth for durable backend history that already belongs to
`internal/unifiedresources/`.
+When canonical resource history is available, the incident read path must also
+project alert lifecycle and remediation entries back out of the unified-resource
+timeline instead of reading those durable facts only from AI memory. AI memory
+may retain annotation-only entries such as notes and analysis, but the live
+incident timeline shown to handlers, prompts, and operators should read as one
+projection over canonical resource history plus investigation-local annotations.
The AI correlation root-cause engine also consumes the canonical unified-
resource relationship model directly, so cross-resource reasoning stays aligned
with the same relationship edges that back the resource API instead of
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index b49c20ed6b..455bc0a4ba 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -77,6 +77,10 @@ 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 monitor-owned incident store wiring must therefore attach the canonical
+resource timeline reader whenever the unified monitor adapter is present, so
+operator alert timelines and AI incident context project those lifecycle events
+from canonical history instead of reading a second monitoring-owned 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 d0dbb498df..ce7a1e7832 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -99,6 +99,10 @@ 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.
+The canonical monitor adapter therefore also serves read-side incident
+projection support: when a consumer needs an alert timeline, the incident view
+should read canonical resource changes back through the attached timeline store
+instead of rebuilding another durable event history beside `ResourceChange`.
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/internal/ai/memory/incidents.go b/internal/ai/memory/incidents.go
index 4099b3ce0c..1aa8a0d1f7 100644
--- a/internal/ai/memory/incidents.go
+++ b/internal/ai/memory/incidents.go
@@ -11,6 +11,7 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
"github.com/rs/zerolog/log"
)
@@ -153,25 +154,33 @@ type IncidentStoreConfig struct {
// investigation memory. Durable resource history belongs to the canonical
// unified-resource change model.
type IncidentStore struct {
- mu sync.RWMutex
- saveMu sync.Mutex
- incidents []*Incident
- maxIncidents int
- maxEvents int
- maxAge time.Duration
- dataDir string
- filePath string
+ mu sync.RWMutex
+ saveMu sync.Mutex
+ incidents []*Incident
+ maxIncidents int
+ maxEvents int
+ maxAge time.Duration
+ dataDir string
+ filePath string
+ resourceTimelineStore IncidentTimelineStore
}
const (
- defaultIncidentMaxIncidents = 500
- defaultIncidentMaxEvents = 120
- defaultIncidentMaxAgeDays = 90
- incidentFileName = "ai_incidents.json"
- maxIncidentFileSize = 20 * 1024 * 1024 // 20MB
- incidentStartMatchTolerance = 10 * time.Minute
+ defaultIncidentMaxIncidents = 500
+ defaultIncidentMaxEvents = 120
+ defaultIncidentMaxAgeDays = 90
+ incidentFileName = "ai_incidents.json"
+ maxIncidentFileSize = 20 * 1024 * 1024 // 20MB
+ incidentStartMatchTolerance = 10 * time.Minute
+ projectedIncidentChangeLimit = 256
)
+// IncidentTimelineStore exposes the canonical resource timeline used to derive
+// incident lifecycle and remediation history.
+type IncidentTimelineStore interface {
+ GetRecentChanges(canonicalID string, since time.Time, limit int) ([]unifiedresources.ResourceChange, error)
+}
+
// NewIncidentStore creates a new incident store with persistence.
func NewIncidentStore(cfg IncidentStoreConfig) *IncidentStore {
maxIncidents := cfg.MaxIncidents
@@ -207,6 +216,17 @@ func NewIncidentStore(cfg IncidentStoreConfig) *IncidentStore {
return store
}
+// SetResourceTimelineStore attaches the canonical resource timeline used to
+// project durable incident lifecycle and remediation history.
+func (s *IncidentStore) SetResourceTimelineStore(store IncidentTimelineStore) {
+ if s == nil {
+ return
+ }
+ s.mu.Lock()
+ s.resourceTimelineStore = store
+ s.mu.Unlock()
+}
+
// RecordAlertFired opens or updates an incident for a fired alert.
func (s *IncidentStore) RecordAlertFired(alert *alerts.Alert) {
if alert == nil {
@@ -220,14 +240,18 @@ func (s *IncidentStore) RecordAlertFired(alert *alerts.Alert) {
if incident == nil {
incident = newIncidentFromAlert(alert)
s.incidents = append(s.incidents, incident)
- s.addEventLocked(incident, IncidentEventAlertFired, formatAlertSummary(alert), map[string]interface{}{
- "type": alert.Type,
- "level": string(alert.Level),
- "value": alert.Value,
- "threshold": alert.Threshold,
- })
+ if !s.projectsFromCanonicalLocked() {
+ s.addEventLocked(incident, IncidentEventAlertFired, formatAlertSummary(alert), map[string]interface{}{
+ "type": alert.Type,
+ "level": string(alert.Level),
+ "value": alert.Value,
+ "threshold": alert.Threshold,
+ })
+ }
} else {
updateIncidentFromAlert(incident, alert)
+ incident.Status = IncidentStatusOpen
+ incident.ClosedAt = nil
}
s.trimLocked()
@@ -254,9 +278,11 @@ func (s *IncidentStore) RecordAlertAcknowledged(alert *alerts.Alert, user string
}
incident.AckUser = user
- s.addEventLocked(incident, IncidentEventAlertAcknowledged, "Alert acknowledged", map[string]interface{}{
- "user": user,
- })
+ if !s.projectsFromCanonicalLocked() {
+ s.addEventLocked(incident, IncidentEventAlertAcknowledged, "Alert acknowledged", map[string]interface{}{
+ "user": user,
+ })
+ }
s.trimLocked()
s.saveAsync()
@@ -277,9 +303,11 @@ func (s *IncidentStore) RecordAlertUnacknowledged(alert *alerts.Alert, user stri
incident.AckTime = nil
incident.AckUser = ""
- s.addEventLocked(incident, IncidentEventAlertUnacknowledged, "Alert unacknowledged", map[string]interface{}{
- "user": user,
- })
+ if !s.projectsFromCanonicalLocked() {
+ s.addEventLocked(incident, IncidentEventAlertUnacknowledged, "Alert unacknowledged", map[string]interface{}{
+ "user": user,
+ })
+ }
s.trimLocked()
s.saveAsync()
@@ -307,9 +335,11 @@ func (s *IncidentStore) RecordAlertResolved(alert *alerts.Alert, resolvedAt time
}
incident.ClosedAt = &resolvedAt
- s.addEventLocked(incident, IncidentEventAlertResolved, "Alert resolved", map[string]interface{}{
- "resolved_at": resolvedAt.Format(time.RFC3339),
- })
+ if !s.projectsFromCanonicalLocked() {
+ s.addEventLocked(incident, IncidentEventAlertResolved, "Alert resolved", map[string]interface{}{
+ "resolved_at": resolvedAt.Format(time.RFC3339),
+ })
+ }
s.trimLocked()
s.saveAsync()
@@ -367,6 +397,11 @@ func (s *IncidentStore) RecordCommand(alertIdentifier, command string, success b
if details == nil {
details = make(map[string]interface{})
}
+ if incident.ResourceID == "" {
+ if resourceID, ok := details["resource_id"].(string); ok {
+ incident.ResourceID = strings.TrimSpace(resourceID)
+ }
+ }
details["command"] = command
details["success"] = success
if output != "" {
@@ -379,7 +414,9 @@ func (s *IncidentStore) RecordCommand(alertIdentifier, command string, success b
}
summary := fmt.Sprintf("Command %s: %s", status, command)
- s.addEventLocked(incident, IncidentEventCommand, summary, details)
+ if !s.projectsFromCanonicalLocked() {
+ s.addEventLocked(incident, IncidentEventCommand, summary, details)
+ }
s.trimLocked()
s.saveAsync()
}
@@ -414,7 +451,9 @@ func (s *IncidentStore) RecordRunbook(alertIdentifier, runbookID, title string,
details["message"] = message
}
- s.addEventLocked(incident, IncidentEventRunbook, summary, details)
+ if !s.projectsFromCanonicalLocked() {
+ s.addEventLocked(incident, IncidentEventRunbook, summary, details)
+ }
s.trimLocked()
s.saveAsync()
}
@@ -461,13 +500,15 @@ func (s *IncidentStore) GetTimelineByAlertIdentifier(alertIdentifier string) *In
}
s.mu.RLock()
- defer s.mu.RUnlock()
+ incident := cloneIncident(s.findLatestIncidentByAlertIdentifierLocked(alertIdentifier))
+ timelineStore := s.resourceTimelineStore
+ maxAge := s.maxAge
+ s.mu.RUnlock()
- incident := s.findLatestIncidentByAlertIdentifierLocked(alertIdentifier)
if incident == nil {
- return nil
+ return s.projectIncidentFromCanonical(alertIdentifier, time.Time{}, timelineStore, maxAge)
}
- return cloneIncident(incident)
+ return s.projectIncident(incident, timelineStore)
}
// GetTimelineByAlertAt returns the incident closest to the provided start time for an alert.
@@ -480,8 +521,6 @@ func (s *IncidentStore) GetTimelineByAlertAt(alertIdentifier string, startedAt t
}
s.mu.RLock()
- defer s.mu.RUnlock()
-
var best *Incident
var bestDelta time.Duration
for _, incident := range s.incidents {
@@ -497,11 +536,14 @@ func (s *IncidentStore) GetTimelineByAlertAt(alertIdentifier string, startedAt t
bestDelta = delta
}
}
+ timelineStore := s.resourceTimelineStore
+ maxAge := s.maxAge
+ s.mu.RUnlock()
if best == nil || bestDelta > incidentStartMatchTolerance {
- return nil
+ return s.projectIncidentFromCanonical(alertIdentifier, startedAt, timelineStore, maxAge)
}
- return cloneIncident(best)
+ return s.projectIncident(cloneIncident(best), timelineStore)
}
// ListIncidentsByResource returns recent incidents for a resource.
@@ -511,8 +553,6 @@ func (s *IncidentStore) ListIncidentsByResource(resourceID string, limit int) []
}
s.mu.RLock()
- defer s.mu.RUnlock()
-
var matches []*Incident
for i := len(s.incidents) - 1; i >= 0; i-- {
incident := s.incidents[i]
@@ -523,7 +563,17 @@ func (s *IncidentStore) ListIncidentsByResource(resourceID string, limit int) []
}
}
}
- return matches
+ timelineStore := s.resourceTimelineStore
+ s.mu.RUnlock()
+
+ if timelineStore == nil {
+ return matches
+ }
+ projected := make([]*Incident, 0, len(matches))
+ for _, incident := range matches {
+ projected = append(projected, s.projectIncident(incident, timelineStore))
+ }
+ return projected
}
// FormatForAlert returns a condensed incident timeline for prompt injection.
@@ -591,22 +641,30 @@ func (s *IncidentStore) FormatForPatrol(limit int) string {
}
s.mu.RLock()
- defer s.mu.RUnlock()
+ snapshot := make([]*Incident, 0, len(s.incidents))
+ for i := len(s.incidents) - 1; i >= 0 && len(snapshot) < limit; i-- {
+ if incident := s.incidents[i]; incident != nil {
+ snapshot = append(snapshot, cloneIncident(incident))
+ }
+ }
+ timelineStore := s.resourceTimelineStore
+ s.mu.RUnlock()
- if len(s.incidents) == 0 {
+ if len(snapshot) == 0 {
return ""
}
+ if timelineStore != nil {
+ for i := range snapshot {
+ snapshot[i] = s.projectIncident(snapshot[i], timelineStore)
+ }
+ }
+
var b strings.Builder
b.WriteString("\n\n## Incident Memory\n")
b.WriteString("Recent incidents across infrastructure:\n")
- count := 0
- for i := len(s.incidents) - 1; i >= 0 && count < limit; i-- {
- incident := s.incidents[i]
- if incident == nil {
- continue
- }
+ for _, incident := range snapshot {
status := string(incident.Status)
if incident.Acknowledged && incident.Status == IncidentStatusOpen {
status = "acknowledged"
@@ -642,12 +700,369 @@ func (s *IncidentStore) FormatForPatrol(limit int) string {
b.WriteString(truncateOutput(incident.Message, 80))
}
b.WriteString("\n")
- count++
}
return b.String()
}
+func (s *IncidentStore) projectsFromCanonicalLocked() bool {
+ return s.resourceTimelineStore != nil
+}
+
+func (s *IncidentStore) projectIncident(incident *Incident, timelineStore IncidentTimelineStore) *Incident {
+ if incident == nil || timelineStore == nil {
+ return incident
+ }
+
+ projectedEvents := s.loadProjectedIncidentEvents(incident, timelineStore)
+ if len(projectedEvents) == 0 {
+ return incident
+ }
+
+ projected := cloneIncident(incident)
+ projectedKinds := make(map[IncidentEventType]bool, len(projectedEvents))
+ for _, event := range projectedEvents {
+ projectedKinds[event.Type] = true
+ }
+
+ filtered := make([]IncidentEvent, 0, len(projected.Events)+len(projectedEvents))
+ for _, event := range projected.Events {
+ if isCanonicalProjectedIncidentEventType(event.Type) && projectedKinds[event.Type] {
+ continue
+ }
+ filtered = append(filtered, cloneIncidentEvent(event))
+ }
+ filtered = append(filtered, projectedEvents...)
+ sortIncidentEvents(filtered)
+ projected.Events = filtered
+ applyProjectedIncidentState(projected, projectedEvents)
+ return projected
+}
+
+func (s *IncidentStore) projectIncidentFromCanonical(alertIdentifier string, startedAt time.Time, timelineStore IncidentTimelineStore, maxAge time.Duration) *Incident {
+ if timelineStore == nil || strings.TrimSpace(alertIdentifier) == "" {
+ return nil
+ }
+
+ since := time.Now().Add(-defaultIncidentMaxAgeDays * 24 * time.Hour)
+ if maxAge > 0 {
+ since = time.Now().Add(-maxAge)
+ }
+
+ changes, err := timelineStore.GetRecentChanges("", since, projectedIncidentChangeLimit)
+ if err != nil || len(changes) == 0 {
+ return nil
+ }
+
+ events := make([]IncidentEvent, 0, len(changes))
+ projected := &Incident{
+ ID: "projected-" + strings.TrimSpace(alertIdentifier),
+ AlertIdentifier: strings.TrimSpace(alertIdentifier),
+ Status: IncidentStatusOpen,
+ }
+ for _, change := range changes {
+ if projectedAlertIdentifier(change) != projected.AlertIdentifier {
+ continue
+ }
+ event, ok := incidentEventFromResourceChange(change)
+ if !ok {
+ continue
+ }
+ events = append(events, event)
+ hydrateIncidentFromCanonicalChange(projected, change)
+ }
+ if len(events) == 0 {
+ return nil
+ }
+
+ sortIncidentEvents(events)
+ projected.Events = events
+ if !startedAt.IsZero() {
+ openAt := projected.OpenedAt
+ if openAt.IsZero() {
+ openAt = events[0].Timestamp
+ }
+ delta := openAt.Sub(startedAt)
+ if delta < 0 {
+ delta = -delta
+ }
+ if delta > incidentStartMatchTolerance {
+ return nil
+ }
+ }
+ applyProjectedIncidentState(projected, events)
+ return projected
+}
+
+func (s *IncidentStore) loadProjectedIncidentEvents(incident *Incident, timelineStore IncidentTimelineStore) []IncidentEvent {
+ if incident == nil || timelineStore == nil {
+ return nil
+ }
+
+ resourceID := strings.TrimSpace(incident.ResourceID)
+ alertIdentifier := strings.TrimSpace(incident.AlertIdentifier)
+ if resourceID == "" || alertIdentifier == "" {
+ return nil
+ }
+
+ since := incident.OpenedAt
+ if since.IsZero() {
+ since = time.Now().Add(-defaultIncidentMaxAgeDays * 24 * time.Hour)
+ } else {
+ since = since.Add(-incidentStartMatchTolerance)
+ }
+
+ changes, err := timelineStore.GetRecentChanges(resourceID, since, projectedIncidentChangeLimit)
+ if err != nil || len(changes) == 0 {
+ return nil
+ }
+
+ events := make([]IncidentEvent, 0, len(changes))
+ for _, change := range changes {
+ if projectedAlertIdentifier(change) != alertIdentifier {
+ continue
+ }
+ event, ok := incidentEventFromResourceChange(change)
+ if !ok {
+ continue
+ }
+ events = append(events, event)
+ hydrateIncidentFromCanonicalChange(incident, change)
+ }
+ sortIncidentEvents(events)
+ return events
+}
+
+func hydrateIncidentFromCanonicalChange(incident *Incident, change unifiedresources.ResourceChange) {
+ if incident == nil {
+ return
+ }
+ if resourceID := strings.TrimSpace(change.ResourceID); resourceID != "" && incident.ResourceID == "" {
+ incident.ResourceID = resourceID
+ }
+ if alertType, ok := stringMetadata(change.Metadata, unifiedresources.MetadataAlertType); ok && incident.AlertType == "" {
+ incident.AlertType = alertType
+ }
+ if level, ok := stringMetadata(change.Metadata, unifiedresources.MetadataAlertLevel); ok && incident.Level == "" {
+ incident.Level = level
+ }
+ if message, ok := stringMetadata(change.Metadata, unifiedresources.MetadataAlertMessage); ok && incident.Message == "" {
+ incident.Message = message
+ }
+ if incident.OpenedAt.IsZero() {
+ incident.OpenedAt = incidentEventTimestamp(change)
+ }
+}
+
+func applyProjectedIncidentState(incident *Incident, events []IncidentEvent) {
+ if incident == nil || len(events) == 0 {
+ return
+ }
+
+ for _, event := range events {
+ if incident.OpenedAt.IsZero() || (!event.Timestamp.IsZero() && event.Timestamp.Before(incident.OpenedAt)) {
+ incident.OpenedAt = event.Timestamp
+ }
+
+ switch event.Type {
+ case IncidentEventAlertFired:
+ incident.Status = IncidentStatusOpen
+ incident.ClosedAt = nil
+ case IncidentEventAlertAcknowledged:
+ incident.Acknowledged = true
+ timestamp := event.Timestamp
+ incident.AckTime = &timestamp
+ incident.AckUser = eventActor(event)
+ case IncidentEventAlertUnacknowledged:
+ incident.Acknowledged = false
+ incident.AckTime = nil
+ incident.AckUser = ""
+ case IncidentEventAlertResolved:
+ incident.Status = IncidentStatusResolved
+ timestamp := event.Timestamp
+ incident.ClosedAt = &timestamp
+ }
+ }
+}
+
+func incidentEventFromResourceChange(change unifiedresources.ResourceChange) (IncidentEvent, bool) {
+ eventType, ok := incidentEventTypeFromChangeKind(change.Kind)
+ if !ok {
+ return IncidentEvent{}, false
+ }
+
+ details := cloneIncidentEventDetails(change.Metadata)
+ if user := strings.TrimSpace(change.Actor); user != "" {
+ switch eventType {
+ case IncidentEventAlertAcknowledged, IncidentEventAlertUnacknowledged:
+ details["user"] = user
+ }
+ }
+
+ return IncidentEvent{
+ ID: strings.TrimSpace(change.ID),
+ Type: eventType,
+ Timestamp: incidentEventTimestamp(change),
+ Summary: incidentEventSummaryFromChange(change, eventType),
+ Details: details,
+ }, true
+}
+
+func incidentEventTypeFromChangeKind(kind unifiedresources.ChangeKind) (IncidentEventType, bool) {
+ switch kind {
+ case unifiedresources.ChangeAlertFired:
+ return IncidentEventAlertFired, true
+ case unifiedresources.ChangeAlertAcknowledged:
+ return IncidentEventAlertAcknowledged, true
+ case unifiedresources.ChangeAlertUnacknowledged:
+ return IncidentEventAlertUnacknowledged, true
+ case unifiedresources.ChangeAlertResolved:
+ return IncidentEventAlertResolved, true
+ case unifiedresources.ChangeCommandExecuted:
+ return IncidentEventCommand, true
+ case unifiedresources.ChangeRunbookExecuted:
+ return IncidentEventRunbook, true
+ default:
+ return "", false
+ }
+}
+
+func incidentEventSummaryFromChange(change unifiedresources.ResourceChange, eventType IncidentEventType) string {
+ switch eventType {
+ case IncidentEventAlertFired:
+ if alertType, ok := stringMetadata(change.Metadata, unifiedresources.MetadataAlertType); ok {
+ level, _ := stringMetadata(change.Metadata, unifiedresources.MetadataAlertLevel)
+ value, hasValue := floatMetadata(change.Metadata, unifiedresources.MetadataAlertValue)
+ threshold, hasThreshold := floatMetadata(change.Metadata, unifiedresources.MetadataAlertThreshold)
+ if hasValue || hasThreshold {
+ return fmt.Sprintf("Alert triggered: %s (%s %.1f >= %.1f)", alertType, level, value, threshold)
+ }
+ if level != "" {
+ return fmt.Sprintf("Alert triggered: %s (%s)", alertType, level)
+ }
+ }
+ return "Alert triggered"
+ case IncidentEventAlertAcknowledged:
+ return "Alert acknowledged"
+ case IncidentEventAlertUnacknowledged:
+ return "Alert unacknowledged"
+ case IncidentEventAlertResolved:
+ return "Alert resolved"
+ default:
+ if summary := strings.TrimSpace(change.Reason); summary != "" {
+ return summary
+ }
+ return unifiedresources.ChangeKindLabel(change.Kind)
+ }
+}
+
+func incidentEventTimestamp(change unifiedresources.ResourceChange) time.Time {
+ if change.OccurredAt != nil && !change.OccurredAt.IsZero() {
+ return change.OccurredAt.UTC()
+ }
+ if !change.ObservedAt.IsZero() {
+ return change.ObservedAt.UTC()
+ }
+ return time.Now().UTC()
+}
+
+func projectedAlertIdentifier(change unifiedresources.ResourceChange) string {
+ value, _ := stringMetadata(change.Metadata, unifiedresources.MetadataAlertIdentifier)
+ return value
+}
+
+func stringMetadata(metadata map[string]any, key string) (string, bool) {
+ if len(metadata) == 0 {
+ return "", false
+ }
+ value, ok := metadata[key]
+ if !ok {
+ return "", false
+ }
+ str, ok := value.(string)
+ if !ok {
+ return "", false
+ }
+ str = strings.TrimSpace(str)
+ if str == "" {
+ return "", false
+ }
+ return str, true
+}
+
+func floatMetadata(metadata map[string]any, key string) (float64, bool) {
+ if len(metadata) == 0 {
+ return 0, false
+ }
+ value, ok := metadata[key]
+ if !ok {
+ return 0, false
+ }
+ switch typed := value.(type) {
+ case float64:
+ return typed, true
+ case float32:
+ return float64(typed), true
+ case int:
+ return float64(typed), true
+ case int64:
+ return float64(typed), true
+ default:
+ return 0, false
+ }
+}
+
+func eventActor(event IncidentEvent) string {
+ if event.Details == nil {
+ return ""
+ }
+ value, ok := event.Details["user"].(string)
+ if !ok {
+ return ""
+ }
+ return strings.TrimSpace(value)
+}
+
+func isCanonicalProjectedIncidentEventType(eventType IncidentEventType) bool {
+ switch eventType {
+ case IncidentEventAlertFired,
+ IncidentEventAlertAcknowledged,
+ IncidentEventAlertUnacknowledged,
+ IncidentEventAlertResolved,
+ IncidentEventCommand,
+ IncidentEventRunbook:
+ return true
+ default:
+ return false
+ }
+}
+
+func sortIncidentEvents(events []IncidentEvent) {
+ sort.Slice(events, func(i, j int) bool {
+ if events[i].Timestamp.Equal(events[j].Timestamp) {
+ return events[i].ID < events[j].ID
+ }
+ return events[i].Timestamp.Before(events[j].Timestamp)
+ })
+}
+
+func cloneIncidentEvent(event IncidentEvent) IncidentEvent {
+ cloned := event
+ cloned.Details = cloneIncidentEventDetails(event.Details)
+ return cloned
+}
+
+func cloneIncidentEventDetails(details map[string]any) map[string]interface{} {
+ if len(details) == 0 {
+ return map[string]interface{}{}
+ }
+ cloned := make(map[string]interface{}, len(details))
+ for key, value := range details {
+ cloned[key] = value
+ }
+ return cloned
+}
+
func newIncidentFromAlert(alert *alerts.Alert) *Incident {
openedAt := alert.StartTime
if openedAt.IsZero() {
diff --git a/internal/ai/memory/incidents_test.go b/internal/ai/memory/incidents_test.go
index 1e58b9ba66..49aa71cb5e 100644
--- a/internal/ai/memory/incidents_test.go
+++ b/internal/ai/memory/incidents_test.go
@@ -7,6 +7,7 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
func TestIncidentJSONCanonicalOutput(t *testing.T) {
@@ -103,6 +104,78 @@ func TestIncidentStore_RecordTimeline(t *testing.T) {
}
}
+func TestIncidentStore_ProjectsCanonicalTimelineWhenAttached(t *testing.T) {
+ store := NewIncidentStore(IncidentStoreConfig{
+ MaxIncidents: 10,
+ MaxEventsPerIncident: 20,
+ MaxAgeDays: 30,
+ })
+ canonicalStore := unifiedresources.NewMemoryStore()
+ store.SetResourceTimelineStore(canonicalStore)
+
+ alertStartedAt := time.Now().UTC().Add(-15 * time.Minute).Truncate(time.Second)
+ alert := &alerts.Alert{
+ ID: "alert-projected-1",
+ Type: "cpu",
+ Level: alerts.AlertLevelCritical,
+ ResourceID: "res-projected-1",
+ ResourceName: "vm-projected-1",
+ StartTime: alertStartedAt,
+ Value: 91,
+ Threshold: 80,
+ }
+
+ store.RecordAlertFired(alert)
+ store.RecordAnalysis(alert.ID, "Pulse Patrol analysis completed", nil)
+
+ fired := unifiedresources.BuildAlertTimelineChange(alert.ResourceID, unifiedresources.ChangeAlertFired, alert.StartTime, "", unifiedresources.AlertTimelineChange{
+ AlertIdentifier: alert.ID,
+ AlertType: alert.Type,
+ AlertLevel: string(alert.Level),
+ AlertMessage: alert.Message,
+ AlertValue: alert.Value,
+ AlertThreshold: alert.Threshold,
+ })
+ runbook := unifiedresources.BuildRunbookExecutionChange(alert.ResourceID, alert.ID, "agent:pulse-patrol", "rb-1", "Restart service", "resolved", true, "Recovered", nil)
+ resolvedAt := alert.StartTime.Add(5 * time.Minute)
+ resolved := unifiedresources.BuildAlertTimelineChange(alert.ResourceID, unifiedresources.ChangeAlertResolved, resolvedAt, "", unifiedresources.AlertTimelineChange{
+ AlertIdentifier: alert.ID,
+ AlertType: alert.Type,
+ AlertLevel: string(alert.Level),
+ AlertMessage: "CPU normalized",
+ })
+ for _, change := range []*unifiedresources.ResourceChange{fired, runbook, resolved} {
+ if err := canonicalStore.RecordChange(*change); err != nil {
+ t.Fatalf("RecordChange(%s): %v", change.ID, err)
+ }
+ }
+
+ timeline := store.GetTimelineByAlertIdentifier(alert.ID)
+ if timeline == nil {
+ t.Fatal("expected projected timeline")
+ }
+ if timeline.Status != IncidentStatusResolved {
+ t.Fatalf("Status = %q, want %q", timeline.Status, IncidentStatusResolved)
+ }
+
+ foundAnalysis := false
+ foundRunbook := false
+ for _, event := range timeline.Events {
+ switch event.Type {
+ case IncidentEventAnalysis:
+ foundAnalysis = true
+ case IncidentEventRunbook:
+ foundRunbook = true
+ }
+ }
+ if !foundAnalysis {
+ t.Fatal("expected analysis event to remain in projected timeline")
+ }
+ if !foundRunbook {
+ t.Fatal("expected runbook event to be projected from canonical history")
+ }
+}
+
func TestIncidentStore_GetTimelineByAlertAt(t *testing.T) {
store := NewIncidentStore(IncidentStoreConfig{
MaxIncidents: 10,
diff --git a/internal/ai/service.go b/internal/ai/service.go
index 0dce6ec496..322d32f303 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -326,12 +326,17 @@ func (s *Service) SetOrgID(orgID string) {
}
oldStore := s.resourceExportStore
+ incidentStore := s.incidentStore
persistence := s.persistence
s.orgID = normalized
s.resourceExportStore = nil
s.resourceExportStoreOrgID = ""
s.mu.Unlock()
+ if incidentStore != nil {
+ incidentStore.SetResourceTimelineStore(nil)
+ }
+
if oldStore != nil {
if err := oldStore.Close(); err != nil {
log.Warn().Err(err).Str("orgID", normalized).Msg("failed to close previous unified resource export store")
@@ -352,7 +357,11 @@ func (s *Service) SetOrgID(orgID string) {
if s.orgID == normalized && s.resourceExportStore == nil {
s.resourceExportStore = store
s.resourceExportStoreOrgID = normalized
+ incidentStore = s.incidentStore
s.mu.Unlock()
+ if incidentStore != nil {
+ incidentStore.SetResourceTimelineStore(store)
+ }
return
}
s.mu.Unlock()
@@ -757,6 +766,9 @@ func (s *Service) SetIncidentStore(store *memory.IncidentStore) {
s.mu.Lock()
defer s.mu.Unlock()
s.incidentStore = store
+ if store != nil {
+ store.SetResourceTimelineStore(s.resourceExportStore)
+ }
if s.patrolService != nil {
s.patrolService.SetIncidentStore(store)
@@ -1002,10 +1014,15 @@ func (s *Service) Stop() {
s.mu.Lock()
store := s.resourceExportStore
+ incidentStore := s.incidentStore
s.resourceExportStore = nil
s.resourceExportStoreOrgID = ""
defer s.mu.Unlock()
+ if incidentStore != nil {
+ incidentStore.SetResourceTimelineStore(nil)
+ }
+
if s.infraDiscoveryCancel != nil {
s.infraDiscoveryCancel()
s.infraDiscoveryCancel = nil
diff --git a/internal/ai/service_coverage_imp_test.go b/internal/ai/service_coverage_imp_test.go
index 671f6d38e7..2efe3c05ea 100644
--- a/internal/ai/service_coverage_imp_test.go
+++ b/internal/ai/service_coverage_imp_test.go
@@ -9,6 +9,7 @@ import (
"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/alerts"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
@@ -191,6 +192,62 @@ func TestService_RecordIncidentRunbook(t *testing.T) {
}
}
+func TestService_SetIncidentStore_AttachesCanonicalTimelineProjection(t *testing.T) {
+ svc := NewService(nil, nil)
+ canonicalStore := unifiedresources.NewMemoryStore()
+
+ svc.resourceExportStore = canonicalStore
+ svc.resourceExportStoreOrgID = svc.orgID
+
+ incidentStore := memory.NewIncidentStore(memory.IncidentStoreConfig{})
+ svc.SetIncidentStore(incidentStore)
+
+ alertStartedAt := time.Now().UTC().Add(-15 * time.Minute).Truncate(time.Second)
+ alert := &alerts.Alert{
+ ID: "alert-service-projected",
+ Type: "cpu",
+ Level: alerts.AlertLevelCritical,
+ ResourceID: "vm-service-projected",
+ ResourceName: "vm-service-projected",
+ StartTime: alertStartedAt,
+ Value: 94,
+ Threshold: 80,
+ }
+ incidentStore.RecordAlertFired(alert)
+ incidentStore.RecordAnalysis(alert.ID, "analysis", nil)
+
+ for _, change := range []*unifiedresources.ResourceChange{
+ unifiedresources.BuildAlertTimelineChange(alert.ResourceID, unifiedresources.ChangeAlertFired, alertStartedAt, "", unifiedresources.AlertTimelineChange{
+ AlertIdentifier: alert.ID,
+ AlertType: alert.Type,
+ AlertLevel: string(alert.Level),
+ AlertValue: alert.Value,
+ AlertThreshold: alert.Threshold,
+ }),
+ unifiedresources.BuildRunbookExecutionChange(alert.ResourceID, alert.ID, "agent:pulse-patrol", "rb-service", "Restart service", "resolved", true, "ok", nil),
+ } {
+ if err := canonicalStore.RecordChange(*change); err != nil {
+ t.Fatalf("RecordChange(%s): %v", change.ID, err)
+ }
+ }
+
+ timeline := incidentStore.GetTimelineByAlertIdentifier(alert.ID)
+ if timeline == nil {
+ t.Fatal("expected projected timeline")
+ }
+
+ foundRunbook := false
+ for _, event := range timeline.Events {
+ if event.Type == memory.IncidentEventRunbook {
+ foundRunbook = true
+ break
+ }
+ }
+ if !foundRunbook {
+ t.Fatal("expected canonical runbook event in projected timeline")
+ }
+}
+
func TestAbsFloat(t *testing.T) {
tests := []struct {
input float64
diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.go
index d3e02ce8fe..7fde95c879 100644
--- a/internal/monitoring/canonical_guardrails_test.go
+++ b/internal/monitoring/canonical_guardrails_test.go
@@ -8,6 +8,7 @@ import (
"testing"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/memory"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
@@ -91,9 +92,11 @@ func TestLegacyMemorySourceAliasesRemainCanonicalized(t *testing.T) {
func TestAlertLifecycleCanonicalChangesRemainWritable(t *testing.T) {
store := unifiedresources.NewMemoryStore()
+ incidentStore := memory.NewIncidentStore(memory.IncidentStoreConfig{})
monitor := &Monitor{
- resourceStore: unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(store)),
+ incidentStore: incidentStore,
}
+ monitor.SetResourceStore(unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(store)))
startedAt := time.Date(2026, 3, 20, 9, 0, 0, 0, time.UTC)
alert := &alerts.Alert{
@@ -117,4 +120,12 @@ func TestAlertLifecycleCanonicalChangesRemainWritable(t *testing.T) {
if changes[0].Kind != unifiedresources.ChangeAlertFired {
t.Fatalf("Kind = %q, want %q", changes[0].Kind, unifiedresources.ChangeAlertFired)
}
+
+ timeline := incidentStore.GetTimelineByAlertIdentifier(alert.ID)
+ if timeline == nil {
+ t.Fatal("expected incident timeline")
+ }
+ if len(timeline.Events) != 1 || timeline.Events[0].Type != memory.IncidentEventAlertFired {
+ t.Fatalf("expected projected alert-fired event, got %#v", timeline.Events)
+ }
}
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index fc911575e6..6c058d1a9d 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -3853,9 +3853,18 @@ func (m *Monitor) DisableTemperatureMonitoring() {
func (m *Monitor) SetResourceStore(store ResourceStoreInterface) {
m.mu.Lock()
m.resourceStore = store
+ incidentStore := m.incidentStore
m.mu.Unlock()
log.Info().Msg("resource store set for polling optimization")
+ if incidentStore != nil {
+ if timelineStore, ok := store.(memory.IncidentTimelineStore); ok {
+ incidentStore.SetResourceTimelineStore(timelineStore)
+ } else {
+ incidentStore.SetResourceTimelineStore(nil)
+ }
+ }
+
// Immediately backfill the store from current state so ReadState
// consumers have data as soon as the store is wired.
// Guard against minimally initialized monitors (e.g., test fixtures
diff --git a/internal/unifiedresources/change_presentation_test.go b/internal/unifiedresources/change_presentation_test.go
index 4bdca59d02..7727c65c4e 100644
--- a/internal/unifiedresources/change_presentation_test.go
+++ b/internal/unifiedresources/change_presentation_test.go
@@ -196,7 +196,7 @@ func TestBuildIncidentTimelineChanges(t *testing.T) {
if alertChange.SourceType != SourceHeuristic {
t.Fatalf("SourceType = %q, want %q", alertChange.SourceType, SourceHeuristic)
}
- if got := alertChange.Metadata[metadataAlertIdentifier]; got != "alert-1" {
+ if got := alertChange.Metadata[MetadataAlertIdentifier]; got != "alert-1" {
t.Fatalf("alert_identifier = %#v, want alert-1", got)
}
@@ -212,7 +212,7 @@ func TestBuildIncidentTimelineChanges(t *testing.T) {
if commandChange.SourceType != SourceAgentAction {
t.Fatalf("SourceType = %q, want %q", commandChange.SourceType, SourceAgentAction)
}
- if got := commandChange.Metadata[metadataOutputExcerpt].(string); len(got) <= resourceChangeOutputExcerptLimit {
+ if got := commandChange.Metadata[MetadataOutputExcerpt].(string); len(got) <= resourceChangeOutputExcerptLimit {
t.Fatalf("expected truncated output excerpt to include ellipsis, got length %d", len(got))
}
@@ -226,7 +226,7 @@ func TestBuildIncidentTimelineChanges(t *testing.T) {
if runbookChange.SourceType != SourceAgentAction {
t.Fatalf("SourceType = %q, want %q", runbookChange.SourceType, SourceAgentAction)
}
- if got := runbookChange.Metadata[metadataRunbookID]; got != "rb-1" {
+ if got := runbookChange.Metadata[MetadataRunbookID]; got != "rb-1" {
t.Fatalf("runbook_id = %#v, want rb-1", got)
}
}
diff --git a/internal/unifiedresources/incident_changes.go b/internal/unifiedresources/incident_changes.go
index 81de24242c..bc065dfaf7 100644
--- a/internal/unifiedresources/incident_changes.go
+++ b/internal/unifiedresources/incident_changes.go
@@ -9,19 +9,19 @@ import (
)
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"
+ 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
@@ -60,12 +60,12 @@ func BuildAlertTimelineChange(resourceID string, kind ChangeKind, occurredAt tim
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,
+ 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() {
@@ -96,11 +96,11 @@ func BuildCommandExecutionChange(resourceID, alertIdentifier, actor, command str
Reason: commandExecutionReason(command, success),
Metadata: cloneChangeMetadata(details),
}
- change.Metadata[metadataAlertIdentifier] = strings.TrimSpace(alertIdentifier)
- change.Metadata[metadataCommand] = command
- change.Metadata[metadataSuccess] = success
+ change.Metadata[MetadataAlertIdentifier] = strings.TrimSpace(alertIdentifier)
+ change.Metadata[MetadataCommand] = command
+ change.Metadata[MetadataSuccess] = success
if excerpt := truncateResourceChangeOutput(output, resourceChangeOutputExcerptLimit); excerpt != "" {
- change.Metadata[metadataOutputExcerpt] = excerpt
+ change.Metadata[MetadataOutputExcerpt] = excerpt
}
return change
}
@@ -130,15 +130,15 @@ func BuildRunbookExecutionChange(resourceID, alertIdentifier, actor, runbookID,
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
+ 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
+ change.Metadata[MetadataMessage] = trimmedMessage
}
return change
}
diff --git a/internal/unifiedresources/monitor_adapter.go b/internal/unifiedresources/monitor_adapter.go
index e7fde68c52..f604464cbd 100644
--- a/internal/unifiedresources/monitor_adapter.go
+++ b/internal/unifiedresources/monitor_adapter.go
@@ -51,6 +51,16 @@ func (a *MonitorAdapter) RecordChange(change ResourceChange) error {
return registry.store.RecordChange(change)
}
+// GetRecentChanges forwards canonical resource-history reads into the
+// underlying resource store when monitoring has a durable store attached.
+func (a *MonitorAdapter) GetRecentChanges(canonicalID string, since time.Time, limit int) ([]ResourceChange, error) {
+ registry := a.currentRegistry()
+ if registry == nil || registry.store == nil {
+ return nil, nil
+ }
+ return registry.store.GetRecentChanges(canonicalID, since, limit)
+}
+
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 97a118dd32..ed5e6d7427 100644
--- a/internal/unifiedresources/monitor_adapter_read_state_test.go
+++ b/internal/unifiedresources/monitor_adapter_read_state_test.go
@@ -239,3 +239,31 @@ func TestMonitorAdapterRecordChangeForwardsToStore(t *testing.T) {
t.Fatalf("Kind = %q, want %q", changes[0].Kind, ChangeAlertFired)
}
}
+
+func TestMonitorAdapterGetRecentChangesForwardsToStore(t *testing.T) {
+ store := NewMemoryStore()
+ adapter := NewMonitorAdapter(NewRegistry(store))
+ observedAt := time.Date(2026, 3, 20, 12, 5, 0, 0, time.UTC)
+
+ if err := store.RecordChange(ResourceChange{
+ ID: "command-change-1",
+ ResourceID: "vm-2",
+ ObservedAt: observedAt,
+ Kind: ChangeCommandExecuted,
+ SourceType: SourceAgentAction,
+ Confidence: ConfidenceHigh,
+ }); err != nil {
+ t.Fatalf("RecordChange: %v", err)
+ }
+
+ changes, err := adapter.GetRecentChanges("vm-2", 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 != ChangeCommandExecuted {
+ t.Fatalf("Kind = %q, want %q", changes[0].Kind, ChangeCommandExecuted)
+ }
+}
diff --git a/internal/unifiedresources/store_test.go b/internal/unifiedresources/store_test.go
index 00792fb946..ce0eef4e68 100644
--- a/internal/unifiedresources/store_test.go
+++ b/internal/unifiedresources/store_test.go
@@ -786,6 +786,10 @@ func TestStorePersistsCanonicalIncidentTimelineKinds(t *testing.T) {
t.Fatalf("CountRecentChangesByKind[%q] = %d, want 1", kind, counts[kind])
}
}
+
+ if got := results[0].Kind; got != ChangeRunbookExecuted {
+ t.Fatalf("latest kind = %q, want %q", got, ChangeRunbookExecuted)
+ }
}
func TestCountRecentChangesBySourceType_RespectsFilters(t *testing.T) {