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.

Count each finished Patrol investigation once in the weekly digest

rcourtmanb633e5410548
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 045699ff64..8ef31a95b2 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -9452,6 +9452,11 @@ Persisted report attempts and email retries retain that boundary. Recovery of a
report delivery never replays an infrastructure action or grants an agent new
execution authority.
+The 23 October 2026 change to how the digest counts investigation runs, and to
+how `internal/api/patrol_digest_email.go` words their outcomes, is read-only
+counting and copy. The email still renders the digest and issues no agent
+command, plan, capability, token, or binding change.
+
### Independent module CPU sampling baselines
The host default system collector retains its own `hostmetrics.Collector` for
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 1c5d9f5bf3..79e67d6831 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -7150,6 +7150,27 @@ longer reaches the start of the window. Unknown model pricing is reported as
`PatrolDigest`. Proofs: `internal/ai/patrol_digest_test.go` and
`frontend-modern/src/api/__tests__/patrol.test.ts`.
+Since 23 October 2026 the digest counts investigation runs, not outcome rows.
+`digestInvestigationRuns` counts one investigation for each run that finished
+inside the window, from the lifecycle rows the findings store already writes
+for every run: the `investigation_updated` row that moves the status out of
+`running` (or out of the empty status a regression set while the run was
+open), or, for a run whose own fix was verified while it was open, the
+`verification_passed` row, after which a closing row belongs to the same run.
+Later `investigation_outcome` and `verification_passed` rows from the action
+lifecycle relabel the latest finished run with its fix's result instead of
+counting again, so a queued fix that is later run and verified is one
+investigation ending `fix_verified`. A run that failed with no outcome is
+`failed`, the bucket telemetry already uses. The summary-field
+(`LastInvestigatedAt`) fallback is gone: every run since the v6 release writes
+lifecycle rows, and the fallback could count one run in two adjacent weeks.
+Lifecycle rows carry no session ID, so a late end written by an older run reads
+as the end of the open run, and a run whose rows the 50-row lifecycle has
+dropped is not counted. Before this the digest counted only
+`investigation_outcome` rows and read their outcome from a `metadata["outcome"]`
+key the store never writes, so every one was `unknown`. Proof:
+`internal/ai/patrol_digest_test.go` drives the store's own writers.
+
### Patrol digest client is the only consumer path
`getPatrolDigest(days)` in `frontend-modern/src/api/patrol.ts` is the single
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 1567cc8f6f..2e86f8072d 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -12028,6 +12028,16 @@ an error so clients can render an honest "Patrol has not run" state, and
`frontend-modern/src/api/__tests__/patrol.test.ts`, and
`frontend-modern/src/utils/__tests__/docsLinks.test.ts`.
+Since 23 October 2026 `investigations.total` counts investigation runs that
+finished in the window, one per run, and `investigations.by_outcome` keys are
+investigation outcomes plus `failed`, a run that ended on an error with no
+outcome, and `unknown`, a finished run with no recorded outcome. The field set
+is unchanged. The weekly email words `failed` as "ended with an error", and when
+no outcome in the breakdown has wording it shows the count without a detail line
+rather than "No issues needed a closer look." Proofs:
+`internal/api/contract_test.go` (findings store writers through
+`BuildPatrolDigest` to the email) and `internal/api/patrol_digest_email_test.go`.
+
### Patrol digest client mirrors the endpoint exactly
The `PatrolDigest` types and `getPatrolDigest` client in
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 1b49b14167..b0670e6802 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -6624,6 +6624,11 @@ file under the tenant `reports` directory and never calls the retention prune;
the email body is the only artifact. Recovery and retention state are
unaffected.
+The 23 October 2026 change to how the digest counts investigation runs, and to
+how `internal/api/patrol_digest_email.go` words their outcomes, reads the same
+in-memory findings store and writes nothing. It opens no backup, snapshot,
+retention, cleanup or recovery path.
+
Legacy `incident_windows.json` recovery is read-only through
`internal/metrics/incident_archive.go`. Construction does not read the file, and
explicit reads neither expire records nor rewrite contents or permissions.
diff --git a/internal/ai/patrol_digest.go b/internal/ai/patrol_digest.go
index ff9cdaf554..5f5424b714 100644
--- a/internal/ai/patrol_digest.go
+++ b/internal/ai/patrol_digest.go
@@ -81,7 +81,9 @@ type PatrolDigestFindings struct {
Suppressed int `json:"suppressed"`
}
-// PatrolDigestInvestigations summarises completed investigations by outcome.
+// PatrolDigestInvestigations summarises the investigation runs that finished
+// in the window, one per run, by how each ended. A run whose fix later ran or
+// was verified carries that later outcome.
type PatrolDigestInvestigations struct {
Total int `json:"total"`
ByOutcome map[string]int `json:"by_outcome"`
@@ -314,7 +316,6 @@ func summarizeDigestFindings(digest *PatrolDigest, findings []*Finding, inWindow
if f.ResolvedAt != nil && inWindow(*f.ResolvedAt) && !f.AutoResolved {
manualResolved++
}
- investigationEvents := 0
for _, event := range f.Lifecycle {
if !inWindow(event.At) {
continue
@@ -324,37 +325,93 @@ func summarizeDigestFindings(digest *PatrolDigest, findings []*Finding, inWindow
digest.Findings.Dismissed++
case "suppressed":
digest.Findings.Suppressed++
- case "investigation_outcome":
- investigationEvents++
- digest.Investigations.Total++
- digest.Investigations.ByOutcome[digestOutcomeLabel("", event.Metadata)]++
}
}
- // Findings that predate lifecycle logging, or were investigated through a
- // path that only stamps the summary fields, still count once.
- if investigationEvents == 0 && f.LastInvestigatedAt != nil && inWindow(*f.LastInvestigatedAt) {
+ for _, outcome := range digestInvestigationRuns(f.Lifecycle, inWindow) {
digest.Investigations.Total++
- digest.Investigations.ByOutcome[digestOutcomeLabel(f.InvestigationOutcome, nil)]++
+ digest.Investigations.ByOutcome[outcome]++
}
}
digest.Findings.Resolved = digest.Findings.AutoResolved + manualResolved
}
-// digestOutcomeLabel reads the investigation outcome from a lifecycle event.
-// The "investigation_outcome" event stores the outcome in metadata and keeps
-// From/To for the loop state, so metadata wins and To is only a fallback.
-func digestOutcomeLabel(fallback string, metadata map[string]string) string {
- outcome := ""
- if metadata != nil {
- outcome = strings.TrimSpace(metadata["outcome"])
+// digestInvestigationRuns returns how each investigation run recorded in a
+// finding's lifecycle ended, for the runs that finished inside the window.
+// Each run counts once, in the window it finished. The lifecycle keeps a
+// finding's latest 50 rows, so a run whose rows it has already dropped is not
+// counted.
+//
+// A run's start and end are "investigation_updated" rows that move the status
+// into and out of running; a regression clears the status of a run still in
+// progress, so its end can also start from an empty status. A run whose own
+// fix is verified while it is open logs "verification_passed" at that
+// verification and no closing row, unless stuck-run recovery closes it or its
+// own end records a different outcome. The digest counts such a run at the
+// verification, keeps the verified result, and treats a closing row that
+// follows as the same run. A run whose end the store never records stays open
+// here until the next run starts, and a verification of its fix in that time
+// finishes it. After a run finishes, its fix can still move through the action
+// lifecycle ("investigation_outcome", then "verification_passed" once
+// verified); those rows relabel the latest finished run rather than counting
+// as another investigation. Rows carry no session ID, so the walker relies on
+// their order: a late end written by an older run reads as the end of
+// whichever run is open.
+func digestInvestigationRuns(lifecycle []FindingLifecycleEvent, inWindow func(time.Time) bool) []string {
+ running := string(InvestigationStatusRunning)
+ var finished []*string
+ var latest *string
+ open, closedByVerification := false, false
+ finish := func(outcome string, at time.Time) {
+ latest = &outcome
+ if inWindow(at) {
+ finished = append(finished, latest)
+ }
}
- if outcome == "" {
- outcome = strings.TrimSpace(fallback)
+ for _, event := range lifecycle {
+ switch event.Type {
+ case "investigation_updated":
+ prev := strings.TrimSpace(event.Metadata["prev_status"])
+ next := strings.TrimSpace(event.Metadata["next_status"])
+ switch {
+ case next == running:
+ open, closedByVerification = true, false
+ case next != "" && (prev == running || open):
+ if !closedByVerification {
+ finish(digestRunOutcome(event.Metadata["next_outcome"], next), event.At)
+ }
+ open, closedByVerification = false, false
+ }
+ case "investigation_outcome":
+ // While a run is open its closing row carries the result.
+ if outcome := strings.TrimSpace(event.Metadata["next_outcome"]); !open && latest != nil && outcome != "" {
+ *latest = strings.ToLower(outcome)
+ }
+ case "verification_passed":
+ if open {
+ open, closedByVerification = false, true
+ finish(string(InvestigationOutcomeFixVerified), event.At)
+ } else if latest != nil {
+ *latest = string(InvestigationOutcomeFixVerified)
+ }
+ }
+ }
+ outcomes := make([]string, len(finished))
+ for i, outcome := range finished {
+ outcomes[i] = *outcome
+ }
+ return outcomes
+}
+
+// digestRunOutcome names how a run ended. A run that failed before reaching
+// any outcome is "failed", the same bucket telemetry uses for that state.
+func digestRunOutcome(outcome, status string) string {
+ if outcome = strings.ToLower(strings.TrimSpace(outcome)); outcome != "" {
+ return outcome
}
- if outcome == "" {
- return "unknown"
+ if strings.EqualFold(strings.TrimSpace(status), string(InvestigationStatusFailed)) {
+ return "failed"
}
- return strings.ToLower(outcome)
+ return "unknown"
}
func summarizeDigestActions(records []unifiedresources.ActionAuditRecord, inWindow func(time.Time) bool) PatrolDigestActions {
@@ -430,14 +487,15 @@ func PatrolDigestOutcomeOrder(byOutcome map[string]int) []string {
"fix_verification_failed": 2,
"cannot_fix": 3,
"timed_out": 4,
- "unclassified": 5,
- "fix_queued": 6,
- "fix_executed": 7,
- "fix_verification_unknown": 8,
- "fix_verified": 9,
- "resolved": 10,
- "fix_rejected": 11,
- "interrupted": 12,
+ "failed": 5,
+ "unclassified": 6,
+ "fix_queued": 7,
+ "fix_executed": 8,
+ "fix_verification_unknown": 9,
+ "fix_verified": 10,
+ "resolved": 11,
+ "fix_rejected": 12,
+ "interrupted": 13,
}
keys := make([]string, 0, len(byOutcome))
for key := range byOutcome {
diff --git a/internal/ai/patrol_digest_test.go b/internal/ai/patrol_digest_test.go
index aea8169251..94ede1195c 100644
--- a/internal/ai/patrol_digest_test.go
+++ b/internal/ai/patrol_digest_test.go
@@ -2,6 +2,7 @@ package ai
import (
"math"
+ "reflect"
"testing"
"time"
@@ -68,9 +69,7 @@ func TestBuildPatrolDigestRollsUpTheWeek(t *testing.T) {
findings := []*Finding{
{ID: "open-critical", Severity: FindingSeverityCritical, DetectedAt: now.Add(-1 * day)},
- {ID: "open-warning", Severity: FindingSeverityWarning, DetectedAt: now.Add(-2 * day), Lifecycle: []FindingLifecycleEvent{
- {At: investigatedAt, Type: "investigation_outcome", From: "investigating", To: "investigating", Metadata: map[string]string{"outcome": "needs_attention"}},
- }},
+ {ID: "open-warning", Severity: FindingSeverityWarning, DetectedAt: now.Add(-2 * day)},
{ID: "old-open", Severity: FindingSeverityCritical, DetectedAt: now.Add(-20 * day)},
{ID: "manually-resolved", Severity: FindingSeverityWarning, DetectedAt: now.Add(-6 * day), ResolvedAt: &resolvedAt, AutoResolved: false},
{ID: "auto-resolved", Severity: FindingSeverityWarning, DetectedAt: now.Add(-6 * day), ResolvedAt: &resolvedAt, AutoResolved: true},
@@ -130,7 +129,10 @@ func TestBuildPatrolDigestRollsUpTheWeek(t *testing.T) {
if got := digest.Findings.OpenBySeverity; got.Critical != 1 || got.Warning != 2 || got.Watch != 0 || got.Info != 0 {
t.Fatalf("open by severity = %+v", got)
}
- if digest.Investigations.Total != 2 || digest.Investigations.ByOutcome["needs_attention"] != 1 || digest.Investigations.ByOutcome["fix_verified"] != 1 {
+ // Investigations are counted from the run rows the findings store writes
+ // (TestBuildPatrolDigestCountsEachInvestigationRunOnce). Summary fields
+ // with no run in the lifecycle, as on legacy-investigated, are not a run.
+ if digest.Investigations.Total != 0 || len(digest.Investigations.ByOutcome) != 0 {
t.Fatalf("investigations = %+v", digest.Investigations)
}
if got := digest.Actions; got.Proposed != 5 || got.Approved != 3 || got.Rejected != 1 || got.Executed != 3 || got.Verified != 1 || got.Failed != 1 || got.Pending != 2 {
@@ -145,6 +147,143 @@ func TestBuildPatrolDigestRollsUpTheWeek(t *testing.T) {
}
}
+// digestTestRuns drives investigation runs through the findings store's own
+// writers, the way the orchestrator does: a run is marked running with no
+// outcome, then its end records the status, outcome and time.
+type digestTestRuns struct {
+ store *FindingsStore
+}
+
+func newDigestTestRuns(ids ...string) digestTestRuns {
+ runs := digestTestRuns{store: NewFindingsStore()}
+ for _, id := range ids {
+ runs.store.Add(&Finding{ID: id, ResourceID: "vm-" + id, ResourceName: id, Severity: FindingSeverityWarning, Category: FindingCategoryReliability, Title: "Finding " + id})
+ }
+ return runs
+}
+
+func (r digestTestRuns) start(id, session string) {
+ f := r.store.Get(id)
+ r.store.UpdateInvestigation(id, session, string(InvestigationStatusRunning), "", f.LastInvestigatedAt, f.InvestigationAttempts+1)
+}
+
+func (r digestTestRuns) finish(id, session string, status InvestigationStatus, outcome InvestigationOutcome) {
+ f := r.store.Get(id)
+ ended := time.Now()
+ r.store.UpdateInvestigation(id, session, string(status), string(outcome), &ended, f.InvestigationAttempts)
+}
+
+func TestBuildPatrolDigestCountsEachInvestigationRunOnce(t *testing.T) {
+ t.Parallel()
+ runs := newDigestTestRuns("twice", "approved", "verified-in-run", "verified-then-done", "verified-then-error", "regressed-mid-run", "interrupted", "recovered-verified", "running")
+
+ // Two runs on one finding count twice: an answer, then a provider error
+ // that left no outcome.
+ runs.start("twice", "chat-1")
+ runs.finish("twice", "chat-1", InvestigationStatusCompleted, InvestigationOutcomeNeedsAttention)
+ runs.start("twice", "chat-2")
+ runs.finish("twice", "chat-2", InvestigationStatusFailed, "")
+
+ // A queued fix that is later run and verified is one investigation that
+ // ended fixed and verified, not one per action step.
+ runs.start("approved", "chat-3")
+ runs.finish("approved", "chat-3", InvestigationStatusCompleted, InvestigationOutcomeFixQueued)
+ runs.store.UpdateInvestigationOutcome("approved", string(InvestigationOutcomeFixExecuted))
+ runs.store.UpdateInvestigationOutcome("approved", string(InvestigationOutcomeFixVerified))
+
+ // A run whose own fix was verified, after an earlier run timed out.
+ runs.start("verified-in-run", "chat-4")
+ runs.finish("verified-in-run", "chat-4", InvestigationStatusFailed, InvestigationOutcomeTimedOut)
+ runs.start("verified-in-run", "chat-5")
+ runs.finish("verified-in-run", "chat-5", InvestigationStatusCompleted, InvestigationOutcomeFixVerified)
+
+ // The action lifecycle can verify a run's fix before the run itself ends.
+ // The run still counts once and keeps the verified result, whether its own
+ // end then succeeds or fails.
+ for _, ending := range []struct {
+ id, session string
+ status InvestigationStatus
+ outcome InvestigationOutcome
+ }{
+ {"verified-then-done", "chat-9", InvestigationStatusCompleted, InvestigationOutcomeFixVerified},
+ {"verified-then-error", "chat-10", InvestigationStatusFailed, ""},
+ } {
+ runs.start(ending.id, ending.session)
+ session := &InvestigationSession{FindingID: ending.id, SessionID: ending.session, StartedAt: time.Now()}
+ if applied, _ := runs.store.ReconcileInvestigationOutcome(ending.id, session, string(InvestigationOutcomeFixVerified)); !applied {
+ t.Fatalf("%s: verification of the running session was not applied", ending.id)
+ }
+ runs.finish(ending.id, ending.session, ending.status, ending.outcome)
+ }
+
+ // The finding is resolved and detected again while a run is in progress.
+ // The regression clears the run's status, and the run still counts when it
+ // ends.
+ runs.start("regressed-mid-run", "chat-11")
+ if !runs.store.Resolve("regressed-mid-run", false) {
+ t.Fatal("resolve the investigated finding")
+ }
+ runs.store.Add(&Finding{ID: "regressed-mid-run", ResourceID: "vm-regressed-mid-run", ResourceName: "regressed-mid-run", Severity: FindingSeverityWarning, Category: FindingCategoryReliability, Title: "Finding regressed-mid-run"})
+ if f := runs.store.Get("regressed-mid-run"); f.RegressionCount != 1 || f.InvestigationStatus != "" {
+ t.Fatalf("regression = %d, status %q; want the run's status cleared by one regression", f.RegressionCount, f.InvestigationStatus)
+ }
+ runs.finish("regressed-mid-run", "chat-11", InvestigationStatusCompleted, InvestigationOutcomeNeedsAttention)
+
+ // Stuck-run recovery closes runs the orchestrator lost, including one whose
+ // session already held a verified result.
+ runs.start("interrupted", "chat-6")
+ runs.store.RecoverStuckInvestigation("interrupted", "chat-6", time.Time{}, InvestigationStatusFailed, InvestigationOutcomeInterrupted, time.Now())
+ runs.start("recovered-verified", "chat-7")
+ runs.store.RecoverStuckInvestigation("recovered-verified", "chat-7", time.Time{}, InvestigationStatusCompleted, InvestigationOutcomeFixVerified, time.Now())
+
+ // A run still in progress has not finished, so it does not count yet.
+ runs.start("running", "chat-8")
+
+ digest := BuildPatrolDigest(PatrolDigestInput{Now: time.Now(), Days: 7, Findings: runs.store.GetAll(nil)})
+ want := map[string]int{"needs_attention": 2, "failed": 1, "fix_verified": 5, "timed_out": 1, "interrupted": 1}
+ if digest.Investigations.Total != 10 || !reflect.DeepEqual(digest.Investigations.ByOutcome, want) {
+ t.Fatalf("investigations = %+v, want 10 runs %v", digest.Investigations, want)
+ }
+
+ // A week on, every run finished before the window opened.
+ later := BuildPatrolDigest(PatrolDigestInput{Now: time.Now().Add(8 * 24 * time.Hour), Days: 7, Findings: runs.store.GetAll(nil)})
+ if later.Investigations.Total != 0 || len(later.Investigations.ByOutcome) != 0 {
+ t.Fatalf("investigations a week later = %+v, want none", later.Investigations)
+ }
+}
+
+func TestBuildPatrolDigestCountsARunInTheWindowItFinished(t *testing.T) {
+ t.Parallel()
+ runs := newDigestTestRuns("approved")
+ runs.start("approved", "chat-1")
+ runs.finish("approved", "chat-1", InvestigationStatusCompleted, InvestigationOutcomeFixQueued)
+ runs.store.UpdateInvestigationOutcome("approved", string(InvestigationOutcomeFixExecuted))
+
+ findings := runs.store.GetAll(nil)
+ if len(findings) != 1 {
+ t.Fatalf("findings = %d", len(findings))
+ }
+ // Move the run ten days back and leave its fix running inside the window.
+ // GetAll copies only the finding, so copy the lifecycle before editing it.
+ f := findings[0]
+ f.Lifecycle = append([]FindingLifecycleEvent(nil), f.Lifecycle...)
+ tenDays := 10 * 24 * time.Hour
+ for i := range f.Lifecycle {
+ if f.Lifecycle[i].Type != "investigation_outcome" {
+ f.Lifecycle[i].At = f.Lifecycle[i].At.Add(-tenDays)
+ }
+ }
+
+ digest := BuildPatrolDigest(PatrolDigestInput{Now: time.Now(), Days: 7, Findings: findings})
+ if digest.Investigations.Total != 0 || len(digest.Investigations.ByOutcome) != 0 {
+ t.Fatalf("investigations = %+v, want none: the run finished before the window and its fix is not another investigation", digest.Investigations)
+ }
+ digest = BuildPatrolDigest(PatrolDigestInput{Now: time.Now(), Days: 14, Findings: findings})
+ if digest.Investigations.Total != 1 || digest.Investigations.ByOutcome["fix_executed"] != 1 {
+ t.Fatalf("investigations = %+v, want the run once with its fix's latest outcome", digest.Investigations)
+ }
+}
+
func TestBuildPatrolDigestFlagsTruncatedHistoryAndUnknownPricing(t *testing.T) {
t.Parallel()
now := time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 1e414d8230..5ac48799e3 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -2438,6 +2438,43 @@ func TestContract_PatrolStatusMissingAssistantServiceUsesNativeSurfaceIdentity(t
}
}
+// TestContract_PatrolDigestCountsEachFinishedRunFromTheFindingsStore follows
+// the scheduled Patrol summary's real path: runs recorded by the findings
+// store's own writers, the handler's digest assembly, then the email renderer.
+func TestContract_PatrolDigestCountsEachFinishedRunFromTheFindingsStore(t *testing.T) {
+ t.Parallel()
+ handler := createTestAIHandler(t)
+ findings := ai.NewFindingsStore()
+ findings.Add(&ai.Finding{ID: "disk", ResourceID: "vm-101", ResourceName: "web-01", Severity: ai.FindingSeverityWarning, Category: ai.FindingCategoryCapacity, Title: "Disk nearly full"})
+ // Each run is marked running with no outcome, then records how it ended,
+ // as the orchestrator does. The second run's queued fix then runs.
+ run := func(session string, status ai.InvestigationStatus, outcome ai.InvestigationOutcome) {
+ findings.UpdateInvestigation("disk", session, string(ai.InvestigationStatusRunning), "", nil, 1)
+ ended := time.Now()
+ findings.UpdateInvestigation("disk", session, string(status), string(outcome), &ended, 1)
+ }
+ run("chat-1", ai.InvestigationStatusFailed, "")
+ run("chat-2", ai.InvestigationStatusCompleted, ai.InvestigationOutcomeFixQueued)
+ findings.UpdateInvestigationOutcome("disk", string(ai.InvestigationOutcomeFixExecuted))
+
+ patrol := &ai.PatrolService{}
+ setUnexportedField(t, patrol, "runHistoryStore", ai.NewPatrolRunHistoryStore(10))
+ setUnexportedField(t, patrol, "findings", findings)
+ setUnexportedField(t, handler.defaultAIService, "patrolService", patrol)
+
+ digest, available := handler.BuildPatrolDigest(context.Background(), 7)
+ if !available {
+ t.Fatal("digest must report available once a Patrol service exists")
+ }
+ want := map[string]int{"failed": 1, "fix_executed": 1}
+ if digest.Investigations.Total != 2 || !reflect.DeepEqual(digest.Investigations.ByOutcome, want) {
+ t.Fatalf("investigations = %+v, want two runs %v", digest.Investigations, want)
+ }
+ if _, _, textBody := renderPatrolDigestEmail(digest, ""); !strings.Contains(textBody, "Investigated: 2\n 1 ended with an error, 1 fix run.\n") {
+ t.Fatalf("email does not describe the two runs:\n%s", textBody)
+ }
+}
+
func TestContract_AISettingsDoesNotExposeQuickstartActivation(t *testing.T) {
tmp := t.TempDir()
cfg := &config.Config{DataPath: tmp}
diff --git a/internal/api/patrol_digest_email.go b/internal/api/patrol_digest_email.go
index ba9202b8b6..68d179178a 100644
--- a/internal/api/patrol_digest_email.go
+++ b/internal/api/patrol_digest_email.go
@@ -141,7 +141,7 @@ func patrolDigestEmailLines(digest ai.PatrolDigest) []patrolDigestEmailLine {
investigated := patrolDigestEmailLine{label: "Investigated", value: fmt.Sprintf("%d", digest.Investigations.Total)}
outcomeCopy := map[string]string{
"needs_attention": "need you", "fix_failed": "fix failed", "fix_verification_failed": "fix not confirmed",
- "cannot_fix": "could not fix", "timed_out": "timed out", "fix_queued": "fix waiting for approval",
+ "cannot_fix": "could not fix", "timed_out": "timed out", "failed": "ended with an error", "fix_queued": "fix waiting for approval",
"fix_executed": "fix run", "fix_verification_unknown": "fix run, result unknown", "fix_verified": "fixed and verified",
"resolved": "resolved", "fix_rejected": "fix declined",
"unclassified": "finished without a clear conclusion", "interrupted": "interrupted by a restart",
@@ -160,6 +160,9 @@ func patrolDigestEmailLines(digest ai.PatrolDigest) []patrolDigestEmailLine {
switch {
case len(outcomeDetails) > 0:
investigated.details = []string{strings.Join(outcomeDetails, ", ") + "."}
+ case digest.Investigations.Total > 0:
+ // Runs whose outcome has no wording here still happened, so the line
+ // must not say that nothing was investigated.
case digest.Mode == config.PatrolAutonomyMonitor:
investigated.details = []string{"Patrol is watch only, so it reports issues without investigating them."}
default:
diff --git a/internal/api/patrol_digest_email_test.go b/internal/api/patrol_digest_email_test.go
index 7e0afb4e99..7817351144 100644
--- a/internal/api/patrol_digest_email_test.go
+++ b/internal/api/patrol_digest_email_test.go
@@ -55,6 +55,36 @@ func TestRenderPatrolDigestEmailMirrorsTheCardInPlainLanguage(t *testing.T) {
}
}
+func TestRenderPatrolDigestEmailNamesHowInvestigationsEnded(t *testing.T) {
+ digest := ai.PatrolDigest{
+ Window: ai.PatrolDigestWindow{Days: 7, HistoryComplete: true},
+ Mode: config.PatrolAutonomyApproval,
+ Runs: ai.PatrolDigestRuns{Total: 6},
+ Investigations: ai.PatrolDigestInvestigations{Total: 3, ByOutcome: map[string]int{"interrupted": 1, "failed": 2}},
+ Spend: ai.PatrolDigestSpend{PricingKnown: true},
+ }
+ _, _, textBody := renderPatrolDigestEmail(digest, "")
+ if !strings.Contains(textBody, "Investigated: 3\n 2 ended with an error, 1 interrupted by a restart.\n") {
+ t.Fatalf("text body does not name how the runs ended:\n%s", textBody)
+ }
+
+ // A counted run whose outcome has no wording here must not turn the line
+ // into "nothing was investigated", in any mode.
+ for _, mode := range []string{config.PatrolAutonomyApproval, config.PatrolAutonomyMonitor} {
+ digest.Mode = mode
+ digest.Investigations = ai.PatrolDigestInvestigations{Total: 1, ByOutcome: map[string]int{"unknown": 1}}
+ _, _, textBody = renderPatrolDigestEmail(digest, "")
+ if !strings.Contains(textBody, "Investigated: 1\n\n") {
+ t.Fatalf("%s: text body = \n%s", mode, textBody)
+ }
+ for _, contradiction := range []string{"No issues needed a closer look.", "reports issues without investigating them"} {
+ if strings.Contains(textBody, contradiction) {
+ t.Fatalf("%s: one investigation reported as none (%q):\n%s", mode, contradiction, textBody)
+ }
+ }
+ }
+}
+
func TestRenderPatrolDigestEmailHandlesQuietWatchOnlyWeeks(t *testing.T) {
since := time.Date(2026, 8, 29, 8, 0, 0, 0, time.UTC)
digest := ai.PatrolDigest{