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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Read incident evidence from canonical resource history
rcourtman580a246981c7
diff --git a/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md b/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.mdindex 80de650f93..d7b545793d 100644--- a/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md+++ b/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md@@ -1816,3 +1816,73 @@ still open. The typed compatibility get path also does not accept the canonicalID returned by its list path, so its mount regression uses an existing acceptedname. That identity residual is recorded for modernization, not silently fixedthrough this mount projection.++## Canonical incident history, 2026-09-06++The tmpfs correction passed the exact worker hook and was pushed as+`6e18777d30f30b498def39d30016a697cabc4ea7` in PR #1935. That scoped+delivery does not change the failed storage diagnosis or partial recovery verdict.++The incident audit found a source-of-truth mismatch, not evidence that an existing+recording merely needed an ID alias. The legacy five-second recorder has no+production alert callback connected to its coordinator. It samples cached values+using recorder time without preserving their source measurement time. Connecting+that recorder would not supply trustworthy higher-frequency history.++The canonical resource timeline already stores observed changes, alert lifecycle+events and executed actions. Assistant handoffs use a bounded excerpt of this+same store. The shared `pulse_knowledge` incidents action now reads that+organization-pinned timeline directly, using the supplied canonical resource ID.+It does not require the resource still to exist in current inventory, infer+identity from names, include related resources implicitly, or reconstruct events+from current metrics. The response preserves canonical source, observation and+optional occurrence timestamps, state transitions and metadata. `since` filters+on observation time, and bounded results report `has_more`. Empty retained history+does not establish health. Missing or failed storage is a failed read.++Explicit legacy `window_id` lookups remain isolated archive reads, must match the+requested resource, and explain that sample timestamps do not establish source+freshness. The primary incidents action no longer uses those recordings. The+legacy recorder/coordinator startup and API active-count plumbing still exist.+Their retirement is a separate cleanup in this redesign and must preserve any+saved archives. Do not connect them as a replacement incident truth source.++Qualification uses the real SQLite resource store with a fired/resolved lifecycle,+an older excluded record, a related-resource negative control, absent occurrence+time, truncation and empty history. Unavailable/failed storage, invalid input and+archive resource isolation are separate negative controls. Captured actual tool+responses must pass the Assistant expansion, scrolling and reload matrix at+`/patrol`, 1440x1000, 900x1000 and 390x1000. This is contract and rendering proof,+not a new real-model or continuous-coverage claim.++Read-only API inspection of the actual removed storage fixture confirmed a+remaining canonical write-boundary defect. The canonical app-container timeline+returns its creation and removal, while the fired event at 13:14:28.59485Z and+resolved event at 13:17:58.634095Z remain under its legacy Docker resource ID.+The resource API includes related network changes by design. The new tool uses+direct resource history only. `recordAlertTimelineChange` passes the alert's+source ID directly to `BuildAlertTimelineChange`, and `MonitorAdapter.RecordChange`+forwards it without canonical resolution. Consequently this read-path change is+only partial incident-history remediation. The next required owning fix must+resolve event identity before persistence and preserve access to retained prior+identity records, including removed resources, through the shared identity/history+contract. It must not add a Docker string rewrite inside the Assistant tool.+The shared writer and retained-identity correction remain required in this goal.+Private raw API receipts are in `tmp/patrol-canonical-history/live-timeline.json`+and `live-legacy-alert-timeline.json`. No model call or infrastructure mutation+was made during these reads.++The history regression passes through the registered tool dispatcher. The full+tools package passed in 59.856s, the final focused capture passed in 0.036s, and the+focused race check passed in 1.189s on pulse-dev with Go1.26.8 and GOMAXPROCS4.+The final Pro build passed and was installed into the local development stack.+Its SHA256 is `4929aeb869db54122bc5525352d3126c0e9fa7c4847e3fdfa741500600b5e00d`.+The managed backend restarted healthy. Final Playwright proof passed all five+registered-tool cases at `/patrol`, 1440x1000, 900x1000 and 390x1000, including+hover/focus, Enter/Space, deepest output scrolling, Escape and controlled session+reload with exact input/output and success/failure comparison. Root inspected+actual pixels at all three widths. Source and binary hashes remained fixed.+The provider warning stayed visible and no retry, route switch or provider+request was made. This is captured-response rendering, not real-model diagnosis+or server persistence qualification. The exact scoped worker hook gates delivery+through PR #1935.diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.jsonindex 4f9e7377ab..af9de87e96 100644--- a/docs/release-control/v6/internal/status.json+++ b/docs/release-control/v6/internal/status.json@@ -10201,7 +10201,7 @@},{"id": "patrol-assistant-customer-outcome-qualification",- "summary": "The explicit redesign plan and source-bound receipts remain in docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md. The goal is open. Model judgment owns diagnosis, with observations, hypotheses, proposals, executions and independently verified outcomes kept distinct. The recorded baseline has 127 paid installations, 71 with Patrol enabled, 23 with Assistant calls and fourteen verified resolutions from one installation. Schema17 outcome/provider/cost fields had no adoption. These are not representative success, false-alarm or missed-problem rates. Shared provenance, history, risk, missing-access and continuity corrections landed through PR1928/1929. Proposal-as-proof and proxy-driven diagnostic completion policy were removed. PR1934 merged the tool-ID and transcript-identity correction at 6b0abc3bee9ffa81f6ab298b5b67ee11369688a0 with all checks passing. Its captured-response browser replay preserves seven healthy and sixteen dependency tool records. The two ordinary subscription Assistant cases took 82.835s and 204.384s. Their primary decisions had useful evidence, but storage exclusion, recovery implications and config-not-found errors remain unqualified. Independent Docker fixtures prove injection, negative controls and deadline cleanup, not completed recovery or model/action competence. The current scoped Docker measurement correction preserves per-direction observation presence, separates corrected history from ambiguous legacy rows, removes image-layer ratios from capacity, and carries optional rates through resource/browser conversion. Legacy workload direction availability, Docker-host first-disk history and network presence remain distinct consumer/source follow-ups. The current configuration-read correction resolves identity and placement from canonical inventory, preserves explicit query restrictions, and distinguishes unavailable capability/provider observations from missing resources with the shared tool error bit. Fourteen contract cases, full tools package, targeted race checks and captured-result browser rendering pass. Both corrections are pushed to PR1935 at 355ac1f0a481d6dbc9a7ff3977bced0956711979 with exact worker hooks passing and remote checks pending. A fresh ordinary storage assessment took 177.869s and thirteen successful reads. It identified the actual capacity alert and preserved limited I/O history, but contradictory capacity assurance, unsupported artifact attribution and a misplaced CPU-peak time keep diagnosis unqualified. All thirteen rendered tool records match persistence. Desktop/mobile browser proof and its artificial route-warning limit are recorded in the plan. The current shared connection projection names command transport explicitly, omits unqueried connection and execution hints/counts from topology and Assistant inventory, and separates parent-node transport from direct guest connectivity. Four canonical connection/control cases, unobserved/empty topology, inventory context, full tools/chat packages, focused race checks and nine captured browser results pass. The connection correction passed its exact worker hook and is pushed as f5f440dbad18d83557104d2cf6197d8319949e44 in PR1935, with CI ongoing. Unsupported filter handling remains a tool-context review item. Claude Max explicitly refused autonomous Patrol readiness. Cached refusal and API409 enforcement remain intact. Ordinary Assistant is not autonomous qualification. Separate paid-provider approval remains pending and no paid request occurred. Reliable interpretation, real-model retest of config reads, storage/backup and approved/rejected action outcomes remain required local work. Independent volunteered Pro environments remain a separate wider-readiness gate. A new ordinary storage-fault diagnosis took 114.847s and ten calls, then same-session recovery took 91.358s and five calls. Independent baseline, ENOSPC, unchanged fault after answer, recovery, post-answer health and two-pass cleanup all passed. Diagnosis failed by ruling out resource pressure without filesystem capacity evidence. Recovery identified current health and alert resolution but overstated continuous control health from sparse observations. Fifteen rendered tool records match persisted history. The shared collector currently being corrected drops HostConfig.Tmpfs, while query projection loses mount type/options and misreads compound read-only options. The collector and shared query corrections pass focused/full package and race proof, and final source-bound Docker/Assistant captured-result browser checks. Exact scoped hook and landing remain pending. Installed-collector and model qualification remain unperformed, and the existing responsive Docker details omit a dedicated mounts section. No autonomous call, action execution, provider-policy bypass or paid request was part of the case. Incident-record identity lookup and typed compatibility canonical-ID lookup remain documented follow-ups.",+ "summary": "The redesign goal remains open, with its executable plan and detailed receipts in docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md. Patrol owns investigation and Assistant continues the same issue. Observations, hypotheses, accepted proposals, execution and independently verified outcomes remain distinct. The recorded baseline contains 127 paid installations, 71 Patrol-enabled, 23 with Assistant calls and fourteen verified resolutions from one installation. Schema17 outcome/provider/cost fields had no adoption. These do not establish representative success, false-alarm or missed-problem rates. Shared provenance/history/risk fixes and removal of proposal-as-proof and proxy completion policy landed through PR1928/1929. PR1934 merged canonical tool/transcript identity. PR1935 contains measurement-presence, capacity, canonical config-read, command-connectivity and tmpfs collection/query corrections through 6e18777d30f30b498def39d30016a697cabc4ea7. Exact worker hooks and named browser matrices passed, with remote landing pending. Real ordinary storage diagnosis failed by ruling out pressure without filesystem capacity evidence. Same-session recovery correctly identified present health and alert resolution but overstated continuous control health. Independent fault-intact, recovery, two-pass cleanup and persisted transcript checks passed. The current incident history correction replaces the primary legacy recorder read with the existing organization-pinned canonical resource timeline, preserving source/time semantics, bounded history, empty coverage and failed-read distinctions. Explicit legacy archive reads remain resource-bound. Its registered-tool SQLite, full tools package, focused race and final-source browser proofs pass. The exact scoped worker hook gates delivery through PR1935. Live reads of the removed storage fixture confirm that health alert fired/resolved records remain under the legacy Docker ID while creation/removal use the canonical app-container ID. This is partial incident-history remediation. The shared timeline writer and retained identity/history contract must repair that split, including removed resources, without an Assistant-local ID rewrite. The unused legacy recorder/coordinator startup needs retirement while preserving saved archives. Installed tmpfs collector and real-model interpretation remain unqualified. Other named residuals include unsupported filters, typed compatibility canonical-ID lookup, legacy direction availability, Docker-host history and responsive mount details. Claude Max explicitly refused autonomous Patrol readiness. Cached refusal and API409 enforcement remain enforced. Separate paid-provider approval is pending, with no paid request or policy bypass. Ordinary Assistant is not autonomous qualification. Required local work still includes reliable interpretation, config-read/model retest, storage/backup and approved/rejected action outcomes. Independent volunteered Pro environments remain a separate wider-readiness gate.","owner": "project-owner","status": "planned","recorded_at": "2026-09-05",diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex ed6cdf198f..7e4b62e2be 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -3605,6 +3605,22 @@ has a single definition in the canonical resource contract.## Completion Obligations+The `pulse_knowledge` incidents action reads the organization-pinned canonical+resource timeline used by resource history and Assistant handoffs. It preserves+resource identity, observation and optional occurrence time, source and event+metadata. Reads use explicit observation-time bounds and a bounded event count+with truncation disclosure. Empty retained history is not continuous healthy+coverage, and an unavailable or failed history store is a failed tool read.+Legacy recording IDs are isolated archive lookups bound to the requested+resource. Their recorder timestamps cannot establish source measurement time.+The primary history path must not restore the legacy recorder as a parallel+incident authority or derive fresh history by resampling cached metrics.+`TestIncidentHistoryRetainsCanonicalEvidence` uses SQLite lifecycle records,+time/resource negative controls, missing occurrence time and bounded reads.+The corresponding unavailable/invalid and archive tests cover failure semantics+and resource isolation. Live model interpretation remains governed by the+customer journey qualification plan.+Every per-organization Assistant or legacy AI service that can discover ordispatch through the host-agent command transport must receive anorganization-pinned command-server view. A tenant service must never enumeratediff --git a/frontend-modern/browser-verification.json b/frontend-modern/browser-verification.jsonindex 40505e579d..a87940a568 100644--- a/frontend-modern/browser-verification.json+++ b/frontend-modern/browser-verification.json@@ -1,44 +1,24 @@{"version": 1,- "base_sha": "f5f440dbad18d83557104d2cf6197d8319949e44",- "verified_at": "2026-09-06T13:39:36.848659+00:00",+ "base_sha": "6e18777d30f30b498def39d30016a697cabc4ea7",+ "verified_at": "2026-09-06T14:26:55.462Z","result": "passed","changed_paths": [],"content_sha256": {},"backend_content_sha256": {- "internal/dockeragent/collect.go": "869eb906ac8d6fe57304a296bc81bc689f72a07b5a76267982b81228d147852d",- "internal/ai/tools/data_types.go": "91fff7a17735c9f9f4bf64c7fe42c7d4c5cf9e436af36ac07dec92feb952afc6",- "internal/ai/tools/tools_query.go": "5ba1f2c8ec7aadb21d594c967a5b2858db3471b02174889b7f78472e3a33235b"+ "internal/ai/tools/tools_knowledge.go": "d98ea1bab481acce5eee4988d74d364dc73c4068ca33725d843b54117cc9cc85",+ "internal/ai/tools/executor.go": "c476d6aec1f7925467f1547f0219e6c6265639a62b397649adc82a8ed87b7e4a"},- "binary_sha256": "0a21dca4106c2ddc6873a3aca3b23378dccef35383ca00d7e9292b966de7c200",+ "binary_sha256": "4929aeb869db54122bc5525352d3126c0e9fa7c4847e3fdfa741500600b5e00d","rendering_content_sha256": {"frontend-modern/src/components/AI/Chat/hooks/useChat.ts": "0b56b7a56e35d51ca96f0e126dd493b3164aa9e0ad4d8ae24bcf3af7a574b97c","frontend-modern/src/components/AI/Chat/ChatMessages.tsx": "9672f7608d1e3a531c73cba20fd4a78752316783212afd0c292ddfd11d2bf371",- "frontend-modern/src/components/AI/Chat/ToolExecutionBlock.tsx": "cc7bd548a418c3863486f0fe987c5c3110c2f6cdfa70b630b2ec05fb794d60d6",- "frontend-modern/src/features/docker/DockerContainersTable.tsx": "af58fb901b55b188be084105e78c71084af5a594d1a7dde2647959eb00cc6131",- "frontend-modern/src/features/docker/dockerContainerTableModel.ts": "48bf66fe7e3bacf6352c48d7ccd568dd337e9d27670da435f30c3caabccf79bc"+ "frontend-modern/src/components/AI/Chat/ToolExecutionBlock.tsx": "cc7bd548a418c3863486f0fe987c5c3110c2f6cdfa70b630b2ec05fb794d60d6"},"routes": [- "/docker","/patrol"],"viewports": [- {- "width": 1920,- "height": 1080- },- {- "width": 1440,- "height": 1080- },- {- "width": 900,- "height": 1080- },- {- "width": 390,- "height": 1080- },{"width": 1440,"height": 1000@@ -53,13 +33,13 @@}],"states": [- "Captured canonical app-container and parent agent with tmpfs and bind mounts. Existing mount summary is a wide-table column, with no dedicated mount section in responsive detail views.",- "Two captured shared query results preserve native type, options, source, destination and RW. They establish mount configuration, not measured capacity.",- "Final Pro source/binary binding and original cached refusal preserved. No provider or production mutation in rendering proof."+ "Five captured registered-tool results: retained canonical lifecycle, bounded/truncated history, empty retained history, unavailable store, and failed store read.",+ "Observation and optional occurrence timestamps, source metadata, empty arrays, coverage limitations and failed tool status survive rendering.",+ "Existing provider route warning remains visible. No retry, route switch, model request or infrastructure mutation was performed."],"interactions": [- "Docker mount summary/title hover, keyboard expansion/collapse, mobile row tap, adjacent detail state, mount destination search, Escape and reloaded search.",- "Assistant exact input/output comparison, hover/focus, Enter/Space, deepest output scrolling, Escape, full reload and controlled session selection/reopening.",- "Pixel inspection at desktop/mobile. Private receipts: tmp/patrol-storage-fault-case/browser and docker-browser. Captured REST/SSE fixtures do not qualify installed collector, model diagnosis or server persistence."+ "Hover/focus and Enter expansion, exact input/output comparison, deepest output scroll and pixel inspection at desktop/intermediate/mobile widths, Space collapse and Escape.",+ "Full reload, controlled session selection, reopen each result and compare exact retained input/output and completed/failed state.",+ "Final verified Pro build installed locally, healthy restart, fixed source/binary hashes before and after. Private receipt: tmp/patrol-canonical-history/browser/receipt.json. Captured response/session fixtures qualify rendering, not real-model diagnosis or backend persistence."]}diff --git a/internal/ai/tools/executor.go b/internal/ai/tools/executor.goindex 7b1870a176..bf045aca2d 100644--- a/internal/ai/tools/executor.go+++ b/internal/ai/tools/executor.go@@ -1221,7 +1221,7 @@ func (e *PulseToolExecutor) isToolAvailable(name string) bool {case agentcapabilities.PulseDiscoveryToolName:return e.discoveryProvider != nilcase agentcapabilities.PulseKnowledgeToolName:- return e.knowledgeStoreProvider != nil || e.incidentRecorderProvider != nil || e.eventCorrelatorProvider != nil+ return e.actionAuditStore != nil || e.knowledgeStoreProvider != nil || e.incidentRecorderProvider != nil || e.eventCorrelatorProvider != nilcase agentcapabilities.PulsePMGToolName:return e.hasReadState()case agentcapabilities.PulseSummarizeToolName:diff --git a/internal/ai/tools/incident_history_test.go b/internal/ai/tools/incident_history_test.gonew file mode 100644index 0000000000..08df16b58a--- /dev/null+++ b/internal/ai/tools/incident_history_test.go@@ -0,0 +1,134 @@+package tools++import (+ "context"+ "encoding/json"+ "errors"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+ "github.com/stretchr/testify/require"+)++type failedIncidentHistoryStore struct{ unifiedresources.ResourceStore }++func (failedIncidentHistoryStore) GetRecentChanges(string, time.Time, int) ([]unifiedresources.ResourceChange, error) {+ return nil, errors.New("history store unavailable")+}++type incidentArchiveFixture struct{ window *IncidentWindow }++func (s incidentArchiveFixture) GetWindow(string) *IncidentWindow { return s.window }+func (s incidentArchiveFixture) GetWindowsForResource(string, int) []*IncidentWindow {+ panic("canonical incident reads must not enumerate legacy recordings")+}++func TestIncidentHistoryRetainsCanonicalEvidence(t *testing.T) {+ store, err := unifiedresources.NewSQLiteResourceStore(t.TempDir(), "incident-test")+ require.NoError(t, err)+ t.Cleanup(func() { require.NoError(t, store.Close()) })+ resourceID := "app-container-7020f37498275208"+ start := time.Now().UTC().Add(-time.Hour).Truncate(time.Second)+ occurred := start.Add(-time.Minute)+ changes := []unifiedresources.ResourceChange{+ {ID: "outside-window", ResourceID: resourceID, ObservedAt: start.Add(-time.Second), Kind: unifiedresources.ChangeRestart, SourceType: unifiedresources.SourcePlatformEvent},+ {ID: "alert-fired", ResourceID: resourceID, ObservedAt: start.Add(time.Minute), OccurredAt: &occurred, Kind: unifiedresources.ChangeAlertFired, SourceType: unifiedresources.SourcePulseDiff, From: "healthy", To: "unhealthy", Reason: "Health check failed", Metadata: map[string]any{"alert_id": "health-check", "value": 1.0}},+ {ID: "related-only", ResourceID: "agent-parent", RelatedResources: []string{resourceID}, ObservedAt: start.Add(2 * time.Minute), Kind: unifiedresources.ChangeRestart, SourceType: unifiedresources.SourcePlatformEvent},+ {ID: "alert-resolved", ResourceID: resourceID, ObservedAt: start.Add(3 * time.Minute), Kind: unifiedresources.ChangeAlertResolved, SourceType: unifiedresources.SourcePulseDiff, From: "unhealthy", To: "healthy"},+ }+ for _, change := range changes {+ require.NoError(t, store.RecordChange(change))+ }+ // No live inventory or incident recorder is necessary to read a retained+ // event for a container that has since been removed.+ exec := NewPulseToolExecutor(ExecutorConfig{ActionAuditStore: store, IncidentRecorderProvider: incidentArchiveFixture{}})+ require.True(t, exec.isToolAvailable(agentcapabilities.PulseKnowledgeToolName))+ for _, tc := range []struct {+ name string+ id string+ limit int+ wantCount int+ wantMore bool+ }{+ {"retained lifecycle", resourceID, 50, 2, false},+ {"bounded lifecycle", resourceID, 1, 1, true},+ {"empty history", "app-container-absent", 50, 0, false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ input := map[string]interface{}{"action": "incidents", "resource_id": tc.id, "since": start.Format(time.RFC3339), "limit": float64(tc.limit)}+ result, err := exec.registry.Execute(context.Background(), exec, agentcapabilities.PulseKnowledgeToolName, input)+ require.NoError(t, err)+ require.False(t, result.IsError, result.Content)+ var got struct {+ Source string `json:"source"`+ Events []unifiedresources.ResourceChange `json:"events"`+ HasMore bool `json:"has_more"`+ Coverage string `json:"coverage"`+ TimeBasis string `json:"time_basis"`+ }+ require.NoError(t, json.Unmarshal([]byte(result.Content[0].Text), &got))+ require.Equal(t, "canonical_resource_timeline", got.Source)+ require.Equal(t, "retained_records_only", got.Coverage)+ require.Equal(t, "observed_at", got.TimeBasis)+ require.NotNil(t, got.Events)+ require.Len(t, got.Events, tc.wantCount)+ require.Equal(t, tc.wantMore, got.HasMore)+ if tc.wantCount > 0 {+ require.Equal(t, "alert-resolved", got.Events[0].ID)+ require.Nil(t, got.Events[0].OccurredAt)+ }+ if tc.wantCount == 2 {+ require.Equal(t, changes[1], got.Events[1])+ }+ capture, err := json.Marshal(map[string]any{"case": tc.name, "input": input, "result": result})+ require.NoError(t, err)+ t.Logf("INCIDENT_EVIDENCE %s", capture)+ })+ }+}++func TestIncidentHistoryUnavailableAndInvalid(t *testing.T) {+ for _, tc := range []struct {+ name string+ store unifiedresources.ResourceStore+ input map[string]interface{}+ }{+ {"unavailable", nil, map[string]interface{}{"resource_id": "app-container-1"}},+ {"failed", failedIncidentHistoryStore{}, map[string]interface{}{"resource_id": "app-container-1"}},+ {"empty resource", unifiedresources.NewMemoryStore(), map[string]interface{}{"resource_id": " "}},+ {"invalid time", unifiedresources.NewMemoryStore(), map[string]interface{}{"resource_id": "app-container-1", "since": "yesterday"}},+ {"future time", unifiedresources.NewMemoryStore(), map[string]interface{}{"resource_id": "app-container-1", "since": time.Now().Add(time.Hour).Format(time.RFC3339)}},+ {"negative limit", unifiedresources.NewMemoryStore(), map[string]interface{}{"resource_id": "app-container-1", "limit": float64(-1)}},+ {"large limit", unifiedresources.NewMemoryStore(), map[string]interface{}{"resource_id": "app-container-1", "limit": float64(201)}},+ } {+ t.Run(tc.name, func(t *testing.T) {+ exec := NewPulseToolExecutor(ExecutorConfig{ActionAuditStore: tc.store, IncidentRecorderProvider: incidentArchiveFixture{}})+ tc.input["action"] = "incidents"+ result, err := exec.registry.Execute(context.Background(), exec, agentcapabilities.PulseKnowledgeToolName, tc.input)+ require.NoError(t, err)+ require.True(t, result.IsError, result.Content)+ capture, err := json.Marshal(map[string]any{"case": tc.name, "input": tc.input, "result": result})+ require.NoError(t, err)+ t.Logf("INCIDENT_EVIDENCE %s", capture)+ })+ }+}++func TestIncidentHistoryLegacyArchiveIsResourceBound(t *testing.T) {+ window := &IncidentWindow{ID: "archive-1", ResourceID: "vm-1"}+ exec := NewPulseToolExecutor(ExecutorConfig{IncidentRecorderProvider: incidentArchiveFixture{window}})+ for _, id := range []string{"vm-1", "vm-2"} {+ result, err := exec.executeGetIncidentWindow(context.Background(), map[string]interface{}{"resource_id": id, "window_id": window.ID})+ require.NoError(t, err)+ if id == window.ResourceID {+ require.False(t, result.IsError)+ require.Contains(t, result.Content[0].Text, "legacy_incident_recording")+ require.Contains(t, result.Content[0].Text, "cached observations")+ } else {+ require.True(t, result.IsError)+ require.NotContains(t, result.Content[0].Text, "vm-1")+ }+ }+}diff --git a/internal/ai/tools/tools_knowledge.go b/internal/ai/tools/tools_knowledge.goindex 58c987764c..7af911beb0 100644--- a/internal/ai/tools/tools_knowledge.go+++ b/internal/ai/tools/tools_knowledge.go@@ -3,9 +3,11 @@ package toolsimport ("context""fmt"+ "strings""time""github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")// IncidentRecorderProvider provides access to incident recording data@@ -87,7 +89,7 @@ func (e *PulseToolExecutor) registerKnowledgeTools() {Actions:- remember: Save a note about a resource for future reference- recall: Retrieve saved notes about a resource-- incidents: Get high-resolution incident recording data+- incidents: Read retained canonical resource history, including observed state changes, alerts and executed actions. Records preserve observation time, source and any known occurrence time. This is not continuous health or filesystem-capacity coverage. Use pulse_summarize for retained metrics.- correlate: Get correlated events around a timestampExamples:@@ -105,7 +107,7 @@ Examples:},"resource_id": {Type: "string",- Description: "Resource ID to operate on",+ Description: "Resource ID to operate on. For incidents use the canonical resource ID returned by pulse_query, including for a resource no longer in current inventory.",},"note": {Type: "string",@@ -117,7 +119,11 @@ Examples:},"window_id": {Type: "string",- Description: "For incidents: specific incident window ID",+ Description: "For incidents: optional legacy recording ID, read as an archive only. Omit to read canonical resource history.",+ },+ "since": {+ Type: "string",+ Description: "For incidents: earliest observation timestamp (RFC3339, default 24 hours ago). Retention and collection gaps still apply.",},"timestamp": {Type: "string",@@ -129,7 +135,7 @@ Examples:},"limit": {Type: "integer",- Description: "For incidents: max windows to return (default: 5)",+ Description: "For incidents: maximum retained events to return, newest first (default 50, range 1-200)",},},Required: []string{"action", "resource_id"},@@ -168,38 +174,77 @@ func (e *PulseToolExecutor) executeKnowledge(ctx context.Context, args map[strinfunc (e *PulseToolExecutor) executeGetIncidentWindow(_ context.Context, args map[string]interface{}) (CallToolResult, error) {resourceID, _ := args["resource_id"].(string)+ resourceID = strings.TrimSpace(resourceID)windowID, _ := args["window_id"].(string)- limit := intArg(args, "limit", 5)if resourceID == "" {return NewErrorResult(fmt.Errorf("resource_id is required")), nil}- if e.incidentRecorderProvider == nil {- return NewTextResult("Incident recording data not available. The incident recorder may not be enabled."), nil- }-- // If a specific window ID is requested+ // Isolate legacy recordings from the canonical timeline. Their sample times+ // are recorder timestamps, not verified source observation timestamps.if windowID != "" {+ if e.incidentRecorderProvider == nil {+ return NewErrorResult(fmt.Errorf("legacy incident recording archive is unavailable")), nil+ }window := e.incidentRecorderProvider.GetWindow(windowID)- if window == nil {- return NewTextResult(fmt.Sprintf("Incident window '%s' not found.", windowID)), nil+ if window == nil || window.ResourceID != resourceID {+ return NewErrorResult(fmt.Errorf("legacy incident recording not found for the requested resource")), nil}return NewJSONResult(map[string]interface{}{- "window": window,+ "source": "legacy_incident_recording",+ "window": window,+ "evidence_limit": "Recording timestamps do not establish when the source measured each value. Repeated values may be cached observations. This archive is not the canonical incident timeline.",}), nil}- // Get windows for the resource- windows := e.incidentRecorderProvider.GetWindowsForResource(resourceID, limit)- if len(windows) == 0 {- return NewTextResult(fmt.Sprintf("No incident recording data found for resource '%s'. Incident data is captured when alerts fire.", resourceID)), nil+ limit := intArg(args, "limit", 50)+ if limit < 1 || limit > 200 {+ return NewErrorResult(fmt.Errorf("limit must be between 1 and 200")), nil+ }+ queriedAt := time.Now().UTC()+ since := queriedAt.Add(-24 * time.Hour)+ if value, exists := args["since"]; exists {+ text, ok := value.(string)+ if !ok {+ return NewErrorResult(fmt.Errorf("since must be an RFC3339 timestamp")), nil+ }+ var err error+ since, err = time.Parse(time.RFC3339, text)+ if err != nil || since.After(queriedAt) {+ return NewErrorResult(fmt.Errorf("since must be an RFC3339 timestamp no later than now")), nil+ }+ }+ if e.actionAuditStore == nil {+ return NewErrorResult(fmt.Errorf("canonical resource history is unavailable")), nil+ }+ // This organization-pinned store is also used by the resource history API+ // and Assistant handoffs. Do not reconstruct history from current metrics,+ // match resource names, or include adjacent resources implicitly.+ events, err := e.actionAuditStore.GetRecentChanges(resourceID, since, limit+1)+ if err != nil {+ return NewErrorResult(fmt.Errorf("read canonical resource history: %w", err)), nil+ }+ hasMore := len(events) > limit+ if hasMore {+ events = events[:limit]+ }+ if events == nil {+ events = []unifiedresources.ResourceChange{}}return NewJSONResult(map[string]interface{}{- "resource_id": resourceID,- "windows": windows,- "count": len(windows),+ "resource_id": resourceID,+ "source": "canonical_resource_timeline",+ "since": since,+ "queried_at": queriedAt,+ "time_basis": "observed_at",+ "events": events,+ "count": len(events),+ "limit": limit,+ "has_more": hasMore,+ "coverage": "retained_records_only",+ "evidence_limit": "These are retained observations, not continuous coverage. Empty history does not establish health or absence of incidents. ObservedAt is when Pulse observed a change, while OccurredAt is present only when its occurrence time is known. An alert resolving establishes that alert's recovery, not its cause or a verified action outcome.",}), nil}