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.

End-to-end test the agent substrate's discovery → triage → depth flow

rcourtman8cf15fe63988
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 4cbeec4baf..068024f29c 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -975,6 +975,14 @@ the bounded approval-store scan, and a per-resource operator-state
SQLite point lookup. Agents pick "where do I focus?" from the
fleet view and then drill into the per-resource bundle for depth.
+`/api/agent/capabilities` is registered in the router's
+`publicPaths` list so the global auth middleware does not gate
+the discovery manifest. The manifest is unauthenticated by
+design: an agent that does not yet have a token must still be
+able to introspect Pulse to learn how to ask for one. The
+underlying capabilities the manifest declares keep their own auth
+scopes — the public posture applies only to discovery itself.
+
The findings runtime now consumes operator-set per-resource state
through a provider adapter wired in `internal/api/router.go` at
startup. The adapter returns a `ResourceOperatorStateProjection`
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 3caf152ea0..53945036e5 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1425,12 +1425,27 @@ the closed set of stable error codes the response may carry. Agents
fetch this once at startup to learn what's available; future
MCP-server slices read the manifest to register tools. The manifest
itself is unauthenticated and cacheable (`Cache-Control: public,
-max-age=300`); the underlying capabilities keep their own auth
-scopes. Adding a capability is a deliberate "this is part of the
-agent surface" commitment — the manifest is hand-authored rather
-than auto-generated so contract decisions (which capabilities are
-agent-stable, what the stable error codes are, what category each
-belongs to) cannot drift behind code changes.
+max-age=300`) — declared in the router's `publicPaths` list so
+the global auth middleware does not gate it; the underlying
+capabilities keep their own auth scopes. The manifest's
+`unauthenticated` posture is the chicken-and-egg fix: an agent
+that does not yet have a token must still be able to introspect
+Pulse to learn how to ask for one. Adding a capability is a
+deliberate "this is part of the agent surface" commitment — the
+manifest is hand-authored rather than auto-generated so contract
+decisions (which capabilities are agent-stable, what the stable
+error codes are, what category each belongs to) cannot drift
+behind code changes.
+
+The agent surface uses one error-envelope shape across every
+endpoint — `{"error": "<stable_code>", "message": "<human>"}` —
+written via `writeJSONError`. Agents branch on the `error` field
+(snake_case stable codes, e.g. `resource_not_found`,
+`operator_state_not_set`, `operator_state_invalid`); the `message`
+field carries human-readable text agents can surface to operators
+without losing the code. The capabilities manifest's `errorCodes`
+list per capability is the closed set of values the `error` field
+may carry on failure; an unmatched value is a contract regression.
`/api/agent/resource-context/{id}` is the agent-consumable bundled
context endpoint. One read returns the full situated picture of a
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 388a4d33a2..217ba71a87 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -555,6 +555,14 @@ canonical Pulse fleet scale; agents that need to scan tens of
thousands of resources should narrow the registry first via the
existing filtered list endpoints, not the fleet rollup.
+`/api/agent/capabilities` is unauthenticated and cacheable
+(`Cache-Control: public, max-age=300`); the manifest is a small,
+hand-authored static structure serialized once per request with
+no I/O, so even unbounded discovery traffic costs nothing per
+request beyond JSON encoding. Agents are expected to fetch the
+manifest once at startup and rely on the 5-minute cache header,
+not poll on every operation.
+
The new-finding hot path now consults a per-resource operator-state
provider when one is wired. The provider call is gated on
`f.ResourceID != ""` and a non-nil provider so deployments without
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index d2e2328f26..e16b284e3c 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -991,6 +991,15 @@ the unified-resources store and the approval store rehydrate on
startup, the fleet view recovers the same situated picture without
any fleet-specific rehydration step.
+The agent capabilities manifest at `/api/agent/capabilities` is
+hand-authored static data. There is no persistence to recover —
+the manifest is a constant compiled into the binary; on every
+restart it serves identical content as soon as the HTTP listener
+is up. The endpoint sits in the router's `publicPaths` list so
+the global auth middleware does not gate it, which makes
+discovery available before any bootstrap-token / first-run flow
+completes.
+
The findings runtime reads operator-set state through the same
durable `resource_operator_state` SQLite table on every
new-finding-add. Both the time-bounded maintenance window and the
diff --git a/internal/api/agent_substrate_e2e_test.go b/internal/api/agent_substrate_e2e_test.go
new file mode 100644
index 0000000000..cf6da28da5
--- /dev/null
+++ b/internal/api/agent_substrate_e2e_test.go
@@ -0,0 +1,216 @@
+package api
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+// TestAgentSubstrate_DiscoveryToTriageToDepthFlowsThroughHTTPBoundary is
+// the end-to-end contract proof for the agent-paradigm read substrate.
+// Unit tests cover each piece in isolation; this test boots the full
+// router stack and proves the discovery → triage → depth chain works
+// as one substrate through the actual HTTP boundary an external agent
+// would hit.
+//
+// Specifically:
+// - GET /api/agent/capabilities returns the v1 manifest with
+// get_resource_context, get_fleet_context, and subscribe_events
+// declared. This is the discovery contract — agents fetch this
+// once at startup and learn what's available.
+// - The manifest's declared path for get_fleet_context actually
+// resolves and returns the iteration-safe AgentFleetContext shape
+// (resources is an array, never null). This is the triage entry
+// point: "where do I focus?"
+// - The manifest's declared path for get_resource_context returns
+// the stable resource_not_found error code for an unknown id,
+// not a generic 404 with human text. This is the depth entry
+// point's documented error contract — agents branch on the code,
+// not on the human message.
+// - All three endpoints sit behind monitoring:read auth, exercised
+// via the X-API-Token transport.
+//
+// If any of these break, an external agent walking the substrate the
+// way the manifest documents will silently fail in a way the
+// per-piece unit tests can't catch.
+func TestAgentSubstrate_DiscoveryToTriageToDepthFlowsThroughHTTPBoundary(t *testing.T) {
+ rawToken := "agent-substrate-e2e-test.12345678"
+ record := newTokenRecord(t, rawToken, []string{config.ScopeMonitoringRead}, nil)
+ cfg := newTestConfigWithTokens(t, record)
+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
+
+ // --- 1. Discovery: fetch the capabilities manifest. ---
+ // Intentionally unauthenticated — the manifest itself is public
+ // (the underlying capabilities have their own auth scopes); the
+ // discovery contract is that an agent can introspect Pulse before
+ // holding a token.
+ req := httptest.NewRequest(http.MethodGet, "/api/agent/capabilities", nil)
+ rec := httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("capabilities GET: status = %d, body = %s", rec.Code, rec.Body.String())
+ }
+ if got := rec.Header().Get("Content-Type"); got != "application/json" {
+ t.Errorf("capabilities Content-Type: got %q, want application/json", got)
+ }
+ var manifest AgentCapabilitiesManifest
+ if err := json.NewDecoder(rec.Body).Decode(&manifest); err != nil {
+ t.Fatalf("decode manifest: %v", err)
+ }
+ if manifest.Version != "v1" {
+ t.Fatalf("manifest version: got %q, want v1", manifest.Version)
+ }
+
+ // Index by name so we can pull the declared path / shape for the
+ // next steps without depending on slice ordering.
+ byName := map[string]AgentCapability{}
+ for _, c := range manifest.Capabilities {
+ byName[c.Name] = c
+ }
+ required := []string{
+ "get_resource_context",
+ "get_fleet_context",
+ "subscribe_events",
+ "get_operator_state",
+ "set_operator_state",
+ "clear_operator_state",
+ "list_findings",
+ "acknowledge_finding",
+ "snooze_finding",
+ "dismiss_finding",
+ "resolve_finding",
+ }
+ for _, name := range required {
+ if _, ok := byName[name]; !ok {
+ t.Errorf("manifest missing required capability %q — discovery contract broken", name)
+ }
+ }
+
+ // --- 2. Triage: call the path the manifest declares for the
+ // fleet view. The declared shape is "AgentFleetContext", which
+ // must round-trip through the actual handler. ---
+ fleetCap := byName["get_fleet_context"]
+ if fleetCap.Path != "/api/agent/fleet-context" {
+ t.Fatalf("get_fleet_context path: got %q, want /api/agent/fleet-context", fleetCap.Path)
+ }
+ if fleetCap.Method != http.MethodGet {
+ t.Fatalf("get_fleet_context method: got %q, want GET", fleetCap.Method)
+ }
+ if fleetCap.Scope != "monitoring:read" {
+ t.Fatalf("get_fleet_context scope: got %q, want monitoring:read", fleetCap.Scope)
+ }
+ if fleetCap.ResponseShape != "AgentFleetContext" {
+ t.Fatalf("get_fleet_context response shape: got %q, want AgentFleetContext", fleetCap.ResponseShape)
+ }
+
+ // Unauthenticated call must be rejected — the underlying
+ // capability's own auth scope holds even though discovery is
+ // unauthenticated.
+ req = httptest.NewRequest(http.MethodGet, fleetCap.Path, nil)
+ rec = httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("fleet GET unauth: status = %d, want 401, body = %s", rec.Code, rec.Body.String())
+ }
+
+ // Authenticated call must serve the iteration-safe shape.
+ req = httptest.NewRequest(http.MethodGet, fleetCap.Path, nil)
+ req.Header.Set("X-API-Token", rawToken)
+ rec = httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("fleet GET auth: status = %d, body = %s", rec.Code, rec.Body.String())
+ }
+ body := rec.Body.String()
+ // Empty registry (no monitor wired) must surface as `resources:
+ // []`, never null. Pin the wire form rather than the decoded
+ // length so a regression that turns the empty slice into null is
+ // caught here even though Go would happily decode either.
+ if !strings.Contains(body, `"resources":[]`) {
+ t.Errorf("fleet response must surface resources as empty array; body = %s", body)
+ }
+ var fleet AgentFleetContext
+ if err := json.Unmarshal([]byte(body), &fleet); err != nil {
+ t.Fatalf("decode fleet: %v", err)
+ }
+ if fleet.Resources == nil {
+ t.Error("fleet.Resources must never be nil — agents iterate without nil-checks")
+ }
+ if fleet.GeneratedAt.IsZero() {
+ t.Error("fleet.GeneratedAt must be populated so agents can reason about freshness")
+ }
+
+ // --- 3. Depth: call the path the manifest declares for the
+ // per-resource bundle. The manifest also declares the stable
+ // error code "resource_not_found" — exercise the unknown-id path
+ // to confirm the error code reaches the wire verbatim. ---
+ contextCap := byName["get_resource_context"]
+ if contextCap.Path != "/api/agent/resource-context/{resourceId}" {
+ t.Fatalf("get_resource_context path: got %q, want /api/agent/resource-context/{resourceId}", contextCap.Path)
+ }
+ hasNotFoundCode := false
+ for _, code := range contextCap.ErrorCodes {
+ if code == "resource_not_found" {
+ hasNotFoundCode = true
+ break
+ }
+ }
+ if !hasNotFoundCode {
+ t.Fatalf("get_resource_context manifest must declare resource_not_found error code; got %v", contextCap.ErrorCodes)
+ }
+
+ // Substitute a deliberately-unknown canonical id so the handler
+ // has to take the not-found branch and write the stable error
+ // token. The substrate's contract is that this token reaches the
+ // wire intact so agents branch on it rather than parsing human
+ // text.
+ unknownPath := strings.Replace(contextCap.Path, "{resourceId}", "vm:e2e-unknown-99", 1)
+ req = httptest.NewRequest(http.MethodGet, unknownPath, nil)
+ req.Header.Set("X-API-Token", rawToken)
+ rec = httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+ if rec.Code != http.StatusNotFound {
+ t.Fatalf("resource-context unknown: status = %d, want 404, body = %s", rec.Code, rec.Body.String())
+ }
+ body = rec.Body.String()
+ // The error code lives under the canonical `"error"` key (the
+ // shared writeJSONError shape used across the API surface), with
+ // human-readable text under `"message"`. Pin both: the stable
+ // token agents branch on, and the message field's presence so
+ // agents can surface human text without losing the code.
+ if !strings.Contains(body, `"error":"resource_not_found"`) {
+ t.Errorf("resource-context unknown body must carry stable error code resource_not_found under the \"error\" key; body = %s", body)
+ }
+ var errEnvelope map[string]string
+ if err := json.Unmarshal([]byte(body), &errEnvelope); err != nil {
+ t.Fatalf("decode error envelope: %v", err)
+ }
+ if errEnvelope["error"] != "resource_not_found" {
+ t.Errorf("error envelope code: got %q, want resource_not_found", errEnvelope["error"])
+ }
+ if strings.TrimSpace(errEnvelope["message"]) == "" {
+ t.Error("error envelope must carry a human-readable message alongside the stable code")
+ }
+
+ // --- 4. The SSE-stream subscribe_events capability: assert the
+ // declared path is wired (a HEAD/GET probe is enough — we don't
+ // hold the connection open). The substrate proof here is that
+ // discovery's claim about /api/agent/events is honest: the path
+ // resolves (auth-gated) rather than 404'ing. ---
+ streamCap := byName["subscribe_events"]
+ if streamCap.Path != "/api/agent/events" {
+ t.Fatalf("subscribe_events path: got %q, want /api/agent/events", streamCap.Path)
+ }
+ req = httptest.NewRequest(http.MethodGet, streamCap.Path, nil)
+ rec = httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+ // Without a token, the stream must reject at the auth boundary
+ // rather than 404 — the path is registered, just gated.
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("subscribe_events unauth: status = %d, want 401 (path must be registered, just gated); body = %s", rec.Code, rec.Body.String())
+ }
+}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index d722f39b2e..64388a2665 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -13623,6 +13623,25 @@ func TestContract_AgentFleetContextEndpointSurfacesStableShape(t *testing.T) {
}
}
+// TestContract_AgentCapabilitiesManifestIsPublic pins the auth
+// contract for the discovery surface: the manifest must be in the
+// router's publicPaths list so it serves without a token. The
+// manifest's purpose is "let an agent introspect Pulse before it
+// has credentials" — gating the manifest behind the same
+// monitoring:read scope that gates everything else makes
+// discovery a chicken-and-egg problem. Slice 40 had this wrong;
+// slice 47 fixed it. Pin so it cannot regress silently.
+func TestContract_AgentCapabilitiesManifestIsPublic(t *testing.T) {
+ source, err := os.ReadFile("router.go")
+ if err != nil {
+ t.Fatalf("read router.go: %v", err)
+ }
+ src := string(source)
+ if !strings.Contains(src, "\"/api/agent/capabilities\", // Agent-paradigm discovery manifest") {
+ t.Error("router.go publicPaths must include /api/agent/capabilities so the discovery manifest serves without a token — agents need to introspect Pulse before they have credentials")
+ }
+}
+
// TestContract_GetFleetContextCapabilityListed pins the discovery
// contract: the capabilities manifest must declare get_fleet_context
// so an agent reading the manifest learns the fleet view exists and
diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.go
index f4068acddf..6e2d5e67ea 100644
--- a/internal/api/route_inventory_test.go
+++ b/internal/api/route_inventory_test.go
@@ -260,6 +260,7 @@ var dynamicRouteAllowlist = []string{}
var publicRouteAllowlist = []string{
"/api/health",
"/api/version",
+ "/api/agent/capabilities",
"/api/agent/version",
"/api/agent/ws",
"/api/server/info",
diff --git a/internal/api/router.go b/internal/api/router.go
index f6cdd57b8b..a03db603dc 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -3727,6 +3727,7 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
"/install.sh", // Unified agent installer
"/install.ps1", // Unified agent Windows installer
"/download/pulse-agent", // Unified agent binary
+ "/api/agent/capabilities", // Agent-paradigm discovery manifest; underlying capabilities keep their own auth scopes
"/api/agent/version", // Agent update checks need to work before auth
"/api/agent/ws", // Agent WebSocket has its own auth via registration
"/api/server/info", // Server info for installer script