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.

Cover API relay converters, request filters and AI approval helpers

rcourtman0b5763764cea
diff --git a/internal/ai/patrol_pure_helpers_branchcov0722pm_test.go b/internal/ai/patrol_pure_helpers_branchcov0722pm_test.go
new file mode 100644
index 0000000000..15ef3d86f1
--- /dev/null
+++ b/internal/ai/patrol_pure_helpers_branchcov0722pm_test.go
@@ -0,0 +1,257 @@
+package ai
+
+import (
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/operationaltrust"
+)
+
+// branchcov0722PMRecord builds a minimal alerts.Alert whose
+// attentionAlertNewer comparison only depends on the two timestamps it reads.
+func branchcov0722PMRecord(stateChanged, lastObserved time.Time) alerts.Alert {
+ return alerts.Alert{
+ OperationalRecord: &operationaltrust.OperationalRecord{
+ ID: "rec",
+ StateChangedAt: stateChanged,
+ LastObservedAt: lastObserved,
+ },
+ }
+}
+
+func TestBranchcov0722PMAttentionAlertNewer(t *testing.T) {
+ base := time.Date(2026, 7, 22, 12, 0, 0, 0, time.UTC)
+ later := base.Add(time.Hour)
+
+ cases := []struct {
+ name string
+ candidate alerts.Alert
+ existing alerts.Alert
+ want bool
+ }{
+ {
+ name: "candidate nil operational record returns false",
+ candidate: alerts.Alert{},
+ existing: branchcov0722PMRecord(base, base),
+ want: false,
+ },
+ {
+ name: "existing nil operational record returns true",
+ candidate: branchcov0722PMRecord(base, base),
+ existing: alerts.Alert{},
+ want: true,
+ },
+ {
+ name: "candidate state changed newer wins regardless of last observed",
+ candidate: branchcov0722PMRecord(later, base),
+ existing: branchcov0722PMRecord(base, later),
+ want: true,
+ },
+ {
+ name: "existing state changed newer wins regardless of last observed",
+ candidate: branchcov0722PMRecord(base, later),
+ existing: branchcov0722PMRecord(later, base),
+ want: false,
+ },
+ {
+ name: "state changed tie falls back to candidate last observed newer",
+ candidate: branchcov0722PMRecord(base, later),
+ existing: branchcov0722PMRecord(base, base),
+ want: true,
+ },
+ {
+ name: "state changed tie falls back to existing last observed newer",
+ candidate: branchcov0722PMRecord(base, base),
+ existing: branchcov0722PMRecord(base, later),
+ want: false,
+ },
+ {
+ name: "exact tie on both timestamps keeps existing",
+ candidate: branchcov0722PMRecord(base, base),
+ existing: branchcov0722PMRecord(base, base),
+ want: false,
+ },
+ {
+ name: "both zero time keeps existing",
+ candidate: branchcov0722PMRecord(time.Time{}, time.Time{}),
+ existing: branchcov0722PMRecord(time.Time{}, time.Time{}),
+ want: false,
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := attentionAlertNewer(tc.candidate, tc.existing)
+ if got != tc.want {
+ t.Fatalf("attentionAlertNewer = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestBranchcov0722PMCountPatrolRunFact(t *testing.T) {
+ cases := []struct {
+ name string
+ value int
+ label string
+ want string
+ }{
+ {name: "zero omits fact", value: 0, label: "nodes", want: ""},
+ {name: "negative omits fact", value: -3, label: "nodes", want: ""},
+ {name: "single emits one label verbatim", value: 1, label: "node", want: "1 node"},
+ {name: "many emits count and label verbatim", value: 5, label: "nodes", want: "5 nodes"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := countPatrolRunFact(tc.value, tc.label)
+ if got != tc.want {
+ t.Fatalf("countPatrolRunFact(%d, %q) = %q, want %q",
+ tc.value, tc.label, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestBranchcov0722PMPatrolLookupResourceMetrics(t *testing.T) {
+ t.Run("node present returns cpu and memory metrics", func(t *testing.T) {
+ snap := patrolRuntimeState{
+ Nodes: []models.Node{
+ {
+ ID: "node-1",
+ Name: "node-one",
+ CPU: 0.42,
+ Memory: models.Memory{Usage: 80.0},
+ },
+ },
+ }
+ metrics, ok := patrolLookupResourceMetrics(snap, "node-1")
+ if !ok {
+ t.Fatal("patrolLookupResourceMetrics(node-1): expected ok=true, got false")
+ }
+ if metrics["cpu"] != 42.0 {
+ t.Fatalf("cpu metric = %v, want 42.0", metrics["cpu"])
+ }
+ if metrics["memory"] != 80.0 {
+ t.Fatalf("memory metric = %v, want 80.0", metrics["memory"])
+ }
+ if _, leaked := metrics["disk"]; leaked {
+ t.Fatalf("node metrics unexpectedly included disk: %v", metrics)
+ }
+ })
+
+ t.Run("storage present returns usage metric", func(t *testing.T) {
+ snap := patrolRuntimeState{
+ Storage: []models.Storage{
+ {ID: "storage-1", Name: "pool-one", Usage: 55.5},
+ },
+ }
+ metrics, ok := patrolLookupResourceMetrics(snap, "storage-1")
+ if !ok {
+ t.Fatal("patrolLookupResourceMetrics(storage-1): expected ok=true, got false")
+ }
+ if len(metrics) != 1 {
+ t.Fatalf("expected single usage key, got %v", metrics)
+ }
+ if metrics["usage"] != 55.5 {
+ t.Fatalf("usage metric = %v, want 55.5", metrics["usage"])
+ }
+ })
+
+ t.Run("resource absent returns nil and false", func(t *testing.T) {
+ snap := patrolRuntimeState{
+ Nodes: []models.Node{{ID: "node-1", Name: "node-one"}},
+ }
+ metrics, ok := patrolLookupResourceMetrics(snap, "missing")
+ if ok {
+ t.Fatal("expected ok=false for absent resource, got true")
+ }
+ if metrics != nil {
+ t.Fatalf("expected nil metrics for absent resource, got %v", metrics)
+ }
+ })
+
+ t.Run("empty snapshot returns nil and false", func(t *testing.T) {
+ snap := patrolRuntimeState{}
+ metrics, ok := patrolLookupResourceMetrics(snap, "anything")
+ if ok {
+ t.Fatal("expected ok=false for empty snapshot, got true")
+ }
+ if metrics != nil {
+ t.Fatalf("expected nil metrics for empty snapshot, got %v", metrics)
+ }
+ })
+
+ t.Run("present node with all zero metrics still found", func(t *testing.T) {
+ // The node visitor always emits {"cpu": node.cpu} and only adds
+ // "memory" when mem > 0. A zero-CPU, zero-memory node is still
+ // "present" (found=true) but returns a minimal {"cpu": 0} map.
+ // A truly empty metrics map is not reachable through this visitor
+ // for an in-package snapshot literal.
+ snap := patrolRuntimeState{
+ Nodes: []models.Node{{ID: "node-zero", Name: "zero"}},
+ }
+ metrics, ok := patrolLookupResourceMetrics(snap, "node-zero")
+ if !ok {
+ t.Fatal("expected ok=true for present node with zero metrics")
+ }
+ if len(metrics) != 1 {
+ t.Fatalf("expected exactly one key {cpu:0}, got %v", metrics)
+ }
+ if metrics["cpu"] != 0 {
+ t.Fatalf("cpu metric = %v, want 0", metrics["cpu"])
+ }
+ if _, hasMem := metrics["memory"]; hasMem {
+ t.Fatalf("did not expect memory key when mem==0, got %v", metrics)
+ }
+ })
+
+ t.Run("identifier matched by name alias", func(t *testing.T) {
+ snap := patrolRuntimeState{
+ Nodes: []models.Node{
+ {ID: "node-1", Name: "node-one", CPU: 0.10},
+ },
+ }
+ metrics, ok := patrolLookupResourceMetrics(snap, "node-one")
+ if !ok {
+ t.Fatal("expected ok=true when matching by name alias")
+ }
+ if metrics["cpu"] != 10.0 {
+ t.Fatalf("cpu metric = %v, want 10.0", metrics["cpu"])
+ }
+ })
+
+ t.Run("mutating returned map does not corrupt snapshot", func(t *testing.T) {
+ snap := patrolRuntimeState{
+ Nodes: []models.Node{
+ {
+ ID: "node-1",
+ Name: "node-one",
+ CPU: 0.42,
+ Memory: models.Memory{Usage: 80.0},
+ },
+ },
+ }
+ first, ok := patrolLookupResourceMetrics(snap, "node-1")
+ if !ok {
+ t.Fatal("expected ok=true on first lookup")
+ }
+ first["cpu"] = 999.0
+ delete(first, "memory")
+ first["bogus"] = -1
+
+ second, ok := patrolLookupResourceMetrics(snap, "node-1")
+ if !ok {
+ t.Fatal("expected ok=true on second lookup")
+ }
+ if second["cpu"] != 42.0 {
+ t.Fatalf("snapshot corrupted by map mutation: cpu = %v, want 42.0", second["cpu"])
+ }
+ if second["memory"] != 80.0 {
+ t.Fatalf("snapshot corrupted by map mutation: memory = %v, want 80.0", second["memory"])
+ }
+ if _, leaked := second["bogus"]; leaked {
+ t.Fatalf("snapshot corrupted: bogus key leaked into fresh lookup: %v", second)
+ }
+ })
+}
diff --git a/internal/ai/service_approval_branchcov0722pm_test.go b/internal/ai/service_approval_branchcov0722pm_test.go
new file mode 100644
index 0000000000..9f05d63eda
--- /dev/null
+++ b/internal/ai/service_approval_branchcov0722pm_test.go
@@ -0,0 +1,402 @@
+package ai
+
+import (
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+// TestBranchcov0722PMResolveRunCommandApprovalTarget drives every branch of
+// resolveRunCommandApprovalTarget: runOnHost true/false, empty vs populated
+// targetHost, each ExecuteRequest shape that changes the resolved type/ID/name,
+// and the node/hostname/host_name context fallbacks (string vs non-string vs
+// empty). All three return values are asserted for every case.
+func TestBranchcov0722PMResolveRunCommandApprovalTarget(t *testing.T) {
+ tests := []struct {
+ name string
+ req ExecuteRequest
+ runOnHost bool
+ targetHost string
+ wantType string
+ wantID string
+ wantName string
+ }{
+ {
+ name: "runOnHost true with populated targetHost overrides type and binds normalized host",
+ req: ExecuteRequest{},
+ runOnHost: true,
+ targetHost: "PVE-01",
+ wantType: agentcapabilities.ActionTargetTypeAgent,
+ wantID: "pve-01",
+ wantName: "pve-01",
+ },
+ {
+ name: "runOnHost true overrides explicit non-agent target type keeping the explicit id",
+ req: ExecuteRequest{TargetType: "vm", TargetID: "vm-100"},
+ runOnHost: true,
+ targetHost: "",
+ wantType: agentcapabilities.ActionTargetTypeAgent,
+ wantID: "vm-100",
+ wantName: "vm-100",
+ },
+ {
+ name: "runOnHost false normalizes and preserves non-agent target type, name falls back to id",
+ req: ExecuteRequest{TargetType: " VM ", TargetID: "vm-100"},
+ runOnHost: false,
+ targetHost: "",
+ wantType: agentcapabilities.ActionTargetTypeVM,
+ wantID: "vm-100",
+ wantName: "vm-100",
+ },
+ {
+ name: "runOnHost false empty type defaults to agent and resolves node context lowercased",
+ req: ExecuteRequest{Context: map[string]interface{}{"node": "Node-1"}},
+ runOnHost: false,
+ targetHost: "",
+ wantType: agentcapabilities.ActionTargetTypeAgent,
+ wantID: "node-1",
+ wantName: "node-1",
+ },
+ {
+ name: "hostname context fallback resolved lowercased when node absent",
+ req: ExecuteRequest{Context: map[string]interface{}{"hostname": "Host-A"}},
+ runOnHost: false,
+ targetHost: "",
+ wantType: agentcapabilities.ActionTargetTypeAgent,
+ wantID: "host-a",
+ wantName: "host-a",
+ },
+ {
+ name: "host_name context fallback resolved lowercased when node and hostname absent",
+ req: ExecuteRequest{Context: map[string]interface{}{"host_name": "Host-B"}},
+ runOnHost: false,
+ targetHost: "",
+ wantType: agentcapabilities.ActionTargetTypeAgent,
+ wantID: "host-b",
+ wantName: "host-b",
+ },
+ {
+ name: "populated targetHost supplies name via original-case trim without populating id when not runOnHost",
+ req: ExecuteRequest{},
+ runOnHost: false,
+ targetHost: " PVE-02 ",
+ wantType: agentcapabilities.ActionTargetTypeAgent,
+ wantID: "",
+ wantName: "PVE-02",
+ },
+ {
+ name: "non-string node context value is ignored leaving id empty",
+ req: ExecuteRequest{Context: map[string]interface{}{"node": 123}},
+ runOnHost: false,
+ targetHost: "",
+ wantType: agentcapabilities.ActionTargetTypeAgent,
+ wantID: "",
+ wantName: "",
+ },
+ {
+ name: "empty-string node context is ignored",
+ req: ExecuteRequest{Context: map[string]interface{}{"node": ""}},
+ runOnHost: false,
+ targetHost: "",
+ wantType: agentcapabilities.ActionTargetTypeAgent,
+ wantID: "",
+ wantName: "",
+ },
+ {
+ name: "runOnHost true with whitespace-only targetHost keeps explicit id and name falls back to id",
+ req: ExecuteRequest{TargetType: "system-container", TargetID: "ct-200"},
+ runOnHost: true,
+ targetHost: " ",
+ wantType: agentcapabilities.ActionTargetTypeAgent,
+ wantID: "ct-200",
+ wantName: "ct-200",
+ },
+ {
+ name: "node context takes priority over hostname and host_name",
+ req: ExecuteRequest{Context: map[string]interface{}{"node": "N1", "hostname": "H1", "host_name": "HN1"}},
+ runOnHost: false,
+ targetHost: "",
+ wantType: agentcapabilities.ActionTargetTypeAgent,
+ wantID: "n1",
+ wantName: "n1",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ gotType, gotID, gotName := resolveRunCommandApprovalTarget(tt.req, tt.runOnHost, tt.targetHost)
+ if gotType != tt.wantType {
+ t.Errorf("targetType = %q, want %q", gotType, tt.wantType)
+ }
+ if gotID != tt.wantID {
+ t.Errorf("targetID = %q, want %q", gotID, tt.wantID)
+ }
+ if gotName != tt.wantName {
+ t.Errorf("targetName = %q, want %q", gotName, tt.wantName)
+ }
+ })
+ }
+}
+
+// withGlobalApprovalStore swaps the package-global approval store for the
+// duration of a subtest and restores the previous value on cleanup. The store
+// is process-global state, so every subtest must restore it to avoid leaking
+// into siblings.
+func withGlobalApprovalStore(t *testing.T, store *approval.Store) {
+ t.Helper()
+ previous := approval.GetStore()
+ approval.SetStore(store)
+ t.Cleanup(func() { approval.SetStore(previous) })
+}
+
+// TestBranchcov0722PMCreateRunCommandApprovalRecord covers the three return
+// paths of createRunCommandApprovalRecord: nil store (""), CreateApproval error
+// (""), and success (record ID). The success path asserts the deterministic
+// persisted fields and that two distinct inputs never collide. The ID embeds a
+// random UUID (see store.CreateApproval), so only shape/non-emptiness and
+// non-collision are asserted, not the literal value.
+func TestBranchcov0722PMCreateRunCommandApprovalRecord(t *testing.T) {
+ t.Run("nil store returns empty string", func(t *testing.T) {
+ withGlobalApprovalStore(t, nil)
+
+ got := createRunCommandApprovalRecord("default", "uptime", "tool-1", ExecuteRequest{}, true, "pve-01", "reason")
+ if got != "" {
+ t.Fatalf("expected empty string when store is nil, got %q", got)
+ }
+ })
+
+ t.Run("success persists deterministic record fields retrievable by id", func(t *testing.T) {
+ store, err := approval.NewStore(approval.StoreConfig{
+ DataDir: t.TempDir(),
+ DisablePersistence: true,
+ DefaultTimeout: 1 * time.Minute,
+ MaxApprovals: 100,
+ })
+ if err != nil {
+ t.Fatalf("NewStore() error = %v", err)
+ }
+ withGlobalApprovalStore(t, store)
+
+ id := createRunCommandApprovalRecord(
+ "default",
+ "pct exec 100 -- uptime",
+ "tool-call-7",
+ ExecuteRequest{},
+ true,
+ "pve-01",
+ "investigating load",
+ )
+ if id == "" {
+ t.Fatal("expected non-empty approval id on success")
+ }
+
+ rec, ok := store.GetApproval(id)
+ if !ok {
+ t.Fatalf("approval %q not retrievable from store", id)
+ }
+ if rec.Command != "pct exec 100 -- uptime" {
+ t.Errorf("Command = %q, want %q", rec.Command, "pct exec 100 -- uptime")
+ }
+ if rec.ToolID != "tool-call-7" {
+ t.Errorf("ToolID = %q, want %q", rec.ToolID, "tool-call-7")
+ }
+ if rec.OrgID != "default" {
+ t.Errorf("OrgID = %q, want %q", rec.OrgID, "default")
+ }
+ // resolveRunCommandApprovalTarget with runOnHost=true, targetHost="pve-01"
+ // yields type=agent, id=pve-01, name=pve-01.
+ if rec.TargetType != agentcapabilities.ActionTargetTypeAgent {
+ t.Errorf("TargetType = %q, want %q", rec.TargetType, agentcapabilities.ActionTargetTypeAgent)
+ }
+ if rec.TargetID != "pve-01" {
+ t.Errorf("TargetID = %q, want %q", rec.TargetID, "pve-01")
+ }
+ if rec.TargetName != "pve-01" {
+ t.Errorf("TargetName = %q, want %q", rec.TargetName, "pve-01")
+ }
+ if rec.Context != "investigating load" {
+ t.Errorf("Context = %q, want %q", rec.Context, "investigating load")
+ }
+ if rec.Status != approval.StatusPending {
+ t.Errorf("Status = %q, want %q", rec.Status, approval.StatusPending)
+ }
+ })
+
+ t.Run("two distinct inputs produce non-colliding ids", func(t *testing.T) {
+ store, err := approval.NewStore(approval.StoreConfig{
+ DataDir: t.TempDir(),
+ DisablePersistence: true,
+ MaxApprovals: 100,
+ })
+ if err != nil {
+ t.Fatalf("NewStore() error = %v", err)
+ }
+ withGlobalApprovalStore(t, store)
+
+ idA := createRunCommandApprovalRecord("default", "uptime", "tool-1", ExecuteRequest{}, false, "host-a", "ra")
+ idB := createRunCommandApprovalRecord("default", "df -h", "tool-2", ExecuteRequest{}, false, "host-b", "rb")
+ if idA == "" || idB == "" {
+ t.Fatalf("expected both ids non-empty, got %q and %q", idA, idB)
+ }
+ if idA == idB {
+ t.Fatalf("expected distinct ids for distinct inputs, both = %q", idA)
+ }
+ })
+
+ t.Run("CreateApproval error returns empty string", func(t *testing.T) {
+ store, err := approval.NewStore(approval.StoreConfig{
+ DataDir: t.TempDir(),
+ DisablePersistence: true,
+ MaxApprovals: 1,
+ })
+ if err != nil {
+ t.Fatalf("NewStore() error = %v", err)
+ }
+ withGlobalApprovalStore(t, store)
+
+ // Fill the single pending slot so the next creation hits the capacity
+ // cap and CreateApproval returns an error.
+ if err := store.CreateApproval(&approval.ApprovalRequest{
+ Command: "filler",
+ TargetType: agentcapabilities.ActionTargetTypeAgent,
+ }); err != nil {
+ t.Fatalf("seed approval: %v", err)
+ }
+
+ got := createRunCommandApprovalRecord("default", "uptime", "tool-1", ExecuteRequest{}, true, "pve-01", "reason")
+ if got != "" {
+ t.Fatalf("expected empty string when CreateApproval fails, got %q", got)
+ }
+ })
+}
+
+// TestBranchcov0722PMMergeProviderCatalogFallbackModels covers the unknown
+// provider (unchanged), de-duplication when the catalog already contains a
+// fallback, empty catalogs, empty-id skipping, and case-insensitive dedup.
+// Ordering and de-duplication are asserted explicitly.
+func TestBranchcov0722PMMergeProviderCatalogFallbackModels(t *testing.T) {
+ // deepseek is registered with four fallback models in this exact order.
+ deepseekFallbackOrder := []string{
+ config.DeepSeekModelV4Flash,
+ config.DeepSeekModelV4Pro,
+ config.DeepSeekModelLegacyChat,
+ config.DeepSeekModelLegacyReasoner,
+ }
+
+ t.Run("unknown provider returns models unchanged", func(t *testing.T) {
+ in := []providers.ModelInfo{{ID: "m1"}, {ID: "m2"}}
+ got := mergeProviderCatalogFallbackModels("totally-unknown-prov", in)
+ if len(got) != 2 {
+ t.Fatalf("len = %d, want 2", len(got))
+ }
+ if got[0].ID != "m1" || got[1].ID != "m2" {
+ t.Errorf("order changed: got %q, %q, want m1, m2", got[0].ID, got[1].ID)
+ }
+ })
+
+ t.Run("unknown provider returns nil for nil input", func(t *testing.T) {
+ got := mergeProviderCatalogFallbackModels("totally-unknown-prov", nil)
+ if got != nil {
+ t.Errorf("expected nil, got %v", got)
+ }
+ })
+
+ t.Run("empty catalog returns fallbacks only in defined order", func(t *testing.T) {
+ got := mergeProviderCatalogFallbackModels(config.AIProviderDeepSeek, nil)
+ if len(got) != len(deepseekFallbackOrder) {
+ t.Fatalf("len = %d, want %d", len(got), len(deepseekFallbackOrder))
+ }
+ for i, want := range deepseekFallbackOrder {
+ if got[i].ID != want {
+ t.Errorf("got[%d].ID = %q, want %q", i, got[i].ID, want)
+ }
+ }
+ })
+
+ t.Run("catalog entries precede fallbacks with duplicate removed", func(t *testing.T) {
+ in := []providers.ModelInfo{
+ {ID: config.DeepSeekModelV4Flash},
+ {ID: "extra-model"},
+ }
+ got := mergeProviderCatalogFallbackModels(config.AIProviderDeepSeek, in)
+
+ wantOrder := []string{
+ config.DeepSeekModelV4Flash,
+ "extra-model",
+ config.DeepSeekModelV4Pro,
+ config.DeepSeekModelLegacyChat,
+ config.DeepSeekModelLegacyReasoner,
+ }
+ if len(got) != len(wantOrder) {
+ t.Fatalf("len = %d, want %d (%+v)", len(got), len(wantOrder), got)
+ }
+ for i, want := range wantOrder {
+ if got[i].ID != want {
+ t.Errorf("got[%d].ID = %q, want %q", i, got[i].ID, want)
+ }
+ }
+ // Explicitly assert no duplicate of the shared fallback id.
+ count := 0
+ for _, m := range got {
+ if m.ID == config.DeepSeekModelV4Flash {
+ count++
+ }
+ }
+ if count != 1 {
+ t.Errorf("duplicate id %q appeared %d times, want 1", config.DeepSeekModelV4Flash, count)
+ }
+ })
+
+ t.Run("empty-id catalog entries are skipped", func(t *testing.T) {
+ in := []providers.ModelInfo{
+ {ID: ""},
+ {ID: " "},
+ {ID: config.DeepSeekModelV4Flash},
+ {ID: "new-model"},
+ }
+ got := mergeProviderCatalogFallbackModels(config.AIProviderDeepSeek, in)
+
+ wantOrder := []string{
+ config.DeepSeekModelV4Flash,
+ "new-model",
+ config.DeepSeekModelV4Pro,
+ config.DeepSeekModelLegacyChat,
+ config.DeepSeekModelLegacyReasoner,
+ }
+ if len(got) != len(wantOrder) {
+ t.Fatalf("len = %d, want %d (%+v)", len(got), len(wantOrder), got)
+ }
+ for i, want := range wantOrder {
+ if got[i].ID != want {
+ t.Errorf("got[%d].ID = %q, want %q", i, got[i].ID, want)
+ }
+ }
+ })
+
+ t.Run("dedup is case-insensitive keeping catalog casing", func(t *testing.T) {
+ in := []providers.ModelInfo{{ID: "DeepSeek-V4-Flash"}}
+ got := mergeProviderCatalogFallbackModels(config.AIProviderDeepSeek, in)
+
+ if len(got) != len(deepseekFallbackOrder) {
+ t.Fatalf("len = %d, want %d (dup not removed case-insensitively)", len(got), len(deepseekFallbackOrder))
+ }
+ if got[0].ID != "DeepSeek-V4-Flash" {
+ t.Errorf("catalog entry casing not preserved: got[0].ID = %q, want %q", got[0].ID, "DeepSeek-V4-Flash")
+ }
+ // Remaining entries must be the non-duplicate fallbacks in order.
+ wantTail := []string{
+ config.DeepSeekModelV4Pro,
+ config.DeepSeekModelLegacyChat,
+ config.DeepSeekModelLegacyReasoner,
+ }
+ for i, want := range wantTail {
+ if got[1+i].ID != want {
+ t.Errorf("got[%d].ID = %q, want %q", 1+i, got[1+i].ID, want)
+ }
+ }
+ })
+}
diff --git a/internal/api/ai_relay_converters_branchcov0722pm_test.go b/internal/api/ai_relay_converters_branchcov0722pm_test.go
new file mode 100644
index 0000000000..f9ac77a771
--- /dev/null
+++ b/internal/api/ai_relay_converters_branchcov0722pm_test.go
@@ -0,0 +1,297 @@
+package api
+
+import (
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/chat"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"
+ "github.com/stretchr/testify/assert"
+)
+
+// branchcovHandoffActionAllFields builds a HandoffAction whose every string
+// field is set to strVal and every bool field is set to boolVal. Used so the
+// merge tests can distinguish "canonical won" from "requested won" per field
+// via a single struct-equality assertion.
+func branchcovHandoffActionAllFields(strVal string, boolVal bool) chat.HandoffAction {
+ return chat.HandoffAction{
+ FindingID: strVal,
+ RecordID: strVal,
+ ApprovalID: strVal,
+ ApprovalStatus: strVal,
+ ApprovalRequestedAt: strVal,
+ ApprovalExpiresAt: strVal,
+ ApprovalDecidedAt: strVal,
+ ApprovalConsumed: boolVal,
+ ActionID: strVal,
+ ActionState: strVal,
+ ActionUpdatedAt: strVal,
+ ActionRequestedBy: strVal,
+ ActionCapability: strVal,
+ ActionApprovalPolicy: strVal,
+ ActionRequiresApproval: boolVal,
+ ActionPlanExpiresAt: strVal,
+ ActionPlanMessage: strVal,
+ ActionPreflight: strVal,
+ ActionDryRunSummary: strVal,
+ ActionResult: strVal,
+ FixID: strVal,
+ Description: strVal,
+ RiskLevel: strVal,
+ Destructive: boolVal,
+ TargetHost: strVal,
+ TargetResourceID: strVal,
+ TargetResourceName: strVal,
+ TargetResourceType: strVal,
+ TargetNode: strVal,
+ }
+}
+
+func TestBranchcov0722PM_ApprovalRequestToInfo(t *testing.T) {
+ t.Run("nil request returns nil", func(t *testing.T) {
+ assert.Nil(t, approvalRequestToInfo(nil))
+ })
+
+ t.Run("populated request maps every field", func(t *testing.T) {
+ requestedAt := time.Date(2024, 1, 2, 3, 4, 5, 0, time.UTC)
+ expiresAt := time.Date(2024, 1, 2, 4, 4, 5, 0, time.UTC)
+ decidedAt := time.Date(2024, 5, 6, 7, 8, 9, 0, time.UTC)
+ preflightGeneratedAt := time.Date(2024, 3, 4, 5, 6, 7, 0, time.UTC)
+
+ req := &approval.ApprovalRequest{
+ ID: "ap-1",
+ OrgID: "org-1",
+ ExecutionID: "exec-1",
+ ToolID: "tool-1",
+ Command: "systemctl restart x",
+ TargetType: "agent",
+ TargetID: "agent-1",
+ TargetName: "node-1",
+ Context: "restart context",
+ RequestedBy: "alice",
+ RiskLevel: approval.RiskHigh,
+ Status: approval.StatusPending,
+ RequestedAt: requestedAt,
+ ExpiresAt: expiresAt,
+ DecidedAt: &decidedAt,
+ DecidedBy: "bob",
+ DenyReason: "not-now",
+ CommandHash: "hash-1",
+ Consumed: true,
+ ContextConfidence: &approval.ContextConfidence{
+ Level: approval.ContextConfidenceVerified,
+ Summary: "verified summary",
+ Evidence: []string{"e1", "e2"},
+ },
+ Preflight: &approval.ActionPreflight{
+ Target: "preflight-target",
+ CurrentState: "running",
+ IntendedChange: "restart",
+ DryRunAvailable: true,
+ DryRunSummary: "dry ok",
+ SafetyChecks: []string{"s1"},
+ VerificationSteps: []string{"v1"},
+ GeneratedAt: preflightGeneratedAt,
+ },
+ }
+
+ info := approvalRequestToInfo(req)
+ if assert.NotNil(t, info) {
+ assert.Equal(t, "ap-1", info.ID)
+ assert.Equal(t, "org-1", info.OrgID)
+ assert.Equal(t, "exec-1", info.ExecutionID)
+ assert.Equal(t, "tool-1", info.ToolID)
+ assert.Equal(t, "systemctl restart x", info.Command)
+ assert.Equal(t, "agent", info.TargetType)
+ assert.Equal(t, "agent-1", info.TargetID)
+ assert.Equal(t, "node-1", info.TargetName)
+ assert.Equal(t, "restart context", info.Context)
+ assert.Equal(t, "alice", info.RequestedBy)
+ assert.Equal(t, "high", info.RiskLevel)
+ assert.Equal(t, "pending", info.Status)
+ assert.Equal(t, requestedAt, info.RequestedAt)
+ assert.Equal(t, expiresAt, info.ExpiresAt)
+ if assert.NotNil(t, info.DecidedAt) {
+ assert.Equal(t, decidedAt, *info.DecidedAt)
+ }
+ assert.Equal(t, "bob", info.DecidedBy)
+ assert.Equal(t, "not-now", info.DenyReason)
+ assert.Equal(t, "hash-1", info.CommandHash)
+ assert.True(t, info.Consumed)
+ assert.Nil(t, info.Plan)
+
+ if assert.NotNil(t, info.ContextConfidence) {
+ assert.Equal(t, "verified", info.ContextConfidence.Level)
+ assert.Equal(t, "verified summary", info.ContextConfidence.Summary)
+ assert.Equal(t, []string{"e1", "e2"}, info.ContextConfidence.Evidence)
+ }
+ if assert.NotNil(t, info.Preflight) {
+ assert.Equal(t, "preflight-target", info.Preflight.Target)
+ assert.Equal(t, "running", info.Preflight.CurrentState)
+ assert.Equal(t, "restart", info.Preflight.IntendedChange)
+ assert.True(t, info.Preflight.DryRunAvailable)
+ assert.Equal(t, "dry ok", info.Preflight.DryRunSummary)
+ assert.Equal(t, []string{"s1"}, info.Preflight.SafetyChecks)
+ assert.Equal(t, []string{"v1"}, info.Preflight.VerificationSteps)
+ assert.Equal(t, preflightGeneratedAt, info.Preflight.GeneratedAt)
+ }
+ }
+ })
+
+ t.Run("zero-value request still converts", func(t *testing.T) {
+ info := approvalRequestToInfo(&approval.ApprovalRequest{})
+ if assert.NotNil(t, info) {
+ assert.Empty(t, info.ID)
+ assert.Equal(t, "", info.RiskLevel)
+ assert.Equal(t, "", info.Status)
+ assert.Nil(t, info.ContextConfidence)
+ assert.Nil(t, info.Preflight)
+ assert.Nil(t, info.Plan)
+ assert.Nil(t, info.DecidedAt)
+ }
+ })
+}
+
+func TestBranchcov0722PM_ContextConfidenceRequestToInfo(t *testing.T) {
+ t.Run("nil returns nil", func(t *testing.T) {
+ assert.Nil(t, contextConfidenceRequestToInfo(nil))
+ })
+
+ t.Run("populated maps fields", func(t *testing.T) {
+ conf := &approval.ContextConfidence{
+ Level: approval.ContextConfidencePartial,
+ Summary: "partial summary",
+ Evidence: []string{"a", "b"},
+ }
+ info := contextConfidenceRequestToInfo(conf)
+ if assert.NotNil(t, info) {
+ assert.Equal(t, "partial", info.Level)
+ assert.Equal(t, "partial summary", info.Summary)
+ assert.Equal(t, []string{"a", "b"}, info.Evidence)
+ }
+ })
+
+ t.Run("evidence slice is copied not aliased", func(t *testing.T) {
+ conf := &approval.ContextConfidence{
+ Level: approval.ContextConfidenceInferred,
+ Evidence: []string{"x"},
+ }
+ info := contextConfidenceRequestToInfo(conf)
+ info.Evidence[0] = "mutated"
+ assert.Equal(t, "x", conf.Evidence[0], "mutating the returned slice must not affect the source")
+ })
+
+ t.Run("nil evidence yields nil slice", func(t *testing.T) {
+ info := contextConfidenceRequestToInfo(&approval.ContextConfidence{Level: approval.ContextConfidenceUnknown})
+ if assert.NotNil(t, info) {
+ assert.Nil(t, info.Evidence)
+ assert.Equal(t, "unknown", info.Level)
+ }
+ })
+}
+
+func TestBranchcov0722PM_ContextConfidenceInfoToRequest(t *testing.T) {
+ t.Run("nil returns nil", func(t *testing.T) {
+ assert.Nil(t, contextConfidenceInfoToRequest(nil))
+ })
+
+ t.Run("populated maps fields", func(t *testing.T) {
+ info := &aicontracts.ContextConfidenceInfo{
+ Level: "verified",
+ Summary: "s",
+ Evidence: []string{"a", "b"},
+ }
+ req := contextConfidenceInfoToRequest(info)
+ if assert.NotNil(t, req) {
+ assert.Equal(t, approval.ContextConfidenceVerified, req.Level)
+ assert.Equal(t, "s", req.Summary)
+ assert.Equal(t, []string{"a", "b"}, req.Evidence)
+ }
+ })
+
+ t.Run("evidence slice is copied not aliased", func(t *testing.T) {
+ info := &aicontracts.ContextConfidenceInfo{
+ Level: "inferred",
+ Evidence: []string{"x"},
+ }
+ req := contextConfidenceInfoToRequest(info)
+ req.Evidence[0] = "mutated"
+ assert.Equal(t, "x", info.Evidence[0], "mutating the returned slice must not affect the source")
+ })
+}
+
+func TestBranchcov0722PM_ContextConfidenceRoundTrip(t *testing.T) {
+ original := &aicontracts.ContextConfidenceInfo{
+ Level: "partial",
+ Summary: "round-trip summary",
+ Evidence: []string{"e1", "e2", "e3"},
+ }
+ roundTripped := contextConfidenceRequestToInfo(contextConfidenceInfoToRequest(original))
+ assert.Equal(t, original, roundTripped, "Info->Request->Info must preserve every field")
+}
+
+func TestBranchcov0722PM_SameNonEmptyHandoffActionID(t *testing.T) {
+ cases := []struct {
+ name string
+ left, right string
+ want bool
+ }{
+ {"both empty", "", "", false},
+ {"left empty right set", "", "id-1", false},
+ {"left set right empty", "id-1", "", false},
+ {"equal exact non-empty", "abc", "abc", true},
+ {"equal case-insensitive", "ABC", "abc", true},
+ {"differing non-empty", "abc", "abd", false},
+ {"whitespace-only both treated as empty", " ", " ", false},
+ {"whitespace-only left treated as empty", " ", "abc", false},
+ {"trimmed surrounding whitespace still equal", " abc ", "abc", true},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ assert.Equal(t, tc.want, sameNonEmptyHandoffActionID(tc.left, tc.right))
+ })
+ }
+}
+
+func TestBranchcov0722PM_MergeHandoffActionSafeFields(t *testing.T) {
+ t.Run("canonical wins when already populated", func(t *testing.T) {
+ canonical := branchcovHandoffActionAllFields("canon", true)
+ requested := branchcovHandoffActionAllFields("req", false)
+ // Every canonical field is non-empty / truthy, so requested must be
+ // ignored entirely: the merged result equals canonical.
+ assert.Equal(t, canonical, mergeHandoffActionSafeFields(canonical, requested))
+ })
+
+ t.Run("requested fills when canonical is empty", func(t *testing.T) {
+ requested := branchcovHandoffActionAllFields("req", true)
+ // A zero-value canonical has every string empty and every bool false,
+ // so every field is taken from requested.
+ assert.Equal(t, requested, mergeHandoffActionSafeFields(chat.HandoffAction{}, requested))
+ })
+
+ t.Run("whitespace-only canonical string is treated as empty", func(t *testing.T) {
+ canonical := chat.HandoffAction{FindingID: " "}
+ requested := chat.HandoffAction{FindingID: "req-id"}
+ got := mergeHandoffActionSafeFields(canonical, requested)
+ assert.Equal(t, "req-id", got.FindingID)
+ })
+
+ t.Run("bool stays true from canonical despite requested false", func(t *testing.T) {
+ canonical := chat.HandoffAction{Destructive: true, ActionRequiresApproval: true, ApprovalConsumed: true}
+ requested := chat.HandoffAction{Destructive: false, ActionRequiresApproval: false, ApprovalConsumed: false}
+ got := mergeHandoffActionSafeFields(canonical, requested)
+ assert.True(t, got.Destructive)
+ assert.True(t, got.ActionRequiresApproval)
+ assert.True(t, got.ApprovalConsumed)
+ })
+
+ t.Run("bool taken from requested when canonical false", func(t *testing.T) {
+ canonical := chat.HandoffAction{}
+ requested := chat.HandoffAction{Destructive: true, ActionRequiresApproval: true, ApprovalConsumed: true}
+ got := mergeHandoffActionSafeFields(canonical, requested)
+ assert.True(t, got.Destructive)
+ assert.True(t, got.ActionRequiresApproval)
+ assert.True(t, got.ApprovalConsumed)
+ })
+}
diff --git a/internal/api/filters_branchcov0722pm_test.go b/internal/api/filters_branchcov0722pm_test.go
new file mode 100644
index 0000000000..21257a91b6
--- /dev/null
+++ b/internal/api/filters_branchcov0722pm_test.go
@@ -0,0 +1,418 @@
+package api
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/deploy"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+// This file raises branch/function coverage for five currently-uncovered
+// pure helper functions in the internal/api package:
+// - filterPVEBackups (pve_backups.go)
+// - filterReplicationJobs (replication.go)
+// - cephDiscoveryTarget (resources.go)
+// - capMetricPointSeriesByIndex (router.go)
+// - deriveInstallJobStatus (deploy_handlers.go)
+//
+// Conventions mirror internal/api/deploy_handlers_test.go (package api,
+// httptest.NewRequest for query-param driven helpers, table-driven subtests).
+
+// --- filterPVEBackups -------------------------------------------------------
+
+func branchcov0722PMSamplePVEBackups() models.PVEBackups {
+ return models.PVEBackups{
+ BackupTasks: []models.BackupTask{
+ {ID: "t1", Instance: "pve-a", Node: "node1", VMID: 100},
+ {ID: "t2", Instance: "pve-b", Node: "node2", VMID: 200},
+ },
+ StorageBackups: []models.StorageBackup{
+ {ID: "s1", Instance: "pve-a", Node: "node1", VMID: 100},
+ {ID: "s2", Instance: "pve-b", Node: "node2", VMID: 200},
+ },
+ GuestSnapshots: []models.GuestSnapshot{
+ {ID: "g1", Instance: "pve-a", Node: "node1", VMID: 100},
+ {ID: "g2", Instance: "pve-b", Node: "node2", VMID: 200},
+ },
+ }
+}
+
+func TestBranchcov0722PM_FilterPVEBackups(t *testing.T) {
+ backups := branchcov0722PMSamplePVEBackups()
+
+ checkIDs := func(label string, got []string, want []string) {
+ t.Helper()
+ if len(got) != len(want) {
+ t.Fatalf("%s: got %d entries (%v), want %d (%v)", label, len(got), got, len(want), want)
+ }
+ for i := range got {
+ if got[i] != want[i] {
+ t.Errorf("%s[%d]: got %q, want %q", label, i, got[i], want[i])
+ }
+ }
+ }
+
+ tests := []struct {
+ name string
+ query string
+ wantTasks []string // expected BackupTask IDs
+ wantStore []string // expected StorageBackup IDs
+ wantSnaps []string // expected GuestSnapshot IDs
+ }{
+ {
+ name: "no_filter_passes_all_through",
+ query: "/x",
+ wantTasks: []string{"t1", "t2"},
+ wantStore: []string{"s1", "s2"},
+ wantSnaps: []string{"g1", "g2"},
+ },
+ {
+ name: "instance_match_pve_a",
+ query: "/x?instance=pve-a",
+ wantTasks: []string{"t1"},
+ wantStore: []string{"s1"},
+ wantSnaps: []string{"g1"},
+ },
+ {
+ name: "instance_case_insensitive",
+ query: "/x?instance=PVE-A",
+ wantTasks: []string{"t1"},
+ wantStore: []string{"s1"},
+ wantSnaps: []string{"g1"},
+ },
+ {
+ name: "instance_non_matching_yields_empty",
+ query: "/x?instance=does-not-exist",
+ wantTasks: nil,
+ wantStore: nil,
+ wantSnaps: nil,
+ },
+ {
+ name: "node_match_node2",
+ query: "/x?node=node2",
+ wantTasks: []string{"t2"},
+ wantStore: []string{"s2"},
+ wantSnaps: []string{"g2"},
+ },
+ {
+ name: "vmid_match_200",
+ query: "/x?vmid=200",
+ wantTasks: []string{"t2"},
+ wantStore: []string{"s2"},
+ wantSnaps: []string{"g2"},
+ },
+ {
+ // Non-numeric vmid can never equal strconv.Itoa(VMID), so every
+ // entry is filtered out — this is the "invalid filter value" arm.
+ name: "vmid_invalid_non_numeric_yields_empty",
+ query: "/x?vmid=not-a-number",
+ wantTasks: nil,
+ wantStore: nil,
+ wantSnaps: nil,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, tc.query, nil)
+ got := filterPVEBackups(backups, req)
+
+ taskIDs := make([]string, len(got.BackupTasks))
+ for i := range got.BackupTasks {
+ taskIDs[i] = got.BackupTasks[i].ID
+ }
+ storeIDs := make([]string, len(got.StorageBackups))
+ for i := range got.StorageBackups {
+ storeIDs[i] = got.StorageBackups[i].ID
+ }
+ snapIDs := make([]string, len(got.GuestSnapshots))
+ for i := range got.GuestSnapshots {
+ snapIDs[i] = got.GuestSnapshots[i].ID
+ }
+ checkIDs("backupTasks", taskIDs, tc.wantTasks)
+ checkIDs("storageBackups", storeIDs, tc.wantStore)
+ checkIDs("guestSnapshots", snapIDs, tc.wantSnaps)
+ })
+ }
+}
+
+// --- filterReplicationJobs --------------------------------------------------
+
+func TestBranchcov0722PM_FilterReplicationJobs(t *testing.T) {
+ jobs := []models.ReplicationJob{
+ {ID: "j1", Instance: "pve-a", GuestID: 100, GuestName: "vm-100", Guest: "guest100"},
+ {ID: "j2", Instance: "pve-b", GuestID: 200, GuestName: "vm-200", Guest: "guest200"},
+ }
+
+ tests := []struct {
+ name string
+ query string
+ want []string // expected job IDs, in order
+ }{
+ {name: "no_filter_returns_copy_of_all", query: "/x", want: []string{"j1", "j2"}},
+ {name: "platform_proxmox_valid_token", query: "/x?platform=proxmox", want: []string{"j1", "j2"}},
+ {name: "platform_proxmox_pve_valid_token", query: "/x?platform=proxmox-pve", want: []string{"j1", "j2"}},
+ {name: "platform_pve_valid_token", query: "/x?platform=pve", want: []string{"j1", "j2"}},
+ {name: "platform_unknown_returns_empty", query: "/x?platform=vmware", want: nil},
+ {name: "platform_unknown_uppercase_returns_empty", query: "/x?platform=Unknown", want: nil},
+ {name: "instance_match", query: "/x?instance=pve-a", want: []string{"j1"}},
+ {name: "instance_case_insensitive", query: "/x?instance=PVE-B", want: []string{"j2"}},
+ {name: "instance_non_matching", query: "/x?instance=nope", want: nil},
+ {name: "guest_match_by_guest_id", query: "/x?guest=100", want: []string{"j1"}},
+ {name: "guest_match_by_guest_name", query: "/x?guest=vm-200", want: []string{"j2"}},
+ {name: "guest_match_by_guest_field", query: "/x?guest=guest100", want: []string{"j1"}},
+ {name: "guest_non_matching", query: "/x?guest=999", want: nil},
+ {name: "platform_and_instance_combined", query: "/x?platform=pve&instance=pve-b", want: []string{"j2"}},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, tc.query, nil)
+ got := filterReplicationJobs(jobs, req)
+
+ if len(got) != len(tc.want) {
+ t.Fatalf("got %d jobs, want %d (ids=%v)", len(got), len(tc.want), jobIDs(got))
+ }
+ for i := range got {
+ if got[i].ID != tc.want[i] {
+ t.Errorf("job[%d]: got %q, want %q", i, got[i].ID, tc.want[i])
+ }
+ }
+ })
+ }
+}
+
+func jobIDs(jobs []models.ReplicationJob) []string {
+ out := make([]string, len(jobs))
+ for i := range jobs {
+ out[i] = jobs[i].ID
+ }
+ return out
+}
+
+// --- cephDiscoveryTarget ----------------------------------------------------
+
+func TestBranchcov0722PM_CephDiscoveryTarget(t *testing.T) {
+ tests := []struct {
+ name string
+ resource unified.Resource
+ wantNil bool
+ want *unified.DiscoveryTarget
+ }{
+ {
+ name: "non_ceph_resource_nil_ceph_returns_nil",
+ resource: unified.Resource{ID: "r1", Name: "host1"},
+ wantNil: true,
+ },
+ {
+ name: "ceph_nil_and_no_name_or_id_returns_nil",
+ resource: unified.Resource{Ceph: &unified.CephMeta{}},
+ wantNil: true,
+ },
+ {
+ name: "populated_ceph_uses_fsid_as_agent_id",
+ resource: unified.Resource{
+ ID: "ceph-cluster-1",
+ Name: "ceph-prod",
+ Ceph: &unified.CephMeta{FSID: "fsid-aaa", HealthStatus: "HEALTH_OK"},
+ },
+ want: &unified.DiscoveryTarget{
+ ResourceType: "ceph",
+ AgentID: "fsid-aaa",
+ ResourceID: "ceph-cluster-1",
+ Hostname: "ceph-prod",
+ },
+ },
+ {
+ name: "ceph_without_fsid_falls_back_to_name",
+ resource: unified.Resource{
+ ID: "ceph-cluster-2",
+ Name: "ceph-staging",
+ Ceph: &unified.CephMeta{HealthStatus: "HEALTH_WARN"},
+ },
+ want: &unified.DiscoveryTarget{
+ ResourceType: "ceph",
+ AgentID: "ceph-staging",
+ ResourceID: "ceph-cluster-2",
+ Hostname: "ceph-staging",
+ },
+ },
+ {
+ name: "ceph_without_fsid_or_name_falls_back_to_id",
+ resource: unified.Resource{
+ ID: "res-id-only",
+ Ceph: &unified.CephMeta{HealthStatus: "HEALTH_ERR"},
+ },
+ want: &unified.DiscoveryTarget{
+ ResourceType: "ceph",
+ AgentID: "res-id-only",
+ ResourceID: "res-id-only",
+ Hostname: "", // resource.Name is empty
+ },
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got := cephDiscoveryTarget(tc.resource)
+ if tc.wantNil {
+ if got != nil {
+ t.Fatalf("expected nil target, got %+v", got)
+ }
+ return
+ }
+ if got == nil {
+ t.Fatalf("expected non-nil target, got nil")
+ }
+ if got.ResourceType != tc.want.ResourceType {
+ t.Errorf("ResourceType: got %q, want %q", got.ResourceType, tc.want.ResourceType)
+ }
+ if got.AgentID != tc.want.AgentID {
+ t.Errorf("AgentID: got %q, want %q", got.AgentID, tc.want.AgentID)
+ }
+ if got.ResourceID != tc.want.ResourceID {
+ t.Errorf("ResourceID: got %q, want %q", got.ResourceID, tc.want.ResourceID)
+ }
+ if got.Hostname != tc.want.Hostname {
+ t.Errorf("Hostname: got %q, want %q", got.Hostname, tc.want.Hostname)
+ }
+ })
+ }
+}
+
+// --- capMetricPointSeriesByIndex --------------------------------------------
+
+func TestBranchcov0722PM_CapMetricPointSeriesByIndex(t *testing.T) {
+ // 10 distinct points: timestamp == index, value == index.
+ points := make([]MetricPoint, 10)
+ for i := range points {
+ points[i] = MetricPoint{Timestamp: int64(i), Value: float64(i)}
+ }
+
+ tests := []struct {
+ name string
+ points []MetricPoint
+ maxPoints int
+ wantLen int
+ wantFirst int64 // expected first result timestamp
+ wantLast int64 // expected last result timestamp
+ }{
+ {
+ name: "len_le_maxpoints_returned_unchanged",
+ points: points,
+ maxPoints: 15,
+ wantLen: 10,
+ wantFirst: 0,
+ wantLast: 9,
+ },
+ {
+ name: "maxpoints_le_zero_returned_unchanged",
+ points: points,
+ maxPoints: 0,
+ wantLen: 10,
+ wantFirst: 0,
+ wantLast: 9,
+ },
+ {
+ name: "negative_maxpoints_returned_unchanged",
+ points: points,
+ maxPoints: -3,
+ wantLen: 10,
+ wantFirst: 0,
+ wantLast: 9,
+ },
+ {
+ name: "empty_input_returned_unchanged",
+ points: nil,
+ maxPoints: 5,
+ wantLen: 0,
+ wantFirst: 0,
+ wantLast: 0,
+ },
+ {
+ name: "len_gt_maxpoints_samples_keeping_first_and_last",
+ points: points,
+ maxPoints: 3,
+ wantLen: 3,
+ wantFirst: 0, // points[0]
+ wantLast: 9, // points[9]
+ },
+ {
+ name: "maxpoints_one_returns_only_last",
+ points: points,
+ maxPoints: 1,
+ wantLen: 1,
+ wantFirst: 9, // only element is points[len-1]
+ wantLast: 9,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got := capMetricPointSeriesByIndex(tc.points, tc.maxPoints)
+ if len(got) != tc.wantLen {
+ t.Fatalf("len: got %d, want %d", len(got), tc.wantLen)
+ }
+ if tc.wantLen == 0 {
+ return
+ }
+ if got[0].Timestamp != tc.wantFirst {
+ t.Errorf("first timestamp: got %d, want %d", got[0].Timestamp, tc.wantFirst)
+ }
+ if got[len(got)-1].Timestamp != tc.wantLast {
+ t.Errorf("last timestamp: got %d, want %d", got[len(got)-1].Timestamp, tc.wantLast)
+ }
+ // For the maxPoints=3 case, assert the exact sampled middle point
+ // (index 5) so the sampling math — not just the endpoints — is verified.
+ if tc.name == "len_gt_maxpoints_samples_keeping_first_and_last" {
+ if got[1].Timestamp != 5 || got[1].Value != 5 {
+ t.Errorf("middle sampled point: got {ts=%d val=%v}, want {ts=5 val=5}", got[1].Timestamp, got[1].Value)
+ }
+ }
+ if tc.name == "maxpoints_one_returns_only_last" {
+ if got[0].Value != 9 {
+ t.Errorf("single point value: got %v, want 9", got[0].Value)
+ }
+ }
+ })
+ }
+}
+
+// --- deriveInstallJobStatus -------------------------------------------------
+
+func TestBranchcov0722PM_DeriveInstallJobStatus(t *testing.T) {
+ tests := []struct {
+ name string
+ targets []deploy.TargetStatus
+ want deploy.JobStatus
+ }{
+ {name: "empty_targets_succeeded", targets: nil, want: deploy.JobSucceeded},
+ {name: "all_succeeded", targets: []deploy.TargetStatus{deploy.TargetSucceeded, deploy.TargetSucceeded}, want: deploy.JobSucceeded},
+ {name: "all_verifying_counts_as_succeeded", targets: []deploy.TargetStatus{deploy.TargetVerifying}, want: deploy.JobSucceeded},
+ {name: "all_enrolling_counts_as_succeeded", targets: []deploy.TargetStatus{deploy.TargetEnrolling}, want: deploy.JobSucceeded},
+ {name: "all_failed_permanent", targets: []deploy.TargetStatus{deploy.TargetFailedPermanent, deploy.TargetFailedPermanent}, want: deploy.JobFailed},
+ {name: "all_failed_retryable", targets: []deploy.TargetStatus{deploy.TargetFailedRetryable}, want: deploy.JobFailed},
+ {name: "skipped_and_canceled_count_as_failed", targets: []deploy.TargetStatus{deploy.TargetSkippedAgent, deploy.TargetCanceled}, want: deploy.JobFailed},
+ {name: "pending_default_branch_counts_as_failed", targets: []deploy.TargetStatus{deploy.TargetPending, deploy.TargetPending}, want: deploy.JobFailed},
+ {name: "installing_default_branch_counts_as_failed", targets: []deploy.TargetStatus{deploy.TargetInstalling}, want: deploy.JobFailed},
+ {name: "mixed_succeeded_and_failed_partial", targets: []deploy.TargetStatus{deploy.TargetSucceeded, deploy.TargetFailedPermanent}, want: deploy.JobPartialSuccess},
+ {name: "succeeded_plus_pending_partial", targets: []deploy.TargetStatus{deploy.TargetSucceeded, deploy.TargetPending}, want: deploy.JobPartialSuccess},
+ {name: "enrolling_plus_failed_partial", targets: []deploy.TargetStatus{deploy.TargetEnrolling, deploy.TargetFailedRetryable}, want: deploy.JobPartialSuccess},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ targets := make([]deploy.Target, len(tc.targets))
+ for i, s := range tc.targets {
+ targets[i] = deploy.Target{ID: "tgt", Status: s}
+ }
+ got := deriveInstallJobStatus(targets)
+ if got != tc.want {
+ t.Errorf("got %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
diff --git a/internal/api/helpers_branchcov0722pm_test.go b/internal/api/helpers_branchcov0722pm_test.go
new file mode 100644
index 0000000000..dde8812513
--- /dev/null
+++ b/internal/api/helpers_branchcov0722pm_test.go
@@ -0,0 +1,283 @@
+package api
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+)
+
+// This file raises branch/function coverage for a set of previously
+// uncovered pure helper functions across the internal/api package:
+// - normalizePBSUser / normalizePMGUser (config_node_handlers.go)
+// - canonicalAutoRegisterCheckMissingFieldsMessage (config_setup_handlers.go)
+// - redactMagicLinkURL (magic_link.go)
+// - metadataSaveErrorMessage (metadata_helpers.go)
+// - shellQuote (docker_container_action_executor.go)
+// - dockerPodmanAgentCommandCount (diagnostics.go)
+// - hostedEntitlementRefreshBackoff (hosted_entitlement_refresh.go)
+//
+// Every top-level function is prefixed with TestBranchcov0722PM so the run
+// can be scoped with -run "^TestBranchcov0722PM".
+
+// panics reports whether f panics when invoked. Used only to document the
+// nil-deref behaviour of metadataSaveErrorMessage (a latent robustness bug
+// that is reported, not fixed).
+func panics(f func()) (did bool) {
+ defer func() { did = recover() != nil }()
+ f()
+ return
+}
+
+func TestBranchcov0722PMNormalizePBSUser(t *testing.T) {
+ cases := []struct{ name, in, want string }{
+ {"empty_returns_empty", "", ""},
+ {"whitespace_returns_empty", " ", ""},
+ {"plain_appends_suffix", "root", "root@pbs"},
+ {"trims_then_appends", " root ", "root@pbs"},
+ {"email_passthrough", "[email protected]", "[email protected]"},
+ {"email_passthrough_after_trim", " [email protected] ", "[email protected]"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := normalizePBSUser(tc.in); got != tc.want {
+ t.Fatalf("normalizePBSUser(%q) = %q, want %q", tc.in, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestBranchcov0722PMNormalizePMGUser(t *testing.T) {
+ cases := []struct{ name, in, want string }{
+ {"empty_returns_empty", "", ""},
+ {"whitespace_returns_empty", "\t\n", ""},
+ {"plain_appends_suffix", "admin", "admin@pmg"},
+ {"trims_then_appends", " admin ", "admin@pmg"},
+ {"email_passthrough", "[email protected]", "[email protected]"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := normalizePMGUser(tc.in); got != tc.want {
+ t.Fatalf("normalizePMGUser(%q) = %q, want %q", tc.in, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestBranchcov0722PMCanonicalAutoRegisterCheckMissingFieldsMessage(t *testing.T) {
+ const base = "Missing required canonical auto-register check fields"
+ cases := []struct {
+ name string
+ typeValue, host, serverName string
+ want string
+ }{
+ {"all_present", "pve", "10.0.0.1", "node1", base},
+ {"whitespace_counts_as_missing", " ", "10.0.0.1", "node1", base + ": type"},
+ {"type_missing", "", "10.0.0.1", "node1", base + ": type"},
+ {"host_missing", "pve", "", "node1", base + ": host"},
+ {"serverName_missing", "pve", "10.0.0.1", "", base + ": serverName"},
+ {"type_and_host_missing", "", "", "node1", base + ": type, host"},
+ {"all_missing", "", "", "", base + ": type, host, serverName"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := canonicalAutoRegisterCheckMissingFieldsMessage(tc.typeValue, tc.host, tc.serverName)
+ if got != tc.want {
+ t.Fatalf("canonicalAutoRegisterCheckMissingFieldsMessage(%q,%q,%q) = %q, want %q",
+ tc.typeValue, tc.host, tc.serverName, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestBranchcov0722PMRedactMagicLinkURL(t *testing.T) {
+ cases := []struct {
+ name, in, want, leak string
+ }{
+ {
+ name: "token_in_query_stripped",
+ in: "https://mail.example.com/accept?token=ml1_SUPERSECRET",
+ want: "https://mail.example.com/accept",
+ leak: "ml1_SUPERSECRET",
+ },
+ {
+ name: "token_in_fragment_stripped",
+ in: "https://mail.example.com/accept#token=ml1_FRAGSECRET",
+ want: "https://mail.example.com/accept",
+ leak: "ml1_FRAGSECRET",
+ },
+ {
+ name: "token_in_query_and_fragment_stripped",
+ in: "https://mail.example.com/accept?token=ml1_Q#token=ml1_F",
+ want: "https://mail.example.com/accept",
+ leak: "ml1_Q",
+ },
+ {
+ name: "path_preserved_with_creds_dropped",
+ in: "https://app.test/a/b/c?token=ml1_X&other=keep#ml1_Y",
+ want: "https://app.test/a/b/c",
+ leak: "ml1_X",
+ },
+ {
+ // Unclosed IPv6 host bracket -> url.Parse reports an error -> "".
+ name: "malformed_unparseable_returns_empty",
+ in: "http://[",
+ want: "",
+ },
+ {
+ name: "empty_returns_empty",
+ in: "",
+ want: "",
+ },
+ {
+ name: "whitespace_only_returns_empty",
+ in: " ",
+ want: "",
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := redactMagicLinkURL(tc.in)
+ if got != tc.want {
+ t.Fatalf("redactMagicLinkURL(%q) = %q, want %q", tc.in, got, tc.want)
+ }
+ // Security invariant: the secret token must never survive redaction.
+ if tc.leak != "" && strings.Contains(got, tc.leak) {
+ t.Fatalf("secret %q leaked into redacted output %q", tc.leak, got)
+ }
+ // And defensively, neither the fragment value nor the literal key.
+ if strings.Contains(got, "token=") {
+ t.Fatalf("token query key leaked into redacted output %q", got)
+ }
+ })
+ }
+}
+
+func TestBranchcov0722PMMetadataSaveErrorMessage(t *testing.T) {
+ cases := []struct {
+ name string
+ err error
+ want string
+ }{
+ {
+ name: "permission_substring",
+ err: errors.New("disk permission denied by OS"),
+ want: "Permission denied - check file permissions",
+ },
+ {
+ name: "wrapped_permission",
+ err: fmt.Errorf("save failed: %w", errors.New("permission issue")),
+ want: "Permission denied - check file permissions",
+ },
+ {
+ name: "no_space_substring",
+ err: errors.New("write failed: no space left on device"),
+ want: "Disk full - cannot save metadata",
+ },
+ {
+ name: "plain_error_default",
+ err: errors.New("network timeout"),
+ want: "Failed to save metadata",
+ },
+ {
+ name: "wrapped_plain_error_default",
+ err: fmt.Errorf("boom: %w", errors.New("database locked")),
+ want: "Failed to save metadata",
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := metadataSaveErrorMessage(tc.err); got != tc.want {
+ t.Fatalf("metadataSaveErrorMessage(%v) = %q, want %q", tc.err, got, tc.want)
+ }
+ })
+ }
+
+ // The signature accepts (err error) but the body calls err.Error()
+ // unconditionally, so a nil error is NOT safe: it nil-derefs. Assert that
+ // real behaviour and surface it as a latent robustness bug (reported, not fixed).
+ t.Run("nil_panics_nil_deref_bug", func(t *testing.T) {
+ if !panics(func() { _ = metadataSaveErrorMessage(nil) }) {
+ t.Fatalf("expected metadataSaveErrorMessage(nil) to panic (nil deref in err.Error()), but it did not")
+ }
+ })
+}
+
+func TestBranchcov0722PMShellQuote(t *testing.T) {
+ cases := []struct {
+ name, in, want string
+ }{
+ {"empty", "", "''"},
+ {"plain", "hello", "'hello'"},
+ {"spaces_preserved", "hello world", "'hello world'"},
+ {"newline_preserved", "line1\nline2", "'line1\nline2'"},
+ {"tab_preserved", "a\tb", "'a\tb'"},
+ {"single_quote_escaped", "a'b", `'a'"'"'b'`},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := shellQuote(tc.in); got != tc.want {
+ t.Fatalf("shellQuote(%q) = %q, want %q", tc.in, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestBranchcov0722PMDockerPodmanAgentCommandCount(t *testing.T) {
+ cases := []struct {
+ name string
+ in int
+ want string
+ }{
+ {"zero_uses_plural", 0, "0 Docker / Podman module commands"},
+ {"singular", 1, "1 Docker / Podman module command"},
+ {"plural", 3, "3 Docker / Podman module commands"},
+ {"plural_large", 42, "42 Docker / Podman module commands"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := dockerPodmanAgentCommandCount(tc.in); got != tc.want {
+ t.Fatalf("dockerPodmanAgentCommandCount(%d) = %q, want %q", tc.in, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestBranchcov0722PMHostedEntitlementRefreshBackoff(t *testing.T) {
+ const (
+ def = 2 * time.Hour
+ backoffMin = 30 * time.Second
+ backoffMax = 30 * time.Minute
+ )
+ cases := []struct {
+ name string
+ in int
+ want time.Duration
+ }{
+ {"zero_uses_default_interval", 0, def},
+ {"negative_uses_default_interval", -5, def},
+ {"failure_1", 1, backoffMin}, // 30s * (1<<0) = 30s
+ {"failure_2", 2, 2 * backoffMin}, // 30s * (1<<1) = 60s
+ {"failure_3", 3, 4 * backoffMin}, // 30s * (1<<2) = 120s
+ {"failure_6_below_cap", 6, 32 * backoffMin}, // 30s * (1<<5) = 960s = 16m < 30m
+ {"failure_7_hits_cap", 7, backoffMax}, // 30s * (1<<6) = 1920s = 32m > 30m
+ {"failure_11_shift_clamped", 11, backoffMax}, // (1<<min(10,10)) -> capped
+ {"huge_count_capped", 100000, backoffMax}, // (1<<10) -> capped
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := hostedEntitlementRefreshBackoff(tc.in)
+ if got != tc.want {
+ t.Fatalf("hostedEntitlementRefreshBackoff(%d) = %v, want %v", tc.in, got, tc.want)
+ }
+ })
+ }
+
+ // Contract: a strictly positive backoff for every possible input.
+ for _, failures := range []int{-100, -1, 0, 1, 5, 50, 100000} {
+ if d := hostedEntitlementRefreshBackoff(failures); d <= 0 {
+ t.Fatalf("hostedEntitlementRefreshBackoff(%d) returned non-positive duration %v", failures, d)
+ }
+ }
+}
diff --git a/internal/api/ledger_licensing_branchcov0722pm_test.go b/internal/api/ledger_licensing_branchcov0722pm_test.go
new file mode 100644
index 0000000000..c1c6ffe3b8
--- /dev/null
+++ b/internal/api/ledger_licensing_branchcov0722pm_test.go
@@ -0,0 +1,420 @@
+package api
+
+import (
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/unified"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"
+)
+
+func assertPanicsBranchcov0722PM(t *testing.T, fn func()) {
+ t.Helper()
+ defer func() {
+ if r := recover(); r == nil {
+ t.Fatal("expected panic, but call returned normally")
+ }
+ }()
+ fn()
+}
+
+func bcovPtrTime(v time.Time) *time.Time {
+ return &v
+}
+
+func TestBranchcov0722PM_MonitoredSystemLedgerStatusSummary(t *testing.T) {
+ tests := []struct {
+ name string
+ status string
+ want string
+ }{
+ {"online", "online", "All included top-level collection paths currently report online status."},
+ {"warning", "warning", "At least one included top-level collection path is degraded, so Pulse marks this monitored system as warning."},
+ {"offline", "offline", "At least one included source is offline or disconnected, so Pulse marks this monitored system as offline."},
+ {"unknown_falls_through_default", "unknown", "Pulse cannot determine a canonical runtime status for this monitored system yet."},
+ {"empty_status_default", "", "Pulse cannot determine a canonical runtime status for this monitored system yet."},
+ {"unrecognized_status_default", "degraded", "Pulse cannot determine a canonical runtime status for this monitored system yet."},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := defaultMonitoredSystemLedgerStatusSummary(tt.status)
+ if got != tt.want {
+ t.Errorf("defaultMonitoredSystemLedgerStatusSummary(%q) = %q, want %q", tt.status, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestBranchcov0722PM_ErrMonitoredSystemLedgerValidation(t *testing.T) {
+ const message = "candidate.source is required"
+ err := errMonitoredSystemLedgerValidation(message)
+
+ if err == nil {
+ t.Fatal("expected non-nil error")
+ }
+ if got := err.Error(); got != message {
+ t.Errorf("Error() = %q, want %q", got, message)
+ }
+
+ var typed monitoredSystemLedgerValidationError
+ if !errors.As(err, &typed) {
+ t.Fatalf("error is not classifiable as monitoredSystemLedgerValidationError (errors.As): %T", err)
+ }
+ if string(typed) != message {
+ t.Errorf("typed error payload = %q, want %q", string(typed), message)
+ }
+
+ if errors.Is(err, errMalformedLicenseSentinel) {
+ t.Errorf("validation error must not be confused with a license sentinel error")
+ }
+}
+
+func TestBranchcov0722PM_CommunityRuntimeIdentityFromLicensing(t *testing.T) {
+ got := communityRuntimeIdentityFromLicensing()
+
+ if got.Build != "community" {
+ t.Errorf("Build = %q, want %q", got.Build, "community")
+ }
+ if got.Label != "Pulse Community runtime" {
+ t.Errorf("Label = %q, want %q", got.Label, "Pulse Community runtime")
+ }
+ if got.DownloadURL != "" {
+ t.Errorf("DownloadURL = %q, want empty", got.DownloadURL)
+ }
+}
+
+func TestBranchcov0722PM_NormalizeDowngradeRetentionStateFromLicensing(t *testing.T) {
+ t.Run("already_normal_returned_unchanged", func(t *testing.T) {
+ in := downgradeRetentionStateModel{
+ PreviousTier: "pro",
+ CurrentTier: "free",
+ PreviousHistoryDays: 90,
+ CurrentHistoryDays: 7,
+ DetectedAt: 111,
+ RecoveryGuaranteedTo: 222,
+ PurgeEligibleAt: 333,
+ }
+ got := normalizeDowngradeRetentionStateFromLicensing(in)
+ if got != in {
+ t.Errorf("already-normal state was mutated: got %+v, want %+v", got, in)
+ }
+ })
+
+ t.Run("previous_tier_clamped", func(t *testing.T) {
+ in := downgradeRetentionStateModel{
+ PreviousTier: " PRO ",
+ CurrentTier: "free",
+ PreviousHistoryDays: 90,
+ DetectedAt: 111,
+ }
+ got := normalizeDowngradeRetentionStateFromLicensing(in)
+ if got.PreviousTier != "pro" {
+ t.Errorf("PreviousTier = %q, want %q", got.PreviousTier, "pro")
+ }
+ if got.CurrentTier != "free" {
+ t.Errorf("CurrentTier = %q, want %q", got.CurrentTier, "free")
+ }
+ if got.PreviousHistoryDays != 90 || got.DetectedAt != 111 {
+ t.Errorf("non-tier field changed: got %+v", got)
+ }
+ })
+
+ t.Run("current_tier_clamped", func(t *testing.T) {
+ in := downgradeRetentionStateModel{
+ PreviousTier: "pro",
+ CurrentTier: "\tFREE\n",
+ CurrentHistoryDays: 7,
+ }
+ got := normalizeDowngradeRetentionStateFromLicensing(in)
+ if got.CurrentTier != "free" {
+ t.Errorf("CurrentTier = %q, want %q", got.CurrentTier, "free")
+ }
+ if got.PreviousTier != "pro" {
+ t.Errorf("PreviousTier = %q, want %q", got.PreviousTier, "pro")
+ }
+ })
+
+ t.Run("both_tiers_uppercase_trimmed", func(t *testing.T) {
+ in := downgradeRetentionStateModel{
+ PreviousTier: "RELAY",
+ CurrentTier: "FREE",
+ }
+ got := normalizeDowngradeRetentionStateFromLicensing(in)
+ if got.PreviousTier != "relay" || got.CurrentTier != "free" {
+ t.Errorf("tiers = (%q,%q), want (relay,free)", got.PreviousTier, got.CurrentTier)
+ }
+ })
+}
+
+func TestBranchcov0722PM_WantsMockFixturesFromEnv(t *testing.T) {
+ tests := []struct {
+ name string
+ value string
+ want bool
+ }{
+ {"set_true", "true", true},
+ {"set_true_case_insensitive_and_padded", " True ", true},
+ {"set_false", "false", false},
+ {"junk_value", "banana", false},
+ {"empty_equivalent_to_unset", "", false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Setenv("PULSE_MOCK_MODE", tt.value)
+ if got := wantsMockFixturesFromEnv(); got != tt.want {
+ t.Errorf("wantsMockFixturesFromEnv() with PULSE_MOCK_MODE=%q = %v, want %v", tt.value, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestBranchcov0722PM_UnifiedLifecycleFromAI(t *testing.T) {
+ t.Run("nil_or_empty_returns_nil", func(t *testing.T) {
+ if got := unifiedLifecycleFromAI(nil); got != nil {
+ t.Errorf("unifiedLifecycleFromAI(nil) = %+v, want nil", got)
+ }
+ if got := unifiedLifecycleFromAI([]ai.FindingLifecycleEvent{}); got != nil {
+ t.Errorf("unifiedLifecycleFromAI(empty) = %+v, want nil", got)
+ }
+ })
+
+ at1 := time.Date(2026, 7, 22, 9, 0, 0, 0, time.UTC)
+ at2 := time.Date(2026, 7, 22, 9, 30, 0, 0, time.UTC)
+
+ t.Run("populated_events_converted_field_for_field", func(t *testing.T) {
+ in := []ai.FindingLifecycleEvent{
+ {
+ At: at1,
+ Type: "detected",
+ Message: "first detection",
+ To: "active",
+ Metadata: map[string]string{
+ "run_id": "r-1",
+ "host": "tower",
+ },
+ },
+ {
+ At: at2,
+ Type: "remediated",
+ From: "active",
+ To: "resolved",
+ },
+ }
+ got := unifiedLifecycleFromAI(in)
+ if len(got) != len(in) {
+ t.Fatalf("len = %d, want %d", len(got), len(in))
+ }
+
+ if got[0].At != at1 || got[0].Type != "detected" || got[0].Message != "first detection" || got[0].To != "active" || got[0].From != "" {
+ t.Errorf("event[0] mismatched: %+v", got[0])
+ }
+ if got[0].Metadata == nil || got[0].Metadata["run_id"] != "r-1" || got[0].Metadata["host"] != "tower" {
+ t.Errorf("event[0].Metadata not preserved: %+v", got[0].Metadata)
+ }
+
+ if got[1].At != at2 || got[1].Type != "remediated" || got[1].From != "active" || got[1].To != "resolved" || got[1].Message != "" {
+ t.Errorf("event[1] mismatched: %+v", got[1])
+ }
+ if got[1].Metadata != nil {
+ t.Errorf("event[1].Metadata = %+v, want nil", got[1].Metadata)
+ }
+ })
+}
+
+func TestBranchcov0722PM_UnifiedFindingFromAI(t *testing.T) {
+ t.Run("nil_input_panics", func(t *testing.T) {
+ assertPanicsBranchcov0722PM(t, func() { _ = unifiedFindingFromAI(nil) })
+ })
+
+ t.Run("minimal_finding", func(t *testing.T) {
+ in := &ai.Finding{
+ ID: "f-min",
+ Title: "Minimal",
+ Severity: ai.FindingSeverityInfo,
+ Category: ai.FindingCategoryGeneral,
+ }
+ got := unifiedFindingFromAI(in)
+ if got == nil {
+ t.Fatal("expected non-nil unified finding")
+ }
+ if got.ID != "f-min" {
+ t.Errorf("ID = %q, want %q", got.ID, "f-min")
+ }
+ if got.Title != "Minimal" {
+ t.Errorf("Title = %q, want %q", got.Title, "Minimal")
+ }
+ if got.Source != unified.SourceAIPatrol {
+ t.Errorf("Source = %q, want %q", got.Source, unified.SourceAIPatrol)
+ }
+ if got.Severity != unified.SeverityInfo {
+ t.Errorf("Severity = %q, want %q", got.Severity, unified.SeverityInfo)
+ }
+ if got.Category != unified.CategoryGeneral {
+ t.Errorf("Category = %q, want %q", got.Category, unified.CategoryGeneral)
+ }
+ if got.Lifecycle != nil {
+ t.Errorf("Lifecycle = %+v, want nil", got.Lifecycle)
+ }
+ })
+
+ t.Run("fully_populated_finding", func(t *testing.T) {
+ detected := time.Date(2026, 7, 22, 8, 0, 0, 0, time.UTC)
+ lastSeen := time.Date(2026, 7, 22, 8, 15, 0, 0, time.UTC)
+ resolved := time.Date(2026, 7, 22, 9, 0, 0, 0, time.UTC)
+ lastInvestigated := time.Date(2026, 7, 22, 8, 45, 0, 0, time.UTC)
+ lastRegression := time.Date(2026, 7, 21, 9, 0, 0, 0, time.UTC)
+ acknowledged := time.Date(2026, 7, 22, 8, 5, 0, 0, time.UTC)
+ snoozed := time.Date(2026, 7, 23, 0, 0, 0, 0, time.UTC)
+ remind := time.Date(2026, 7, 24, 0, 0, 0, 0, time.UTC)
+ investigationRecord := &aicontracts.InvestigationRecord{}
+
+ in := &ai.Finding{
+ ID: "f-full",
+ Severity: ai.FindingSeverityWarning,
+ Category: ai.FindingCategoryCapacity,
+ ResourceID: "res-1",
+ ResourceName: "tower",
+ ResourceType: "host",
+ Node: "node-1",
+ Title: "Disk filling up",
+ Description: "Root partition at 92%.",
+ Impact: "System may become unresponsive.",
+ PreviousResolvedFixSummary: "Cleared old logs on 2026-07-10.",
+ Recommendation: "Prune /var/log archives.",
+ Evidence: "df -h / => 92%",
+ DetectedAt: detected,
+ LastSeenAt: lastSeen,
+ ResolvedAt: &resolved,
+ AutoResolved: true,
+ InvestigationSessionID: "sess-1",
+ InvestigationStatus: "completed",
+ InvestigationOutcome: "fix_verified",
+ LastInvestigatedAt: &lastInvestigated,
+ InvestigationAttempts: 3,
+ InvestigationRecord: investigationRecord,
+ LoopState: "resolved",
+ Lifecycle: []ai.FindingLifecycleEvent{
+ {
+ At: detected,
+ Type: "detected",
+ Message: "first seen",
+ To: "active",
+ Metadata: map[string]string{
+ "run_id": "r-1",
+ },
+ },
+ {
+ At: resolved,
+ Type: "remediated",
+ From: "active",
+ To: "resolved",
+ },
+ },
+ RegressionCount: 2,
+ LastRegressionAt: &lastRegression,
+ AcknowledgedAt: &acknowledged,
+ SnoozedUntil: &snoozed,
+ DismissedReason: "will_fix_later",
+ UserNote: "watch over the weekend",
+ Suppressed: false,
+ TimesRaised: 5,
+ RemindAt: &remind,
+ }
+
+ got := unifiedFindingFromAI(in)
+ if got == nil {
+ t.Fatal("expected non-nil unified finding")
+ }
+
+ if got.ID != "f-full" {
+ t.Errorf("ID = %q", got.ID)
+ }
+ if got.Source != unified.SourceAIPatrol {
+ t.Errorf("Source = %q, want %q", got.Source, unified.SourceAIPatrol)
+ }
+ if got.Severity != unified.SeverityWarning {
+ t.Errorf("Severity = %q, want %q", got.Severity, unified.SeverityWarning)
+ }
+ if got.Category != unified.CategoryCapacity {
+ t.Errorf("Category = %q, want %q", got.Category, unified.CategoryCapacity)
+ }
+ if got.ResourceID != "res-1" || got.ResourceName != "tower" || got.ResourceType != "host" || got.Node != "node-1" {
+ t.Errorf("resource fields mismatched: %+v", got)
+ }
+ if got.Title != "Disk filling up" || got.Description != "Root partition at 92%." {
+ t.Errorf("title/description mismatched: %+v", got)
+ }
+ if got.Impact != "System may become unresponsive." {
+ t.Errorf("Impact = %q", got.Impact)
+ }
+ if got.PreviousResolvedFixSummary != "Cleared old logs on 2026-07-10." {
+ t.Errorf("PreviousResolvedFixSummary = %q", got.PreviousResolvedFixSummary)
+ }
+ if got.Recommendation != "Prune /var/log archives." || got.Evidence != "df -h / => 92%" {
+ t.Errorf("recommendation/evidence mismatched: %+v", got)
+ }
+ if got.DetectedAt != detected || got.LastSeenAt != lastSeen {
+ t.Errorf("timestamps mismatched: detected=%v lastSeen=%v", got.DetectedAt, got.LastSeenAt)
+ }
+ if got.ResolvedAt == nil || *got.ResolvedAt != resolved {
+ t.Errorf("ResolvedAt = %+v, want %v", got.ResolvedAt, resolved)
+ }
+ if !got.AutoResolved {
+ t.Errorf("AutoResolved = false, want true")
+ }
+ if got.InvestigationSessionID != "sess-1" || got.InvestigationStatus != "completed" || got.InvestigationOutcome != "fix_verified" {
+ t.Errorf("investigation identity/status mismatched: %+v", got)
+ }
+ if got.LastInvestigatedAt == nil || *got.LastInvestigatedAt != lastInvestigated {
+ t.Errorf("LastInvestigatedAt = %+v, want %v", got.LastInvestigatedAt, lastInvestigated)
+ }
+ if got.InvestigationAttempts != 3 {
+ t.Errorf("InvestigationAttempts = %d, want 3", got.InvestigationAttempts)
+ }
+ if got.InvestigationRecord != investigationRecord {
+ t.Errorf("InvestigationRecord pointer not preserved: %p vs %p", got.InvestigationRecord, investigationRecord)
+ }
+ if got.LoopState != "resolved" {
+ t.Errorf("LoopState = %q", got.LoopState)
+ }
+ if got.RegressionCount != 2 {
+ t.Errorf("RegressionCount = %d, want 2", got.RegressionCount)
+ }
+ if got.LastRegressionAt == nil || *got.LastRegressionAt != lastRegression {
+ t.Errorf("LastRegressionAt = %+v, want %v", got.LastRegressionAt, lastRegression)
+ }
+ if got.AcknowledgedAt == nil || *got.AcknowledgedAt != acknowledged {
+ t.Errorf("AcknowledgedAt = %+v, want %v", got.AcknowledgedAt, acknowledged)
+ }
+ if got.SnoozedUntil == nil || *got.SnoozedUntil != snoozed {
+ t.Errorf("SnoozedUntil = %+v, want %v", got.SnoozedUntil, snoozed)
+ }
+ if got.DismissedReason != "will_fix_later" || got.UserNote != "watch over the weekend" {
+ t.Errorf("dismissed/usernote mismatched: %+v", got)
+ }
+ if got.Suppressed {
+ t.Errorf("Suppressed = true, want false")
+ }
+ if got.TimesRaised != 5 {
+ t.Errorf("TimesRaised = %d, want 5", got.TimesRaised)
+ }
+ if got.RemindAt == nil || *got.RemindAt != remind {
+ t.Errorf("RemindAt = %+v, want %v", got.RemindAt, remind)
+ }
+
+ if len(got.Lifecycle) != 2 {
+ t.Fatalf("Lifecycle len = %d, want 2", len(got.Lifecycle))
+ }
+ if got.Lifecycle[0].At != detected || got.Lifecycle[0].Type != "detected" || got.Lifecycle[0].Message != "first seen" || got.Lifecycle[0].To != "active" {
+ t.Errorf("lifecycle[0] mismatched: %+v", got.Lifecycle[0])
+ }
+ if got.Lifecycle[0].Metadata == nil || got.Lifecycle[0].Metadata["run_id"] != "r-1" {
+ t.Errorf("lifecycle[0].Metadata not preserved: %+v", got.Lifecycle[0].Metadata)
+ }
+ if got.Lifecycle[1].Type != "remediated" || got.Lifecycle[1].From != "active" || got.Lifecycle[1].To != "resolved" {
+ t.Errorf("lifecycle[1] mismatched: %+v", got.Lifecycle[1])
+ }
+ })
+}