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.

Record maintenance evidence in resource timelines

rcourtman14d5cd4b3b75
diff --git a/internal/api/resources_operator_state.go b/internal/api/resources_operator_state.go
index 7e5e743ca3..5e376277f4 100644
--- a/internal/api/resources_operator_state.go
+++ b/internal/api/resources_operator_state.go
@@ -96,6 +96,11 @@ func (h *ResourceHandlers) HandleResourceOperatorState(w http.ResponseWriter, r
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
+ previous, previousFound, err := store.GetResourceOperatorState(resourceID)
+ if err != nil {
+ http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
+ return
+ }
// canonical_id from URL wins over body to prevent scope confusion
// (operator wrote vm:101 in the URL but vm:102 in the body).
state := unified.ResourceOperatorState{
@@ -128,13 +133,36 @@ func (h *ResourceHandlers) HandleResourceOperatorState(w http.ResponseWriter, r
http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
return
}
+ if err := recordMaintenanceWindowLifecycleChange(store, previous, previousFound, persisted, true, persisted.SetAt, persisted.SetBy); err != nil {
+ http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
+ return
+ }
writeJSON(w, http.StatusOK, toResourceOperatorStateAPI(persisted))
case http.MethodDelete:
+ previous, previousFound, err := store.GetResourceOperatorState(resourceID)
+ if err != nil {
+ http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
+ return
+ }
+ observedAt := time.Now().UTC()
+ actor := getUserID(r)
if err := store.ClearResourceOperatorState(resourceID); err != nil {
http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
return
}
+ if err := recordMaintenanceWindowLifecycleChange(
+ store,
+ previous,
+ previousFound,
+ unified.ResourceOperatorState{CanonicalID: resourceID},
+ false,
+ observedAt,
+ actor,
+ ); err != nil {
+ http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
+ return
+ }
w.WriteHeader(http.StatusNoContent)
default:
@@ -154,3 +182,19 @@ func extractOperatorStateResourceID(path string) string {
trimmed = strings.TrimSuffix(trimmed, "/")
return unified.CanonicalResourceID(trimmed)
}
+
+func recordMaintenanceWindowLifecycleChange(
+ store unified.ResourceStore,
+ previous unified.ResourceOperatorState,
+ previousFound bool,
+ current unified.ResourceOperatorState,
+ currentFound bool,
+ observedAt time.Time,
+ actor string,
+) error {
+ change, ok := unified.BuildMaintenanceWindowLifecycleChange(previous, previousFound, current, currentFound, observedAt, actor)
+ if !ok {
+ return nil
+ }
+ return store.RecordChange(change)
+}
diff --git a/internal/api/resources_operator_state_test.go b/internal/api/resources_operator_state_test.go
index d6ff613517..89833f87db 100644
--- a/internal/api/resources_operator_state_test.go
+++ b/internal/api/resources_operator_state_test.go
@@ -9,6 +9,7 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
// newOperatorStateHandlers spins up a ResourceHandlers wired against a
@@ -108,6 +109,75 @@ func TestHandleResourceOperatorState_PutPersistsAndGetReturns200(t *testing.T) {
}
}
+func TestHandleResourceOperatorState_RecordsMaintenanceWindowLifecycleChanges(t *testing.T) {
+ h := newOperatorStateHandlers(t)
+ store, err := h.getStore("default")
+ if err != nil {
+ t.Fatalf("get store: %v", err)
+ }
+
+ start := time.Date(2026, 5, 9, 12, 0, 0, 0, time.UTC)
+ end := time.Date(2026, 5, 9, 14, 0, 0, 0, time.UTC)
+ body, _ := json.Marshal(map[string]any{
+ "maintenanceStartAt": start.Format(time.RFC3339),
+ "maintenanceEndAt": end.Format(time.RFC3339),
+ "maintenanceReason": "storage controller patch",
+ })
+
+ putRec := httptest.NewRecorder()
+ putReq := httptest.NewRequest(http.MethodPut, "/api/resources/vm:101/operator-state", bytes.NewReader(body))
+ h.HandleResourceOperatorState(putRec, putReq)
+ if putRec.Code != http.StatusOK {
+ t.Fatalf("expected 200 on PUT; got %d body=%s", putRec.Code, putRec.Body.String())
+ }
+
+ changes, err := store.GetRecentChangesFiltered("vm:101", time.Time{}, 0, unified.ResourceChangeFilters{
+ SourceTypes: []unified.ChangeSourceType{unified.SourceUserAction},
+ })
+ if err != nil {
+ t.Fatalf("recent changes after PUT: %v", err)
+ }
+ if len(changes) != 1 {
+ t.Fatalf("expected one maintenance lifecycle change after PUT, got %d", len(changes))
+ }
+ if changes[0].Metadata["activityType"] != unified.MaintenanceWindowLifecycleEventScheduled {
+ t.Fatalf("activityType = %#v want scheduled", changes[0].Metadata["activityType"])
+ }
+ if changes[0].Reason != "Maintenance window scheduled" {
+ t.Fatalf("reason = %q want scheduled", changes[0].Reason)
+ }
+
+ delRec := httptest.NewRecorder()
+ delReq := httptest.NewRequest(http.MethodDelete, "/api/resources/vm:101/operator-state", nil)
+ h.HandleResourceOperatorState(delRec, delReq)
+ if delRec.Code != http.StatusNoContent {
+ t.Fatalf("expected 204 on DELETE; got %d body=%s", delRec.Code, delRec.Body.String())
+ }
+
+ changes, err = store.GetRecentChangesFiltered("vm:101", time.Time{}, 0, unified.ResourceChangeFilters{
+ SourceTypes: []unified.ChangeSourceType{unified.SourceUserAction},
+ })
+ if err != nil {
+ t.Fatalf("recent changes after DELETE: %v", err)
+ }
+ if len(changes) != 2 {
+ t.Fatalf("expected scheduled + cleared changes, got %d", len(changes))
+ }
+ var cleared *unified.ResourceChange
+ for i := range changes {
+ if changes[i].Metadata["activityType"] == unified.MaintenanceWindowLifecycleEventCleared {
+ cleared = &changes[i]
+ break
+ }
+ }
+ if cleared == nil {
+ t.Fatalf("expected cleared lifecycle change, got %+v", changes)
+ }
+ if cleared.To != "no maintenance window" {
+ t.Fatalf("delete change to = %q want no maintenance window", cleared.To)
+ }
+}
+
func TestHandleResourceOperatorState_PutRejectsInvalidWith400(t *testing.T) {
h := newOperatorStateHandlers(t)
diff --git a/internal/maintenancesentinel/sentinel_test.go b/internal/maintenancesentinel/sentinel_test.go
index 4ce313e28d..9a248f3486 100644
--- a/internal/maintenancesentinel/sentinel_test.go
+++ b/internal/maintenancesentinel/sentinel_test.go
@@ -55,6 +55,48 @@ func TestSentinelTickOnceWritesReportAndDedupes(t *testing.T) {
}
}
+func TestMaintenanceSentinelTickOnceWritesTimelineEvidence(t *testing.T) {
+ now := time.Date(2026, 5, 12, 12, 0, 0, 0, time.UTC)
+ windowStart := now.Add(-time.Hour)
+ windowEnd := now.Add(-15 * time.Minute)
+
+ store := unified.NewMemoryStore()
+ if err := store.SetResourceOperatorState(unified.ResourceOperatorState{
+ CanonicalID: "vm:101",
+ MaintenanceStartAt: &windowStart,
+ MaintenanceEndAt: &windowEnd,
+ SetAt: windowStart,
+ SetBy: "operator",
+ }); err != nil {
+ t.Fatalf("seed operator state: %v", err)
+ }
+
+ providers := Providers{
+ Stores: func(orgID string) (unified.ResourceStore, error) { return store, nil },
+ Now: func() time.Time { return now },
+ }
+ sentinel, err := New(Config{OrgID: "default", Tick: time.Minute}, providers)
+ if err != nil {
+ t.Fatalf("new sentinel: %v", err)
+ }
+
+ sentinel.tickOnce(context.Background())
+
+ changes, err := store.GetRecentChanges("vm:101", windowStart, 0)
+ if err != nil {
+ t.Fatalf("recent changes: %v", err)
+ }
+ if len(changes) != 1 {
+ t.Fatalf("expected one timeline change from the verification report, got %d", len(changes))
+ }
+ if changes[0].SourceAdapter != unified.ChangeSourceAdapter("maintenance_sentinel") {
+ t.Fatalf("source adapter = %q want maintenance_sentinel", changes[0].SourceAdapter)
+ }
+ if changes[0].Metadata["activityType"] != unified.MaintenanceVerificationActivityReported {
+ t.Fatalf("activityType = %#v want maintenance verification reported", changes[0].Metadata["activityType"])
+ }
+}
+
func TestSentinelSkipsAncientWindows(t *testing.T) {
now := time.Date(2026, 5, 12, 12, 0, 0, 0, time.UTC)
windowStart := now.Add(-30 * 24 * time.Hour)
diff --git a/internal/unifiedresources/loop_reports.go b/internal/unifiedresources/loop_reports.go
index 5b2c3d03b0..df03c06784 100644
--- a/internal/unifiedresources/loop_reports.go
+++ b/internal/unifiedresources/loop_reports.go
@@ -21,6 +21,12 @@ const (
LoopReportTypeMaintenanceVerification LoopReportType = "maintenance_verification"
)
+const (
+ MaintenanceVerificationActivityReported = "maintenance_verification_reported"
+
+ maintenanceVerificationSourceAdapter ChangeSourceAdapter = "maintenance_sentinel"
+)
+
// LoopReportStatus reports the verification outcome.
//
// - healthy — all deterministic checks passed.
@@ -38,10 +44,10 @@ const (
type LoopReportStatus string
const (
- LoopReportStatusPending LoopReportStatus = "pending"
- LoopReportStatusHealthy LoopReportStatus = "healthy"
- LoopReportStatusNeedsReview LoopReportStatus = "needs_review"
- LoopReportStatusFailedVerification LoopReportStatus = "failed_verification"
+ LoopReportStatusPending LoopReportStatus = "pending"
+ LoopReportStatusHealthy LoopReportStatus = "healthy"
+ LoopReportStatusNeedsReview LoopReportStatus = "needs_review"
+ LoopReportStatusFailedVerification LoopReportStatus = "failed_verification"
)
// LoopReportUserOutcome records the operator's review verdict after
@@ -287,3 +293,72 @@ func trimAndDedupeStrings(in []string) []string {
}
return out
}
+
+// BuildLoopReportResourceChange projects an immutable loop report into the
+// canonical resource timeline. The report remains the source-of-truth record;
+// this change is the discoverable timeline evidence that lets existing
+// change consumers explain why the resource's post-maintenance state changed.
+func BuildLoopReportResourceChange(report LoopReport) (ResourceChange, bool) {
+ report = NormalizeLoopReport(report)
+ if report.ID == "" || report.Scope == "" || report.Type != LoopReportTypeMaintenanceVerification {
+ return ResourceChange{}, false
+ }
+ observedAt := report.CompletedAt
+ if observedAt.IsZero() {
+ observedAt = report.StartedAt
+ }
+ if observedAt.IsZero() {
+ observedAt = time.Now().UTC()
+ }
+ observedAt = observedAt.UTC()
+
+ var occurredAt *time.Time
+ if report.WindowEndedAt != nil {
+ t := report.WindowEndedAt.UTC()
+ occurredAt = &t
+ }
+
+ metadata := map[string]any{
+ "activityType": MaintenanceVerificationActivityReported,
+ "reportId": report.ID,
+ "reportType": string(report.Type),
+ "status": string(report.Status),
+ "trigger": report.Trigger,
+ }
+ if report.WindowStartedAt != nil {
+ metadata["windowStartedAt"] = report.WindowStartedAt.UTC().Format(time.RFC3339)
+ }
+ if report.WindowEndedAt != nil {
+ metadata["windowEndedAt"] = report.WindowEndedAt.UTC().Format(time.RFC3339)
+ }
+ if report.Recommendation != "" {
+ metadata["recommendation"] = report.Recommendation
+ }
+ if len(report.LinkedAlertIDs) > 0 {
+ metadata["linkedAlertCount"] = len(report.LinkedAlertIDs)
+ }
+ if len(report.LinkedFindingIDs) > 0 {
+ metadata["linkedFindingCount"] = len(report.LinkedFindingIDs)
+ }
+ if len(report.LinkedActionIDs) > 0 {
+ metadata["linkedActionCount"] = len(report.LinkedActionIDs)
+ }
+ if report.Evidence.OperatorStateSummary != "" {
+ metadata["operatorStateSummary"] = report.Evidence.OperatorStateSummary
+ }
+
+ return ResourceChange{
+ ID: resourceChangeID("loop-report", report.Scope, report.ID, observedAt),
+ ObservedAt: observedAt,
+ OccurredAt: occurredAt,
+ ResourceID: report.Scope,
+ Kind: ChangeActivity,
+ From: report.Trigger,
+ To: string(report.Status),
+ SourceType: SourceHeuristic,
+ SourceAdapter: maintenanceVerificationSourceAdapter,
+ Confidence: ConfidenceHigh,
+ Reason: "Maintenance verification reported " + string(report.Status),
+ Metadata: metadata,
+ }, true
+}
diff --git a/internal/unifiedresources/loop_reports_store.go b/internal/unifiedresources/loop_reports_store.go
index 84a2c60893..056e39148d 100644
--- a/internal/unifiedresources/loop_reports_store.go
+++ b/internal/unifiedresources/loop_reports_store.go
@@ -137,8 +137,6 @@ func (s *SQLiteResourceStore) RecordLoopReport(report LoopReport) error {
}
s.mu.Lock()
- defer s.mu.Unlock()
-
_, err = s.db.Exec(`
INSERT INTO loop_reports (
id, report_type, scope, trigger, goal, status, started_at, completed_at,
@@ -168,9 +166,15 @@ func (s *SQLiteResourceStore) RecordLoopReport(report LoopReport) error {
report.ReviewedBy,
report.ReviewNote,
)
+ s.mu.Unlock()
if err != nil {
return fmt.Errorf("insert loop report: %w", err)
}
+ if change, ok := BuildLoopReportResourceChange(report); ok {
+ if err := s.RecordChange(change); err != nil {
+ return fmt.Errorf("record loop report resource change: %w", err)
+ }
+ }
return nil
}
@@ -316,18 +320,18 @@ type loopReportScanner interface {
func scanLoopReportRow(scanner loopReportScanner) (LoopReport, error) {
var (
- r LoopReport
- typ, status, outcome string
- windowStart, windowEnd sql.NullTime
- reviewedAt sql.NullTime
- evidenceJSON string
- findingIDsJSON string
- alertIDsJSON string
- actionIDsJSON string
- linkedPatrolRunID string
- recommendation, goal string
- reviewedBy, reviewNote string
- trigger string
+ r LoopReport
+ typ, status, outcome string
+ windowStart, windowEnd sql.NullTime
+ reviewedAt sql.NullTime
+ evidenceJSON string
+ findingIDsJSON string
+ alertIDsJSON string
+ actionIDsJSON string
+ linkedPatrolRunID string
+ recommendation, goal string
+ reviewedBy, reviewNote string
+ trigger string
)
if err := scanner.Scan(
&r.ID,
@@ -410,14 +414,20 @@ func (m *MemoryStore) RecordLoopReport(report LoopReport) error {
return err
}
m.mu.Lock()
- defer m.mu.Unlock()
if m.loopReports == nil {
m.loopReports = make(map[string]LoopReport)
}
if _, exists := m.loopReports[report.ID]; exists {
+ m.mu.Unlock()
return fmt.Errorf("%w: id %q already exists", ErrLoopReportInvalid, report.ID)
}
m.loopReports[report.ID] = report
+ m.mu.Unlock()
+ if change, ok := BuildLoopReportResourceChange(report); ok {
+ if err := m.RecordChange(change); err != nil {
+ return fmt.Errorf("record loop report resource change: %w", err)
+ }
+ }
return nil
}
diff --git a/internal/unifiedresources/loop_reports_store_test.go b/internal/unifiedresources/loop_reports_store_test.go
index af4bf12b63..1aa499f677 100644
--- a/internal/unifiedresources/loop_reports_store_test.go
+++ b/internal/unifiedresources/loop_reports_store_test.go
@@ -45,6 +45,58 @@ func TestSQLiteRecordLoopReport_RoundTrip(t *testing.T) {
}
}
+func TestLoopReport_RecordMaintenanceVerificationResourceChange(t *testing.T) {
+ dataDir := t.TempDir()
+ store, err := NewSQLiteResourceStore(dataDir, "default")
+ if err != nil {
+ t.Fatalf("new store: %v", err)
+ }
+ defer store.Close()
+
+ windowStart := time.Date(2026, 5, 12, 11, 0, 0, 0, time.UTC)
+ windowEnd := time.Date(2026, 5, 12, 12, 0, 0, 0, time.UTC)
+ report := newLoopReport("mv-vm_101-20260512T120000Z", "vm:101", windowEnd, LoopReportStatusNeedsReview)
+ report.WindowStartedAt = &windowStart
+ report.LinkedAlertIDs = []string{"alert-1"}
+ report.Evidence.ActiveWarningAlerts = 1
+ if err := store.RecordLoopReport(report); err != nil {
+ t.Fatalf("record: %v", err)
+ }
+
+ changes, err := store.GetRecentChanges("vm:101", windowEnd.Add(-time.Minute), 0)
+ if err != nil {
+ t.Fatalf("recent changes: %v", err)
+ }
+ if len(changes) != 1 {
+ t.Fatalf("expected one resource change for the loop report, got %d", len(changes))
+ }
+ change := changes[0]
+ if change.Kind != ChangeActivity {
+ t.Fatalf("change kind = %q want activity", change.Kind)
+ }
+ if change.SourceType != SourceHeuristic {
+ t.Fatalf("source type = %q want heuristic", change.SourceType)
+ }
+ if change.SourceAdapter != maintenanceVerificationSourceAdapter {
+ t.Fatalf("source adapter = %q want maintenance_sentinel", change.SourceAdapter)
+ }
+ if change.To != string(LoopReportStatusNeedsReview) {
+ t.Fatalf("change to = %q want needs_review", change.To)
+ }
+ if change.OccurredAt == nil || !change.OccurredAt.Equal(windowEnd) {
+ t.Fatalf("occurredAt = %v want %v", change.OccurredAt, windowEnd)
+ }
+ if change.Metadata["activityType"] != MaintenanceVerificationActivityReported {
+ t.Fatalf("activityType = %#v want maintenance verification reported", change.Metadata["activityType"])
+ }
+ if change.Metadata["reportId"] != report.ID {
+ t.Fatalf("reportId = %#v want %q", change.Metadata["reportId"], report.ID)
+ }
+ if change.Metadata["linkedAlertCount"] != float64(1) {
+ t.Fatalf("linkedAlertCount = %#v want 1", change.Metadata["linkedAlertCount"])
+ }
+}
+
func TestSQLiteRecordLoopReport_AllowsRerunForSameWindow(t *testing.T) {
dataDir := t.TempDir()
store, err := NewSQLiteResourceStore(dataDir, "default")
diff --git a/internal/unifiedresources/resource_operator_state.go b/internal/unifiedresources/resource_operator_state.go
index a729af19d7..642cc05fe3 100644
--- a/internal/unifiedresources/resource_operator_state.go
+++ b/internal/unifiedresources/resource_operator_state.go
@@ -175,3 +175,172 @@ func NormalizeResourceOperatorState(state ResourceOperatorState) ResourceOperato
state.Criticality = ResourceCriticality(strings.ToLower(strings.TrimSpace(string(state.Criticality))))
return state
}
+
+const (
+ MaintenanceWindowLifecycleEventScheduled = "maintenance_window_scheduled"
+ MaintenanceWindowLifecycleEventUpdated = "maintenance_window_updated"
+ MaintenanceWindowLifecycleEventCleared = "maintenance_window_cleared"
+
+ resourceOperatorStateSourceAdapter ChangeSourceAdapter = "operator_state"
+)
+
+type maintenanceWindowLifecycleSnapshot struct {
+ start time.Time
+ end time.Time
+ reason string
+}
+
+// BuildMaintenanceWindowLifecycleChange returns the canonical resource
+// timeline record for a maintenance-window lifecycle transition. It is
+// intentionally scoped to the maintenance window fields; other
+// operator-state flags have their own product meaning and must not be
+// folded into this lifecycle evidence.
+func BuildMaintenanceWindowLifecycleChange(previous ResourceOperatorState, previousFound bool, current ResourceOperatorState, currentFound bool, observedAt time.Time, actor string) (ResourceChange, bool) {
+ if !previousFound {
+ previous = ResourceOperatorState{}
+ }
+ if !currentFound {
+ current = ResourceOperatorState{CanonicalID: previous.CanonicalID}
+ }
+ canonicalID := CanonicalResourceID(current.CanonicalID)
+ if canonicalID == "" {
+ canonicalID = CanonicalResourceID(previous.CanonicalID)
+ }
+ if canonicalID == "" {
+ return ResourceChange{}, false
+ }
+
+ before, beforeOK := maintenanceWindowSnapshot(previous)
+ after, afterOK := maintenanceWindowSnapshot(current)
+
+ event := ""
+ switch {
+ case !beforeOK && afterOK:
+ event = MaintenanceWindowLifecycleEventScheduled
+ case beforeOK && afterOK && !before.equal(after):
+ event = MaintenanceWindowLifecycleEventUpdated
+ case beforeOK && !afterOK:
+ event = MaintenanceWindowLifecycleEventCleared
+ default:
+ return ResourceChange{}, false
+ }
+
+ if observedAt.IsZero() {
+ observedAt = maintenanceWindowObservedAt(previous, previousFound, current, currentFound)
+ } else {
+ observedAt = observedAt.UTC()
+ }
+ actor = strings.TrimSpace(actor)
+ if actor == "" && currentFound {
+ actor = strings.TrimSpace(current.SetBy)
+ }
+ if actor == "" && previousFound {
+ actor = strings.TrimSpace(previous.SetBy)
+ }
+
+ metadata := map[string]any{
+ "activityType": event,
+ "operatorStateChange": "maintenance_window_lifecycle",
+ }
+ if beforeOK {
+ metadata["previousMaintenanceStartAt"] = before.start.UTC().Format(time.RFC3339)
+ metadata["previousMaintenanceEndAt"] = before.end.UTC().Format(time.RFC3339)
+ if before.reason != "" {
+ metadata["previousMaintenanceReason"] = before.reason
+ }
+ }
+ if afterOK {
+ metadata["maintenanceStartAt"] = after.start.UTC().Format(time.RFC3339)
+ metadata["maintenanceEndAt"] = after.end.UTC().Format(time.RFC3339)
+ if after.reason != "" {
+ metadata["maintenanceReason"] = after.reason
+ }
+ }
+
+ return ResourceChange{
+ ID: resourceChangeID("resource-operator-state", canonicalID, event, observedAt),
+ ObservedAt: observedAt,
+ ResourceID: canonicalID,
+ Kind: ChangeActivity,
+ From: maintenanceWindowSummary(before, beforeOK),
+ To: maintenanceWindowSummary(after, afterOK),
+ SourceType: SourceUserAction,
+ SourceAdapter: resourceOperatorStateSourceAdapter,
+ Confidence: ConfidenceHigh,
+ Actor: actor,
+ Reason: maintenanceWindowLifecycleReason(event),
+ Metadata: metadata,
+ }, true
+}
+
+func maintenanceWindowSnapshot(state ResourceOperatorState) (maintenanceWindowLifecycleSnapshot, bool) {
+ if state.MaintenanceStartAt == nil || state.MaintenanceEndAt == nil {
+ return maintenanceWindowLifecycleSnapshot{}, false
+ }
+ return maintenanceWindowLifecycleSnapshot{
+ start: state.MaintenanceStartAt.UTC(),
+ end: state.MaintenanceEndAt.UTC(),
+ reason: strings.TrimSpace(state.MaintenanceReason),
+ }, true
+}
+
+func (s maintenanceWindowLifecycleSnapshot) equal(other maintenanceWindowLifecycleSnapshot) bool {
+ return s.start.Equal(other.start) && s.end.Equal(other.end) && s.reason == other.reason
+}
+
+func maintenanceWindowObservedAt(previous ResourceOperatorState, previousFound bool, current ResourceOperatorState, currentFound bool) time.Time {
+ if currentFound && !current.SetAt.IsZero() {
+ return current.SetAt.UTC()
+ }
+ if previousFound && !previous.SetAt.IsZero() {
+ return previous.SetAt.UTC()
+ }
+ return time.Now().UTC()
+}
+
+func maintenanceWindowSummary(window maintenanceWindowLifecycleSnapshot, ok bool) string {
+ if !ok {
+ return "no maintenance window"
+ }
+ summary := window.start.UTC().Format(time.RFC3339) + " to " + window.end.UTC().Format(time.RFC3339)
+ if window.reason != "" {
+ summary += " (" + window.reason + ")"
+ }
+ return summary
+}
+
+func maintenanceWindowLifecycleReason(event string) string {
+ switch event {
+ case MaintenanceWindowLifecycleEventScheduled:
+ return "Maintenance window scheduled"
+ case MaintenanceWindowLifecycleEventUpdated:
+ return "Maintenance window updated"
+ case MaintenanceWindowLifecycleEventCleared:
+ return "Maintenance window cleared"
+ default:
+ return "Maintenance window lifecycle changed"
+ }
+}
+
+func resourceChangeID(prefix, canonicalID, event string, observedAt time.Time) string {
+ if observedAt.IsZero() {
+ observedAt = time.Now().UTC()
+ }
+ return fmt.Sprintf("%s:%s:%s:%d", prefix, sanitizeResourceChangeIDComponent(canonicalID), sanitizeResourceChangeIDComponent(event), observedAt.UTC().UnixNano())
+}
+
+func sanitizeResourceChangeIDComponent(value string) string {
+ var b strings.Builder
+ b.Grow(len(value))
+ for _, r := range value {
+ switch {
+ case (r >= 'a' && r <= 'z'), (r >= 'A' && r <= 'Z'), (r >= '0' && r <= '9'):
+ b.WriteRune(r)
+ case r == '-' || r == '_' || r == '.':
+ b.WriteRune(r)
+ default:
+ b.WriteRune('_')
+ }
+ }
+ return b.String()
+}
diff --git a/internal/unifiedresources/resource_operator_state_test.go b/internal/unifiedresources/resource_operator_state_test.go
index d0c71d4264..5d1e9c4226 100644
--- a/internal/unifiedresources/resource_operator_state_test.go
+++ b/internal/unifiedresources/resource_operator_state_test.go
@@ -174,6 +174,81 @@ func TestNormalizeResourceOperatorState_TrimsAndLowersCriticality(t *testing.T)
}
}
+func TestResourceOperatorState_BuildMaintenanceWindowLifecycleChange(t *testing.T) {
+ now := time.Date(2026, 5, 12, 12, 0, 0, 0, time.UTC)
+ start := now.Add(time.Hour)
+ end := now.Add(2 * time.Hour)
+ updatedEnd := now.Add(3 * time.Hour)
+
+ current := ResourceOperatorState{
+ CanonicalID: "vm:101",
+ MaintenanceStartAt: &start,
+ MaintenanceEndAt: &end,
+ MaintenanceReason: "kernel patch",
+ SetAt: now,
+ SetBy: "operator:richard",
+ }
+
+ scheduled, ok := BuildMaintenanceWindowLifecycleChange(ResourceOperatorState{}, false, current, true, time.Time{}, "")
+ if !ok {
+ t.Fatal("expected a lifecycle change when a maintenance window is scheduled")
+ }
+ if scheduled.Kind != ChangeActivity {
+ t.Fatalf("kind = %q want activity", scheduled.Kind)
+ }
+ if scheduled.SourceType != SourceUserAction {
+ t.Fatalf("source type = %q want user_action", scheduled.SourceType)
+ }
+ if scheduled.SourceAdapter != resourceOperatorStateSourceAdapter {
+ t.Fatalf("source adapter = %q want operator_state", scheduled.SourceAdapter)
+ }
+ if scheduled.Actor != "operator:richard" {
+ t.Fatalf("actor = %q want operator:richard", scheduled.Actor)
+ }
+ if scheduled.Reason != "Maintenance window scheduled" {
+ t.Fatalf("reason = %q want scheduled", scheduled.Reason)
+ }
+ if scheduled.From != "no maintenance window" || !strings.Contains(scheduled.To, "kernel patch") {
+ t.Fatalf("unexpected from/to: %q -> %q", scheduled.From, scheduled.To)
+ }
+ if scheduled.Metadata["activityType"] != MaintenanceWindowLifecycleEventScheduled {
+ t.Fatalf("activityType = %#v want scheduled", scheduled.Metadata["activityType"])
+ }
+ if scheduled.Metadata["maintenanceStartAt"] != start.Format(time.RFC3339) {
+ t.Fatalf("maintenanceStartAt metadata = %#v", scheduled.Metadata["maintenanceStartAt"])
+ }
+
+ unchanged, ok := BuildMaintenanceWindowLifecycleChange(current, true, current, true, now, "")
+ if ok || unchanged.ID != "" {
+ t.Fatalf("unchanged maintenance window should not produce a change: %+v", unchanged)
+ }
+
+ updated := current
+ updated.MaintenanceEndAt = &updatedEnd
+ updated.SetAt = now.Add(time.Minute)
+ changed, ok := BuildMaintenanceWindowLifecycleChange(current, true, updated, true, time.Time{}, "")
+ if !ok {
+ t.Fatal("expected a lifecycle change when the maintenance window end changes")
+ }
+ if changed.Metadata["activityType"] != MaintenanceWindowLifecycleEventUpdated {
+ t.Fatalf("activityType = %#v want updated", changed.Metadata["activityType"])
+ }
+ if changed.Metadata["previousMaintenanceEndAt"] != end.Format(time.RFC3339) {
+ t.Fatalf("previous end metadata = %#v", changed.Metadata["previousMaintenanceEndAt"])
+ }
+
+ cleared, ok := BuildMaintenanceWindowLifecycleChange(updated, true, ResourceOperatorState{CanonicalID: "vm:101"}, false, now.Add(2*time.Minute), "operator:richard")
+ if !ok {
+ t.Fatal("expected a lifecycle change when the maintenance window is cleared")
+ }
+ if cleared.Metadata["activityType"] != MaintenanceWindowLifecycleEventCleared {
+ t.Fatalf("activityType = %#v want cleared", cleared.Metadata["activityType"])
+ }
+ if cleared.To != "no maintenance window" {
+ t.Fatalf("cleared to = %q want no maintenance window", cleared.To)
+ }
+}
+
func TestMemoryStore_ResourceOperatorState_SetGetClearRoundTrip(t *testing.T) {
store := NewMemoryStore()