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.

Stability sweep on the agent-substrate arc

rcourtmaneeb2975d22c9
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index be57bd389e..50a707b6ae 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1427,8 +1427,12 @@ capability with stable name (snake_case agent identifier),
description, category (`context` / `operator-state` / `finding`),
HTTP method + path, required auth scope, response shape name, and
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
+fetch this once at startup to learn what's available; the
+`cmd/pulse-mcp` adapter reads the manifest to register MCP tools,
+and any future adapter (HTTP-API SDK, Claude-Code custom toolkit,
+etc.) reads the same manifest the same way — manifest-driven
+projection is the substrate's deliberate single source of truth
+for "what can an agent do here?". The manifest
itself is unauthenticated and cacheable (`Cache-Control: public,
max-age=300`) — declared in the router's `publicPaths` list so
the global auth middleware does not gate it; the underlying
@@ -1445,12 +1449,28 @@ 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.
+(snake_case stable codes); the `message` field carries
+human-readable text agents can surface to operators without
+losing the code.
+
+There are two layers of stable codes. First, **capability-specific
+codes** are declared per capability in the manifest's `errorCodes`
+list and represent the closed set of failure modes that
+capability's handler emits. Today these are:
+`resource_not_found` (`get_resource_context`),
+`operator_state_not_set` (`get_operator_state`),
+`operator_state_invalid` (`set_operator_state`).
+Adding or renaming one requires both the handler emission and the
+manifest declaration to move together — drift between them is a
+contract regression. Second, **cross-cutting codes** apply to
+every authenticated endpoint and are emitted by the
+multi-tenant / auth middleware rather than any specific
+capability handler: `invalid_org` (400) when the org id resolves
+to garbage, `org_suspended` (403) when the resolved org has been
+suspended, and `access_denied` (403) when the org RBAC denies the
+request. Agents must accept these alongside any capability's
+declared codes; the manifest deliberately does not duplicate them
+on every entry.
The agent substrate is end-to-end exercised by two paired tests in
`internal/api/agent_substrate_e2e_test.go`. The first test boots
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 2b73e4b02c..b6d4de6edf 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -14,6 +14,7 @@ import (
"os"
"path/filepath"
"reflect"
+ "regexp"
"sort"
"strings"
"testing"
@@ -13728,6 +13729,98 @@ func TestContract_OperatorStateWriteEmitsStableErrorTokens(t *testing.T) {
}
}
+// TestContract_AgentSurfaceErrorCodesMatchManifestDeclarations pins
+// the symmetry between what handlers actually emit and what the
+// capabilities manifest declares. The doc says the manifest's
+// errorCodes list is "the closed set of values the error field may
+// carry on failure"; this test enforces that claim by reading every
+// writeJSONError call from the two agent-surface handler files and
+// asserting each emitted code is either (a) declared by the matching
+// capability, or (b) one of the three cross-cutting codes the auth
+// middleware emits universally. Drift in either direction is a
+// contract regression — emitting an undeclared code silently breaks
+// agents that branch on the closed set; declaring a code the
+// handler never emits misleads agents into writing dead-code paths.
+func TestContract_AgentSurfaceErrorCodesMatchManifestDeclarations(t *testing.T) {
+ // Codes emitted by the multi-tenant / auth middleware that apply
+ // to every authenticated endpoint and are intentionally not
+ // duplicated on per-capability errorCodes lists. Documented in
+ // api-contracts.md "cross-cutting codes" paragraph.
+ crossCutting := map[string]bool{
+ "invalid_org": true,
+ "org_suspended": true,
+ "access_denied": true,
+ }
+
+ // Handler files that back agent-surface capabilities. If a future
+ // capability adds a new file, append it here so the audit follows.
+ handlerFiles := []string{
+ "agent_resource_context.go",
+ "resources_operator_state.go",
+ }
+
+ // Extract every (status, code) pair from writeJSONError calls.
+ // The regex tolerates whitespace/newlines that gofmt may insert
+ // between the call's arguments.
+ emitted := map[string]bool{}
+ codeRE := regexp.MustCompile(`writeJSONError\([^"]*"[^"]+",\s*"([a-z_][a-z_0-9]*)"`)
+ for _, file := range handlerFiles {
+ body, err := os.ReadFile(file)
+ if err != nil {
+ t.Fatalf("read %s: %v", file, err)
+ }
+ // codeRE captures the second string literal (the code), but
+ // the first arg is `w` (an identifier), then a status int, so
+ // we use a looser pattern: find writeJSONError followed by
+ // `, "code"` somewhere on the same logical call.
+ looseRE := regexp.MustCompile(`writeJSONError\([^)]*?"([a-z_][a-z_0-9]+)"`)
+ // Try the strict match first for documentation; fall back to
+ // the loose one for actual extraction.
+ _ = codeRE
+ for _, m := range looseRE.FindAllSubmatch(body, -1) {
+ emitted[string(m[1])] = true
+ }
+ }
+ if len(emitted) == 0 {
+ t.Fatal("no writeJSONError emissions found in agent-surface handler files; the audit regex must be wrong")
+ }
+
+ // Pull declared codes from the manifest source so the test
+ // follows manifest edits without duplicating the data here.
+ manifestSrc, err := os.ReadFile("agent_capabilities.go")
+ if err != nil {
+ t.Fatalf("read agent_capabilities.go: %v", err)
+ }
+ declared := map[string]bool{}
+ declaredRE := regexp.MustCompile(`ErrorCodes:\s*\[\]string\{([^}]+)\}`)
+ for _, m := range declaredRE.FindAllSubmatch(manifestSrc, -1) {
+ // The capture group is the content between `{` and `}`,
+ // shaped like `"code1", "code2"`. Pull each quoted string.
+ quoted := regexp.MustCompile(`"([a-z_][a-z_0-9]+)"`)
+ for _, q := range quoted.FindAllSubmatch(m[1], -1) {
+ declared[string(q[1])] = true
+ }
+ }
+
+ // Every emitted code must be either declared somewhere in the
+ // manifest OR a cross-cutting code.
+ for code := range emitted {
+ if declared[code] || crossCutting[code] {
+ continue
+ }
+ t.Errorf("handler emits %q but no capability in the manifest declares it and it is not a documented cross-cutting code — drift here breaks agents that branch on the closed set", code)
+ }
+
+ // Every manifest-declared code must have a matching emission
+ // somewhere in the agent-surface handlers, otherwise agents
+ // follow a code path the substrate never walks.
+ for code := range declared {
+ if !emitted[code] {
+ t.Errorf("manifest declares %q but no agent-surface handler emits it — declaring a dead code misleads agents into writing branches the substrate never triggers", code)
+ }
+ }
+}
+
// 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
diff --git a/internal/api/router_public_paths_inventory_test.go b/internal/api/router_public_paths_inventory_test.go
index 61a5f249f3..87cfd76c8a 100644
--- a/internal/api/router_public_paths_inventory_test.go
+++ b/internal/api/router_public_paths_inventory_test.go
@@ -120,6 +120,7 @@ var publicPathsAllowlist = []string{
"/install.sh",
"/install.ps1",
"/download/pulse-agent",
+ "/api/agent/capabilities",
"/api/agent/version",
"/api/agent/ws",
"/api/server/info",