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.

Add ResourceOperatorState foundation for per-resource operator intent

rcourtmanee21942f2af8
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 2eeb12cf79..c339b09ce2 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -561,6 +561,28 @@ AI-only summary payloads, or page-local heuristics.
## Current State
+`resource_operator_state.go` owns the operator-set per-resource intent
+schema. `ResourceOperatorState` carries four narrow operator-intent
+fields (`IntentionallyOffline`, `NeverAutoRemediate`, maintenance
+window via `MaintenanceStartAt` / `MaintenanceEndAt` / `MaintenanceReason`,
+and a canonical `Criticality` hint of `high|medium|low|""`) plus
+operator-attribution metadata (`Note`, `SetAt`, `SetBy`). The shape is
+intentionally fixed-field rather than a freeform metadata bag so
+downstream finding-suppression and severity-weighting logic has a stable
+contract to honor. `ValidateResourceOperatorState` rejects malformed
+records with a stable `ErrResourceOperatorStateInvalid` sentinel
+(empty canonical id, partial maintenance window, end ≤ start, unknown
+criticality), and `NormalizeResourceOperatorState` trims whitespace
+and lower-cases the criticality value before persistence. The
+`ResourceStore` interface now exposes
+`GetResourceOperatorState`, `SetResourceOperatorState`, and
+`ClearResourceOperatorState`; both the SQLite (table
+`resource_operator_state` keyed on `canonical_id`) and Memory stores
+implement the same upsert + idempotent-clear contract. This slice is
+the foundational shape only — the API surface (GET/PUT/DELETE) and the
+finding-suppression / action-broker integrations land in subsequent
+slices that consume this contract.
+
`actions.go` now owns the canonical action preflight and audit-normalization
contract. Action plans must carry dry-run availability, safety checks, and
verification steps through `preflight`, and `RecordActionAudit` plus
diff --git a/internal/unifiedresources/resource_operator_state.go b/internal/unifiedresources/resource_operator_state.go
new file mode 100644
index 0000000000..a729af19d7
--- /dev/null
+++ b/internal/unifiedresources/resource_operator_state.go
@@ -0,0 +1,177 @@
+package unifiedresources
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+)
+
+// ResourceCriticality is an operator-set hint about how important a resource
+// is to the operator. Patrol uses it as a sort-order tiebreaker on findings
+// of equal severity — high-criticality resources surface first. Empty string
+// is the default ("no operator-set criticality"), distinct from "medium".
+type ResourceCriticality string
+
+const (
+ CriticalityHigh ResourceCriticality = "high"
+ CriticalityMedium ResourceCriticality = "medium"
+ CriticalityLow ResourceCriticality = "low"
+)
+
+// IsValidCriticality reports whether the value is empty or one of the three
+// canonical levels. Empty is valid (operator has not set a hint). Anything
+// else is rejected at the API boundary so freeform strings cannot accumulate
+// into per-deployment dialects.
+func IsValidCriticality(value string) bool {
+ switch ResourceCriticality(value) {
+ case "", CriticalityHigh, CriticalityMedium, CriticalityLow:
+ return true
+ }
+ return false
+}
+
+// ResourceOperatorState captures operator-set per-resource intent that
+// modulates Patrol's behavior on findings against this resource. The shape
+// is intentionally narrow: every field encodes a specific operator intent
+// (intentionally offline, never auto-remediate, maintenance window,
+// criticality hint) rather than a freeform metadata bag, so the
+// finding-suppression and severity-weighting logic that consumes this state
+// has a fixed contract to honor.
+//
+// All fields are optional; an empty record is equivalent to the default
+// "no operator-set state" posture. Persistence stores must treat the
+// canonical_id as the primary key and overwrite the entire record on
+// SetResourceOperatorState — there is no per-field merge, so callers who
+// want to flip a single flag must read-modify-write.
+type ResourceOperatorState struct {
+ // CanonicalID is the resource identity this state attaches to. Must
+ // match the canonical resource ID format used elsewhere in the
+ // unified-resources store; the API boundary trims and rejects empty.
+ CanonicalID string `json:"canonicalId"`
+
+ // IntentionallyOffline marks the resource as expected-to-be-offline.
+ // Findings of the form "resource X is offline" against this resource
+ // will be auto-acknowledged with reason=intentionally_offline by the
+ // Patrol findings store. Other finding categories (high CPU, disk
+ // pressure on a still-mounted volume, etc.) are unaffected.
+ IntentionallyOffline bool `json:"intentionallyOffline"`
+
+ // NeverAutoRemediate forbids Patrol from dispatching automated fixes
+ // against this resource even under approval policy. The action broker
+ // must refuse a dispatch targeting this resource with a stable error
+ // ("resource_remediation_locked") rather than silently degrading. The
+ // operator must clear the flag to allow remediation.
+ NeverAutoRemediate bool `json:"neverAutoRemediate"`
+
+ // MaintenanceStartAt and MaintenanceEndAt define a time-bounded
+ // suppression window. When now is within [start, end), all findings
+ // raised against this resource get auto-acknowledged with
+ // reason=maintenance. Both values must be set together; either alone
+ // is treated as no window. End must be strictly after Start.
+ MaintenanceStartAt *time.Time `json:"maintenanceStartAt,omitempty"`
+ MaintenanceEndAt *time.Time `json:"maintenanceEndAt,omitempty"`
+
+ // MaintenanceReason is freeform operator note attached to the window
+ // for audit / Assistant context. Surfaced verbatim in the
+ // auto-acknowledge note so the operator can see WHY future findings
+ // were quiet during the window.
+ MaintenanceReason string `json:"maintenanceReason,omitempty"`
+
+ // Criticality is an operator hint that affects finding sort order on
+ // the Patrol surface. Empty = default; CriticalityHigh promotes
+ // findings on this resource above same-severity peers; CriticalityLow
+ // demotes them. Severity itself is not modified — escalation paths
+ // stay deterministic.
+ Criticality ResourceCriticality `json:"criticality,omitempty"`
+
+ // Note is a freeform operator explanation surfaced alongside the
+ // state on the resource detail surface. Distinct from
+ // MaintenanceReason which is window-scoped.
+ Note string `json:"note,omitempty"`
+
+ // SetAt and SetBy track who last touched the state for audit. SetAt
+ // must be populated on every Set; SetBy may be empty when the state
+ // was set by a system path (e.g. a maintenance window completing
+ // itself).
+ SetAt time.Time `json:"setAt"`
+ SetBy string `json:"setBy,omitempty"`
+}
+
+// IsEmpty reports whether the state carries no operator intent — every
+// field is at its zero value. Stores may treat an IsEmpty record as
+// equivalent to "no entry" for the purpose of the GET API surface, though
+// the persistence layer MAY keep an audit row to track that the operator
+// explicitly cleared the state.
+func (s ResourceOperatorState) IsEmpty() bool {
+ return !s.IntentionallyOffline &&
+ !s.NeverAutoRemediate &&
+ s.MaintenanceStartAt == nil &&
+ s.MaintenanceEndAt == nil &&
+ strings.TrimSpace(s.MaintenanceReason) == "" &&
+ s.Criticality == "" &&
+ strings.TrimSpace(s.Note) == ""
+}
+
+// IsInMaintenanceAt reports whether `now` falls within the configured
+// maintenance window. Returns false when no window is configured, when only
+// one of start/end is set (treated as no window), or when end <= start.
+func (s ResourceOperatorState) IsInMaintenanceAt(now time.Time) bool {
+ if s.MaintenanceStartAt == nil || s.MaintenanceEndAt == nil {
+ return false
+ }
+ if !s.MaintenanceEndAt.After(*s.MaintenanceStartAt) {
+ return false
+ }
+ if now.Before(*s.MaintenanceStartAt) {
+ return false
+ }
+ if !now.Before(*s.MaintenanceEndAt) {
+ return false
+ }
+ return true
+}
+
+// ErrResourceOperatorStateInvalid is returned by stores when the supplied
+// state fails validation (empty canonical ID, malformed maintenance window,
+// unknown criticality value). The action broker translates it into a 400
+// at the API boundary; the audit path treats it as a refused write.
+var ErrResourceOperatorStateInvalid = errors.New("resource_operator_state_invalid")
+
+// ValidateResourceOperatorState applies the contract checks the Set path
+// must enforce before persisting. Returns nil on a valid record, an
+// ErrResourceOperatorStateInvalid-wrapped error on a violation. Validation
+// is structural only — operator-set meaning (was the maintenance window
+// actually intended? is the note correct?) is the operator's call.
+func ValidateResourceOperatorState(state ResourceOperatorState) error {
+ if strings.TrimSpace(state.CanonicalID) == "" {
+ return fmt.Errorf("%w: canonical_id is required", ErrResourceOperatorStateInvalid)
+ }
+ if !IsValidCriticality(string(state.Criticality)) {
+ return fmt.Errorf("%w: criticality %q is not one of (high, medium, low, empty)", ErrResourceOperatorStateInvalid, state.Criticality)
+ }
+ startSet := state.MaintenanceStartAt != nil
+ endSet := state.MaintenanceEndAt != nil
+ if startSet != endSet {
+ return fmt.Errorf("%w: maintenance window requires both start_at and end_at", ErrResourceOperatorStateInvalid)
+ }
+ if startSet && endSet {
+ if !state.MaintenanceEndAt.After(*state.MaintenanceStartAt) {
+ return fmt.Errorf("%w: maintenance end_at must be strictly after start_at", ErrResourceOperatorStateInvalid)
+ }
+ }
+ return nil
+}
+
+// NormalizeResourceOperatorState applies the canonical trim / default
+// behavior expected before persisting. Returns a copy with whitespace
+// trimmed on string fields and Criticality coerced to lower-case. Does
+// NOT validate — call ValidateResourceOperatorState afterward.
+func NormalizeResourceOperatorState(state ResourceOperatorState) ResourceOperatorState {
+ state.CanonicalID = strings.TrimSpace(state.CanonicalID)
+ state.MaintenanceReason = strings.TrimSpace(state.MaintenanceReason)
+ state.Note = strings.TrimSpace(state.Note)
+ state.SetBy = strings.TrimSpace(state.SetBy)
+ state.Criticality = ResourceCriticality(strings.ToLower(strings.TrimSpace(string(state.Criticality))))
+ return state
+}
diff --git a/internal/unifiedresources/resource_operator_state_test.go b/internal/unifiedresources/resource_operator_state_test.go
new file mode 100644
index 0000000000..d0c71d4264
--- /dev/null
+++ b/internal/unifiedresources/resource_operator_state_test.go
@@ -0,0 +1,256 @@
+package unifiedresources
+
+import (
+ "errors"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestResourceOperatorState_IsEmpty(t *testing.T) {
+ if !(ResourceOperatorState{}).IsEmpty() {
+ t.Error("zero value must report IsEmpty=true; the default no-state posture has no operator intent")
+ }
+ cases := []struct {
+ name string
+ state ResourceOperatorState
+ }{
+ {"intentionally offline", ResourceOperatorState{IntentionallyOffline: true}},
+ {"never auto remediate", ResourceOperatorState{NeverAutoRemediate: true}},
+ {"criticality", ResourceOperatorState{Criticality: CriticalityHigh}},
+ {"note", ResourceOperatorState{Note: "intentionally archived"}},
+ {"maintenance reason only", ResourceOperatorState{MaintenanceReason: "scheduled"}},
+ {"maintenance window", ResourceOperatorState{
+ MaintenanceStartAt: timePointer(time.Date(2026, 5, 9, 0, 0, 0, 0, time.UTC)),
+ MaintenanceEndAt: timePointer(time.Date(2026, 5, 9, 1, 0, 0, 0, time.UTC)),
+ }},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if tc.state.IsEmpty() {
+ t.Errorf("state %+v must not report IsEmpty=true; it carries operator intent", tc.state)
+ }
+ })
+ }
+}
+
+func TestResourceOperatorState_IsInMaintenanceAt(t *testing.T) {
+ start := time.Date(2026, 5, 9, 12, 0, 0, 0, time.UTC)
+ end := time.Date(2026, 5, 9, 14, 0, 0, 0, time.UTC)
+ state := ResourceOperatorState{
+ MaintenanceStartAt: &start,
+ MaintenanceEndAt: &end,
+ }
+
+ cases := []struct {
+ name string
+ now time.Time
+ want bool
+ }{
+ {"before window", time.Date(2026, 5, 9, 11, 59, 59, 0, time.UTC), false},
+ {"exactly start is in", start, true},
+ {"midway is in", time.Date(2026, 5, 9, 13, 0, 0, 0, time.UTC), true},
+ {"exactly end is out (half-open interval)", end, false},
+ {"after end is out", time.Date(2026, 5, 9, 14, 0, 1, 0, time.UTC), false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := state.IsInMaintenanceAt(tc.now); got != tc.want {
+ t.Errorf("IsInMaintenanceAt(%v) = %v, want %v", tc.now, got, tc.want)
+ }
+ })
+ }
+
+ t.Run("no window configured", func(t *testing.T) {
+ empty := ResourceOperatorState{}
+ if empty.IsInMaintenanceAt(start) {
+ t.Error("no-window state must always report IsInMaintenanceAt=false")
+ }
+ })
+
+ t.Run("only start set is treated as no window", func(t *testing.T) {
+ half := ResourceOperatorState{MaintenanceStartAt: &start}
+ if half.IsInMaintenanceAt(time.Date(2026, 5, 9, 13, 0, 0, 0, time.UTC)) {
+ t.Error("partial maintenance window must not gate suppression")
+ }
+ })
+
+ t.Run("end before start is treated as no window", func(t *testing.T) {
+ bad := ResourceOperatorState{MaintenanceStartAt: &end, MaintenanceEndAt: &start}
+ if bad.IsInMaintenanceAt(time.Date(2026, 5, 9, 13, 0, 0, 0, time.UTC)) {
+ t.Error("inverted maintenance window must not gate suppression — validation should also reject this on Set")
+ }
+ })
+}
+
+func TestValidateResourceOperatorState(t *testing.T) {
+ t.Run("rejects empty canonical id", func(t *testing.T) {
+ err := ValidateResourceOperatorState(ResourceOperatorState{CanonicalID: " "})
+ if !errors.Is(err, ErrResourceOperatorStateInvalid) {
+ t.Fatalf("expected ErrResourceOperatorStateInvalid, got %v", err)
+ }
+ })
+
+ t.Run("rejects unknown criticality", func(t *testing.T) {
+ err := ValidateResourceOperatorState(ResourceOperatorState{
+ CanonicalID: "vm:101",
+ Criticality: "very-high", // not one of the canonical levels
+ })
+ if !errors.Is(err, ErrResourceOperatorStateInvalid) {
+ t.Fatalf("expected ErrResourceOperatorStateInvalid for unknown criticality, got %v", err)
+ }
+ if !strings.Contains(err.Error(), "criticality") {
+ t.Errorf("error should name the criticality field; got %v", err)
+ }
+ })
+
+ t.Run("rejects half-set maintenance window", func(t *testing.T) {
+ start := time.Now()
+ err := ValidateResourceOperatorState(ResourceOperatorState{
+ CanonicalID: "vm:101",
+ MaintenanceStartAt: &start,
+ })
+ if !errors.Is(err, ErrResourceOperatorStateInvalid) {
+ t.Fatalf("expected ErrResourceOperatorStateInvalid for half-set window, got %v", err)
+ }
+ })
+
+ t.Run("rejects end equal to start (zero-length window has no semantics)", func(t *testing.T) {
+ t0 := time.Date(2026, 5, 9, 12, 0, 0, 0, time.UTC)
+ err := ValidateResourceOperatorState(ResourceOperatorState{
+ CanonicalID: "vm:101",
+ MaintenanceStartAt: &t0,
+ MaintenanceEndAt: &t0,
+ })
+ if !errors.Is(err, ErrResourceOperatorStateInvalid) {
+ t.Fatalf("expected ErrResourceOperatorStateInvalid for zero-length window, got %v", err)
+ }
+ })
+
+ t.Run("accepts canonical empty (default) criticality", func(t *testing.T) {
+ err := ValidateResourceOperatorState(ResourceOperatorState{
+ CanonicalID: "vm:101",
+ })
+ if err != nil {
+ t.Errorf("default state must validate clean; got %v", err)
+ }
+ })
+
+ t.Run("accepts canonical levels", func(t *testing.T) {
+ for _, level := range []ResourceCriticality{CriticalityHigh, CriticalityMedium, CriticalityLow} {
+ err := ValidateResourceOperatorState(ResourceOperatorState{
+ CanonicalID: "vm:101",
+ Criticality: level,
+ })
+ if err != nil {
+ t.Errorf("criticality %q must validate; got %v", level, err)
+ }
+ }
+ })
+}
+
+func TestNormalizeResourceOperatorState_TrimsAndLowersCriticality(t *testing.T) {
+ got := NormalizeResourceOperatorState(ResourceOperatorState{
+ CanonicalID: " vm:101 ",
+ MaintenanceReason: " weekend window ",
+ Note: "\tarchived\n",
+ SetBy: " agent:ops ",
+ Criticality: " HIGH ",
+ })
+ if got.CanonicalID != "vm:101" {
+ t.Errorf("canonical id should be trimmed; got %q", got.CanonicalID)
+ }
+ if got.MaintenanceReason != "weekend window" {
+ t.Errorf("maintenance reason should be trimmed; got %q", got.MaintenanceReason)
+ }
+ if got.Note != "archived" {
+ t.Errorf("note should be trimmed; got %q", got.Note)
+ }
+ if got.SetBy != "agent:ops" {
+ t.Errorf("set_by should be trimmed; got %q", got.SetBy)
+ }
+ if got.Criticality != CriticalityHigh {
+ t.Errorf("criticality should be trimmed and lowered; got %q", got.Criticality)
+ }
+}
+
+func TestMemoryStore_ResourceOperatorState_SetGetClearRoundTrip(t *testing.T) {
+ store := NewMemoryStore()
+
+ // Initial GET on a fresh store returns no entry.
+ state, found, err := store.GetResourceOperatorState("vm:101")
+ if err != nil {
+ t.Fatalf("unexpected error on initial get: %v", err)
+ }
+ if found {
+ t.Errorf("expected no entry on fresh store; got %+v", state)
+ }
+
+ start := time.Date(2026, 5, 9, 12, 0, 0, 0, time.UTC)
+ end := time.Date(2026, 5, 9, 14, 0, 0, 0, time.UTC)
+ setAt := time.Date(2026, 5, 9, 11, 59, 0, 0, time.UTC)
+ original := ResourceOperatorState{
+ CanonicalID: "vm:101",
+ IntentionallyOffline: true,
+ NeverAutoRemediate: true,
+ MaintenanceStartAt: &start,
+ MaintenanceEndAt: &end,
+ MaintenanceReason: "Q3 storage upgrade",
+ Criticality: CriticalityHigh,
+ Note: "do not auto-fix; restoration in progress",
+ SetAt: setAt,
+ SetBy: "operator:richard",
+ }
+ if err := store.SetResourceOperatorState(original); err != nil {
+ t.Fatalf("set failed: %v", err)
+ }
+
+ state, found, err = store.GetResourceOperatorState("vm:101")
+ if err != nil {
+ t.Fatalf("get failed: %v", err)
+ }
+ if !found {
+ t.Fatal("expected entry after Set")
+ }
+ if !state.IntentionallyOffline {
+ t.Error("intentionally_offline must round-trip")
+ }
+ if !state.NeverAutoRemediate {
+ t.Error("never_auto_remediate must round-trip")
+ }
+ if state.MaintenanceStartAt == nil || !state.MaintenanceStartAt.Equal(start) {
+ t.Errorf("maintenance start must round-trip; got %v", state.MaintenanceStartAt)
+ }
+ if state.MaintenanceEndAt == nil || !state.MaintenanceEndAt.Equal(end) {
+ t.Errorf("maintenance end must round-trip; got %v", state.MaintenanceEndAt)
+ }
+ if state.Criticality != CriticalityHigh {
+ t.Errorf("criticality must round-trip; got %q", state.Criticality)
+ }
+ if state.Note != "do not auto-fix; restoration in progress" {
+ t.Errorf("note must round-trip; got %q", state.Note)
+ }
+
+ // Clear is idempotent and removes the entry.
+ if err := store.ClearResourceOperatorState("vm:101"); err != nil {
+ t.Fatalf("clear failed: %v", err)
+ }
+ if _, found, _ := store.GetResourceOperatorState("vm:101"); found {
+ t.Error("entry must be gone after Clear")
+ }
+ if err := store.ClearResourceOperatorState("vm:101"); err != nil {
+ t.Errorf("Clear must be idempotent; got %v", err)
+ }
+}
+
+func TestMemoryStore_SetResourceOperatorState_RejectsInvalid(t *testing.T) {
+ store := NewMemoryStore()
+ err := store.SetResourceOperatorState(ResourceOperatorState{Criticality: "bogus"})
+ if !errors.Is(err, ErrResourceOperatorStateInvalid) {
+ t.Fatalf("invalid state must be rejected with ErrResourceOperatorStateInvalid; got %v", err)
+ }
+}
+
+func timePointer(t time.Time) *time.Time {
+ return &t
+}
diff --git a/internal/unifiedresources/store.go b/internal/unifiedresources/store.go
index 2d447c63cd..00a7e2d0e9 100644
--- a/internal/unifiedresources/store.go
+++ b/internal/unifiedresources/store.go
@@ -45,6 +45,10 @@ type ResourceStore interface {
GetActionLifecycleEvents(actionID string, since time.Time, limit int) ([]ActionLifecycleEvent, error)
RecordExportAudit(record ExportAuditRecord) error
GetExportAudits(since time.Time, limit int) ([]ExportAuditRecord, error)
+ // Operator-set per-resource state. See ResourceOperatorState.
+ GetResourceOperatorState(canonicalID string) (ResourceOperatorState, bool, error)
+ SetResourceOperatorState(state ResourceOperatorState) error
+ ClearResourceOperatorState(canonicalID string) error
Close() error
}
@@ -351,6 +355,20 @@ func (s *SQLiteResourceStore) initSchema() error {
redactions_json TEXT
);
CREATE INDEX IF NOT EXISTS idx_export_audits_timestamp ON export_audits(timestamp DESC);
+
+ CREATE TABLE IF NOT EXISTS resource_operator_state (
+ canonical_id TEXT PRIMARY KEY,
+ intentionally_offline INTEGER NOT NULL DEFAULT 0,
+ never_auto_remediate INTEGER NOT NULL DEFAULT 0,
+ maintenance_start_at DATETIME,
+ maintenance_end_at DATETIME,
+ maintenance_reason TEXT,
+ criticality TEXT,
+ note TEXT,
+ set_at DATETIME NOT NULL,
+ set_by TEXT
+ );
+ CREATE INDEX IF NOT EXISTS idx_resource_operator_state_maintenance ON resource_operator_state(maintenance_end_at);
`
_, err := s.db.Exec(schema)
@@ -1373,6 +1391,170 @@ func (s *SQLiteResourceStore) GetExportAudits(since time.Time, limit int) ([]Exp
return records, nil
}
+// GetResourceOperatorState reads the operator-set state for the given
+// canonical ID. Returns (zero, false, nil) on no entry; (state, true,
+// nil) on a hit; (zero, false, error) on a query failure. The found
+// signal is meaningful for the API GET path which returns 404 vs
+// returning the default no-state record.
+func (s *SQLiteResourceStore) GetResourceOperatorState(canonicalID string) (ResourceOperatorState, bool, error) {
+ canonicalID = strings.TrimSpace(canonicalID)
+ if canonicalID == "" {
+ return ResourceOperatorState{}, false, nil
+ }
+ row := s.db.QueryRow(`
+ SELECT canonical_id, intentionally_offline, never_auto_remediate,
+ maintenance_start_at, maintenance_end_at, maintenance_reason,
+ criticality, note, set_at, set_by
+ FROM resource_operator_state WHERE canonical_id = ?`, canonicalID)
+
+ var state ResourceOperatorState
+ var (
+ intentional int
+ neverRemediate int
+ startAt, endAt sql.NullTime
+ reason sql.NullString
+ criticality sql.NullString
+ note sql.NullString
+ setBy sql.NullString
+ )
+ if err := row.Scan(
+ &state.CanonicalID,
+ &intentional,
+ &neverRemediate,
+ &startAt,
+ &endAt,
+ &reason,
+ &criticality,
+ &note,
+ &state.SetAt,
+ &setBy,
+ ); err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return ResourceOperatorState{}, false, nil
+ }
+ return ResourceOperatorState{}, false, fmt.Errorf("query resource operator state: %w", err)
+ }
+ state.IntentionallyOffline = intentional != 0
+ state.NeverAutoRemediate = neverRemediate != 0
+ if startAt.Valid {
+ t := startAt.Time
+ state.MaintenanceStartAt = &t
+ }
+ if endAt.Valid {
+ t := endAt.Time
+ state.MaintenanceEndAt = &t
+ }
+ if reason.Valid {
+ state.MaintenanceReason = reason.String
+ }
+ if criticality.Valid {
+ state.Criticality = ResourceCriticality(criticality.String)
+ }
+ if note.Valid {
+ state.Note = note.String
+ }
+ if setBy.Valid {
+ state.SetBy = setBy.String
+ }
+ return state, true, nil
+}
+
+// SetResourceOperatorState upserts the state row. Validates and
+// normalizes before persistence; rejects malformed records (empty
+// canonical ID, mismatched maintenance window, unknown criticality)
+// with ErrResourceOperatorStateInvalid so the API boundary can return
+// 400 with a stable error code.
+func (s *SQLiteResourceStore) SetResourceOperatorState(state ResourceOperatorState) error {
+ state = NormalizeResourceOperatorState(state)
+ if err := ValidateResourceOperatorState(state); err != nil {
+ return err
+ }
+ intentional := 0
+ if state.IntentionallyOffline {
+ intentional = 1
+ }
+ neverRemediate := 0
+ if state.NeverAutoRemediate {
+ neverRemediate = 1
+ }
+ var (
+ startAt, endAt sql.NullTime
+ reason sql.NullString
+ criticality sql.NullString
+ note sql.NullString
+ setBy sql.NullString
+ )
+ if state.MaintenanceStartAt != nil {
+ startAt.Time = *state.MaintenanceStartAt
+ startAt.Valid = true
+ }
+ if state.MaintenanceEndAt != nil {
+ endAt.Time = *state.MaintenanceEndAt
+ endAt.Valid = true
+ }
+ if state.MaintenanceReason != "" {
+ reason.String = state.MaintenanceReason
+ reason.Valid = true
+ }
+ if state.Criticality != "" {
+ criticality.String = string(state.Criticality)
+ criticality.Valid = true
+ }
+ if state.Note != "" {
+ note.String = state.Note
+ note.Valid = true
+ }
+ if state.SetBy != "" {
+ setBy.String = state.SetBy
+ setBy.Valid = true
+ }
+ _, err := s.db.Exec(`
+ INSERT INTO resource_operator_state (
+ canonical_id, intentionally_offline, never_auto_remediate,
+ maintenance_start_at, maintenance_end_at, maintenance_reason,
+ criticality, note, set_at, set_by
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(canonical_id) DO UPDATE SET
+ intentionally_offline = excluded.intentionally_offline,
+ never_auto_remediate = excluded.never_auto_remediate,
+ maintenance_start_at = excluded.maintenance_start_at,
+ maintenance_end_at = excluded.maintenance_end_at,
+ maintenance_reason = excluded.maintenance_reason,
+ criticality = excluded.criticality,
+ note = excluded.note,
+ set_at = excluded.set_at,
+ set_by = excluded.set_by`,
+ state.CanonicalID,
+ intentional,
+ neverRemediate,
+ startAt,
+ endAt,
+ reason,
+ criticality,
+ note,
+ state.SetAt,
+ setBy,
+ )
+ if err != nil {
+ return fmt.Errorf("upsert resource operator state: %w", err)
+ }
+ return nil
+}
+
+// ClearResourceOperatorState removes the row for the given canonical
+// ID. Idempotent — returns nil whether or not a row existed.
+func (s *SQLiteResourceStore) ClearResourceOperatorState(canonicalID string) error {
+ canonicalID = strings.TrimSpace(canonicalID)
+ if canonicalID == "" {
+ return nil
+ }
+ _, err := s.db.Exec(`DELETE FROM resource_operator_state WHERE canonical_id = ?`, canonicalID)
+ if err != nil {
+ return fmt.Errorf("delete resource operator state: %w", err)
+ }
+ return nil
+}
+
// MemoryStore is an in-memory implementation for tests.
type MemoryStore struct {
mu sync.RWMutex
@@ -1382,10 +1564,13 @@ type MemoryStore struct {
actionAudits []ActionAuditRecord
actionLifecycleEvents []ActionLifecycleEvent
exportAudits []ExportAuditRecord
+ resourceOperatorState map[string]ResourceOperatorState
}
func NewMemoryStore() *MemoryStore {
- return &MemoryStore{}
+ return &MemoryStore{
+ resourceOperatorState: make(map[string]ResourceOperatorState),
+ }
}
func (m *MemoryStore) AddLink(link ResourceLink) error {
@@ -1866,6 +2051,58 @@ func (m *MemoryStore) GetExportAudits(since time.Time, limit int) ([]ExportAudit
return out, nil
}
+// GetResourceOperatorState returns the operator-set state for the given
+// canonical resource ID. The found bool distinguishes "no entry" (the
+// default no-state posture) from "explicit empty entry the operator
+// cleared" — both have the same effective behavior but the latter may
+// be surfaced differently on the audit timeline.
+func (m *MemoryStore) GetResourceOperatorState(canonicalID string) (ResourceOperatorState, bool, error) {
+ canonicalID = strings.TrimSpace(canonicalID)
+ if canonicalID == "" {
+ return ResourceOperatorState{}, false, nil
+ }
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ state, ok := m.resourceOperatorState[canonicalID]
+ if !ok {
+ return ResourceOperatorState{}, false, nil
+ }
+ return state, true, nil
+}
+
+// SetResourceOperatorState upserts the supplied state, validating it
+// before persistence. Callers should pass a fully-populated record;
+// per-field merge is not supported, so reading the existing state and
+// modifying it is the operator's responsibility.
+func (m *MemoryStore) SetResourceOperatorState(state ResourceOperatorState) error {
+ state = NormalizeResourceOperatorState(state)
+ if err := ValidateResourceOperatorState(state); err != nil {
+ return err
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.resourceOperatorState == nil {
+ m.resourceOperatorState = make(map[string]ResourceOperatorState)
+ }
+ m.resourceOperatorState[state.CanonicalID] = state
+ return nil
+}
+
+// ClearResourceOperatorState removes any operator-set state for the
+// given canonical ID. Returns nil whether or not an entry was present —
+// the operation is idempotent so the API surface can issue
+// fire-and-forget DELETE without round-tripping the existence check.
+func (m *MemoryStore) ClearResourceOperatorState(canonicalID string) error {
+ canonicalID = strings.TrimSpace(canonicalID)
+ if canonicalID == "" {
+ return nil
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ delete(m.resourceOperatorState, canonicalID)
+ return nil
+}
+
func normalizePair(a, b string) (string, string) {
a = CanonicalResourceID(a)
b = CanonicalResourceID(b)
diff --git a/internal/unifiedresources/store_test.go b/internal/unifiedresources/store_test.go
index ba6b5c9097..d8c01a7288 100644
--- a/internal/unifiedresources/store_test.go
+++ b/internal/unifiedresources/store_test.go
@@ -1875,3 +1875,88 @@ func seedLegacyLinksTable(t *testing.T, legacyPath string) {
t.Fatalf("failed to seed legacy link row: %v", err)
}
}
+
+func TestSQLiteResourceStore_ResourceOperatorState_RoundTrips(t *testing.T) {
+ // Smoke test the SQLite implementation of ResourceOperatorState
+ // upsert + get + clear. The Memory store has a deeper test suite in
+ // resource_operator_state_test.go; this run pins that the SQLite
+ // schema migration succeeds and the column round-trips work end-to-end.
+ dataDir := t.TempDir()
+ store, err := NewSQLiteResourceStore(dataDir, defaultOrgID)
+ if err != nil {
+ t.Fatalf("open store: %v", err)
+ }
+ defer store.Close()
+
+ if _, found, err := store.GetResourceOperatorState("vm:101"); err != nil {
+ t.Fatalf("initial get: %v", err)
+ } else if found {
+ t.Fatal("fresh store must not return an entry")
+ }
+
+ start := time.Date(2026, 5, 9, 12, 0, 0, 0, time.UTC)
+ end := time.Date(2026, 5, 9, 14, 0, 0, 0, time.UTC)
+ want := ResourceOperatorState{
+ CanonicalID: "vm:101",
+ IntentionallyOffline: true,
+ NeverAutoRemediate: true,
+ MaintenanceStartAt: &start,
+ MaintenanceEndAt: &end,
+ MaintenanceReason: "Q3 storage upgrade",
+ Criticality: CriticalityHigh,
+ Note: "do not auto-fix",
+ SetAt: time.Date(2026, 5, 9, 11, 59, 0, 0, time.UTC),
+ SetBy: "operator:richard",
+ }
+ if err := store.SetResourceOperatorState(want); err != nil {
+ t.Fatalf("set: %v", err)
+ }
+
+ got, found, err := store.GetResourceOperatorState("vm:101")
+ if err != nil {
+ t.Fatalf("get: %v", err)
+ }
+ if !found {
+ t.Fatal("expected entry after set")
+ }
+ if !got.IntentionallyOffline || !got.NeverAutoRemediate {
+ t.Errorf("boolean flags must round-trip: %+v", got)
+ }
+ if got.Criticality != CriticalityHigh {
+ t.Errorf("criticality: got %q want %q", got.Criticality, CriticalityHigh)
+ }
+ if got.MaintenanceReason != "Q3 storage upgrade" || got.Note != "do not auto-fix" {
+ t.Errorf("string columns must round-trip: %+v", got)
+ }
+ if got.MaintenanceStartAt == nil || !got.MaintenanceStartAt.Equal(start) {
+ t.Errorf("maintenance_start_at: got %v want %v", got.MaintenanceStartAt, start)
+ }
+ if got.MaintenanceEndAt == nil || !got.MaintenanceEndAt.Equal(end) {
+ t.Errorf("maintenance_end_at: got %v want %v", got.MaintenanceEndAt, end)
+ }
+
+ // Upsert: Set again with different values should overwrite, not error.
+ want.IntentionallyOffline = false
+ want.Criticality = CriticalityLow
+ if err := store.SetResourceOperatorState(want); err != nil {
+ t.Fatalf("re-set: %v", err)
+ }
+ got, _, _ = store.GetResourceOperatorState("vm:101")
+ if got.IntentionallyOffline {
+ t.Error("upsert must overwrite IntentionallyOffline")
+ }
+ if got.Criticality != CriticalityLow {
+ t.Errorf("upsert must overwrite criticality; got %q", got.Criticality)
+ }
+
+ // Clear: idempotent removal.
+ if err := store.ClearResourceOperatorState("vm:101"); err != nil {
+ t.Fatalf("clear: %v", err)
+ }
+ if _, found, _ := store.GetResourceOperatorState("vm:101"); found {
+ t.Error("entry must be gone after clear")
+ }
+ if err := store.ClearResourceOperatorState("vm:101"); err != nil {
+ t.Errorf("clear must be idempotent; got %v", err)
+ }
+}