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
backend and governance: MCP contract, agent capabilities, API, and release-control
rcourtmanee8a24e14a1f
diff --git a/README.md b/README.mdindex 47e2430b85..5355b8c42d 100644--- a/README.md+++ b/README.md@@ -182,7 +182,7 @@ Self-hosted tiers:|---|---:|---|---:|---|| Community | Free | Included | 7 days | Full self-hosted monitoring || Relay | $39/yr or $4.99/mo | Included | 14 days | Remote web access, mobile app pairing, and push notifications |-| Pro | $79/yr or $8.99/mo | Included | 90 days | Root-cause analysis, safe remediation workflows, and operations tooling |+| Pro | $79/yr or $8.99/mo | Included | 90 days | Hands-on Patrol modes, issue investigation, verified fixes, and operations tooling |Pulse still counts top-level monitored systems once no matter how they arecollected. VMs, containers, pods, disks, backups, and other child resources@@ -198,8 +198,8 @@ Runtime-aligned capability summary:|---|:---:|:---:|:---:|:---:|| Pulse Patrol (Background Health Checks) | ✅ | ✅ | ✅ | ✅ || Remote Access / Mobile / Push | — | ✅ | ✅ | ✅ |-| Alert-Triggered Root-Cause Analysis | — | — | ✅ | ✅ |-| Safe Remediation Workflows | — | — | ✅ | ✅ |+| Patrol Investigates Issues | — | — | ✅ | ✅ |+| Patrol Handles Safe Fixes | — | — | ✅ | ✅ || Centralized Agent Profiles | — | — | ✅ | ✅ || Update Alerts (Container/Package Updates) | ✅ | ✅ | ✅ | ✅ || SSO (OIDC/SAML/Multi-Provider) | ✅ | ✅ | ✅ | ✅ |diff --git a/cmd/agent-probe/main.go b/cmd/agent-probe/main.goindex 93c8512c7e..e845d97924 100644--- a/cmd/agent-probe/main.go+++ b/cmd/agent-probe/main.go@@ -25,8 +25,11 @@//// Hard constraints honored on purpose://-// - Standard library only. No internal/ai imports, no Pulse types-// reused. A real external agent has no privileged access.+// - No internal/ai or API handler imports. The only Pulse package+// reused is the tiny agentcapabilities wire/projection package, so this+// in-repo reference client cannot drift from the manifest shape or path+// projection rules. A real external agent can define the same JSON shape+// from the manifest or a generated client.// - Branches on stable error codes from the manifest, never on// human-readable error messages.// - Resolves paths from the manifest rather than hardcoding them.@@ -44,39 +47,17 @@package mainimport (- "bufio""context""encoding/json""flag""fmt"- "io""net/http"- "net/url""os""strings""time"-)--// agentCapability mirrors the api package's AgentCapability wire-// shape — defined inline so this program depends on nothing in the-// pulse module. If the manifest's shape evolves, this struct-// follows; the JSON tags are the contract.-type agentCapability struct {- Name string `json:"name"`- Description string `json:"description"`- Category string `json:"category"`- Method string `json:"method"`- Path string `json:"path"`- Scope string `json:"scope"`- ResponseShape string `json:"responseShape,omitempty"`- ErrorCodes []string `json:"errorCodes,omitempty"`- RequestBodyShape string `json:"requestBodyShape,omitempty"`-}-type agentCapabilitiesManifest struct {- Version string `json:"version"`- Capabilities []agentCapability `json:"capabilities"`-}+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+)// fleetResource is the per-resource thin rollup the fleet endpoint// returns. We only depend on the fields the probe actually needs to@@ -102,15 +83,6 @@ type fleetContext struct {GeneratedAt time.Time `json:"generatedAt"`}-// errorEnvelope is the shared shape every agent-surface endpoint-// uses on failure. The "error" field is a stable snake_case code-// (e.g. resource_not_found, operator_state_not_set); "message" is-// human text agents may surface but must not branch on.-type errorEnvelope struct {- Error string `json:"error"`- Message string `json:"message"`-}-func main() {baseURL := flag.String("base-url", "http://localhost:7655", "Pulse base URL")token := flag.String("token", "", "API token with monitoring:read scope (required for triage and depth steps)")@@ -125,7 +97,7 @@ func main() {client := &http.Client{Timeout: 15 * time.Second}// --- 1. Discovery. Public, no token needed. ---- manifest, err := fetchManifest(client, *baseURL)+ manifest, err := agentcapabilities.FetchManifest(context.Background(), client, *baseURL)if err != nil {exitf("discovery failed: %v", err)}@@ -134,26 +106,13 @@ func main() {fmt.Printf(" %-22s %s %s (%s)\n", cap.Name, cap.Method, cap.Path, cap.Scope)}- byName := map[string]agentCapability{}- for _, c := range manifest.Capabilities {- byName[c.Name] = c- }-- fleetCap, ok := byName["get_fleet_context"]- if !ok {- exitf("manifest missing required capability get_fleet_context")- }- contextCap, ok := byName["get_resource_context"]- if !ok {- exitf("manifest missing required capability get_resource_context")- }- streamCap, ok := byName["subscribe_events"]+ streamCap, ok := agentcapabilities.FindCapability(manifest.Capabilities, agentcapabilities.EventSubscriptionCapabilityName)if !ok {exitf("manifest missing required capability subscribe_events")}// --- 2. Triage. Authenticated. ---- fleet, err := fetchFleet(client, *baseURL, fleetCap.Path, *token)+ fleet, err := fetchFleet(context.Background(), client, *baseURL, manifest.Capabilities, *token)if err != nil {exitf("triage failed: %v", err)}@@ -184,8 +143,17 @@ func main() {fmt.Println("\nno resources visible to this token; skipping depth step")} else {// --- 3. Depth. ---- depthPath := strings.Replace(contextCap.Path, "{resourceId}", focus.CanonicalID, 1)- body, err := fetchAuthenticatedRaw(client, *baseURL+depthPath, *token)+ body, err := agentcapabilities.CallRequestResponseCapabilityHTTPBodyByName(+ context.Background(),+ client,+ *baseURL,+ *token,+ manifest.Capabilities,+ agentcapabilities.ResourceContextCapabilityName,+ map[string]any{+ "resourceId": focus.CanonicalID,+ },+ )if err != nil {exitf("depth failed for %s: %v", focus.CanonicalID, err)}@@ -207,7 +175,7 @@ func main() {streamCap.Path, *eventTimeout)ctx, cancel := context.WithTimeout(context.Background(), *eventTimeout)defer cancel()- if err := readOneSSEEvent(ctx, *baseURL+streamCap.Path, *token); err != nil {+ if err := readOneSSEEvent(ctx, *baseURL, streamCap.Path, *token); err != nil {// Timeout is the boring case (no events fired); not a hard// failure for a probe.if strings.Contains(err.Error(), "deadline exceeded") {@@ -219,24 +187,16 @@ func main() {fmt.Println("\nagent-probe done — discovery, triage, depth, and push all walked the substrate cleanly.")}-func fetchManifest(client *http.Client, baseURL string) (*agentCapabilitiesManifest, error) {- resp, err := client.Get(baseURL + "/api/agent/capabilities")- if err != nil {- return nil, fmt.Errorf("GET capabilities: %w", err)- }- defer resp.Body.Close()- if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("GET capabilities: status %d", resp.StatusCode)- }- var manifest agentCapabilitiesManifest- if err := json.NewDecoder(resp.Body).Decode(&manifest); err != nil {- return nil, fmt.Errorf("decode manifest: %w", err)- }- return &manifest, nil-}--func fetchFleet(client *http.Client, baseURL, path, token string) (*fleetContext, error) {- body, err := fetchAuthenticatedRaw(client, baseURL+path, token)+func fetchFleet(ctx context.Context, client *http.Client, baseURL string, capabilities []agentcapabilities.Capability, token string) (*fleetContext, error) {+ body, err := agentcapabilities.CallRequestResponseCapabilityHTTPBodyByName(+ ctx,+ client,+ baseURL,+ token,+ capabilities,+ agentcapabilities.FleetContextCapabilityName,+ nil,+ )if err != nil {return nil, err}@@ -247,43 +207,6 @@ func fetchFleet(client *http.Client, baseURL, path, token string) (*fleetContextreturn &fleet, nil}-// fetchAuthenticatedRaw is the shared GET helper for any-// authenticated agent-surface endpoint. Branches on the stable-// error envelope when a non-2xx comes back so the caller sees the-// agent-stable code, not just an HTTP status.-func fetchAuthenticatedRaw(client *http.Client, fullURL, token string) ([]byte, error) {- parsed, err := url.Parse(fullURL)- if err != nil {- return nil, fmt.Errorf("parse %q: %w", fullURL, err)- }- req, err := http.NewRequest(http.MethodGet, parsed.String(), nil)- if err != nil {- return nil, fmt.Errorf("build request: %w", err)- }- req.Header.Set("X-API-Token", token)- resp, err := client.Do(req)- if err != nil {- return nil, fmt.Errorf("GET %s: %w", parsed.Path, err)- }- defer resp.Body.Close()- body, err := io.ReadAll(resp.Body)- if err != nil {- return nil, fmt.Errorf("read body: %w", err)- }- if resp.StatusCode >= 200 && resp.StatusCode < 300 {- return body, nil- }- // Non-2xx: try to surface the stable error code from the- // envelope. Unauthenticated rejection comes through as plain- // text from the auth middleware (not the envelope), so fall back- // to the body verbatim if the JSON decode fails.- var env errorEnvelope- if err := json.Unmarshal(body, &env); err == nil && env.Error != "" {- return nil, fmt.Errorf("GET %s: %d %s (%s)", parsed.Path, resp.StatusCode, env.Error, env.Message)- }- return nil, fmt.Errorf("GET %s: %d %s", parsed.Path, resp.StatusCode, strings.TrimSpace(string(body)))-}-// pickFocus chooses the most "interesting" resource from a fleet// sweep. The triage rule is lexicographic — severity dominates// count: any resource with a critical finding outranks every@@ -322,57 +245,19 @@ func focusLess(a, b fleetResource) bool {}// readOneSSEEvent opens the SSE stream, reads up to the first-// non-keepalive event payload, prints it, and returns. SSE is line--// based with empty lines as record separators; this implementation-// is deliberately minimal — a few hundred bytes of stdlib code is-// enough to consume the substrate's push channel.-func readOneSSEEvent(ctx context.Context, fullURL, token string) error {- req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullURL, nil)- if err != nil {+// non-keepalive event payload through the shared Pulse Intelligence+// SSE parser, prints it, and returns.+func readOneSSEEvent(ctx context.Context, baseURL, path, token string) error {+ seen := false+ if err := agentcapabilities.StreamAgentActionableSSERecords(ctx, nil, baseURL, path, token, func(record agentcapabilities.SSERecord) bool {+ fmt.Printf(" event: %s\n data: %s\n", record.Event, record.Data)+ seen = true+ return false+ }); err != nil {return err}- req.Header.Set("X-API-Token", token)- req.Header.Set("Accept", "text/event-stream")- // No timeout on this client — context cancels the read.- resp, err := http.DefaultClient.Do(req)- if err != nil {- return err- }- defer resp.Body.Close()- if resp.StatusCode != http.StatusOK {- return fmt.Errorf("subscribe: status %d", resp.StatusCode)- }-- scanner := bufio.NewScanner(resp.Body)- scanner.Buffer(make([]byte, 64*1024), 1<<20)-- var event, data string- skippedConnected := false- for scanner.Scan() {- line := scanner.Text()- switch {- case strings.HasPrefix(line, "event: "):- event = strings.TrimPrefix(line, "event: ")- case strings.HasPrefix(line, "data: "):- data = strings.TrimPrefix(line, "data: ")- case line == "":- // End of event record. The first event the server- // always emits is "stream.connected" — skip it once so- // the probe surfaces the first *real* event (or a- // heartbeat).- if event == "stream.connected" && !skippedConnected {- skippedConnected = true- event, data = "", ""- continue- }- if event != "" || data != "" {- fmt.Printf(" event: %s\n data: %s\n", event, data)- return nil- }- }- }- if err := scanner.Err(); err != nil {- return err+ if seen {+ return nil}return ctx.Err()}diff --git a/cmd/agent-probe/main_test.go b/cmd/agent-probe/main_test.goindex 909081fe1c..ad99414592 100644--- a/cmd/agent-probe/main_test.go+++ b/cmd/agent-probe/main_test.go@@ -1,7 +1,15 @@package mainimport (+ "context"+ "io"+ "net/http"+ "net/http/httptest"+ "os"+ "strings""testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")// TestPickFocus_PrefersCriticalThenWarningThenInfo pins the focus@@ -81,3 +89,95 @@ func TestPickFocus_PrefersCriticalThenWarningThenInfo(t *testing.T) {})}}++func TestFetchFleetUsesSharedCapabilityBodyExecutor(t *testing.T) {+ var got struct {+ Method string+ Path string+ Token string+ }+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ got.Method = r.Method+ got.Path = r.URL.EscapedPath()+ got.Token = r.Header.Get(agentcapabilities.AgentAPITokenHeader)+ w.WriteHeader(http.StatusAccepted)+ _, _ = w.Write([]byte(`{+ "generatedAt": "2026-06-18T07:00:00Z",+ "resources": [+ {+ "canonicalId": "vm:101",+ "resourceType": "vm",+ "resourceName": "web",+ "findings": {"total": 1, "critical": 1, "warning": 0, "info": 0},+ "pendingApprovalCount": 2+ }+ ]+ }`))+ }))+ defer server.Close()++ fleet, err := fetchFleet(context.Background(), server.Client(), server.URL, []agentcapabilities.Capability{{+ Name: agentcapabilities.FleetContextCapabilityName,+ Method: http.MethodGet,+ Path: "/api/agent/fleet-context",+ }}, "probe-token")+ if err != nil {+ t.Fatalf("fetchFleet: %v", err)+ }+ if len(fleet.Resources) != 1 || fleet.Resources[0].CanonicalID != "vm:101" || fleet.Resources[0].Findings.Critical != 1 {+ t.Fatalf("fleet = %+v", fleet)+ }+ if got.Method != http.MethodGet || got.Path != "/api/agent/fleet-context" {+ t.Fatalf("request method/path = %s %s", got.Method, got.Path)+ }+ if got.Token != "probe-token" {+ t.Fatalf("token = %q", got.Token)+ }+}++func TestReadOneSSEEventUsesSharedActionableFilter(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Header.Get("Accept") != agentcapabilities.AgentSSEAccept {+ t.Errorf("Accept header = %q, want %q", r.Header.Get("Accept"), agentcapabilities.AgentSSEAccept)+ }+ if r.Header.Get(agentcapabilities.AgentAPITokenHeader) != "probe-token" {+ t.Errorf("%s header = %q", agentcapabilities.AgentAPITokenHeader, r.Header.Get(agentcapabilities.AgentAPITokenHeader))+ }+ w.Header().Set("Content-Type", agentcapabilities.AgentSSEAccept)+ _, _ = w.Write([]byte(strings.Join([]string{+ "event: " + string(agentcapabilities.EventKindStreamConnected),+ "data: {}",+ "",+ "event: " + string(agentcapabilities.EventKindHeartbeat),+ "",+ "event: " + string(agentcapabilities.EventKindFindingCreated),+ "data: {\"findingId\":\"f1\"}",+ "",+ }, "\n")))+ }))+ defer server.Close()++ oldStdout := os.Stdout+ r, w, err := os.Pipe()+ if err != nil {+ t.Fatalf("pipe stdout: %v", err)+ }+ os.Stdout = w+ err = readOneSSEEvent(context.Background(), server.URL, agentcapabilities.AgentEventsPath, "probe-token")+ _ = w.Close()+ os.Stdout = oldStdout+ output, readErr := io.ReadAll(r)+ if readErr != nil {+ t.Fatalf("read stdout: %v", readErr)+ }+ if err != nil {+ t.Fatalf("readOneSSEEvent: %v", err)+ }+ text := string(output)+ if !strings.Contains(text, "event: "+string(agentcapabilities.EventKindFindingCreated)) {+ t.Fatalf("stdout missing finding event: %s", text)+ }+ if strings.Contains(text, string(agentcapabilities.EventKindStreamConnected)) || strings.Contains(text, string(agentcapabilities.EventKindHeartbeat)) {+ t.Fatalf("stdout included transport event: %s", text)+ }+}diff --git a/cmd/pulse-mcp/README.md b/cmd/pulse-mcp/README.mdindex ec0153d38e..1c963c63df 100644--- a/cmd/pulse-mcp/README.md+++ b/cmd/pulse-mcp/README.md@@ -1,14 +1,40 @@# pulse-mcp-`pulse-mcp` is a Model Context Protocol (MCP) server that wraps Pulse's-agent surface as a tool set. It lets Claude Desktop, Claude Code, and any-other MCP-speaking client drive Pulse natively: list findings, read the-fleet, drill into a resource, set operator intent, run governed actions.+`pulse-mcp` is the Model Context Protocol (MCP) adapter for Pulse+Intelligence. It exposes the same governed operations substrate that+Pulse Assistant uses inside the app, but as tools for Claude Desktop,+Claude Code, OpenCode, and any other MCP-speaking client: list findings,+read the fleet, drill into a resource, set operator intent, and run+governed actions.++## Pulse Intelligence surface contract++<!-- pulse-mcp-surface-contract:start -->+- **Pulse Intelligence Core**: Canonical context, governed actions, safety gates, approval state, action audit, and verification shared by Pulse Assistant, Pulse MCP, and Pulse Patrol.+- **Pulse Patrol**: Patrol is the first-party operations surface: it watches, investigates, acts within the chosen Patrol mode, verifies outcomes, and records what happened.+- **Pulse Assistant** (the native Pulse surface): The contextual explanation, approval, and handoff surface for Patrol findings, governed actions, verification, and operator questions. Affordances: tools and interactive questions.+- **Pulse MCP**: The external-agent adapter that projects canonical Pulse Intelligence capabilities as MCP tools. Affordances: tools, resources, prompts, and capability metadata.+<!-- pulse-mcp-surface-contract:end -->The adapter is manifest-driven. Every tool it exposes is one entry in-Pulse's hand-authored capabilities manifest at `/api/agent/capabilities`.-Adding a capability there extends this server automatically. There is no-hardcoded tool list to keep in sync.+Pulse's canonical capabilities manifest at `/api/agent/capabilities`.+Adding a request/response capability to the manifest-owned Pulse MCP surface+tool contract extends this server automatically. There is no hardcoded tool+list to keep in sync, and there is no separate MCP-only action path to maintain+beside Pulse Assistant. `tools/list` uses the shared Pulse Intelligence+projection to expose the manifest metadata in each tool description, including+route, auth scope, action mode (`read`, `mixed`, `write`), approval policy+(`scope_only`, `action_plan`), request/response shape, and stable error codes.+Operator-state writes plus governed action and finding lifecycle tools also+expose typed `inputSchema` definitions for their top-level arguments, including+stable enums for criticality, approval decisions, and dismissal reasons.+The same shared projection exposes `resources/list` and `resources/read`+when the manifest contains the canonical fleet and per-resource context+capabilities. Resource URIs use `pulse://resource/<resource-id>` and+`resources/read` returns the same JSON bundle as `get_resource_context`.+It also exposes `prompts/list` and `prompts/get` from the manifest-owned+`workflowPrompts` catalogue. Those prompts are workflow hints over the+manifest tools and resource URIs, not a separate MCP playbook layer.## Install@@ -77,26 +103,42 @@ Use any of the install paths above. The rest of this guide assumes### 2. Mint an API token-Pulse needs a token with `monitoring:read` for the read tools, and-`monitoring:write` if you want the write tools (`set_operator_state`,-`clear_operator_state`) to work. Mint one in **Settings → Security → API-Tokens**.+Pulse fetches the live capabilities manifest first, and every tool+description includes its required auth scope. For a read-only external+agent, start with `monitoring:read`. For the full published Pulse+Intelligence surface, mint a token with the current manifest scopes:+<!-- pulse-mcp-scope-list:start -->+`monitoring:read`, `monitoring:write`, `settings:read`, `settings:write`, and `ai:execute`+<!-- pulse-mcp-scope-list:end -->++You can also mint narrower tokens for specific workflows. For example,+omit `settings:write` if the client should not add or edit monitored+infrastructure sources, and omit `ai:execute` if it should not review+Patrol findings or plan, approve, or execute governed actions. Mint the+token in **Settings →+Security → API Tokens**.### 3. Wire it into your client-#### Claude Desktop+<!-- pulse-mcp-client-config:start -->+Most MCP clients need the same manifest-owned runtime facts: server name `pulse`, command `pulse-mcp`, base URL flag `--base-url`, default URL `http://localhost:7655`, and token environment variable `PULSE_API_TOKEN`.+The generated examples below cover the currently declared config families: `OpenCode`, `Claude-style clients`, and `custom MCP clients`.+If your client uses a different outer config format, keep those runtime facts and adapt only the wrapper.-Edit `~/Library/Application Support/Claude/claude_desktop_config.json`-(macOS) or the platform equivalent. Add a `pulse` entry under-`mcpServers`:+#### OpenCode++Uses OpenCode's top-level mcp object.+Add this to `opencode.json`, `opencode.jsonc`, and `~/.config/opencode/opencode.json`:```json{- "mcpServers": {+ "$schema": "https://opencode.ai/config.json",+ "mcp": {"pulse": {- "command": "/usr/local/bin/pulse-mcp",- "args": ["--base-url", "http://localhost:7655"],- "env": {+ "type": "local",+ "command": ["pulse-mcp", "--base-url", "http://localhost:7655"],+ "enabled": true,+ "environment": {"PULSE_API_TOKEN": "your-token-here"}}@@ -104,11 +146,12 @@ Edit `~/Library/Application Support/Claude/claude_desktop_config.json`}```-Restart Claude Desktop. The Pulse tools appear in the tool picker.+Restart OpenCode or reload its config after saving. Pulse tools appear under the `pulse` MCP server name.-#### Claude Code+#### Claude-style clients-Add the server to your project's `.mcp.json` (or your user-level config):+Uses the common mcpServers object supported by Claude Desktop and Claude Code.+Use this shape for `Claude Desktop` and `Claude Code` in `~/Library/Application Support/Claude/claude_desktop_config.json` and `.mcp.json`:```json{@@ -124,6 +167,14 @@ Add the server to your project's `.mcp.json` (or your user-level config):}```+Restart your client after saving the config. If the client cannot resolve `pulse-mcp` from `PATH`, use the full binary path.++#### custom MCP clients++Keeps the Pulse MCP command, base URL flag, and token environment variable while adapting the outer client config shape.+Use command `pulse-mcp`, pass `--base-url http://localhost:7655`, set `PULSE_API_TOKEN` to the API token, and keep the server name `pulse` when the client asks for one.+<!-- pulse-mcp-client-config:end -->+## Configuration| Flag | Default | Purpose |@@ -161,71 +212,88 @@ flag off and consume the SSE stream directly.When `--emit-notifications` is on, the `initialize` responseadvertises the supported event kinds under-`capabilities.experimental.pulseNotifications.kinds`. Clients that-don't understand the experimental block ignore it silently.+`capabilities.experimental.pulseNotifications.kinds`. That list is+projected from the shared Pulse Intelligence event vocabulary, so it+stays aligned with `/api/agent/events`. Clients that don't understand+the experimental block ignore it silently.## What the tools do-The exact set is whatever your Pulse instance's manifest declares. As of-this writing, the published capabilities are:+The exact request/response tool set is whatever your Pulse instance's+manifest declares. The generated inventory below reflects the canonical+manifest in this checkout; run `tools/list` from your MCP client to see+the live set.+<!-- pulse-mcp-tools:start -->**Context (read-only):**-- `get_resource_context` returns the situated picture of one resource:- identity, operator-set state, active findings, pending approvals,- recent actions including refused dispatches with their stable error- tokens.-- `get_fleet_context` returns a thin per-resource rollup across the org- for triage: identity, operator flags, per-severity finding counts,- pending-approval count.+- `get_resource_context` (Get resource context, `GET /api/agent/resource-context/{resourceId}`, scope `monitoring:read`, mode `read`, approval `scope_only`): Return the situated picture of a resource — identity, operator-set state with maintenance-window-active flag, active findings, pending approvals scoped to this resource, recent actions including refused dispatches. Command fields are redacted for monitoring-read API tokens unless the token also has ai:execute.+- `get_fleet_context` (Get fleet context, `GET /api/agent/fleet-context`, scope `monitoring:read`, mode `read`, approval `scope_only`): Return a thin per-resource triage rollup across every resource visible to the org — identity, operator flags (intentionallyOffline, neverAutoRemediate, maintenanceWindowActive), per-severity finding counts (total/critical/warning/info), and pending-approval count. One read for 'where do I focus?'; follow up via get_resource_context for depth.+- `get_operations_loop_status` (Get Patrol work status, `GET /api/agent/operations-loop/status`, scope `monitoring:read`, mode `read`, approval `scope_only`): Return the current content-safe Patrol work status: Patrol issue evidence, pending approvals, governed decisions/actions, verified outcomes, Patrol control outcome evidence, compatibility aliases, and optional MCP readiness. The payload is count-only and deliberately omits finding ids, action ids, prompts, commands, resource names, and output.**Operator state (per-resource intent):**-- `get_operator_state` reads the operator-set state for a resource- (intentionally offline, never-auto-remediate, maintenance window,- criticality).-- `set_operator_state` replaces the entire record. The server populates- attribution (`setAt`, `setBy`) so client values cannot spoof it.-- `clear_operator_state` removes the entry. Idempotent.+- `get_operator_state` (Get operator state, `GET /api/resources/{resourceId}/operator-state`, scope `monitoring:read`, mode `read`, approval `scope_only`): Read the operator-set state for a resource (intentionally offline, never auto-remediate, maintenance window, criticality).+- `set_operator_state` (Set operator state, `PUT /api/resources/{resourceId}/operator-state`, scope `monitoring:write`, mode `write`, approval `scope_only`): Replace the operator-set state for a resource. URL canonicalId wins over body; server populates setAt and setBy from the authenticated identity.+- `clear_operator_state` (Clear operator state, `DELETE /api/resources/{resourceId}/operator-state`, scope `monitoring:write`, mode `write`, approval `scope_only`): Remove any operator-set state for a resource. Idempotent — succeeds whether or not an entry was present.**Findings (Patrol lifecycle):**-- `list_findings` returns every Patrol finding (active, dismissed,- resolved). Filter client-side.-- `acknowledge_finding` marks a finding as seen but keeps it visible.-- `snooze_finding` hides a finding for a duration in hours.-- `dismiss_finding` permanently dismisses a finding with a reason- (`not_an_issue`, `expected_behavior`, `will_fix_later`).-- `resolve_finding` manually marks a finding resolved.+- `list_findings` (List findings, `GET /api/ai/patrol/findings`, scope `ai:execute`, mode `read`, approval `scope_only`): List all Patrol findings (active, dismissed, resolved). Filter client-side on returned shape.+- `acknowledge_finding` (Acknowledge finding, `POST /api/ai/patrol/acknowledge`, scope `ai:execute`, mode `write`, approval `scope_only`): Mark a finding as seen but keep it visible. Auto-resolves when the underlying condition clears.+- `snooze_finding` (Snooze finding, `POST /api/ai/patrol/snooze`, scope `ai:execute`, mode `write`, approval `scope_only`): Hide a finding for a defined duration in hours.+- `dismiss_finding` (Dismiss finding, `POST /api/ai/patrol/dismiss`, scope `ai:execute`, mode `write`, approval `scope_only`): Dismiss a finding with a reason: not_an_issue (permanent suppression), expected_behavior (acknowledged forever), or will_fix_later (7-day reminder commitment).+- `resolve_finding` (Resolve finding, `POST /api/ai/patrol/resolve`, scope `ai:execute`, mode `write`, approval `scope_only`): Manually mark a finding as resolved when the underlying issue has been fixed out-of-band.**Actions (governed plan/approval/execute):**-- `plan_action` validates an action request, records the plan, and- returns approval policy, blast radius, plan hash, and preflight- summary.-- `decide_action` records an approval or rejection for a planned- action.-- `execute_action` executes a previously planned and approved action- and returns the persisted audit result.+- `plan_action` (Plan action, `POST /api/actions/plan`, scope `ai:execute`, mode `write`, approval `action_plan`): Plan an action against a resource. The planner validates the request, looks up the capability on the resource, checks executor-owned live availability, and returns an ActionPlan with the approval policy, blast radius, plan hash, and preflight summary. The plan is persisted to the audit history at the planned/pending state only after the live availability check passes, so subsequent decide_action and execute_action calls can reference it by id. Plan-and-execute is a two-step flow when the resulting plan requires approval, one-step otherwise.+- `decide_action` (Decide action, `POST /api/actions/{actionId}/decision`, scope `ai:execute`, mode `write`, approval `action_plan`): Record an approval decision (approved or rejected) on a previously planned action. The actor is taken from the authenticated identity; an explicit reason can be passed in the body. Idempotent on the persisted decision: re-deciding a non-pending action surfaces the action_not_pending stable code so agents can branch on the conflict rather than retrying blindly.+- `execute_action` (Execute action, `POST /api/actions/{actionId}/execute`, scope `ai:execute`, mode `write`, approval `action_plan`): Execute a previously planned and (when required) approved action. Returns the persisted audit record with the execution result attached. Refuses with stable codes when the action is in the wrong lifecycle state (action_not_approved, action_already_executing, action_execution_final, action_dry_run_only, action_plan_expired), when the approved plan no longer matches the current resource/capability contract (action_plan_drift), when the target is operator-locked against automated remediation (resource_remediation_locked), or when the API instance has no executor wired (action_executor_unavailable). action.completed SSE events fire on every terminal state so agents watching the stream do not need to poll this endpoint after dispatch.**Provisioning (infrastructure onboarding):**-- `discover_lan` scans a subnet, or returns cached scan results, to- find candidate infrastructure hosts before import.-- `list_nodes` returns configured Pulse infrastructure sources with- credential secret values redacted.-- `add_node` adds a Proxmox VE, Proxmox Backup Server, or Proxmox Mail- Gateway source.-- `update_node` updates a configured source without changing omitted- fields.-- `remove_node` removes a configured source.-- `test_node_credentials` validates proposed source credentials without- saving them.-- `test_node_connection` validates a saved source by id.-- `refresh_node_cluster_membership` re-detects Proxmox VE cluster- endpoint metadata for an existing source.--Run `tools/list` from your MCP client to see the live set.+- `list_nodes` (List nodes, `GET /api/config/nodes`, scope `settings:read`, mode `read`, approval `scope_only`): List configured infrastructure sources that Pulse can monitor or manage. Credential secret values are redacted; use the returned id with update_node, remove_node, test_node_connection, or refresh_node_cluster_membership.+- `add_node` (Add node, `POST /api/config/nodes`, scope `settings:write`, mode `write`, approval `scope_only`): Add a Proxmox VE, Proxmox Backup Server, or Proxmox Mail Gateway source to Pulse after credentials have been collected, generated, or approved.+- `update_node` (Update node, `PUT /api/config/nodes/{nodeId}`, scope `settings:write`, mode `write`, approval `scope_only`): Update a configured infrastructure source. Omitted fields preserve the current value; tokenValue or password only changes when supplied.+- `remove_node` (Remove node, `DELETE /api/config/nodes/{nodeId}`, scope `settings:write`, mode `write`, approval `scope_only`): Remove a configured infrastructure source from Pulse by node id.+- `test_node_credentials` (Test node credentials, `POST /api/config/nodes/test-config`, scope `settings:write`, mode `mixed`, approval `scope_only`): Validate proposed source credentials and connection details without saving them to Pulse.+- `test_node_connection` (Test node connection, `POST /api/config/nodes/{nodeId}/test`, scope `settings:write`, mode `mixed`, approval `scope_only`): Validate the saved connection for an existing configured infrastructure source.+- `refresh_node_cluster_membership` (Refresh node cluster membership, `POST /api/config/nodes/{nodeId}/refresh-cluster`, scope `settings:write`, mode `write`, approval `scope_only`): Re-detect Proxmox VE cluster membership and endpoint metadata for a configured source.+- `discover_lan` (Discover LAN, `POST /api/discover`, scope `settings:write`, mode `mixed`, approval `scope_only`): Scan a subnet, or return cached scan results, to find candidate infrastructure hosts before deciding which sources to add to Pulse.+<!-- pulse-mcp-tools:end -->++## Workflow prompts++Clients that support MCP prompts can also discover Pulse workflow hints.+They are projected from the manifest-owned `workflowPrompts` catalogue:++<!-- pulse-mcp-prompts:start -->+- `pulse_triage_fleet` (Triage fleet): Triage the Pulse fleet using the canonical fleet context capability, then choose where deeper investigation is warranted.+- `pulse_operations_loop` (Ask Patrol to handle an issue): Have Patrol investigate active findings, follow the configured Patrol mode, take approved actions, verify the outcome, and record what happened.+- `pulse_investigate_resource` (Investigate resource; required argument `resourceId`): Investigate one Pulse resource using the canonical resource context capability and resource URI projection.+- `pulse_review_finding` (Review finding; required argument `finding_id`): Review one Patrol finding and propose the safest governed next step.+<!-- pulse-mcp-prompts:end -->++Run `prompts/list` from your MCP client to see the live prompt set.++## Resource browser++Clients that support MCP resources can call `resources/list` to browse+the same canonical resource IDs returned by `get_fleet_context`, then+`resources/read` to fetch the full `get_resource_context` JSON bundle+for one resource.++Example URI:++```text+pulse://resource/vm:101+```++The adapter does not maintain a separate resource registry. The resource+list is rebuilt through the live fleet-context capability, and each read+is a normal per-resource context capability call with the same auth scope,+redaction rules, and error envelope as the tool surface.## Stable error envelope@@ -239,13 +307,24 @@ The MCP tool result wraps that JSON in a text content block with`isError: true`. Branch on `error` (snake_case stable codes); use`message` for surfacing to humans, never for branching.-Capability-specific codes the substrate currently emits include-`resource_not_found` (depth read on an unknown id),-`operator_state_not_set` (read on a resource with no operator entry), and-`operator_state_invalid` (write rejected by the validator). Cross-cutting-codes from the auth / multi-tenant middleware (`invalid_org`,-`org_suspended`, `access_denied`) can apply to any authenticated tool-call.+Capability-specific stable codes are advertised by the manifest:++<!-- pulse-mcp-errors:start -->+- `get_resource_context`: `resource_not_found`+- `get_operator_state`: `operator_state_not_set`+- `set_operator_state`: `operator_state_invalid`+- `acknowledge_finding`: `invalid_finding_request`, `finding_not_found`, `finding_action_not_allowed`, and `patrol_unavailable`+- `snooze_finding`: `invalid_finding_request`, `finding_not_found`, `finding_action_not_allowed`, and `patrol_unavailable`+- `dismiss_finding`: `invalid_finding_request`, `finding_not_found`, `finding_action_not_allowed`, and `patrol_unavailable`+- `resolve_finding`: `invalid_finding_request`, `finding_not_found`, `finding_action_not_allowed`, and `patrol_unavailable`+- `plan_action`: `invalid_action_request`, `resource_not_found`, `capability_not_found`, and `action_execution_unavailable`+- `decide_action`: `missing_id`, `invalid_id`, `invalid_action_decision`, `action_not_found`, `action_not_pending`, and `action_plan_expired`+- `execute_action`: `missing_id`, `invalid_id`, `invalid_action_execution`, `action_not_found`, `action_not_approved`, `action_already_executing`, `action_execution_final`, `action_dry_run_only`, `action_plan_expired`, `action_plan_drift`, `resource_remediation_locked`, and `action_executor_unavailable`+<!-- pulse-mcp-errors:end -->++Cross-cutting codes from the auth / multi-tenant middleware+(`invalid_org`, `org_suspended`, `access_denied`) can apply to any+authenticated tool call.## Known limitations@@ -263,10 +342,6 @@ call.lifetime. Restart `pulse-mcp` to pick up new capabilities afterupgrading Pulse.-- **No resource URIs.** MCP supports a `resources/` channel in addition- to `tools/`. The adapter exposes only tools today; this is sufficient- for the substrate's current surface and keeps the adapter small.-## Troubleshooting**"env var PULSE_API_TOKEN is empty" on startup.**@@ -281,9 +356,13 @@ the proxy is gating the manifest endpoint. Make sure`/api/agent/capabilities` is reachable without a credential, the sameway `/api/health` is.-**Tools work, but `set_operator_state` returns 403 access_denied.**-Your token is missing `monitoring:write`. Either mint a new token with-both scopes, or restrict yourself to the read tools.+**Tools work, but a write or action tool returns 403 access_denied.**+Your token is missing that tool's required scope. Run `tools/list` and+check the `required scope` line in the tool description. Operator-state+writes need `monitoring:write`, provisioning tools need `settings:read`+or `settings:write`, and Patrol finding plus governed action tools need+`ai:execute`. Mint a narrower or broader token depending on which+external-agent workflows you want to allow.**Tools list is empty.**The adapter filters `subscribe_events` out (it is not request/response@@ -293,16 +372,20 @@ manifest is empty, which is a Pulse-side bug; check## Implementation notes-The adapter is one stdlib-only Go file (`main.go`) in around 430 lines.-It speaks JSON-RPC 2.0 over stdio with line-delimited framing, logs to-stderr to keep the JSON-RPC channel on stdout clean, and derives each-tool's input schema from the manifest entry: `{name}` segments in the-declared path become required string properties, and non-GET/DELETE-tools accept a free-form `body` object.+The adapter binary is intentionally thin. It speaks JSON-RPC 2.0 over+stdio with line-delimited framing, logs to stderr to keep the JSON-RPC+channel on stdout clean, and delegates method semantics, tool projection,+call-argument normalization, HTTP projection, and result envelopes to the+shared Pulse Intelligence contracts in `internal/agentcapabilities`.+Tool input schemas come from the manifest-owned JSON Schema when present;+the shared projection only falls back to deriving path placeholders and a+permissive body object for capabilities that have not yet authored a+stricter schema.The companion worked example, `cmd/agent-probe`, walks the samesubstrate as a plain HTTP client and is a useful reference for anyonebuilding a non-MCP integration. Together the two binaries demonstrate-the substrate's two consumer profiles: stdio MCP and HTTP API. Both are-manifest-driven and stdlib-only, so adding capabilities to Pulse extends-both without code changes here.+Pulse Intelligence's external-agent profiles: stdio MCP and direct HTTP+API. Pulse Assistant remains the first-party in-app surface over the+same governed contracts; `pulse-mcp` is the adapter for users who prefer+an external agent host.diff --git a/cmd/pulse-mcp/main.go b/cmd/pulse-mcp/main.goindex 7e5d1097a4..36bf0a1ac5 100644--- a/cmd/pulse-mcp/main.go+++ b/cmd/pulse-mcp/main.go@@ -1,11 +1,12 @@-// Command pulse-mcp is a minimal MCP (Model Context Protocol)-// adapter that wraps Pulse's agent surface for stdio-speaking-// clients like Claude Desktop and Claude Code. It is the-// translation layer the substrate was designed to make cheap:-// every MCP tool here is a one-line projection of an entry in-// Pulse's hand-authored capabilities manifest.+// Command pulse-mcp is the Model Context Protocol adapter for+// Pulse Intelligence. It exposes the same governed operations+// substrate that Pulse Assistant uses natively, but for+// stdio-speaking external agents like OpenCode, Claude Desktop,+// Claude Code, and other MCP clients. It is deliberately a thin+// translation layer: every MCP tool here is a one-line projection+// of an entry in Pulse's canonical capabilities manifest.//-// Usage (typical Claude Desktop config entry):+// Usage (common mcpServers-style config entry)://// {// "mcpServers": {@@ -24,39 +25,46 @@//// 1. Fetches /api/agent/capabilities from the configured Pulse// instance at startup. The manifest is the single source of-// truth — adding a capability there automatically extends the-// MCP tool surface here, no MCP-side changes required.+// truth — adding a request/response capability to the Pulse MCP+// surface tool contract automatically extends the MCP tool+// surface here, no MCP-side changes required.//// 2. Translates each capability into an MCP tool with:// - tool name = capability name (snake_case agent identifier)-// - description = capability description-// - inputSchema = derived from path placeholders + body shape:-// {resourceId} segments become required string properties;-// non-GET tools accept a free-form `body` object.+// - description = capability description plus manifest metadata+// (route, scope, action mode, approval policy, shapes, errors)+// - inputSchema = the manifest-owned JSON Schema when declared,+// with a path/body fallback for capabilities that have not yet+// authored a stricter schema.//-// 3. Handles the MCP JSON-RPC methods Claude actually calls:-// initialize, tools/list, tools/call. Each tools/call+// 3. Handles the MCP JSON-RPC methods agents actually call:+// initialize, tools/list, tools/call, resources/list,+// resources/read, prompts/list, and prompts/get. Each tools/call// resolves the manifest entry by name, substitutes path// params, makes the HTTP request to Pulse with the configured// token, and returns the JSON response (or stable error// envelope) as a text content block.//-// What it does not do (yet):+// What stays out of the request/response tool projection://-// - subscribe_events. SSE streaming doesn't fit the MCP tool-// shape; it would be an MCP "notification" or a long-running-// tool. Future slices can layer this on; agents that need-// real-time push consume the SSE stream directly.+// - subscribe_events as a callable tool. SSE streaming doesn't+// fit the MCP request/response shape, so --emit-notifications+// bridges it into JSON-RPC notifications when an agent needs+// real-time push.//-// - Resource URIs. MCP supports `resources/list`/`resources/read`-// in addition to tools, but for Pulse the tool-only model is-// sufficient and keeps the adapter small. A future slice can-// project resource-context bundles as MCP resources if the-// UX value is clear.+// MCP resources are also manifest-backed: resources/list uses the+// canonical fleet context capability, and resources/read uses the+// canonical per-resource context capability. The resource URI shape+// and capability projection live in internal/agentcapabilities so+// this adapter does not grow a second inventory model.+//+// MCP prompts are manifest-backed workflow hints over that same+// tool/resource surface. The prompt catalog and prompt rendering live+// in internal/agentcapabilities so this adapter does not grow local+// operational playbooks.package mainimport (- "bufio""bytes""context""encoding/json"@@ -66,70 +74,26 @@ import ("log""net/http""os"- "regexp""strings""sync""time"-)--// agentCapability mirrors Pulse's manifest wire shape — defined-// inline so the adapter depends on nothing in the pulse module.-type agentCapability struct {- Name string `json:"name"`- Description string `json:"description"`- Category string `json:"category"`- Method string `json:"method"`- Path string `json:"path"`- Scope string `json:"scope"`- ResponseShape string `json:"responseShape,omitempty"`- ErrorCodes []string `json:"errorCodes,omitempty"`- RequestBodyShape string `json:"requestBodyShape,omitempty"`- InputSchema json.RawMessage `json:"inputSchema,omitempty"`-}--type agentCapabilitiesManifest struct {- Version string `json:"version"`- Capabilities []agentCapability `json:"capabilities"`-}--// jsonRPCRequest is the JSON-RPC 2.0 request envelope. Method is-// the MCP method name (e.g. "tools/list"); params is method--// specific. ID is null for notifications, otherwise echoed back on-// the response.-type jsonRPCRequest struct {- JSONRPC string `json:"jsonrpc"`- ID json.RawMessage `json:"id,omitempty"`- Method string `json:"method"`- Params json.RawMessage `json:"params,omitempty"`-}-type jsonRPCResponse struct {- JSONRPC string `json:"jsonrpc"`- ID json.RawMessage `json:"id,omitempty"`- Result any `json:"result,omitempty"`- Error *jsonRPCError `json:"error,omitempty"`-}+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+)-type jsonRPCError struct {- Code int `json:"code"`- Message string `json:"message"`- Data any `json:"data,omitempty"`-}+type agentCapability = agentcapabilities.Capability+type agentCapabilitiesManifest = agentcapabilities.Manifest-// MCP tool shape. inputSchema is JSON Schema (draft-07-ish) that-// the agent uses to validate before calling.-type mcpTool struct {- Name string `json:"name"`- Description string `json:"description"`- InputSchema json.RawMessage `json:"inputSchema"`-}+type jsonRPCRequest = agentcapabilities.JSONRPCRequest-// pathPlaceholderRE matches `{paramName}` in capability paths.-var pathPlaceholderRE = regexp.MustCompile(`\{([a-zA-Z][a-zA-Z0-9]*)\}`)+const (+ pulseMCPServerName = "pulse-mcp"+ pulseMCPServerVersion = "0.1.0"+)func main() {- baseURL := flag.String("base-url", "http://localhost:7655", "Pulse base URL")- tokenEnv := flag.String("token-env", "PULSE_API_TOKEN", "Env var holding the Pulse API token")+ baseURL := flag.String("base-url", agentcapabilities.DefaultMCPAdapterDefaultBaseURL, "Pulse base URL")+ tokenEnv := flag.String("token-env", agentcapabilities.DefaultMCPAdapterTokenEnv, "Env var holding the Pulse API token")emitNotifications := flag.Bool("emit-notifications", false, "Translate Pulse SSE events into JSON-RPC notifications on stdout. Off by default because not every MCP client surfaces server-initiated notifications; enable when wiring an autonomous agent that processes the JSON-RPC stream.")flag.Parse()@@ -137,17 +101,18 @@ func main() {log.SetPrefix("pulse-mcp ")log.SetFlags(log.LstdFlags | log.Lshortfile)- token := strings.TrimSpace(os.Getenv(*tokenEnv))- if token == "" {- log.Fatalf("env var %s is empty; pulse-mcp needs an API token with monitoring:read scope (and monitoring:write for set/clear operator-state)", *tokenEnv)- }-- manifest, err := fetchManifest(*baseURL)+ manifestClient := &http.Client{Timeout: 10 * time.Second}+ manifest, err := agentcapabilities.FetchManifest(context.Background(), manifestClient, *baseURL)if err != nil {log.Fatalf("could not fetch capabilities manifest from %s: %v", *baseURL, err)}log.Printf("fetched manifest %s with %d capabilities from %s", manifest.Version, len(manifest.Capabilities), *baseURL)+ token := strings.TrimSpace(os.Getenv(*tokenEnv))+ if token == "" {+ log.Fatal(missingAPITokenMessage(*tokenEnv, manifest))+ }+server := &mcpServer{baseURL: *baseURL,token: token,@@ -158,6 +123,14 @@ func main() {server.serve(os.Stdin, os.Stdout)}+func missingAPITokenMessage(tokenEnv string, manifest *agentCapabilitiesManifest) string {+ scopeList := agentcapabilities.ManifestRequiredScopeList(manifest)+ if scopeList == "" {+ return fmt.Sprintf("env var %s is empty; pulse-mcp needs an API token for the manifest tools you enable", tokenEnv)+ }+ return fmt.Sprintf("env var %s is empty; pulse-mcp needs an API token. Mint one with the manifest scopes for the tools you enable (current manifest scopes: %s)", tokenEnv, scopeList)+}+// mcpServer holds the per-process state: the configured Pulse base// URL and token, the manifest fetched at startup, and the HTTP// client used to call Pulse.@@ -165,7 +138,7 @@ type mcpServer struct {baseURL stringtoken stringmanifest *agentCapabilitiesManifest- http *http.Client+ http agentcapabilities.HTTPDoermu sync.Mutex // guards stdout writesemitNotifications bool// notificationsOnce ensures the SSE consumer goroutine starts@@ -180,49 +153,46 @@ type mcpServer struct {out io.Writer}+type pulseMCPAgentSurfaceHTTPDoer struct {+ next agentcapabilities.HTTPDoer+}++func (d pulseMCPAgentSurfaceHTTPDoer) Do(req *http.Request) (*http.Response, error) {+ if req != nil {+ req = req.Clone(req.Context())+ req.Header = req.Header.Clone()+ req.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseMCP)+ }+ next := d.next+ if next == nil {+ next = http.DefaultClient+ }+ return next.Do(req)+}+// serve is the stdio loop: read line-delimited JSON-RPC requests// from `in`, dispatch, write responses to `out`. Each request is on// its own line; blank lines are ignored; EOF stops the server.func (s *mcpServer) serve(in io.Reader, out io.Writer) {s.out = out- scanner := bufio.NewScanner(in)- scanner.Buffer(make([]byte, 64*1024), 1<<22) // up to 4 MB per message- for scanner.Scan() {- line := strings.TrimSpace(scanner.Text())- if line == "" {- continue- }- var req jsonRPCRequest- if err := json.Unmarshal([]byte(line), &req); err != nil {- s.writeJSON(out, jsonRPCResponse{- JSONRPC: "2.0",- Error: &jsonRPCError{- Code: -32700, // Parse error- Message: fmt.Sprintf("malformed JSON-RPC request: %v", err),- },- })- continue- }- resp := s.dispatch(context.Background(), &req)- // Notifications (id is null/absent) get no response.- if len(req.ID) == 0 || string(req.ID) == "null" {- continue- }- s.writeJSON(out, resp)- }- if err := scanner.Err(); err != nil && err != io.EOF {- log.Printf("stdio scanner: %v", err)+ if err := agentcapabilities.ServeJSONRPCLines(+ context.Background(),+ in,+ func(ctx context.Context, req agentcapabilities.JSONRPCRequest) agentcapabilities.JSONRPCResponse {+ return s.dispatch(ctx, &req)+ },+ func(resp agentcapabilities.JSONRPCResponse) error {+ return s.writeJSON(out, resp)+ },+ ); err != nil {+ log.Printf("stdio JSON-RPC: %v", err)}}-// dispatch routes one JSON-RPC request to the right handler. The-// MCP methods we support are minimal: initialize, tools/list,-// tools/call. Anything else gets method-not-found per JSON-RPC.-func (s *mcpServer) dispatch(ctx context.Context, req *jsonRPCRequest) jsonRPCResponse {- resp := jsonRPCResponse{JSONRPC: "2.0", ID: req.ID}- switch req.Method {- case "initialize":- resp.Result = s.handleInitialize()+// dispatch delegates MCP method semantics to the shared Pulse Intelligence+// boundary. This binary owns session policy and stdout serialization only.+func (s *mcpServer) dispatch(ctx context.Context, req *jsonRPCRequest) agentcapabilities.JSONRPCResponse {+ return agentcapabilities.DispatchMCPToolServerRequest(ctx, *req, s.manifestToolServer().Handlers(func() {// Start the SSE-to-notifications bridge once per process,// only if the operator opted in. Spawned after the// initialize response is queued so the client sees the@@ -232,265 +202,79 @@ func (s *mcpServer) dispatch(ctx context.Context, req *jsonRPCRequest) jsonRPCRego s.consumeSSEEvents(context.Background())})}- case "tools/list":- resp.Result = s.handleToolsList()- case "tools/call":- result, err := s.handleToolsCall(ctx, req.Params)- if err != nil {- resp.Error = &jsonRPCError{Code: -32603, Message: err.Error()}- } else {- resp.Result = result- }- case "ping":- resp.Result = map[string]any{}- default:- resp.Error = &jsonRPCError{- Code: -32601,- Message: fmt.Sprintf("method not found: %s", req.Method),- }- }- return resp+ }))}-// handleInitialize returns the MCP server's capabilities. Tools-// are the only request/response category we expose. When the-// operator opts in via --emit-notifications, the server also-// publishes server-initiated notifications translated from-// Pulse's SSE event stream; resources, prompts, and sampling-// remain intentionally unadvertised.-func (s *mcpServer) handleInitialize() any {- caps := map[string]any{- "tools": map[string]any{},- }- // MCP advertises notifications via experimental/extension- // keys today. We use a clearly-namespaced "experimental"- // block so clients that don't understand it ignore it- // silently rather than erroring on unknown keys.- if s.emitNotifications {- caps["experimental"] = map[string]any{- "pulseNotifications": map[string]any{- "kinds": []string{- "finding.created",- "approval.pending",- "action.completed",- },- },- }- }- return map[string]any{- "protocolVersion": "2024-11-05",- "capabilities": caps,- "serverInfo": map[string]any{- "name": "pulse-mcp",- "version": "0.1.0",- },+func (s *mcpServer) manifestToolServer() agentcapabilities.MCPManifestToolServer {+ var manifest agentcapabilities.Manifest+ if s.manifest != nil {+ manifest = *s.manifest+ }+ return agentcapabilities.MCPManifestToolServer{+ ServerName: pulseMCPServerName,+ ServerVersion: pulseMCPServerVersion,+ SurfaceID: agentcapabilities.SurfaceIDPulseMCP,+ EmitPulseNotifications: s.emitNotifications,+ Client: s.pulseMCPHTTPClient(),+ BaseURL: s.baseURL,+ Token: s.token,+ Manifest: manifest,+ RecordWorkflowPromptActivity: s.recordWorkflowPromptActivity,}}-// handleToolsList projects each manifest capability into an MCP-// tool. subscribe_events is filtered out — SSE streaming doesn't-// fit the request/response tool shape.-func (s *mcpServer) handleToolsList() any {- tools := make([]mcpTool, 0, len(s.manifest.Capabilities))- for _, cap := range s.manifest.Capabilities {- if cap.Name == "subscribe_events" {- continue- }- schema := buildInputSchema(cap)- tools = append(tools, mcpTool{- Name: cap.Name,- Description: cap.Description,- InputSchema: schema,- })+func (s *mcpServer) pulseMCPHTTPClient() agentcapabilities.HTTPDoer {+ if s == nil {+ return pulseMCPAgentSurfaceHTTPDoer{}}- return map[string]any{"tools": tools}+ return pulseMCPAgentSurfaceHTTPDoer{next: s.http}}-// handleToolsCall executes one tool invocation. params is shaped-// `{"name": "...", "arguments": {...}}`. The tool name resolves-// to a manifest capability; arguments fill path placeholders and-// (for non-GET tools) the request body.-func (s *mcpServer) handleToolsCall(ctx context.Context, raw json.RawMessage) (any, error) {- var params struct {- Name string `json:"name"`- Arguments map[string]any `json:"arguments"`- }- if err := json.Unmarshal(raw, ¶ms); err != nil {- return nil, fmt.Errorf("decode tools/call params: %w", err)- }- cap, ok := s.findCapability(params.Name)- if !ok {- return nil, fmt.Errorf("unknown tool: %s", params.Name)+func (s *mcpServer) recordWorkflowPromptActivity(ctx context.Context, promptName string) {+ promptName = strings.TrimSpace(promptName)+ if s == nil || promptName == "" || strings.TrimSpace(s.baseURL) == "" || strings.TrimSpace(s.token) == "" {+ return}+ ctx, cancel := context.WithTimeout(ctx, 2*time.Second)+ defer cancel()- url, err := substitutePathParams(cap.Path, params.Arguments)+ body, err := json.Marshal(map[string]string{"name": promptName})if err != nil {- return nil, fmt.Errorf("substitute path params: %w", err)- }-- var body io.Reader- if cap.Method != http.MethodGet && cap.Method != http.MethodDelete {- // Non-GET/DELETE tools accept a `body` argument that's- // JSON-encoded as the request body. If absent, we send an- // empty object — that's fine for the finding-action- // capabilities that just need `{ "finding_id": "..." }`.- bodyArg, ok := params.Arguments["body"]- if !ok {- // Some capabilities take their body fields at the top- // level (no nested "body" key). Treat the whole- // arguments object as the body, minus any consumed- // path-placeholder keys.- pathParams := pathParamSet(cap.Path)- cleaned := map[string]any{}- for k, v := range params.Arguments {- if !pathParams[k] {- cleaned[k] = v- }- }- bodyArg = cleaned- }- buf, err := json.Marshal(bodyArg)- if err != nil {- return nil, fmt.Errorf("marshal request body: %w", err)- }- body = bytes.NewReader(buf)+ log.Printf("workflow prompt activity: marshal: %v", err)+ return}-- httpReq, err := http.NewRequestWithContext(ctx, cap.Method, s.baseURL+url, body)+ req, err := agentcapabilities.NewAgentHTTPRequest(+ ctx,+ http.MethodPost,+ s.baseURL,+ agentcapabilities.AgentWorkflowPromptActivityPath,+ s.token,+ bytes.NewReader(body),+ )if err != nil {- return nil, fmt.Errorf("build request: %w", err)- }- httpReq.Header.Set("X-API-Token", s.token)- if body != nil {- httpReq.Header.Set("Content-Type", "application/json")+ log.Printf("workflow prompt activity: %v", err)+ return}-- resp, err := s.http.Do(httpReq)+ resp, err := s.pulseMCPHTTPClient().Do(req)if err != nil {- return nil, fmt.Errorf("call Pulse: %w", err)+ log.Printf("workflow prompt activity: %v", err)+ return}defer resp.Body.Close()- respBody, err := io.ReadAll(resp.Body)- if err != nil {- return nil, fmt.Errorf("read response: %w", err)- }-- // Build the MCP content result. The substrate's stable error- // envelope ({"error": "code", "message": "..."}) is preserved- // verbatim — agents on the MCP side branch on the same code- // they would branching on the HTTP response.- text := string(respBody)- isError := resp.StatusCode < 200 || resp.StatusCode >= 300- return map[string]any{- "content": []map[string]any{- {- "type": "text",- "text": text,- },- },- "isError": isError,- }, nil-}--func (s *mcpServer) findCapability(name string) (agentCapability, bool) {- for _, c := range s.manifest.Capabilities {- if c.Name == name {- return c, true- }+ _, _ = io.Copy(io.Discard, resp.Body)+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ log.Printf("workflow prompt activity: status %d", resp.StatusCode)}- return agentCapability{}, false}-func (s *mcpServer) writeJSON(out io.Writer, v any) {+func (s *mcpServer) writeJSON(out io.Writer, v any) error {s.mu.Lock()defer s.mu.Unlock()- enc := json.NewEncoder(out)- enc.SetEscapeHTML(false)- if err := enc.Encode(v); err != nil {+ if err := agentcapabilities.WriteJSONRPCMessage(out, v); err != nil {log.Printf("encode response: %v", err)+ return err}-}--// buildInputSchema generates a permissive JSON Schema for a-// capability. Path placeholders become required string properties;-// non-GET/DELETE capabilities also accept a free-form `body`-// object. The schema is permissive on purpose — the manifest is-// the source of truth for what the underlying endpoint accepts;-// MCP just needs enough shape so the agent knows which fields to-// pass.-func buildInputSchema(cap agentCapability) json.RawMessage {- if len(cap.InputSchema) > 0 {- return cap.InputSchema- }-- properties := map[string]any{}- required := []string{}- for _, m := range pathPlaceholderRE.FindAllStringSubmatch(cap.Path, -1) {- name := m[1]- properties[name] = map[string]any{- "type": "string",- "description": "Canonical " + name + " (e.g. \"vm:101\", \"container:web-1\")",- }- required = append(required, name)- }- if cap.Method != http.MethodGet && cap.Method != http.MethodDelete {- desc := "Request body fields"- if cap.RequestBodyShape != "" {- desc = "Request body fields. Shape hint: " + cap.RequestBodyShape- }- properties["body"] = map[string]any{- "type": "object",- "description": desc,- "additionalProperties": true,- }- }- schema := map[string]any{- "type": "object",- "properties": properties,- "additionalProperties": true,- }- if len(required) > 0 {- schema["required"] = required- }- out, _ := json.Marshal(schema)- return out-}--// substitutePathParams replaces `{name}` segments in a capability's-// path with the corresponding argument value. Missing args for-// declared placeholders are an error so the agent gets a stable-// failure rather than an HTTP 404 on a malformed URL.-func substitutePathParams(path string, args map[string]any) (string, error) {- var missing []string- out := pathPlaceholderRE.ReplaceAllStringFunc(path, func(match string) string {- name := match[1 : len(match)-1] // strip { and }- v, ok := args[name]- if !ok {- missing = append(missing, name)- return match- }- s, ok := v.(string)- if !ok {- missing = append(missing, name+" (not a string)")- return match- }- return s- })- if len(missing) > 0 {- return "", fmt.Errorf("missing path argument(s): %s", strings.Join(missing, ", "))- }- return out, nil-}--// pathParamSet returns the set of placeholder names declared in a-// path. Used to filter path args out of the request body when a-// caller passes everything at the top level.-func pathParamSet(path string) map[string]bool {- set := map[string]bool{}- for _, m := range pathPlaceholderRE.FindAllStringSubmatch(path, -1) {- set[m[1]] = true- }- return set+ return nil}// consumeSSEEvents opens a long-lived SSE connection to Pulse's@@ -507,10 +291,9 @@ func pathParamSet(path string) map[string]bool {// stays up across the kinds of stream stalls the MCP server's// idle-tolerance budget already accepts on the substrate side.func (s *mcpServer) consumeSSEEvents(ctx context.Context) {- url := s.baseURL + "/api/agent/events"backoff := time.Secondfor ctx.Err() == nil {- if err := s.streamSSEOnce(ctx, url); err != nil {+ if err := s.streamSSEOnce(ctx, agentcapabilities.AgentEventsPath); err != nil {if ctx.Err() != nil {return}@@ -532,95 +315,13 @@ func (s *mcpServer) consumeSSEEvents(ctx context.Context) {}// streamSSEOnce opens one SSE connection and reads events until-// the connection drops or the context is cancelled. Each parsed-// event becomes a JSON-RPC notification; the initial-// stream.connected event is skipped (it's a synchronization marker-// from the server, not an agent-actionable event).-func (s *mcpServer) streamSSEOnce(ctx context.Context, url string) error {- req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)- if err != nil {- return err- }- req.Header.Set("X-API-Token", s.token)- req.Header.Set("Accept", "text/event-stream")- // Bypass the s.http client's Timeout — the SSE stream is- // long-lived; ctx is the right cancellation signal.- resp, err := http.DefaultClient.Do(req)- if err != nil {- return err- }- defer resp.Body.Close()- if resp.StatusCode != http.StatusOK {- return fmt.Errorf("subscribe: status %d", resp.StatusCode)- }-- scanner := bufio.NewScanner(resp.Body)- scanner.Buffer(make([]byte, 64*1024), 1<<22)-- var event, data string- for scanner.Scan() {- line := scanner.Text()- switch {- case strings.HasPrefix(line, "event: "):- event = strings.TrimPrefix(line, "event: ")- case strings.HasPrefix(line, "data: "):- data = strings.TrimPrefix(line, "data: ")- case line == "":- s.maybeEmitNotification(event, data)- event, data = "", ""- }- }- if err := scanner.Err(); err != nil {- return err- }- return nil-}--// maybeEmitNotification turns a parsed SSE record into a JSON-RPC-// notification, filtering out keepalives and the connect marker-// that aren't agent-actionable. The notification's params is the-// raw JSON of the SSE data field, so the receiver gets the same-// payload the substrate publishes.-func (s *mcpServer) maybeEmitNotification(event, data string) {- if event == "" || data == "" {- return- }- // Skip events that are pure transport plumbing — agents- // branching on event kind don't care about these.- if event == "stream.connected" || event == "heartbeat" {- return- }- var params json.RawMessage = []byte(data)- notification := jsonRPCRequest{- JSONRPC: "2.0",- Method: "notifications/" + event,- Params: params,- }- s.writeJSON(s.out, notification)-}--// fetchManifest pulls the capabilities manifest from Pulse. This-// is the only call the adapter makes before its first tool-// invocation; the manifest is not cached or refreshed during the-// process lifetime — restart pulse-mcp to pick up new-// capabilities.-func fetchManifest(baseURL string) (*agentCapabilitiesManifest, error) {- req, err := http.NewRequest(http.MethodGet, baseURL+"/api/agent/capabilities", nil)- if err != nil {- return nil, err- }- client := &http.Client{Timeout: 10 * time.Second}- resp, err := client.Do(req)- if err != nil {- return nil, err- }- defer resp.Body.Close()- if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("manifest GET returned %d", resp.StatusCode)- }- var m agentCapabilitiesManifest- if err := json.NewDecoder(resp.Body).Decode(&m); err != nil {- return nil, fmt.Errorf("decode manifest: %w", err)- }- return &m, nil+// the connection drops or the context is cancelled. The shared+// Pulse Intelligence core owns SSE-to-MCP notification projection;+// the adapter only serializes projected notifications to stdout.+func (s *mcpServer) streamSSEOnce(ctx context.Context, path string) error {+ // Bypass the finite s.http timeout: the SSE stream is long-lived and ctx is+ // the right cancellation signal. The wrapper still marks the adapter surface.+ return agentcapabilities.StreamMCPEventNotifications(ctx, pulseMCPAgentSurfaceHTTPDoer{}, s.baseURL, path, s.token, func(notification agentcapabilities.JSONRPCRequest) error {+ return s.writeJSON(s.out, notification)+ })}diff --git a/cmd/pulse-mcp/main_test.go b/cmd/pulse-mcp/main_test.goindex ca86bb5608..c874568a21 100644--- a/cmd/pulse-mcp/main_test.go+++ b/cmd/pulse-mcp/main_test.go@@ -7,24 +7,182 @@ import ("io""net/http""net/http/httptest"+ "os""strings""sync""testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")-// TestBuildInputSchema_PathPlaceholdersBecomeRequiredStringProps+type httpDoerFunc func(*http.Request) (*http.Response, error)++func (f httpDoerFunc) Do(req *http.Request) (*http.Response, error) {+ return f(req)+}++func TestAgentCapabilityUsesSharedWireContract(t *testing.T) {+ rawSchema := json.RawMessage(`{"type":"object","additionalProperties":false}`)+ rawOutputSchema := json.RawMessage(`{"type":"object","properties":{"resources":{"type":"array"}}}`)+ capability := agentCapability{+ Name: "get_fleet_context",+ Method: http.MethodGet,+ Path: "/api/agent/fleet-context",+ ActionMode: agentcapabilities.ActionModeRead,+ InputSchema: rawSchema,+ OutputSchema: rawOutputSchema,+ }+ manifest := agentCapabilitiesManifest{+ Version: "v1",+ Capabilities: []agentcapabilities.Capability{capability},+ }+ var shared agentCapability = manifest.Capabilities[0]++ if shared.Name != capability.Name {+ t.Fatalf("shared manifest capability name = %q, want %q", shared.Name, capability.Name)+ }+ if shared.ActionMode != agentcapabilities.ActionModeRead {+ t.Fatalf("shared manifest action mode = %q, want %q", shared.ActionMode, agentcapabilities.ActionModeRead)+ }+ if string(shared.InputSchema) != string(rawSchema) {+ t.Fatalf("shared manifest input schema = %s, want %s", shared.InputSchema, rawSchema)+ }+ if string(shared.OutputSchema) != string(rawOutputSchema) {+ t.Fatalf("shared manifest output schema = %s, want %s", shared.OutputSchema, rawOutputSchema)+ }+}++func TestMissingAPITokenMessageUsesManifestScopeSummary(t *testing.T) {+ msg := missingAPITokenMessage("PULSE_API_TOKEN", &agentCapabilitiesManifest{+ RequiredScopes: []string{+ "settings:write",+ "monitoring:read",+ "ai:execute",+ "monitoring:read",+ },+ Capabilities: []agentCapability{+ {Name: "legacy_extra", Scope: "monitoring:write"},+ },+ })++ for _, want := range []string{+ "env var PULSE_API_TOKEN is empty",+ "current manifest scopes: monitoring:read, settings:write, ai:execute",+ } {+ if !strings.Contains(msg, want) {+ t.Fatalf("missing token message missing %q in %q", want, msg)+ }+ }+ if strings.Count(msg, "monitoring:read") != 1 {+ t.Fatalf("missing token message must deduplicate scopes; got %q", msg)+ }+}++func TestMissingAPITokenMessageFallsBackForLegacyManifest(t *testing.T) {+ msg := missingAPITokenMessage("PULSE_API_TOKEN", &agentCapabilitiesManifest{+ Capabilities: []agentCapability{+ {Name: "write_settings", Scope: "settings:write"},+ {Name: "read_monitoring", Scope: "monitoring:read"},+ },+ })++ if !strings.Contains(msg, "current manifest scopes: monitoring:read, settings:write") {+ t.Fatalf("missing token message should fall back to capability scopes for legacy manifests; got %q", msg)+ }+}++func TestMainTokenGuidanceUsesSharedManifestScopeSummary(t *testing.T) {+ source, err := os.ReadFile("main.go")+ if err != nil {+ t.Fatalf("read main.go: %v", err)+ }+ text := string(source)+ if !strings.Contains(text, "agentcapabilities.ManifestRequiredScopeList(manifest)") {+ t.Fatal("pulse-mcp token guidance must consume the manifest-owned requiredScopes summary")+ }+ if strings.Contains(text, "RequiredCapabilityScopeList(capabilities)") {+ t.Fatal("pulse-mcp token guidance must not recompute current manifest scopes from capability rows")+ }+ if strings.Contains(text, "monitoring:read scope (and monitoring:write") {+ t.Fatal("pulse-mcp must not hardcode partial token-scope guidance in startup errors")+ }+}++func TestMainUsesSharedMCPAdapterRuntimeDefaults(t *testing.T) {+ source, err := os.ReadFile("main.go")+ if err != nil {+ t.Fatalf("read main.go: %v", err)+ }+ text := string(source)+ for _, want := range []string{+ `flag.String("base-url", agentcapabilities.DefaultMCPAdapterDefaultBaseURL`,+ `flag.String("token-env", agentcapabilities.DefaultMCPAdapterTokenEnv`,+ } {+ if !strings.Contains(text, want) {+ t.Fatalf("pulse-mcp runtime defaults must come from the shared MCP adapter contract; missing %s", want)+ }+ }+}++func TestReadmePresentsSharedMCPClientConfig(t *testing.T) {+ source, err := os.ReadFile("README.md")+ if err != nil {+ t.Fatalf("read README.md: %v", err)+ }+ text := string(source)+ for _, want := range []string{+ agentcapabilities.MCPReadmeClientConfigStartMarker,+ agentcapabilities.MCPReadmeClientConfigEndMarker,+ "Most MCP clients need the same manifest-owned runtime facts",+ "server name `pulse`, command `pulse-mcp`, base URL flag `--base-url`",+ "currently declared config families: `OpenCode`, `Claude-style clients`, and `custom MCP clients`",+ "Uses OpenCode's top-level mcp object.",+ `"type": "local"`,+ `"command": ["pulse-mcp", "--base-url", "http://localhost:7655"]`,+ `"environment": {`,+ "Uses the common mcpServers object supported by Claude Desktop and Claude Code.",+ "Use command `pulse-mcp`, pass `--base-url http://localhost:7655`",+ "Restart your client after saving the config.",+ "Claude Desktop",+ "Claude Code",+ "OpenCode",+ } {+ if !strings.Contains(text, want) {+ t.Fatalf("README.md must include shared MCP client setup copy %q", want)+ }+ }+ if strings.Contains(text, "Restart Claude Desktop. The Pulse tools appear") {+ t.Fatal("README.md must not present Pulse MCP setup as Claude Desktop-only")+ }+ if strings.Contains(text, "The examples below use the common\n`mcpServers` shape") {+ t.Fatal("README.md must not present OpenCode as a generic mcpServers wrapper")+ }+}++func testPulseMCPSurfaceToolContracts(toolNames ...string) []agentcapabilities.SurfaceToolContract {+ return []agentcapabilities.SurfaceToolContract{+ {+ SurfaceID: agentcapabilities.SurfaceIDPulseMCP,+ ToolSource: agentcapabilities.SurfaceToolSourceCapabilityManifest,+ ToolNames: append([]string(nil), toolNames...),+ Affordances: agentcapabilities.DefaultSurfaceAffordancesForID(agentcapabilities.SurfaceIDPulseMCP),+ },+ }+}++// TestToolInputSchema_PathPlaceholdersBecomeRequiredStringProps// pins the rule that turns capability paths into MCP tool input// schemas: every {name} segment in the path becomes a required// string property the agent must supply, with a description that// hints at the canonical shape ("vm:101", "container:web-1") so// the LLM forms the right id without back-and-forth.-func TestBuildInputSchema_PathPlaceholdersBecomeRequiredStringProps(t *testing.T) {+func TestToolInputSchema_PathPlaceholdersBecomeRequiredStringProps(t *testing.T) {cap := agentCapability{Name: "get_resource_context",Path: "/api/agent/resource-context/{resourceId}",Method: http.MethodGet,}- raw := buildInputSchema(cap)+ raw := agentcapabilities.ToolInputSchema(cap)var schema map[string]anyif err := json.Unmarshal(raw, &schema); err != nil {t.Fatalf("unmarshal schema: %v", err)@@ -48,13 +206,13 @@ func TestBuildInputSchema_PathPlaceholdersBecomeRequiredStringProps(t *testing.T}}-// TestBuildInputSchema_NonGetCapabilitiesAcceptBody pins that+// TestToolInputSchema_NonGetCapabilitiesAcceptBody pins that// non-GET/DELETE tools expose a `body` property the agent fills// with the request payload. GET tools must NOT advertise a body// property so the agent doesn't try to send one (which would be// dropped by net/http anyway, but advertising it would be// misleading).-func TestBuildInputSchema_NonGetCapabilitiesAcceptBody(t *testing.T) {+func TestToolInputSchema_NonGetCapabilitiesAcceptBody(t *testing.T) {get := agentCapability{Path: "/api/foo", Method: http.MethodGet}post := agentCapability{Path: "/api/foo",@@ -74,7 +232,7 @@ func TestBuildInputSchema_NonGetCapabilitiesAcceptBody(t *testing.T) {"DELETE": {del, false},} {t.Run(name, func(t *testing.T) {- raw := buildInputSchema(tc.cap)+ raw := agentcapabilities.ToolInputSchema(tc.cap)var schema map[string]anyif err := json.Unmarshal(raw, &schema); err != nil {t.Fatalf("unmarshal schema: %v", err)@@ -88,7 +246,28 @@ func TestBuildInputSchema_NonGetCapabilitiesAcceptBody(t *testing.T) {}}-func TestBuildInputSchema_UsesManifestProvidedSchema(t *testing.T) {+func TestToolInputSchema_FallbackUsesSharedPermissiveEnvelope(t *testing.T) {+ raw := agentcapabilities.ToolInputSchema(agentCapability{+ Path: "/api/resources/{id}/operator-state",+ Method: http.MethodPut,+ })+ var schema map[string]any+ if err := json.Unmarshal(raw, &schema); err != nil {+ t.Fatalf("unmarshal schema: %v", err)+ }+ if schema["additionalProperties"] != true {+ t.Fatalf("fallback schema additionalProperties = %v, want true", schema["additionalProperties"])+ }+ props, _ := schema["properties"].(map[string]any)+ if _, hasID := props["id"]; !hasID {+ t.Fatalf("fallback schema must include path argument id: %v", props)+ }+ if _, hasBody := props["body"]; !hasBody {+ t.Fatalf("fallback schema must include body property for non-GET methods: %v", props)+ }+}++func TestToolInputSchema_UsesManifestProvidedSchema(t *testing.T) {rawSchema := json.RawMessage(`{"type": "object","properties": {@@ -105,7 +284,7 @@ func TestBuildInputSchema_UsesManifestProvidedSchema(t *testing.T) {InputSchema: rawSchema,}- got := buildInputSchema(cap)+ got := agentcapabilities.ToolInputSchema(cap)var schema map[string]anyif err := json.Unmarshal(got, &schema); err != nil {t.Fatalf("unmarshal schema: %v", err)@@ -118,25 +297,99 @@ func TestBuildInputSchema_UsesManifestProvidedSchema(t *testing.T) {}}-func TestSubstitutePathParams_FillsAllPlaceholders(t *testing.T) {- got, err := substitutePathParams(+func TestToolInputSchema_PreservesManifestActionArgumentSchema(t *testing.T) {+ rawSchema := json.RawMessage(`{+ "type": "object",+ "properties": {+ "actionId": { "type": "string", "pattern": "^[a-zA-Z0-9_-]+$" },+ "outcome": { "type": "string", "enum": ["approved", "rejected"] },+ "reason": { "type": "string" }+ },+ "required": ["actionId", "outcome"],+ "additionalProperties": false+ }`)+ cap := agentCapability{+ Name: "decide_action",+ Path: "/api/actions/{actionId}/decision",+ Method: http.MethodPost,+ InputSchema: rawSchema,+ }++ got := agentcapabilities.ToolInputSchema(cap)+ var schema map[string]any+ if err := json.Unmarshal(got, &schema); err != nil {+ t.Fatalf("unmarshal schema: %v", err)+ }+ props, _ := schema["properties"].(map[string]any)+ if _, hasActionID := props["actionId"]; !hasActionID {+ t.Fatalf("manifest-provided action schema must preserve path argument actionId: %s", string(got))+ }+ if _, hasBody := props["body"]; hasBody {+ t.Fatalf("manifest-provided action schema must not be replaced by generic body wrapper: %s", string(got))+ }++ operatorStateSchema := json.RawMessage(`{+ "type": "object",+ "properties": {+ "resourceId": { "type": "string" },+ "intentionallyOffline": { "type": "boolean" },+ "neverAutoRemediate": { "type": "boolean" }+ },+ "required": ["resourceId", "intentionallyOffline", "neverAutoRemediate"],+ "additionalProperties": false+ }`)+ operatorCap := agentCapability{+ Name: agentcapabilities.SetOperatorStateCapabilityName,+ Path: agentcapabilities.OperatorStateCapabilityPath,+ Method: http.MethodPut,+ InputSchema: operatorStateSchema,+ }++ got = agentcapabilities.ToolInputSchema(operatorCap)+ if err := json.Unmarshal(got, &schema); err != nil {+ t.Fatalf("unmarshal operator-state schema: %v", err)+ }+ props, _ = schema["properties"].(map[string]any)+ if _, hasResourceID := props["resourceId"]; !hasResourceID {+ t.Fatalf("manifest-provided operator-state schema must preserve resourceId path argument: %s", string(got))+ }+ if _, hasBody := props["body"]; hasBody {+ t.Fatalf("manifest-provided operator-state schema must not be replaced by generic body wrapper: %s", string(got))+ }+}++func TestSubstitutePathParameters_FillsAllPlaceholders(t *testing.T) {+ got, err := agentcapabilities.SubstitutePathParameters("/api/agent/resource-context/{resourceId}",map[string]any{"resourceId": "vm:101"},)if err != nil {t.Fatalf("unexpected error: %v", err)}- if got != "/api/agent/resource-context/vm:101" {- t.Errorf("got %q, want /api/agent/resource-context/vm:101", got)+ if got != "/api/agent/resource-context/vm%3A101" {+ t.Errorf("got %q, want /api/agent/resource-context/vm%%3A101", got)+ }+}++func TestSubstitutePathParameters_EscapesReservedCharacters(t *testing.T) {+ got, err := agentcapabilities.SubstitutePathParameters(+ "/api/config/nodes/{nodeId}/test",+ map[string]any{"nodeId": "pve/lab node"},+ )+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if got != "/api/config/nodes/pve%2Flab%20node/test" {+ t.Errorf("got %q, want escaped node id in a single path segment", got)}}-func TestSubstitutePathParams_MissingPlaceholderIsAStableError(t *testing.T) {+func TestSubstitutePathParameters_MissingPlaceholderIsAStableError(t *testing.T) {// The agent must get a clear error when it forgets a path// argument — better to fail with "missing path argument// resourceId" than to send a literal `{resourceId}` URL to// Pulse and get a confusing 404.- _, err := substitutePathParams(+ _, err := agentcapabilities.SubstitutePathParameters("/api/agent/resource-context/{resourceId}",map[string]any{},)@@ -148,8 +401,8 @@ func TestSubstitutePathParams_MissingPlaceholderIsAStableError(t *testing.T) {}}-func TestSubstitutePathParams_NonStringIsAnError(t *testing.T) {- _, err := substitutePathParams(+func TestSubstitutePathParameters_NonStringIsAnError(t *testing.T) {+ _, err := agentcapabilities.SubstitutePathParameters("/api/resources/{id}/operator-state",map[string]any{"id": 12345},)@@ -164,7 +417,8 @@ func TestSubstitutePathParams_NonStringIsAnError(t *testing.T) {// `tools` is present. The server must advertise tools so Claude// (Desktop / Code) bothers to enumerate the surface.func TestServer_DispatchInitializeReturnsToolsCapability(t *testing.T) {- s := &mcpServer{manifest: &agentCapabilitiesManifest{Version: "v1"}}+ manifest := agentcapabilities.CanonicalManifest()+ s := &mcpServer{manifest: &manifest}resp := s.dispatch(context.Background(), &jsonRPCRequest{JSONRPC: "2.0",ID: json.RawMessage(`1`),@@ -173,31 +427,355 @@ func TestServer_DispatchInitializeReturnsToolsCapability(t *testing.T) {if resp.Error != nil {t.Fatalf("initialize: error = %+v", resp.Error)}- result, _ := resp.Result.(map[string]any)- caps, _ := result["capabilities"].(map[string]any)- if _, ok := caps["tools"]; !ok {+ result, _ := resp.Result.(agentcapabilities.MCPInitializeResult)+ if result.Capabilities.Tools == nil {t.Fatal("initialize must advertise tools capability so MCP clients enumerate the tool surface")}- info, _ := result["serverInfo"].(map[string]any)- if info["name"] != "pulse-mcp" {- t.Errorf("serverInfo.name = %v, want pulse-mcp", info["name"])+ if !strings.Contains(result.Instructions, "governed infrastructure-operations surface") {+ t.Fatalf("initialize must include shared Pulse Intelligence operating instructions, got %q", result.Instructions)+ }+ if result.ServerInfo.Name != "pulse-mcp" {+ t.Errorf("serverInfo.name = %v, want pulse-mcp", result.ServerInfo.Name)+ }+ expected := agentcapabilities.NewMCPToolServerInitializeResult(pulseMCPServerName, pulseMCPServerVersion, false)+ if result.ProtocolVersion != expected.ProtocolVersion || result.ServerInfo != expected.ServerInfo {+ t.Fatalf("initialize result must use shared MCP constructor; got %+v want %+v", result, expected)+ }+}++func TestServer_ResourcesListAndReadProjectContextCapabilities(t *testing.T) {+ type captured struct {+ paths []string+ token string+ }+ var got captured+ mu := sync.Mutex{}+ pulse := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mu.Lock()+ defer mu.Unlock()+ got.paths = append(got.paths, r.URL.EscapedPath())+ got.token = r.Header.Get(agentcapabilities.AgentAPITokenHeader)++ w.Header().Set("Content-Type", "application/json")+ switch r.URL.EscapedPath() {+ case "/api/agent/fleet-context":+ _, _ = w.Write([]byte(`{+ "resources": [+ {+ "canonicalId": "vm:101",+ "resourceType": "virtual-machine",+ "resourceName": "Database VM",+ "technology": "proxmox",+ "pendingApprovalCount": 1,+ "findings": { "total": 2, "critical": 1, "warning": 1, "info": 0 }+ }+ ]+ }`))+ case "/api/agent/resource-context/vm%3A101":+ _, _ = w.Write([]byte(`{"canonicalId":"vm:101","resourceName":"Database VM"}`))+ default:+ http.NotFound(w, r)+ }+ }))+ defer pulse.Close()++ s := &mcpServer{+ baseURL: pulse.URL,+ token: "resource-test-token",+ manifest: &agentCapabilitiesManifest{+ Version: "v1",+ Capabilities: []agentCapability{+ {Name: agentcapabilities.FleetContextCapabilityName, Path: "/api/agent/fleet-context", Method: http.MethodGet, Description: "triage"},+ {Name: agentcapabilities.ResourceContextCapabilityName, Path: "/api/agent/resource-context/{resourceId}", Method: http.MethodGet, Description: "depth"},+ },+ },+ http: pulse.Client(),+ }++ init := s.dispatch(context.Background(), &jsonRPCRequest{+ JSONRPC: "2.0",+ ID: json.RawMessage(`1`),+ Method: agentcapabilities.MCPMethodInitialize,+ })+ if init.Error != nil {+ t.Fatalf("initialize: error = %+v", init.Error)+ }+ initResult, ok := init.Result.(agentcapabilities.MCPInitializeResult)+ if !ok {+ t.Fatalf("initialize result type = %T, want shared MCPInitializeResult", init.Result)+ }+ if initResult.Capabilities.Resources == nil {+ t.Fatalf("initialize must advertise resources when both context capabilities exist: %+v", initResult.Capabilities)+ }++ list := s.dispatch(context.Background(), &jsonRPCRequest{+ JSONRPC: "2.0",+ ID: json.RawMessage(`2`),+ Method: agentcapabilities.MCPMethodResourcesList,+ })+ if list.Error != nil {+ t.Fatalf("resources/list: error = %+v", list.Error)+ }+ listResult, ok := list.Result.(agentcapabilities.MCPListResourcesResult)+ if !ok {+ t.Fatalf("resources/list result type = %T, want shared MCPListResourcesResult", list.Result)+ }+ if len(listResult.Resources) != 1 {+ t.Fatalf("resources/list returned %+v, want one resource", listResult.Resources)+ }+ resource := listResult.Resources[0]+ if resource.URI != agentcapabilities.MCPResourceURI("vm:101") || resource.Name != "Database VM" || resource.MimeType != agentcapabilities.MCPResourceContextMIMEType {+ t.Fatalf("projected MCP resource = %+v", resource)+ }+ if !strings.Contains(resource.Description, "virtual-machine") || !strings.Contains(resource.Description, "pending approvals: 1") {+ t.Fatalf("projected resource description must carry fleet context summary; got %q", resource.Description)+ }++ params, _ := json.Marshal(agentcapabilities.MCPReadResourceParams{URI: resource.URI})+ read := s.dispatch(context.Background(), &jsonRPCRequest{+ JSONRPC: "2.0",+ ID: json.RawMessage(`3`),+ Method: agentcapabilities.MCPMethodResourcesRead,+ Params: params,+ })+ if read.Error != nil {+ t.Fatalf("resources/read: error = %+v", read.Error)+ }+ readResult, ok := read.Result.(agentcapabilities.MCPReadResourceResult)+ if !ok {+ t.Fatalf("resources/read result type = %T, want shared MCPReadResourceResult", read.Result)+ }+ if len(readResult.Contents) != 1 {+ t.Fatalf("resources/read contents = %+v, want one JSON content block", readResult.Contents)+ }+ content := readResult.Contents[0]+ if content.URI != resource.URI || content.MimeType != agentcapabilities.MCPResourceContextMIMEType {+ t.Fatalf("resources/read content = %+v", content)+ }+ if content.Text != `{"canonicalId":"vm:101","resourceName":"Database VM"}` {+ t.Fatalf("resources/read content text = %q", content.Text)+ }++ mu.Lock()+ defer mu.Unlock()+ if got.token != "resource-test-token" {+ t.Fatalf("upstream token = %q, want resource-test-token", got.token)+ }+ if strings.Join(got.paths, ",") != "/api/agent/fleet-context,/api/agent/resource-context/vm%3A101" {+ t.Fatalf("upstream paths = %+v", got.paths)}}-// TestServer_ToolsListProjectsManifestSkippingSubscribeEvents-// pins the auto-generation rule: tools/list must surface every-// manifest capability except subscribe_events (which is a stream,-// not a tool). Adding a capability to the manifest must-// automatically make it visible to MCP clients without changes-// here.-func TestServer_ToolsListProjectsManifestSkippingSubscribeEvents(t *testing.T) {+func TestServer_PromptsListAndGetProjectManifestWorkflowPrompts(t *testing.T) {+ s := &mcpServer{+ manifest: &agentCapabilitiesManifest{+ Version: "v1",+ Capabilities: []agentCapability{+ {Name: agentcapabilities.FleetContextCapabilityName, Path: "/api/agent/fleet-context", Method: http.MethodGet, Description: "triage"},+ {Name: agentcapabilities.ResourceContextCapabilityName, Path: "/api/agent/resource-context/{resourceId}", Method: http.MethodGet, Description: "depth"},+ {Name: "list_findings", Path: "/api/ai/patrol/findings", Method: http.MethodGet, Description: "findings"},+ },+ },+ }++ init := s.dispatch(context.Background(), &jsonRPCRequest{+ JSONRPC: "2.0",+ ID: json.RawMessage(`1`),+ Method: agentcapabilities.MCPMethodInitialize,+ })+ if init.Error != nil {+ t.Fatalf("initialize: error = %+v", init.Error)+ }+ initResult, ok := init.Result.(agentcapabilities.MCPInitializeResult)+ if !ok {+ t.Fatalf("initialize result type = %T, want shared MCPInitializeResult", init.Result)+ }+ if initResult.Capabilities.Prompts == nil {+ t.Fatalf("initialize must advertise prompts when workflow capabilities exist: %+v", initResult.Capabilities)+ }++ list := s.dispatch(context.Background(), &jsonRPCRequest{+ JSONRPC: "2.0",+ ID: json.RawMessage(`2`),+ Method: agentcapabilities.MCPMethodPromptsList,+ })+ if list.Error != nil {+ t.Fatalf("prompts/list: error = %+v", list.Error)+ }+ listResult, ok := list.Result.(agentcapabilities.MCPListPromptsResult)+ if !ok {+ t.Fatalf("prompts/list result type = %T, want shared MCPListPromptsResult", list.Result)+ }+ if len(listResult.Prompts) != 3 {+ t.Fatalf("prompts/list returned %+v, want three prompts", listResult.Prompts)+ }++ params, _ := json.Marshal(agentcapabilities.MCPGetPromptParams{+ Name: agentcapabilities.MCPPromptReviewFinding,+ Arguments: map[string]string{"finding_id": "finding-1"},+ })+ get := s.dispatch(context.Background(), &jsonRPCRequest{+ JSONRPC: "2.0",+ ID: json.RawMessage(`3`),+ Method: agentcapabilities.MCPMethodPromptsGet,+ Params: params,+ })+ if get.Error != nil {+ t.Fatalf("prompts/get: error = %+v", get.Error)+ }+ getResult, ok := get.Result.(agentcapabilities.MCPGetPromptResult)+ if !ok {+ t.Fatalf("prompts/get result type = %T, want shared MCPGetPromptResult", get.Result)+ }+ if len(getResult.Messages) != 1 || getResult.Messages[0].Role != "user" {+ t.Fatalf("prompts/get messages = %+v", getResult.Messages)+ }+ if !strings.Contains(getResult.Messages[0].Content.Text, `"finding-1"`) || !strings.Contains(getResult.Messages[0].Content.Text, "list_findings") {+ t.Fatalf("finding prompt text = %q", getResult.Messages[0].Content.Text)+ }+}++func TestServer_PromptsGetRecordsWorkflowPromptActivity(t *testing.T) {+ var got struct {+ path string+ token string+ surface string+ name string+ }+ client := httpDoerFunc(func(r *http.Request) (*http.Response, error) {+ got.path = r.URL.Path+ got.token = r.Header.Get(agentcapabilities.AgentAPITokenHeader)+ got.surface = r.Header.Get(agentcapabilities.AgentSurfaceHeader)+ var payload map[string]string+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {+ t.Fatalf("decode activity payload: %v", err)+ }+ got.name = payload["name"]+ return &http.Response{+ StatusCode: http.StatusNoContent,+ Header: make(http.Header),+ Body: io.NopCloser(strings.NewReader("")),+ Request: r,+ }, nil+ })++ s := &mcpServer{+ baseURL: "http://pulse.local",+ token: "test-token",+ http: client,+ manifest: &agentCapabilitiesManifest{+ Version: "v1",+ WorkflowPrompts: []agentcapabilities.PulseWorkflowPrompt{{+ Name: agentcapabilities.PulseWorkflowPromptOperationsLoop,+ Label: "Ask Patrol to handle an issue",+ Description: "Have Patrol investigate, follow policy, take approved actions, verify, and record the result.",+ }},+ },+ }+ params, _ := json.Marshal(agentcapabilities.MCPGetPromptParams{Name: agentcapabilities.MCPPromptOperationsLoop})+ resp := s.dispatch(context.Background(), &jsonRPCRequest{+ JSONRPC: "2.0",+ ID: json.RawMessage(`1`),+ Method: agentcapabilities.MCPMethodPromptsGet,+ Params: params,+ })+ if resp.Error != nil {+ t.Fatalf("prompts/get: error = %+v", resp.Error)+ }++ if got.path != agentcapabilities.AgentWorkflowPromptActivityPath {+ t.Fatalf("activity path = %q, want %q", got.path, agentcapabilities.AgentWorkflowPromptActivityPath)+ }+ if got.token != "test-token" {+ t.Fatalf("%s = %q, want test-token", agentcapabilities.AgentAPITokenHeader, got.token)+ }+ if got.surface != agentcapabilities.AgentSurfacePulseMCP {+ t.Fatalf("%s = %q, want %s", agentcapabilities.AgentSurfaceHeader, got.surface, agentcapabilities.AgentSurfacePulseMCP)+ }+ if got.name != agentcapabilities.PulseWorkflowPromptOperationsLoop {+ t.Fatalf("activity prompt name = %q, want %s", got.name, agentcapabilities.PulseWorkflowPromptOperationsLoop)+ }+}++func TestServerDispatchUsesSharedMCPDispatcher(t *testing.T) {+ src, err := os.ReadFile("main.go")+ if err != nil {+ t.Fatalf("read main.go: %v", err)+ }+ text := string(src)++ if !strings.Contains(text, "agentcapabilities.DispatchMCPToolServerRequest(") {+ t.Fatal("pulse-mcp dispatch must delegate MCP method semantics to agentcapabilities")+ }+ for _, required := range []string{+ "s.manifestToolServer().Handlers(func()",+ "agentcapabilities.MCPManifestToolServer{",+ "ServerName: pulseMCPServerName",+ "SurfaceID: agentcapabilities.SurfaceIDPulseMCP",+ "Manifest: manifest",+ } {+ if !strings.Contains(text, required) {+ t.Fatalf("pulse-mcp must project manifest-backed tool semantics through agentcapabilities; missing %s", required)+ }+ }+ for _, required := range []string{+ "agentcapabilities.ServeJSONRPCLines(",+ "agentcapabilities.WriteJSONRPCMessage(out, v)",+ "agentcapabilities.StreamMCPEventNotifications(",+ } {+ if !strings.Contains(text, required) {+ t.Fatalf("pulse-mcp must delegate JSON-RPC request handling to agentcapabilities; missing %s", required)+ }+ }+ for _, forbidden := range []string{+ "bufio.NewScanner(in)",+ "scanner.Scan()",+ "agentcapabilities.DecodeJSONRPCRequest(",+ "agentcapabilities.NewJSONRPCParseErrorResponse(",+ "agentcapabilities.JSONRPCRequestExpectsResponse(",+ "agentcapabilities.StreamAgentSSERecords(",+ "agentcapabilities.NewMCPEventNotification(",+ "func (s *mcpServer) maybeEmitNotification(",+ "json.Unmarshal([]byte(line)",+ "agentcapabilities.NewJSONRPCErrorResponse(\n\t\t\t\tnil",+ "agentcapabilities.JSONRPCErrorParse",+ "len(req.ID) == 0",+ "string(req.ID) == \"null\"",+ "switch req.Method",+ "type jsonRPCError = agentcapabilities.JSONRPCError",+ "agentcapabilities.MCPToolServerHandlers{",+ "agentcapabilities.NewJSONRPCResponse(req.ID, nil)",+ "agentcapabilities.JSONRPCErrorInternal",+ "agentcapabilities.JSONRPCErrorMethodNotFound",+ "func (s *mcpServer) handleInitialize(",+ "func (s *mcpServer) handleToolsList(",+ "func (s *mcpServer) handleToolsCall(",+ "agentcapabilities.NewMCPToolServerInitializeResult(pulseMCPServerName",+ "agentcapabilities.ProjectTools(s.manifest.Capabilities)",+ "agentcapabilities.ExecuteMCPToolHTTP(",+ "agentcapabilities.ExecuteMCPManifestSurfaceToolHTTP(ctx, s.http, s.baseURL, s.token, s.manifest",+ } {+ if strings.Contains(text, forbidden) {+ t.Fatalf("pulse-mcp must not own MCP method dispatch or error mapping; found %s", forbidden)+ }+ }+}++// TestServer_ToolsListProjectsPulseMCPSurfaceContract pins the auto-generation+// rule: tools/list must surface the manifest-owned Pulse MCP tool contract,+// not every raw manifest capability. Streaming capabilities and capabilities+// omitted from the Pulse MCP contract stay out of the request/response tool+// surface.+func TestServer_ToolsListProjectsPulseMCPSurfaceContract(t *testing.T) {s := &mcpServer{manifest: &agentCapabilitiesManifest{- Version: "v1",+ Version: "v1",+ SurfaceContract: agentcapabilities.CanonicalManifest().SurfaceContract,+ SurfaceToolContracts: testPulseMCPSurfaceToolContracts(agentcapabilities.ResourceContextCapabilityName, agentcapabilities.SetOperatorStateCapabilityName),Capabilities: []agentCapability{- {Name: "get_resource_context", Path: "/api/agent/resource-context/{resourceId}", Method: http.MethodGet, Description: "depth"},- {Name: "get_fleet_context", Path: "/api/agent/fleet-context", Method: http.MethodGet, Description: "triage"},- {Name: "subscribe_events", Path: "/api/agent/events", Method: http.MethodGet, Description: "stream"},- {Name: "set_operator_state", Path: "/api/resources/{resourceId}/operator-state", Method: http.MethodPut, Description: "write intent"},+ {Name: "get_resource_context", Title: "Inspect resource", Path: "/api/agent/resource-context/{resourceId}", Method: http.MethodGet, Description: "depth", ActionMode: agentcapabilities.ActionModeRead, OutputSchema: json.RawMessage(`{"type":"object","properties":{"canonicalId":{"type":"string"}}}`)},+ {Name: "get_fleet_context", Title: "Triage fleet", Path: "/api/agent/fleet-context", Method: http.MethodGet, Description: "triage", ActionMode: agentcapabilities.ActionModeRead},+ {Name: "subscribe_events", Title: "Subscribe events", Path: "/api/agent/events", Method: http.MethodGet, Description: "stream", ActionMode: agentcapabilities.ActionModeRead},+ {Name: agentcapabilities.SetOperatorStateCapabilityName, Title: "Set operator state", Path: agentcapabilities.OperatorStateCapabilityPath, Method: http.MethodPut, Scope: "monitoring:write", Description: "write intent", ActionMode: agentcapabilities.ActionModeWrite},},}}resp := s.dispatch(context.Background(), &jsonRPCRequest{@@ -208,19 +786,177 @@ func TestServer_ToolsListProjectsManifestSkippingSubscribeEvents(t *testing.T) {if resp.Error != nil {t.Fatalf("tools/list: error = %+v", resp.Error)}- result, _ := resp.Result.(map[string]any)- tools, _ := result["tools"].([]mcpTool)+ result, _ := resp.Result.(agentcapabilities.MCPProjectedToolsResult)+ tools := result.Tools+ if len(tools) != 2 {+ t.Fatalf("tools/list len = %d, want 2 Pulse MCP surface tools", len(tools))+ }names := map[string]bool{}+ titles := map[string]string{}+ descriptions := map[string]string{}+ outputSchemas := map[string]json.RawMessage{}+ annotations := map[string]*agentcapabilities.MCPToolAnnotations{}+ metadata := map[string]map[string]any{}for _, tool := range tools {names[tool.Name] = true+ titles[tool.Name] = tool.Title+ descriptions[tool.Name] = tool.Description+ outputSchemas[tool.Name] = tool.OutputSchema+ annotations[tool.Name] = tool.Annotations+ if meta, ok := tool.Meta[agentcapabilities.ToolMetaPulseCapabilityKey].(map[string]any); ok {+ metadata[tool.Name] = meta+ }}- for _, want := range []string{"get_resource_context", "get_fleet_context", "set_operator_state"} {+ for _, want := range []string{agentcapabilities.ResourceContextCapabilityName, agentcapabilities.SetOperatorStateCapabilityName} {if !names[want] {t.Errorf("tools/list missing %q", want)}}+ if names[agentcapabilities.FleetContextCapabilityName] {+ t.Errorf("%s must not be exposed when omitted from the Pulse MCP surface contract", agentcapabilities.FleetContextCapabilityName)+ }+ if !strings.Contains(descriptions[agentcapabilities.SetOperatorStateCapabilityName], "write intent") {+ t.Errorf("tools/list must preserve manifest description; got %q", descriptions[agentcapabilities.SetOperatorStateCapabilityName])+ }+ if titles[agentcapabilities.ResourceContextCapabilityName] != "Inspect resource" {+ t.Errorf("tools/list must project manifest title; got %q", titles[agentcapabilities.ResourceContextCapabilityName])+ }+ if !strings.Contains(string(outputSchemas[agentcapabilities.ResourceContextCapabilityName]), `"canonicalId"`) {+ t.Errorf("tools/list must project manifest outputSchema; got %s", string(outputSchemas[agentcapabilities.ResourceContextCapabilityName]))+ }+ if !strings.Contains(descriptions[agentcapabilities.SetOperatorStateCapabilityName], "required scope: ") {+ t.Errorf("tools/list must project manifest capability metadata; got %q", descriptions[agentcapabilities.SetOperatorStateCapabilityName])+ }+ setOperatorMeta := metadata[agentcapabilities.SetOperatorStateCapabilityName]+ if setOperatorMeta["scope"] != "monitoring:write" {+ t.Errorf("tools/list must project structured Pulse scope metadata; got %#v", setOperatorMeta)+ }+ route, _ := setOperatorMeta["route"].(map[string]any)+ if route["method"] != http.MethodPut || route["path"] != agentcapabilities.OperatorStateCapabilityPath {+ t.Errorf("tools/list must project structured Pulse route metadata; got %#v", route)+ }+ governance, _ := setOperatorMeta["governance"].(map[string]any)+ if governance["actionMode"] != string(agentcapabilities.ActionModeWrite) {+ t.Errorf("tools/list must project structured Pulse governance metadata; got %#v", governance)+ }+ assertMCPToolAnnotations(t, annotations[agentcapabilities.ResourceContextCapabilityName], true, false, true, true)+ assertMCPToolAnnotations(t, annotations[agentcapabilities.SetOperatorStateCapabilityName], false, true, false, true)if names["subscribe_events"] {- t.Error("subscribe_events must NOT be exposed as an MCP tool — SSE streams don't fit the request/response shape; future slices can layer notifications")+ t.Error("subscribe_events must NOT be exposed as an MCP tool — SSE streams don't fit the request/response shape")+ }+}++func assertMCPToolAnnotations(t *testing.T, annotations *agentcapabilities.MCPToolAnnotations, readOnly, destructive, idempotent, openWorld bool) {+ t.Helper()+ if annotations == nil {+ t.Fatal("tool annotations are nil")+ }+ assertMCPBoolRef(t, "readOnlyHint", annotations.ReadOnlyHint, readOnly)+ assertMCPBoolRef(t, "destructiveHint", annotations.DestructiveHint, destructive)+ assertMCPBoolRef(t, "idempotentHint", annotations.IdempotentHint, idempotent)+ assertMCPBoolRef(t, "openWorldHint", annotations.OpenWorldHint, openWorld)+}++func assertMCPBoolRef(t *testing.T, name string, got *bool, want bool) {+ t.Helper()+ if got == nil {+ t.Fatalf("%s is nil, want %v", name, want)+ }+ if *got != want {+ t.Fatalf("%s = %v, want %v", name, *got, want)+ }+}++func TestFormatToolDescriptionProjectsCapabilityMetadata(t *testing.T) {+ desc := agentcapabilities.ToolDescription(agentCapability{+ Name: "plan_action",+ Description: "Plan an action against a resource.",+ Category: "action",+ Method: http.MethodPost,+ Path: "/api/actions/plan",+ Scope: "ai:execute",+ ActionMode: "write",+ ApprovalPolicy: "action_plan",+ RequestBodyShape: "ActionRequest",+ ResponseShape: "ActionPlan",+ ErrorCodes: []string{"invalid_action_request", "resource_not_found"},+ })++ for _, want := range []string{+ "Plan an action against a resource.",+ "Pulse capability metadata:",+ "category: action",+ "route: POST /api/actions/plan",+ "required scope: ai:execute",+ "action mode: write",+ "approval policy: action_plan",+ "request body: ActionRequest",+ "response: ActionPlan",+ "stable error codes: invalid_action_request, resource_not_found",+ } {+ if !strings.Contains(desc, want) {+ t.Fatalf("ToolDescription missing %q in %q", want, desc)+ }+ }+}++func TestServer_ToolsCallRejectsUnknownManifestCapability(t *testing.T) {+ s := &mcpServer{manifest: &agentCapabilitiesManifest{+ Version: "v1",+ Capabilities: []agentCapability{+ {Name: "get_fleet_context", Path: "/api/agent/fleet-context", Method: http.MethodGet},+ },+ }}++ params, _ := json.Marshal(map[string]any{+ "name": "missing_capability",+ "arguments": map[string]any{},+ })+ resp := s.dispatch(context.Background(), &jsonRPCRequest{+ JSONRPC: "2.0",+ ID: json.RawMessage(`1`),+ Method: "tools/call",+ Params: params,+ })++ if resp.Error == nil {+ t.Fatal("unknown manifest capability must produce a JSON-RPC error")+ }+ if !strings.Contains(resp.Error.Message, "unknown tool: missing_capability") {+ t.Fatalf("unknown capability error = %q, want stable unknown tool message", resp.Error.Message)+ }+}++func TestServer_ToolsCallRejectsMalformedParamsWithSharedDecodeMessage(t *testing.T) {+ s := &mcpServer{manifest: &agentCapabilitiesManifest{Version: "v1"}}+ resp := s.dispatch(context.Background(), &jsonRPCRequest{+ JSONRPC: "2.0",+ ID: json.RawMessage(`1`),+ Method: "tools/call",+ Params: json.RawMessage(`{"name":`),+ })++ if resp.Error == nil {+ t.Fatal("malformed tools/call params must produce a JSON-RPC error")+ }+ if resp.Error.Code != agentcapabilities.JSONRPCErrorInternal {+ t.Fatalf("error code = %d, want JSONRPCErrorInternal", resp.Error.Code)+ }+ if !strings.Contains(resp.Error.Message, "decode tools/call params") {+ t.Fatalf("decode error = %q, want shared decode message", resp.Error.Message)+ }++ resp = s.dispatch(context.Background(), &jsonRPCRequest{+ JSONRPC: "2.0",+ ID: json.RawMessage(`2`),+ Method: "tools/call",+ Params: json.RawMessage(`{"name":" ","arguments":{}}`),+ })+ if resp.Error == nil {+ t.Fatal("invalid tools/call params must produce a JSON-RPC error")+ }+ if !strings.Contains(resp.Error.Message, "decode tools/call params: tool name is required") {+ t.Fatalf("invalid params error = %q, want shared validation message", resp.Error.Message)}}@@ -232,34 +968,41 @@ func TestServer_ToolsListProjectsManifestSkippingSubscribeEvents(t *testing.T) {// would on the wire.func TestServer_ToolsCallProxiesToPulseAndPreservesErrorEnvelope(t *testing.T) {type captured struct {- method string- path string- token string- body string+ method string+ path string+ token string+ surface string+ body string}var got capturedmu := sync.Mutex{}- pulse := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ const errorBody = `{"error":"resource_not_found","message":"No resource is registered with this canonical id."}`+ client := httpDoerFunc(func(r *http.Request) (*http.Response, error) {mu.Lock()defer mu.Unlock()got.method = r.Methodgot.path = r.URL.Pathgot.token = r.Header.Get("X-API-Token")+ got.surface = r.Header.Get(agentcapabilities.AgentSurfaceHeader)if r.Body != nil {b, _ := io.ReadAll(r.Body)got.body = string(b)}- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(http.StatusNotFound)- _, _ = w.Write([]byte(`{"error":"resource_not_found","message":"No resource is registered with this canonical id."}`))- }))- defer pulse.Close()+ return &http.Response{+ StatusCode: http.StatusNotFound,+ Header: http.Header{"Content-Type": []string{"application/json"}},+ Body: io.NopCloser(strings.NewReader(errorBody)),+ Request: r,+ }, nil+ })s := &mcpServer{- baseURL: pulse.URL,+ baseURL: "http://pulse.test",token: "test-token",manifest: &agentCapabilitiesManifest{- Version: "v1",+ Version: "v1",+ SurfaceContract: agentcapabilities.CanonicalManifest().SurfaceContract,+ SurfaceToolContracts: testPulseMCPSurfaceToolContracts(agentcapabilities.ResourceContextCapabilityName),Capabilities: []agentCapability{{Name: "get_resource_context",@@ -269,7 +1012,7 @@ func TestServer_ToolsCallProxiesToPulseAndPreservesErrorEnvelope(t *testing.T) {},},},- http: pulse.Client(),+ http: client,}params, _ := json.Marshal(map[string]any{@@ -295,17 +1038,34 @@ func TestServer_ToolsCallProxiesToPulseAndPreservesErrorEnvelope(t *testing.T) {if got.token != "test-token" {t.Errorf("upstream token header = %q, want test-token", got.token)}+ if got.surface != agentcapabilities.AgentSurfacePulseMCP {+ t.Errorf("upstream agent surface header = %q, want %q", got.surface, agentcapabilities.AgentSurfacePulseMCP)+ }- result, _ := resp.Result.(map[string]any)- if result["isError"] != true {- t.Errorf("non-2xx upstream must surface as MCP isError=true; got %v", result["isError"])+ result, ok := resp.Result.(agentcapabilities.MCPToolResult)+ if !ok {+ t.Fatalf("tools/call result type = %T, want shared MCPToolResult", resp.Result)+ }+ if !result.IsError {+ t.Errorf("non-2xx upstream must surface as MCP isError=true; got %v", result.IsError)+ }+ if len(result.Content) != 1 {+ t.Fatalf("content len = %d, want 1", len(result.Content))+ }+ expected := agentcapabilities.NewCapabilityHTTPToolResult(agentcapabilities.HTTPCallResponse{+ Method: http.MethodGet,+ Path: "/api/agent/resource-context/vm:does-not-exist",+ StatusCode: http.StatusNotFound,+ Body: []byte(errorBody),+ })+ if result.IsError != expected.IsError || result.Content[0].Text != expected.Content[0].Text {+ t.Fatalf("tools/call result must use shared HTTP-to-MCP result semantics; got %+v want %+v", result, expected)}- content, _ := result["content"].([]map[string]any)- if len(content) != 1 {- t.Fatalf("content len = %d, want 1", len(content))+ if result.StructuredContent["error"] != "resource_not_found" {+ t.Fatalf("tools/call structuredContent = %+v, want resource_not_found error", result.StructuredContent)}- if !strings.Contains(content[0]["text"].(string), `"error":"resource_not_found"`) {- t.Errorf("MCP content must preserve substrate error envelope verbatim; got %v", content[0]["text"])+ if !strings.Contains(result.Content[0].Text, `"error":"resource_not_found"`) {+ t.Errorf("MCP content must preserve substrate error envelope verbatim; got %v", result.Content[0].Text)}}@@ -349,30 +1109,31 @@ func TestServer_NotificationGetsNoResponse(t *testing.T) {func TestServer_InitializeAdvertisesNotificationsCapabilityWhenEnabled(t *testing.T) {t.Run("disabled by default", func(t *testing.T) {s := &mcpServer{manifest: &agentCapabilitiesManifest{}}- result := s.handleInitialize().(map[string]any)- caps := result["capabilities"].(map[string]any)- if _, ok := caps["experimental"]; ok {+ result := s.manifestToolServer().Initialize()+ if len(result.Capabilities.Experimental) > 0 {t.Error("initialize must NOT advertise pulseNotifications when --emit-notifications is off")}})t.Run("advertised when enabled", func(t *testing.T) {s := &mcpServer{manifest: &agentCapabilitiesManifest{}, emitNotifications: true}- result := s.handleInitialize().(map[string]any)- caps := result["capabilities"].(map[string]any)- exp, ok := caps["experimental"].(map[string]any)- if !ok {+ result := s.manifestToolServer().Initialize()+ exp := result.Capabilities.Experimental+ if len(exp) == 0 {t.Fatal("initialize must advertise experimental block when --emit-notifications is on")}- pn, ok := exp["pulseNotifications"].(map[string]any)+ pn, ok := exp[agentcapabilities.MCPPulseNotificationsExperimentalKey].(agentcapabilities.MCPPulseNotificationsCapability)if !ok {t.Fatal("experimental block must contain pulseNotifications descriptor")}- kinds, ok := pn["kinds"].([]string)- if !ok || len(kinds) == 0 {- t.Fatalf("pulseNotifications.kinds must list the SSE event kinds; got %v", pn["kinds"])+ kinds := pn.Kinds+ if len(kinds) == 0 {+ t.Fatalf("pulseNotifications.kinds must list the SSE event kinds; got %v", pn.Kinds)+ }+ want := map[string]bool{}+ for _, kind := range agentcapabilities.AgentActionableEventKinds() {+ want[kind] = false}- want := map[string]bool{"finding.created": false, "approval.pending": false, "action.completed": false}for _, k := range kinds {if _, exists := want[k]; exists {want[k] = true@@ -386,58 +1147,6 @@ func TestServer_InitializeAdvertisesNotificationsCapabilityWhenEnabled(t *testin})}-// TestServer_MaybeEmitNotificationFiltersTransportEvents pins that-// the bridge skips events that are pure transport plumbing-// (stream.connected, heartbeat). Forwarding those would surface-// noise an agent has no useful action on, and would teach-// downstream code to filter them client-side instead of trusting-// the substrate's "doorbell, not transport" intent.-func TestServer_MaybeEmitNotificationFiltersTransportEvents(t *testing.T) {- cases := []struct {- name string- event, data string- shouldEmit bool- methodPrefix string- }{- {"finding.created passes through", "finding.created", `{"findingId":"f1"}`, true, "notifications/finding.created"},- {"approval.pending passes through", "approval.pending", `{"approvalId":"a1"}`, true, "notifications/approval.pending"},- {"action.completed passes through", "action.completed", `{"actionId":"x1"}`, true, "notifications/action.completed"},- {"stream.connected is filtered", "stream.connected", `{}`, false, ""},- {"heartbeat is filtered", "heartbeat", "", false, ""},- {"empty event is filtered", "", `{"x":1}`, false, ""},- {"empty data is filtered", "finding.created", "", false, ""},- }- for _, tc := range cases {- t.Run(tc.name, func(t *testing.T) {- out := &bytes.Buffer{}- s := &mcpServer{out: out}- s.maybeEmitNotification(tc.event, tc.data)- if tc.shouldEmit {- if out.Len() == 0 {- t.Fatalf("expected notification on stdout for %q; got nothing", tc.event)- }- body := out.String()- if !strings.Contains(body, `"method":"`+tc.methodPrefix+`"`) {- t.Errorf("expected method %q; got %s", tc.methodPrefix, body)- }- if !strings.Contains(body, `"jsonrpc":"2.0"`) {- t.Errorf("notification must be JSON-RPC 2.0; got %s", body)- }- // Notifications must NOT carry an id field per- // JSON-RPC 2.0 spec — clients that see an id treat- // the message as a request and may try to respond.- if strings.Contains(body, `"id":`) {- t.Errorf("notification must omit the id field; got %s", body)- }- } else {- if out.Len() != 0 {- t.Errorf("expected silence for %q event; got %s", tc.event, out.String())- }- }- })- }-}-// TestServer_StreamSSEOnceTranslatesEventsToNotifications is the// integration test for the bridge: spin up a fake SSE server// emitting the substrate's wire format, point the consumer at it,@@ -445,24 +1154,31 @@ func TestServer_MaybeEmitNotificationFiltersTransportEvents(t *testing.T) {// notification on the configured out writer.func TestServer_StreamSSEOnceTranslatesEventsToNotifications(t *testing.T) {sseBody := strings.Join([]string{- "event: stream.connected",+ ": sync comment uses standard SSE comment framing",+ "event: " + string(agentcapabilities.EventKindStreamConnected),"data: {}","",- "event: finding.created",+ "event: " + string(agentcapabilities.EventKindFindingCreated),"data: {\"findingId\":\"f1\",\"severity\":\"critical\"}","",- "event: heartbeat",+ "event: " + string(agentcapabilities.EventKindHeartbeat),"",- "event: action.completed",+ "event: " + string(agentcapabilities.EventKindActionCompleted),"data: {\"actionId\":\"x1\",\"success\":true,\"verification\":{\"ran\":true,\"success\":true,\"commandRedacted\":true}}","",- }, "\n") + "\n"+ }, "\r\n") + "\r\n"pulse := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.Header.Get("X-API-Token") != "test-token" {+ if r.Header.Get(agentcapabilities.AgentAPITokenHeader) != "test-token" {w.WriteHeader(http.StatusUnauthorized)return}+ if r.Header.Get("Accept") != agentcapabilities.AgentSSEAccept {+ t.Errorf("Accept header = %q, want %q", r.Header.Get("Accept"), agentcapabilities.AgentSSEAccept)+ }+ if r.Header.Get(agentcapabilities.AgentSurfaceHeader) != agentcapabilities.AgentSurfacePulseMCP {+ t.Errorf("%s header = %q, want %q", agentcapabilities.AgentSurfaceHeader, r.Header.Get(agentcapabilities.AgentSurfaceHeader), agentcapabilities.AgentSurfacePulseMCP)+ }w.Header().Set("Content-Type", "text/event-stream")_, _ = w.Write([]byte(sseBody))}))@@ -475,7 +1191,7 @@ func TestServer_StreamSSEOnceTranslatesEventsToNotifications(t *testing.T) {http: pulse.Client(),out: out,}- if err := s.streamSSEOnce(context.Background(), pulse.URL+"/api/agent/events"); err != nil {+ if err := s.streamSSEOnce(context.Background(), agentcapabilities.AgentEventsPath); err != nil {t.Fatalf("streamSSEOnce: %v", err)}@@ -489,7 +1205,7 @@ func TestServer_StreamSSEOnceTranslatesEventsToNotifications(t *testing.T) {if !strings.Contains(body, `"verification":{"ran":true,"success":true,"commandRedacted":true}`) {t.Errorf("action.completed verification must round-trip through MCP notification params; got %s", body)}- if strings.Contains(body, "stream.connected") {+ if strings.Contains(body, string(agentcapabilities.EventKindStreamConnected)) {t.Errorf("stream.connected must be filtered out as transport plumbing; got %s", body)}if strings.Contains(body, `"method":"notifications/heartbeat"`) {@@ -546,11 +1262,13 @@ func TestServer_ToolsCallSendsPutBodyForWriteCapabilities(t *testing.T) {baseURL: pulse.URL,token: "write-test-token",manifest: &agentCapabilitiesManifest{- Version: "v1",+ Version: "v1",+ SurfaceContract: agentcapabilities.CanonicalManifest().SurfaceContract,+ SurfaceToolContracts: testPulseMCPSurfaceToolContracts(agentcapabilities.SetOperatorStateCapabilityName),Capabilities: []agentCapability{{- Name: "set_operator_state",- Path: "/api/resources/{resourceId}/operator-state",+ Name: agentcapabilities.SetOperatorStateCapabilityName,+ Path: agentcapabilities.OperatorStateCapabilityPath,Method: http.MethodPut,Scope: "monitoring:write",RequestBodyShape: "ResourceOperatorStateInput",@@ -562,7 +1280,7 @@ func TestServer_ToolsCallSendsPutBodyForWriteCapabilities(t *testing.T) {}params, _ := json.Marshal(map[string]any{- "name": "set_operator_state",+ "name": agentcapabilities.SetOperatorStateCapabilityName,"arguments": map[string]any{"resourceId": "vm:101","body": map[string]any{@@ -610,20 +1328,26 @@ func TestServer_ToolsCallSendsPutBodyForWriteCapabilities(t *testing.T) {t.Errorf("upstream body must round-trip note verbatim; got %v", sentBody["note"])}- // MCP result shape: 2xx upstream becomes isError=false with- // the upstream body in a text content block.- result, _ := resp.Result.(map[string]any)- if result["isError"] != false {- t.Errorf("2xx upstream must surface as isError=false; got %v", result["isError"])+ // MCP result shape: 2xx upstream becomes isError=false with the upstream+ // body in a text content block plus shared structuredContent for clients+ // that can branch on machine-readable tool output.+ result, ok := resp.Result.(agentcapabilities.MCPToolResult)+ if !ok {+ t.Fatalf("tools/call result type = %T, want shared MCPToolResult", resp.Result)+ }+ if result.IsError {+ t.Errorf("2xx upstream must surface as isError=false; got %v", result.IsError)}- content, _ := result["content"].([]map[string]any)- if len(content) != 1 {- t.Fatalf("content len = %d, want 1", len(content))+ if len(result.Content) != 1 {+ t.Fatalf("content len = %d, want 1", len(result.Content))}- text, _ := content[0]["text"].(string)+ text := result.Content[0].Textif !strings.Contains(text, `"canonicalId":"vm:101"`) {t.Errorf("MCP content must carry upstream response body; got %q", text)}+ if result.StructuredContent["canonicalId"] != "vm:101" {+ t.Fatalf("MCP structuredContent = %+v, want canonicalId vm:101", result.StructuredContent)+ }// Server-populated attribution must reach the agent so it// can see WHO the substrate recorded the write under (not the// supplied token, but the resolved actor id).@@ -654,9 +1378,11 @@ func TestServer_ToolsCallTopLevelArgsMakeUpRequestBody(t *testing.T) {baseURL: pulse.URL,token: "test",manifest: &agentCapabilitiesManifest{+ SurfaceContract: agentcapabilities.CanonicalManifest().SurfaceContract,+ SurfaceToolContracts: testPulseMCPSurfaceToolContracts(agentcapabilities.AcknowledgeFindingCapabilityName),Capabilities: []agentCapability{{- Name: "acknowledge_finding",+ Name: agentcapabilities.AcknowledgeFindingCapabilityName,Path: "/api/ai/patrol/acknowledge",Method: http.MethodPost,},@@ -702,12 +1428,14 @@ func TestServer_ToolsCallTopLevelArgsMakeUpRequestBody(t *testing.T) {// canonicalId duplication.func TestServer_ToolsCallTopLevelArgsExcludesPathPlaceholders(t *testing.T) {type captured struct {- path string- body string+ path string+ requestURI string+ body string}var got capturedpulse := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {got.path = r.URL.Path+ got.requestURI = r.RequestURIb, _ := io.ReadAll(r.Body)got.body = string(b)w.WriteHeader(http.StatusOK)@@ -719,10 +1447,12 @@ func TestServer_ToolsCallTopLevelArgsExcludesPathPlaceholders(t *testing.T) {baseURL: pulse.URL,token: "test",manifest: &agentCapabilitiesManifest{+ SurfaceContract: agentcapabilities.CanonicalManifest().SurfaceContract,+ SurfaceToolContracts: testPulseMCPSurfaceToolContracts(agentcapabilities.SetOperatorStateCapabilityName),Capabilities: []agentCapability{{- Name: "set_operator_state",- Path: "/api/resources/{resourceId}/operator-state",+ Name: agentcapabilities.SetOperatorStateCapabilityName,+ Path: agentcapabilities.OperatorStateCapabilityPath,Method: http.MethodPut,},},@@ -731,9 +1461,9 @@ func TestServer_ToolsCallTopLevelArgsExcludesPathPlaceholders(t *testing.T) {}params, _ := json.Marshal(map[string]any{- "name": "set_operator_state",+ "name": agentcapabilities.SetOperatorStateCapabilityName,"arguments": map[string]any{- "resourceId": "vm:101",+ "resourceId": "vm/special 101","intentionallyOffline": true,},})@@ -747,8 +1477,8 @@ func TestServer_ToolsCallTopLevelArgsExcludesPathPlaceholders(t *testing.T) {t.Fatalf("tools/call: rpc error = %+v", resp.Error)}- if got.path != "/api/resources/vm:101/operator-state" {- t.Errorf("path-placeholder substitution failed; got %q", got.path)+ if got.requestURI != "/api/resources/vm%2Fspecial%20101/operator-state" {+ t.Errorf("path-placeholder substitution failed; got request URI %q", got.requestURI)}var sent map[string]anyif err := json.Unmarshal([]byte(got.body), &sent); err != nil {diff --git a/docs/AGENT_SUBSTRATE.md b/docs/AGENT_SUBSTRATE.mdindex d59da5056c..d337577b91 100644--- a/docs/AGENT_SUBSTRATE.md+++ b/docs/AGENT_SUBSTRATE.md@@ -8,15 +8,19 @@ what shape this work took.## What it isPulse v6 ships an agent-paradigm substrate so external agents (Claude-Desktop, Claude Code, custom MCP clients, plain HTTP consumers) can+Desktop, Claude Code, OpenCode, other MCP clients, plain HTTP consumers) candrive Pulse with the same context an in-process Patrol or Assistanthas. The substrate has four axes:-**Discovery.** A hand-authored manifest at `/api/agent/capabilities`+**Discovery.** A canonical manifest at `/api/agent/capabilities`lists every agent-consumable capability with its name, description,-HTTP method and path, required auth scope, response shape, and stable-error codes. The manifest is unauthenticated so an agent without a-token can introspect Pulse before asking for one.+HTTP method and path, required auth scope, response shape, stable+error codes, and the deduplicated `requiredScopes` summary for the+current full surface. It also carries the Pulse Intelligence Core,+Patrol, Assistant, and MCP surface contract, including which+affordances each supported operator surface exposes. The manifest is+unauthenticated so an agent without a token can introspect Pulse before+asking for one.**Depth.** `/api/agent/resource-context/{id}` returns the situatedpicture of one resource in a single read: identity, operator-set@@ -56,49 +60,61 @@ polling the audit endpoint.## What ships consuming it-Two reference consumers, both standard-library-only, both-manifest-driven:+Three first-party consumers are built on the same manifest:++- **Settings -> API Access -> Agent integrations** is the in-app+ operator surface. It fetches `/api/agent/capabilities` from the+ running instance, lists the declared capabilities by category, shows+ the manifest-owned surface contract and affordance badges, shows each+ capability's method, path, scope, and stable error codes, and+ generates client-ready `pulse-mcp` config snippets from the+ manifest-owned MCP adapter setup contract: server name, command,+ base URL flag, token environment variable, and the supported client config families.+ The panel fills in the current Pulse URL for OpenCode's native `opencode.json` / `mcp` shape+ and the common `mcpServers` shape for Claude-style clients.+ Tokens are still minted in API Access, so the same settings tab covers+ "what agents can do" and "which token unlocks it."- **`cmd/agent-probe`** is a small Go binary that walks thediscovery, triage, depth, push flow against a running Pulseinstance. Useful as a smoke test or worked example for someonebuilding their own integration.-- **`cmd/pulse-mcp`** is the MCP server adapter. Wire it into Claude- Desktop or Claude Code per the README at `cmd/pulse-mcp/README.md`- and Pulse's tools appear natively. The adapter projects each- manifest capability into one MCP tool with auto-derived input- schema; adding capabilities to Pulse extends the MCP surface- without changes in the adapter. Run with `--emit-notifications`- to also translate Pulse's SSE events (`finding.created`,+- **`cmd/pulse-mcp`** is the MCP server adapter. Wire it into any+ MCP client that can launch a local server; the README at+ `cmd/pulse-mcp/README.md` includes generated setup plus OpenCode,+ Claude Desktop, and Claude Code examples from the same adapter contract,+ and the in-app Agent integrations panel shows both+ OpenCode's native `opencode.json` shape and the common `mcpServers`+ block. The adapter projects each manifest capability into one MCP+ tool with auto-derived input schema; adding capabilities to Pulse+ extends the MCP surface without changes in the adapter. Run with+ `--emit-notifications` to also translate Pulse's SSE events (`finding.created`,`approval.pending`, `action.completed`) into JSON-RPCnotifications on the stdio channel so autonomous MCP-bound agentscan react to push events without holding a separate HTTPconnection.+`pulse-mcp` also has a published distribution path: the one-line+installers (`install-mcp.sh` and `install-mcp.ps1`) download the+matching binary from the latest Pulse GitHub Release and verify the+release checksum. Building from source remains available for local+development.+## What it does not do yet-- Real-world consumer feedback. The substrate ships with two- reference adapters (HTTP and MCP) and end-to-end contract tests,- but no external integration has been load-bearing on it yet.- Until somebody wires `pulse-mcp` into Claude Desktop or builds- against the agent surface from a custom client, the next- meaningful work item is whatever friction usage surfaces, not- more substrate plumbing.--- A user-facing surface inside Pulse for managing agent- integrations. Today the agent surface is invisible to the- operator running Pulse: there is no Settings panel listing the- declared capabilities, no "generate MCP config snippet" button,- no token template that says "create token for agent- integration." Adding those is what makes the substrate real for- humans, not just for agents.--- A distribution path for `pulse-mcp`. Today an integrator must- clone the repo and `go build`. A release artifact (Homebrew- formula, Docker image, signed binary) would turn integration- from "build from source" into "install Pulse, copy this- config."+- Real-world consumer feedback. The substrate ships with the in-app+ Agent integrations panel, two reference adapters (HTTP and MCP),+ release installers, and end-to-end contract tests, but no external+ integration has been load-bearing on it yet. The next meaningful+ work item is whatever friction first usage surfaces, not more+ substrate plumbing.++- macOS notarization and package-manager polish. The installer+ verifies release checksums, but the first launch of the unsigned+ macOS binary can still show a Gatekeeper warning. Homebrew or other+ package-manager distribution can sit on top of the release binary+ path when usage signal warrants the maintenance.## Provable claims@@ -133,7 +149,11 @@ manifest-driven:agent-surface paragraphs in the `## Current State` section.- Implementation: `internal/api/agent_*.go` and`internal/api/resources_operator_state.go`.+- In-app setup surface:+ `frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx`.- MCP adapter: `cmd/pulse-mcp/` (with README).+- MCP installers: `scripts/install-mcp.sh` and+ `scripts/install-mcp.ps1`.- HTTP worked example: `cmd/agent-probe/`.- Subsystem dependencies: relevant paragraphs in `agent-lifecycle.md`,`performance-and-scalability.md`, and `storage-recovery.md` underdiff --git a/docs/AI.md b/docs/AI.mdindex 733da8580e..637d21cb2d 100644--- a/docs/AI.md+++ b/docs/AI.md@@ -1,17 +1,22 @@-# Pulse AI+# Pulse Intelligence-Pulse Patrol is available to everyone on the Community plan with BYOK (your own AI provider). Pro adds alert-triggered root-cause analysis and safe remediation workflows, while hosted Cloud carries those capabilities for hosted environments. Learn more at <https://pulserelay.pro> or see [PULSE_PRO.md](PULSE_PRO.md).+Pulse Patrol is available to everyone on the Community plan with BYOK (your own AI provider). Pro adds hands-on Patrol modes, issue investigation, governed fixes, verified outcomes, and 90-day history, while hosted Cloud carries those capabilities for hosted environments. Learn more at <https://pulserelay.pro> or see [PULSE_PRO.md](PULSE_PRO.md).---## Overview-Pulse includes two model-powered systems:+<!-- pulse-intelligence-overview:start -->+Pulse Intelligence is built around a shared **Pulse Intelligence Core**: Canonical context, governed actions, safety gates, approval state, action audit, and verification shared by Pulse Assistant, Pulse MCP, and Pulse Patrol.-1. **Pulse Assistant** — An interactive chat interface for ad-hoc troubleshooting, investigations, and infrastructure control.-2. **Pulse Patrol** — A scheduled, context-aware model workflow that gathers infrastructure evidence, exposes governed tools, and asks your configured LLM to report actionable findings.+That core is deliberately surfaced with Patrol as the primary built-in operator and Assistant plus MCP as access paths over the same governed capabilities:-Both systems are built on the same tool-driven architecture: the configured LLM owns diagnosis, prioritization, remediation reasoning, and tool choice; Pulse supplies context, tools, safety gates, approval state, and audit trails.+1. **Pulse Patrol**: Patrol is the first-party operations surface: it watches, investigates, acts within the chosen Patrol mode, verifies outcomes, and records what happened.+2. **Pulse Assistant**: The contextual explanation, approval, and handoff surface for Patrol findings, governed actions, verification, and operator questions. Affordances: tools and interactive questions.+3. **Pulse MCP**: The external-agent adapter that projects canonical Pulse Intelligence capabilities as MCP tools. Affordances: tools, resources, prompts, and capability metadata.+<!-- pulse-intelligence-overview:end -->++These surfaces are built on the same action-driven architecture: the configured LLM owns diagnosis, prioritization, fix reasoning, and action choice; Pulse supplies context, capabilities, safety gates, approval state, and audit trails. Verification is part of the governed action lifecycle rather than a separate model-owned feature.### Not Just Another Chatbot@@ -21,14 +26,14 @@ Pulse Assistant is a **protocol-driven, safety-gated LLM tool surface** that:- **Caches session facts** — extracts bounded tool facts to avoid redundant queries during the current conversation- **Enforces workflow invariants** — FSM prevents dangerous state transitions- **Supports parallel tool execution** — efficient batch operations with concurrency control-- **Detects and prevents hallucinations** — phantom execution detection+- **Grounds answers in real tool work** — visible tool traces, read-after-write verification, and transcript hygiene prevent unsupported execution claims from being treated as facts- **Returns structured tool errors** — the model can recover from clear, machine-readable failures📖 **For a deep technical dive into the Assistant architecture, see [architecture/pulse-assistant-deep-dive.md](architecture/pulse-assistant-deep-dive.md).**### Not Just Another Alerting System-Pulse Patrol is a **scheduled model-owned operations loop** that:+Pulse Patrol is a **scheduled and event-triggered governed operator** that:- **Assembles evidence** from metrics, storage, backups, discovery, alerts, and resource timelines- **Provides statistical context** such as baselines, trend summaries, capacity estimates, and event relationships@@ -42,6 +47,19 @@ All while running entirely on your infrastructure with BYOK for complete privacySee [architecture/pulse-assistant.md](architecture/pulse-assistant.md) for the original safety architecture documentation.+### Assistant And MCP++Pulse Assistant and `pulse-mcp` are sibling surfaces over Pulse Intelligence,+not competing implementations, and neither replaces the other. Assistant remains+the in-app Pro surface for current resource/finding/run handoffs, approval+cards, governed action status, and operator-friendly timelines. `pulse-mcp`+owns the external-agent bridge: it fetches `/api/agent/capabilities`, projects+those canonical API capabilities as MCP tools, and preserves the same stable+error envelopes and approval/audit contracts. New operational capabilities+should be added to the canonical API manifest first, then consumed by Assistant+or MCP as appropriate; MCP-only actions and Assistant-only copies of the same+business logic are drift.+---## Pulse Patrol@@ -71,7 +89,7 @@ patrol_report_finding() / patrol_resolve_finding() ── model-owned finding limodel-reported findings ── validated, deduplicated, stored│▼ (if configured)-MaybeInvestigateFinding() ── model investigation + governed remediation+MaybeInvestigateFinding() ── model investigation + governed fix planning/execution```### What Patrol Sees@@ -162,23 +180,22 @@ Dismissed and resolved findings persist across Pulse restarts.----## Autonomy Levels+## Patrol Modes-Patrol supports three autonomy modes that control how much action it can take:+Patrol supports four modes that decide how far Pulse can go after it finds an issue:| Mode | Behavior | Plan |-|------|----------|------|-| **Monitor** | Detect issues only. No investigation or fixes. | Community (BYOK) |-| **Investigate** | Investigates findings and proposes fixes. All fixes require approval before execution. | Pro / hosted Cloud |-| **Remediate** | Runs governed remediation actions and verifies results. Critical findings still require approval by default. | Pro / hosted Cloud |+|-------|----------|------|+| **Watch only** | Detect issues only. No investigation or fixes. | Community (BYOK) |+| **Ask before changes** | Investigates findings and proposes fixes. All fixes require approval before execution. | Pro / hosted Cloud |+| **Auto-fix safe issues** | Runs warning-level governed fixes automatically and verifies results. Critical findings still require approval by default. | Pro / hosted Cloud |+| **Policy autopilot** | Runs eligible governed fixes automatically and verifies results. Use only in environments where this is acceptable. | Pro / hosted Cloud |-Community and Relay installs can still run scheduled Patrol findings with BYOK.-Investigation, proposed remediation, and fix execution are paid AI-operations-capabilities rather than a core monitoring limit.+Community and Relay installs can still run scheduled Patrol findings with BYOK. Watch only remains the free-first baseline; investigation, proposed fixes, and fix execution are paid AI-operations capabilities rather than a core monitoring limit.### Investigation Flow-When a finding is created in Investigate or Remediate mode:+When a finding is created in a Pro Patrol mode:```Finding created@@ -245,24 +262,24 @@ Pulse Assistant is a **tool-driven** chat interface. It does not "guess" system2. **Investigate**: Uses `pulse_read` to run bounded, read-only commands and check status/logs3. **Act** (optional): Uses `pulse_control` for changes, then verifies with a read-### Available Tools--| Tool | Classification | Purpose |-|------|---------------|---------|-| `pulse_query`, `pulse_discovery` | Resolve | Resource discovery and query |-| `pulse_read` | Read | Read-only operations: exec, file, find, tail, logs |-| `pulse_metrics` | Read | Performance metrics and baselines |-| `pulse_storage` | Read | Storage pools, backups, snapshots, Ceph, RAID, disk health |-| `pulse_kubernetes` | Read | Kubernetes cluster info |-| `pulse_pmg` | Read | Proxmox Mail Gateway stats |-| `pulse_alerts` | Read/Write | Alert management (resolve/dismiss are writes) |-| `pulse_docker` | Read/Write | Docker operations (control/update are writes) |-| `pulse_knowledge` | Read/Write | Knowledge persistence (remember/note/save are writes) |-| `pulse_file_edit` | Read/Write | File operations (write/append are writes) |-| `pulse_control` | Write | Guest control, service management |-| `patrol_report_finding` | Patrol | Report a new finding (patrol runs only) |-| `patrol_resolve_finding` | Patrol | Resolve an active finding (patrol runs only) |-| `patrol_get_findings` | Patrol | List active findings (patrol runs only) |+### Tool Inventory++The Assistant tool list is registry-owned at runtime, not hand-maintained in+this public overview. Each turn receives an available-tool manifest generated+from Pulse's governed tool registry, including action mode (`read`, `mixed`,+`write`) and approval policy (`scope_only`, `action_plan`). That same registry+feeds the Assistant system prompt, provider tool declarations, tool-result+handling, approval boundaries, and Patrol-only tool filtering.++For the current source-owned inventory, see the native tool registry and+governance projection in `internal/ai/tools/` and+`internal/agentcapabilities/`. For external agents, use the live+`/api/agent/capabilities` manifest or `pulse-mcp` `tools/list`; those surfaces+project the canonical agent capabilities rather than a separate MCP-only tool+table.+The same manifest also carries reusable `workflowPrompts` metadata so Pulse+Assistant-compatible starters and MCP `prompts/list` clients discover the same+fleet triage, resource investigation, and Patrol finding review workflows.### Safety Gates@@ -271,7 +288,7 @@ The assistant enforces multiple safety gates:1. **Discovery Before Action** — Action tools cannot operate on resources that weren't first discovered2. **Verification After Write** — After any write, the model must perform a read/status check before providing a final answer3. **Read/Write Separation** — Read operations route through `pulse_read` (stays in READING state); write operations route through `pulse_control` (enters VERIFYING state)-4. **Phantom Detection** — Detects when the model claims execution without tool calls+4. **Grounded Execution Guardrails** — Visible tool traces and read-after-write checks prevent unsupported execution claims from being treated as facts5. **Approval Mode** — In Controlled mode, every write requires explicit user approval6. **Execution Context Binding** — Commands execute within the resolved resource's context, not on parent hosts@@ -297,11 +314,11 @@ When control level is **Controlled**, write actions pause for approval:## Configuration-Configure in the UI: **Settings → System → AI Assistant**+Configure providers in the UI: **Settings → Pulse Intelligence → Provider & Models**### Supported Providers-- **Anthropic** (API key or OAuth)+- **Anthropic** (API key)- **OpenAI**- **OpenRouter**- **DeepSeek**@@ -309,6 +326,10 @@ Configure in the UI: **Settings → System → AI Assistant**- **Ollama** (self-hosted, with tool/function calling support)- **OpenAI-compatible base URL** (for providers that implement the OpenAI API shape)+Legacy Anthropic OAuth fields may still appear in stored settings so existing+installs can disconnect and clear old tokens, but Anthropic OAuth is not a+supported runtime authentication method and does not make Anthropic configured.+### ModelsPulse uses model identifiers in the form: `provider:model-name`@@ -316,7 +337,7 @@ Pulse uses model identifiers in the form: `provider:model-name`You can set separate models for:- Chat (`chat_model`)- Patrol (`patrol_model`)-- Safe remediation model (`auto_fix_model`)+- Patrol fix model (`auto_fix_model`, retained as the compatibility settings key)### Storage@@ -421,10 +442,10 @@ go run ./cmd/eval -scenario resource-context -url http://127.0.0.1:7655 -user adPulse includes settings that control how "active" AI features are:-- **Autonomous mode (Pro and above)**: When enabled, AI may execute safe commands without approval-- **Safe remediation workflows (Pro and above)**: Allows Patrol to propose and run governed remediation actions under the approval or autonomy policy you choose-- **Alert-triggered analysis (Pro and above)**: Limits AI to analyzing specific events when alerts occur-- **Full autonomy unlock (Pro and above)**: Permits critical remediation actions without approval (requires explicit toggle)+- **Patrol modes (Pro and above)**: Lets you choose whether Patrol only watches, asks before changes, handles safe fixes, or uses policy autopilot+- **Governed fixes (Pro and above)**: Allows Patrol to propose, approve, run, verify, and record fixes under the Patrol mode you choose+- **Issue investigation (Pro and above)**: Lets Patrol investigate findings with surrounding infrastructure context+- **Policy autopilot unlock (Pro and above)**: Permits eligible critical fixes without per-fix approval after an explicit opt-inIf you enable execution features, ensure agent tokens and scopes are appropriately restricted.@@ -440,7 +461,7 @@ Use this only in trusted environments.## Privacy-Patrol runs on your server and only sends the minimal context needed for analysis to the configured provider (when AI is enabled). Anonymous outbound telemetry (counts and feature flags only — no hostnames or credentials) is enabled by default and can be disabled any time — see [Privacy](PRIVACY.md) for details.+Patrol runs on your server and only sends the minimal context needed for analysis to the configured provider (when AI is enabled). Anonymous outbound telemetry (counts, feature flags, and coarse Patrol mode and governed Pulse Intelligence operations adoption flags and counters only; no hostnames, credentials, prompts, chat messages, command text, action output, token values, or resource identifiers) is enabled by default and can be disabled any time. See [Privacy](PRIVACY.md) for details.---@@ -449,7 +470,7 @@ Patrol runs on your server and only sends the minimal context needed for analysiAlerts are threshold-based and narrow. Patrol gives the selected model a broader, tool-backed operating picture.- **Alerts**: "Disk > 90%"-- **Patrol**: "The model sees ZFS pool usage, growth rate, datastore consumers, backup context, and governed tools, then decides whether that evidence warrants a finding or action recommendation."+- **Patrol**: "The model sees ZFS pool usage, growth rate, datastore consumers, backup context, and governed actions, then decides whether that evidence warrants a finding or action recommendation."---@@ -467,7 +488,7 @@ Pulse tracks token usage and costs:| Issue | Solution ||-------|----------|-| AI not responding | Verify provider credentials in **Settings → System → AI Assistant** |+| Assistant or Patrol not responding | Verify provider credentials in **Settings → Pulse Intelligence → Provider & Models** || No execution capability | Confirm at least one agent is connected || Findings not persisting | Check Pulse has write access to `ai_findings.json` in the config directory || Too many findings | This shouldn't happen — please report if it does |@@ -478,7 +499,7 @@ Pulse tracks token usage and costs:### Deep Dives (Recommended for Technical Audiences)-- **[Pulse Assistant Deep Dive](architecture/pulse-assistant-deep-dive.md)** — Complete technical breakdown of the model-owned tool surface: explicit context, session fact caching, FSM enforcement, parallel execution, phantom detection, structured errors+- **[Pulse Assistant Deep Dive](architecture/pulse-assistant-deep-dive.md)** — Complete technical breakdown of the model-owned tool surface: explicit context, session fact caching, FSM enforcement, parallel execution, grounded execution guardrails, structured errors- **[Pulse Patrol Deep Dive](architecture/pulse-patrol-deep-dive.md)** — Patrol runtime documentation: evidence assembly, deterministic signal extraction, model evaluation, investigation context, investigation orchestration### Reference Documentationdiff --git a/docs/AI_AUTONOMY.md b/docs/AI_AUTONOMY.mdindex 435a57d84b..efb12a7712 100644--- a/docs/AI_AUTONOMY.md+++ b/docs/AI_AUTONOMY.md@@ -1,8 +1,8 @@-# AI Autonomy and Safety Configuration+# Pulse Intelligence Modes and Safety Configuration-This guide covers how to configure and manage Pulse's AI autonomy levels, control levels, and safety guardrails.+This guide covers how to configure Patrol mode, Pulse Assistant command access, and the safety guardrails that apply before Pulse can change infrastructure.-For a general overview of Pulse AI, see [AI.md](AI.md). For plan-level feature availability, see [PULSE_PRO.md](PULSE_PRO.md).+For a general overview of Pulse Intelligence, see [AI.md](AI.md). For plan-level feature availability, see [PULSE_PRO.md](PULSE_PRO.md).---@@ -10,39 +10,40 @@ For a general overview of Pulse AI, see [AI.md](AI.md). For plan-level feature aPulse separates AI permissions into two independent axes:-1. **Patrol Autonomy Level** — How much Patrol can do on its own (detect, investigate, fix).-2. **Assistant Control Level** — Whether the interactive chat assistant can execute commands.+1. **Patrol Mode** — What Patrol may handle automatically after it finds an issue: watch only, ask before changes, handle safe fixes, or use policy autopilot.+2. **Assistant Command Access** — Whether the interactive chat assistant can execute commands during a chat session.-These are configured independently in **Settings → System → AI Assistant**.+Patrol mode is configured on the **Patrol** page. Assistant command access is configured in **Settings → Pulse Intelligence → Assistant**.----## Patrol Autonomy Levels+## Patrol Modes-Patrol autonomy controls how aggressively Patrol responds to findings.+Patrol mode sets how far Pulse can go when Patrol finds something that needs attention.-| Level | Key | Detect | Investigate | Fix (Warning) | Fix (Critical) | Plan |-|-------|-----|:------:|:-----------:|:-------------:|:--------------:|------|-| **Monitor** | `monitor` | Yes | No | No | No | Community |-| **Approval** | `approval` | Yes | Yes | Approval required | Approval required | Pro / legacy Pro+ / Cloud |-| **Assisted** | `assisted` | Yes | Yes | Execute automatically | Approval required | Pro / legacy Pro+ / Cloud |-| **Full** | `full` | Yes | Yes | Execute automatically | Execute automatically | Pro / legacy Pro+ / Cloud |+| Mode | Key | Detect | Investigate | Fix warning-level issues | Fix critical issues | Plan |+|-------|-----|:------:|:-----------:|:------------------------:|:-------------------:|------|+| **Watch only** | `monitor` | Yes | No | No | No | Community |+| **Ask before changes** | `approval` | Yes | Yes | Approval required | Approval required | Pro / legacy Pro+ / Cloud |+| **Auto-fix safe issues** | `assisted` | Yes | Yes | Execute automatically | Approval required | Pro / legacy Pro+ / Cloud |+| **Policy autopilot** | `full` | Yes | Yes | Execute automatically | Execute automatically | Pro / legacy Pro+ / Cloud |-- **Monitor** (default): Patrol creates findings but takes no action. This is the Community and Relay baseline. Suitable for learning what Patrol detects before enabling investigation or remediation.-- **Approval** (Pro and above): Patrol investigates findings and proposes fixes. All fixes queue for manual approval before execution.-- **Assisted** (Pro and above): Warning-level safe remediation plans can execute automatically. Critical findings still require approval. This is the recommended starting point for most Pro and legacy Pro+ users who enable fix execution.-- **Full** (Pro and above): Safe remediation plans can execute without approval. Requires an explicit toggle and a Pro, legacy Pro+, or Cloud license. Recommended only for environments with thorough alert coverage.+- **Watch only** (default): Patrol creates findings but takes no action. This is the Community and Relay baseline. Suitable for learning what Patrol detects before enabling investigation or fix execution.+- **Ask before changes** (Pro and above): Patrol investigates findings and proposes fixes. All fixes queue for manual approval before execution.+- **Auto-fix safe issues** (Pro and above): Warning-level safe fix plans can execute automatically. Critical findings still require approval. This is the recommended starting point for most Pro and legacy Pro+ users who enable fix execution.+- **Policy autopilot** (Pro and above): Safe fix plans can execute without approval. Requires an explicit toggle and a Pro, legacy Pro+, or Cloud license. Recommended only for environments with thorough alert coverage.### Configuration-**UI:** Settings → System → AI Assistant → Patrol Autonomy Level+**UI:** Patrol → Patrol mode**API:**```bash-# Get current patrol autonomy settings+# Get current Patrol mode settingscurl -s -u admin:admin http://localhost:7655/api/ai/patrol/autonomy-# Update autonomy level+# Update Patrol mode.+# The API keeps the autonomy_level field name for compatibility.curl -X PUT http://localhost:7655/api/ai/patrol/autonomy \-u admin:admin \-H "Content-Type: application/json" \@@ -54,7 +55,7 @@ curl -X PUT http://localhost:7655/api/ai/patrol/autonomy \- `monitor`: Available on all plans. Community and Relay can run Patrol with BYOK.- `approval`, `assisted`, and `full`: Require the `ai_autofix` capability (Pro, legacy Pro+, or Cloud license).-Without the `ai_autofix` capability, the effective autonomy level is clamped to `monitor` at runtime, regardless of the saved configuration. If you previously had a Pro license and downgraded, your saved setting is preserved but enforcement reverts to `monitor`.+Without the `ai_autofix` capability, the effective Patrol mode is clamped to `monitor` at runtime, regardless of the saved configuration. If you previously had a Pro license and downgraded, your saved setting is preserved but enforcement reverts to `monitor`.---@@ -74,7 +75,7 @@ Control levels govern what the interactive Pulse Assistant can do during chat se### Configuration-**UI:** Settings → System → AI Assistant → Control Level+**UI:** Settings → Pulse Intelligence → Assistant → Chat command mode**API:**```bash@@ -100,7 +101,7 @@ Approvals expire after 5 minutes if not acted upon.## Investigation Configuration-When autonomy is `approval`, `assisted`, or `full`, Patrol investigates findings. These parameters tune investigation behavior:+When Patrol mode is `approval`, `assisted`, or `full`, Patrol investigates findings. These parameters tune investigation behavior:| Setting | Default | Range | Description ||---------|---------|-------|-------------|@@ -115,7 +116,7 @@ When autonomy is `approval`, `assisted`, or `full`, Patrol investigates findings## Safety Guardrails-Regardless of autonomy level, Pulse enforces multiple safety layers:+Regardless of Patrol mode, Pulse enforces multiple safety layers:### Blocked Commands@@ -144,12 +145,12 @@ After executing any control action, the assistant must verify the result with a## Recommended Progression-For new deployments, we recommend gradually increasing autonomy:+For new deployments, gradually increase Patrol mode:-1. **Start with Monitor** — Run Patrol for a few cycles to see what it detects. Dismiss false positives.-2. **Move to Approval where available** — Enable investigation. Review proposed fixes to build confidence.-3. **Use Assisted when fix execution is enabled** — Let Patrol execute warning-level remediation while you approve critical fixes.-4. **Consider Full** — Only if your environment has comprehensive alerting and you trust the fix patterns.+1. **Start with Watch only** — Run Patrol for a few cycles to see what it detects. Dismiss false positives.+2. **Move to Ask before changes where available** — Enable investigation. Review proposed fixes to build confidence.+3. **Use Auto-fix safe issues when fix execution is enabled** — Let Patrol execute warning-level fixes while you approve critical fixes.+4. **Consider Policy autopilot** — Only if your environment has comprehensive alerting and you trust the fix patterns.---@@ -165,7 +166,7 @@ Prometheus counters (prefix `pulse_patrol_*`) track:### Cost TrackingToken usage and estimated costs are tracked per provider:-- **UI:** Settings → System → AI Assistant → Usage+- **UI:** Settings → Pulse Intelligence → Provider & Models → Provider Usage & Spend- **API:** `GET /api/ai/cost/summary`- Set monthly budget limits to cap spending@@ -178,7 +179,7 @@ Token usage and estimated costs are tracked per provider:## Related Documentation-- [Pulse AI Overview](AI.md) — Full AI system documentation+- [Pulse Intelligence Overview](AI.md) — Full Pulse Intelligence system documentation- [Plans and Entitlements](PULSE_PRO.md) — Feature availability by plan- [API Reference](API.md) — Complete API documentation- [Pulse Patrol Deep Dive](architecture/pulse-patrol-deep-dive.md) — Technical architecture detailsdiff --git a/docs/API.md b/docs/API.mdindex 4145f53b05..4e335ebe2d 100644--- a/docs/API.md+++ b/docs/API.md@@ -940,7 +940,7 @@ Revoke a resource share. Admin or owner role required.----## 🤖 Pulse AI+## 🤖 Pulse Intelligence**Paid gating:** endpoints labeled with a paid plan require the relevant Relay, Pro, legacy Pro+, or Cloud capability and return `402 Payment Required` if the feature is not licensed.@@ -960,11 +960,13 @@ Lists models available to the configured providers (queried live from provider A- `POST /api/ai/test`- `POST /api/ai/test/{provider}`-### OAuth (Anthropic)-- `POST /api/ai/oauth/start` (admin)-- `POST /api/ai/oauth/exchange` (admin, manual code input)-- `GET /api/ai/oauth/callback` (public, IdP redirect)-- `POST /api/ai/oauth/disconnect` (admin)+### Legacy Anthropic OAuth Cleanup+Anthropic subscription OAuth is unsupported. These routes remain only for+fail-closed compatibility and token cleanup:+- `POST /api/ai/oauth/start` (admin): returns `501` with `unsupported_anthropic_oauth`+- `POST /api/ai/oauth/exchange` (admin): returns `501` with `unsupported_anthropic_oauth`+- `GET /api/ai/oauth/callback` (public): redirects to settings with `ai_oauth_error=unsupported` unless the provider supplied a specific error+- `POST /api/ai/oauth/disconnect` (admin): clears stored legacy OAuth tokens### Execute (Chat + Tools)`POST /api/ai/execute`diff --git a/docs/FAQ.md b/docs/FAQ.mdindex fac1a53c47..60f9396c27 100644--- a/docs/FAQ.md+++ b/docs/FAQ.md@@ -32,10 +32,10 @@ If a setting is disabled with an amber warning, it's being overridden by an envi## 🔍 Monitoring & Metrics### What do Relay, Pro, and Cloud unlock?-Relay adds secure remote access to the Pulse web UI, Pulse Mobile pairing for handoff, push notifications, and 14-day history. Pro and Cloud unlock **alert-triggered root-cause analysis and safe remediation workflows** along with the broader operations feature set. Existing legacy Pro+ holders keep their current continuity, but self-hosted pricing no longer sells more monitoring volume. Pulse Patrol is available to everyone on Community with BYOK and provides scheduled, cross-system analysis that correlates real-time state, recent metrics history, and diagnostics to surface actionable findings.+Relay adds secure remote access to the Pulse web UI, Pulse Mobile pairing for handoff, push notifications, and 14-day history. Pro and Cloud unlock **hands-on Patrol modes, issue investigation, governed fixes, verified outcomes, and 90-day history** along with the broader operations feature set. Existing legacy Pro+ holders keep their current continuity, but self-hosted pricing no longer sells more monitoring volume. Pulse Patrol is available to everyone on Community with BYOK and provides scheduled, cross-system analysis that correlates real-time state, recent metrics history, and diagnostics to surface actionable findings.Example output includes trend-based capacity warnings, backup regressions, Kubernetes cluster analysis, and correlated container failures that simple threshold alerts miss.-See [Pulse AI](AI.md), [Plans and entitlements](PULSE_PRO.md), and <https://pulserelay.pro>.+See [Pulse Intelligence](AI.md), [Plans and entitlements](PULSE_PRO.md), and <https://pulserelay.pro>.### Why do VMs show "-" for disk usage?Proxmox API returns `0` for VM disk usage by default. You must install the **QEMU Guest Agent** inside the VM and enable it in Proxmox (VM → Options → QEMU Guest Agent).diff --git a/docs/PRIVACY.md b/docs/PRIVACY.mdindex 50ecd7acab..31c6b7be3f 100644--- a/docs/PRIVACY.md+++ b/docs/PRIVACY.md@@ -14,9 +14,9 @@ third-party analytics, support diagnostics, or ordinary Settings surfaces.### Anonymous outbound telemetry-Pulse includes anonymous outbound telemetry that is **enabled by default**. It sends a lightweight ping on startup and once every 24 hours to help me understand how many active installations exist, which releases are actually deployed, and which features are in use.+Pulse includes anonymous outbound telemetry that is **enabled by default**. It sends a lightweight ping on startup and once every 24 hours to help me understand how many active installations exist, which releases are actually deployed, which features are in use, and whether Patrol control and governed Pulse Intelligence operations are being adopted.-No hostnames, credentials, infrastructure identifiers, IP addresses, prompts, chat messages, or personally identifiable information is ever sent. See the full field list below.+No hostnames, credentials, infrastructure identifiers, IP addresses, prompts, chat messages, command text, action output, token values, or personally identifiable information is ever sent. See the full field list below.#### How to disable@@ -80,11 +80,69 @@ Every field is listed below with the reason it exists — nothing else leaves yo| Multi-tenant | `true`/`false` | See whether multi-tenant/runtime-org features are being used || Paid license | `true`/`false` | Distinguish free from paid posture without sending the exact commercial tier || Has API tokens | `true`/`false` | See whether token-based automation/integration is being used without sending token counts |+| Pulse Intelligence configured | `true`/`false` | See whether Assistant, Patrol, governed actions, or external-agent access is configured so adoption can be measured without sending configuration details |+| Pulse Intelligence active 30d | `true`/`false` | See whether Assistant, Patrol, external-agent, or governed-action activity occurred in the current 30-day telemetry window |+| Pulse Intelligence governed decision 30d | `true`/`false` | See whether Patrol issue activity reached an approved or rejected governed-action decision without sending prompts, findings, resource identifiers, command text, or action output |+| Pulse Intelligence approved action attempt 30d | `true`/`false` | See whether Patrol issue activity reached an approved governed action attempt without sending action details |+| Pulse Intelligence resolved issue 30d | `true`/`false` | See whether Patrol issue activity reached resolution with an approved action success without sending prompts, findings, resource identifiers, command text, or action output |+| Pulse Intelligence Patrol mode decision 30d | `true`/`false` | See whether a Patrol mode starter, Patrol issue activity, contextual Assistant or external-agent collaboration, and either a rejected governed decision or an approved governed decision with a verified outcome occurred without sending prompt text, checkout details, account links, token details, resource identifiers, command text, or action output |+| Pulse Intelligence Patrol mode resolved issue 30d | `true`/`false` | See whether a Patrol mode starter, Patrol issue activity, contextual Assistant or external-agent collaboration, an approved governed decision, and a verified outcome occurred without sending prompt text, checkout details, account links, token details, resource identifiers, command text, or action output |+| Pulse Intelligence paid Patrol mode decision 30d | `true`/`false` | See whether the install currently has a paid license and Patrol mode reached a governed decision without sending the exact tier, checkout details, account links, prompts, token details, resource identifiers, command text, or action output |+| Pulse Intelligence paid Patrol mode resolved issue 30d | `true`/`false` | See whether the install currently has a paid license and Patrol mode reached a resolved issue without sending the exact tier, checkout details, account links, prompts, token details, resource identifiers, command text, or action output |+| Pulse Intelligence historical Patrol mode decision mirror 30d | `true`/`false` | Compatibility mirror of the Patrol mode decision field for historical aggregate reporting without sending prompt text, checkout details, account links, token details, resource identifiers, command text, or action output |+| Pulse Intelligence historical Patrol mode resolved mirror 30d | `true`/`false` | Compatibility mirror of the Patrol mode resolved field for historical aggregate reporting without sending prompt text, checkout details, account links, token details, resource identifiers, command text, or action output |+| Pulse Intelligence paid historical Patrol mode decision mirror 30d | `true`/`false` | Compatibility mirror of the paid Patrol mode decision field for historical aggregate reporting without sending exact tier, checkout details, account links, token details, resource identifiers, command text, or action output |+| Pulse Intelligence paid historical Patrol mode resolved mirror 30d | `true`/`false` | Compatibility mirror of the paid Patrol mode resolved field for historical aggregate reporting without sending exact tier, checkout details, account links, token details, resource identifiers, command text, or action output |+| Pulse Intelligence governed action active 30d | `true`/`false` | See whether Patrol or Assistant reached action planning, approval, approve/reject decision, or approved-action depth in the current 30-day telemetry window without sending action details |+| Pulse Intelligence Assistant governed decision 30d | `true`/`false` | See whether Assistant collaboration specifically reached the Patrol issue plus approved/rejected governed-action path without sending prompts, chat messages, tool details, findings, command text, or action output |+| Pulse Intelligence Assistant approved action attempt 30d | `true`/`false` | See whether Assistant collaboration specifically reached approved governed-action execution in the 30-day window without sending prompts, chat messages, command text, actors, or action output |+| Pulse Intelligence Assistant approved action success 30d | `true`/`false` | See whether Assistant collaboration specifically reached approved action success in the 30-day window without sending prompts, chat messages, verification details, command text, or action output |+| Pulse Intelligence Assistant resolved issue 30d | `true`/`false` | See whether Assistant collaboration specifically reached Patrol resolution plus approved action success in the 30-day window without sending findings, prompts, chat messages, verification details, command text, or action output |+| Pulse Intelligence external-agent governed decision 30d | `true`/`false` | See whether direct external-agent or MCP collaboration reached the Patrol issue plus approved/rejected governed-action path without sending route parameters, prompts, resource identifiers, command text, or action output |+| Pulse Intelligence external-agent approved action attempt 30d | `true`/`false` | See whether direct external-agent or MCP collaboration reached approved governed-action execution in the 30-day window without sending route parameters, command text, actors, or action output |+| Pulse Intelligence external-agent approved action success 30d | `true`/`false` | See whether direct external-agent or MCP collaboration reached approved action success in the 30-day window without sending route parameters, command text, verification details, or action output |+| Pulse Intelligence external-agent resolved issue 30d | `true`/`false` | See whether direct external-agent or MCP collaboration reached Patrol resolution plus approved action success in the 30-day window without sending findings, route parameters, command text, verification details, or action output |+| Pulse Intelligence `pulse-mcp` governed decision 30d | `true`/`false` | See whether the `pulse-mcp` adapter specifically reached the Patrol issue plus approved/rejected governed-action path without sending prompts, tool inputs, route parameters, resource identifiers, command text, or action output |+| Pulse Intelligence `pulse-mcp` approved action attempt 30d | `true`/`false` | See whether the `pulse-mcp` adapter specifically reached approved governed-action execution in the 30-day window without sending prompts, tool inputs, command text, actors, or action output |+| Pulse Intelligence `pulse-mcp` approved action success 30d | `true`/`false` | See whether the `pulse-mcp` adapter specifically reached approved action success in the 30-day window without sending prompts, tool inputs, verification details, command text, or action output |+| Pulse Intelligence `pulse-mcp` resolved issue 30d | `true`/`false` | See whether the `pulse-mcp` adapter specifically reached Patrol resolution plus approved action success in the 30-day window without sending findings, prompts, tool inputs, verification details, command text, or action output |+| Pulse Intelligence starter requests 30d | `3` | Count shared Patrol-work starter requests in the current 30-day telemetry window without sending prompt text, chat messages, tool inputs, resource IDs, or request details |+| Pulse Intelligence Assistant starter requests 30d | `2` | Count Assistant requests for shared Patrol work in the current 30-day telemetry window without sending prompt text, chat messages, resource IDs, or request details |+| Pulse Intelligence Patrol starter requests 30d | `1` | Count Patrol work starter requests in the current 30-day telemetry window without sending prompt text, findings, resource IDs, or request details |+| Pulse Intelligence Patrol mode starter requests 30d | `1` | Count Patrol work, Patrol-mode, and historical entry-point requests for shared Patrol work in the current 30-day telemetry window without sending prompt text, checkout details, account links, resource IDs, or request details |+| Pulse Intelligence historical Patrol mode starter mirror 30d | `1` | Count historical entry-point requests for Patrol mode in the current 30-day telemetry window without sending prompt text, checkout details, account links, resource IDs, or request details |+| Pulse Intelligence `pulse-mcp` starter requests 30d | `1` | Count `pulse-mcp` requests for shared Patrol work in the current 30-day telemetry window without sending prompt text, tool inputs, resource IDs, route parameters, or request details |+| Pulse Intelligence Assistant AI calls 30d | `18` | Count Assistant model calls in the current 30-day telemetry window without sending prompts, responses, session IDs, or chat text |+| Pulse Intelligence Assistant context AI calls 30d | `7` | Count Assistant model calls tied to a governed resource, finding, handoff, or action context in the current 30-day telemetry window without sending prompts, responses, session IDs, resource IDs, finding IDs, or chat text |+| Pulse Intelligence Assistant tool calls 30d | `11` | Count Assistant tool calls in the current 30-day telemetry window without sending tool names, tool inputs, tool outputs, prompts, responses, session IDs, resource IDs, finding IDs, command text, or chat text |+| Pulse Intelligence Patrol AI calls 30d | `6` | Count Patrol model calls in the current 30-day telemetry window without sending provider-bound context or findings text |+| Pulse Intelligence Patrol runs 30d | `12` | Count Patrol investigations in the current 30-day telemetry window |+| Pulse Intelligence Patrol new findings 30d | `5` | Count new findings produced by Patrol in the current 30-day telemetry window without sending finding IDs or details |+| Pulse Intelligence Patrol investigations 30d | `3` | Count findings investigated by Patrol in the current 30-day telemetry window without sending finding IDs, resource IDs, or details |+| Pulse Intelligence Patrol resolved findings 30d | `2` | Count findings resolved or fix-verified in the current 30-day telemetry window without sending finding IDs, resource IDs, fix details, or verification detail |+| Pulse Intelligence Patrol autofixes 30d | `1` | Count Patrol autofix records in the current 30-day telemetry window without sending target resources or fix content |+| Pulse Intelligence external agent enabled | `true`/`false` | See whether at least one token can use the external Pulse Intelligence agent/MCP surface without sending token counts, names, scopes, or values |+| Pulse Intelligence external agent used 30d | `true`/`false` | See whether an external-agent-capable API token reached a Pulse Intelligence agent/MCP route in the current 30-day telemetry window without sending token identity, route parameters, resource IDs, or request details |+| Pulse Intelligence MCP adapter used 30d | `true`/`false` | See whether the `pulse-mcp` adapter reached a Pulse Intelligence agent/MCP route in the current 30-day telemetry window without sending token identity, route parameters, resource IDs, prompts, or request details |+| Pulse Intelligence external agent context requests 30d | `8` | Count external-agent/MCP resource-context and fleet-context requests in the current 30-day telemetry window without sending resource IDs, route parameters, or request details |+| Pulse Intelligence external agent event stream requests 30d | `3` | Count external-agent/MCP event-stream requests in the current 30-day telemetry window without sending event content, route parameters, or request details |+| Pulse Intelligence external agent provisioning requests 30d | `2` | Count external-agent/MCP provisioning requests in the current 30-day telemetry window without sending discovered resources, credentials, route parameters, or request details |+| Pulse Intelligence external agent operator state requests 30d | `5` | Count external-agent/MCP operator-state requests in the current 30-day telemetry window without sending state payloads, route parameters, or request details |+| Pulse Intelligence external agent finding requests 30d | `4` | Count external-agent/MCP finding-list and finding-decision requests in the current 30-day telemetry window without sending finding IDs, finding text, route parameters, or request details |+| Pulse Intelligence external agent action requests 30d | `1` | Count external-agent/MCP action-plan, action-decision, and action-execution requests in the current 30-day telemetry window without sending command text, action output, route parameters, or request details |+| Pulse Intelligence action plans 30d | `4` | Count governed action plans in the current 30-day telemetry window without sending command text, resource IDs, or plan details |+| Pulse Intelligence approval requests 30d | `2` | Count approval-gated action requests in the current 30-day telemetry window without sending approvers, reasons, command text, or targets |+| Pulse Intelligence rejected action decisions 30d | `1` | Count rejected governed action decisions in the current 30-day telemetry window without sending approvers, reasons, command text, targets, or action IDs |+| Pulse Intelligence approved action decisions 30d | `1` | Count approved governed action decisions in the current 30-day telemetry window without sending approvers, reasons, command text, targets, or action IDs |+| Pulse Intelligence approved action attempts 30d | `1` | Count approved governed action attempts in the current 30-day telemetry window without sending action output, command text, or verification detail |+| Pulse Intelligence approved action successes 30d | `1` | Count approved governed actions that completed successfully in the current 30-day telemetry window without sending action output, command text, resource IDs, actors, reasons, or verification detail |#### Server-side handling and retention- Telemetry pings are stored on the Pulse license server only for aggregate install/use analysis.-- The license server stores only the same coarse telemetry fields listed above; it does not expand them into exact commercial tiers or exact API-token counts.+- The license server stores only the same coarse telemetry fields listed above; it does not expand them into exact commercial tiers, exact API-token counts, prompts, chat messages, command text, action output, token values, or resource identifiers.+- Pulse may derive aggregate Pulse Intelligence adoption reports from those same rows, including whether an install reached Patrol issue activity, Patrol resolution, Assistant, direct external-agent, or MCP collaboration, Patrol mode starter use, paid Patrol mode cohorts, governed-action activity, approved or rejected action decisions, approved action success, recent retention, and observed free-to-paid movement within the source window. Those reports do not add prompts, findings, resource identifiers, tool names, tool inputs, tool outputs, command payloads, action outputs, account links, or exact commercial tiers.+- External-agent/MCP activity is stored only as a coarse adapter-origin flag plus capability-class counters: context, event stream, provisioning, operator state, findings, and action requests.- Telemetry rows older than **90 days** are purged automatically.- The license server uses client IP addresses transiently for abuse/rate limiting, but it does **not** store IP addresses in telemetry rows.@@ -93,7 +151,7 @@ Every field is listed below with the reason it exists — nothing else leaves yo- No IP addresses are stored in telemetry rows- No hostnames, node names, VM names, or any infrastructure identifiers- No Proxmox credentials, API tokens, or passwords-- No alert content, AI prompts, or chat messages+- No alert content, AI prompts, chat messages, tool names, tool inputs, tool outputs, command text, action output, or token values- No personally identifiable information of any kind#### Install ID rotationdiff --git a/docs/PULSE_PRO.md b/docs/PULSE_PRO.mdindex 2c15f612b4..8b24134764 100644--- a/docs/PULSE_PRO.md+++ b/docs/PULSE_PRO.md@@ -91,8 +91,8 @@ capability key is a primary v6 product pillar.These are the current self-hosted Pro pillars that Pulse should keepinvesting in, surfacing, and marketing:-- Alert-triggered root-cause analysis.-- Safe remediation workflows through Patrol fix execution and autonomy controls.+- Patrol investigates issues.+- Patrol handles safe fixes through approval-backed execution and Patrol mode.- 90-day history.- Included team/admin extras: RBAC, audit logging, reporting, and agentprofiles. SSO is included with Community and higher tiers.@@ -110,7 +110,7 @@ be elevated into headline Pro marketing or generic upgrade prompts:These should not appear as current v6 Pro promises unless they are rebuiltinto first-class product surfaces:- `incident memory` as a standalone feature name-- `scheduled remediations`+- `scheduled automated fixes`- `execution audit trail`## Paid Feature Proof Map@@ -124,7 +124,7 @@ surface upgrade prompts unless the user deliberately enters a commercial path.|---|---|---|| Self-hosted monitoring is not sold by monitored-system or child-resource volume. | `pkg/licensing/features.go` and `pkg/licensing/entitlement_payload.go` normalize self-hosted limits to the current no-volume-gate policy. | `pkg/licensing/grant_claims_contract_test.go`, `pkg/licensing/activation_types_test.go`, and `internal/api/licensing_handlers_auto_migrate_test.go` prove self-hosted paid/legacy continuity does not surface finite monitored-system allowances. || Relay includes secure remote web access, Pulse Mobile pairing for handoff, push notifications, and 14-day history. | `pkg/licensing/features.go` grants `relay`, `mobile_app`, `push_notifications`, and `long_term_metrics` to Relay with `TierHistoryDays[relay] == 14`; relay onboarding/settings routes are gated behind Relay. | `pkg/licensing/features_test.go`, `pkg/licensing/entitlement_payload_test.go`, `internal/api/relay_sso_license_gating_test.go`, and `frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsx`. |-| Pro includes alert-triggered root-cause analysis and safe remediation workflows. | `internal/api/ai_handlers.go` gates alert-triggered analysis behind `ai_alerts` and remediation/autonomy behind `ai_autofix`; `internal/ai/service.go` enforces the same capabilities in service-level paths. | `pkg/licensing/features_test.go`, `internal/api/router_routes_ai_execute_stream_test.go`, `internal/api/ai_intelligence_handlers_remediation_more_test.go`, and `frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx`. |+| Pro includes Patrol issue investigation and verified fix actions. | `internal/api/ai_handlers.go` gates alert-triggered analysis behind `ai_alerts` and fix/autonomy behavior behind `ai_autofix`; `internal/ai/service.go` enforces the same capabilities in service-level paths. | `pkg/licensing/features_test.go`, `internal/api/router_routes_ai_execute_stream_test.go`, `internal/api/ai_intelligence_handlers_remediation_more_test.go`, and `frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx`. || Pro includes 90-day history. | `pkg/licensing/features.go` sets `TierHistoryDays[pro] == 90`; `pkg/licensing/entitlement_payload.go` emits `max_history_days`; `frontend-modern/src/stores/license.ts` and `frontend-modern/src/components/shared/useHistoryChartState.ts` lock ranges above the entitlement. | `pkg/licensing/features_test.go`, `pkg/licensing/entitlement_payload_test.go`, and `frontend-modern/src/stores/__tests__/license.test.ts`. || Pro includes business/admin extras: RBAC, audit logging, reporting, and agent profiles. | Router and settings gates use `rbac`, `audit_logging`, `advanced_reporting`, and `agent_profiles`; audit capture is SQLite-backed in `pkg/server/server.go` and `pkg/audit/sqlite_factory.go`, while query/export remains license-gated. | `internal/api/security_regression_test.go`, `internal/api/rbac_lifecycle_test.go`, `pkg/reporting/catalog_test.go`, and `frontend-modern/src/components/Settings/__tests__/settingsNavigation.integration.test.tsx`. |@@ -140,8 +140,8 @@ This matrix is derived from the canonical table in `docs/architecture/ENTITLEMEN|---|---|---|:---:|:---:|:---:|:---:|---|| `FeatureAIPatrol` | `ai_patrol` | Pulse Patrol (Background Health Checks) | Y | Y | Y | Y | Patrol itself is available on Community with your own provider or local model. Higher-autonomy outcomes and fix execution are separately gated. || `FeatureRelay` | `relay` | Remote Access (Mobile Relay) | N | Y | Y | Y | API route gating via `RequireLicenseFeature(..., relay, ...)` for relay settings and onboarding endpoints. |-| `FeatureAIAlerts` | `ai_alerts` | Alert-Triggered Root-Cause Analysis | N | N | Y | Y | API route gating via `RequireLicenseFeature(..., ai_alerts, ...)`. |-| `FeatureAIAutoFix` | `ai_autofix` | Safe Remediation Workflows | N | N | Y | Y | Required for governed fix execution and autonomous remediation actions. |+| `FeatureAIAlerts` | `ai_alerts` | Patrol Investigates Issues | N | N | Y | Y | API route gating via `RequireLicenseFeature(..., ai_alerts, ...)`. |+| `FeatureAIAutoFix` | `ai_autofix` | Patrol Handles Safe Fixes | N | N | Y | Y | Required for governed fix execution and automatic Patrol actions. || `FeatureKubernetesAI` | `kubernetes_ai` | Kubernetes AI Analysis (Compatibility) | N | N | Y | Y | Legacy compatibility gate for `/api/ai/kubernetes/analyze`; not a primary marketed v6 Pro plan pillar. || `FeatureAgentProfiles` | `agent_profiles` | Centralized Agent Profiles | N | N | Y | Y | API route gating via `RequireLicenseFeature(..., agent_profiles, ...)`. || `FeatureUpdateAlerts` | `update_alerts` | Update Alerts (Container/Package Updates) | Y | Y | Y | Y | Included in Community tier per `TierFeatures[TierFree]`. |@@ -156,16 +156,16 @@ This matrix is derived from the canonical table in `docs/architecture/ENTITLEMEN| `FeatureUnlimited` | `unlimited` | Hosted Capacity Policy | N | N | N | Y | Hosted/enterprise capacity policy only; not a self-hosted core monitoring gate. || `FeatureWhiteLabel` | `white_label` | White-Label Report Branding | N | N | N | Y* | Gates custom report branding. Provider defaults and per-client overrides render only when this entitlement is active. |-## Autonomy Levels (AI Safety)+## Patrol Modes-Patrol and the Assistant support tiered autonomy:+Patrol mode decides how far Pulse can go after Patrol finds something that needs attention. Assistant chat command access is configured separately.| Mode | Behavior | Plan ||---|---|---|-| **Monitor** | Detect issues only. No investigation or remediation execution. | Community / Relay |-| **Investigate** | Investigates findings and proposes fixes. All remediation actions require approval. | Pro / hosted Cloud |-| **Remediate** | Runs approved safe remediation actions and verifies the outcome. Critical findings require approval by default. | Pro / hosted Cloud |-| **Full autonomy** | Allows critical remediation actions without approval when explicitly enabled. | Pro / hosted Cloud |+| **Watch only** | Detect issues only. No investigation or fix execution. | Community / Relay |+| **Ask before changes** | Investigates findings and proposes fixes. All fixes require approval before execution. | Pro / hosted Cloud |+| **Auto-fix safe issues** | Runs approved safe fixes and verifies the outcome. Critical findings require approval by default. | Pro / hosted Cloud |+| **Policy autopilot** | Runs eligible policy-approved fixes without approval when explicitly enabled. | Pro / hosted Cloud |## What You Get (By Plan)@@ -183,8 +183,8 @@ Patrol and the Assistant support tiered autonomy:### Pro- Everything in Relay, plus:-- Alert-triggered root-cause analysis.-- Safe remediation workflows and autonomy controls.+- Patrol investigates issues.+- Patrol handles safe fixes through Patrol mode.- Centralized agent profiles.- RBAC, audit logging, and advanced reporting.- 90-day history.@@ -223,4 +223,4 @@ This returns a feature map including keys like `relay`, `ai_alerts`, `ai_autofix- [Pulse Patrol Deep Dive](architecture/pulse-patrol-deep-dive.md)- [Pulse Assistant Deep Dive](architecture/pulse-assistant-deep-dive.md)-- [Pulse AI overview](AI.md)+- [Pulse Intelligence overview](AI.md)diff --git a/docs/README.md b/docs/README.mdindex b8b0bc5048..7e95c22289 100644--- a/docs/README.md+++ b/docs/README.md@@ -65,7 +65,7 @@ All other documents are supporting references unless explicitly required for evi## 📖 Advanced Topics (Relay / Pro / legacy Pro+ / Cloud)-- **[AI Autonomy & Safety](AI_AUTONOMY.md)** – Configure patrol autonomy levels, assistant control levels, investigation tuning, and safety guardrails.+- **[AI Modes & Safety](AI_AUTONOMY.md)** – Configure Patrol mode, assistant control levels, investigation tuning, and safety guardrails.- **[Role-Based Access Control (RBAC)](RBAC.md)** – Define custom roles, assign permissions, and integrate with OIDC group mapping.- **[Audit Logging](AUDIT_LOGGING.md)** – Tamper-evident event logging for compliance, with query, export, and signature verification.@@ -77,7 +77,7 @@ All other documents are supporting references unless explicitly required for evi- **[Relay / Pulse Mobile Handoff](RELAY.md)** – End-to-end encrypted relay for supported Pulse Mobile clients (Relay and above).- **[Recovery Central](RECOVERY.md)** – Unified backup, snapshot, and replication view across all providers.- **[Pulse Cloud (Hosted)](CLOUD.md)** – Fully managed hosting with automatic updates and backups.-- **[Pulse AI](AI.md)** – Chat assistant, patrol findings, alert analysis, intelligence, and forecasts.+- **[Pulse Intelligence](AI.md)** – Pulse Assistant, Patrol findings, alert analysis, governed actions, and forecasts.- **[Metrics History](METRICS_HISTORY.md)** – Persistent metrics storage with configurable retention.- **[Mail Gateway](MAIL_GATEWAY.md)** – Proxmox Mail Gateway (PMG) monitoring.- **[Auto Updates](AUTO_UPDATE.md)** – One-click updates for supported deployments.@@ -91,7 +91,7 @@ Pulse is available in three self-hosted tiers plus hosted Cloud:- **Community**: Free self-hosted monitoring with core monitoring included and 7-day history.- **Relay**: Adds secure remote access to the Pulse web UI, Pulse Mobile pairing for handoff, push notifications, and 14-day history.-- **Pro**: Adds alert-triggered root-cause analysis, safe remediation workflows, operations tooling, governance features, and 90-day history.+- **Pro**: Adds hands-on Patrol modes, issue investigation, governed fixes, verified outcomes, operations tooling, governance features, and 90-day history.- **Cloud**: Hosted Pulse with Pro-level capabilities; hosted pricing is unchanged by the self-hosted model lock.- **[Learn more at pulserelay.pro](https://pulserelay.pro)**diff --git a/docs/architecture/v6-pricing-and-tiering.md b/docs/architecture/v6-pricing-and-tiering.mdindex 4fe48f920c..f536f43e95 100644--- a/docs/architecture/v6-pricing-and-tiering.md+++ b/docs/architecture/v6-pricing-and-tiering.md@@ -106,9 +106,9 @@ than sold by monitored-system volume.| SSO | OIDC/SAML with multi-provider support || Update notifications | Yes || Metrics history | **7 days** |-| AI Patrol | Monitor + root-cause summaries + fix suggestions with the operator's configured provider or local model |-| Safe remediation workflows | **No** (must apply fixes manually) |-| Alert-triggered root-cause analysis | No |+| AI Patrol | Watch-only findings with the operator's configured provider or local model |+| Patrol governed fixes | **No** (must apply fixes manually) |+| Alert investigation | No || Relay | No || Push notifications | No || Customer-specific Relay URL | No |@@ -123,9 +123,10 @@ than sold by monitored-system volume.it's their provider, their key or local runtime, and their operating cost. Pulseapplies technical guardrails such as anti-loop protection and rate protection.-In both modes, the paid gate is governed execution through Pulse: free users see the-full analysis and fix suggestions but apply fixes manually. Pro users can run approved-remediation actions through Pulse.+In both modes, the paid gate is governed execution through Pulse: free users see+watch-only Patrol findings but apply fixes manually. Pro users can let Patrol+investigate, ask for approval when policy requires it, run governed fixes, verify+outcomes, and record what happened.### Relay — $4.99/month or $39/year@@ -138,8 +139,8 @@ remediation actions through Pulse.| Push notifications | **Yes** || Customer-specific Relay URL | No; Relay uses the standard outbound relay service for v6 GA || Metrics history | **14 days** |-| Safe remediation workflows | No |-| Alert-triggered root-cause analysis | No |+| Patrol governed fixes | No |+| Alert investigation | No || RBAC/Audit/Reporting | No || Reporting | No |@@ -153,8 +154,9 @@ without changing their self-hosted monitoring scope.|---|---|| Monitoring scope | **Core self-hosted monitoring included** || Everything in Relay | Yes |-| Safe remediation workflows | **Yes** (approved execution, safety preflight, rollback) |-| Alert-triggered root-cause analysis | **Yes** |+| Patrol modes | **Yes** (choose how much Patrol can do) |+| Issue investigation | **Yes** |+| Governed fixes | **Yes** (approved execution, safety preflight, rollback, verification) || Metrics history | **90 days** || RBAC | **Yes** || Audit logging | **Yes** |@@ -165,8 +167,8 @@ without changing their self-hosted monitoring scope.**Positioning:** For serious self-hosted operators who want Pulse to move from monitoringinto operations. The marketing pitch focuses on three things:-1. "Explain what broke" (alert-triggered root-cause analysis)-2. "Fix it safely" (safe remediation workflows)+1. "Choose Patrol mode" (how much Patrol can do)+2. "Let Patrol investigate and fix governed issues" (issue investigation, governed fixes, verification)3. "Keep longer operating memory" (90-day history)Relay convenience and the team extras (RBAC, audit logging, reporting, and agent@@ -291,8 +293,8 @@ Patrol finding is a conversion moment.### 3. Provider setup stays self-managedAI setup on self-hosted installs should point operators at their own provider connection or-local model endpoint. Paid operations features such as safe remediation-workflows, alert analysis, and longer history remain opt-in extras; they do not+local model endpoint. Paid operations features such as governed fixes,+issue investigation, and longer history remain opt-in extras; they do notreplace the self-managed AI runtime path.### 4. Relay as optional convenience ($39/yr)@@ -309,7 +311,7 @@ opens pricing/activation/recovery/support flows, when the session is hosted/clouexisting entitlement requires a clear renewal or recovery path.High-intent product moments should stay useful without becoming sales surfaces:-- Patrol finds a fixable issue -> show the manual fix and BYOK/provider path first; safe remediation execution can+- Patrol finds a fixable issue -> show the manual fix and BYOK/provider path first; governed fix execution canremain an opt-in Pro capability where commercial prompts are explicitly allowed.- An alert needs deeper explanation -> keep free investigation context useful; paid alertanalysis stays an optional, discoverable extra.@@ -322,7 +324,7 @@ High-intent product moments should stay useful without becoming sales surfaces:Self-hosted Community users should not need a temporary monitored-system overflow path becausecore self-hosted monitoring is included by default and not metered. Onboarding can still surfaceRelay and Pro value when users try remote access, push notifications, longer history, alert-investigation, or safe remediation workflows.+investigation, or governed fixes.### 7. Transparent monitored-system ledgerThe ledger remains important for inventory truth, hosted/MSP limits, and support. It should@@ -428,7 +430,7 @@ explain monitored-system identity:### Boundary-upgrade copy- **Community → Relay:** Want Pulse outside your LAN? Upgrade to Relay for secure remote access, mobile, push notifications, and 14-day history.-- **Relay → Pro:** Want Pulse to do more than alert? Upgrade to Pro for root-cause analysis, safe remediation workflows, and 90-day history.+- **Relay → Pro:** Want Pulse to do more than alert? Upgrade to Pro for hands-on Patrol modes, issue investigation, governed fixes, verified outcomes, and 90-day history.- **Existing self-hosted monitoring:** Your monitored systems keep working. Paid self-hosted tiers add convenience and operations features, not more monitoring room.---diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.jsonindex 2958aab7d6..46179c90c5 100644--- a/docs/release-control/v6/internal/status.json+++ b/docs/release-control/v6/internal/status.json@@ -2750,8 +2750,8 @@"src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts","src/components/patrol/__tests__/ApprovalSection.test.tsx","src/components/AI/__tests__/FindingsPanel.test.ts",- "src/features/patrol/__tests__/PatrolIntelligenceSummary.test.tsx","src/pages/__tests__/AIIntelligence.test.tsx",+ "src/utils/__tests__/patrolEmptyStatePresentation.test.ts","src/utils/__tests__/patrolPagePresentation.test.ts","src/utils/__tests__/patrolSummaryPresentation.test.ts","src/utils/__tests__/aiChatPresentation.test.ts",@@ -2858,22 +2858,22 @@},{"repo": "pulse",- "path": "frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceSummary.test.tsx",+ "path": "frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts","kind": "file"},{"repo": "pulse",- "path": "frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts",+ "path": "frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts","kind": "file"},{"repo": "pulse",- "path": "frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts",+ "path": "frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx","kind": "file"},{"repo": "pulse",- "path": "frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx",+ "path": "frontend-modern/src/utils/__tests__/patrolEmptyStatePresentation.test.ts","kind": "file"},{@@ -3911,11 +3911,15 @@"status": "partial","completion": {"state": "bounded-residual",- "summary": "Commercial readiness is coherent for explicit preview, checkout handoff, paid-user activation/recovery, and hosted-mode paths, while default self-hosted app surfaces stay free-first and non-promotional; because v6 is not publicly GA, production public checkout stays on v5 until explicit GA cutover approval, and the production public flip plus release-day rollout execution remain a separate promotion-time follow-up.",+ "summary": "Commercial readiness is coherent for explicit preview, checkout handoff, paid-user activation/recovery, hosted-mode paths, and the first Pulse Intelligence value-evidence reporting surface, while default self-hosted app surfaces stay free-first and non-promotional; because v6 is not publicly GA, production public checkout stays on v5 until explicit GA cutover approval, and the production public flip plus release-day rollout execution plus the broader governed Patrol control experience remain separate follow-ups.","tracking": [{"kind": "lane-followup","id": "commercial-ga-promotion-package"+ },+ {+ "kind": "lane-followup",+ "id": "pulse-intelligence-pro-activation-loop"}]},@@ -6974,6 +6978,21 @@"L20"],"subsystem_ids": []+ },+ {+ "id": "pulse-intelligence-pro-activation-loop",+ "summary": "Track Pulse Intelligence as the default governed Pro operations experience beyond the current feature floor: a new Pro user should choose what Patrol may handle automatically, then Patrol should watch the infrastructure, investigate real issues, act automatically or ask for approval according to that policy, verify outcomes, and record what happened. Assistant and Pulse MCP must expose the same governed capabilities as contextual and external-agent access paths, but they are not the primary first-party success condition. Pro should record whether completing this Patrol control loop improves activation, retention, and paid conversion. This is L2-owned commercial activation work with explicit dependencies on the L6 Assistant architecture, L20 action governance, and L23 Pulse Intelligence floor.",+ "owner": "project-owner",+ "status": "planned",+ "recorded_at": "2026-06-20",+ "lane_ids": [+ "L2"+ ],+ "repo_ids": [+ "pulse",+ "pulse-pro"+ ],+ "subsystem_ids": []}],"coverage_gaps": [@@ -7720,7 +7739,7 @@},{"id": "patrol-product-language-ai-boundary",- "summary": "Patrol product-language migration boundary audited: customer-facing page titles, nav, route chrome, summary copy, actions, and empty states lead with Patrol/Pulse Patrol/Pulse Assistant. Internal file, store, type, transport, and log identifiers retain the shared AI-runtime boundary. The `/settings/system-ai` panel is the explicit provider/configuration carve-out where AI terminology is reserved; its chrome already leads with 'Assistant & Patrol'. The remaining AgentProfilesPanel 'Ideas' tooltip was product-neutralized to 'Suggest profiles for your estate'.",+ "summary": "Patrol product-language migration boundary audited: customer-facing page titles, nav, route chrome, summary copy, actions, and empty states lead with Patrol/Pulse Patrol/Pulse Assistant. Internal file, store, type, transport, and log identifiers retain the shared AI-runtime boundary. The `/settings/system-ai` route remains the explicit provider/configuration carve-out; its visible chrome now lives under Pulse Intelligence > Provider & Models rather than generic AI settings. The remaining AgentProfilesPanel 'Ideas' tooltip was product-neutralized to 'Suggest profiles for your estate'.","kind": "architecture","decided_at": "2026-04-17","subsystem_ids": [diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex ad100de95e..f635530fa5 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -111,6 +111,29 @@ shared `/api/resources` payload carries a backend-authored Proxmox workloadtarget linked to that node agent. Suppressing an inside-guest install cue forthat case means governed actions have a node-agent path; it must not bepresented as proof that a guest-local agent is installed.+Agent-facing operations-loop status wiring in `internal/api/router.go` and+`internal/api/agent_resource_context.go` is lifecycle-adjacent only because it+shares agent route infrastructure. Workflow starter counts on that endpoint,+contextual Assistant/external-agent collaboration counts inside the Assistant+step, the content-free Patrol control starter split, and Patrol control+completed-loop, resolved-loop, or `patrolControlValueState` proof mirrored to+`patrolAutonomyValueState` compatibility fields are+API-contract telemetry/orientation fields, not agent enrollment, liveness,+setup completion, install, update, command, recovery, or fleet-control+lifecycle authority. Native `pulse_patrol` starts, current paid+`patrol_control` starts, legacy `patrol_autonomy` starts, and legacy+`pulse_pro_activation` starts all contribute to Patrol control starter orientation;+`proActivationOperationsLoopStarterCount` remains a legacy entry-point counter+for the old alias only, while the legacy completed/resolved/value+`proActivation*` fields are compatibility aliases for that same first-party+Patrol control proof while older commercial and telemetry consumers migrate.+Lifecycle surfaces must+not treat `verified`,+legacy-compatible `verified_needs_mcp`, or `governed_decision_recorded` as+proof that an agent install, update, registration, profile rollout, or fleet+command completed. External-agent/MCP readiness is optional collaboration+setup for agents outside the app, not a first-party Patrol control completion+gate and not a lifecycle setup stage.1. `frontend-modern/src/api/agentProfiles.ts` shared with `api-contracts`: the agent profiles frontend client is both an agent lifecycle control surface and a canonical API payload contract boundary.2. `frontend-modern/src/api/nodes.ts` shared with `api-contracts`: the shared Proxmox node client is both an agent lifecycle setup/install control surface and a canonical API payload contract boundary.@@ -260,6 +283,11 @@ same browser-safe history boundary. Lifecycle surfaces, MCP adapters, andagents may display the updated title as human navigation metadata, but theymust not treat a renamed title as command authorization, host identity,enrollment state, capability evidence, or install-token disclosure.+The native Assistant surface-tool inventory at+`GET /api/ai/assistant/surface-tools` is also AI-runtime/API-contract metadata:+lifecycle surfaces may display which Assistant tools are available, but must+not reinterpret that list as agent enrollment state, command authority, install+token scope, or proof that a host can execute lifecycle actions.Agent lifecycle consumers of `/api/agent/events` and`/api/agent/resource-context/{id}` must also honor the shared API commandpayload boundary: API tokens with monitoring/read scope receive@@ -268,6 +296,20 @@ text unless they also hold action execution scope. Lifecycle UI and agents mayuse those redacted events as doorbells or status summaries, but they must fetchgoverned detail through the approval/action surfaces and must not treat amonitoring-readable event stream as command disclosure or execution authority.+Lifecycle surfaces that inspect agent event kinds must consume the shared+`internal/agentcapabilities` event vocabulary. Local lifecycle, MCP, or probe+copies of `finding.created`, `approval.pending`, `action.completed`,+`stream.connected`, or `heartbeat`, or local SSE parser semantics for those+events, are contract drift because event naming and stream framing are+API/AI-owned, not lifecycle-owned.+Lifecycle consumers of agent-surface failures must also consume the shared+`internal/agentcapabilities` error envelope; lifecycle work may branch on the+stable `error` code but must not define a local failure envelope or reinterpret+agent errors as install, enrollment, command, or update authority. Branchable+agent-surface codes exposed through shared `internal/api/` routes must be+referenced from `agentcapabilities.AgentErrCode*` constants so lifecycle UI,+Assistant handoffs, MCP adapters, and manifest declarations do not drift into+separate string vocabularies.The resource-context endpoint's additive context sections are the sameread-only boundary: lifecycle consumers, MCP adapters, and external agents mayuse their bounded facts, provenance, freshness, and explicit redaction metadata@@ -566,6 +608,40 @@ instead of lifecycle-local centered icon/text shells.lifecycle surfaces may display contact email when supplied by the sharedauth boundary, but they must not reinterpret SSO or Stripe email as thecanonical user identifier for setup, install, or fleet-management actions.+ Approved-action tool invocation parsing in `internal/api/router_routes_ai_relay.go`+ is not an agent-lifecycle route grammar: lifecycle-adjacent setup or repair+ flows that execute governed Pulse tools must inherit+ `internal/agentcapabilities.ParseTextToolInvocation` through the API relay+ instead of duplicating `pulse_*` command-string parsing in lifecycle helpers.+ Approved-action replay through that same relay must also use the shared+ `internal/agentcapabilities` approved-action argument helper, not lifecycle-local+ approval argument keys or pass-through maps.+ Native Assistant workflow-prompt rendering through+ `POST /api/ai/workflow-prompts/render` is likewise AI-runtime/API-contract+ ownership even though it is wired through shared `internal/api/` files:+ lifecycle surfaces may benefit from the resulting Assistant prompt text, but+ they must not treat manifest `workflowPrompts`, rendered prompt bodies, or+ Assistant starter availability as install, enrollment, or fleet-control+ route grammar.+ The adjacent workflow-starter activity markers on+ `POST /api/ai/workflow-prompts/activity` and+ `POST /api/agent/workflow-prompt-activity` follow that same split:+ lifecycle surfaces may use the aggregate activation reports, but the+ content-free prompt-name/surface/timestamp marker is not agent enrollment,+ install readiness, fleet-control liveness, command authority, or agent+ update state. The first-party `pulse_patrol` starter surface means a user+ entered the Pulse Intelligence operations-loop journey from app UX; it does+ not imply a host agent is installed, healthy, or authorized to run commands.+ The first-party `patrol_control` starter surface and legacy+ `patrol_autonomy` / `pulse_pro_activation` aliases are paid Patrol control+ journey markers only; lifecycle code must not treat any of them as setup,+ install, fleet-health, or command-agent state.+ The adjacent `GET /api/agent/patrol-control/status` projection in+ `internal/api/agent_resource_context.go` may expose operator-readable Patrol+ status copy for native and external-agent orchestration, but lifecycle+ surfaces must not reinterpret that copy, its next action, or its+ completed/resolved Patrol outcome counts as install readiness, enrollment+ health, command authorization, or agent update state.Hosted Pulse Account may deep-link an MSP operator into a tenant workspace'sagent-install surface through a signed local handoff target such as`/settings/infrastructure?add=linux-host`, but install-token generation,@@ -599,7 +675,20 @@ instead of lifecycle-local centered icon/text shells.Patrol readiness and settings-save payload changes on those shared handlersare also adjacent only: structured provider/model/tool causes may be exposedto Patrol and Assistant, but they do not grant agent install, enrollment,- or fleet command authority.+ or fleet command authority. Assistant runtime identity strings exposed by+ those handlers must name the first-party surface as Pulse Assistant rather+ than the legacy generic `Pulse AI`, and lifecycle consumers must not treat+ that label as agent registration, install progress, or command-agent+ readiness state. Diagnostics from `internal/api/diagnostics.go` follow the+ same adjacent boundary: lifecycle consumers may read+ `assistantRuntimeConnected`, but they must not reinterpret it as MCP+ transport state, agent registration, install progress, or command-agent+ readiness.+ Profile-suggestion availability errors consumed through+ `frontend-modern/src/api/agentProfiles.ts` are shared Pulse Intelligence+ availability guidance, not lifecycle registration state; the client must+ point operators at Assistant & Patrol settings instead of reviving `Pulse+ Assistant settings` copy.Hosted handoff subjects consumed through the shared API auth boundary mustalready be stable, non-email principals; lifecycle-adjacent routes must notrecover authority from a blank handoff subject by falling back to contact@@ -653,7 +742,16 @@ instead of lifecycle-local centered icon/text shells.`internal/api/ai_handlers.go` and `internal/api/chat_service_adapter.go`may be invoked by lifecycle-adjacent surfaces, but AI runtime auth andprovider selection remain `ai-runtime` plus `api-contracts` concerns rather- than install-token or lifecycle credential state. Lifecycle flows must not+ than install-token or lifecycle credential state. Legacy Anthropic OAuth+ fields exposed by AI settings are cleanup-only compatibility state:+ lifecycle-adjacent setup, install, profile, and relay flows must not treat+ stored OAuth tokens or `auth_method=oauth` as an agent enrollment, provider+ bootstrap, or AI provider-readiness signal. API-facing Assistant chat tool+ calls projected through `internal/api/chat_service_adapter.go` must stay+ on the shared `agentcapabilities` provider-call shape; lifecycle consumers+ must not treat Assistant transcript tool-call IDs, inputs, output, success+ flags, or provider continuation metadata as enrollment, assignment, installer,+ or fleet-command evidence. Lifecycle flows must notrecreate the retired Patrol quickstart bootstrap path, mint server-issuedhosted-model tokens, or derive AI provider state from installation identity.Per-request `/api/ai/chat` execution-mode overrides follow that same@@ -756,13 +854,36 @@ instead of lifecycle-local centered icon/text shells.4. Keep shared agent-side TLS identity fail-closed across `cmd/pulse-agent/main.go`, `internal/hostagent/`, `internal/agentupdate/`, `internal/remoteconfig/client.go`, and `internal/agenttls/config.go`. Self-signed deployments may use a canonical pinned Pulse server certificate fingerprint, but lifecycle transport must route that pin through reporting, enrollment, command websocket, remote-config, and self-update clients instead of widening `PULSE_INSECURE_SKIP_VERIFY` into a blanket MITM carve-out. A configured custom CA bundle is part of that same trust boundary: if the bundle is unreadable or invalid, lifecycle transport must refuse the connection path rather than silently downgrading back to system roots.5. Keep release-grade updater trust fail-closed across `internal/agentupdate/`, `internal/dockeragent/`, and the shared `internal/api/unified_agent.go` download helpers. When release builds embed trusted update signing keys, published agent binaries and installer assets must carry detached `.sig` plus `.sshsig` sidecars; updater/runtime paths must require `X-Signature-Ed25519` in addition to `X-Checksum-Sha256`, and installer-owned download flows must require the matching base64-encoded `X-Signature-SSHSIG`, instead of silently downgrading to checksum-only trust.6. Keep shared `internal/api/` helper edits isolated from agent lifecycle semantics: Patrol-specific status transport or alert-trigger wiring changes in shared handlers must not bleed into auto-register, installer, or fleet-control behavior unless this contract moves in the same slice.- The same isolation rule applies to AI settings payload work in `internal/api/ai_handlers.go`: provider auth fields, masked-secret echoes, and provider-test model selection remain AI/runtime plus API-contract ownership and must not be reinterpreted as lifecycle setup or registration semantics just because they share backend helper layers.+ The same isolation rule applies to AI settings payload work in `internal/api/ai_handlers.go`: provider auth fields, masked-secret echoes, provider-test model selection, and legacy Anthropic OAuth cleanup fields remain AI/runtime plus API-contract ownership and must not be reinterpreted as lifecycle setup, provider activation, or registration semantics just because they share backend helper layers.+ Patrol readiness labels on the same settings payload, including the+ user-facing Patrol control label for the stable `configuration` check ID,+ remain AI/runtime plus API-contract wording and must not be treated as agent+ lifecycle configuration, install readiness, registration state, or fleet+ control setup.+ Governed AI action-target normalization in+ `internal/api/ai_handlers.go` and `internal/api/ai_resource_types.go`+ follows that same split: Assistant approval routing may map resource types+ to action targets, but lifecycle setup, enrollment, installer, and command+ websocket target semantics remain owned by the lifecycle contracts above.The same isolation rule applies to Pulse Assistant chat SSE progress in`internal/api/ai_handler.go`: neutral `workflow_state` transport livenesssuch as `stream_idle`, provider startup, retry, fallback, and model-thinkingstatus remains AI/runtime plus API-contract ownership and must not bereinterpreted as agent enrollment, install progress, command websocketliveness, or fleet-control freshness.+ Native Assistant workflow-prompt rendering through+ `POST /api/ai/workflow-prompts/render` follows the same split: manifest-owned+ prompt names, argument validation, and rendered starter text remain+ AI/runtime plus API-contract ownership and must not become lifecycle setup,+ enrollment, installer, or fleet-control state just because the route lives in+ `internal/api/ai_handler.go`.+ Workflow-starter activity telemetry recorded after successful Assistant+ prompt rendering, first-party Patrol activation handoff, Pro activation+ handoff, or Pulse MCP prompt rendering follows the same ownership split. The+ marker may contribute to Pulse Intelligence activation reporting, but+ lifecycle code must not treat it as proof of installed agents, reported+ hosts, command connectivity, stale-agent freshness, or fleet-operation+ capability.The same isolation rule applies to report branding validation and renderingrequest assembly in `internal/api/system_settings.go` and`internal/api/metrics_reporting_handlers.go`: lifecycle-owned install,@@ -832,6 +953,45 @@ instead of lifecycle-local centered icon/text shells.valid for one authenticated session, but retained CSRF hashes are notinstall tokens, setup-token state, enrollment authority, or agent credentialcontinuity.+ The same isolation rule applies to the Pulse Intelligence agent capability+ manifest in `internal/agentcapabilities/manifest.go`: lifecycle surfaces may consume infrastructure+ setup routes advertised there, but manifest governance fields, MCP tool+ projection, shared external-tool projection helpers, shared schema-envelope+ helpers, and external-agent typed argument schemas remain API/AI-owned+ contract state rather than agent enrollment or installer semantics.+ Native Pulse Assistant provider seams and native tool-adapter names in+ shared `internal/api/ai_handler.go`, `internal/api/ai_handlers.go`,+ `internal/api/agent_profiles_tools.go`, `internal/api/router.go`, and+ `internal/api/router_routes_ai_relay.go`+ follow that same isolation rule: `MCP` remains an external protocol,+ manifest, and wire-schema term, while the in-app Assistant tool family is+ AI/runtime plus API-contract state. Lifecycle consumers must not infer+ enrollment, installer, command-websocket, or fleet-control authority from+ those native Assistant tool names, and must not reintroduce MCP-named native+ adapters to express lifecycle ownership.+ Pulse Intelligence operations-loop external-agent readiness in+ `internal/api/agent_resource_context.go` follows that same shared-helper+ split: the Pulse MCP token/scope check is AI/runtime plus API-contract+ ownership and must not become agent enrollment, installer, fleet-control, or+ command-websocket readiness.+ Patrol control completed/resolved proof and `patrolControlValueState`+ follow the shared `internal/telemetry` count-only classifier even when they+ are surfaced by `internal/api/agent_resource_context.go`; legacy+ `patrolAutonomy*` fields mirror those values only for compatibility, and+ lifecycle surfaces may observe them as operations-orientation evidence only.+ `proActivationOperationsLoopStarterCount` is only legacy entry-point+ orientation, and the legacy completed/resolved/value `proActivation*` status+ fields mirror Patrol control values as compatibility aliases, not as a second+ lifecycle signal. MCP readiness remains a separate+ external-agent handoff signal and is not a Patrol control proof input,+ agent install, registration, update, profile, command, or fleet-control+ completion.+ Approved Assistant tool execution exposed through the same shared+ `internal/api/router_routes_ai_relay.go` extension point follows that native+ naming rule: `AssistantToolExecutor` / `ApprovedAssistantToolExecutor` is the+ only current cross-repo fix-execution dependency. MCP remains an external+ protocol adapter term and must not reappear as a lifecycle command ownership+ or approved-fix execution dependency.The same shared-helper rule now covers SSO outbound discovery and metadata fetches plus credential-file loads in `internal/api/sso_outbound.go`, `internal/api/saml_service.go`, and `internal/api/oidc_service.go`: lifecycle-adjacent setup or auth work may depend on that shared trust boundary, but it must not fork a second HTTP client, redirect policy, file-read rule, or SSO entitlement interpretation inside lifecycle-local flows. SAML and multi-provider SSO availability remains API/security-owned Community-tier behavior, not an agent lifecycle setup gate.The same shared-helper rule also covers organization membership andcross-organization sharing transport in `internal/api/org_handlers.go` plus@@ -1292,6 +1452,18 @@ Agent` secondary handoff against the live setup wizard instead of relying## Current State+Denied Patrol investigation-fix approvals passing through shared+`internal/api/` handlers are adjacent AI-runtime/action-governance state only.+The `fix_rejected` finding outcome records that an operator declined a proposed+Patrol fix before execution; it must not be reinterpreted as agent enrollment,+install progress, fleet liveness, or an agent-command failure.++Patrol finding lifecycle payloads exposed through shared AI handlers, including+operator resolution-note fields, remain AI-runtime/API-contract vocabulary:+adjacent fleet and install surfaces may render the lifecycle state when another+surface supplies it, but they must not reinterpret it as install progress,+agent approval state, topology truth, or lifecycle-owned remediation policy.+Default-org token scoping and notification-settings fan-out on shared`internal/api/` handlers are likewise adjacent only: org-bound token denialfor the default org and instance-wide webhook allowlist propagation are@@ -1363,6 +1535,14 @@ unauthenticated and cacheable; the underlying capabilities keeptheir own auth scopes. Adding a capability is a deliberate "thisis part of the agent surface" commitment so the agent contractstays curated, not auto-derived from every internal endpoint.+The manifest's action mode and approval policy metadata are API/AI-owned+governance posture; lifecycle setup, enrollment, and fleet-control flows may+surface that metadata to agents but must not reinterpret it as install,+registration, heartbeat, update, or agent authority.+The same adjacency applies to manifest `inputSchema` metadata: typed tool+arguments help external agents call API-owned actions, but do not create a+lifecycle-owned setup command path, operator-state write contract, or+agent-control argument registry.`/api/agent/resource-context/{id}` is the agent-paradigm substrateendpoint: any agent (in-process Patrol/Assistant or external) reads@@ -1409,6 +1589,12 @@ The handlers were migrated from the platform-wide `APIError`envelope to the agent-stable `{"error", "message", "details"?}`shape so the substrate keeps a single envelope contract acrossread, write, and action capabilities.+The governed Patrol finding lifecycle tools advertised in the same+manifest (`acknowledge_finding`, `snooze_finding`, `dismiss_finding`,+`resolve_finding`) also return that agent-stable envelope for branchable+failures and declare their closed error-code set in the manifest. That is+an API/AI-runtime contract only: it does not create agent lifecycle state,+registration state, install state, or any new durable recovery artifact.Docker / Podman lifecycle execution extends that same action category only:the manifest advertises the `execute_action` substrate, while per-resourcecontainer capabilities, policy checks, action audit records, and terminal@@ -1748,6 +1934,94 @@ setup or router work touches shared `internal/api/` files, telemetry previewand install-ID reset routes must keep reusing the canonical system-settingstrust boundary and server-owned telemetry runtime instead of borrowing agentlifecycle proof or state ownership just because the same router surface moved.+Content-free Pulse Intelligence telemetry rollups under shared `internal/api/`+also remain system-settings, API-contract, and security/privacy ownership:+lifecycle-adjacent surfaces may observe that action-plan, approval,+approved-action-decision, rejected-action-decision, first-party workflow+starter, Pro activation starter, and external-agent usage is summarized, but+they must not reinterpret those anonymous counters as agent enrollment, install+success, recovery scope, or lifecycle state.+External-agent activity may be counted when a narrow API token satisfies the+specific manifest capability scope being called, including read-only+`monitoring:read` context usage. That signal remains API-owned collaboration+telemetry, not evidence that a command agent installed, checked in, or applied+fleet state.+External-agent/MCP readiness may also be true for a non-expired token that+covers any Pulse MCP-published capability scope, but that readiness remains a+collaboration-surface setup signal. Agent lifecycle code must not reinterpret+it as host-agent enrollment, command-agent reachability, or applied fleet+configuration. The manifest shape alone may prove that Pulse can publish the+external-agent contract, but it must not satisfy `externalAgentReady` on+`/api/agent/patrol-control/status` without a current token that covers at+least one Pulse MCP surface capability. The legacy+`/api/agent/operations-loop/status` URL is only a compatibility alias. Missing+external-agent readiness must not downgrade or block first-party Patrol control+completed/resolved proof; the legacy `verified_needs_mcp` state is retained+only as compatibility input and must not become new lifecycle or activation+output.+The Patrol-control status projection at+`GET /api/agent/patrol-control/status` follows the same ownership split. Its+stage labels, next action, Patrol issue evidence count, pending approval count,+contextual collaboration count, governed action count, verified outcome count,+Patrol control starter/completed/resolved proof exposed first through+`patrolControl*` fields and mirrored through `patrolAutonomy*` compatibility+fields,+`proActivationOperationsLoopStarterCount` as legacy entry-point orientation,+legacy completed/resolved/value `proActivation*` aliases, and optional+external-agent readiness+are content-free Pulse Intelligence collaboration signals; lifecycle code must+not reinterpret them as installed-agent proof, command-agent heartbeat,+installer progress, profile convergence, or fleet-control authority.+When that projection lets an aggregate active Patrol finding or pending approval+outrank older completed/resolved loop proof, the result is still operator+orientation only; it is not host-agent liveness, install health, or command+authorization evidence.+The same route may use action lifecycle events to notice recent loop activity,+but its governance and verification counts remain action-governance signals:+`governedActionCount` requires approved or rejected governed-action evidence,+`approvedDecisionCount` and `rejectedDecisionCount` expose that split without+identifiers, and `verifiedOutcomeCount` requires an approved governed action+with verified post-action evidence. Agent lifecycle surfaces must not satisfy+those stages from generic `executing`, `completed`, or `failed` command-agent+state, and must not reinterpret a rejected-only no-execution terminal decision+as command-agent success or failure.+The same verified-outcome predicate backs outbound Pulse Intelligence+approved-success telemetry: a completed action result is not lifecycle proof+unless the approved action also has `VerificationOutcome.Status=verified` or a+canonical verification result that ran and succeeded. Agent lifecycle surfaces+must not count host-agent command completion, installer success, or generic+execution success as Patrol control resolved-loop proof.+The route's four-step operator rollup follows the same boundary: governance+step counts may represent pending approvals before a decision or+approved/rejected decision evidence after one exists, while verification step+counts may represent verified outcomes or terminal rejected decisions. Optional+MCP readiness stays in `externalAgentReady`, not in the operator step list.+Agent lifecycle surfaces must not read those step counts as host-agent+heartbeat, command-agent install state, or fleet-control authority.+Approved action decision telemetry may use action lifecycle events or approved+approval records as its API-owned proof source, but the exported value remains+an anonymous approve/reject journey counter. Agent-lifecycle surfaces must not+read that rollup as command dispatch, command-agent reachability, profile+convergence, install success, or fleet lifecycle state.+Approved execution attempt telemetry may use action lifecycle events as its+API-owned proof source, but the exported value remains an anonymous operations+loop counter. Agent-lifecycle surfaces must not treat that rollup as command+agent heartbeat, installation proof, profile convergence, or fleet lifecycle+state.+Approved action success telemetry may also derive from the same governed action+audit stream, but only as a content-free count of approved actions that reached+completed state with a successful result. The existing approved execution+counter remains attempt-based for compatibility; the success counter must not+export resource identifiers, actor identifiers, command text, command output,+verification details, or host-agent state.+The external-agent recent-use bit is backed by content-free authenticated+agent/MCP route activity for manifest-capable API tokens; it is not an agent+lifecycle heartbeat, install proof, or generic token-last-used proxy.+The MCP adapter recent-use bit is narrower adapter-origin telemetry for+`pulse-mcp` requests on that same shared agent surface. It may distinguish MCP+adapter collaboration from direct external-agent API collaboration, but agent+lifecycle surfaces must not treat it as evidence that `pulse-agent` installed,+checked in, accepted remote config, or executed a command.That same shared `internal/api/ai_handlers.go` dependency also now assumesPatrol-specific settings and status expansions stay Patrol-owned. When sharedAI handlers add split scoped-trigger fields, recency labels, or trigger-statediff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 2e37b5415a..ff6a7a4c9d 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -9,51 +9,911 @@"contract_file": "docs/release-control/v6/internal/subsystems/ai-runtime.md","status_file": "docs/release-control/v6/internal/status.json","registry_file": "docs/release-control/v6/internal/subsystems/registry.json",- "dependency_subsystem_ids": ["api-contracts", "cloud-paid", "frontend-primitives"]+ "dependency_subsystem_ids": [+ "api-contracts",+ "cloud-paid",+ "frontend-primitives"+ ]}```## Purpose-Own Pulse Assistant and Patrol backend runtime behavior, AI orchestration,-runtime cost control, shared AI transport surfaces, and browser-visible-Assistant transcript actions that define what visible operator/model text can-leave the transcript without exposing hidden provider/tool metadata.+Own the Pulse Intelligence Core: canonical context, governed actions, safety+gates, approval state, action audit, and verification. That core backs Pulse+Patrol as the primary built-in operator that watches, investigates, acts within+the chosen Patrol mode, verifies outcomes, and records what happened. Pulse+Assistant is the contextual+explanation, approval, and handoff access path over that same work, while the+Pulse MCP adapter is the external-agent access path over canonical API+contracts. The subsystem also owns AI orchestration, runtime cost control,+shared AI transport surfaces, and browser-visible Assistant transcript actions+that define what visible operator/model text can leave the transcript without+exposing hidden provider/tool metadata.+When backend Patrol summaries or Assistant handoffs expose run coverage to the+browser, they translate internal full-run, scoped-run, and verification+precision into plain operator check language rather than activation-loop,+proof-strip, or scoped/full-run jargon.+Coverage warnings must stay action-oriented: they may tell the operator to run+Patrol to check everything, but must not ask for a "full issue list" or otherwise+expose backend full-run vocabulary as the product instruction.+Patrol model-facing system prompts must derive the active control-mode block+from the effective `patrol_autonomy_level`, after license and full-mode-lock+clamping, so Watch only, Ask first, Safe auto-fix, and Autopilot give the model+the same investigate, approval, execution, and verification boundaries enforced+by the orchestrator. Prompt copy must not fall back to the legacy+`patrol_auto_fix` boolean or the retired "observe only" / "auto-fix mode"+framing.+Patrol finding storage must consolidate equivalent active storage-capacity+siblings before they reach browser surfaces: a broader storage risk and a+generic usage/capacity finding for the same normalized storage identity are one+operator issue, while distinct backup, health, and pool-vs-device findings+remain separate. This consolidation belongs in the finding store, not the+frontend row renderer.++The public Pulse Intelligence overview is a projection of those runtime+contracts, not a second Assistant tool inventory. It must point readers at the+registry-owned Assistant tool governance and the manifest-owned external-agent+capabilities instead of carrying hand-maintained tool tables.+It is also the public product-language contract for paid Patrol capabilities:+Pro positioning must describe hands-on Patrol modes, issue investigation,+governed fixes, verified outcomes, and history. Public docs and generated+commercial copy must not reintroduce proof-first activation-loop framing or the+retired `Patrol Control Levels`, `Patrol control`, and `Alert investigation`+labels as the visible paid story. API fields and route markers may retain+compatibility names such as `autonomy_level` only when the surrounding copy+plainly calls the operator-facing choice `Patrol mode`.+Its Core/Patrol/Assistant/MCP relationship block must be rendered from+`PulseIntelligenceOverviewMarkdown(Manifest.SurfaceContract)` rather than+maintained as prose separate from the agent capabilities manifest.+Reusable workflow starters are manifest-owned `workflowPrompts` metadata+derived from the shared Pulse Intelligence workflow-prompt core. Prompt names,+Assistant display labels, presentation kind hints, descriptions, arguments,+availability, and rendered text belong to that shared catalogue. Pulse+Assistant-compatible starters, frontend manifest clients, MCP `prompts/list`,+and generated docs consume that catalogue instead of maintaining per-surface+prompt lists or browser-local starter copy.+The shared catalogue includes the global `pulse_operations_loop` workflow+starter for the Patrol mode operations loop: it is projected only when the+manifest has fleet context, resource context, findings, governed+plan/decide/execute action, and finding resolution capabilities. Its rendered+prompt must keep the operator in an approve-or-reject loop with execution only+after policy allows it and verification before finding resolution, while the+status schema treats Patrol mode starter evidence only as entry-point+orientation, Patrol mode completed-loop evidence as aggregate terminal+approve/reject proof, and Patrol mode resolved-loop evidence only as+aggregate approved-and-verified outcome proof, not Assistant transcript, Patrol+finding identity, approval payload, action command, or MCP setup detail.+`pulse_patrol`, the current paid `patrol_control` marker, the legacy+`patrol_autonomy` marker, and the legacy `pulse_pro_activation` alias all+contribute to first-party Patrol mode starter evidence;+`proActivationOperationsLoopStarterCount` is a compatibility field retained+for older external-agent clients, while primary clients must read+`patrolControlOperationsLoopStarterCount`. The other `proActivation*` status+fields are compatibility aliases for the same first-party Patrol mode+journey rather than a separate AI-runtime loop, and manifest descriptions must+not describe them as a Pro activation journey.+The same status schema must expose the aggregate Patrol mode value state as+a content-safe enum so Assistant-compatible and MCP-facing agents can branch+without reverse-engineering counts. `governed_decision_recorded` is a safe+terminal decision state, not proven operations value; `verified` is the only+completed first-party value state and requires the approved, verified outcome+plus recorded action history. MCP/external-agent readiness remains optional+external-agent setup context.+Native Assistant workflow starters in `frontend-modern/src/components/AI/Chat/`+are a browser projection of that same catalogue, not a second prompt registry:+they may decide which manifest-owned prompt is contextually usable, but display+labels and rendered prompt text must come from shared manifest metadata and the+shared backend renderer on+`POST /api/ai/workflow-prompts/render`.## Canonical Files1. `internal/ai/`+ 1a. `cmd/pulse-mcp/main.go`+ 1b. `cmd/pulse-mcp/README.md`+ 1c. `internal/agentcapabilities/`+ 1d. `scripts/generate-pulse-intelligence-docs.go`2. `internal/config/ai.go`3. `internal/api/ai_handler.go`4. `internal/api/ai_handlers.go`5. `internal/api/ai_hosted_runtime.go`6. `internal/api/ai_intelligence_handlers.go`-7. `frontend-modern/src/api/ai.ts`-8. `frontend-modern/src/api/aiChat.ts`+7. `frontend-modern/src/api/agentCapabilities.ts`+ 7a. `frontend-modern/src/api/generated/agentCapabilities.ts`+8. `frontend-modern/src/api/ai.ts`+ 8a. `frontend-modern/src/api/aiChat.ts`9. `frontend-modern/src/api/patrol.ts`10. `frontend-modern/src/components/AI/AICostDashboard.tsx`-11. `frontend-modern/src/components/AI/Chat/`-12. `frontend-modern/src/utils/aiChatPresentation.ts`-13. `frontend-modern/src/utils/aiControlLevelPresentation.ts`-14. `frontend-modern/src/utils/aiCostPresentation.ts`-15. `frontend-modern/src/utils/aiProviderHealthPresentation.ts`-16. `frontend-modern/src/utils/aiProviderPresentation.ts`-17. `frontend-modern/src/utils/textPresentation.ts`-18. `frontend-modern/src/stores/aiRuntimeState.ts`-19. `frontend-modern/src/stores/aiChat.ts`-20. `docs/AI.md`-21. `pkg/aicontracts/investigation.go`+11. `frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx`+12. `frontend-modern/src/components/AI/Chat/`+13. `frontend-modern/src/utils/aiChatPresentation.ts`+14. `frontend-modern/src/utils/aiControlLevelPresentation.ts`+15. `frontend-modern/src/utils/aiCostPresentation.ts`+16. `frontend-modern/src/utils/aiProviderHealthPresentation.ts`+17. `frontend-modern/src/utils/aiProviderPresentation.ts`+18. `frontend-modern/src/utils/textPresentation.ts`+19. `frontend-modern/src/stores/aiRuntimeState.ts`+20. `frontend-modern/src/stores/aiChat.ts`+21. `docs/AI.md`+22. `pkg/aicontracts/investigation.go`+23. `pkg/aicontracts/orchestrator_deps.go`+24. `pkg/aicontracts/fix_execution.go`+25. `pkg/extensions/ai_autofix.go`## Shared Boundaries-1. `frontend-modern/src/api/ai.ts` shared with `api-contracts`: the AI frontend client is both an AI runtime control surface and a canonical API payload contract boundary.-2. `frontend-modern/src/api/patrol.ts` shared with `api-contracts`: the Patrol frontend client is both an AI runtime control surface and a canonical API payload contract boundary.-3. `frontend-modern/src/stores/aiChat.ts` shared with `frontend-primitives`: the assistant drawer and session store is both an AI runtime control surface and a canonical app-shell presentation boundary.-4. `internal/api/ai_handler.go` shared with `api-contracts`: Pulse Assistant handlers are both an AI runtime control surface and a canonical API payload contract boundary.-5. `internal/api/ai_handlers.go` shared with `api-contracts`: AI settings and remediation handlers are both an AI runtime control surface and a canonical API payload contract boundary.-6. `internal/api/ai_intelligence_handlers.go` shared with `api-contracts`: AI intelligence handlers are both an AI runtime control surface and a canonical API payload contract boundary.+1. `cmd/pulse-mcp/main.go` shared with `api-contracts`: the Pulse MCP adapter runtime is both an AI runtime surface for external-agent access to Pulse Intelligence and a canonical API contract projection over the agent capabilities manifest and Pulse MCP surface tool contract.+2. `cmd/pulse-mcp/README.md` shared with `api-contracts`: the Pulse MCP adapter guide is both an AI runtime surface for external-agent access to Pulse Intelligence and a canonical API contract projection over the agent capabilities manifest.+3. `frontend-modern/src/api/agentCapabilities.ts` shared with `api-contracts`: the agent capabilities frontend client is both the Pulse Intelligence external-agent manifest consumer and a canonical API payload contract boundary.+ Its presentation sanitizer may translate legacy Pro activation manifest+ descriptions into Patrol mode outcome/status language, but it must not+ reintroduce proof-first or activation-loop copy into Assistant, Patrol, or+ external-agent onboarding surfaces.+4. `frontend-modern/src/api/ai.ts` shared with `api-contracts`: the AI frontend client is both an AI runtime control surface and a canonical API payload contract boundary.+5. `frontend-modern/src/api/aiChat.ts` shared with `api-contracts`: the Assistant chat frontend client is both the first-party Assistant transport surface and a canonical API payload contract boundary.+6. `frontend-modern/src/api/generated/agentCapabilities.ts` shared with `api-contracts`: the generated agent capabilities frontend types are both the Pulse Intelligence manifest TypeScript projection and a canonical API payload contract boundary.+7. `frontend-modern/src/api/patrol.ts` shared with `api-contracts`: the Patrol frontend client is both an AI runtime control surface and a canonical API payload contract boundary.+8. `frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx` shared with `api-contracts`, `frontend-primitives`: the External agents settings panel is the optional settings-shell projection of Pulse MCP onboarding, the AI runtime connected-agent onboarding surface, and a presentation consumer of the shared agent capabilities frontend client.+ Its default copy must frame connected clients as optional connector access+ to Pulse context and Patrol work, with Patrol as the operator that watches,+ acts within Patrol mode, asks for approval when required, verifies outcomes,+ and records history. The normal Assistant settings view must keep setup+ mechanics behind a `Show connector setup` disclosure, with direct setup+ links opening that disclosure automatically. Default copy must make clear+ that connected tools do not get separate powers. Tool-contract posture and manifest facts are+ client-builder diagnostics and must stay behind a Developer details+ disclosure rather than beside the normal external-agent setup steps; posture+ and policy context belongs under Patrol access model, while prompt, scope,+ failure-code, and tool inventories must sit one level deeper behind Live+ manifest details using user-facing labels such as Agent starting points and+ Agent capabilities.+ Direct links to+ `/settings/pulse-intelligence/assistant#external-agent-setup` must focus this+ External agents panel after the Assistant settings layout settles,+ because connected agents are optional access to Patrol work and should not+ strand users at the generic token inventory. Legacy+ `/settings/security/api#external-agent-setup` and+ `/settings/security/api#pulse-mcp-setup` links must remain accepted and+ redirect to the canonical Pulse Intelligence Assistant route.+ The `Choose Patrol mode` handoff must target the Patrol operator surface at+ `/patrol#patrol-control`, where the mode is configured, while API+ Access remains the token and external-client setup surface. The expanded+ setup checklist owns that handoff as Step 1; the panel header must not repeat+ a second visible `Choose Patrol mode` action while setup is open.+ The visible full-surface token preset for that setup is `Patrol external agent`;+ `pulse_intelligence_agent` remains only the compatibility preset id used by+ the route and token model.+9. `frontend-modern/src/stores/aiChat.ts` shared with `frontend-primitives`: the assistant drawer and session store is both an AI runtime control surface and a canonical app-shell presentation boundary.+10. `internal/agentcapabilities/action_target.go` shared with `api-contracts`: the Pulse Intelligence governed action target type and resource-to-action-target mapping vocabulary are both the Assistant approval/runtime routing contract and the canonical API/agent target contract for governed actions.+11. `internal/agentcapabilities/control_level.go` shared with `api-contracts`: the Pulse Intelligence control-level vocabulary and control-tool availability predicate are both the Assistant runtime gating contract and the canonical API/agent permission posture for governed action tools.+12. `internal/agentcapabilities/errors.go` shared with `api-contracts`: the Pulse Intelligence agent error envelope is both the canonical API failure payload contract and the AI runtime adapter error-parsing contract for Assistant and external-agent surfaces.+13. `internal/agentcapabilities/events.go` shared with `api-contracts`: the Pulse Intelligence event vocabulary is both the canonical API SSE event contract and the AI runtime adapter notification contract for Assistant and external-agent surfaces.+14. `internal/agentcapabilities/governance_prompt.go` shared with `api-contracts`: the Pulse Intelligence surface-affordance-resolved model-facing operating-instruction, tool-governance prompt, reusable provider-tool governance description, Assistant-native offered-tool filtering, and Assistant-native interactive question-tool governance projections are both the Assistant system-prompt governance section and the shared API/agent vocabulary for action mode, approval posture, MCP affordance advertisement, and non-registry interaction-tool boundaries.+15. `internal/agentcapabilities/http.go` shared with `api-contracts`: the Pulse Intelligence agent HTTP substrate is both the API capabilities invocation contract and the shared AI runtime adapter execution primitive for MCP and reference agent clients.+16. `internal/agentcapabilities/manifest.go` shared with `api-contracts`: the canonical Pulse Intelligence agent capabilities manifest declaration, including capability display titles, manifest-owned finding lifecycle schemas, manifest-owned governed action schemas and routes, manifest-owned external-adapter surface tool contracts, and manifest-owned structured output schemas, is both the API discovery payload source and the AI runtime projection contract for Pulse Assistant and MCP-facing agent tools.+17. `internal/agentcapabilities/markdown.go` shared with `api-contracts`: the Pulse Intelligence manifest Markdown projection, including manifest-owned capability titles, surface-filtered Pulse MCP tool/error inventories, and prompt labels, is both the canonical API/agent documentation projection and the AI runtime onboarding projection for Assistant-compatible external-agent surfaces.+18. `internal/agentcapabilities/mcp.go` shared with `api-contracts`: the Pulse Intelligence MCP protocol version, JSON-RPC, method dispatch, method payload, surface-tool-contract-gated initialize operating-instruction and capability advertisement payload, manifest surface-filtered tools/list and tools/call execution bridge, manifest surface-gated resources/list and resources/read bridge, manifest-owned and surface-affordance-gated workflow prompt projection, protocol wire aliases, resource and prompt handler gates, and notification projection collectively define the external-agent adapter wire contract over the shared Pulse Intelligence tool core; MCP initialize, tools/call execution, resource list/read projection, and prompt list/get projection must enter through manifest-owned surface and workflow-prompt contracts so raw capability slices cannot bypass the published external-adapter contract.+19. `internal/agentcapabilities/mcp_adapter.go` shared with `api-contracts`: the Pulse MCP adapter setup contract defaults and normalization are both the canonical API manifest setup projection and the AI runtime onboarding contract for Assistant-compatible external-agent surfaces.+20. `internal/agentcapabilities/projection.go` shared with `api-contracts`: the agent capability external-tool projection helper, normalized manifest-owned surface tool contract resolution and tools-affordance gating, manifest-owned resource-context route and argument vocabulary, operator-state capability and route vocabulary, finding workflow capability and lifecycle argument vocabulary including resolution and dismissal notes, governed action capability, route, and argument vocabulary, manifest-owned tool title and outputSchema projection, structured Pulse capability _meta, and shared tool behavior hints are both the canonical API manifest projection contract and the AI runtime adapter projection for Pulse Assistant and MCP-facing agent tools, with MCP annotation and metadata wire names confined to adapter-edge aliases.+21. `internal/agentcapabilities/provider_tool_artifacts.go` shared with `api-contracts`: the provider tool-call artifact detector and streaming tool-name prefix splitter are both the Assistant stream-sanitization boundary and the shared external-adapter leak guard for provider-native tool-call markup that escaped the structured channel.+22. `internal/agentcapabilities/schema.go` shared with `api-contracts`: the agent capability input schema contract is both the canonical API manifest schema envelope and the AI runtime structured tool-schema, governance-aware provider-projection with neutral behavior hints and Pulse governance metadata, offered-tool governance extraction for Assistant prompt policy, manifest-affordance-gated Assistant provider-surface composition, manifest raw-schema to Assistant provider-schema projection for capability tools, legacy native Assistant utility provider aliases and schemas, provider-call normalization, provider-result context projection, Assistant-native interaction provider-tool declaration, and live Assistant execution-normalization contract for Pulse Assistant and MCP-facing agent tools.+23. `internal/agentcapabilities/scopes.go` shared with `api-contracts`: the manifest-derived required-scope summary is both the canonical API/agent token guidance contract and the AI runtime adapter startup/onboarding contract for Assistant-compatible external-agent surfaces.+24. `internal/agentcapabilities/sse.go` shared with `api-contracts`: the Pulse Intelligence SSE subscription transport and record parser are both the canonical API event-stream consumption contract and the AI runtime adapter push bridge contract for MCP and reference agent clients.+25. `internal/agentcapabilities/surface_contract.go` shared with `api-contracts`: the Pulse Intelligence operator-surface affordance contract, shared surface-affordance, surface-tool identity, Assistant surface tool filtering, normalized external surface tool resolver, surface lookup, affordance labels, and manifest-published external-adapter surface tool allowlist projection are both the canonical API manifest surface model and the AI runtime prompt and onboarding guardrail for Assistant and MCP-facing surfaces.+26. `internal/agentcapabilities/text_tool_invocation.go` shared with `api-contracts`: the Pulse Intelligence text tool invocation parser, internal approval argument, and current_resource handle vocabulary are both the Assistant approved-action execution projection and the shared tool-call params bridge for governed Pulse Intelligence tool calls, with MCP tools/call compatibility staying at the adapter edge.+27. `internal/agentcapabilities/tool_call.go` shared with `api-contracts`: the Pulse Intelligence shared tool-call params, normalization, validation, direct registry preparation, registry-entrypoint failure result helpers, and provider/registry tool-call safety classification are both the native Assistant execution/FSM contract and the canonical API/agent tools/call compatibility contract for governed Pulse Intelligence tool calls.+28. `internal/agentcapabilities/tool_execution.go` shared with `api-contracts`: the Pulse Intelligence neutral capability tool HTTP execution helper and direct tool execution output/error mapper are both the Assistant-native direct execution contract and the canonical API/agent request/response execution contract, with MCP adapters consuming the neutral helpers only after the shared MCP manifest-surface execution bridge has applied the published surface tool contract.+29. `internal/agentcapabilities/tool_marker.go` shared with `api-contracts`: the Pulse Intelligence Assistant tool marker vocabulary and approval/policy marker parser are both the Assistant structured tool-result compatibility contract and the canonical API/agent branching contract for governed tool outcomes.+30. `internal/agentcapabilities/tool_names.go` shared with `api-contracts`: the Pulse Intelligence registry tool-name vocabulary is both the native Assistant execution/display contract and the canonical API/agent tool identity contract for MCP-facing external-agent adapters.+31. `internal/agentcapabilities/tool_response.go` shared with `api-contracts`: the shared tool response envelope, tool error-code vocabulary, and tool-result error-code and verification evidence parsers are both the Assistant structured tool-result contract and the canonical API/agent branching contract for Pulse Intelligence tool failures, recovery tracking, and write self-verification.+32. `internal/agentcapabilities/tool_result.go` shared with `api-contracts`: the Pulse Intelligence shared tool-result content/result envelope, structuredContent projection, result constructors, HTTP response-to-result mapping, text projection, and result interpretation helpers are both the Assistant registry result contract and the canonical API/agent result projection contract for governed tool outcomes.+33. `internal/agentcapabilities/types.go` shared with `api-contracts`: the agent capabilities manifest wire type, manifest-owned external-adapter surface tool contract field, capability display title and structured output schema fields, approval-policy vocabulary, capability governance normalization, and tool-governance descriptor shape are both the canonical API payload contract and the AI runtime projection contract for Pulse Assistant and MCP-facing agent tools.+34. `internal/agentcapabilities/workflow_prompt.go` shared with `api-contracts`: the Pulse Intelligence workflow prompt catalogue, manifest-owned `workflowPrompts` projection, MCP prompt title projection, presentation kind hints, shared resource-context and finding argument vocabulary, Patrol issue-handling capability gating, argument validation, and manifest-gated shared prompt rendering rules are both the AI runtime starter contract for Assistant-compatible surfaces and the canonical API/agent prompt projection contract for MCP-facing clients.+35. `internal/api/ai_handler.go` shared with `api-contracts`: Pulse Assistant handlers are both an AI runtime control surface and a canonical API payload contract boundary.+36. `internal/api/ai_handlers.go` shared with `api-contracts`: AI settings and remediation handlers are both an AI runtime control surface and a canonical API payload contract boundary.+37. `internal/api/ai_intelligence_handlers.go` shared with `api-contracts`: AI intelligence handlers are both an AI runtime control surface and a canonical API payload contract boundary.+38. `pkg/aicontracts/fix_execution.go` shared with `api-contracts`: the public approved-fix execution contract is both an AI runtime approved-action boundary and a canonical API dependency contract for Patrol and enterprise auto-fix binders.+39. `pkg/aicontracts/investigation.go` shared with `api-contracts`: the public Patrol investigation record and finding contract is both an AI runtime handoff boundary and a canonical API payload contract for Patrol, Assistant, unified findings, persistence, and audit surfaces.+40. `pkg/aicontracts/orchestrator_deps.go` shared with `api-contracts`: the public investigation orchestrator dependency contract is both an AI runtime handoff boundary and a canonical API payload contract for Assistant and Patrol tool-call history.+41. `pkg/extensions/ai_autofix.go` shared with `api-contracts`: the enterprise auto-fix extension dependency seam is both an AI runtime approved-action boundary and a canonical API extension contract over Assistant and Patrol execution dependencies.+42. `scripts/generate-pulse-intelligence-docs.go` shared with `api-contracts`: the Pulse Intelligence manifest docs generator is both an AI runtime docs/onboarding projection and a canonical API contract projection over the agent capabilities manifest and Pulse MCP surface tool contract.++The shared agent-capabilities manifest also owns the runtime surface contract:+the manifest wire type and generated frontend projection must name Pulse+Intelligence Core as the shared core, Pulse Patrol as the primary built-in+operator, and Pulse Assistant plus Pulse MCP as contextual and external-agent+access paths over the same governed capabilities. Frontend copy, MCP docs, and+Assistant onboarding must consume that relationship from the manifest rather+than carrying parallel surface tables.+The same manifest owns Pulse MCP adapter setup facts: server name, command,+base URL flag/default, token environment variable, and supported client config+families. Settings, README generation, and adapter onboarding may present those+facts for operators, but they must not maintain separate MCP setup constants.+The in-app setup surface for those facts belongs under Pulse Intelligence+settings because Pulse MCP is an external-agent access path over governed+Patrol actions. API Access may be linked for scoped-token creation, but it must+not host the external-agent setup walkthrough.+Pulse Intelligence telemetry readiness for the external-agent surface follows+that same manifest surface boundary: a non-expired API token covering any+Pulse MCP-published capability scope is enough to mark MCP/external-agent+readiness, while route-level usage still comes only from authenticated+capability activity markers. Readiness must not be tied to the full manifest+scope set because least-privilege external-agent setups are supported.+The `pulse-mcp` adapter marks its own capability requests with the content-free+`X-Pulse-Agent-Surface: pulse_mcp` header so telemetry can distinguish adapter+use from direct external-agent API use without recording prompts, payloads,+route parameters, token identity, or resource identifiers.+Successful workflow starter rendering follows the same content-free boundary:+native Assistant render calls, first-party paid Patrol autonomy handoffs, and+Pulse MCP `prompts/get` calls may persist only the manifest prompt name, coarse+surface (`pulse_assistant`, `pulse_patrol`, `patrol_autonomy`, legacy+`pulse_pro_activation`, or `pulse_mcp`), and timestamp. The first-party+activation marker is `POST /api/ai/workflow-prompts/activity`; it is an+authenticated `ai:chat` route for app-owned surfaces such as the paid Patrol+autonomy handoff into Patrol, validates prompt names against the manifest+workflow prompt catalogue, accepts only first-party surfaces, and must remain a+starter marker rather than proof that Assistant context, governed action+approval, execution, verification, or finding resolution occurred.+`pulse_pro_activation` exists only as a legacy alias for older Pro+success/current-plan entry points; current paid handoffs use `patrol_autonomy`+and neither surface adds a new prompt, tool, model surface, or operations-loop+completion signal. Prompt arguments, rendered text, resource+IDs, finding IDs, session IDs, token identity, request bodies, and model output+must not enter workflow starter activity history or outbound telemetry.+Runtime model-facing instructions must consume that same contract as data.+`BuildPulseAssistantOperatingInstructions` identifies Pulse Assistant as the+native in-app surface over Pulse Intelligence Core, while manifest-backed MCP+initialize responses identify Pulse MCP as the external-agent adapter over the+same core and Pulse Patrol as the primary built-in operator. That copy belongs in+`internal/agentcapabilities`; Assistant prompts, MCP initialize payloads, and+future agent surfaces must not re-create local Assistant/MCP/Patrol relationship+wording outside the manifest-owned surface contract.+Surface tool summaries follow the same shared-core rule. The native Assistant+runtime exposes provider tools through `ProjectPulseAssistantProviderTools`,+which applies the manifest-owned Pulse Assistant surface affordances before+registry or native interaction tools reach model requests, and exposes+`PulseToolExecutor.AssistantSurfaceToolContract`, which projects the same+runtime-available provider tools through `ProjectPulseAssistantSurfaceToolContract`;+external-agent adapters project request/response manifest capabilities through+`ProjectManifestSurfaceToolContract` and publish the static external-adapter+inventory on `Manifest.SurfaceToolContracts`. Missing external-adapter+`surfaceToolContracts` entries fail closed rather than inferring tools from raw+manifest capabilities; static surface-tool affordance metadata may narrow an+external operator surface, but must not re-enable a disabled surface affordance+or keep tool/capability names when the effective `tools` affordance is false.+Disabled Assistant affordances likewise fail closed rather than allowing runtime+registry availability to re-enable provider tools.+Assistant prompt fallback governance follows that same contract: when no live+executor-owned offered-tool manifest is available, registry-owned fallback+governance must enter through+`CanonicalToolGovernanceForManifestSurface(ControlLevelControlled, CanonicalManifest(), SurfaceIDPulseAssistant)`,+and the chat prompt fallback must derive explicit offered tool names from+`ManifestSurfaceAffordances` so registry tools and the native `pulse_question`+interaction tool cannot be reintroduced by nil offered-tool semantics.+Assistant registry tools, Assistant-native interaction tools, and MCP manifest+capabilities must stay explicit buckets in that contract so Pulse can support+both surfaces without duplicating tool logic or+implying MCP replaces the in-app Assistant.+Frontend consumers must import the generated `SurfaceToolContract` shape from+the shared agent-capabilities client rather than maintaining a local copy.+Patrol work contract availability for browser surfaces is also a shared+agent-capabilities-client verdict: consumers must derive the Pulse MCP contract+from the normalized MCP adapter setup, the manifest-owned+`pulse_operations_loop` workflow prompt, and the Pulse MCP surface tool contract+through `frontend-modern/src/api/agentCapabilities.ts`; feature shells must not+hard-code MCP contract availability or infer it from raw manifest capabilities.+Runtime external-agent readiness is stricter:+`GET /api/agent/patrol-control/status` may mark `externalAgentReady` only when+that contract is available and a single non-expired API token covers every+scope required by the published Pulse MCP Patrol work capability set.+`GET /api/agent/operations-loop/status` remains only a compatibility alias for+older clients. That shared Patrol work tool set starts with+`get_patrol_control_status`, the count-only+`GET /api/agent/patrol-control/status` orientation read, then uses the same+fleet-context, resource-context, finding, governed action, and finding+resolution tools as the rest of the governed issue-handling flow.+`get_operations_loop_status` and `/api/agent/operations-loop/status` are+compatibility aliases, not primary capability names. AI runtime prompts, MCP+readiness helpers, and frontend presentation helpers must not carry separate+Patrol work inventories. The native Patrol work surface may display that same+status projection, but it must fetch it through the shared agent-capabilities+frontend client so Assistant, MCP, and native UI stay on the same Patrol work+contract. The manifest-owned status schema must describe governed counts as+decision-backed, split approved and rejected decision counts explicitly, and+describe verified counts as approved-action-backed. The same schema now exposes+content-free Patrol work starter counts for the total flow and the+Assistant, Patrol mode, older-client compatibility field, and Pulse MCP+source surfaces, an Assistant step count for contextual Assistant or+external-agent collaboration, plus a content-free Patrol mode+completed-loop count derived when Patrol mode starter evidence, Patrol+issue evidence, contextual collaboration, and either a rejected governed+decision or an approved governed decision with verified outcome proof coexist+in the same status window. It also exposes a stricter Patrol mode+resolved-loop count only when that status window has an approved governed+decision and verified outcome proof. The `proActivationOperationsLoopStarterCount`+field is retained only for older clients; primary clients must use+`patrolControlOperationsLoopStarterCount`. The legacy `patrolAutonomy*` and+`proActivation*` completed-loop, resolved-loop, and value-state fields mirror+the Patrol mode counts and value state for compatibility. AI runtime+surfaces may use those counts to show that a starter+was rendered or launched, that contextual collaboration occurred, or that the+first-party Patrol mode+loop reached terminal or resolved proof, but must not treat them as Assistant+transcript, approval payload, action command, resource identity, or+finding-resolution detail. External-agent prompts and MCP adapters may treat a+rejected-only decision as a terminal no-execution outcome, but approved+decisions must still continue through execution and verification before the+verified-outcome stage is complete.+Runtime Assistant availability remains an authenticated Assistant concern,+served by `GET /api/ai/assistant/surface-tools`, not a static fact in the+public agent-capabilities manifest. When the Pulse Assistant shell displays+live capability availability, it must load that authenticated endpoint through+`AIChatAPI.getAssistantSurfaceTools()` and format the posture through+`frontend-modern/src/api/agentCapabilities.ts`; the shell must not keep a local+registry-tool catalogue or reuse MCP manifest capability names as native+Assistant inventory. The External agents settings panel may show the+external Pulse MCP tool posture, but it must get the normalized static+`SurfaceToolContract` from `manifest.surfaceToolContracts` through+`getAgentManifestSurfaceToolContract(manifest, AGENT_SURFACE_ID_PULSE_MCP)`+and format it with `getAgentSurfaceToolPosturePresentation`;+external-adapter request/response filtering, including the `subscribe_events`+streaming exception and any capability omitted from the published Pulse MCP+surface allowlist, must be owned by the backend projection in+`ProjectManifestSurfaceToolContracts`; shared capability reads must use+`ResolveManifestSurfaceToolContract` and `ManifestSurfaceToolCapabilities` so+the normalized surface contract and the resolved `tools` affordance gate are+applied once. MCP initialize must also advertise the `tools` capability and+name "offered tools" in operating instructions only when that same published+surface tool contract resolves. MCP prompt support must similarly enter through+`MCPManifestSurfacePromptProjectionSupported`, which combines the target+surface's `prompts` affordance with the manifest-owned workflow prompt+catalogue before initialize or `prompts/list` advertises prompts, and through+`GetMCPPromptFromManifestSurface` before `prompts/get` renders any prompt. The+global `pulse_operations_loop` prompt is part of that same shared catalogue,+not a native Assistant-only starter: it must appear in Assistant and MCP only+when the manifest can support the full Patrol-to-Assistant-to-governed-action+flow, and it must guide contextual explanation, plan-first governed action,+approval or rejection only when the returned policy requires a decision,+policy-allowed execution, post-action verification, and finding resolution from+the same rendered prompt text. The rendered prompt must orient+first through `get_patrol_control_status` and re-read that status, resource+context, and findings before treating an outcome as verified. Successful render activity for+that starter is activation evidence for the Patrol issue-handling journey, not+proof of contextual collaboration, governed action execution, verification, or+finding resolution.+Native Assistant callers may request a preferred workflow prompt through safe+browser context, but the drawer must resolve that request against the+manifest-owned workflow prompt catalogue and render it through+`/api/ai/workflow-prompts/render`; it must not inline prompt templates or+silently append to an existing composer draft. Preferred workflow prompt+requests are one-shot browser seeds and must be cleared with the scoped handoff+payload after the first successful send.+The MCP `tools/call` execution+helper must+accept the manifest and surface id, apply the same affordance and surface-tool+allowlist used by `tools/list`, and only then delegate to neutral capability+HTTP execution; it must not accept a caller-supplied raw capability slice as the+MCP execution boundary. Frontend consumers may normalize a published+`surfaceToolContracts` entry for presentation, but must not infer MCP tools+from raw manifest capabilities when that entry is missing, and must not add a+Pulse-MCP-specific frontend helper alias around the generic surface resolver.+The generated Pulse MCP README follows the same rule: its surface-contract+block must be rendered by `MCPSurfaceContractMarkdown` from+`Manifest.SurfaceContract`, alongside the manifest-derived scope, tool, prompt,+and error-code inventories.+The public Pulse Intelligence overview follows the public-docs version of that+rule: the marked overview block in `docs/AI.md` must be rendered by+`PulseIntelligenceOverviewMarkdown` from the same manifest-owned+`SurfaceContract`, while surrounding product detail may remain human-authored.+The External agents settings panel follows the browser-facing version of+that same rule: its Pulse Intelligence Core, Patrol, Assistant, and MCP surface+summary must be projected from `/api/agent/capabilities.surfaceContract` through+`frontend-modern/src/api/agentCapabilities.ts`, not maintained as panel-local+copy; surface affordance badges are part of that same manifest projection. Its+capability-publication wording must describe published manifest-owned surface+contracts, not raw backend capability rows, so the panel does not imply that+adding a raw capability automatically exposes it to Pulse MCP.+Its external-agent recovery summary must also be manifest-backed: stable+failure-code chips or summaries may be rendered for setup ergonomics, but they+must derive from capability `errorCodes` through the shared frontend manifest+client rather than a panel-local recovery-code list.+External-agent token setup copy in that panel must route operators back to the+API Access token creation surface and the manifest-derived `Pulse Intelligence+agent` preset instead of carrying MCP-local token minting logic or a+component-local required-scope list.+## Extension Points+Pulse Intelligence presents Patrol as the primary first-party operations+surface. Pulse Assistant is the in-app contextual explanation, approval-card,+governed-action, verification, and handoff access path over Patrol work.+`cmd/pulse-mcp/` is the external-agent adapter for MCP-speaking clients. The+adapter must stay thin: it fetches `/api/agent/capabilities`, projects that+canonical manifest as MCP tools, and forwards calls to the declared API routes.+The shared `MCPManifestToolServer` must therefore consume the manifest as a+unit, not only a detached capability slice, so initialize instructions, tool+projection, resources, prompts, notifications, and future manifest-backed+surface metadata remain coupled to the same discovery document. It must resolve+the target surface's affordance contract before initialize advertisement and+before tool, resource, and prompt handlers run; raw manifest capabilities,+workflow prompts, or context routes are availability inputs only after the+surface contract allows that affordance.+When an adapter renders a manifest prompt locally, it may notify Pulse through+the authenticated `POST /api/agent/workflow-prompt-activity` marker endpoint+only after the prompt render succeeds. That marker route accepts manifest-owned+prompt names only, requires the token to cover `monitoring:read`, normalizes+`X-Pulse-Agent-Surface: pulse_mcp` into the Pulse MCP surface, and records no+prompt arguments, rendered text, resources, findings, token identity, or+request payload.+`scripts/generate-pulse-intelligence-docs.go` is part of that coupling: it+must update the MCP README's Pulse Intelligence surface contract and the public+`docs/AI.md` overview from the manifest instead of leaving hand-written+Core/Patrol/Assistant/MCP relationship prose beside generated inventories.+Public AI docs may describe anonymous outbound telemetry only as counts,+feature flags, and coarse Patrol control and governed Pulse Intelligence+operations adoption flags and counters.+They must keep prompts, chat messages, command text, action output, token+values, resource identifiers, and hostnames explicitly outside that telemetry+scope.+Governed-operation workflow starter counts may appear in that outbound telemetry+only as 30-day aggregate counts for the canonical `pulse_operations_loop`+prompt, split by total, native Assistant, first-party Patrol, and Pulse MCP surfaces. Those counts+may make `pulse_intelligence_loop_active_30d` true because the operator entered+the guided journey, but they must not satisfy contextual-collaboration,+complete-loop, approved-execution, or resolved-loop telemetry by themselves.+Assistant cost-ledger events may carry only the coarse `context_scope`+classifier for product-originated finding, resource, handoff, action, or+structured-mention turns; telemetry may aggregate that classifier into+governed-context Assistant counts, but it must not export prompts, session IDs,+resource IDs, finding IDs, command text, or action payloads.+Assistant cost-ledger events may also carry only a count-only+`tool_call_count` for accepted, model-selected governed tool calls within the+turn. Telemetry may aggregate that number into Assistant governed-tool+collaboration counts, but it must not export tool names, tool arguments, tool+results, provider call IDs, transcript content, resource IDs, finding IDs,+command text, action payloads, or session IDs.+The Pulse MCP README and the in-app Agent integrations panel must present that+adapter as one reusable runtime contract with client-native config wrappers:+OpenCode uses a top-level `mcp` object in `opencode.json` / `opencode.jsonc`,+while Claude-style clients use `mcpServers`. The shared command, base URL, and+token environment variable remain the Pulse Intelligence contract; client file+formats are wrappers around that contract, not separate Pulse Intelligence+surfaces. In the in-app Pulse Intelligence settings panel, those copied wrapper+snippets are on-demand setup detail; they must not occupy the default+external-agent read above the Patrol-autonomy and scoped-token hierarchy. The+Security API Access page may mint the scoped token, but it must not become the+external-agent setup page.+Full-surface token scope guidance must come from the canonical manifest's+manifest-owned `requiredScopes` set through shared+`agentcapabilities.ManifestRequiredScopeList` /+`ManifestRequiredScopeMarkdownList` helpers rather than Assistant-, UI-, or+adapter-local hardcoded or recomputed scope copy.+The native Assistant runtime prompt, lifecycle logs, and readiness messages+must identify that first-party surface as Pulse Assistant rather than the+legacy generic `Pulse AI` persona; the shared engine/core vocabulary remains+Pulse Intelligence.+The canonical manifest declaration, manifest wire shape, action-mode enum,+registry tool-name vocabulary, structured registry tool schema, provider projection helpers, JSON Schema+object-envelope helpers, provider tool/call/result shapes, provider-call+projection helper, provider tool-name catalog exact/prefix matching,+provider tool-call artifact detection and streaming tool-name prefix holding,+provider tool-call input normalization that clones caller+maps and nested JSON-like argument values before initializing empty input+objects, provider-emitted streamed tool-input parsing, final provider+tool-input raw fallback handling, and native Assistant question input parsing,+control-level vocabulary, control-tool availability+predicate, tool-governance defaulting, disabled-control guidance, capability+lookup and typed lookup-error helpers, external-tool+projection helpers, and shared agent HTTP substrate, including named capability+execution, live in+`internal/agentcapabilities`; MCP JSON-RPC envelopes, method constants,+request decoding, line-delimited stdio request serving, notification response+policy, stable JSON-RPC encoding, manifest-backed tool-server semantics,+tool-server method dispatch, initialize instruction/tool-call/resource/prompt payloads,+tool-server initialize result construction, notification methods, MCP+`tools/call` raw params decode, MCP resource URI projection, context-backed+`resources/list` / `resources/read` projection, and manifest-backed+`prompts/list` / `prompts/get` projection live at the MCP adapter edge.+Native Assistant registry declarations are part of that same identity contract:+every registry `Tool.Definition.Name` for Pulse Intelligence tools, including+the read-only `pulse_summarize` reporting synthesis tool and Patrol runtime+tools, must consume `internal/agentcapabilities/tool_names.go` constants rather+than owning string literals in `internal/ai/tools`.+Shared Pulse Intelligence workflow prompt definitions, manifest-owned+`workflowPrompts` catalogue selection, prompt display labels, MCP prompt title+projection, presentation kind hints, prompt argument validation, and prompt+rendering rules live in the neutral workflow-prompt core so native Assistant+starters, frontend manifest consumers, and external MCP prompts cannot drift.+When `workflowPrompts` is present on a manifest it is authoritative; capability+projection is compatibility plumbing for older manifests, not a second prompt+catalogue. The native Assistant starter row must therefore derive starter+availability from `workflowPrompts` and the attached Assistant context, then call+the AI/API-owned render route before inserting any prompt text into the composer;+it must not copy prompt labels, prompt bodies, or MCP `prompts/get` rendering+logic into frontend state. MCP prompt list/get helpers must likewise accept the+manifest-owned workflow prompt catalogue through `ManifestPulseWorkflowPrompts`,+`ProjectMCPWorkflowPrompts`, `GetMCPPromptFromManifestSurface`,+`GetMCPPromptFromManifest`, and+`BuildMCPPromptFromManifest`; they must not expose raw-capability `ProjectMCPPrompts`,+`GetMCPPrompt`, or `BuildMCPPrompt` entrypoints that can re-create a second MCP+prompt catalogue. Shared tool-call+parameter normalization and validation live in the neutral tool-call core: tool+names are trimmed and required, argument maps+are cloned deeply enough to detach nested JSON-like `body` maps/slices and+initialized, and malformed or semantically invalid tool-call params must fail+before capability lookup so native Assistant execution, the legacy text+projection, and external MCP adapters cannot drift on empty-name, nil-argument,+or caller-owned nested argument handling. Shared capability tool HTTP execution+and direct execution output/error mapping live in the neutral tool-execution+core, while result wrapping, result-text extraction, result interpretation, and+the canonical `HTTPCallResponse` to shared tool-result mapping live in the+neutral tool-result core. JSON object result bodies must also project into the+same shared structuredContent envelope while preserving the serialized text+content block for compatibility, so MCP clients and native Assistant paths see+one canonical result contract. Native Assistant direct execution paths must use that+shared text/marker interpretation and output/error projection instead of+flattening tool-result content blocks or branching on `isError`, approval, or+policy outcomes locally, so in-app execution and external MCP adapters+interpret the shared result envelope the same way. MCP `tools/call` decoding is+adapter-edge protocol work, but execution authorization must still enter the+neutral tool-execution core only after the shared manifest surface contract has+selected the allowed request/response capabilities. Patrol-only Assistant+registry tools that return JSON must build those responses through the shared+`agentcapabilities` JSON result constructors instead of manually marshaling JSON+into text-only results, so `structuredContent` remains available to both native+Assistant and external-agent result consumers. Patrol verification+tool-call records that decide success, failure,+approval-required, or policy-blocked outcomes must also branch through the+shared tool result interpretation rather than treating `isError` alone as the+success boundary. Reference clients that need a successful raw response body must also+use the shared request/response capability body helper so named capability+lookup, path/body projection, API-token headers, and stable non-2xx error+formatting stay in one place. The+agent SSE subscription transport, record parser, actionable-record filter, and+SSE-to-MCP notification bridge also live there so MCP notification bridges and+reference probes consume the same `Accept: text/event-stream`, status handling,+`event:` / `data:` framing rules, transport-event filtering, and JSON-RPC+notification projection.+The legacy+approved-action text projection for Pulse tool calls is also parsed there into+the shared `ToolCallParams` shape, including the internal approved-action+argument key/helper that carries a granted approval into replayed tool execution,+the `current_resource` handle plus governed aliases, and the recursive+tool-argument detector that blocks unresolved attached-resource placeholders+before visible execution; text invocations are then normalized and validated+through the same shared parameter contract, so+Assistant approval execution and MCP-compatible adapters cannot drift on tool+name, `default_api:` prefix, quoted argument handling, placeholder target+semantics, empty names, nil+arguments, or pre-approved action replay semantics. Structured tool+response envelopes, tool error-code vocabulary, the structured tool-result+error-code parser, and the `verification.ok` evidence parser also live there+so Assistant blocked/failed tool outcomes, provider call params, agent-facing+tool failure contracts, FSM block/recovery codes, recovery tracking, and+write-tool self-verification semantics cannot drift. The legacy-compatible Assistant tool markers+for approval-required and policy-blocked outcomes also live there, including+the stable `APPROVAL_REQUIRED:` / `POLICY_BLOCKED:` prefixes, payload `type`+values, formatter helpers, parser helpers, and the typed approval-required+payload contract for plan, context-confidence, preflight, target, risk, and+description data. Tool families may own the resource-specific payload fields+they add to those markers, but they must not redeclare the marker envelope,+rebuild anonymous approval payload readers, branch on local prefix strings, or+hide shared marker parsing behind Assistant-local parser wrappers. Legacy+service approval-marker handling may keep compatibility fallback behavior for+old marker text, but the canonical decision path must call the shared marker+parser directly at the branch site. Tool execution must not drop the returned+argument map when carrying a granted approval into replayed tool execution.+Native Assistant tool protocol aliases must expose only the shared neutral+registry shapes the Assistant actually executes (`Tool`, `ToolCallParams`,+`ToolResult`, `ToolContent`, and structured tool-response envelopes). JSON-RPC,+MCP initialize/list/resource/prompt payloads, and other MCP wire aliases remain+at the external adapter edge in `internal/agentcapabilities/mcp.go`, not in+`internal/ai/tools/protocol.go`. Chat transcript and API-facing tool-result+shapes must alias the shared provider-call contract while the richer in-app+Assistant transcript projects to that shared shape through an explicit helper.+Provider-result context projection also belongs to `internal/agentcapabilities`:+native Assistant, the legacy AI service loop, external adapters, and future+Pulse Intelligence surfaces must build full transcript results and model-context+results through the shared projection so transcript preservation, error flags,+and model-result truncation cannot drift into surface-local pairs.+API handlers, Assistant tool governance, `cmd/pulse-mcp`, and the in-repo probe+consume that shared contract so agent projections cannot drift into local+structs, local structured schema types, local provider schema projection, local+schema wrappers, local request/response filters, local capability maps, local+path placeholder parsing, local argument-to-body shaping, local manifest+fetchers, local API-token header spelling, local stable error-envelope+formatting, local named capability execution, local tool-governance defaulting,+local disabled-control guidance, local MCP manifest-backed+tool-server handlers, local MCP method dispatch, local MCP request decoding or+line-framing loops, local JSON-RPC encoders, local notification response+checks, local MCP initialize builders, local+HTTP-to-MCP result wrapping, local MCP result interpretation,+local SSE record scanners, local SSE-to-MCP notification bridges, local+tool-result maps, or local tool-description builders. Path placeholders from the manifest and top-level+tool arguments must be projected through the shared+`agentcapabilities.ProjectCapabilityCall` helper before dispatch, so path+values are percent-encoded single segments and non-placeholder write arguments+become the JSON request body when no nested `body` object is provided.+Internal tool-call metadata such as approved-action grants must stay on the+shared `agentcapabilities` argument helper path and be stripped by the shared+projection before any public manifest-backed HTTP body is built.+Canonical IDs containing `:`, `/`, spaces, or other reserved characters cannot+alter the route shape.+The Assistant and MCP surfaces must also rely on the router-owned manifest+route/scope proof: every canonical capability is projected through the shared+call helper into a concrete request, then exercised against the API router with+a token that lacks the advertised scope so drift between manifest metadata,+agent-facing placeholders, and real authorization fails before either surface+ships a mismatched tool.+Native Assistant provider seams are part of the Pulse Assistant surface, not+the external MCP adapter. Chat service aliases, API handler setter signatures,+router dependency wiring, direct in-app tool execution, and findings-store+adapters plus the broader native tool adapter family must use Assistant/Pulse+Intelligence terminology; `MCP` names are reserved for the protocol adapter,+MCP-compatible action-contract interface, wire envelopes, and result+interpretation contracts.+The Pulse Intelligence event vocabulary is part of that same shared+`internal/agentcapabilities` boundary. API SSE producers, the+`subscribe_events` manifest description, MCP notification advertising, MCP+transport-event filtering, MCP notification method projection, shared SSE+record parsing, shared SSE-to-MCP notification bridging, and reference probes+must consume the shared event kind constants/helpers instead of maintaining local copies of+`finding.created`, `approval.pending`, `action.completed`, `stream.connected`,+or `heartbeat`.+MCP `tools/list` must use the shared+`agentcapabilities.ProjectManifestSurfaceTools` projection for the Pulse MCP+surface. The manifest-owned `surfaceToolContracts` field is the allowlist for+which request/response tools Pulse MCP may advertise or execute; raw+`Manifest.Capabilities` remains the metadata and execution source, not the+surface availability decision. MCP initialize capability advertisement,+operating-instruction affordance copy, `tools/list`, `tools/call`,+`resources/list`, `resources/read`, `prompts/list`, and `prompts/get` must also+pass through the manifest-owned surface affordance contract: the surface must+allow tools, resources, prompts, and capability metadata before raw manifest+capability or prompt presence can expose them to an external client. The shared+`agentcapabilities.ProjectTools`+helper still owns the full request/response tool shape, including+manifest-owned capability metadata (category, method/path, scope, action mode,+approval policy, request/response shape, stable error codes, input schema, and+structured output schema). That metadata must be available both in model-facing+description prose and in the standard MCP `_meta["pulse.capability"]` object+for clients that need structured route/scope/governance facts, so external-agent+clients see the same governed API contract without a second MCP-specific tool+registry, projection loop, allowlist, or prose table. Action mode (`read`,+`mixed`, `write`) and approval policy (`scope_only`, `action_plan`) are+manifest-owned governance fields; MCP must not infer or override them from HTTP+method or local tool names. Manifest-backed capability lookup and `tools/list`+projection must also detach raw `inputSchema`, raw `outputSchema`, structured+metadata maps, and error-code slices through `agentcapabilities.CloneCapability`,+`CloneCapabilities`, and `CloneRawMessage`, so external-agent adapters cannot+mutate the manifest-backed contract while serializing or post-processing one+projected tool list.+The manifest-owned `get_patrol_control_status` structured output schema is+part of the same AI runtime contract. Its four-step operator rollup is a+content-free stage projection for Assistant and MCP callers: governance step+counts represent pending approvals until an approved or rejected decision+exists, then represent decision evidence, while verification step counts+represent verified outcomes or terminal rejected decisions. Optional MCP+readiness remains a separate `externalAgentReady` capability signal, not an+operator step. AI runtime surfaces must consume that manifest schema and backend+projection instead of inventing chat-local stage-count rules. The schema's+Patrol control starter count includes native Patrol, current paid Patrol+control, and legacy Pro activation handoff starts; its+completed-loop and resolved-loop counts are aggregate orientation fields for+native Assistant and MCP-facing orchestration only. Legacy+`patrolAutonomy*` and `proActivation*` completed-loop, resolved-loop, and+value-state fields are aliases for the Patrol control values; the legacy Pro+activation starter field remains an entry-point-specific count. All of+those fields must remain free of prompt names, finding IDs, action IDs,+resource names, actors, request bodies, commands, or model output.+Resolved-loop semantics remain approved-and-verified only.+`cmd/pulse-mcp` startup guidance and the generated MCP README token-scope+block must consume the manifest-owned `requiredScopes` summary through+`agentcapabilities.ManifestRequiredScopeList` /+`agentcapabilities.ManifestRequiredScopeMarkdownList`. MCP README tool and+capability-specific error-code inventories are generated through+`scripts/generate-pulse-intelligence-docs.go` from the manifest-owned Pulse MCP+surface contract via `agentcapabilities.MCPToolCapabilityInventoryMarkdown` and+`agentcapabilities.MCPErrorCodeInventoryMarkdown`. Workflow-prompt inventory is+generated through `agentcapabilities.MCPPromptInventoryMarkdown` from the same+`MCPManifestSurfacePromptProjectionSupported` gate and+`ManifestPulseWorkflowPrompts` / `ProjectMCPWorkflowPrompts` projection used by+`prompts/list`, including manifest labels as prompt titles. README tool lists,+prompt lists, scope lists, and capability-specific error-code lists must not be+hand-maintained snapshots. MCP+`tools/call` must use the same shared+`agentcapabilities.ManifestSurfaceToolCapabilities` resolver as `tools/list`;+streaming capabilities such as `subscribe_events`, and raw manifest+capabilities omitted from the Pulse MCP surface contract, remain unavailable to+request/response tool calls even if a client sends their name manually. Adding+a raw capability to `Manifest.Capabilities` is not enough to publish an MCP+tool; the Pulse MCP `surfaceToolContracts` allowlist must opt it into that+external-agent surface. Publishing the Patrol work prompt also requires the+surface contract to include `get_patrol_control_status`, so MCP clients can+read the same content-safe Patrol work stage before requesting fleet, finding,+resource, approval, action, or resolution detail. The legacy+`get_operations_loop_status` name may remain accepted only at compatibility+edges.+MCP `resources/list` and `resources/read` are also shared manifest-backed+projections: `resources/list` must call the canonical `get_fleet_context`+capability, `resources/read` must call `get_resource_context`, and the+`pulse://resource/<resource-id>` URI shape, resource content MIME type, and+resource read parameter validation live in `internal/agentcapabilities` rather+than in `cmd/pulse-mcp` or an MCP-only inventory registry. They must enter+through `ManifestSurfaceResourceCapabilities`,+`ListMCPManifestSurfaceResourcesHTTP`, and+`ReadMCPManifestSurfaceResourceHTTP`, not raw-capability+`ListMCPResourcesHTTP` or `ReadMCPResourceHTTP` helpers. The MCP resource+methods remain disabled when the target surface affordance contract disables+resources, even if those context capabilities exist in the manifest.+Operator-state writes, governed finding lifecycle tools, and action+plan/decision/execute tools must also carry manifest-owned `inputSchema`+definitions for their exact arguments so external-agent clients receive typed+fields and enums from the canonical manifest instead of an MCP-local free-form+body convention. When the manifest has no authored schema, MCP may derive a+permissive fallback through the shared `agentcapabilities.ToolInputSchema`+helper, but it must not hand-roll a second JSON Schema envelope.+Governed finding lifecycle tools must return the agent-stable error envelope+from `internal/agentcapabilities/errors.go` for branchable failures+(`invalid_finding_request`, `finding_not_found`,+`finding_action_not_allowed`, `patrol_unavailable`) and declare those codes in+the canonical manifest; UI callers may still use the same HTTP routes, but the+wire contract is owned by the Pulse Intelligence agent surface once the route+is advertised there. The exported `agentcapabilities.AgentErrCode*` constants+are the source of those values for both manifest declarations and+`internal/api/` handler emissions; local string literals in either layer are+contract drift. Manifest `scope` values are auth-owned vocabulary from+`pkg/auth` and must be declared through manifest-local aliases to those+constants, not repeated as string literals, so MCP tools and direct HTTP agents+advertise the same scopes the API authorization layer enforces. Patrol finding+capabilities (`list_findings`, `acknowledge_finding`, `snooze_finding`,+`dismiss_finding`, and `resolve_finding`) are part of the AI runtime route+surface and therefore advertise `ai:execute`; they must not be downgraded to+monitoring scopes in MCP docs or manifest projections while the router gates+those HTTP routes through AI execution authorization.+Do not add MCP-only business logic or a second tool registry here. If a new+operation should be available to external agents, add it to the canonical API+capability manifest and make Assistant consume the same governed backend+contract when the in-app UX needs it.+Assistant prompt governance follows the same rule: live turns derive tool+mode, typed approval policy (`scope_only` or `action_plan`), approval summary,+and tool summary text from the shared `agentcapabilities.ToolGovernanceDescriptor`+shape returned by `PulseToolExecutor.ListToolGovernance`; descriptor defaults+must be constructed through `agentcapabilities.NewToolGovernanceDescriptor`,+and fallback prompt+text must call the registry-owned+`tools.CanonicalToolGovernanceForSurface` helper with the explicit requesting+Pulse Intelligence surface rather than maintaining a chat-local copy of tool names, governance+descriptor fields, policy vocabulary, or governance prose.+Assistant-only structured interaction tools such as `pulse_question` must also+be projected through the shared+`agentcapabilities.BuildAssistantToolGovernancePromptSection` and+`agentcapabilities.AssistantGovernanceOfferedToolNames` helpers rather than by+hand-building prompt-policy lines or offered-tool filters in chat-local code;+those tools remain native Assistant interaction boundaries, not MCP manifest+capabilities.+Direct Assistant registry execution is also part of the shared Pulse+Intelligence tool-call contract: `ToolRegistry.Execute` must normalize and+validate tool names and arguments through `agentcapabilities.ToolCallParams`+and use the shared invalid-params, unknown-tool, and control-disabled tool+result helpers before lookup or handler dispatch, so in-app direct execution+cannot drift from external MCP `tools/call` on trimmed names, blank-name+rejection, nil-argument initialization, deep caller-argument copying, or+standard entrypoint failure envelopes.+Chat-service direct execution paths such as autonomous command execution and+approved-fix replay must route through one Assistant registry execution helper+before calling `agentcapabilities.InterpretDirectToolExecution`, so+surface-specific failure wording does not fork executor lookup, registry+dispatch, marker interpretation, or shared result handling. MCP-named+direct-execution symbols are not part of the shared adapter contract; native+Assistant code and MCP adapters must use the neutral direct tool execution+helper.+Cross-repo auto-fix and Patrol-approved action binders must resolve approved+tool execution through `AIAutoFixHandlerDeps.ResolveApprovedAssistantToolExecutor`;+that resolver returns the native `ApprovedAssistantToolExecutor` only, so+enterprise code cannot recreate MCP-named Assistant execution selection. The+current public runtime must populate `AssistantToolExecutor` only; MCP remains+an external adapter boundary and is not an approved-fix execution dependency.+Assistant telemetry that records recoverable policy-block attempts must also+use the shared `agentcapabilities` tool-response error-code constants rather+than local string literals, so metrics labels, structured tool responses,+Assistant recovery tracking, and MCP-facing agent error vocabulary stay+aligned.+Assistant provider tool schemas are also registry-owned: chat must obtain the+runtime provider tool surface from `PulseToolExecutor.AssistantProviderTools`+so availability filtering, registry-owned governance descriptors, and+Assistant-native interaction tools are composed at one executor-owned boundary+instead of being paired manually in chat paths. That executor projection must+project registered `tools.Tool.InputSchema` values through the shared+`agentcapabilities.ProjectProviderTools` provider-schema helper and the+manifest-affordance-gated+`agentcapabilities.ProjectPulseAssistantProviderTools` provider-surface helper,+and model-selected tool calls must flow through+`agentcapabilities.ProjectProviderToolCallToToolCall` and the shared+`agentcapabilities.NormalizeProviderToolCallForExecution` /+`NormalizeProviderToolCallsForExecution` execution normalizers, not local schema+maps, compatibility aliases, raw provider call fields, chat-local provider+projection wrappers, or MCP-shaped provider-projection wrappers.+MCP-shaped provider projection names remain protocol compatibility aliases in+`internal/agentcapabilities/mcp.go`; they must not be implemented in the neutral+provider schema boundary or imported by native Assistant runtime paths.+Shared projected-tool behavior hints are the same class of boundary: the+neutral projection owns `ToolBehaviorHints`, while any `MCPToolAnnotations`+name is an alias in the MCP wire edge only.+Assistant-only provider tools are still shared Pulse Intelligence declarations:+the native `pulse_question` clarification tool must be included in provider+tool lists through `agentcapabilities.ProjectPulseAssistantProviderTools` and+`agentcapabilities.AssistantNativeProviderTools`, its declaration must come+from `agentcapabilities.NewPulseQuestionProviderTool`, its JSON Schema must+remain owned by `agentcapabilities.PulseQuestionProviderInputSchema`, its+question type/defaulting vocabulary must use+`agentcapabilities.PulseQuestionToolTypeValues` and+`agentcapabilities.NormalizePulseQuestionToolType`, its emitted provider input+must parse through `agentcapabilities.ParsePulseQuestionToolInput`, and+allowlists that recognize leaked provider tool calls must consume+`agentcapabilities.NewAssistantProviderToolNameCatalog` instead of hard-coding+Assistant-native names or rebuilding provider-tool name sets locally. Provider+tool-call artifact detection and streaming partial-tool-name holding must use+`agentcapabilities.ProviderToolCallArtifactIndex` and+`agentcapabilities.SplitTrailingProviderToolNamePrefix` with that shared catalog,+so Assistant and future adapter boundaries do not fork DSML/XML/pipe/JSON/function+leak semantics. Chat may own waiting for user answers, UI event+emission, and FSM user-input behavior, but it must not carry a chat-local+provider schema, description, tool-list append rule, prompt-filter rule, parser,+tool identity, or provider artifact detector for that interaction.+That schema boundary is also a copy boundary: registry tool definitions must+normalize through `agentcapabilities.Tool.NormalizeCollections`, and+`ToolRegistry.Register` / `ToolRegistry.ListTools` must not expose caller-owned+or registry-owned `InputSchema` maps, required slices, enum slices, provider+input-schema maps, or JSON-schema default containers for later mutation by an+Assistant, provider, or external-agent surface. Direct provider schema+projection helpers must normalize through that same copy boundary before+emitting provider JSON so JSON-schema default containers cannot alias registry+definitions.+Provider tool-call normalization must also stay shared: provider responses,+Assistant transcript storage, live Assistant execution, and API adapter+projections must get independent input maps, nested JSON-like argument values,+trimmed executable tool names, initialized empty argument maps, and raw provider+thought-signature payload bytes from+`agentcapabilities.ProviderToolCall.NormalizeCollections` plus the shared+execution normalizers so a later mutation in one surface cannot rewrite another+surface's tool arguments or provider reasoning-continuity metadata.+Assistant transcript normalization is part of that copy boundary:+`chat.Message.NormalizeCollections` and `chat.ToolCall.NormalizeCollections`+must detach tool-call slices, nested tool-call input maps/slices, provider+thought signatures, success pointers, and tool-result pointers before stored+messages are reused across session storage, provider-continuation, browser/API,+or orchestrator adapter surfaces.+Provider-facing tool results follow the same shared boundary: Assistant+tool execution must project shared tool-call results through+`agentcapabilities.NewProviderToolResultFromToolResult` and build transcript or+model-context result messages through `agentcapabilities.NewProviderToolResult`+so result text flattening and `is_error` semantics stay aligned with+external-agent adapters. MCP-named provider-result projection helpers are not+part of the adapter contract; runtime paths that need the plain text from a+shared tool result must call `agentcapabilities.ToolResultText` at the execution+site instead of keeping Assistant-, Patrol-, or MCP-local result-text wrappers.+Runtime paths that convert chat transcripts, repair orphan tool calls, or run+legacy service tool loops must not assemble `providers.ToolResult` or+`chat.ToolResult` structs locally, and must not hide shared provider-result+construction behind Assistant-local pointer wrappers.+Native Assistant registry execution and external MCP method dispatch must also+normalize shared `ToolResult` values through+`agentcapabilities.ToolResult.NormalizeCollections` before returning them, so+handler-owned content slices and nil content collections cannot leak across+Assistant, provider, or MCP response boundaries. MCP may retain only actual+`MCPToolResult` / `MCPContent` protocol wire aliases; result constructors,+structured tool-response projection, JSON object and array-wrapper+structuredContent projection, text extraction, and interpretation stay neutral+shared helpers rather than MCP-named wrappers.+Assistant runtime settings and tool exposure must derive+read-only/controlled/autonomous semantics from+`agentcapabilities.ControlLevel` and+`agentcapabilities.ControlLevelAllowsControlTools`; future MCP adapters may+alias the same values, but must not carry separate control-tool availability+rules, disabled-control guidance, or tool-governance defaulting.+Guest-family AI runtime code paths (VMs and LXC system containers) sharegeneric helpers instead of per-family copies. Patrol guest intelligencegathers both families through `gatherGuestIntelligenceFromViews` in@@ -70,10 +930,15 @@ driven by `fileMutationSpec` (`internal/ai/tools/tools_file.go`), andnamespaced kubectl actions share `executeKubernetesResourceAction` driven by`kubernetesResourceAction` (`internal/ai/tools/tools_kubernetes.go`) — newfile or kubectl actions add a spec, keeping approval-command text stable,-instead of duplicating the approval/audit pipeline. Anthropic message-conversion is shared by the API-key and OAuth clients through-`convertMessagesToAnthropic` (`internal/ai/providers/anthropic.go`), and AI-memory history files load through the generic `loadMemoryHistory`+instead of duplicating the approval/audit pipeline. OpenAI-compatible message+conversion for both non-streaming and streaming turns is shared through+`convertMessagesToOpenAI` (`internal/ai/providers/openai.go`), Anthropic message+conversion for both non-streaming and streaming turns is shared by the API-key+and OAuth clients through `convertMessagesToAnthropic`+(`internal/ai/providers/anthropic.go`), Gemini message conversion for both+non-streaming and streaming turns is shared through `convertMessagesToGemini`+(`internal/ai/providers/gemini.go`), and AI memory history files load through+the generic `loadMemoryHistory`(`internal/ai/memory/paths.go`). `Finding`/`findingJSON` and`UnifiedFinding`/`unifiedFindingJSON` are deliberate marshal-mirror twins —do not merge them; the mirror invariants are enforced by@@ -83,7 +948,14 @@ the transport side: `orchestratorChatAdapter.GetMessages`(`internal/api/ai_handlers.go`) and `chatServiceAdapter.GetMessages`(`internal/api/chat_service_adapter.go`) convert the same chat-servicemessages onto deliberately separate output contracts; do not merge them, and-keep their field mapping aligned —+keep their field mapping aligned. Orchestrator-facing tool-call and+tool-result payloads must project through+`aicontracts.OrchestratorToolCallInfoFromProvider`,+`OrchestratorToolCallInfo.ProviderToolCall`,+`aicontracts.OrchestratorToolResultInfoFromProvider`, and+`OrchestratorToolResultInfo.ProviderToolResult` so the public investigation+handoff contract inherits the same `agentcapabilities` input-map,+thought-signature, and provider-result normalization as Assistant and MCP —`TestOrchestratorAndChatAdaptersMapTheSameMessageFields` enforces it.Assistant frontend presentation changes under@@ -158,30 +1030,30 @@ deriving an older display status from `workflowStatusHistory`.`ResourceRoutingScopeLocalOnly` (Restricted sensitivity — tagged secret/pii,PMG, k8s-secrets, ...) have their identifiers redacted and never leave thelocal trust boundary. Everything else (Internal and Sensitive) flows.- Both are enforced by the model-boundary sanitizer- `modelboundary.RequestSanitizerForModel(model, provider)` (`internal/ai/modelboundary`),- which returns nil for local (Ollama) models — local always receives full context.- UNIVERSAL backstop rule: EVERY code path that sends infrastructure-derived- content to an external model MUST install `RequestSanitizerForModel` before the- provider request — not only the interactive agentic loop. This explicitly- includes session compaction (`internal/ai/chat/session_compaction.go`- `SummarizeSession`), which sends the PERSISTED transcript (original user prompts- and tool outputs carry raw identifiers), and the shared service helper- `(*Service).requestSanitizerForModel` (`internal/ai/service.go`) used by- discovery analysis, the report and fleet narrators, quick analysis, and the- ExecuteAgentic paths. A new model-bound request path that skips the sanitizer is- a leak and is not permitted. (Static capability probes with no resource content,- e.g. the Patrol preflight self-test, are exempt only because their payload is- fixed and carries no identifiers.)- Redaction-placeholder hygiene: Pulse-authored model-bound directives (the- resource-context handoff instructions in `internal/ai/chat/service.go` and- `internal/ai/chat/plain_text_resource_context.go`) must NOT inject the literal- redaction placeholder (`unifiedresources.ResourcePolicyRedactedLabel`,- "redacted by policy") into the prompt — naming it makes the model echo it back- as if it were a resource name. Directives reference withheld labels neutrally- ("a withheld or placeholder label") and must instruct the model not to repeat a- withheld placeholder back to the user as the resource identity; the- `current_resource` handle remains the authoritative target.+ Both are enforced by the model-boundary sanitizer+ `modelboundary.RequestSanitizerForModel(model, provider)` (`internal/ai/modelboundary`),+ which returns nil for local (Ollama) models — local always receives full context.+ UNIVERSAL backstop rule: EVERY code path that sends infrastructure-derived+ content to an external model MUST install `RequestSanitizerForModel` before the+ provider request — not only the interactive agentic loop. This explicitly+ includes session compaction (`internal/ai/chat/session_compaction.go`+ `SummarizeSession`), which sends the PERSISTED transcript (original user prompts+ and tool outputs carry raw identifiers), and the shared service helper+ `(*Service).requestSanitizerForModel` (`internal/ai/service.go`) used by+ discovery analysis, the report and fleet narrators, quick analysis, and the+ ExecuteAgentic paths. A new model-bound request path that skips the sanitizer is+ a leak and is not permitted. (Static capability probes with no resource content,+ e.g. the Patrol preflight self-test, are exempt only because their payload is+ fixed and carries no identifiers.)+ Redaction-placeholder hygiene: Pulse-authored model-bound directives (the+ resource-context handoff instructions in `internal/ai/chat/service.go` and+ `internal/ai/chat/plain_text_resource_context.go`) must NOT inject the literal+ redaction placeholder (`unifiedresources.ResourcePolicyRedactedLabel`,+ "redacted by policy") into the prompt — naming it makes the model echo it back+ as if it were a resource name. Directives reference withheld labels neutrally+ ("a withheld or placeholder label") and must instruct the model not to repeat a+ withheld placeholder back to the user as the resource identity; the+ `current_resource` handle remains the authoritative target.3. Add or change Pulse Assistant request flow through `internal/api/ai_handler.go`, `frontend-modern/src/api/ai.ts`, and `frontend-modern/src/api/aiChat.ts`Assistant session compaction is a runtime-backed session workflow, not alocal waiting message, transcript-only UI action, or stubbed summarize@@ -369,17 +1241,17 @@ deriving an older display status from `workflowStatusHistory`.question controls live in the transcript. The referenced OpenCode source atcommit `9ed17da55ab1f7360cc0e01075f763e27fa899e9` mutates active toolparts into terminal `success` or `failed` rows in- `packages/opencode/src/cli/cmd/tui/context/sync-v2.tsx`- (`session.next.tool.success`, lines 328-348;- `session.next.tool.failed`, lines 350-371), and the processor marks- interrupted active tools terminal before completing the assistant message in- `packages/opencode/src/session/processor.ts` (lines 888-917). Pulse adapts- that by retaining completed tool rows and assistant text while removing- unresolved interactive rows from terminal browser transcript state.- Completed tool rows must preserve timing once a pending row resolves. The- referenced OpenCode source at fetched `origin/dev` commit- `effd27b23900720a53e965396ff1a105c1f7e9c8` carries tool identity and- state through `toolCommit` / `startTool` / `doneTool` in+ `packages/opencode/src/cli/cmd/tui/context/sync-v2.tsx`+ (`session.next.tool.success`, lines 328-348;+ `session.next.tool.failed`, lines 350-371), and the processor marks+ interrupted active tools terminal before completing the assistant message in+ `packages/opencode/src/session/processor.ts` (lines 888-917). Pulse adapts+ that by retaining completed tool rows and assistant text while removing+ unresolved interactive rows from terminal browser transcript state.+ Completed tool rows must preserve timing once a pending row resolves. The+ referenced OpenCode source at fetched `origin/dev` commit+ `effd27b23900720a53e965396ff1a105c1f7e9c8` carries tool identity and+ state through `toolCommit` / `startTool` / `doneTool` in`packages/opencode/src/cli/cmd/run/session-data.ts` (lines 622-733) andformats elapsed tool state with `span` in`packages/opencode/src/cli/cmd/run/tool.ts` (lines 191-200). Pulse adapts@@ -417,16 +1289,16 @@ deriving an older display status from `workflowStatusHistory`.`pulse_read` or bare fallback labels such as `read` remain fallback-onlydebug/detail vocabulary.Live workflow activity is also active turn state, not disposable waiting- copy. The referenced OpenCode source at fetched `origin/dev` commit- `1025540fcc2a69609a0131a7168300205656d728` defines model, shell, step,- and tool lifecycle events in `packages/core/src/session/event.ts` (model- switched lines 62-70; shell started/ended lines 151-174; tool lifecycle- lines 340-392), projects them into durable message/part rows in- `packages/core/src/session/message-updater.ts` (step started lines- 189-210; tool called/progress/success/failed lines 269-335), and renders- model-switch plus tool rows in- `packages/opencode/src/cli/cmd/tui/feature-plugins/system/session-v2.tsx`- (model switch lines 120-122 and 262-274; tool rows lines 455-500).+ copy. The referenced OpenCode source at fetched `origin/dev` commit+ `1025540fcc2a69609a0131a7168300205656d728` defines model, shell, step,+ and tool lifecycle events in `packages/core/src/session/event.ts` (model+ switched lines 62-70; shell started/ended lines 151-174; tool lifecycle+ lines 340-392), projects them into durable message/part rows in+ `packages/core/src/session/message-updater.ts` (step started lines+ 189-210; tool called/progress/success/failed lines 269-335), and renders+ model-switch plus tool rows in+ `packages/opencode/src/cli/cmd/tui/feature-plugins/system/session-v2.tsx`+ (model switch lines 120-122 and 262-274; tool rows lines 455-500).Pulse adapts that by keeping the latest browser `workflow_status` activityvisible in the live stream event sequence across content, tool, approval,and question boundaries instead of dropping it the instant a richer row@@ -1180,10 +2052,10 @@ deriving an older display status from `workflowStatusHistory`.`packages/opencode/src/cli/cmd/tui/feature-plugins/system/session-v2.tsx`.Pulse's compact tool rows must follow that operator-language model: the rowshould summarize the actual governed action (`search "prowlarr"`, `list- active alerts`, `topology summary`, `Inspect devices on current resource`,+active alerts`, `topology summary`, `Inspect devices on current resource`,or exact governed write commands where the command itself is the operatordecision) instead of exposing only internal action names such as `QUERY- search`, `exec`, provider function calls, or raw JSON; raw input and full+search`, `exec`, provider function calls, or raw JSON; raw input and fulloutput stay available behind Details. The referenced OpenCode source atfetched `origin/dev` commit`06d7840d1d42c9815d2d2e45e7fa4090ca4e3577` renders Bash tool state through@@ -1205,7 +2077,7 @@ deriving an older display status from `workflowStatusHistory`.(`InlineTool`, lines 563-651; `Bash`, lines 701-735; `Read`, lines758-770; `Grep`, lines 788-790). Pulse adapts that by usingaction-specific pending copy such as `Writing command...`, `Preparing- query...`, and `Reading storage...` before streamed tool arguments are+query...`, and `Reading storage...` before streamed tool arguments areparseable, then replacing that copy with the governed command/query/resourcesummary as soon as input arrives.The referenced OpenCode source at fetched `origin/dev` commit@@ -1614,6 +2486,12 @@ deriving an older display status from `workflowStatusHistory`.logged server-side or attached as redacted internal Patrol evidence wheregoverned, but they must not be returned through the browser provider-testcontract.+ Anthropic runtime provider execution must be API-key backed. Legacy+ Anthropic OAuth tokens may remain in encrypted settings only as cleanup+ state; they must not make Anthropic configured, instantiate an OAuth-backed+ provider, refresh tokens, or send model requests. OAuth start/exchange and+ callback handling must fail closed, while disconnect may clear stored legacy+ tokens.Patrol findings history transport must stay bounded when resolved findingsare included: `/api/ai/patrol/findings?include_resolved=1` defaults to a200-finding limit and caps explicit limits at 500, and the frontend Patrol@@ -1644,6 +2522,16 @@ deriving an older display status from `workflowStatusHistory`.remain route-distinct: if the configured chat override resolves to the sameroute as the effective default or the already selected session model, thedrawer must not render a duplicate override action.+ Assistant provider-readiness actions must send operators to the canonical+ Pulse Intelligence > Provider & Models route+ `/settings/pulse-intelligence/provider`; `/settings/system-ai` remains a+ compatibility alias for old deep links rather than the href emitted by new+ Assistant repair actions.+ Assistant discovery-context hints must use the same product language as+ Pulse Intelligence settings: the visible hint is `Discovery is off`, while+ the body explains that enabling it gives Assistant real service, version,+ and command context instead of generic guidance. The hint must not+ reintroduce the old `Workload Discovery` label as a separate product concept.Assistant route and control chrome belongs with the prompt surface, not thedrawer title row. The referenced OpenCode source at commit`9ed17da55ab1f7360cc0e01075f763e27fa899e9`@@ -1727,6 +2615,13 @@ deriving an older display status from `workflowStatusHistory`.edit, remove, promote, resume, and clear controls, but the primary headlinemust not imply the user's just-submitted follow-up disappeared behind ageneric `Generating response` state.+ Restored Patrol mode save-failure handoffs may preserve compatible+ summary kinds such as `patrol_configuration_failure`, but Assistant drawer+ titles, subjects, action labels, and safety notes must describe Patrol mode+ rather than reviving generic configuration wording. Stable route markers,+ telemetry fields, and API wire names may retain `patrol_control`;+ user-facing Assistant, external-agent, generated MCP, and frontend copy must+ call the operator's choice `Patrol mode`.7. Keep AI chat presentation helpers aligned through `frontend-modern/src/components/AI/Chat/` and the shared `frontend-modern/src/utils/textPresentation.ts`8. Keep assistant drawer context, session, and org-switch reset state aligned through the shared `frontend-modern/src/stores/aiChat.ts` boundary instead of letting `frontend-modern/src/App.tsx`, `frontend-modern/src/AppLayout.tsx`, or feature callers fork their own assistant shell stateThat shared drawer ownership also covers passive resource reads while the@@ -1754,25 +2649,52 @@ deriving an older display status from `workflowStatusHistory`.attached, the Assistant emptymessage state must also remain source-named and must not fall back to genericcluster/system starter prompts that compete with the attached briefing.- Structured Patrol run and Patrol configuration handoffs may render bounded,+ Structured Patrol run and Patrol mode save-failure handoffs may render bounded,redacted diagnostic lines in the drawer when they are opened directly from- Patrol runtime/configuration surfaces, but the attached headline must remain- source-owned (`Patrol run attached`, `Patrol configuration ... attached`)+ Patrol runtime/control surfaces, but the attached headline must remain+ source-owned (`Patrol run attached`, `Patrol mode ... attached`)and the drawer must still exclude raw provider payloads, commands, andPatrol-authored remediation steps.Reloaded Assistant sessions may consume the backend-owned`handoff_summary` only as safe presentation state and a Patrol findingpointer; hidden model context, command payloads, preflight data, and actionresults stay backend-owned and must not be reconstructed in the browser.-9. Add or change public AI overview wording through `docs/AI.md`; it may+9. Add or change public Pulse Intelligence overview wording through `docs/AI.md`; it maydescribe Assistant and Patrol capabilities, but it must not revive legacycommercial shorthand such as `incident memory` as a current product promise.+ The public overview must preserve the product architecture: Pulse+ Intelligence Core owns canonical context, governed actions, safety gates,+ approval state, action audit, and verification; Pulse Patrol is the primary+ built-in operator on that core; its public summary must stay concise as+ watching, investigating, acting within the chosen Patrol mode, verifying outcomes,+ and recording what happened; and Pulse Assistant plus Pulse MCP are+ contextual and external-agent access paths over the same governed+ capabilities.+ Public overview, safety, and onboarding copy must use the same visible+ Patrol mode labels as the product (`Watch only`, `Ask before changes`,+ `Auto-fix safe issues`, `Policy autopilot`) and must not reintroduce the+ retired `Only watch`, `Fix safe issues`, or `Full control` labels as+ customer-facing names.The public overview must also preserve the model-owned AI boundary: PulseAssistant and Patrol provide governed context, tools, safety gates,approval state, and audit trails, while the configured LLM owns diagnosis,- prioritization, remediation reasoning, and tool choice. Public copy must not+ prioritization, fix reasoning, and tool choice. Public copy must notpresent Pulse code as the intelligence engine, a prompt-keyword router, a- learned operational-meaning engine, or a deterministic finding author.+ deterministic auto-remediation oracle, a provider replacement, a learned+ operational-meaning engine, or a deterministic finding author.+ The public overview must not carry a hand-maintained Assistant tool table.+ Assistant tool inventory, action modes, approval policies, provider+ declarations, and Patrol-only filtering are registry-owned in+ `internal/ai/tools/` and projected through `internal/agentcapabilities/`;+ external-agent inventory belongs to `/api/agent/capabilities` and+ `pulse-mcp` `tools/list`.+ External-agent setup metadata follows the same rule: Pulse MCP server name,+ command, base URL flag/default, token environment variable, and supported+ client config families are manifest-owned in+ `/api/agent/capabilities.mcpAdapter`. Assistant, Pulse Intelligence+ settings, README, and MCP surfaces may present that setup, but must not+ maintain separate MCP setup constants. Security API settings may only host+ the scoped-token creation link used by that setup.10. Platform/runtime top-level pages registered in`frontend-modern/src/App.tsx` and the primary tab list in`frontend-modern/src/AppLayout.tsx` must keep the AI launcher chrome@@ -1816,7 +2738,7 @@ deriving an older display status from `workflowStatusHistory`.## Completion Obligations-1. Update this contract when canonical AI runtime or transport entry points move, including transport-level provider request-shape changes such as OpenAI-compatible `tool_choice` handling, runtime-failure classification splits (for example separating tool-choice request rejection, no tool-capable endpoint, and generic model-level lack of tool support into distinct causes), Patrol-specific verification surfaces such as `POST /api/ai/patrol/preflight` that exercise the full chat-completions path with a minimal tool definition rather than only listing models, Patrol-preflight cache observability where the AI Service caches the most recent preflight outcome (success, soft warning, or classified failure) and the AI settings response surfaces it as `patrol_preflight` so the UI can hydrate a "last verified" indicator without forcing operators to re-run preflight on every page load, the auto-trigger contract on `HandleUpdateAISettings` where the save handler runs `TriggerPatrolPreflightAsync` only when the change actually moved Patrol transport (model swap, provider key for that model changed, or assistant just enabled with a Patrol model) so routine settings saves do not burn provider tokens, the startup-seed contract where the AI Service handler dispatches the same async preflight on Pulse boot when assistant is enabled and a Patrol model is configured so the cache is populated for the first `/api/settings/ai` poll after a restart instead of blanking back to "never verified", the readiness-integration contract where the `tools` check in the Patrol readiness payload consults the cached preflight and surfaces the classified evidence (success, soft warning, or failure with classified summary plus "last preflight <age>") for the configured provider+model when available (falling back to the static `PatrolToolReadinessForModel` classifier only when the cache is empty or holds a result for a different model), the stateless-Patrol-input contract where `ExecutePatrolStream` must pass only the current run's user prompt into the agentic loop rather than reloading the persisted `patrol-main` session history (so a prior run that ended with orphan `tool_calls` cannot poison every subsequent run with malformed conversation structure), and the deterministic-resolve-gate contract where the `patrol_resolve_finding` tool adapter rejects LLM-driven resolves of event/persistent category findings (`backup`, `reliability`, `security`, `general`) when a deterministic verifier exists for the finding's key and that verifier either still detects the failure signal **or returns an inconclusive result** — preventing the LLM from optimistically resolving a finding its current investigation simply didn't re-surface, which was the source of the "Backup failed" flap (detected → auto-resolved → re-detected ten times in a day before this gate). The fail-closed-on-inconclusive policy treats verifier errors (timeouts, executor unavailability, transport faults) as "we don't know" rather than "go ahead": resolution of an event/persistent finding is effectively permanent (next detection registers as a regression and inflates counters), so the safe default is to refuse and require either a successful re-verification or operator action. The gate has a symmetric counterpart, the verified stale-resolve contract: `reconcileStaleFindings` (`internal/ai/patrol_ai.go`) may auto-resolve an event/persistent finding that was seeded but neither re-reported nor resolved ONLY when the finding's key has a deterministic verifier and that verifier affirmatively confirms the failure signal is gone — absence of a re-report remains insufficient evidence for these categories, "still present" or inconclusive verification leaves the finding active (the same fail-closed default), and verifications are capped per reconcile pass (`maxVerifiedStaleResolvesPerRun`) with deferred candidates logged and retried on the next successful full patrol. Without this counterpart the lifecycle was asymmetric: a genuinely fixed backup or recovered service stayed an active finding indefinitely unless the LLM happened to call `patrol_resolve_finding`. `hasDeterministicVerifierForKey` (`internal/ai/patrol_findings.go`) is the single source of truth for which keys have verifiers, consulted by both the gate and the reconcile pass, and must stay aligned with the dispatch switch in `verifyFixDeterministically` (it previously listed two of the seven dispatch keys, silently skipping verification that existed). Finding keys normalize onto the canonical verifier vocabulary in `normalizeFindingKey` via an alias map of unambiguous directional synonyms (`high-cpu` → `cpu-high`, `high-memory` → `memory-high`, `high-disk` → `disk-high`) so deduplication and deterministic verification meet on one key, and the `patrol_report_finding` key guidance (`internal/ai/tools/tools_patrol.go`) teaches the canonical vocabulary; semantically distinct keys (`pbs-job-failed`, `node-offline`) must not be aliased onto verifier keys whose resource model they do not match, the assessment-recovery contract where the overall-health "Recent Patrol errors" coverage factor in `summarizeRecentPatrolCoverage` suppresses the score penalty once three consecutive trailing successful full Patrol runs exist at the most-recent end of the recent-runs window — so the grade reflects current reality after a Patrol-affecting bug is fixed rather than dragging stale failures forward for the ~9 hours it takes scheduled runs to age them out of the trailing-10 ratio, the orphan-tool-call-repair contract where `convertToProviderMessages` injects synthetic is_error tool result messages for any `tool_call_id` in an assistant message that has no matching downstream tool result, so a chat session that ended mid-tool-call (network drop, ctx timeout, browser crash) cannot poison its next message with the structural-violation error the provider rejects — the synthetic content is marked is_error=true and explains the interruption so the model can retry the call or proceed without the data, and the patrol-session-bound contract where `ExecutePatrolStream` calls `SessionStore.TrimMessages` after persisting each run's messages to cap the patrol-main session at 200 messages (roughly two recent runs' worth) — without the bound the file grew unbounded at every scheduled run, reaching 16 MB and 3,593 messages within a month and making every `AddMessage` rewrite linearly more expensive; the canonical Patrol forensic log is the `PatrolRunRecord` history surfaced at `/api/ai/patrol/runs`, not the chat-session-shaped file+1. Update this contract when canonical AI runtime or transport entry points move, including transport-level provider request-shape changes such as OpenAI-compatible `tool_choice` handling, runtime-failure classification splits (for example separating tool-choice request rejection, no tool-capable endpoint, and generic model-level lack of tool support into distinct causes), Patrol-specific verification surfaces such as `POST /api/ai/patrol/preflight` that exercise the full chat-completions path with a minimal tool definition rather than only listing models, Patrol-preflight cache observability where the AI Service caches the most recent preflight outcome (success, soft warning, or classified failure) and the AI settings response surfaces it as `patrol_preflight` so the UI can hydrate a "last verified" indicator without forcing operators to re-run preflight on every page load, the auto-trigger contract on `HandleUpdateAISettings` where the save handler runs `TriggerPatrolPreflightAsync` only when the change actually moved Patrol transport (model swap, provider key for that model changed, or assistant just enabled with a Patrol model) so routine settings saves do not burn provider tokens, the startup-seed contract where the AI Service handler dispatches the same async preflight on Pulse boot when assistant is enabled and a Patrol model is configured so the cache is populated for the first `/api/settings/ai` poll after a restart instead of blanking back to "never verified", the readiness-integration contract where the `tools` check in the Patrol readiness payload consults the cached preflight and surfaces the classified evidence (success, soft warning, or failure with classified summary plus "last preflight <age>") for the configured provider+model when available (falling back to the static `PatrolToolReadinessForModel` classifier only when the cache is empty or holds a result for a different model), the preflight-runtime-recovery contract where a successful Patrol preflight with an observed tool call resolves the synthetic Patrol runtime failure finding while failed or no-tool-call preflights leave it active, the stateless-Patrol-input contract where `ExecutePatrolStream` must pass only the current run's user prompt into the agentic loop rather than reloading the persisted `patrol-main` session history (so a prior run that ended with orphan `tool_calls` cannot poison every subsequent run with malformed conversation structure), and the deterministic-resolve-gate contract where the `patrol_resolve_finding` tool adapter rejects LLM-driven resolves of event/persistent category findings (`backup`, `reliability`, `security`, `general`) when a deterministic verifier exists for the finding's key and that verifier either still detects the failure signal **or returns an inconclusive result** — preventing the LLM from optimistically resolving a finding its current investigation simply didn't re-surface, which was the source of the "Backup failed" flap (detected → auto-resolved → re-detected ten times in a day before this gate). The fail-closed-on-inconclusive policy treats verifier errors (timeouts, executor unavailability, transport faults) as "we don't know" rather than "go ahead": resolution of an event/persistent finding is effectively permanent (next detection registers as a regression and inflates counters), so the safe default is to refuse and require either a successful re-verification or operator action. The gate has a symmetric counterpart, the verified stale-resolve contract: `reconcileStaleFindings` (`internal/ai/patrol_ai.go`) may auto-resolve an event/persistent finding that was seeded but neither re-reported nor resolved ONLY when the finding's key has a deterministic verifier and that verifier affirmatively confirms the failure signal is gone — absence of a re-report remains insufficient evidence for these categories, "still present" or inconclusive verification leaves the finding active (the same fail-closed default), and verifications are capped per reconcile pass (`maxVerifiedStaleResolvesPerRun`) with deferred candidates logged and retried on the next successful full patrol. Without this counterpart the lifecycle was asymmetric: a genuinely fixed backup or recovered service stayed an active finding indefinitely unless the LLM happened to call `patrol_resolve_finding`. `hasDeterministicVerifierForKey` (`internal/ai/patrol_findings.go`) is the single source of truth for which keys have verifiers, consulted by both the gate and the reconcile pass, and must stay aligned with the dispatch switch in `verifyFixDeterministically` (it previously listed two of the seven dispatch keys, silently skipping verification that existed). Finding keys normalize onto the canonical verifier vocabulary in `normalizeFindingKey` via an alias map of unambiguous directional synonyms (`high-cpu` → `cpu-high`, `high-memory` → `memory-high`, `high-disk` → `disk-high`) so deduplication and deterministic verification meet on one key, and the `patrol_report_finding` key guidance (`internal/ai/tools/tools_patrol.go`) teaches the canonical vocabulary; semantically distinct keys (`pbs-job-failed`, `node-offline`) must not be aliased onto verifier keys whose resource model they do not match, the assessment-recovery contract where the overall-health "Recent Patrol errors" coverage factor in `summarizeRecentPatrolCoverage` suppresses the score penalty once three consecutive trailing successful full Patrol runs exist at the most-recent end of the recent-runs window — so the grade reflects current reality after a Patrol-affecting bug is fixed rather than dragging stale failures forward for the ~9 hours it takes scheduled runs to age them out of the trailing-10 ratio, the orphan-tool-call-repair contract where `convertToProviderMessages` injects synthetic is_error tool result messages for any `tool_call_id` in an assistant message that has no matching downstream tool result, so a chat session that ended mid-tool-call (network drop, ctx timeout, browser crash) cannot poison its next message with the structural-violation error the provider rejects — the synthetic content is marked is_error=true and explains the interruption so the model can retry the call or proceed without the data, and the patrol-session-bound contract where `ExecutePatrolStream` calls `SessionStore.TrimMessages` after persisting each run's messages to cap the patrol-main session at 200 messages (roughly two recent runs' worth) — without the bound the file grew unbounded at every scheduled run, reaching 16 MB and 3,593 messages within a month and making every `AddMessage` rewrite linearly more expensive; the canonical Patrol forensic log is the `PatrolRunRecord` history surfaced at `/api/ai/patrol/runs`, not the chat-session-shaped file2. Keep AI runtime and shared API proof routing aligned in `registry.json`3. Preserve explicit coverage for chat, Patrol, remediation, and cost-control behavior when AI runtime changes. Interactive Assistant and Patrol tool selection must remain model-owned: Pulse may provide governed context, tools, approval state, resource-resolution facts, safety policy, and neutral resource-scoped action history, but it must not add prompt-keyword routers, expected-tool retries, auto-recovery tool calls, keyword-matched prior-fix suggestions, or Pulse-authored remediation/finding fallbacks that choose the next investigative or corrective action for the model.Assistant FSM gates remain safety boundaries after the model chooses a tool:@@ -1917,6 +2839,9 @@ deriving an older display status from `workflowStatusHistory`.metadata, while manual run requests, scheduled ticks, and scopedalert/anomaly runs must fail or skip before LLM execution when the selectedPatrol model/provider is known not-ready.+ Readiness checks may retain stable machine IDs such as `configuration`, but+ human-facing labels in the settings payload must frame the operator boundary+ as Patrol mode rather than Patrol configuration.Monitor-only Patrol autonomy saves are part of the same runtime gate:when the safe-remediation extension or entitlement is unavailable, both thebrowser state owner and `internal/api/ai_handlers.go` must clear stale@@ -1968,9 +2893,19 @@ deriving an older display status from `workflowStatusHistory`.the fact's category/key/value, so the model can attribute and weight what itreports instead of stating untraceable facts. Both are omitted when empty.When the shared registry blocks a control tool in read-only mode, its- operator guidance must point to Assistant & Patrol settings and the Pulse- Assistant Permissions Control mode, not legacy Pulse Assistant settings- paths.+ operator guidance must point to Pulse Intelligence > Provider & Models+ settings and the Pulse Assistant Permissions Control mode, not legacy Pulse+ Assistant settings paths.+ Runtime status, preflight, settings-persistence, profile-suggestion, and+ remediation-impact messages must preserve the same product boundary:+ use Pulse Assistant only for the first-party in-app Assistant runtime itself,+ Provider & Models for the shared provider/model settings surface, and Pulse+ Intelligence for the shared Assistant/Patrol/agent substrate rather than+ reviving the legacy generic `Pulse AI` label or `Pulse Assistant settings`+ copy. Pulse Intelligence external-agent setup copy may point to Patrol mode,+ but it must frame the first step as setting how autonomous Patrol should be+ before connected agents request work; it must not present connected-agent+ setup as a separate operations-loop, MCP-readiness, or feature-unlock model.9. Keep self-hosted Patrol messaging aligned with the v6 GA product contract:ordinary self-hosted installs use BYOK or local providers, and the runtimemust not surface retired managed-model credits, trial prompts, account-backed@@ -1978,24 +2913,24 @@ deriving an older display status from `workflowStatusHistory`.The shared app shell must also keep `/cloud` and `/cloud/signup` out ofordinary self-hosted public routes so Cloud acquisition cannot reappear as aproxy for retired hosted-model or AI quickstart activation.- The public AI overview must likewise use productized context language such+ The public Pulse Intelligence overview must likewise use productized context language suchas alert history, Patrol runs, and resource timelines instead of presenting`incident memory` as a standalone feature. It must also describe Patrolbaselines, trends, correlations, forecasts, and deterministic signals asmodel-bound evidence/context rather than Pulse-authored intelligence orfallback finding creation.10. Keep discovery-analysis prompt bounds and response budgets aligned across- `internal/ai/service.go` and the shared service-discovery prompt builders:- the runtime must reserve enough output tokens for structured discovery JSON,- and discovery prompts must cap fact/path/port fan-out explicitly instead of- relying on providers to truncate oversized infrastructure inventories.- That same runtime-owned command-target boundary must resolve hostnames- through `internal/unifiedresources/hostname_equivalence.go`.- `internal/ai/tools/internal_routing.go`,- `internal/ai/tools/tools_control.go`, and adjacent AI command helpers may- match a short host against its FQDN, but they must not broaden that- fallback into a generic short-name collapse that would make two distinct- FQDNs with the same short host look interchangeable.+ `internal/ai/service.go` and the shared service-discovery prompt builders:+ the runtime must reserve enough output tokens for structured discovery JSON,+ and discovery prompts must cap fact/path/port fan-out explicitly instead of+ relying on providers to truncate oversized infrastructure inventories.+ That same runtime-owned command-target boundary must resolve hostnames+ through `internal/unifiedresources/hostname_equivalence.go`.+ `internal/ai/tools/internal_routing.go`,+ `internal/ai/tools/tools_control.go`, and adjacent AI command helpers may+ match a short host against its FQDN, but they must not broaden that+ fallback into a generic short-name collapse that would make two distinct+ FQDNs with the same short host look interchangeable.11. Keep AI runtime transport compatibility separate from operator-facingproduct copy. Existing Patrol payload fields such as `fixed_count`,`auto_fix_model`, and `patrol_auto_fix` may remain stable wire/API names,@@ -2130,7 +3065,7 @@ deriving an older display status from `workflowStatusHistory`.container-restart, container-stop, k8s-rollout-restart, plus theProxmox VM lifecycle classes proxmox-vm-reboot, proxmox-vm-stop,proxmox-vm-start, proxmox-vm-shutdown and the matching pct-driven- proxmox-ct-* container lifecycle classes) and return hand-authored+ proxmox-ct-\* container lifecycle classes) and return hand-authoredoperational copy: what the command actually touches, how Pulse willread back success. The additions append onto the defaultsafety/verification arrays rather than replacing them, so the@@ -2231,8 +3166,8 @@ deriving an older display status from `workflowStatusHistory`.whole-surface review sessions even when their bounded action referencesname individual findings; the session list must not infer a`patrol_finding` identity from those action references once metadata is- present. Patrol configuration failure handoffs remain- `patrol_configuration_failure` sessions and may expose only the safe+ present. Patrol mode save-failure handoffs remain+ `patrol_configuration_failure` sessions for compatibility and may expose only the saferuntime-failure boolean needed for browser presentation. Run-specificfields stay reserved for `patrol_run` handoffs, while hidden model context,command payloads, preflight output, and action results remain@@ -2283,11 +3218,11 @@ deriving an older display status from `workflowStatusHistory`.does not yet carry the latest approval ID. Those references are reviewcontext only: they must not include raw command text, must not grantapproval or execution authority, and must route any requested action back- through the governed approval/remediation flow. Patrol provides the+ through the governed approval and fix flow. Patrol provides theconfigured LLM with observed finding context, evidence, policy posture, and- governed action state; the LLM owns diagnosis and remediation reasoning.+ governed action state; the LLM owns diagnosis and fix reasoning.Operator-visible handoffs must not describe Patrol as having already- authored the correct remediation. The finding briefing may carry only+ authored the correct fix. The finding briefing may carry onlyfactual governed action artifact metadata from those same structuredreferences after live-approval recovery, including safe current status,request/expiry timestamps, approval policy, action plan identity, plan@@ -2403,6 +3338,62 @@ deriving an older display status from `workflowStatusHistory`.## Current State+The canonical findings store must present one active Patrol issue per real+problem. When the model reports an equivalent active sibling under a different+finding ID, key, or severity for the same resource, `internal/ai/findings.go`+must merge it into the existing active finding before it reaches+`/api/ai/patrol/findings`, keep the highest observed severity for the merged+issue, increment recurrence, and record a bounded duplicate-merge lifecycle+event instead of creating a second operator-facing row. Distinct symptoms on+the same resource, such as CPU pressure and memory pressure, must remain+separate findings. Verification is+`go test ./internal/ai -run 'TestFindingsStore'` plus+`go test ./internal/ai -run 'TestPatrolService_GetAllFindings|TestPatrolService_GetFindingsForResource|TestPatrolService_GetAllFindingsIncludingResolved'`.++Public Pulse Intelligence overview, safety, and onboarding copy now use the+same visible Patrol mode labels as the product: `Watch only`,+`Ask before changes`, `Auto-fix safe issues`, and `Policy autopilot`. The+legacy `Only watch`, `Fix safe issues`, and `Full control` names may remain+only as historical context or compatibility implementation details, not as customer-facing Patrol mode labels.++Assistant provider-readiness repair actions now use the canonical Pulse+Intelligence > Provider & Models route+`/settings/pulse-intelligence/provider`. The legacy `/settings/system-ai`+route remains a compatibility alias for old deep links, not a href emitted by+new Assistant provider-repair actions.++Rejected Patrol investigation-fix approvals are terminal governed-action+decisions in the AI runtime. `/api/ai/approvals/{id}/deny` must persist the+approval-store denial, record a rejected unified action-audit decision when the+approval carries a governed action plan, and move the owning finding to+`fix_rejected` so Assistant handoffs, Patrol summaries, and external agent+adapters see the declined fix as explicit loop state rather than a disappeared+pending approval.++Legacy Assistant provider-tool declarations for manifest-backed Patrol finding+lifecycle tools now consume the manifest-owned raw input schemas through+`agentcapabilities.ProviderInputSchemaFromRaw`. The native Assistant runtime+may keep first-party model-facing descriptions, but it must not re-declare+required arguments such as `resolution_note` or dismissal `note` when the+canonical Pulse Intelligence manifest and API contract mark those fields+optional.+Legacy native Assistant utility provider aliases for `run_command`, `fetch_url`,+and `set_resource_url`, plus their provider JSON schemas, are owned by+`agentcapabilities.LegacyAssistantUtilityProviderTools`. The older native+Assistant service may continue to expose those compatibility aliases while the+execution migration proceeds, but it must consume the shared provider projection+and shared argument constants rather than carrying inline schema maps or local+tool-input string keys.+Native Assistant registry tools that operate on Patrol finding lifecycle state+must also consume the same `agentcapabilities` argument vocabulary for+`finding_id`, `resolution_note`, `reason`, and `note` instead of repeating+local field-name strings in their provider schema or execution maps.++Anthropic runtime provider execution is API-key backed only. Legacy Anthropic+OAuth tokens may remain in encrypted settings solely for disconnect cleanup;+they do not make Anthropic configured, do not instantiate a provider, do not+refresh tokens, and cannot send model requests.+The done event carries `context_limit_tokens` (the active model's contextwindow from `providers.ContextWindowTokens`) alongside token usage, and thedrawer's last-turn summary renders input tokens as a percentage of that@@ -2669,13 +3660,13 @@ hidden server log. The referenced OpenCode source at fetched `dev` commit`packages/opencode/src/cli/cmd/tui/component/prompt/index.tsx`. Pulse adaptsthat contract at the owning stream boundary: `WorkflowStateData` carries`attempt`, `max_attempts`, and `retry_after_ms`, and `AgenticLoop` emits- `provider_retry` before sleeping between transient pre-output provider- attempts. The frontend active-turn footer and live transcript workflow row- render that same typed workflow state immediately as compact attempt/backoff- progress, counting down `retry_after_ms` from `started_at` while the turn- remains active, so the user sees Pulse moving through a retry instead of- staring at an obsolete provider-wait message. Retry workflow states are not- held behind workflow-history pacing.+`provider_retry` before sleeping between transient pre-output provider+attempts. The frontend active-turn footer and live transcript workflow row+render that same typed workflow state immediately as compact attempt/backoff+progress, counting down `retry_after_ms` from `started_at` while the turn+remains active, so the user sees Pulse moving through a retry instead of+staring at an obsolete provider-wait message. Retry workflow states are not+held behind workflow-history pacing.Assistant workflow progress is also a live typed activity row while a turn isin flight, not only hidden footer state. The referenced OpenCode source at@@ -2693,14 +3684,14 @@ same typed status, and visible assistant content, reasoning, tool,approval/question, terminal `done`, and terminal `error` events clear that row.The frontend now also keeps a bounded live-only `workflowStatusHistory` for theactive assistant message so the reducer preserves state continuity while- backend preparation, context, and provider-start labels are being replaced. The- shared workflow-status presentation helper owns both the transcript row and the- active-turn composer footer so the two live surfaces show the latest canonical- workflow state immediately. Retry/backoff and stream-idle liveness states cut- through pacing because they are current route health, not neutral setup motion.- The transcript and footer therefore show current motion while the provider is- starting, retrying, or reasoning, but completed answers do not retain stale- internal-progress prose.+backend preparation, context, and provider-start labels are being replaced. The+shared workflow-status presentation helper owns both the transcript row and the+active-turn composer footer so the two live surfaces show the latest canonical+workflow state immediately. Retry/backoff and stream-idle liveness states cut+through pacing because they are current route health, not neutral setup motion.+The transcript and footer therefore show current motion while the provider is+starting, retrying, or reasoning, but completed answers do not retain stale+internal-progress prose.Stream-idle heartbeats are part of that same visible workflow state. When thefrontend knows the selected provider/model route from the backend workflow eventor the streaming assistant message, the idle heartbeat must render as@@ -2754,8 +3745,8 @@ tool metadata updates in `packages/opencode/src/session/tools.ts` lines 54-63,while adapting the interaction to Pulse's single active-turn plus queuedfollow-up safety model.-Assistant command access follows the same OpenCode-referenced footer principle:-commands are reachable from prompt-adjacent chrome, not only from a hidden slash+Assistant chat actions follow the same OpenCode-referenced footer principle:+actions are reachable from prompt-adjacent chrome, not only from a hidden slashdraft. The referenced OpenCode source at fetched `dev` commit`e82542b8023a8374f29c23b70ec019c8f256354e` builds the direct command surface in`packages/opencode/src/cli/cmd/run/footer.command.tsx` (`RunCommandMenuBody`@@ -3042,6 +4033,11 @@ usage and spend backing Pulse Assistant and Patrol rather than generic `AI`history, and `frontend-modern/src/utils/aiCostPresentation.ts` must own thetitle, empty/loading states, budget note, and reset/export history messaging sosettings shells and runtime widgets do not fork their own usage wording.+Usage grouping rows must present product concepts such as Assistant sessions,+Patrol runs, Discovery runs, or concrete resource labels. Raw target storage+keys, opaque session identifiers, UUIDs, and values such as+`assistant_session_title:<id>` are accounting implementation detail and must+stay out of the operator-facing table.That same runtime-facing table ownership applies to the cost dashboard shell:`frontend-modern/src/components/AI/AICostDashboard.tsx` owns provider usage,budget, and history semantics, but its tabular presentation must compose the@@ -3249,6 +4245,9 @@ for provider naming, provider health labels, control-level semantics,chat drawer title/subtitle, launcher title/aria copy, session-menu labeling,discovery hint framing, chat/session empty states, assistant message andquestion-card labels.+Discovery hint framing must follow the Pulse Intelligence settings IA: use the+simple `Discovery` label, and explain the concrete service context it unlocks,+without promoting workload discovery as another first-class product surface.Settings and chat surfaces must consume those helpers instead of keeping localAI wording or model/provider inference branches.Assistant chat must not render Pulse-authored explore pre-pass cards or@@ -3378,7 +4377,12 @@ handoffs preserve Patrol provenance before later action-audit hydration refreshethe current action state. Backend chat refresh of a Patrol finding handoff musthydrate the same requester identity directly from the live approval record, soAssistant does not depend on browser-authored metadata to distinguish-Patrol-origin proposals from generic Assistant actions.+Patrol-origin proposals from generic Assistant actions. Rejected Patrol+investigation-fix approvals must also enter that shared decision lifecycle:+`/api/ai/approvals/{id}/deny` records a rejected unified action-audit decision+when the approval has a governed action plan and moves the owning Patrol+finding to `fix_rejected`, so a declined fix remains a visible governed loop+outcome rather than disappearing when the pending approval leaves the queue.The same ownership includes the Pulse query tool schema under`internal/ai/tools/`: topology-query input names must stay canonical insidethe AI runtime itself, so new tool arguments such as `max_proxmox_nodes`@@ -3965,7 +4969,7 @@ legacy managed-credit block conditions remain part of the governed runtimecontract instead of being inferred later from the last successful patrolsummary.When missing provider configuration blocks Patrol, `blocked_reason` must point-to Assistant & Patrol provider settings and tool-capable Patrol model+to Pulse Intelligence > Provider & Models settings and tool-capable Patrol modelselection.That runtime-state contract must be derived from live Patrol runtime inputs,not only from the last failed run attempt, and the backend must clear any stale@@ -3976,6 +4980,12 @@ derive `Health A` or `100/100` from "no active findings" alone when recentPatrol evidence is limited to alert-scoped runs or includes recent Patrol runerrors; the summary must degrade and explain that overall infrastructure healthis not fully verified until a recent successful full Patrol run exists.+The backend may keep precise full-run, scoped-run, and verification terms in+wire fields and internal decisions, but browser-facing summary and handoff copy+emitted from `internal/ai` should translate that precision into check language:+recent broad checks, targeted checks, follow-up checks, current issues, and+verified outcomes. Runtime explanations must not surface activation-loop,+proof-strip, or scoped/full-run jargon as the ordinary operator vocabulary.That coverage explanation must also stay faithful to the actual recent runshape. When the most recent verification evidence includes a full Patrol runthat ended with errors, the health summary must say that a recent full patrol@@ -4008,17 +5018,21 @@ so the full-run seed/reconcile path must not auto-resolve them as`Resource no longer exists in infrastructure` just because `ai-service` is notpresent in the infrastructure snapshot. Those findings stay active untilPatrol actually succeeds or resolves them for a Patrol-owned reason.-That success boundary includes provider-backed scoped Patrol runs. A successful-scoped run proves that Patrol can currently reach the selected provider/model-and complete tool-backed analysis, so it must clear the synthetic-`ai-service` runtime failure just as a successful full Patrol run does, without-loosening ordinary scoped finding reconciliation for infrastructure issues.+That success boundary includes provider-backed scoped Patrol runs and successful+Patrol tool-call preflights. A successful scoped run proves that Patrol can+currently reach the selected provider/model and complete tool-backed analysis;+a successful preflight with an observed tool call proves the configured+provider/model currently accepts Patrol's tool-call path. Either must clear the+synthetic `ai-service` runtime failure just as a successful full Patrol run+does, without loosening ordinary scoped finding reconciliation for+infrastructure issues. A soft-warning preflight where the provider responds but+the model does not emit a tool call is not sufficient recovery evidence.Because those findings represent Patrol blindness rather than operator-triagedinfrastructure noise, the Patrol runtime must also reject manual acknowledge,snooze, dismiss, resolve, and suppress actions against synthetic `ai-service`runtime findings. The canonical recovery path is to correct Patrol provider-configuration in Assistant & Patrol settings and let Patrol re-evaluate the-runtime condition on the next run.+configuration in Pulse Intelligence > Provider & Models settings and let Patrol+re-evaluate the runtime condition on the next run.The shared findings lifecycle must also treat a regressed issue as a new activeoccurrence. When a resolved finding reappears, `internal/ai/findings.go` mustclear any stale acknowledgement timestamp from the prior occurrence instead of@@ -4227,6 +5241,17 @@ after every `loop.ExecuteWithTools` return — success or error,since the operator was billed regardless of whether the loopproduced a clean response. It emits a `cost.UsageEvent` with`UseCase="chat"` in the same shape the rest of the runtime uses.+When a chat turn carries a product-originated finding, resource, handoff,+action, or structured-mention context, the event may also include the coarse+`context_scope` classifier so privacy-safe telemetry can count governed-context+Assistant collaboration without exporting prompts, session IDs, resource IDs,+finding IDs, command text, or action payloads.+When the same turn includes accepted model-selected governed tool calls, the+agentic loop records only the total count on the resulting cost event. That+count supports Pulse Intelligence adoption telemetry for Assistant+collaboration while keeping tool names, arguments, results, provider call IDs,+transcript content, resource IDs, finding IDs, command text, action payloads,+and session IDs out of persisted/exported telemetry.The store is threaded through `chat.Config.CostStore`, wired bythe router from the per-tenant `AISettingsHandler.GetAIService`via `Service.CostStore()`. `ExecutePatrolStream` deliberatelydiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex a0e12fface..d87ea8359c 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -25,100 +25,113 @@ the trust boundary that keeps customer-safe support diagnostics and normalproduct API routes free of maintainer commercial analytics.## Canonical Files+1. `internal/api/contract_test.go`-1a. `internal/api/platform_connection_shared.go`-1b. `internal/api/metadata_handlers_shared.go`+ 1a. `internal/api/platform_connection_shared.go`+ 1b. `internal/api/metadata_handlers_shared.go`2. `internal/api/resources.go`3. `internal/api/discovery_handlers.go`-3. `internal/api/alerts.go`-4. `internal/api/activity_audit_handlers.go`-5. `internal/api/actions.go`-5a. `internal/api/action_executor.go`-5b. `internal/api/docker_container_action_executor.go`-5c. `internal/api/proxmox_guest_action_executor.go`-6. `internal/actionplanner/planner.go`-7. `pkg/pulsecli/api_client.go`-8. `pkg/pulsecli/actions.go`-9. `pkg/pulsecli/fleet.go`-10. `pkg/pulsecli/root.go`-5. `frontend-modern/src/types/api.ts`-6. `frontend-modern/src/types/actionAudit.ts`-7. `frontend-modern/src/api/actionAudit.ts`-7a. `frontend-modern/src/api/resourceActions.ts`-6. `frontend-modern/src/api/responseUtils.ts`-7. `frontend-modern/src/components/Settings/APITokenManager.tsx`-8. `frontend-modern/src/components/Settings/apiTokenManagerModel.ts`-9. `frontend-modern/src/constants/apiScopes.ts`-9. `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`-10. `frontend-modern/src/components/Settings/useAPITokenManagerState.ts`-11. `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx`-12. `frontend-modern/src/components/Settings/NodeModalAuthenticationSection.tsx`-15. `frontend-modern/src/components/Settings/NodeModalBasicInfoSection.tsx`-16. `frontend-modern/src/components/Settings/nodeModalModel.ts`-17. `frontend-modern/src/components/Settings/NodeModalMonitoringSection.tsx`-18. `frontend-modern/src/components/Settings/NodeModalSetupGuideSection.tsx`-19. `frontend-modern/src/components/Settings/NodeModalStatusFooter.tsx`-20. `frontend-modern/src/components/Settings/useNodeModalState.ts`-21. `frontend-modern/src/utils/agentInstallCommand.ts`-22. `frontend-modern/src/api/nodes.ts`-23. `frontend-modern/src/api/license.ts`-24. `frontend-modern/src/api/monitoredSystemLedger.ts`-25. `frontend-modern/src/api/resources.ts`-26. `frontend-modern/src/api/monitoring.ts`-27. `internal/api/monitored_system_ledger.go`-28. `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`-29. `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts`-31. `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts`-32. `frontend-modern/src/utils/apiTokenPresentation.ts`-33. `frontend-modern/src/utils/infrastructureSettingsPresentation.ts`-34. `internal/api/router_routes_auth_security.go`-35. `internal/api/relay_hosted_runtime.go`-36. `internal/api/ai_hosted_runtime.go`-37. `internal/api/router_routes_licensing.go`-38. `internal/api/reporting_inventory_handlers.go`-39. `internal/cloudcp/portal/bootstrap.go`-40. `internal/cloudcp/portal/handlers.go`-41. `internal/cloudcp/portal/page.go`-42. `internal/cloudcp/portal/page_templates.go`-43. `internal/cloudcp/portal/frontend/src/index.ts`-44. `internal/cloudcp/portal/frontend/src/shell.ts`-45. `internal/cloudcp/portal/frontend/src/billing.ts`-46. `internal/cloudcp/portal/frontend/src/runtime.ts`-47. `internal/cloudcp/portal/frontend/src/types.ts`-48. `internal/cloudcp/portal/frontend/src/styles.css`-49. `internal/cloudcp/portal/frontend/tsconfig.json`-50. `internal/cloudcp/portal/frontend_sync_test.go`-51. `internal/api/recovery_handlers.go`-51a. `internal/api/pbs_backups.go`-52. `internal/api/config_setup_handlers.go`-52a. `internal/api/setup_script_render.go`-52b. `internal/api/cloud_agent_install_command.go`-53. `internal/api/demo_mode_commercial.go`-54. `internal/api/demo_mode_operations.go`-55. `internal/api/security_status_capabilities.go`-56. `internal/api/demo_middleware.go`-56. `frontend-modern/src/stores/aiRuntimeState.ts`-57. `internal/api/connections_types.go`-58. `internal/api/connections_aggregator.go`-59. `internal/api/connections_handlers.go`-60. `internal/api/connections_probe.go`-61. `frontend-modern/src/api/connections.ts`-62. `frontend-modern/src/utils/connectionErrorPresentation.ts`-63. `internal/api/availability_handlers.go`-64. `frontend-modern/src/api/availabilityTargets.ts`-65. `frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/AvailabilityTargetSlot.tsx`-65a. `frontend-modern/src/components/Settings/AvailabilitySettingsPanel.tsx`-65b. `frontend-modern/src/components/Settings/availabilitySettingsModel.ts`-66. `pkg/aicontracts/investigation.go`-67. `internal/api/ai_intelligence_handlers.go`-68. `frontend-modern/src/api/ai.ts`-69. `frontend-modern/src/api/aiChat.ts`-69a. `frontend-modern/src/api/aiChatDevStreamFixture.ts`-70. `frontend-modern/src/api/patrol.ts`-71. `frontend-modern/src/api/generated/aiChatEvents.ts`-72. `internal/api/agent_exec_token_binding.go`-73. `internal/agentcontext/`-74. `scripts/generate-types.go`+4. `internal/api/alerts.go`+5. `internal/api/activity_audit_handlers.go`+6. `internal/api/actions.go`+ 5a. `internal/api/action_executor.go`+ 5b. `internal/api/docker_container_action_executor.go`+ 5c. `internal/api/proxmox_guest_action_executor.go`+7. `internal/actionplanner/planner.go`+8. `pkg/pulsecli/api_client.go`+9. `pkg/pulsecli/actions.go`+10. `pkg/pulsecli/fleet.go`+11. `pkg/pulsecli/root.go`+12. `frontend-modern/src/types/api.ts`+13. `frontend-modern/src/types/actionAudit.ts`+14. `frontend-modern/src/api/actionAudit.ts`+ 7a. `frontend-modern/src/api/resourceActions.ts`+ 7b. `frontend-modern/src/api/agentCapabilities.ts`+ 7c. `frontend-modern/src/api/generated/agentCapabilities.ts`+15. `frontend-modern/src/api/responseUtils.ts`+16. `frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx`+17. `frontend-modern/src/components/Settings/APITokenManager.tsx`+18. `frontend-modern/src/components/Settings/apiTokenManagerModel.ts`+19. `frontend-modern/src/constants/apiScopes.ts`+20. `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`+21. `frontend-modern/src/components/Settings/useAPITokenManagerState.ts`+22. `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx`+23. `frontend-modern/src/components/Settings/NodeModalAuthenticationSection.tsx`+24. `frontend-modern/src/components/Settings/NodeModalBasicInfoSection.tsx`+25. `frontend-modern/src/components/Settings/nodeModalModel.ts`+26. `frontend-modern/src/components/Settings/NodeModalMonitoringSection.tsx`+27. `frontend-modern/src/components/Settings/NodeModalSetupGuideSection.tsx`+28. `frontend-modern/src/components/Settings/NodeModalStatusFooter.tsx`+29. `frontend-modern/src/components/Settings/useNodeModalState.ts`+30. `frontend-modern/src/utils/agentInstallCommand.ts`+31. `frontend-modern/src/api/nodes.ts`+32. `frontend-modern/src/api/license.ts`+ 23a. `frontend-modern/src/api/settings.ts`+33. `frontend-modern/src/api/monitoredSystemLedger.ts`+34. `frontend-modern/src/api/resources.ts`+35. `frontend-modern/src/api/monitoring.ts`+36. `internal/api/monitored_system_ledger.go`+37. `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`+38. `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts`+39. `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts`+40. `frontend-modern/src/utils/apiTokenPresentation.ts`+41. `frontend-modern/src/utils/infrastructureSettingsPresentation.ts`+42. `internal/api/router_routes_auth_security.go`+43. `internal/api/relay_hosted_runtime.go`+44. `internal/api/ai_hosted_runtime.go`+45. `internal/api/router_routes_licensing.go`+46. `internal/api/reporting_inventory_handlers.go`+47. `internal/cloudcp/portal/bootstrap.go`+48. `internal/cloudcp/portal/handlers.go`+49. `internal/cloudcp/portal/page.go`+50. `internal/cloudcp/portal/page_templates.go`+51. `internal/cloudcp/portal/frontend/src/index.ts`+52. `internal/cloudcp/portal/frontend/src/shell.ts`+53. `internal/cloudcp/portal/frontend/src/billing.ts`+54. `internal/cloudcp/portal/frontend/src/runtime.ts`+55. `internal/cloudcp/portal/frontend/src/types.ts`+56. `internal/cloudcp/portal/frontend/src/styles.css`+57. `internal/cloudcp/portal/frontend/tsconfig.json`+58. `internal/cloudcp/portal/frontend_sync_test.go`+59. `internal/api/recovery_handlers.go`+ 51a. `internal/api/pbs_backups.go`+60. `internal/api/config_setup_handlers.go`+ 52a. `internal/api/setup_script_render.go`+ 52b. `internal/api/cloud_agent_install_command.go`+61. `internal/api/demo_mode_commercial.go`+62. `internal/api/demo_mode_operations.go`+63. `internal/api/security_status_capabilities.go`+64. `internal/api/demo_middleware.go`+65. `frontend-modern/src/stores/aiRuntimeState.ts`+66. `internal/api/connections_types.go`+67. `internal/api/connections_aggregator.go`+68. `internal/api/connections_handlers.go`+69. `internal/api/connections_probe.go`+70. `frontend-modern/src/api/connections.ts`+71. `frontend-modern/src/utils/connectionErrorPresentation.ts`+72. `internal/api/availability_handlers.go`+73. `frontend-modern/src/api/availabilityTargets.ts`+74. `frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/AvailabilityTargetSlot.tsx`+ 65a. `frontend-modern/src/components/Settings/AvailabilitySettingsPanel.tsx`+ 65b. `frontend-modern/src/components/Settings/availabilitySettingsModel.ts`+75. `pkg/aicontracts/investigation.go`+ 66a. `pkg/aicontracts/orchestrator_deps.go`+ 66b. `pkg/aicontracts/fix_execution.go`+76. `internal/api/ai_intelligence_handlers.go`+77. `frontend-modern/src/api/ai.ts`+78. `frontend-modern/src/api/aiChat.ts`+ 69a. `frontend-modern/src/api/aiChatDevStreamFixture.ts`+79. `frontend-modern/src/api/patrol.ts`+80. `frontend-modern/src/api/generated/aiChatEvents.ts`+81. `internal/api/agent_exec_token_binding.go`+ 72a. `cmd/pulse-mcp/main.go`+ 72b. `cmd/pulse-mcp/README.md`+ 72c. `cmd/agent-probe/main.go`+ 72d. `scripts/generate-pulse-intelligence-docs.go`+82. `internal/agentcontext/`+ 73a. `internal/agentcapabilities/`+ 73b. `pkg/extensions/ai_autofix.go`+83. `scripts/generate-types.go`## Shared Boundaries@@ -126,6 +139,285 @@ Assistant chat `workflow_state` events are a shared AI/API payload boundary.The backend source of truth is `internal/ai/chat.WorkflowStateData`, generatedto `frontend-modern/src/api/generated/aiChatEvents.ts` by`scripts/generate-types.go` and pinned by `internal/api/contract_test.go`.+Agent capabilities manifest payloads follow the same rule:+`internal/agentcapabilities.Manifest`, `Capability`, `CapabilityCategory`,+`SurfaceContract`, `SurfaceContractComponent`, `OperatorSurfaceContract`,+`SurfaceAffordanceContract`, `MCPAdapterContract`, and+`MCPAdapterConfigFamily` generate+`frontend-modern/src/api/generated/agentCapabilities.ts`; the shared frontend+client must alias those generated types instead of redeclaring a browser-local+manifest model. The manifest-owned `surfaceContract` is the+canonical API statement that Pulse Intelligence Core is shared, Pulse Patrol is+the primary built-in operator, and Pulse Assistant plus Pulse MCP are the+supported access paths over the same governed capabilities, including the+affordances each path exposes. The Patrol surface description is also+manifest-owned product copy; API clients, docs, and settings projections must+render the concise policy-bound operator summary from the manifest instead of+carrying local control-level prose.+The manifest-owned `mcpAdapter` is the canonical API statement for Pulse MCP+client setup facts: server name, command, base URL flag/default, token+environment variable, and supported client config families. UI and docs may+compose copy around those facts, but they must not carry component-local or+README-local setup constants.+Manifest-backed MCP initialize responses must render that relationship from+`Manifest.SurfaceContract` rather than hard-coded adapter prose. Native+Assistant operating instructions must use the same shared renderer, with+surface-specific affordance flags controlling only whether tools, resources,+prompts, capability metadata, and Assistant-native interactive questions are+advertised. MCP initialize responses and JSON-RPC handlers must resolve those+surface affordances before advertising or serving tools, resources, prompts, or+capability metadata; raw manifest capability and prompt presence can satisfy an+allowed affordance, but cannot enable a disabled surface affordance. Prompt+advertising and serving must use `MCPManifestSurfacePromptProjectionSupported`+and `GetMCPPromptFromManifestSurface` so the target surface's `prompts`+affordance and the manifest-owned workflow prompt catalogue are resolved+together before initialize, `prompts/list`, or `prompts/get` exposes prompts.+The Pulse Intelligence manifest docs generator must also render the MCP README+surface-contract block from `Manifest.SurfaceContract` and the MCP client+config block from `Manifest.MCPAdapter`; scope, tool, prompt, error-code, and+Assistant/MCP/Core/Patrol relationship docs are all API-manifest projections,+not parallel onboarding snapshots.+Native Assistant workflow-prompt rendering is a canonical API projection of+that same manifest. `POST /api/ai/workflow-prompts/render` is an authenticated+`ai:chat` route owned by `internal/api/ai_handler.go` and+`internal/api/router_routes_ai_relay.go`; it accepts the manifest prompt name+plus argument map, validates them against the manifest-owned workflow prompt+catalogue through `internal/agentcapabilities`, and returns only the rendered+Assistant prompt text plus description. Browser+clients must read prompt names, display labels, presentation kind hints,+descriptions, and arguments through the generated `workflowPrompts` manifest+type and call `AIChatAPI.renderWorkflowPrompt` rather than rendering prompt+templates locally. Browser context may carry a preferred workflow prompt name+only as a request to render one manifest-owned starter through that API route;+it is not a transport for prompt text or a reason to bypass argument resolution.+MCP `prompts/list` projects those same labels as protocol prompt titles and MCP+`prompts/get` remains the protocol-edge projection over the same shared+workflow-prompt core. Route inventory and AI chat scope tests must pin that+route so it does not drift into public manifest discovery, relay-mobile access,+or `ai:execute` approval replay.+Successful workflow prompt rendering is also the API boundary for content-free+guided-starter activity: native Assistant rendering records only the manifest+prompt name, coarse Assistant surface, and timestamp; first-party Pulse app+surfaces that start the same governed journey without rendering prompt text may+record through authenticated `POST /api/ai/workflow-prompts/activity`; and MCP+adapters that render prompts locally may report the same event through+`POST /api/agent/workflow-prompt-activity`. The first-party marker route is an+authenticated `ai:chat` route owned by `internal/api/ai_handler.go` and+`internal/api/router_routes_ai_relay.go`; it accepts one JSON object with a+manifest-declared prompt name plus an optional first-party surface, allows only+`pulse_assistant`, `pulse_patrol`, `patrol_control`, `patrol_autonomy`, and+the legacy `pulse_pro_activation` alias, defaults omitted surface to `pulse_assistant`,+rejects unknown prompts or non-first-party surfaces, and returns no payload.+`pulse_patrol` is the ordinary first-party Patrol entry marker, while+`patrol_control` is the current paid Patrol control handoff marker for the+same manifest-owned Patrol work prompt. `patrol_autonomy` and+`pulse_pro_activation` remain legacy Pro activation entry-point aliases for+compatibility only; none of these surfaces is a separate prompt, route,+Assistant surface, or completion proof.+The browser-only paid Patrol control handoff may carry the coarse+`patrolControlStarter=patrol_control` route query so Patrol can record that+same marker after navigation. The old `operationsLoopStarter=patrol_control`,+`operationsLoopStarter=patrol_autonomy`, and+`operationsLoopStarter=pulse_pro_activation` values must remain accepted as+legacy aliases that normalize to the current Patrol control starter, but those+queries are not API payload fields and may not contain prompt arguments,+resource IDs, finding IDs, account identity, token identity, or terminal proof.+Consuming that route handoff must still enter the authenticated first-party+marker route described here before any status projection treats it as Patrol+control starter evidence. Operations status projections count `pulse_patrol`,+`patrol_control`, legacy `patrol_autonomy`, and legacy `pulse_pro_activation`+as Patrol control starter evidence, while `proActivationOperationsLoopStarterCount`+preserves only the legacy Pro activation entry-point count. The+agent marker route is an authenticated `monitoring:read` API-token route,+accepts only one JSON object with a manifest-declared prompt name, normalizes+the `X-Pulse-Agent-Surface` value `pulse_mcp` to the Pulse MCP surface, and+must reject unknown prompts without recording activity. Neither route may+accept or persist prompt arguments, rendered text, resource IDs, finding IDs,+session IDs, token identity, request bodies, or model output.+Telemetry preview and outbound ping payloads project that same content-free+activity into 30-day Patrol work starter counters: one total starter count+plus source-specific Assistant, Pulse Patrol, primary Patrol control, legacy+Pro activation entry-point, and Pulse MCP counts. Those payload fields are+API-contract fields for adoption/value measurement only; they must not carry+prompt text, prompt arguments, resource/finding identity, session identity,+checkout/account identity, or request details.+`GET /api/agent/patrol-control/status` owns the shared content-safe Patrol+control value state exposed to native Pulse and MCP-facing agents. The legacy+`GET /api/agent/operations-loop/status` URL remains a compatibility alias, not+the primary route:+`not_started`, `in_progress`, `governed_decision_recorded`,+`verified_needs_mcp`, and `verified`. `verified_needs_mcp` remains a tolerated+legacy value for older payloads, but MCP readiness is no longer a Patrol+control value gate. Counts remain the aggregate evidence source, while+`patrolControlValueState` is the canonical branch signal for distinguishing a+safe terminal rejection from a verified operations-value outcome.+`patrolAutonomyValueState` and+`proActivationValueProofState` mirror that value as compatibility aliases for+older commercial and telemetry consumers. Only `verified` means the first-party+Patrol control loop has approved-governed action, verified outcome proof, and+recorded action history; adjacent UI or agent clients must not infer that from+`nextAction=complete` alone.+Current-work precedence is part of that same contract: `activeFindingCount` must+include aggregate active issue-level findings from the canonical Patrol findings+store, including runtime/service findings that are not attached to a unified+registry resource. Pending approvals and active findings are current operator+work and must outrank older completed/resolved loop proof when the route chooses+`nextAction` and step status. Historical Patrol control proof remains recorded+as count-only value evidence, but it must render as history until the current+finding or approval is handled.+The authenticated `GET /api/agent/patrol-control/status` projection exposes the same content-free starter evidence as count-only fields+(`operationsLoopStarterCount`, `assistantOperationsLoopStarterCount`,+`patrolOperationsLoopStarterCount`,+`patrolControlOperationsLoopStarterCount`,+`patrolControlCompletedOperationsLoopCount`,+`patrolControlResolvedOperationsLoopCount`, `patrolControlValueState`,+`patrolAutonomyOperationsLoopStarterCount`,+`patrolAutonomyCompletedOperationsLoopCount`,+`patrolAutonomyResolvedOperationsLoopCount`, `patrolAutonomyValueState`,+`proActivationOperationsLoopStarterCount`,+`proActivationCompletedOperationsLoopCount`,+`proActivationResolvedOperationsLoopCount`, and `mcpOperationsLoopStarterCount`)+inside the status evidence window. These fields are orientation/adoption+evidence for Assistant, Patrol control, older compatibility clients, and MCP+loop entry points. `patrolControlOperationsLoopStarterCount` is the primary+starter count for native Pulse Patrol and Patrol control starts, while+`patrolAutonomyOperationsLoopStarterCount` mirrors it for compatibility and+`proActivationOperationsLoopStarterCount` is retained only for older+external-agent clients; primary clients must use+`patrolControlOperationsLoopStarterCount`. Only the completed-loop and+resolved-loop counts may+summarize that first-party starter evidence and terminal loop evidence+coexisted in the current evidence window. `patrolControlCompletedOperationsLoopCount`+requires Patrol issue evidence, contextual Assistant or external-agent+collaboration, and either a rejected governed decision or an approved governed+decision with verified outcome proof. `patrolControlResolvedOperationsLoopCount`+is stricter: it requires Patrol issue evidence, contextual Assistant or+external-agent collaboration, an approved governed decision, and verified+outcome proof. The completed-loop, resolved-loop, and value-state+`patrolAutonomy*` and `proActivation*` fields are compatibility aliases for the+same Patrol control proof model; human-facing manifest descriptions and+external-agent docs must describe all of these fields as Patrol control+compatibility metadata rather than a Pro activation journey. The+`internal/telemetry.ClassifyPulseIntelligencePatrolControlProof` helper is the+canonical count-only classifier for those completed/resolved counts and the+`patrolControlValueState` string; API status projections and outbound+telemetry/adoption projections must call that helper or its legacy alias+wrapper instead of restating the branch rules locally, and must not pass+`externalAgentReady` into that classifier because MCP readiness is not a Patrol+control proof input. The+`externalAgentReady` field is not manifest-shape readiness by itself: the route+must first prove the Pulse MCP Patrol work contract exists in the canonical+manifest and then require a single non-expired API token covering every scope+required by the published Pulse MCP Patrol work capability set. It is+optional external-agent readiness for settings handoff and MCP clients, not a+completed/resolved Patrol control proof requirement. They must+not expose+prompt names, surfaces, identities, payloads, checkout/account+identity, route parameters, action IDs, command text, resource names, or+finding IDs, and they do not replace the detail-owning Assistant, Patrol,+governed-action, verification, or finding-resolution routes.+The public `docs/AI.md` Pulse Intelligence overview must use the same API+projection: its marked Core/Patrol/Assistant/MCP block is rendered by+`PulseIntelligenceOverviewMarkdown(Manifest.SurfaceContract)`, while+surrounding product detail may stay human-authored.+The External agents settings panel is part of the same API projection: its+surface summary must consume the generated frontend manifest types and+`/api/agent/capabilities.surfaceContract` through+`frontend-modern/src/api/agentCapabilities.ts` instead of repeating+Assistant/MCP/Core/Patrol relationship copy or affordance labels in the+component.+Its MCP client examples and copied config snippets must also consume+`/api/agent/capabilities.mcpAdapter` through that same shared frontend client;+the component must not own local `pulse-mcp`, `--base-url`, token-env, or+client-family constants, and copied config snippets should be available only+inside an on-demand setup disclosure rather than becoming the default API Access+page content.+The public investigation orchestrator dependency contract in+`pkg/aicontracts/orchestrator_deps.go` is also part of this shared boundary:+orchestrator tool-call and tool-result payloads must bridge to the shared+`agentcapabilities.ProviderToolCall` / `ProviderToolResult` shapes through the+`aicontracts` projection helpers, preserving Assistant/MCP input-map,+thought-signature, and provider-result normalization instead of duplicating+local payload copies in API handlers.+The API contract proof for native Assistant provider tools follows the same+shared-boundary rule: chat-facing API tests must pin+`PulseToolExecutor.AssistantProviderTools` as the single native Assistant+provider-tool projection entrypoint, while the executor owns the manifest+surface-affordance gate and the pairing of runtime-available registry tools,+registry governance descriptors, and Assistant-native interaction tools before+provider requests are assembled.+Surface tool inventories are a shared Pulse Intelligence API contract rather+than a UI or adapter inference. `internal/agentcapabilities.SurfaceToolContract`+and `ProjectPulseIntelligenceSurfaceToolContracts` must describe Pulse+Assistant tools as `assistant_registry` sourced provider tools, splitting+registry-backed tools from Assistant-native interaction tools such as+`pulse_question`, while manifest-declared external-adapter tools are+`capability_manifest` sourced request/response capabilities projected from+`Manifest.Capabilities` by `ProjectManifestSurfaceToolContracts` and published+on `Manifest.SurfaceToolContracts`. External surfaces, including Pulse MCP,+must resolve through the surface-generic manifest contract path and must fail+closed when their published `surfaceToolContracts` entry is missing. Native+Assistant provider-tool projection must enter through+`ProjectPulseAssistantProviderTools`, so disabled Assistant affordances also+fail closed instead of letting runtime registry availability re-enable provider+tools. The two surfaces therefore share governance vocabulary and core+execution contracts without pretending their tool-name lists are+interchangeable.+The frontend-facing contract type must be generated from that same Go shape+(`frontend-modern/src/api/generated/agentCapabilities.ts`) and re-exported by+the shared agent-capabilities client. Do not hand-write a parallel frontend+copy. Runtime surface-tool normalization and count/presentation helpers also+belong in `frontend-modern/src/api/agentCapabilities.ts`, so native Assistant+UI, MCP onboarding surfaces, and future agent-compatible surfaces do not infer+tool availability from local tool-name lists. Do not expose live Assistant+registry availability through the public, cacheable `/api/agent/capabilities`+manifest; that runtime inventory belongs behind the authenticated+`GET /api/ai/assistant/surface-tools` Assistant surface endpoint when the UI+needs it. The Pulse Assistant shell may render a runtime tool-posture chip, but+it must call `AIChatAPI.getAssistantSurfaceTools()` and+`getAgentSurfaceToolPosturePresentation` instead of hard-coding registry tool+names or treating MCP capability names as native Assistant tools. The Agent+integrations panel may render MCP tool posture from the static public manifest,+but the request/response capability filtering and `SurfaceToolContract`+construction must be backend-owned in `Manifest.SurfaceToolContracts`; the+generic `getAgentManifestSurfaceToolContract(manifest,+AGENT_SURFACE_ID_PULSE_MCP)` frontend client path may normalize only that+published manifest field. Missing `surfaceToolContracts` entries must not cause+the browser to infer MCP tools from raw capabilities. The panel must not know the+streaming-only `subscribe_events` exception, call a per-surface projection+alias, or maintain a local MCP tool count. The shared frontend client must not+export a Pulse-MCP-specific surface tool helper; MCP onboarding uses the generic+surface resolver with `AGENT_SURFACE_ID_PULSE_MCP` so future external surfaces do+not require browser-side helper duplication.+Frontend surfaces that need to know whether Pulse MCP exposes the full Patrol+work loop must derive that readiness through the shared agent-capabilities+client from the manifest-owned operations-loop workflow prompt, MCP adapter+contract, and Pulse MCP surface tool contract rather than hard-coding readiness+in the consuming component. The Patrol work capability set includes the+content-safe `get_patrol_control_status` capability as the first orientation+read, followed by fleet context, resource context, findings, governed action+planning, action decision, action execution, and finding resolution; readiness+helpers, workflow-prompt gates, and MCP surface projections must consume that+one shared set instead of maintaining local loop-tool lists. Native Patrol+surfaces that need the current loop evidence must call the authenticated+`GET /api/agent/patrol-control/status` route through+`frontend-modern/src/api/agentCapabilities.ts`, not through a+Patrol-local fetcher or a browser-side reconstruction of agent capability+progress. First-party Patrol presentation may tolerate legacy `open_mcp` and+`verified_needs_mcp` payloads as already verified operator-loop history, and it+may show `externalAgentReady` only as optional external-agent context. Patrol+current-work state/model must not fetch the manifest to derive MCP readiness,+accept MCP readiness props, or introduce a page-local MCP readiness contract.+First-party Patrol UI may present that projection as Patrol current work, but+the authenticated route, query compatibility aliases, and generated wire fields+remain the `operations-loop` contract until a deliberate API migration changes+them.+Backend consumers that need an external surface's request/response capability+set must resolve it through `ResolveManifestSurfaceToolContract` and+`ManifestSurfaceToolCapabilities`, not by reading raw `surfaceToolContracts`+entries directly; that shared path normalizes `CapabilityNames`/`ToolNames`,+filters non-request/response capabilities, and enforces the resolved surface+`tools` affordance before docs, adapters, or UI projections see any tools.Provider retry progress must use typed fields (`attempt`, `max_attempts`,`retry_after_ms`) on that same event instead of frontend-only string parsing orprovider-specific ad hoc events; the Assistant UI may format those fields, but@@ -334,38 +626,280 @@ templates are collapsible guidance over the account payload; they must notreplace tenant-local setup facts, become a readiness source, or require apayload shape change when the portal presents compact client rows.-1. `frontend-modern/src/api/agentProfiles.ts` shared with `agent-lifecycle`: the agent profiles frontend client is both an agent lifecycle control surface and a canonical API payload contract boundary.-2. `frontend-modern/src/api/ai.ts` shared with `ai-runtime`: the AI frontend client is both an AI runtime control surface and a canonical API payload contract boundary.-3. `frontend-modern/src/api/nodes.ts` shared with `agent-lifecycle`: the shared Proxmox node client is both an agent lifecycle setup/install control surface and a canonical API payload contract boundary.-4. `frontend-modern/src/api/notifications.ts` shared with `notifications`: the notifications frontend client is both a notification delivery control surface and a canonical API payload contract boundary.-5. `frontend-modern/src/api/orgs.ts` shared with `organization-settings`: the organization frontend client is both an organization settings control surface and a canonical API payload contract boundary.-6. `frontend-modern/src/api/patrol.ts` shared with `ai-runtime`: the Patrol frontend client is both an AI runtime control surface and a canonical API payload contract boundary.- The Patrol status payload owns Patrol readiness as structured API state:- provider/model/settings/tool prerequisites must travel as bounded readiness- checks instead of frontend-only heuristics or generic analysis-failed text.- `/api/settings/ai/update` must persist recoverable provider/model changes- and return the same structured readiness cause in its settings payload, while- `/api/ai/patrol/run` must use the `patrol_readiness_not_ready` error taxonomy- when it rejects a known-bad Patrol runtime configuration. Bounded `status`,- `cause`, `provider`, and `model` details are the canonical transport shape.- `/api/ai/patrol/findings` is the canonical Patrol-page findings source, and- `/api/ai/patrol/runs` records may expose bounded `source` provenance so demo- evidence can be separated from live runtime assessment state without- changing the stable run payload shape.- The Patrol status payload's `trigger_status` object is the canonical- transport for alert/anomaly trigger queue and mode facts. Patrol summary UI- may present that state as factual trigger-mode context, but it must not infer- trigger enablement or queue state from settings payloads, route state, or- run-history labels.-7. `frontend-modern/src/api/rbac.ts` shared with `organization-settings`: the RBAC frontend client is both an organization settings control surface and a canonical API payload contract boundary.-8. `frontend-modern/src/api/security.ts` shared with `security-privacy`: the security frontend client is both a security/privacy control surface and a canonical API payload contract boundary.-9. `frontend-modern/src/api/updates.ts` shared with `deployment-installability`: the updates frontend client is both a deployment-installability control surface and a canonical API payload contract boundary.- It must preserve `/api/updates/plan.readiness` payloads as backend-owned- API state so settings UI can render `ready`, `attention`, and `blocked`- update checks without rebuilding upgrade state locally. The frontend may- disable blocked installs, but the backend apply route remains authoritative- and must reject a recomputed `blocked` readiness verdict.-10. `frontend-modern/src/components/Settings/APITokenManager.tsx` shared with `security-privacy`: the API token settings surface is both a security/privacy control surface and a canonical API payload contract boundary.+1. `cmd/pulse-mcp/main.go` shared with `ai-runtime`: the Pulse MCP adapter runtime is both an AI runtime surface for external-agent access to Pulse Intelligence and a canonical API contract projection over the agent capabilities manifest and Pulse MCP surface tool contract.+2. `cmd/pulse-mcp/README.md` shared with `ai-runtime`: the Pulse MCP adapter guide is both an AI runtime surface for external-agent access to Pulse Intelligence and a canonical API contract projection over the agent capabilities manifest.+ Manifest path placeholders projected by `cmd/pulse-mcp` are canonical API+ path parameters, not string concatenation hints: adapter calls must use the+ shared `internal/agentcapabilities` call projection helper to+ percent-encode placeholder values as single path segments before dispatching+ to Pulse so resource IDs and node IDs cannot change the declared route. That+ same helper owns the top-level-argument fallback for JSON request bodies:+ non-placeholder write arguments become the body when the caller does not+ provide a nested `body` object, and internal tool-call metadata such as+ approved-action grants is stripped before any public API body is built.+ MCP tool descriptions and fallback tool input schemas must project the same+ manifest-owned method/path, scope, request/response shape, category,+ action-mode, approval-policy, and stable error-code metadata through that+ shared helper rather than maintaining a second adapter-local capability+ table. The manifest-owned `surfaceToolContracts` field is the Pulse MCP+ tool allowlist for `tools/list` and `tools/call`, and the same shared+ `ManifestSurfaceToolCapabilities` resolver must gate execution, so+ streaming-only capabilities such as `subscribe_events`, or raw manifest+ capabilities omitted from the Pulse MCP surface contract, cannot be invoked+ through an MCP request/response tool even if a client sends their name+ manually. Adding a raw capability to `Manifest.Capabilities` is not enough+ to publish an MCP tool; the Pulse MCP `surfaceToolContracts` allowlist must+ opt it into that external-agent surface. A `surfaceToolContracts` entry may+ narrow the operator surface's affordance posture, but it must not re-enable a+ disabled surface affordance; normalized external-adapter surface summaries+ must clear tool and capability names when the effective `tools` affordance is+ false. MCP initialize capability+ advertisement and the shared manifest-backed tool, resource, and prompt+ handlers must also pass through the manifest-owned surface affordance+ contract, so tools, resources, prompts, and capability metadata are exposed+ only when the target surface allows that affordance and the manifest has the+ backing data to satisfy it. Prompt support is proven through+ `MCPManifestSurfacePromptProjectionSupported`, not a raw workflow-prompt+ presence check at individual call sites. Generated MCP prompt inventory must+ also pass through the same surface prompt projection gate rather than listing+ raw workflow prompts directly.+ MCP notification advertising, transport-event filtering, notification+ method projection, and SSE-to-MCP notification bridging are also shared API+ contract projections: the event kinds listed in+ `capabilities.experimental.pulseNotifications.kinds`, the+ `subscribe_events` manifest description, and the API SSE producer must use+ the same `internal/agentcapabilities` event vocabulary rather than+ adapter-local string lists.+ The agent SSE subscription transport, record parser, actionable-record+ filter, and MCP notification projector are part of that same shared boundary:+ `cmd/pulse-mcp` and reference probes may own connection lifetime and+ reconnect policy, but they must not carry their own event-stream request+ headers, subscribe status handling, `event:` / `data:` scanner loops,+ transport-event parser semantics, or SSE-to-MCP notification bridge.+ MCP JSON-RPC method constants, JSON-RPC envelopes, request decoding,+ notification response policy, shared manifest-backed and+ surface-affordance-gated tool-server semantics,+ shared tool-server method dispatch, initialize/tool-call/resource payloads,+ notification method projection, MCP resource URI projection,+ context-backed `resources/list` / `resources/read` projection, and prompt+ catalog/rendering payloads belong to the MCP adapter edge. MCP must not+ re-export neutral provider-call, provider-result, registry-preparation,+ result-construction, result-text, result-interpretation, or direct-execution+ helpers under MCP names; those helpers live under the neutral shared tool+ core and are consumed directly by Assistant and adapter surfaces. The raw+ `tools/call` params decode may stay in `mcp.go`, but parameter+ normalization and validation belong to the neutral shared tool-call core:+ tool names must be trimmed and required, argument maps must be cloned deeply+ enough to detach nested JSON-like `body` maps/slices and then initialized,+ and invalid params must fail before capability lookup so empty-name calls are+ not reported as unknown manifest tools.+ Projected-tool behavior hints are neutral API manifest projection state:+ `ToolBehaviorHints` belongs in the shared projection core, while+ `MCPToolAnnotations` may exist only as a protocol-facing alias at the MCP+ adapter edge.+ Native Assistant direct registry execution must consume the neutral+ `ToolCallParams` normalization/validation contract and the shared+ invalid-params, unknown-tool, and control-disabled tool result helpers from+ `internal/agentcapabilities/tool_call.go` before tool lookup or handler+ dispatch, rather than carrying a second name/argument path or local+ entrypoint failure envelope for in-app execution.+ The approved-action text projection for Pulse tool calls is part of that+ same boundary: API relay execution may receive the legacy command string,+ but parsing tool names, `default_api:` prefixes, and quoted arguments must+ happen in `internal/agentcapabilities`, return the shared+ `ToolCallParams` shape, and pass through the same normalization and+ validation contract as decoded MCP `tools/call` payloads. The same helper+ owns the `current_resource` handle plus governed aliases and recursive+ tool-argument detector so native Assistant, API relay execution, and+ MCP-compatible adapters cannot drift on unresolved attached-resource+ placeholder handling.+ Structured tool response envelopes, the tool-result error-code parser,+ the `verification.ok` evidence parser, provider tool/call/result shape projection,+ provider-result context projection for full transcript plus model-context results,+ neutral provider-tool behavior hints and Pulse governance metadata,+ provider-emitted streamed tool-input parsing, final provider tool-input raw+ fallback handling, native Assistant provider-tool name catalog and exact/prefix matching,+ provider tool-call artifact detection and streaming tool-name prefix holding, question-type/defaulting+ vocabulary, native Assistant question input parsing, and tool error-code/FSM recovery vocabulary are part of that same boundary; native Assistant tool+ protocol wrappers may preserve only neutral registry tool aliases and must+ not expose MCP/JSON-RPC wire aliases or carry local copies of provider+ tool JSON, provider call params, chat tool-call JSON, chat tool-result JSON,+ provider-native tool-call artifact regexes, the blocked/failed/retryable shape, common error-code strings, recovery error-code parsing, write self-verification evidence parsing, or the+ approval-required / policy-blocked marker prefixes, payload `type` values,+ formatter helpers, parser helpers, or typed approval-required payload+ contract used by governed Assistant tool outcomes. Chat and API consumers+ may project that shared marker payload into their own event shapes, but they+ must not define anonymous local approval-marker readers or discard the shared+ approved-action argument map returned for replayed tool execution. MCP-shaped+ provider projection aliases and structured tool-response result aliases must+ not exist as helper wrappers; MCP may keep protocol wire aliases only for the+ actual `tools/call` params/result envelopes while using the neutral provider,+ tool-response, and direct-execution helpers by their shared names.+ Assistant registry tool schemas must also behave as API-contract values:+ `agentcapabilities.Tool.NormalizeCollections` owns independent copies of+ structured `InputSchema` maps, required slices, enum slices, provider+ input-schema maps, and JSON-schema default containers; direct provider+ schema projection helpers must normalize through that same path before+ emitting provider JSON, while `ToolRegistry.Register` and+ `ToolRegistry.ListTools` must normalize at their respective boundaries+ instead of exposing mutable caller-owned or registry-owned schema+ collections.+ Manifest-backed external-agent tools follow the same rule:+ `agentcapabilities.CloneCapability`, `CloneCapabilities`, and+ `CloneRawMessage` must detach raw manifest `inputSchema` and `outputSchema`+ bytes, structured `_meta["pulse.capability"]` maps, and error-code slices+ before lookup or projection results leave the shared boundary, so MCP+ `tools/list` serialization and adapter post-processing cannot mutate the+ fetched or canonical manifest.+ Provider tool-call input normalization is owned there too: provider+ responses, stored Assistant transcript calls, and API-facing chat-message+ projections must clone tool input maps, nested JSON-like argument values, and+ raw provider thought-signature payload bytes+ through the shared `ProviderToolCall.NormalizeCollections` path rather than+ reusing mutable caller maps across surfaces.+ Provider result context projection is owned there as well: native Assistant,+ external adapters, and future Pulse Intelligence surfaces must use the shared+ projection for full transcript results and model-context results instead of+ locally pairing provider tool-result structs or reimplementing the truncation+ notice.+ Shared tool result normalization is also owned by the neutral tool-result+ core:+ `agentcapabilities.ToolResult.NormalizeCollections` must initialize empty+ content collections, detach content slices, and clone structuredContent maps+ before native Assistant registry execution or external MCP method dispatch+ returns a result envelope.+ Result-text extraction, result interpretation, JSON object and array-wrapper+ structuredContent projection, and `HTTPCallResponse` to shared tool-result+ wrapping must live in `internal/agentcapabilities/tool_result.go`; MCP may+ alias only the actual `MCPToolResult`/`MCPContent` wire envelopes and must+ not keep MCP-named constructor, text, or interpretation wrappers.+ Direct native execution over those shared result envelopes must use the+ surface-neutral `agentcapabilities.InterpretDirectToolExecution` helper;+ MCP-named direct-execution symbols are not part of the adapter contract.+ Manifest fetches, agent request+ construction, API-token header placement, JSON content-type posture,+ capability HTTP invocation, neutral `ExecuteCapabilityToolHTTP`+ request/response execution, request/response capability body-return helpers,+ and stable non-2xx error-envelope formatting are+ shared-core behavior. `cmd/pulse-mcp` may own stdio and retry/backoff policy,+ but it must not re-declare the MCP wire/result structs or local agent HTTP+ client rules that Assistant tool execution and reference clients also+ consume.+3. `frontend-modern/src/api/agentCapabilities.ts` shared with `ai-runtime`: the agent capabilities frontend client is both the Pulse Intelligence external-agent manifest consumer and a canonical API payload contract boundary.+4. `frontend-modern/src/api/agentProfiles.ts` shared with `agent-lifecycle`: the agent profiles frontend client is both an agent lifecycle control surface and a canonical API payload contract boundary.+5. `frontend-modern/src/api/ai.ts` shared with `ai-runtime`: the AI frontend client is both an AI runtime control surface and a canonical API payload contract boundary.+6. `frontend-modern/src/api/aiChat.ts` shared with `ai-runtime`: the Assistant chat frontend client is both the first-party Assistant transport surface and a canonical API payload contract boundary.+7. `frontend-modern/src/api/generated/agentCapabilities.ts` shared with `ai-runtime`: the generated agent capabilities frontend types are both the Pulse Intelligence manifest TypeScript projection and a canonical API payload contract boundary.+8. `frontend-modern/src/api/nodes.ts` shared with `agent-lifecycle`: the shared Proxmox node client is both an agent lifecycle setup/install control surface and a canonical API payload contract boundary.+9. `frontend-modern/src/api/notifications.ts` shared with `notifications`: the notifications frontend client is both a notification delivery control surface and a canonical API payload contract boundary.+10. `frontend-modern/src/api/orgs.ts` shared with `organization-settings`: the organization frontend client is both an organization settings control surface and a canonical API payload contract boundary.+11. `frontend-modern/src/api/patrol.ts` shared with `ai-runtime`: the Patrol frontend client is both an AI runtime control surface and a canonical API payload contract boundary.+ The Patrol status payload owns Patrol readiness as structured API state:+ provider/model/settings/tool prerequisites must travel as bounded readiness+ checks instead of frontend-only heuristics or generic analysis-failed text.+ `/api/settings/ai/update` must persist recoverable provider/model changes+ and return the same structured readiness cause in its settings payload, while+ `/api/ai/patrol/run` must use the `patrol_readiness_not_ready` error taxonomy+ when it rejects a known-bad Patrol runtime configuration. Bounded `status`,+ `cause`, `provider`, and `model` details are the canonical transport shape.+ Patrol may demote the shared model catalog behind an explicit advanced UI+ action, but it must still source selectable model routes from the shared AI+ runtime catalog/settings payloads rather than introducing a Patrol-local+ model list or inferred provider catalog.+ `/api/ai/patrol/findings` is the canonical Patrol-page findings source, and+ `/api/ai/patrol/runs` records may expose bounded `source` provenance so demo+ evidence can be separated from live runtime assessment state without+ changing the stable run payload shape.+ The Patrol status payload's `trigger_status` object is the canonical+ transport for alert/anomaly trigger queue and mode facts. Patrol summary UI+ may present that state as factual trigger-mode context, but it must not infer+ trigger enablement or queue state from settings payloads, route state, or+ run-history labels.+12. `frontend-modern/src/api/rbac.ts` shared with `organization-settings`: the RBAC frontend client is both an organization settings control surface and a canonical API payload contract boundary.+13. `frontend-modern/src/api/security.ts` shared with `security-privacy`: the security frontend client is both a security/privacy control surface and a canonical API payload contract boundary.+14. `frontend-modern/src/api/updates.ts` shared with `deployment-installability`: the updates frontend client is both a deployment-installability control surface and a canonical API payload contract boundary.+ It must preserve `/api/updates/plan.readiness` payloads as backend-owned+ API state so settings UI can render `ready`, `attention`, and `blocked`+ update checks without rebuilding upgrade state locally. The frontend may+ disable blocked installs, but the backend apply route remains authoritative+ and must reject a recomputed `blocked` readiness verdict.+15. `frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx` shared with `ai-runtime`, `frontend-primitives`: the External agents settings panel is the optional settings-shell projection of Pulse MCP onboarding, the AI runtime connected-agent onboarding surface, and a presentation consumer of the shared agent capabilities frontend client.+ The panel may own settings placement, copy composition, local fallback+ rendering, and the user-facing hierarchy that frames Patrol as the primary+ governed operator with MCP clients as secondary access to the same approval+ policy and action history. Capability category order, labels,+ descriptions, required scopes, the Pulse Intelligence surface contract,+ surface affordance badges, and capability rows must still come through+ `frontend-modern/src/api/agentCapabilities.ts` instead of a browser-local+ category table or component-local manifest fetcher.+ Manifest-owned prompt, scope, failure-code, tool-contract posture, and raw capability+ inventories should be available for client builders but must stay demoted+ behind a builder-oriented Developer details disclosure rather than occupying+ the default Assistant settings view. The external-agent setup checklist must+ stay behind a user-triggered `Show connector setup` disclosure, while direct setup+ links open that disclosure automatically. Posture and policy summaries+ belong under Patrol access model, while prompt, scope, failure-code, and+ tool inventories must be nested behind Live manifest details so opening the+ developer disclosure does not immediately dump the full manifest. Visible+ nested labels should use user-facing terms such as Agent starting points and+ Agent capabilities rather than raw workflow/MCP inventory labels. External+ adapter posture must read as `External agents expose ... through Patrol+ mode`; `Pulse MCP` and `pulse_operations_loop` may remain only as manifest+ or wire names inside builder/debugging detail, not as the visible product+ model a user must learn.+ The External agents Patrol handoff must use `Choose Patrol mode` and+ frame the first step as choosing what Patrol may handle automatically before+ a connected agent can request work; connected-agent setup must not revive+ activation-loop or raw MCP readiness language as the primary call to action.+ When the setup checklist is expanded, Step 1 owns the visible Patrol-mode+ handoff and the panel header must not repeat the same call to action.+ The same wording applies when API-owned projections feed Patrol availability+ or plan-comparison presentation: customer-facing helpers must describe+ governed scope as what Patrol may handle automatically, not as how far Patrol+ can go or how much control Patrol has.+ Client config follows the same product hierarchy: it may expose+ manifest-derived OpenCode and Claude-style wrappers, but the default panel+ must lead with Patrol control and scoped-token setup, not raw JSON blocks.+ Direct `/settings/pulse-intelligence/assistant#external-agent-setup` links+ must scroll and briefly focus the External agents panel after the+ Assistant settings layout settles, so the external-agent setup route lands+ on the optional client setup boundary rather than generic token inventory.+ Legacy `/settings/security/api#external-agent-setup` and+ `/settings/security/api#pulse-mcp-setup` links must remain accepted and+ redirect to the canonical Pulse Intelligence Assistant route. Normal API+ Access visits keep token management first; token-preset links may still+ land on API Access because credential minting remains the API token+ contract, not a separate credential or execution surface.+ The Patrol control handoff must target the Patrol operator surface where the+ inline control level is configured, while API Access remains the token+ and external-agent setup surface.+ Failure-code+ summaries in the panel must derive from capability `errorCodes` through the+ same frontend manifest client instead of a browser-local recovery-code+ registry. Explanatory capability-publication copy in that panel must point+ at the manifest-owned surface contract, not raw backend capability rows, so+ the API contract remains clear that Pulse MCP publication requires the+ `surfaceToolContracts` boundary. Token setup handoffs in+ this panel may link to the API token creation form, but the named+ full-surface preset must remain the manifest-derived `Patrol external agent`+ preset from `frontend-modern/src/components/Settings/APITokenManager.tsx`+ and `frontend-modern/src/components/Settings/apiTokenManagerModel.ts`; the+ Agent integrations panel must not hardcode or recompute the required token+ scope set. MCP adapter setup facts in the panel are also manifest-owned:+ server name, command, base URL flag/default, token environment variable,+ supported config families, and copied OpenCode/`mcpServers` snippets must+ flow through `frontend-modern/src/api/agentCapabilities.ts` from+ `/api/agent/capabilities.mcpAdapter`, not component-local constants.+ The default setup copy must frame connected agents as optional access to+ Pulse context and Patrol work, keep Patrol as the built-in operator that+ watches, acts within Patrol mode, asks when approval is required, verifies+ outcomes, and records history, and say external agents use that same+ boundary. It must not use "Use Pulse MCP only" or "outside client" copy, and+ it must not describe external-agent setup as a separate operator journey.+ The Patrol control handoff belongs to the Patrol control route; API Access+ may mint the token and show MCP client setup, but it must not send operators+ to Assistant settings to choose Patrol's control level.+16. `frontend-modern/src/components/Settings/APITokenManager.tsx` shared with `security-privacy`: the API token settings surface is both a security/privacy control surface and a canonical API payload contract boundary.The API token inventory table may own credential and usage cells, but itmust inherit embedded table framing from `frontend-primitives``PulseDataGrid` rather than carrying API-token-local scroll or border@@ -381,13 +915,21 @@ payload shape change when the portal presents compact client rows.Token refresh/loading state remains API contract data only while thevisible spinner shell routes through frontend-primitives-owned`LoadingSpinner` instead of an API-token-local animate-spin SVG.+ The create-token section may expose stable in-page anchors for sibling+ API Access onboarding surfaces, but preset scope contents must continue to+ flow from the API manifest client and token manager model rather than from+ anchor callers such as Agent integrations.+ Empty scope selection is not a wildcard request in the token manager UI:+ generation must require an explicit scoped preset, custom scope, or+ deliberate Full access selection before the frontend sends a create-token+ payload.Token scope selector semantics stay API-contract owned, but the visiblepressed/unpressed selector pill shell routes through frontend-primitives`SelectablePillButton` instead of API-token-local rounded-full selectorclasses.-11. `frontend-modern/src/components/Settings/apiTokenManagerModel.ts` shared with `security-privacy`: the pure API token settings model is both a security/privacy control surface and a canonical API payload contract boundary.-12. `frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/NodeCredentialSlot.tsx` shared with `agent-lifecycle`: the inline node credential slot is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.-13. `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx` shared with `agent-lifecycle`: the pure infrastructure operations inventory/install model is both an agent fleet lifecycle control surface and an API token, lookup, assignment, and reporting/install contract boundary.+17. `frontend-modern/src/components/Settings/apiTokenManagerModel.ts` shared with `security-privacy`: the pure API token settings model is both a security/privacy control surface and a canonical API payload contract boundary.+18. `frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/NodeCredentialSlot.tsx` shared with `agent-lifecycle`: the inline node credential slot is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.+19. `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx` shared with `agent-lifecycle`: the pure infrastructure operations inventory/install model is both an agent fleet lifecycle control surface and an API token, lookup, assignment, and reporting/install contract boundary.Docker and Podman install-profile labels and descriptions in that sharedmodel must derive their customer-facing source name from`frontend-modern/src/utils/sourcePlatforms.ts` rather than page-local@@ -424,15 +966,15 @@ payload shape change when the portal presents compact client rows.Mock mode must expose authored availability targets through those samelist, saved-test, and connections-ledger payloads so demo endpoints exercisethe canonical API contract rather than a frontend-only fixture.-13. `frontend-modern/src/components/Settings/NodeModalAuthenticationSection.tsx` shared with `agent-lifecycle`: the node setup authentication section is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.-16. `frontend-modern/src/components/Settings/NodeModalBasicInfoSection.tsx` shared with `agent-lifecycle`: the node setup basic-info section is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.-17. `frontend-modern/src/components/Settings/nodeModalModel.ts` shared with `agent-lifecycle`: the pure node setup modal model is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.-18. `frontend-modern/src/components/Settings/NodeModalMonitoringSection.tsx` shared with `agent-lifecycle`: the node setup monitoring section is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.-19. `frontend-modern/src/components/Settings/NodeModalSetupGuideSection.tsx` shared with `agent-lifecycle`: the node setup guide section is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.-20. `frontend-modern/src/components/Settings/NodeModalStatusFooter.tsx` shared with `agent-lifecycle`: the node setup status/footer section is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.-21. `frontend-modern/src/components/Settings/useAPITokenManagerState.ts` shared with `security-privacy`: the API token settings state hook is both a security/privacy control surface and a canonical API payload contract boundary.-22. `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts` shared with `agent-lifecycle`: the direct-node infrastructure settings state hook is both an agent lifecycle control surface and a shared Proxmox node API contract boundary.-23. `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts` shared with `agent-lifecycle`: the infrastructure discovery runtime state hook is both an agent lifecycle control surface and a shared discovery/settings API contract boundary.+20. `frontend-modern/src/components/Settings/NodeModalAuthenticationSection.tsx` shared with `agent-lifecycle`: the node setup authentication section is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.+21. `frontend-modern/src/components/Settings/NodeModalBasicInfoSection.tsx` shared with `agent-lifecycle`: the node setup basic-info section is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.+22. `frontend-modern/src/components/Settings/nodeModalModel.ts` shared with `agent-lifecycle`: the pure node setup modal model is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.+23. `frontend-modern/src/components/Settings/NodeModalMonitoringSection.tsx` shared with `agent-lifecycle`: the node setup monitoring section is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.+24. `frontend-modern/src/components/Settings/NodeModalSetupGuideSection.tsx` shared with `agent-lifecycle`: the node setup guide section is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.+25. `frontend-modern/src/components/Settings/NodeModalStatusFooter.tsx` shared with `agent-lifecycle`: the node setup status/footer section is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.+26. `frontend-modern/src/components/Settings/useAPITokenManagerState.ts` shared with `security-privacy`: the API token settings state hook is both a security/privacy control surface and a canonical API payload contract boundary.+27. `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts` shared with `agent-lifecycle`: the direct-node infrastructure settings state hook is both an agent lifecycle control surface and a shared Proxmox node API contract boundary.+28. `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts` shared with `agent-lifecycle`: the infrastructure discovery runtime state hook is both an agent lifecycle control surface and a shared discovery/settings API contract boundary.That same shared boundary also owns settings-route polling scope for discovery payloads: the `/api/discover` refresh loop and websocket-backed discovery status hydration may run only while the operator is on the canonical Infrastructure settings workspace at `/settings/infrastructure`, not on retired infrastructure sub-routes.Discovery refreshes and scan results are route-scoped state updates. If thesettings route unmounts while a request is in flight, the hook must drop the@@ -446,19 +988,23 @@ payload shape change when the portal presents compact client rows.normalize their `updated` / `timestamp` values into one millisecond-backed`lastResultAt` state so discovery review rows do not depend on transport-specific timestamp shapes.-24. `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx` shared with `agent-lifecycle`: the infrastructure install state hook is both an agent fleet lifecycle control surface and an API token, lookup, and install transport contract boundary.+29. `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx` shared with `agent-lifecycle`: the infrastructure install state hook is both an agent fleet lifecycle control surface and an API token, lookup, and install transport contract boundary.Setup-completion handoff token creation is valid only while the activeinfrastructure add step is an installer route (`agent`, `linux-host`,`unraid`, `docker`, or `kubernetes`). Mounting the infrastructure workspacefor unrelated settings panels must not auto-create install tokens from astale setup handoff.-25. `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx` shared with `agent-lifecycle`: the shared infrastructure operations state hook is both an agent fleet lifecycle control surface and an API token, lookup, assignment, and reporting/install contract boundary.-26. `frontend-modern/src/components/Settings/useNodeModalState.ts` shared with `agent-lifecycle`: the node setup modal state hook is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.-27. `frontend-modern/src/constants/apiScopes.ts` shared with `security-privacy`: the API token scope catalog is both a security/privacy token-management trust surface and a canonical API token payload boundary.+30. `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx` shared with `agent-lifecycle`: the shared infrastructure operations state hook is both an agent fleet lifecycle control surface and an API token, lookup, assignment, and reporting/install contract boundary.+31. `frontend-modern/src/components/Settings/useNodeModalState.ts` shared with `agent-lifecycle`: the node setup modal state hook is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.+32. `frontend-modern/src/constants/apiScopes.ts` shared with `security-privacy`: the API token scope catalog is both a security/privacy token-management trust surface and a canonical API token payload boundary.Docker and Podman scope labels must use the shared source platform labelrather than generic `container` copy, because those labels surface directlyin token presets, custom scopes, and inventory badges.-28. `frontend-modern/src/utils/agentInstallCommand.ts` shared with `agent-lifecycle`: the shared frontend install-command helper is both an agent lifecycle control surface and a canonical API/install transport contract boundary.+ The `ai:execute` scope label is customer-facing API contract copy: it must+ describe Pulse Intelligence actions as governed Patrol actions for plans,+ approvals, policy-allowed fixes, verification, and history rather than as+ generic operations workflows or a separate agent product.+33. `frontend-modern/src/utils/agentInstallCommand.ts` shared with `agent-lifecycle`: the shared frontend install-command helper is both an agent lifecycle control surface and a canonical API/install transport contract boundary.Generated install commands are part of the API contract because they bindthe UI-selected Pulse URL, token source, custom CA, insecure/plain-HTTPbehavior, and `/download/pulse-agent?arch=...` availability proof into the@@ -469,11 +1015,36 @@ payload shape change when the portal presents compact client rows.PowerShell `-File` calls so Windows PowerShell argument binding cannotreinterpret copied `$true` values as strings or let preflight-only returnsabort the parent wrapper before install.-29. `frontend-modern/src/utils/apiTokenPresentation.ts` shared with `security-privacy`: the API token presentation helper is both a security/privacy control surface and a canonical API token management boundary.+34. `frontend-modern/src/utils/apiTokenPresentation.ts` shared with `security-privacy`: the API token presentation helper is both a security/privacy control surface and a canonical API token management boundary.It owns the operator-facing Docker / Podman token vocabulary used by APIAccess, token presets, usage summaries, and revoke warnings.-30. `frontend-modern/src/utils/infrastructureSettingsPresentation.ts` shared with `agent-lifecycle`: the infrastructure settings presentation helper is both an agent lifecycle control surface and an API-backed direct-node/discovery settings boundary.-31. `internal/api/access_control_handlers.go` shared with `organization-settings`: RBAC role and user-assignment handlers are both an organization settings control surface and a canonical API payload contract boundary.+35. `frontend-modern/src/utils/infrastructureSettingsPresentation.ts` shared with `agent-lifecycle`: the infrastructure settings presentation helper is both an agent lifecycle control surface and an API-backed direct-node/discovery settings boundary.+36. `internal/agentcapabilities/action_target.go` shared with `ai-runtime`: the Pulse Intelligence governed action target type and resource-to-action-target mapping vocabulary are both the Assistant approval/runtime routing contract and the canonical API/agent target contract for governed actions.+37. `internal/agentcapabilities/control_level.go` shared with `ai-runtime`: the Pulse Intelligence control-level vocabulary and control-tool availability predicate are both the Assistant runtime gating contract and the canonical API/agent permission posture for governed action tools.+38. `internal/agentcapabilities/errors.go` shared with `ai-runtime`: the Pulse Intelligence agent error envelope is both the canonical API failure payload contract and the AI runtime adapter error-parsing contract for Assistant and external-agent surfaces.+39. `internal/agentcapabilities/events.go` shared with `ai-runtime`: the Pulse Intelligence event vocabulary is both the canonical API SSE event contract and the AI runtime adapter notification contract for Assistant and external-agent surfaces.+40. `internal/agentcapabilities/governance_prompt.go` shared with `ai-runtime`: the Pulse Intelligence surface-affordance-resolved model-facing operating-instruction, tool-governance prompt, reusable provider-tool governance description, Assistant-native offered-tool filtering, and Assistant-native interactive question-tool governance projections are both the Assistant system-prompt governance section and the shared API/agent vocabulary for action mode, approval posture, MCP affordance advertisement, and non-registry interaction-tool boundaries.+41. `internal/agentcapabilities/http.go` shared with `ai-runtime`: the Pulse Intelligence agent HTTP substrate is both the API capabilities invocation contract and the shared AI runtime adapter execution primitive for MCP and reference agent clients.+42. `internal/agentcapabilities/manifest.go` shared with `ai-runtime`: the canonical Pulse Intelligence agent capabilities manifest declaration, including capability display titles, manifest-owned finding lifecycle schemas, manifest-owned governed action schemas and routes, manifest-owned external-adapter surface tool contracts, and manifest-owned structured output schemas, is both the API discovery payload source and the AI runtime projection contract for Pulse Assistant and MCP-facing agent tools.+43. `internal/agentcapabilities/markdown.go` shared with `ai-runtime`: the Pulse Intelligence manifest Markdown projection, including manifest-owned capability titles, surface-filtered Pulse MCP tool/error inventories, and prompt labels, is both the canonical API/agent documentation projection and the AI runtime onboarding projection for Assistant-compatible external-agent surfaces.+44. `internal/agentcapabilities/mcp.go` shared with `ai-runtime`: the Pulse Intelligence MCP protocol version, JSON-RPC, method dispatch, method payload, surface-tool-contract-gated initialize operating-instruction and capability advertisement payload, manifest surface-filtered tools/list and tools/call execution bridge, manifest surface-gated resources/list and resources/read bridge, manifest-owned and surface-affordance-gated workflow prompt projection, protocol wire aliases, resource and prompt handler gates, and notification projection collectively define the external-agent adapter wire contract over the shared Pulse Intelligence tool core; MCP initialize, tools/call execution, resource list/read projection, and prompt list/get projection must enter through manifest-owned surface and workflow-prompt contracts so raw capability slices cannot bypass the published external-adapter contract.+45. `internal/agentcapabilities/mcp_adapter.go` shared with `ai-runtime`: the Pulse MCP adapter setup contract defaults and normalization are both the canonical API manifest setup projection and the AI runtime onboarding contract for Assistant-compatible external-agent surfaces.+46. `internal/agentcapabilities/projection.go` shared with `ai-runtime`: the agent capability external-tool projection helper, normalized manifest-owned surface tool contract resolution and tools-affordance gating, manifest-owned resource-context route and argument vocabulary, operator-state capability and route vocabulary, finding workflow capability and lifecycle argument vocabulary including resolution and dismissal notes, governed action capability, route, and argument vocabulary, manifest-owned tool title and outputSchema projection, structured Pulse capability _meta, and shared tool behavior hints are both the canonical API manifest projection contract and the AI runtime adapter projection for Pulse Assistant and MCP-facing agent tools, with MCP annotation and metadata wire names confined to adapter-edge aliases.+47. `internal/agentcapabilities/provider_tool_artifacts.go` shared with `ai-runtime`: the provider tool-call artifact detector and streaming tool-name prefix splitter are both the Assistant stream-sanitization boundary and the shared external-adapter leak guard for provider-native tool-call markup that escaped the structured channel.+48. `internal/agentcapabilities/schema.go` shared with `ai-runtime`: the agent capability input schema contract is both the canonical API manifest schema envelope and the AI runtime structured tool-schema, governance-aware provider-projection with neutral behavior hints and Pulse governance metadata, offered-tool governance extraction for Assistant prompt policy, manifest-affordance-gated Assistant provider-surface composition, manifest raw-schema to Assistant provider-schema projection for capability tools, legacy native Assistant utility provider aliases and schemas, provider-call normalization, provider-result context projection, Assistant-native interaction provider-tool declaration, and live Assistant execution-normalization contract for Pulse Assistant and MCP-facing agent tools.+49. `internal/agentcapabilities/scopes.go` shared with `ai-runtime`: the manifest-derived required-scope summary is both the canonical API/agent token guidance contract and the AI runtime adapter startup/onboarding contract for Assistant-compatible external-agent surfaces.+50. `internal/agentcapabilities/sse.go` shared with `ai-runtime`: the Pulse Intelligence SSE subscription transport and record parser are both the canonical API event-stream consumption contract and the AI runtime adapter push bridge contract for MCP and reference agent clients.+51. `internal/agentcapabilities/surface_contract.go` shared with `ai-runtime`: the Pulse Intelligence operator-surface affordance contract, shared surface-affordance, surface-tool identity, Assistant surface tool filtering, normalized external surface tool resolver, surface lookup, affordance labels, and manifest-published external-adapter surface tool allowlist projection are both the canonical API manifest surface model and the AI runtime prompt and onboarding guardrail for Assistant and MCP-facing surfaces.+52. `internal/agentcapabilities/text_tool_invocation.go` shared with `ai-runtime`: the Pulse Intelligence text tool invocation parser, internal approval argument, and current_resource handle vocabulary are both the Assistant approved-action execution projection and the shared tool-call params bridge for governed Pulse Intelligence tool calls, with MCP tools/call compatibility staying at the adapter edge.+53. `internal/agentcapabilities/tool_call.go` shared with `ai-runtime`: the Pulse Intelligence shared tool-call params, normalization, validation, direct registry preparation, registry-entrypoint failure result helpers, and provider/registry tool-call safety classification are both the native Assistant execution/FSM contract and the canonical API/agent tools/call compatibility contract for governed Pulse Intelligence tool calls.+54. `internal/agentcapabilities/tool_execution.go` shared with `ai-runtime`: the Pulse Intelligence neutral capability tool HTTP execution helper and direct tool execution output/error mapper are both the Assistant-native direct execution contract and the canonical API/agent request/response execution contract, with MCP adapters consuming the neutral helpers only after the shared MCP manifest-surface execution bridge has applied the published surface tool contract.+55. `internal/agentcapabilities/tool_marker.go` shared with `ai-runtime`: the Pulse Intelligence Assistant tool marker vocabulary and approval/policy marker parser are both the Assistant structured tool-result compatibility contract and the canonical API/agent branching contract for governed tool outcomes.+56. `internal/agentcapabilities/tool_names.go` shared with `ai-runtime`: the Pulse Intelligence registry tool-name vocabulary is both the native Assistant execution/display contract and the canonical API/agent tool identity contract for MCP-facing external-agent adapters.+57. `internal/agentcapabilities/tool_response.go` shared with `ai-runtime`: the shared tool response envelope, tool error-code vocabulary, and tool-result error-code and verification evidence parsers are both the Assistant structured tool-result contract and the canonical API/agent branching contract for Pulse Intelligence tool failures, recovery tracking, and write self-verification.+58. `internal/agentcapabilities/tool_result.go` shared with `ai-runtime`: the Pulse Intelligence shared tool-result content/result envelope, structuredContent projection, result constructors, HTTP response-to-result mapping, text projection, and result interpretation helpers are both the Assistant registry result contract and the canonical API/agent result projection contract for governed tool outcomes.+59. `internal/agentcapabilities/types.go` shared with `ai-runtime`: the agent capabilities manifest wire type, manifest-owned external-adapter surface tool contract field, capability display title and structured output schema fields, approval-policy vocabulary, capability governance normalization, and tool-governance descriptor shape are both the canonical API payload contract and the AI runtime projection contract for Pulse Assistant and MCP-facing agent tools.+60. `internal/agentcapabilities/workflow_prompt.go` shared with `ai-runtime`: the Pulse Intelligence workflow prompt catalogue, manifest-owned `workflowPrompts` projection, MCP prompt title projection, presentation kind hints, shared resource-context and finding argument vocabulary, Patrol issue-handling capability gating, argument validation, and manifest-gated shared prompt rendering rules are both the AI runtime starter contract for Assistant-compatible surfaces and the canonical API/agent prompt projection contract for MCP-facing clients.+61. `internal/api/access_control_handlers.go` shared with `organization-settings`: RBAC role and user-assignment handlers are both an organization settings control surface and a canonical API payload contract boundary.The shared node setup boundary above owns the guided/manual setup splitfor PVE/PBS consumers: API Inventory and Host Telemetry Agent setup modesare auto-registration paths, while Token ID/Value fields, Test Connection,@@ -493,7 +1064,7 @@ payload shape change when the portal presents compact client rows.controls. That sequence is presentation guidance for the existing setuppayload phases; it does not create a second node setup API model or allowpage-local payload ownership.-32. `internal/api/agent_install_command_shared.go` shared with `agent-lifecycle`: agent install command assembly is both an agent lifecycle control surface and a canonical API payload contract boundary.+62. `internal/api/agent_install_command_shared.go` shared with `agent-lifecycle`: agent install command assembly is both an agent lifecycle control surface and a canonical API payload contract boundary.Frontend and backend Unix install command builders must stay on the sametoken-file and preflight transport contract: tokens are passed to theinstaller as ephemeral files, and host install snippets must verify the@@ -504,12 +1075,12 @@ payload shape change when the portal presents compact client rows.the operator wants Patrol actions or server-opted-in Docker-in-LXCinventory from the Proxmox node; generic Proxmox API Inventory setup mustremain least-privilege and command-execution-free.-32a. `internal/api/cloud_agent_install_command.go` shared with `agent-lifecycle`, `cloud-paid`: hosted tenant agent install commands are agent lifecycle enrollment transport, hosted/provider MSP tenant boundary, and canonical API payload contract.+ 32a. `internal/api/cloud_agent_install_command.go` shared with `agent-lifecycle`, `cloud-paid`: hosted tenant agent install commands are agent lifecycle enrollment transport, hosted/provider MSP tenant boundary, and canonical API payload contract.The route and reusable helper must both mint PVE/PBS install tokens only inhosted mode, only for an existing tenant/org, and only into that tenantruntime's token store with the org boundary, command shape, token metadata,and already-loaded tenant-monitor refresh behavior preserved.-33. `internal/api/ai_handler.go` shared with `ai-runtime`: Pulse Assistant handlers are both an AI runtime control surface and a canonical API payload contract boundary.+63. `internal/api/ai_handler.go` shared with `ai-runtime`: Pulse Assistant handlers are both an AI runtime control surface and a canonical API payload contract boundary.Assistant session list payloads may expose only the safe`handoff_summary` projection needed by the browser to mark and restore ascoped handoff. The payload must not expose provider-bound model context,@@ -544,34 +1115,34 @@ payload shape change when the portal presents compact client rows.browser-safe `ChatSession` projection. Rename must not expose or mutatestored prompts, messages, provider reasoning, model handoff context,approvals, action state, or tool evidence. Browser clients must call the- shared `AIChatAPI.renameSession(sessionId, title)` helper so path encoding- and JSON body shape stay canonical.- `POST /api/ai/sessions/{id}/undo` and- `POST /api/ai/sessions/{id}/redo` own the Assistant turn-repair API- contract. Undo removes the latest user-authored turn and all later- assistant/tool messages as one durable unit, returns a browser-safe- `restored_prompt`, `removed_messages`, and `can_redo`, and must not expose- provider reasoning, raw tool output, model-only handoff text, approval- payload internals, or remediation command data. Redo restores the latest- undone turn and returns `restored_messages` plus the remaining `can_redo`- state. `GET /api/ai/sessions` and other `ChatSession` projections may- expose only the boolean `can_redo` hint alongside safe title/timestamp,- count, and handoff-summary fields so the drawer can re-enable redo after a- reload without reading the redo stack itself. Browser clients must use the- shared `AIChatAPI.undoLastTurn(sessionId)` and- `AIChatAPI.redoLastTurn(sessionId)` helpers so path encoding and response- shape stay canonical.- OpenCode-style file diff/revert session routes are deliberately not part- of Pulse's supported Assistant session contract: Pulse sessions do not own- local code-file edits, and infrastructure mutations must be reviewed- through governed approval/action history. Browser clients must not expose- or call `GET /api/ai/sessions/{id}/diff`,- `POST /api/ai/sessions/{id}/revert`, or- `POST /api/ai/sessions/{id}/unrevert`; legacy direct calls to those routes- return `501 Not Implemented` with an explicit unsupported message rather- than a placeholder success payload.- Resource-context follow-up turns are different from Patrol-run rehydration:- browser-safe `handoff_metadata.kind=resource_context` must not replace a+ shared `AIChatAPI.renameSession(sessionId, title)` helper so path encoding+ and JSON body shape stay canonical.+ `POST /api/ai/sessions/{id}/undo` and+ `POST /api/ai/sessions/{id}/redo` own the Assistant turn-repair API+ contract. Undo removes the latest user-authored turn and all later+ assistant/tool messages as one durable unit, returns a browser-safe+ `restored_prompt`, `removed_messages`, and `can_redo`, and must not expose+ provider reasoning, raw tool output, model-only handoff text, approval+ payload internals, or remediation command data. Redo restores the latest+ undone turn and returns `restored_messages` plus the remaining `can_redo`+ state. `GET /api/ai/sessions` and other `ChatSession` projections may+ expose only the boolean `can_redo` hint alongside safe title/timestamp,+ count, and handoff-summary fields so the drawer can re-enable redo after a+ reload without reading the redo stack itself. Browser clients must use the+ shared `AIChatAPI.undoLastTurn(sessionId)` and+ `AIChatAPI.redoLastTurn(sessionId)` helpers so path encoding and response+ shape stay canonical.+ OpenCode-style file diff/revert session routes are deliberately not part+ of Pulse's supported Assistant session contract: Pulse sessions do not own+ local code-file edits, and infrastructure mutations must be reviewed+ through governed approval/action history. Browser clients must not expose+ or call `GET /api/ai/sessions/{id}/diff`,+ `POST /api/ai/sessions/{id}/revert`, or+ `POST /api/ai/sessions/{id}/unrevert`; legacy direct calls to those routes+ return `501 Not Implemented` with an explicit unsupported message rather+ than a placeholder success payload.+ Resource-context follow-up turns are different from Patrol-run rehydration:+ browser-safe `handoff_metadata.kind=resource_context` must not replace astored rich handoff envelope with a partial metadata-only envelope, and thehandler must not ask the browser to resend resource context that the chatruntime can rehydrate from the stored selected-resource envelope.@@ -593,8 +1164,12 @@ payload shape change when the portal presents compact client rows.restored `tool_calls[].input` from backend history as a structured objectas well as legacy/display strings, then normalize it before rendering.Chat stream events are generated from `internal/ai/chat` payload structs- into `frontend-modern/src/api/generated/aiChatEvents.ts`; that generated- union must not include the retired `explore_status` pre-pass event. Runtime+ into `frontend-modern/src/api/generated/aiChatEvents.ts`; agent capability+ manifest types are generated from `internal/agentcapabilities` payload+ structs into `frontend-modern/src/api/generated/agentCapabilities.ts`.+ Those generated projections must stay derived through+ `scripts/generate-types.go`, and the chat event union must not include the+ retired `explore_status` pre-pass event. Runtimeworkflow telemetry may remain a transport event, but browser Assistantstreams must use `chat.StreamEvent.ClientSafe()` so raw provider`thinking` payloads and serialized tool-call prose cannot cross the API@@ -621,25 +1196,25 @@ payload shape change when the portal presents compact client rows.consumption rule only: it must not change event payload shape, event order,timeout handling, reader cleanup, parse-error handling, or ordinarycontent-token throughput.- Cold Assistant streams must include a typed `session` event backed by- `internal/ai/chat.SessionData` as soon as the HTTP SSE writer is ready and- an immediate neutral `workflow_state` preparation event before backend- handoff recovery, model resolution, selected-route retry planning, context- prefetch, inventory reads, or user-visible provider output so the frontend- can bind the backend-created session and show live progress without a- separate create-session request. That cold-stream model resolution must use- explicit configured chat routes or stable provider defaults without waiting- on provider model catalogs; `/api/ai/models` and settings responses own- catalog-backed recommendation, not the first-response chat stream.- The same SSE transport must emit neutral `workflow_state` events with- phase `stream_idle` during governed silent intervals while request-bound- Assistant execution is still in flight. Hidden SSE comment heartbeats are- not sufficient user-visible progress. The handler must serialize comment- heartbeats and JSON event writes through one writer lock, and the+ Cold Assistant streams must include a typed `session` event backed by+ `internal/ai/chat.SessionData` as soon as the HTTP SSE writer is ready and+ an immediate neutral `workflow_state` preparation event before backend+ handoff recovery, model resolution, selected-route retry planning, context+ prefetch, inventory reads, or user-visible provider output so the frontend+ can bind the backend-created session and show live progress without a+ separate create-session request. That cold-stream model resolution must use+ explicit configured chat routes or stable provider defaults without waiting+ on provider model catalogs; `/api/ai/models` and settings responses own+ catalog-backed recommendation, not the first-response chat stream.+ The same SSE transport must emit neutral `workflow_state` events with+ phase `stream_idle` during governed silent intervals while request-bound+ Assistant execution is still in flight. Hidden SSE comment heartbeats are+ not sufficient user-visible progress. The handler must serialize comment+ heartbeats and JSON event writes through one writer lock, and the`stream_idle` event must stop before terminal `done`/`error` rather thanbecoming assistant-authored transcript content.- The generated frontend union, stream parser- tests, and backend JSON snapshot proof must stay in lockstep with that payload;+ The generated frontend union, stream parser+ tests, and backend JSON snapshot proof must stay in lockstep with that payload;`done.session_id` and `question.session_id` remain compatibility payloads,not the primary cold-session creation contract. Assistant `done` eventsmust also carry the effective `model` route that completed the stream so@@ -660,48 +1235,48 @@ payload shape change when the portal presents compact client rows.fast UX iteration against the real stream reducer. That fixture mayshort-circuit `frontend-modern/src/api/aiChat.ts` only in Vite dev or testmode, only for reserved `/fixture ...` prompts, and only by calling the- normal `AIChatAPI.chat` event callback with the generated- `AIChatStreamEvent` union (`session`, `workflow_state`, `thinking`,- `tool_start`, `tool_progress`, `tool_cancel`, `tool_end`, `content`,- `done`). It must not open a backend session, mutate persisted chat history,- add browser-only stream event shapes, or become a production fallback for- provider or VPN failures. At least one fixture-backed Assistant tool- sequence must exercise the OpenCode-parity raw tool-input path by starting- with incomplete provider-style `raw_input`, then mutating the same tool row- with completed arguments through the normal `tool_progress` event.- At least one fixture-backed Assistant tool sequence must exercise the- skipped-tool lifecycle by resolving a visible `tool_start` row through- `tool_cancel` instead of hiding the activity. At least one fixture-backed- Assistant tool sequence must exercise live pending/running tool evidence by- emitting placeholder structured input plus raw provider-style input on- `tool_start`, mutating that same row through `tool_progress`, and pacing the- running state long enough for browser proof to inspect and copy both the- completed input and current progress before `tool_end`. At least one- fixture-backed Assistant tool sequence must exercise successful long- plain-text tool output by emitting enough output lines to prove the browser- drawer renders a bounded collapsed preview, avoids an opaque output badge,- and preserves the full output in expandable details. At least one- fixture-backed Assistant tool sequence must exercise compacted provider artifact- suppression by emitting compacted pre-tool content before a governed tool row- and final normal answer content. At least one fixture-backed Assistant tool- sequence must exercise a buffered `tool_start` -> `tool_end` burst with no- provider delay between the two events, followed by a paced content/terminal- step, so browser proof can verify that fast command activity remains- perceptible without a real provider request. At least one fixture-backed- Assistant tool sequence must exercise consecutive multi-tool activity with a- paced completed first row followed by a live second row, so browser proof can- verify replacement/compaction motion without provider timing. At least one- fixture-backed Assistant sequence must exercise `provider_retry` with `attempt`,- `max_attempts`, and `retry_after_ms` metadata plus a paced retry window, so- browser proof can verify visible retry countdown behavior without a real- provider request, VPN dependency, or API spend. At least one fixture-backed- Assistant sequence must exercise `stream_idle` after selected-provider- startup, so browser proof can verify visible idle liveness without forcing a- real provider to pause on demand. At least one fixture-backed Assistant- sequence must exercise the local prompt-send state by emitting `session`,- then pacing the first backend `workflow_state` long enough for browser proof- to verify immediate visible activity without opening a provider request.-34. `internal/api/ai_handlers.go` shared with `ai-runtime`: AI settings and remediation handlers are both an AI runtime control surface and a canonical API payload contract boundary.+ normal `AIChatAPI.chat` event callback with the generated+ `AIChatStreamEvent` union (`session`, `workflow_state`, `thinking`,+ `tool_start`, `tool_progress`, `tool_cancel`, `tool_end`, `content`,+ `done`). It must not open a backend session, mutate persisted chat history,+ add browser-only stream event shapes, or become a production fallback for+ provider or VPN failures. At least one fixture-backed Assistant tool+ sequence must exercise the OpenCode-parity raw tool-input path by starting+ with incomplete provider-style `raw_input`, then mutating the same tool row+ with completed arguments through the normal `tool_progress` event.+ At least one fixture-backed Assistant tool sequence must exercise the+ skipped-tool lifecycle by resolving a visible `tool_start` row through+ `tool_cancel` instead of hiding the activity. At least one fixture-backed+ Assistant tool sequence must exercise live pending/running tool evidence by+ emitting placeholder structured input plus raw provider-style input on+ `tool_start`, mutating that same row through `tool_progress`, and pacing the+ running state long enough for browser proof to inspect and copy both the+ completed input and current progress before `tool_end`. At least one+ fixture-backed Assistant tool sequence must exercise successful long+ plain-text tool output by emitting enough output lines to prove the browser+ drawer renders a bounded collapsed preview, avoids an opaque output badge,+ and preserves the full output in expandable details. At least one+ fixture-backed Assistant tool sequence must exercise compacted provider artifact+ suppression by emitting compacted pre-tool content before a governed tool row+ and final normal answer content. At least one fixture-backed Assistant tool+ sequence must exercise a buffered `tool_start` -> `tool_end` burst with no+ provider delay between the two events, followed by a paced content/terminal+ step, so browser proof can verify that fast command activity remains+ perceptible without a real provider request. At least one fixture-backed+ Assistant tool sequence must exercise consecutive multi-tool activity with a+ paced completed first row followed by a live second row, so browser proof can+ verify replacement/compaction motion without provider timing. At least one+ fixture-backed Assistant sequence must exercise `provider_retry` with `attempt`,+ `max_attempts`, and `retry_after_ms` metadata plus a paced retry window, so+ browser proof can verify visible retry countdown behavior without a real+ provider request, VPN dependency, or API spend. At least one fixture-backed+ Assistant sequence must exercise `stream_idle` after selected-provider+ startup, so browser proof can verify visible idle liveness without forcing a+ real provider to pause on demand. At least one fixture-backed Assistant+ sequence must exercise the local prompt-send state by emitting `session`,+ then pacing the first backend `workflow_state` long enough for browser proof+ to verify immediate visible activity without opening a provider request.+64. `internal/api/ai_handlers.go` shared with `ai-runtime`: AI settings and remediation handlers are both an AI runtime control surface and a canonical API payload contract boundary.The AI settings payload on `/api/settings/ai` carries no cloud-context-privacyfield: cloud context behavior is a fixed posture (real context to cloud, withcredentials and local-only resources always withheld), not a settings-payload@@ -734,8 +1309,8 @@ payload shape change when the portal presents compact client rows.evidence. The frontend API client, settings shell, and Assistant drawermust treat this payload as the canonical provider health contract ratherthan parsing free-form provider error strings.-35. `internal/api/ai_intelligence_handlers.go` shared with `ai-runtime`: AI intelligence handlers are both an AI runtime control surface and a canonical API payload contract boundary.-36. `internal/api/config_setup_handlers.go` shared with `agent-lifecycle`: auto-register and setup handlers are both an agent lifecycle control surface and a canonical API payload contract boundary.+65. `internal/api/ai_intelligence_handlers.go` shared with `ai-runtime`: AI intelligence handlers are both an AI runtime control surface and a canonical API payload contract boundary.+66. `internal/api/config_setup_handlers.go` shared with `agent-lifecycle`: auto-register and setup handlers are both an agent lifecycle control surface and a canonical API payload contract boundary.That same shared boundary also owns reachable-host selection truth for canonical Proxmox registration: runtime callers may propose ordered `candidateHosts`, but the API contract must persist and echo the first candidate Pulse can actually reach instead of freezing the caller's rejected first preference into the stored node endpoint.That same canonical payload contract also owns strict-TLS truth for that selected host: `/api/auto-register` may only persist `VerifySSL=true` when Pulse actually captured a certificate fingerprint for the selected candidate, and it must not pretend public-CA verification is safe after every candidate fingerprint probe failed.For PVE cluster sources, that same contract must distinguish primary@@ -764,9 +1339,9 @@ payload shape change when the portal presents compact client rows.id. PBS scripts must grant `Audit` to both `pulse-monitor@pbs` and theconcrete token id. Browser/runtime setup callers must not fork this intotoken-shared, token-unprivileged, or user-only ACL variants.-37. `internal/api/enterprise_extension_rbac_admin.go` shared with `organization-settings`: RBAC admin extension endpoints are both an organization settings control surface and a canonical API payload contract boundary.-38. `internal/api/licensing_bridge.go` shared with `cloud-paid`: commercial licensing bridge handlers carry both API payload contract and cloud-paid entitlement boundary ownership.-39. `internal/api/licensing_handlers.go` shared with `cloud-paid`: commercial licensing handlers carry both API payload contract and cloud-paid entitlement boundary ownership.+67. `internal/api/enterprise_extension_rbac_admin.go` shared with `organization-settings`: RBAC admin extension endpoints are both an organization settings control surface and a canonical API payload contract boundary.+68. `internal/api/licensing_bridge.go` shared with `cloud-paid`: commercial licensing bridge handlers carry both API payload contract and cloud-paid entitlement boundary ownership.+69. `internal/api/licensing_handlers.go` shared with `cloud-paid`: commercial licensing handlers carry both API payload contract and cloud-paid entitlement boundary ownership.That same shared licensing boundary also owns authenticatedinstall-version and runtime-build attribution: `internal/api/router.go`must hand the canonical process `serverVersion` and normalized runtime@@ -786,20 +1361,20 @@ payload shape change when the portal presents compact client rows.destination, but the browser/API contract must not reintroducePulse-Pro-as-page-name copy in callback titles, actions, or retryguidance.-40. `internal/api/licensing_legacy_retry.go` shared with `cloud-paid`: the background legacy-exchange retry loop carries both API payload contract and cloud-paid entitlement boundary ownership.-41. `internal/api/notifications.go` shared with `notifications`: notification handlers are both a notification delivery control surface and a canonical API payload contract boundary.-42. `internal/api/org_handlers.go` shared with `organization-settings`: organization management handlers are both an organization settings control surface and a canonical API payload contract boundary.-43. `internal/api/org_lifecycle_handlers.go` shared with `organization-settings`: organization lifecycle handlers are both an organization settings control surface and a canonical API payload contract boundary.-44. `internal/api/payments_webhook_handlers.go` shared with `cloud-paid`: commercial payment webhook handlers carry both API payload contract and cloud-paid billing boundary ownership.-45. `internal/api/public_signup_handlers.go` shared with `cloud-paid`: hosted signup handlers carry both API payload contract and cloud-paid hosted provisioning boundary ownership.+70. `internal/api/licensing_legacy_retry.go` shared with `cloud-paid`: the background legacy-exchange retry loop carries both API payload contract and cloud-paid entitlement boundary ownership.+71. `internal/api/notifications.go` shared with `notifications`: notification handlers are both a notification delivery control surface and a canonical API payload contract boundary.+72. `internal/api/org_handlers.go` shared with `organization-settings`: organization management handlers are both an organization settings control surface and a canonical API payload contract boundary.+73. `internal/api/org_lifecycle_handlers.go` shared with `organization-settings`: organization lifecycle handlers are both an organization settings control surface and a canonical API payload contract boundary.+74. `internal/api/payments_webhook_handlers.go` shared with `cloud-paid`: commercial payment webhook handlers carry both API payload contract and cloud-paid billing boundary ownership.+75. `internal/api/public_signup_handlers.go` shared with `cloud-paid`: hosted signup handlers carry both API payload contract and cloud-paid hosted provisioning boundary ownership.That same shared boundary also owns public hosted-signup response privacy:syntactically valid `/api/public/signup` requests must return one generic`202 Accepted` Pulse Account message whether provisioning/email side effectsran or were suppressed by the owner-email limiter, while invalid bodies andtrue server failures remain explicit.-46. `internal/api/relay_mobile_capability.go` shared with `relay-runtime`: the backend-owned Pulse Mobile relay capability inventory is both a relay runtime boundary and a canonical API payload contract surface.-47. `internal/api/resources.go` shared with `unified-resources`: the unified resource endpoint is both a backend payload contract surface and a unified-resource runtime boundary.-48. `internal/api/security.go` shared with `security-privacy`: the security handlers are both a security/privacy control surface and a canonical API payload contract boundary.+76. `internal/api/relay_mobile_capability.go` shared with `relay-runtime`: the backend-owned Pulse Mobile relay capability inventory is both a relay runtime boundary and a canonical API payload contract surface.+77. `internal/api/resources.go` shared with `unified-resources`: the unified resource endpoint is both a backend payload contract surface and a unified-resource runtime boundary.+78. `internal/api/security.go` shared with `security-privacy`: the security handlers are both a security/privacy control surface and a canonical API payload contract boundary.That same shared security/API boundary owns CSRF replacement-tokenconcurrency. When parallel browser mutations arrive with stale or missingCSRF tokens for the same session, `internal/api/csrf_store.go` may retain@@ -807,7 +1382,7 @@ payload shape change when the portal presents compact client rows.replacement can validate its retry. Logout, password-change, and explicitsession revocation must still delete the full session token set rather thanleaving any retained replacement token valid.-49. `internal/api/security_tokens.go` shared with `security-privacy`: the security token handlers are both a security/privacy control surface and a canonical API payload contract boundary.+79. `internal/api/security_tokens.go` shared with `security-privacy`: the security token handlers are both a security/privacy control surface and a canonical API payload contract boundary.Token owner identity is reserved for the server-authenticated principal:shared token-minting helpers must derive `owner_user_id` from the currentsession or caller token and reject extension metadata that tries to@@ -823,15 +1398,20 @@ payload shape change when the portal presents compact client rows.before minting a `relay:mobile:access` credential. Community installs mayreceive the standard license-required response, but direct API calls mustnot bypass Relay entitlement by creating mobile runtime tokens.-50. `internal/api/setup_script_render.go` shared with `agent-lifecycle`, `storage-recovery`: the generated Proxmox setup-script is a shared boundary across agent lifecycle (forced-command keys, install/uninstall edits), API contracts (rendered token shape and encoded rerun URL), and storage/recovery (backup visibility grants, Pulse-managed temperature SSH keys, and SMART disk-temperature collection).-51. `internal/api/slo.go` shared with `performance-and-scalability`: the SLO endpoint is both an API contract surface and a protected performance hot-path boundary.-52. `internal/api/system_settings.go` shared with `security-privacy`: the system settings telemetry and auth controls are both a security/privacy control surface and a canonical API payload contract boundary.-53. `internal/api/unified_agent.go` shared with `agent-lifecycle`: unified agent download and installer handlers are both an agent lifecycle control surface and a canonical API payload contract boundary.+80. `internal/api/setup_script_render.go` shared with `agent-lifecycle`, `storage-recovery`: the generated Proxmox setup-script is a shared boundary across agent lifecycle (forced-command keys, install/uninstall edits), API contracts (rendered token shape and encoded rerun URL), and storage/recovery (backup visibility grants, Pulse-managed temperature SSH keys, and SMART disk-temperature collection).+81. `internal/api/slo.go` shared with `performance-and-scalability`: the SLO endpoint is both an API contract surface and a protected performance hot-path boundary.+82. `internal/api/system_settings.go` shared with `security-privacy`: the system settings telemetry and auth controls are both a security/privacy control surface and a canonical API payload contract boundary.+83. `internal/api/unified_agent.go` shared with `agent-lifecycle`: unified agent download and installer handlers are both an agent lifecycle control surface and a canonical API payload contract boundary.Development-mode missing-binary responses must report the build commandfor the requested normalized OS/architecture, not a hard-coded Linuxtarget, so installer preflight failures point operators at the artifactthey actually need.-54. `internal/api/updates.go` shared with `deployment-installability`: update handlers are both a deployment-installability control surface and a canonical API payload contract boundary.+84. `internal/api/updates.go` shared with `deployment-installability`: update handlers are both a deployment-installability control surface and a canonical API payload contract boundary.+85. `pkg/aicontracts/fix_execution.go` shared with `ai-runtime`: the public approved-fix execution contract is both an AI runtime approved-action boundary and a canonical API dependency contract for Patrol and enterprise auto-fix binders.+86. `pkg/aicontracts/investigation.go` shared with `ai-runtime`: the public Patrol investigation record and finding contract is both an AI runtime handoff boundary and a canonical API payload contract for Patrol, Assistant, unified findings, persistence, and audit surfaces.+87. `pkg/aicontracts/orchestrator_deps.go` shared with `ai-runtime`: the public investigation orchestrator dependency contract is both an AI runtime handoff boundary and a canonical API payload contract for Assistant and Patrol tool-call history.+88. `pkg/extensions/ai_autofix.go` shared with `ai-runtime`: the enterprise auto-fix extension dependency seam is both an AI runtime approved-action boundary and a canonical API extension contract over Assistant and Patrol execution dependencies.+89. `scripts/generate-pulse-intelligence-docs.go` shared with `ai-runtime`: the Pulse Intelligence manifest docs generator is both an AI runtime docs/onboarding projection and a canonical API contract projection over the agent capabilities manifest and Pulse MCP surface tool contract.Update-plan responses own the structured readiness verdict for serverupdater capability, rollback support, agent continuity, v5 agent migrationtransport security, and agent reporting token scope. That verdict is part@@ -843,20 +1423,20 @@ payload shape change when the portal presents compact client rows.the requested target version through the shared update-target validationpath, recompute readiness from live backend state, and reject `blocked`verdicts before update execution starts.-The platform-connections API contract also owns inactive monitored-system-candidate semantics end to end. `enabled=false` on TrueNAS or VMware preview,-test, add, and update payloads must serialize through the shared ledger client-as `active:false`, and preview responses may legitimately return `no_change`,-`removes_existing`, or `removes_multiple` with empty projected-system lists-when the disabled candidate no longer contributes to a monitored-system group.-That same monitored-system grouping contract now also owns restart-safe host-report continuity at the API boundary. The removed monitored-system limit-enforcement path must not return; the API should treat a returning standalone-host report as existing grouping context when monitoring can match it to recent-persisted host continuity, so a server restart or v6 upgrade does not change-the explanatory grouping model before the live-inventory rebuild catches up. Genuinely new host identities must still return-the canonical monitored-system blocked payload.+ The platform-connections API contract also owns inactive monitored-system+ candidate semantics end to end. `enabled=false` on TrueNAS or VMware preview,+ test, add, and update payloads must serialize through the shared ledger client+ as `active:false`, and preview responses may legitimately return `no_change`,+ `removes_existing`, or `removes_multiple` with empty projected-system lists+ when the disabled candidate no longer contributes to a monitored-system group.+ That same monitored-system grouping contract now also owns restart-safe host+ report continuity at the API boundary. The removed monitored-system limit+ enforcement path must not return; the API should treat a returning standalone+ host report as existing grouping context when monitoring can match it to recent+ persisted host continuity, so a server restart or v6 upgrade does not change+ the explanatory grouping model before the live+ inventory rebuild catches up. Genuinely new host identities must still return+ the canonical monitored-system blocked payload.## Extension Points@@ -887,26 +1467,26 @@ the canonical monitored-system blocked payload.1. Add or change payload fields through handler + contract tests together2. Update frontend API types in lockstep with backend contract changes.Websocket-backed API consumers such as `frontend-modern/src/components/Settings/useAPITokenManagerState.ts` and `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx` may read runtime context only through `frontend-modern/src/contexts/appRuntime.ts`; they must not import `frontend-modern/src/App.tsx`, because payload ownership remains in the API contract rather than the root shell.-2a. Route settings infrastructure connected-system ledgers through- `/api/connections` and `frontend-modern/src/components/Settings/useConnectionsLedger.ts`- together. The frontend ledger may retain the last fulfilled connection- snapshot while polling or manual reload is in flight, but that retention is- only a fetch lifecycle rule; it must not synthesize rows, downgrade backend- fleet state, or replace the shared connection projection with page-local- placeholders.-2b. Route agentless availability target kind changes through- `internal/api/availability_handlers.go`,- `internal/api/platform_mock_connections.go`,- `frontend-modern/src/api/availabilityTargets.ts`, and the unified-resource- availability payload together. The bounded `targetKind` vocabulary is- `machine`, `service`, and `device`; missing legacy values default to- `service`. Browser add-dialog routes may carry a `targetKind` query value- to preselect that bounded kind, but the persisted contract remains the- `AvailabilityTarget.targetKind` payload. Browser consumers must not place- availability targets into Standalone Machines from that classification;- Machines membership requires Pulse Agent resource evidence. API clients- must not infer that classification from protocol, hostname, port, or row- label.+ 2a. Route settings infrastructure connected-system ledgers through+ `/api/connections` and `frontend-modern/src/components/Settings/useConnectionsLedger.ts`+ together. The frontend ledger may retain the last fulfilled connection+ snapshot while polling or manual reload is in flight, but that retention is+ only a fetch lifecycle rule; it must not synthesize rows, downgrade backend+ fleet state, or replace the shared connection projection with page-local+ placeholders.+ 2b. Route agentless availability target kind changes through+ `internal/api/availability_handlers.go`,+ `internal/api/platform_mock_connections.go`,+ `frontend-modern/src/api/availabilityTargets.ts`, and the unified-resource+ availability payload together. The bounded `targetKind` vocabulary is+ `machine`, `service`, and `device`; missing legacy values default to+ `service`. Browser add-dialog routes may carry a `targetKind` query value+ to preselect that bounded kind, but the persisted contract remains the+ `AvailabilityTarget.targetKind` payload. Browser consumers must not place+ availability targets into Standalone Machines from that classification;+ Machines membership requires Pulse Agent resource evidence. API clients+ must not infer that classification from protocol, hostname, port, or row+ label.3. Add dedicated contract tests for new stable payloadsUnified resource type-filter and organization-share resource type additionsmust route through `internal/api/resources.go`, `internal/api/org_handlers.go`,@@ -915,86 +1495,90 @@ the canonical monitored-system blocked payload.by `/api/resources` filters and cross-organization share normalization onlyafter the unified-resource contract defines the canonical resource type andpayload facet.-3a. Route diagnostics payload fields and user-facing diagnostics copy through- `internal/api/diagnostics.go`,- `internal/api/diagnostics_additional_test.go`, and- `internal/api/diagnostics_memory_test.go` together. Docker and Podman- health notes emitted by diagnostics must lead with Docker / Podman module- language and route operator recovery to the Infrastructure and- Security settings surfaces rather than generic runtime family wording or- retired agent-management destinations.-3b. Route Docker / Podman management API response copy through- `internal/api/docker_agents.go`, `internal/api/docker_metadata.go`,- `frontend-modern/src/api/monitoring.ts`, and their route/client tests- together. Operator-facing responses for Docker / Podman host removal,- hide/unhide, pending uninstall, display-name, and host metadata paths must- use Docker / Podman module or host wording instead of generic container- runtime labels.-3c. Route Assistant finding handoff context changes through- `internal/api/ai_handler.go`, `internal/api/ai_handler_test.go`, and- `internal/api/contract_test.go` together. Patrol-originated handoffs must- keep `[Finding Briefing]`, `[Finding Context]`, `[Finding Lifecycle+ 3a. Route diagnostics payload fields and user-facing diagnostics copy through+ `internal/api/diagnostics.go`,+ `internal/api/diagnostics_contract_test.go`,+ `internal/api/diagnostics_additional_test.go`, and+ `internal/api/diagnostics_memory_test.go` together. Docker and Podman+ health notes emitted by diagnostics must lead with Docker / Podman module+ language and route operator recovery to the Infrastructure and+ Security settings surfaces rather than generic runtime family wording or+ retired agent-management destinations. Pulse Assistant diagnostics must+ expose native runtime availability as `assistantRuntimeConnected`; the+ diagnostics payload must not revive legacy MCP transport fields such as+ `mcpConnected` or `mcpToolCount` for the first-party Assistant surface.+ 3b. Route Docker / Podman management API response copy through+ `internal/api/docker_agents.go`, `internal/api/docker_metadata.go`,+ `frontend-modern/src/api/monitoring.ts`, and their route/client tests+ together. Operator-facing responses for Docker / Podman host removal,+ hide/unhide, pending uninstall, display-name, and host metadata paths must+ use Docker / Podman module or host wording instead of generic container+ runtime labels.+ 3c. Route Assistant finding handoff context changes through+ `internal/api/ai_handler.go`, `internal/api/ai_handler_test.go`, and+ `internal/api/contract_test.go` together. Patrol-originated handoffs must+ keep `[Finding Briefing]`, `[Finding Context]`, `[Finding LifecycleContext]`, structured handoff resources, related root-cause/correlation- finding context, and structured handoff actions model-only, with the- briefing summarizing latest lifecycle event and factual governed action- artifact metadata without raw command text or Pulse-authored next-step- guidance. Structured handoff action- references may use the current live Patrol investigation-fix approval for- the finding when that approval is newer than the approval ID on the durable- record, but the payload may carry only IDs, status/risk/target metadata,- request/expiry timestamps, action plan identity and expiry, safe generated- approval summaries, command counts, and fix/action references, never the- approval command payload. Patrol- remediation-plan handoffs must use the same boundary for model-only- context: plan status, risk, step labels, and command counts are allowed,- while raw command and rollback command payloads remain in governed action- surfaces. Frontend Patrol finding-discussion handoffs must force a- request-local approval-required Assistant mode instead of inheriting the- user's persistent autonomous control setting; live approval, action artifact,- fix-outcome, and remediation-plan references only add structured action- metadata, they are not the trigger for the boundary. Frontend-visible Patrol- briefing payloads must stay compact and must not include suggested prompt- chips, Patrol-authored next-step recommendations, or route-owned- recommendation metadata. Frontend queued-fix recovery handoffs- where the live approval or action artifact payload is unavailable must still- carry that Patrol-owned finding briefing, current `fix_queued` posture,- request-local approval-required mode, and model-only evidence context; they must- not degrade into generic Assistant investigation chat or imply that- execution can proceed from missing command payloads. Expired-approval- recovery handoffs may use a still-available structured action artifact payload- only as safe metadata: description, target, risk, rationale, destructive- posture, and command count may enter the briefing, while raw command text- remains owned by governed remediation or approval surfaces. If the unified- finding list lacks a full investigation record, frontend finding-discussion- handoffs may hydrate the latest investigation session for the same safe- action artifact metadata, but they must not paste raw action command text- into the authored prompt or visible briefing. Direct- alert-investigation API handoffs through `internal/api/ai_handlers.go` must- enforce that same request-scoped boundary by setting- `ai.ExecuteRequest.AutonomousMode` to- false and `ai.ExecuteRequest.RequireCommandApproval` to true; API proof must- keep this guarded in both `internal/api/ai_handlers_test.go` and- `internal/api/contract_test.go`. Governed action artifact lines in the- briefing must derive from those- same structured action references after recovery so the briefing cannot- contradict the handoff action payload. Related finding- context must resolve from the current unified finding store, stay bounded- and deduplicated, include current recency and latest lifecycle facts, and- seed only structured handoff resources for canonical policy, state,- topology, and timeline hydration. Chat execution owns- resource-policy sanitization of the assembled model-only handoff before- prompt injection, so API payload builders may pass structured product- context without turning raw resource identity into user-authored text or- disclosure authority.-3d. Route command-agent WebSocket registration token semantics through- `internal/api/agent_exec_token_binding.go`, `internal/api/router.go`, and- `internal/api/contract_test.go` together. `agent:exec` tokens must already- be bound to the registering agent ID or hostname before `/api/agent/ws`- accepts command registration. The only first-use exception is a- Pulse-minted PVE/PBS install-command token carrying the governed install- metadata; that token may bind once to the first command agent ID and- hostname that registers, and a later different agent or hostname must be- rejected. Generic unbound `agent:exec` tokens remain fail-closed.+ finding context, and structured handoff actions model-only, with the+ briefing summarizing latest lifecycle event and factual governed action+ artifact metadata without raw command text or Pulse-authored next-step+ guidance. Structured handoff action+ references may use the current live Patrol investigation-fix approval for+ the finding when that approval is newer than the approval ID on the durable+ record, but the payload may carry only IDs, status/risk/target metadata,+ request/expiry timestamps, action plan identity and expiry, safe generated+ approval summaries, command counts, and fix/action references, never the+ approval command payload. Patrol+ remediation-plan handoffs must use the same boundary for model-only+ context: plan status, risk, step labels, and command counts are allowed,+ while raw command and rollback command payloads remain in governed action+ surfaces. Frontend Patrol finding-discussion handoffs must force a+ request-local approval-required Assistant mode instead of inheriting the+ user's persistent autonomous control setting; live approval, action artifact,+ fix-outcome, and remediation-plan references only add structured action+ metadata, they are not the trigger for the boundary. Frontend-visible Patrol+ briefing payloads must stay compact and must not include suggested prompt+ chips, Patrol-authored next-step recommendations, or route-owned+ recommendation metadata. Frontend queued-fix recovery handoffs+ where the live approval or action artifact payload is unavailable must still+ carry that Patrol-owned finding briefing, current `fix_queued` posture,+ request-local approval-required mode, and model-only evidence context; they must+ not degrade into generic Assistant investigation chat or imply that+ execution can proceed from missing command payloads. Expired-approval+ recovery handoffs may use a still-available structured action artifact payload+ only as safe metadata: description, target, risk, rationale, destructive+ posture, and command count may enter the briefing, while raw command text+ remains owned by governed remediation or approval surfaces. If the unified+ finding list lacks a full investigation record, frontend finding-discussion+ handoffs may hydrate the latest investigation session for the same safe+ action artifact metadata, but they must not paste raw action command text+ into the authored prompt or visible briefing. Direct+ alert-investigation API handoffs through `internal/api/ai_handlers.go` must+ enforce that same request-scoped boundary by setting+ `ai.ExecuteRequest.AutonomousMode` to+ false and `ai.ExecuteRequest.RequireCommandApproval` to true; API proof must+ keep this guarded in both `internal/api/ai_handlers_test.go` and+ `internal/api/contract_test.go`. Governed action artifact lines in the+ briefing must derive from those+ same structured action references after recovery so the briefing cannot+ contradict the handoff action payload. Related finding+ context must resolve from the current unified finding store, stay bounded+ and deduplicated, include current recency and latest lifecycle facts, and+ seed only structured handoff resources for canonical policy, state,+ topology, and timeline hydration. Chat execution owns+ resource-policy sanitization of the assembled model-only handoff before+ prompt injection, so API payload builders may pass structured product+ context without turning raw resource identity into user-authored text or+ disclosure authority.+ 3d. Route command-agent WebSocket registration token semantics through+ `internal/api/agent_exec_token_binding.go`, `internal/api/router.go`, and+ `internal/api/contract_test.go` together. `agent:exec` tokens must already+ be bound to the registering agent ID or hostname before `/api/agent/ws`+ accepts command registration. The only first-use exception is a+ Pulse-minted PVE/PBS install-command token carrying the governed install+ metadata; that token may bind once to the first command agent ID and+ hostname that registers, and a later different agent or hostname must be+ rejected. Generic unbound `agent:exec` tokens remain fail-closed.4. Route unified resource sensitivity, routing, and `aiSafeSummary` payload changes through `internal/api/resources.go`, `internal/api/contract_test.go`, and the canonical frontend resource consumer proofs together; resource governance metadata must not ship as an API-only or frontend-only heuristicThat same resource payload contract owns `aggregations.policyPosture` on`/api/resources` and `/api/resources/stats`. The aggregation must be derived@@ -1079,7 +1663,12 @@ the canonical monitored-system blocked payload.current action state from action audit. Backend `/api/ai/chat` refresh ofa finding handoff must also recover that requester identity from the liveapproval record when action audit has not yet hydrated the current action- state.+ state. Denying a Patrol investigation-fix approval through+ `/api/ai/approvals/{id}/deny` is part of the same API contract: it must+ persist the approval-store denial, record a `rejected` action-audit decision+ when the approval carries a governed action plan, and update the owning+ finding's investigation outcome to `fix_rejected` instead of leaving+ `fix_queued` with no live approval.Action execution is API-owned as the next explicit contract:`POST /api/actions/{id}/execute` may only start execution for an approvedaction or an approval-free executable plan, must atomically persist the@@ -1141,20 +1730,108 @@ the canonical monitored-system blocked payload.hybrid `agent` resource with merged source facets, not as duplicate rowsthat disappear only after REST reconciliation.8. Route unified-agent installer and binary download headers through `internal/api/unified_agent.go` and `internal/api/contract_test.go` together. Unified-agent BINARY downloads must keep the canonical `X-Checksum-Sha256` plus `X-Signature-Ed25519` contract for updater clients whether the binary is served locally or proxied from the matching GitHub release, instead of leaving callers to infer trust from source location alone. The served install-script endpoints (GET /install.sh and /install.ps1) are governed differently and have NO GitHub fallback at all: they serve the locally bundled AGENT installer or fail closed with 503. The agent installer is a per-build artifact bundled into every release tarball and Docker image, not a release asset, so the endpoint must never fetch the top-level GitHub install.sh release asset (the SERVER installer, which rejects the agent wizard's --url / --token-file, issue #1470). It attaches the base64-encoded `X-Signature-SSHSIG` header when the local detached signatures are present and omits it when they are not; a present-but-unsigned local agent installer is still served, because the agent install path (curl piped into bash) does not verify these headers, so correctness of the served script outranks signature presence.-9. Route canonical AI intelligence summary and resource-intelligence reads through `frontend-modern/src/api/ai.ts`, `frontend-modern/src/stores/aiIntelligence.ts`, `frontend-modern/src/stores/aiIntelligenceSummaryModel.ts`, `frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts`, `frontend-modern/src/features/patrol/PatrolIntelligenceSurface.tsx`, the Patrol-owned section files under `frontend-modern/src/features/patrol/`, `frontend-modern/src/pages/AIIntelligence.tsx`, `internal/api/ai_handlers.go`, and `internal/api/contract_test.go` together so the summary card, store normalization owner, runtime hook, feature shell, section owners, route shell, and backend payload stay aligned on one governed surface, including the canonical recent-changes slice- while keeping the learning counters backend-only coverage, so the summary page keeps Patrol health and findings primary and renders timeline, correlation, and policy-posture data as secondary investigation context rather than as a separate headline product metric+9. Route canonical AI intelligence summary and resource-intelligence reads through `frontend-modern/src/api/ai.ts`, `frontend-modern/src/stores/aiIntelligence.ts`, `frontend-modern/src/stores/aiIntelligenceSummaryModel.ts`, `frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts`, `frontend-modern/src/features/patrol/PatrolIntelligenceSurface.tsx`, the Patrol-owned section files under `frontend-modern/src/features/patrol/`, `frontend-modern/src/pages/AIIntelligence.tsx`, `internal/api/ai_handlers.go`, and `internal/api/contract_test.go` together so the store normalization owner, runtime hook, feature shell, Current work workspace, section owners, route shell, and backend payload stay aligned on one governed surface, including the canonical recent-changes slice+ while keeping the learning counters backend-only coverage, so Patrol keeps health and findings primary and renders timeline, correlation, and policy-posture data as selected-item investigation context rather than as a separate headline product metric+ and that secondary investigation context remains explanatory API evidence,+ not a default workspace mode: the Patrol page may expand recent-change,+ correlation, and policy-posture details only for an active Patrol finding or+ an explicitly selected run record, and must not surface those backend+ context payloads as a page-level forensic block from degraded summary health+ alone+ and the Patrol status presentation boundary, so trigger/scheduling status+ from Patrol status APIs stays in the header/control surface instead of being+ repeated as default status chrome, watch-only presentation says Patrol watches+ infrastructure and shows current issues while the selected Watch only mode+ describes the capability positively, such as Patrol watching infrastructure+ and reporting issues only, avoiding repeated header/control+ sentences, `Will not` policy-list wording, secondary Limits disclosures, or repeated+ infrastructure-unchanged caveats, and the browser-visible label stays+ operator-readable even when internal Assistant handoff metadata still uses+ assessment terminologyand the Patrol findings empty-state behavior, so `0 active findings` only renders as a healthy frontend conclusion when the same governed AI summary contract still reports healthy overall health; degraded or not-fully-verified health predictions must flow through to the Patrol findings surface instead of being replaced by page-local "looks healthy" copy- and the Patrol assessment headline plus compact summary-strip behavior, so the same governed AI summary contract decides whether the page leads with verified health, issues detected, coverage incomplete, or another attention state instead of letting count-only page fragments emit a stale `No issues found` conclusion- and the Patrol summary shell treatment itself, so the same governed summary contract still lands inside the shared neutral page-card base while severity travels through compact header accents and icon badges instead of a page-local full-width semantic background- and the Patrol summary/workspace badge treatment, so the API-owned finding,+ and the Patrol control presentation boundary, so the always-visible Patrol+ control selector owns the selected autonomy level, plan-locked installs keep+ watch-only as the current capability while disabled paid-level buttons may+ stay visible. Compact Pro badges and a `Plans & Billing` action may appear+ only when upgrade prompts are allowed; that billing action stays a compact+ handoff beside the selector rather than a separate upsell panel, and the+ selector must still avoid Limits controls, hard-limit matrices, or+ absent-feature explainers.+ Compact control labels remain understandable decisions such as `Ask first`,+ `Safe auto-fix`, and+ `Autopilot` rather than transport shorthand or Pro-matrix labels, the Patrol+ header description derives from the same+ effective control state, and the advanced settings+ drawer stays limited to model, schedule, trigger, and user-level model checks+ sourced from the existing settings APIs rather than duplicating a second+ control-level chooser. Runtime or provider setup+ readiness may suppress run, schedule, model, trigger, and provider-repair+ controls until Patrol can check infrastructure reliably, but it must not hide+ the Patrol mode selector or replace it with setup-first proof/status chrome.+ When provider/model readiness blocks manual Patrol while the header still+ shows current infrastructure work, the primary run control projects that API+ state as a direct Provider & Models setup action instead of an inert disabled+ `Run Patrol` button+ and the first-party Patrol mode starter boundary, so successful direct+ autonomy saves may record the coarse content-free `patrol_control` workflow+ prompt marker only when the effective control level or full-control+ acknowledgement changes and the paid Patrol control feature is available,+ while the autonomy settings API remains the source of truth for persisted+ control state rather than carrying prompt content, finding context, or+ completed-work proof; after recording that marker, Patrol state must reload+ Patrol status, findings, approvals, and run history so first-party control+ changes become visible as the next current-work step without waiting for polling+ and the Patrol trust-history evidence carried by Patrol status, so historical+ regressions keep the current findings empty state out of green all-clear copy+ even when the active finding count is zero and the latest summary score is+ otherwise healthy+ and the Patrol Current work assessment behavior, so the same governed AI summary contract decides whether the workspace leads with verified health, issues detected, coverage incomplete, or another attention state instead of letting count-only page fragments emit a stale `No issues found` conclusion+ and the Patrol Current work copy boundary, so the API-owned health,+ finding, run, and control facts remain semantic inputs while browser-visible+ empty and descriptive text stays operator-facing: what will appear there,+ what Patrol may do under the selected control level, and what to run or+ review next, not activation-loop proof, queue internals, or verification+ accounting+ and the Patrol control dialog/cross-surface Assistant handoff copy, so API+ compatibility identifiers such as `patrol_configuration_failure` may remain+ stable while user-facing and model-facing labels describe setting, saving,+ and reviewing Patrol control rather than a generic configuration/apply flow+ and the Patrol main-surface treatment itself, so the same governed summary contract lands inside the existing workspace and Current work surfaces while severity travels through compact header accents and icon badges instead of a page-local full-width verdict strip+ and the Patrol workspace badge treatment, so the API-owned finding,runtime, and run-history counts remain semantic input only while visiblestate and count badges route through frontend-primitives-owned`StatusIndicatorBadge` and `MetadataBadge` instead of page-local classstrings in the Patrol section owners- and Patrol loading indicator state remains API data only while the visible- header and finding loading spinners route through frontend-primitives-owned- `LoadingSpinner` instead of encoding API state in page-local spinner shells- and the Patrol verification summary derived from run history, so the page also states whether recent Patrol evidence came from a successful full patrol or only from scoped/erroring runs instead of leaving verification scope implicit+ and the Patrol control-level copy, so frontend section owners treat+ `PatrolAutonomyLevel` plus lock state as the API input for current-work and+ findings-workspace descriptions instead of presenting generic investigation+ or fix capabilities when the payload currently resolves to watch-only.+ The same API input owns the visible Patrol control boundary summary: what+ Patrol may do, what must ask for approval or Pro/runtime availability, and+ any explicit hard limits must derive from `PatrolAutonomyLevel` plus lock+ state, not from page-local safety thresholds or operations-loop completion+ proof. The default API-backed presentation must stay on the selected control+ level and its plain summary; it must not render a separate Limits disclosure,+ hard-limit matrix, or always-on explanatory matrix beside the mode picker.+ and the Patrol run-record copy, so `finding_ids` remains the API-owned+ fail-closed scoping input while the frontend presents selected history as a+ Patrol run record instead of a generic findings filter or snapshot workflow+ and Patrol loading indicator state remains API data only while the visible+ header and finding loading spinners route through frontend-primitives-owned+ `LoadingSpinner` instead of encoding API state in page-local spinner shells+ and Patrol first-load refresh failures remain degraded data state rather+ than route failure, so frontend Patrol load orchestration keeps the+ workspace mounted, preserves any last-known Patrol evidence, exposes a+ retry affordance, and sends transport details only to debug/API diagnostics+ instead of raw page copy+ and the Patrol issue-row presentation boundary, so active collapsed Patrol+ rows use API-owned severity, subject, recency, recurrence, and actionable+ workflow state as semantic input while suppressing raw `loopState`,+ investigation-status, investigation-outcome, confidence, and generic+ review/detected process badges from the default row; those process details+ remain available in expanded context, selected run records, Assistant+ handoff context, or API diagnostics when they are actually needed+ and the Patrol verification summary derived from run history, so the page also states whether recent Patrol evidence came from a successful full patrol or only from scoped/erroring runs instead of leaving verification scope implicitand the same-day activity-mix explanation derived from that governed run history, so when a recent full patrol is followed by alert-triggered or anomaly-triggered scoped work the verification surface can explain the mix directly instead of reconstructing it from page-local timing heuristicsand the Patrol status recency split, so `last_patrol_at` remains reserved for completed full Patrol sweeps while scoped runs and verification checks advance `last_activity_at` without claiming a fresh full-estate verification passand the Patrol Assistant handoff model, so frontend handoff prompts pass@@ -1162,25 +1839,53 @@ the canonical monitored-system blocked payload.bounded request metadata while leaving tool selection and remediationreasoning to the configured LLM instead of serializing a frontend-authoredtool route or fix plan into the API request+ and the Patrol control presentation boundary, so frontend copy may summarize+ assisted mode as low or medium-risk automatic fixes allowed by policy, but+ the risk threshold itself remains backend-owned and must not be inferred from+ warning severity, UI labels, or page-local finding state+ and the Patrol control route target, so the frontend-owned+ `/patrol#patrol-control` anchor remains the canonical navigation affordance,+ while `/patrol#operations-loop` remains inbound compatibility only, rather+ than becoming an API payload field, Assistant prompt body, or backend+ completion state machine. The canonical anchor must resolve to the visible+ Patrol mode selector, not to the assessment workspace; that anchor may+ route a new Pro user to Patrol mode from a generic Patrol run state, but issue-backed+ progress through Assistant, governed decision, verification, and MCP parity+ must still derive from real Patrol finding, investigation, approval, action,+ or trust evidence owned by the Patrol state model. The native Patrol+ workspace must not load the authenticated operations-loop status projection+ to decide current work; that projection remains an API/MCP/telemetry and+ adjacent commercial compatibility surface, while local Patrol state exposes+ Patrol work from status, findings, approvals, and run history. The route+ anchor itself must stay out of API payloads and must not become completion+ proof.+ When that projection still returns `nextAction: open_assistant` for a+ current Patrol finding, the first-party Patrol page must treat it as+ compatibility guidance and route the primary action into the Patrol findings+ workflow; Assistant handoffs remain contextual selected-finding actions, not+ the canonical API completion step for Patrol current work.and the canonical alert-triggered Patrol enqueue path in `internal/api/router.go`, so alert-fired Patrol work flows through the unified alert bridge and trigger manager instead of being duplicated by monitor callback wiringand the shared `frontend-modern/src/components/Infrastructure/ResourceChangeSummary.tsx` card, so canonical recent-change timelines stay rendered through one governed frontend card instead of separate page-local list loopsand the shared `frontend-modern/src/utils/resourceChangePresentation.ts` formatter used by the summary page and resource drawer, so canonical change wording does not drift across surfaces- and the Patrol-owned supporting-context selector, so same-state recent-change+ and the Patrol-owned `Details` context selector, so same-state recent-changerecords from the canonical AI payload are normalized into changed-substatewording before Patrol renders them or attaches them to Assistant, avoidingno-op operator copy such as `online` to `online` while preserving the- backend-owned timeline event+ backend-owned timeline event, and so those context payloads stay behind a+ compact operator-opened affordance rather than creating a default forensic+ block on the Patrol pageand the `/api/ai/intelligence/changes` route plus `internal/api/contract_test.go`, so the canonical recent-changes endpoint stays on the same intelligence facade and contract snapshot instead of bypassing the shared timeline sourceand the canonical policy-posture snapshot derived from unified resources, so sensitivity, routing, and redaction counts stay owned by the same AI summary contract instead of being reconstructed as a page-local governance rollupand the resource-intelligence payload carried by the drawer AI card, so the resource-detail surface stays on one canonical intelligence contract instead of introducing a separate detail endpointand the learned-correlation payload loaded into the shared AI intelligence store, so the Patrol intelligence page and the AI summary page consume the same governed correlation slice instead of each page fetching its own copyand the shared dashboard-load bundle inside `frontend-modern/src/stores/aiIntelligence.ts`, so the page orchestration stays on the store-owned bundle instead of enumerating the AI fetches inlineand the Patrol page refresh lifecycle in `frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts`, so slow or stalled secondary reads from that shared dashboard-load bundle may continue resolving in the background while the operator-facing Patrol refresh control remains generation-aware, timeout-bounded, and reusable once Patrol findings and status are already visible+ and the Patrol header support drawer in `frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx`, so API-owned Patrol status and trigger facts can feed a secondary Schedule & model surface without turning provider model, schedule, trigger tuning, or background-only runtime-policy pauses into the primary Patrol control decisionand the shared `frontend-modern/src/components/Infrastructure/ResourcePolicySummary.tsx` card, so the AI summary page renders the governed policy-posture counts while the resource drawer stays on per-resource policy lines instead of carrying duplicate posture UI loopsand the dedicated `frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts` owner, so recent-change, learned-correlation, and policy-coverage summary text stays derived from the canonical AI payload in one place instead of as hook-local count and pluralization logicand that same Patrol investigation-context owner, so the current Patrolassessment summary may open Assistant with bounded model-only assessment,- verification, latest-run, supporting-context evidence, active-finding, and+ verification, latest-run, supporting-context, active-finding, andresource reference context while leaving prioritization and next-stepreasoning to the configured LLM; activefinding entries may carry live pending Patrol approval posture only as safe@@ -1223,39 +1928,101 @@ the canonical monitored-system blocked payload.and the shared `frontend-modern/src/components/Infrastructure/ResourceCorrelationSummary.tsx` card, so learned correlations and correlation context stay rendered through one governed frontend card instead of separate page-local list loopsand the same shared correlation card's ordering and truncation rule, so callers pass raw correlations instead of encoding their own top-N sort behaviorand the shared `frontend-modern/src/components/Infrastructure/ResourceChangeSummary.tsx` and `frontend-modern/src/components/Infrastructure/ResourceCorrelationSummary.tsx` cards' infrastructure resource-link default, so the Patrol page, resource drawer, and problem-resource dashboard panels inherit the canonical resource-filter path construction instead of rebuilding infrastructure URLs inline- and the Patrol runtime-remediation destination shared with the AI settings endpoint, so summary actions, run-history runtime-failure actions, and runtime-finding actions may reuse the governed provider-settings route while still presenting that destination to Patrol operators as Patrol provider configuration instead of generic `AI Settings` copy+ and the Patrol runtime-remediation destination shared with the AI settings endpoint, so summary actions, run-history runtime-failure actions, and runtime-finding actions may reuse the governed provider-settings route while still presenting that destination in Patrol as provider configuration instead of generic `AI Settings` copyand the Patrol route-shell destination itself, so the thin page shell at `frontend-modern/src/pages/AIIntelligence.tsx` may continue to bridge the shared AI-runtime payload boundary while exposing `/patrol` as the canonical product route and keeping retired `/ai` browser entry points unregisteredand the Patrol route-shell accessibility boundary, so brand icons in `frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx` stay decorative when the same heading already exposes visible Patrol text, preventing duplicate accessible names such as `Pulse Patrol Patrol`- and the Patrol autonomy selector boundary, so the header composes the shared `frontend-modern/src/components/shared/FilterButtonGroup.tsx` segmented primitive for the `Monitor` / `Investigate` / `Remediate` presentation while the API contract remains the sole owner of accepted autonomy values, license-required rejection shape, and the monitor-only clamp-9. Route frontend API-client parsed error propagation, API-error-status fallback handling, allowed-status handling, custom status-specific error handling, command-trigger success envelope handling, shared response parsing pipelines, missing-resource lookup handling, metadata CRUD routing, stream event consumption, response status, collection normalization, scalar payload coercion, and structured error normalization through canonical shared helpers under `frontend-modern/src/api/`- Assistant chat stream workflow-state payloads are part of this same- frontend API-client boundary. `workflow_state` events must keep `phase`,- `message`, `state`, and `tool` stable, selected-route starts may carry- `provider` and `model`, and selected-route retry may carry `attempt`,- `max_attempts`, and `retry_after_ms`; automatic provider fallback metadata- (`provider_fallback`, `failed_provider`, `failed_model`, `next_provider`,- `next_model`) is retired from `/api/ai/chat` stream payloads. The- selected-route `provider_start` message is operator- progress copy and must be active/in-progress wording such as- `<Provider> is starting the response.` while the typed `provider` and `model`- fields carry the exact route identity. The generated- `frontend-modern/src/api/generated/aiChatEvents.ts` type must stay derived- from `internal/ai/chat/types.go` through `scripts/generate-types.go`, and- frontend API tests must pin any new generated SSE fields, including live- tool-start and tool-progress payload fields such as `phase` and `message`- and pending tool cancellation payloads such as `reason`.- That same shared org-management client boundary now owns target-consent- sharing semantics across `frontend-modern/src/api/orgs.ts`,- `internal/api/org_handlers.go`, and the shared org route wiring. Cross-org- share creation must remain a pending request until the target organization- accepts it, the payload must preserve `status`, `acceptedAt`, and- `acceptedBy`, and widening an accepted share's requested role must reset the- share back to `pending`. Downstream settings surfaces must not infer live- access from share creation alone or recreate manager-only pending-share- visibility rules locally.-10. Add or change API token scope, assignment, and revocation presentation through `frontend-modern/src/components/Settings/APITokenManager.tsx`, `frontend-modern/src/components/Settings/apiTokenManagerModel.ts`, and `frontend-modern/src/components/Settings/useAPITokenManagerState.ts`+ and the Patrol mode selector boundary, so the default header and the+ Patrol mode dialog compose the shared+ `frontend-modern/src/components/shared/FilterButtonGroup.tsx` primitive for+ the visible `Watch only` / `Ask before changes` / `Auto-fix safe issues` /+ `Policy autopilot` presentation while the API contract remains the sole owner of+ accepted autonomy values, `full_mode_unlocked` persistence,+ license-required rejection shape, and the monitor-only clamp; when the+ API/license state clamps Patrol to monitor for plan reasons, frontend+ consumers must present watch-only as the effective capability and badge paid+ levels rather than rendering a default Pro-absence explainer or a full-loop+ header description, while runtime-locked Pro installs may explain the missing+ runtime; provider model, schedule, trigger tuning, and readiness validation+ must remain advanced settings plumbing alongside that inline Patrol mode+ boundary. API-adjacent frontend and docs projections may keep legacy wire+ values such as `monitor`, `assisted`, and `full`, but customer-facing copy+ must name the visible choices as `Watch only`, `Auto-fix safe issues`, and+ `Policy autopilot` rather than leaking compatibility terminology.+ policy rather than changing the compatibility API boundary; setup-only+ readiness may hide those run/configuration affordances, but the visible+ Patrol mode selector remains the primary policy boundary during setup+ and the Patrol mode presentation boundary, so `frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx` routes active Patrol findings into the Patrol-owned findings workflow, renders the first-party loop as watch/investigate/act-under-policy/verify/record, uses `Patrol mode` as the human-facing name for the governed autonomy selector while preserving `patrol_control`, `patrolControl*`, and `patrol_autonomy` only for compatibility route and wire identifiers, and demotes Assistant and external-agent readiness out of the primary operator loop without introducing a new API request shape, frontend-authored tool route, serialized remediation plan, or page-local MCP setup contract; direct single-finding CTAs must derive from existing finding-presentation helpers and canonical routes such as the Patrol provider-settings route, selected findings, approvals, and history rows may still open contextual Assistant handoffs through their governed owners, setup-only Patrol runtime failures must use existing finding/runtime fields to render the Patrol-owned `Fix Patrol setup` framing, a dedicated setup task, and one direct `Open Provider & Models` action while suppressing the readiness banner, generic issue-row chips, filter chrome, and run-history action chrome that would compete with provider setup, but recent changes, correlations, and policy-coverage payloads must not render as a generic first-party Details/evidence console on the Patrol page, and raw finding lifecycle telemetry must be reserved for explicit all/resolved/history or selected-run review states instead of default active current-issue expansion+ The Patrol page may consume server-authored readiness and preflight-backed+ status, but it must translate that transport state into `Patrol setup issue`+ or `Patrol setup warning`, provider/model context, and the canonical+ `Open Provider & Models` action. Raw preflight, tool-call observation, and+ readiness-internal wording remain API/settings diagnostics rather than+ first-party Patrol operator banner copy.+ and the external-agent Patrol-control status route, so `GET /api/agent/patrol-control/status` may expose only aggregate Patrol issue evidence, aggregate active issue-level Patrol finding counts, pending approvals, contextual collaboration counts inside the Assistant step, governed action counts split into approved and rejected decision counts, verified outcome counts, Patrol control starter/completed-loop/resolved-loop proof exposed through primary `patrolControl*` fields, `patrolAutonomy*` compatibility fields, `proActivationOperationsLoopStarterCount` as an older-client compatibility field, completed/resolved/value `proActivation*` compatibility aliases, optional token-backed MCP readiness, generated timestamps, and the next coarse loop action for native and MCP-facing orchestration; it must not expose finding IDs, action IDs, resource names, commands, prompt text, model output, actors, request bodies, token identity, token names, or token counts, and it must not replace the canonical fleet-context, resource-context, finding, approval, or action routes that own the underlying detail. Its `progressLabel` is operator-facing Patrol status copy: it must describe the current action or outcome in plain Patrol terms such as checking, investigating, approval, rejection, verification, and recorded history rather than activation-loop, value-proof, autonomy, or MCP-completion language. Human-facing manifest capability descriptions, generated MCP README text, and frontend projections for this route must say Patrol mode; wire identifiers such as `patrol_control`, `patrolControlCompletedOperationsLoopCount`, `patrol_autonomy`, `patrolAutonomyCompletedOperationsLoopCount`, and `patrolAutonomyValueState` may retain control/autonomy terminology for compatibility, and `proActivation*` wire identifiers may remain only as compatibility fields, not as user-visible Pro activation journey copy. The route may count generic execution lifecycle as recent loop activity, but the governance stage is decision-backed: `governedActionCount` must require approved or rejected governed-action evidence, `approvedDecisionCount` and `rejectedDecisionCount` must preserve that split without identifiers, and `verifiedOutcomeCount` must require an approved governed action with verified post-action evidence. Current active findings and pending approvals are live operator work: they must keep the next action and four-step rollup pointed at the current finding or approval before older Patrol control completed/resolved proof is presented as history. Aggregate issue evidence and resolved trust history are not by themselves current operator work, so native Patrol consumers must not turn resolved-only history into current finding copy or actions. `patrolControlCompletedOperationsLoopCount` and the mirrored `patrolAutonomyCompletedOperationsLoopCount` may only be derived when content-free Patrol control starter evidence, Patrol issue evidence, contextual Assistant or external-agent collaboration evidence, and either rejected governed-decision evidence or approved governed-decision evidence with verified outcome evidence coexist in the same status window. `patrolControlResolvedOperationsLoopCount` and the mirrored `patrolAutonomyResolvedOperationsLoopCount` may only be derived when content-free Patrol control starter evidence, Patrol issue evidence, contextual Assistant or external-agent collaboration evidence, approved governed-decision evidence, and verified outcome evidence coexist in the same status window; no Patrol control or compatibility alias field may carry prompt, account, action, resource, or finding identity. The four-step `steps` rollup must keep counts aligned with the operator evidence that satisfies each stage: Patrol counts issue evidence, Assistant counts contextual collaboration without prompt or response content, governance counts pending approvals until an approved or rejected decision exists, then counts those decisions, and verification counts verified outcomes or terminal rejected decisions when no write ran. External agents remain optional readiness context through `externalAgentReady` rather than a first-party activation gate or operator step. A rejected-only decision is terminal for the execution-verification branch because no write ran; an approved decision still requires verified outcome proof before the verification step completes.+ The approved-success/verified-outcome predicate is shared inside+ `internal/api/`: outbound Pulse Intelligence action telemetry and+ `GET /api/agent/patrol-control/status` must both route through the same+ approved-action verification helper. A completed action with+ `ExecutionResult.Success=true` is execution evidence only; it must not set+ `verifiedOutcomeCount`, approved-action-success telemetry, Patrol control+ resolved-loop proof, or paid resolved-loop proof unless the action also has+ `VerificationOutcome.Status=verified` or a canonical verification result that+ ran and succeeded.+10. Route frontend API-client parsed error propagation, API-error-status fallback handling, allowed-status handling, custom status-specific error handling, command-trigger success envelope handling, shared response parsing pipelines, missing-resource lookup handling, metadata CRUD routing, stream event consumption, response status, collection normalization, scalar payload coercion, and structured error normalization through canonical shared helpers under `frontend-modern/src/api/`+ Telemetry preview payloads are part of this same frontend API-client+ boundary. `frontend-modern/src/api/settings.ts` must mirror the+ content-free `internal/telemetry.Ping` payload shape exposed by the system+ settings preview route, including Pulse Intelligence loop booleans, Assistant+ and Patrol counters, operations-loop workflow starter counts, governed-action+ counters including approved/rejected action decisions, and external-agent/MCP aggregate, adapter-origin, and+ capability-class counters, so browser preview, privacy disclosure, and+ outbound heartbeat JSON do not drift into separate contracts.+ Operations-loop starter fields may count only the canonical+ `pulse_operations_loop` prompt over the rotating telemetry window, with+ total, native Assistant, first-party Patrol, primary Patrol control,+ legacy Pro activation entry-point, and Pulse MCP counters. They are+ active-journey evidence,+ not proof that the user collaborated with context/tools, approved execution,+ verified an outcome, or resolved a finding.+ The external-agent/MCP readiness boolean in that same payload is a+ manifest-surface capability signal: a non-expired API token covering any+ Pulse MCP-published capability scope may configure the surface, while recent+ use still requires route activity markers and generic `ai:chat` tokens do+ not count as external-agent readiness.+ Assistant chat stream workflow-state payloads are part of this same+ frontend API-client boundary. `workflow_state` events must keep `phase`,+ `message`, `state`, and `tool` stable, selected-route starts may carry+ `provider` and `model`, and selected-route retry may carry `attempt`,+ `max_attempts`, and `retry_after_ms`; automatic provider fallback metadata+ (`provider_fallback`, `failed_provider`, `failed_model`, `next_provider`,+ `next_model`) is retired from `/api/ai/chat` stream payloads. The+ selected-route `provider_start` message is operator+ progress copy and must be active/in-progress wording such as+ `<Provider> is starting the response.` while the typed `provider` and `model`+ fields carry the exact route identity. The generated+ `frontend-modern/src/api/generated/aiChatEvents.ts` type must stay derived+ from `internal/ai/chat/types.go` through `scripts/generate-types.go`;+ `frontend-modern/src/api/generated/agentCapabilities.ts` must stay+ derived from `internal/agentcapabilities`, including manifest surface+ contract fields; and frontend API tests must pin+ any new generated SSE fields, including live tool-start and tool-progress+ payload fields such as `phase` and `message` and pending tool+ cancellation payloads such as `reason`. Control-level+ values exposed through AI settings or chat payloads must alias the shared+ `agentcapabilities.ControlLevel` vocabulary rather than redefining+ read-only/controlled/autonomous strings in API-local code.+ That same shared org-management client boundary now owns target-consent+ sharing semantics across `frontend-modern/src/api/orgs.ts`,+ `internal/api/org_handlers.go`, and the shared org route wiring. Cross-org+ share creation must remain a pending request until the target organization+ accepts it, the payload must preserve `status`, `acceptedAt`, and+ `acceptedBy`, and widening an accepted share's requested role must reset the+ share back to `pending`. Downstream settings surfaces must not infer live+ access from share creation alone or recreate manager-only pending-share+ visibility rules locally.+11. Add or change API token scope, assignment, and revocation presentation through `frontend-modern/src/components/Settings/APITokenManager.tsx`, `frontend-modern/src/components/Settings/apiTokenManagerModel.ts`, and `frontend-modern/src/components/Settings/useAPITokenManagerState.ts`That same shared token contract also owns audit scope separation: audit event, verification, summary, export, and unified action/export audit reads must require the dedicated `audit:read` scope instead of reusing broader monitoring or settings-read token grants.-11. Add or change infrastructure operations token generation, lookup, assignment, the pure unified-agent inventory/install model, the split infrastructure install state owner, the split direct-node/discovery infrastructure settings owners, the shared infrastructure-operations state provider/context shell, and install presentation through `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`, `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts`, `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts`, `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`, and `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx`. Phase 9 retired the InfrastructureOperationsController shell and the useInfrastructureReportingState reporting path; they must not be reintroduced, and aggregator-backed reporting reads are owned by `frontend-modern/src/components/Settings/useConnectionsLedger.ts` under the frontend-primitives contract.+12. Add or change infrastructure operations token generation, lookup, assignment, the pure unified-agent inventory/install model, the split infrastructure install state owner, the split direct-node/discovery infrastructure settings owners, the shared infrastructure-operations state provider/context shell, and install presentation through `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`, `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts`, `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts`, `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`, and `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx`. Phase 9 retired the InfrastructureOperationsController shell and the useInfrastructureReportingState reporting path; they must not be reintroduced, and aggregator-backed reporting reads are owned by `frontend-modern/src/components/Settings/useConnectionsLedger.ts` under the frontend-primitives contract.That same aggregator-backed reporting read may hide passive config orrollout handshakes from primary source-manager attention when the APIreason says only that an agent has not yet reported a comparable applied@@ -1275,11 +2042,11 @@ the canonical monitored-system blocked payload.temperature-key install and uninstall edits must resolve the realauthorized-keys target before filtering Pulse-managed `# pulse-` lines,and `internal/api/contract_test.go` must pin the generated shell shape.-12. Keep `internal/api/session_store.go` on a fail-closed auth-persistence boundary: persisted OIDC refresh tokens may only round-trip through encrypted-at-rest session payloads, and any missing-crypto or invalid-ciphertext path must drop the token instead of preserving plaintext-at-rest session state.-13. Keep tenant AI handler wiring on canonical provider ownership: `internal/api/ai_handlers.go` may wire tenant `ReadState` and tenant-scoped unified-resource providers into AI services, but it must not revive tenant snapshot-provider bridges once Patrol can initialize and verify from those canonical providers directly.-14. Keep Patrol status transport semantics explicit in that same AI handler layer: the Patrol status endpoint must carry machine-readable runtime availability such as blocked, running, disabled, active, or unavailable rather than asking frontend consumers to infer operator state from stale summaries or run history.-15. Keep legacy Patrol quickstart transport semantics retired from the public v6 GA contract: ordinary AI settings and Patrol status payloads must not expose quickstart credit/status fields, and any stale hosted-model blocked copy that survives from compatibility state must normalize back to provider/local-model setup rather than presenting credit badges or acquisition prompts.-16. Keep Patrol intelligence summary transport semantics single-voiced: the canonical overall-health payload and Patrol run-history payload together must support one primary assessment plus one explicit verification explanation, and frontend consumers must not need to derive a second compact assessment or verification verdict row from the same payloads beneath the primary assessment strip.+13. Keep `internal/api/session_store.go` on a fail-closed auth-persistence boundary: persisted OIDC refresh tokens may only round-trip through encrypted-at-rest session payloads, and any missing-crypto or invalid-ciphertext path must drop the token instead of preserving plaintext-at-rest session state.+14. Keep tenant AI handler wiring on canonical provider ownership: `internal/api/ai_handlers.go` may wire tenant `ReadState` and tenant-scoped unified-resource providers into AI services, but it must not revive tenant snapshot-provider bridges once Patrol can initialize and verify from those canonical providers directly.+15. Keep Patrol status transport semantics explicit in that same AI handler layer: the Patrol status endpoint must carry machine-readable runtime availability such as blocked, running, disabled, active, or unavailable rather than asking frontend consumers to infer operator state from stale summaries or run history.+16. Keep legacy Patrol quickstart transport semantics retired from the public v6 GA contract: ordinary AI settings and Patrol status payloads must not expose quickstart credit/status fields, and any stale hosted-model blocked copy that survives from compatibility state must normalize back to provider/local-model setup rather than presenting credit badges or acquisition prompts.+17. Keep Patrol intelligence summary transport semantics single-voiced: the canonical overall-health payload and Patrol run-history payload together must support one primary assessment plus one explicit verification explanation, and frontend consumers must not need to derive a second compact assessment or verification verdict row from the same payloads beneath the primary assessment strip.That same transport split now supports the visible Patrol assessment andaction metadata without adding another API field: the frontend summarycontract derives compact state from existing overall-health, run-history,@@ -1293,10 +2060,10 @@ the canonical monitored-system blocked payload.compact operator summary, but it must not imply a hero, card, duplicateverdict layout, or expanded assessment panel. Normal Patrol page consumersshould keep explanatory assessment, verification, activity, and supporting- context in the owning Findings, Runs, and Supporting context surfaces rather+ context in the owning Findings, Runs, and `Details` surfaces ratherthan re-expanding the primary assessment strip.-17. Keep Pulse Mobile relay credential minting and permission ownership on backend ownership: `internal/api/router_routes_auth_security.go`, `internal/api/security_tokens.go`, `internal/api/auth.go`, `internal/api/relay_mobile_capability.go`, `internal/api/router_routes_ai_relay.go`, and `frontend-modern/src/api/security.ts` may expose the canonical mobile runtime token creator and governed route gates, but browser callers must only consume that route and must not define the mobile runtime scope, compatibility gate list, route inventory, or token-purpose metadata locally.-18. Keep hosted tenant browser-session precedence on the shared auth boundary: `internal/api/auth.go`, `internal/api/contract_test.go`, and hosted tenant callers must treat a valid `pulse_session` as authoritative before any API-only token fallback or no-local-auth anonymous fallback, so cloud handoff can continue into protected hosted routes without flattening the operator back to `anonymous` or forcing a browser session through bearer-token-only mode after the tenant has minted API tokens.+18. Keep Pulse Mobile relay credential minting and permission ownership on backend ownership: `internal/api/router_routes_auth_security.go`, `internal/api/security_tokens.go`, `internal/api/auth.go`, `internal/api/relay_mobile_capability.go`, `internal/api/router_routes_ai_relay.go`, and `frontend-modern/src/api/security.ts` may expose the canonical mobile runtime token creator and governed route gates, but browser callers must only consume that route and must not define the mobile runtime scope, compatibility gate list, route inventory, or token-purpose metadata locally.+19. Keep hosted tenant browser-session precedence on the shared auth boundary: `internal/api/auth.go`, `internal/api/contract_test.go`, and hosted tenant callers must treat a valid `pulse_session` as authoritative before any API-only token fallback or no-local-auth anonymous fallback, so cloud handoff can continue into protected hosted routes without flattening the operator back to `anonymous` or forcing a browser session through bearer-token-only mode after the tenant has minted API tokens.That same shared auth boundary also owns hosted handoff authorization. `internal/api/cloud_handoff.go`,`internal/api/cloud_handoff_handlers.go`, and hosted tenant callers must derive the effective tenant role frompre-existing server-side org membership only, rather than trusting the handoff JWT to append missing members,@@ -1331,7 +2098,7 @@ the canonical monitored-system blocked payload.server-side for org metadata and RBAC assignment while using returnedcontact email only for `GenerateToken`/`SendMagicLink`; the accepted signupresponse remains uniform and must not expose the owner principal.-19. Keep tenant settings-scope authorization aligned with org management: `internal/api/security_setup_fix.go`, `internal/api/contract_test.go`, and settings-bound hosted callers must allow the current non-default org owner/admin membership to exercise privileged tenant routes, rather than requiring a separate configured local admin identity after hosted handoff.+20. Keep tenant settings-scope authorization aligned with org management: `internal/api/security_setup_fix.go`, `internal/api/contract_test.go`, and settings-bound hosted callers must allow the current non-default org owner/admin membership to exercise privileged tenant routes, rather than requiring a separate configured local admin identity after hosted handoff.Hosted handoff must not be treated as an org-management side effect for that same privilege boundary. Onlycanonical invitation, membership-management, or explicit owner-transfer flows may create tenant membership orchange the stored owner/admin role. Shared auth routes and downstream settings consumers must treat handoff role@@ -1358,7 +2125,7 @@ the canonical monitored-system blocked payload.development workflows, but release builds must compile that env overrideout entirely instead of reading it and deciding at runtime whether tohonor or ignore it.-20. Keep mobile onboarding payload reads aligned with the server-owned relay-mobile credential: `internal/api/router_routes_ai_relay.go`, `internal/api/onboarding_handlers.go`, and `internal/api/contract_test.go` must allow the dedicated `relay:mobile:access` scope to reach the governed QR, deep-link, and connection-validation payloads without reintroducing a broader `settings:read` requirement for token-authenticated pairing clients.+21. Keep mobile onboarding payload reads aligned with the server-owned relay-mobile credential: `internal/api/router_routes_ai_relay.go`, `internal/api/onboarding_handlers.go`, and `internal/api/contract_test.go` must allow the dedicated `relay:mobile:access` scope to reach the governed QR, deep-link, and connection-validation payloads without reintroducing a broader `settings:read` requirement for token-authenticated pairing clients.That same shared relay/runtime boundary also owns hostname targetequivalence for agent command routing. `internal/api/router_routes_ai_relay.go`and `internal/api/contract_test.go` may match a short host against the@@ -1386,13 +2153,13 @@ the canonical monitored-system blocked payload.authenticated Proxmox node agent, and must keep inventory collection behindthe monitoring-owned minimal Docker summary contract rather than exposinga new public API payload shape.-21. Keep hosted billing-state quickstart grants retired from new shared API flows: `internal/api/hosted_entitlement_refresh.go`, hosted signup, and trial-state construction must not auto-grant or refresh quickstart inventory for new workspaces, while low-level billing-state readers may still preserve historical fields that already exist on disk.-22. Keep hosted AI settings bootstrap on the shared API contract as a retired path: `internal/api/ai_hosted_runtime.go`, `internal/api/ai_handlers.go`, `internal/api/ai_handler.go`, and `internal/api/contract_test.go` must treat a missing `ai.enc` in hosted mode as an unconfigured BYOK/local-provider state, not as a machine-owned `quickstart:pulse-hosted` bootstrap condition. Hosted tenant reads may inherit billing state for commercial authorization, but they must not create quickstart-backed AI config or call the quickstart bootstrap upstream route.-23. Keep post-boot AI enablement contract-backed on the shared AI/mobile approval surface: `internal/api/ai_handler.go`, `internal/api/ai_handlers.go`, `internal/api/router_routes_ai_relay.go`, and `internal/api/contract_test.go` must turn the governed approvals-list API into the canonical empty-list payload as soon as settings-driven AI enablement succeeds, rather than leaving that surface on `503 Approval store not initialized` until some separate startup-only side effect happens.-24. Keep infrastructure summary chart transport contract-backed on the shared API surface: `internal/api/router.go`, `internal/api/contract_test.go`, and frontend infrastructure summary consumers must normalize long-range mixed-cadence history into equal-time summary buckets before shipping the infrastructure charts API payload, so 7-day and 30-day summary cards do not expose compressed right-edge tails just because recent samples arrive at a finer storage resolution.-25. Keep long-range workload chart transport time-proportional on the shared API surface: `internal/api/router.go`, `internal/api/contract_test.go`, and workload chart consumers must cap mixed-cadence workload history by equal-time buckets rather than raw point index for the per-workload and aggregate workload chart APIs, so 7-day and 30-day workload cards do not bunch recent samples at the right edge just because recent telemetry is stored more densely.-26. Keep chart timestamp precision canonical on that same shared API surface: when `internal/api/router.go` serializes monitoring history into infrastructure or workload chart payloads, it must preserve canonical millisecond timestamps from the shared monitoring timeline instead of rounding through whole-second conversion, so seeded mock history and live appends collapse onto one operator-visible timeline instead of appearing as duplicated tail samples.-27. Keep Patrol remediation payload naming backward-compatible without leaking+22. Keep hosted billing-state quickstart grants retired from new shared API flows: `internal/api/hosted_entitlement_refresh.go`, hosted signup, and trial-state construction must not auto-grant or refresh quickstart inventory for new workspaces, while low-level billing-state readers may still preserve historical fields that already exist on disk.+23. Keep hosted AI settings bootstrap on the shared API contract as a retired path: `internal/api/ai_hosted_runtime.go`, `internal/api/ai_handlers.go`, `internal/api/ai_handler.go`, and `internal/api/contract_test.go` must treat a missing `ai.enc` in hosted mode as an unconfigured BYOK/local-provider state, not as a machine-owned `quickstart:pulse-hosted` bootstrap condition. Hosted tenant reads may inherit billing state for commercial authorization, but they must not create quickstart-backed AI config or call the quickstart bootstrap upstream route.+24. Keep post-boot AI enablement contract-backed on the shared AI/mobile approval surface: `internal/api/ai_handler.go`, `internal/api/ai_handlers.go`, `internal/api/router_routes_ai_relay.go`, and `internal/api/contract_test.go` must turn the governed approvals-list API into the canonical empty-list payload as soon as settings-driven AI enablement succeeds, rather than leaving that surface on `503 Approval store not initialized` until some separate startup-only side effect happens.+25. Keep infrastructure summary chart transport contract-backed on the shared API surface: `internal/api/router.go`, `internal/api/contract_test.go`, and frontend infrastructure summary consumers must normalize long-range mixed-cadence history into equal-time summary buckets before shipping the infrastructure charts API payload, so 7-day and 30-day summary cards do not expose compressed right-edge tails just because recent samples arrive at a finer storage resolution.+26. Keep long-range workload chart transport time-proportional on the shared API surface: `internal/api/router.go`, `internal/api/contract_test.go`, and workload chart consumers must cap mixed-cadence workload history by equal-time buckets rather than raw point index for the per-workload and aggregate workload chart APIs, so 7-day and 30-day workload cards do not bunch recent samples at the right edge just because recent telemetry is stored more densely.+27. Keep chart timestamp precision canonical on that same shared API surface: when `internal/api/router.go` serializes monitoring history into infrastructure or workload chart payloads, it must preserve canonical millisecond timestamps from the shared monitoring timeline instead of rounding through whole-second conversion, so seeded mock history and live appends collapse onto one operator-visible timeline instead of appearing as duplicated tail samples.+28. Keep Patrol remediation payload naming backward-compatible without leakinglegacy automation-first wording into product copy. `frontend-modern/src/api/patrol.ts`,`internal/api/ai_handlers.go`, and `internal/api/router_routes_ai_relay.go`may continue to expose stable transport fields such as `fixed_count`,@@ -1400,8 +2167,8 @@ the canonical monitored-system blocked payload.API license-required messages, and presentation labels layered on that APIcontract must describe the operator-visible capability as remediation orsafe remediation workflows.-27. Keep storage chart identity canonical on that same shared API surface: the shared storage charts endpoint must key pool and physical-disk series by the resolved unified-resource `MetricsTarget.ResourceID`, not by canonical resource IDs or page-local aliases, so storage rows, focused summary cards, sticky summary shells, and detail charts all address the same history series in live and mock mode.-28. Keep synthetic summary-chart fallback identity canonical on that same shared API surface: when `internal/api/router.go` has to synthesize mock summary history for infrastructure, workloads, or storage cards, it must derive the fallback from canonical `resourceType`, `resourceID`, and `metricType` ownership instead of raw min/max seed-prefix helpers, so range changes and runtime mock updates stay on one governed timeline.+29. Keep storage chart identity canonical on that same shared API surface: the shared storage charts endpoint must key pool and physical-disk series by the resolved unified-resource `MetricsTarget.ResourceID`, not by canonical resource IDs or page-local aliases, so storage rows, focused summary cards, sticky summary shells, and detail charts all address the same history series in live and mock mode.+30. Keep synthetic summary-chart fallback identity canonical on that same shared API surface: when `internal/api/router.go` has to synthesize mock summary history for infrastructure, workloads, or storage cards, it must derive the fallback from canonical `resourceType`, `resourceID`, and `metricType` ownership instead of raw min/max seed-prefix helpers, so range changes and runtime mock updates stay on one governed timeline.The same compact chart boundary also owns aggregate-only storage summarytransport. `/api/charts/storage-summary` may batch only the canonical`used` and `avail` storage series required for the aggregate capacity@@ -1411,24 +2178,24 @@ the canonical monitored-system blocked payload.When mock mode is active, that same endpoint must come from themonitor-owned aggregate summary cache rather than rehydrating each poolchart on request.-29. Keep workload-chart response identity canonical on that same shared API surface: `internal/api/router.go`, `internal/api/contract_test.go`, and workload summary consumers must emit provider-backed VM and system-container series under the same canonical workload IDs that workloads page rows use, while resolving history through the unified `MetricsTarget.ResourceID`, so hover and focus selection do not fall off for provider-backed rows.+31. Keep workload-chart response identity canonical on that same shared API surface: `internal/api/router.go`, `internal/api/contract_test.go`, and workload summary consumers must emit provider-backed VM and system-container series under the same canonical workload IDs that workloads page rows use, while resolving history through the unified `MetricsTarget.ResourceID`, so hover and focus selection do not fall off for provider-backed rows.Kubernetes pod workload rows follow that same contract through theirmetrics target. `/api/resources` may expose pod history only through theunified `MetricsTarget.ResourceID`, but that target must be the canonicalprefixed runtime key `k8s:<cluster>:pod:<uid>` and not the bare source podID, so pod workload rows and pod chart payloads stay on one history series.-30. Keep the hosted account portal bootstrap intelligible without duplicate+32. Keep the hosted account portal bootstrap intelligible without duplicatechrome. `internal/cloudcp/portal/page.go`, the maintained portal frontendbundle, and the shared portal styles may refine layout density, but theaccount/billing shell must remain understandable from the primary header,section title, and factual body content alone instead of depending on asecond context-chip strip to restate the same scope.-31. Keep storage wire metadata lossless across shared API payload types.+33. Keep storage wire metadata lossless across shared API payload types.`frontend-modern/src/types/api.ts` must continue to expose provider-backedstorage metadata such as Proxmox `pool` and `zfsPool` fields when thebackend emits them, instead of silently dropping that detail from theshared runtime contract.-32. Keep hosted entitlement refresh ownership on the same governed API contract+34. Keep hosted entitlement refresh ownership on the same governed API contractas hosted status and entitlements reads. `internal/api/licensing_handlers.go`,`internal/api/hosted_entitlement_refresh.go`, and`internal/api/contract_test.go` must resolve the effective hosted billing@@ -1441,7 +2208,7 @@ the canonical monitored-system blocked payload.must route through the `HostedEntitlement*` licensing aliases rather thantreating the retired trial-activation callback as the active acquisitionmodel.-33. Keep public demo bootstrap posture on the shared security-status contract.+35. Keep public demo bootstrap posture on the shared security-status contract.`internal/api/router_routes_auth_security.go`,`internal/api/security_status_capabilities.go`, frontend security-statusconsumers, and shared demo-mode stores must treat@@ -1453,7 +2220,7 @@ the canonical monitored-system blocked payload.the store boundary, so public demo shells do not probe `/api/ai/approvals`or `/api/ai/remediation/plans` after the read-only demo posture is alreadyknown.-34. Keep public demo commercial posture middleware-owned on that same shared+36. Keep public demo commercial posture middleware-owned on that same sharedAPI contract. `internal/api/demo_middleware.go`,`internal/api/demo_mode_commercial.go`,`internal/api/subscription_entitlements.go`, and@@ -1465,7 +2232,7 @@ the canonical monitored-system blocked payload.hidden. Upgrade prompts, trial nudges, monitored-system migration guidance,usage counts, billing identity, and plan metadata must therefore not dependon hidden commercial routes surviving the public demo boundary.-35. Keep the storage summary route in `internal/api/router.go` as the+37. Keep the storage summary route in `internal/api/router.go` as thecanonical storage summary contract across dashboard and storage consumers.`internal/api/router.go`,`internal/api/contract_test.go`, and shared frontend consumers must expose@@ -1473,7 +2240,7 @@ the canonical monitored-system blocked payload.metrics-target IDs, preserve millisecond chart timestamps, and avoidreconstructing storage summary behavior from per-pool`/api/metrics-store/history` fan-out.-36. Keep infrastructure summary metric filtering canonical on that same shared+38. Keep infrastructure summary metric filtering canonical on that same sharedAPI surface. `frontend-modern/src/api/charts.ts`,`internal/api/router_routes_monitoring.go`, `internal/api/router.go`,`internal/api/types.go`, and `internal/api/contract_test.go` must route@@ -1484,7 +2251,7 @@ the canonical monitored-system blocked payload.requested metric filters through the shared guest-chart batch loader in`internal/monitoring/monitor_metrics.go` instead of fetching the full guestmetric set and trimming after the API payload is already assembled.-37. Keep the retired compact dashboard overview route absent from that same+39. Keep the retired compact dashboard overview route absent from that sameshared API surface. `internal/api/resources.go`,`internal/api/router_routes_monitoring.go`, and`frontend-modern/src/api/resources.ts` must not restore@@ -1493,7 +2260,7 @@ the canonical monitored-system blocked payload.rows, governed resource labels, top-infrastructure identity, or metrics-target join keys. New summary payloads must be owned by their productroute and pinned in the API contract there.-38. Keep mock and demo chart reads on the same canonical unified snapshot as+40. Keep mock and demo chart reads on the same canonical unified snapshot asthe rest of the API surface. `internal/api/router.go`,`internal/api/contract_test.go`, and chart consumers must route`/api/charts`, `/api/charts/infrastructure`, and `/api/storage-charts`@@ -1501,7 +2268,7 @@ the canonical monitored-system blocked payload.presentation is active, so VMware, storage, and infrastructure series stayaligned with `/api/resources` and `/api/state` instead of drifting onto thelive store-backed graph.-39. Route the unified connections ledger and address probe through+41. Route the unified connections ledger and address probe through`internal/api/connections_types.go`,`internal/api/connections_aggregator.go`,`internal/api/connections_handlers.go`,@@ -1631,7 +2398,10 @@ the canonical monitored-system blocked payload.## Completion Obligations-1. Update contract tests when payloads change, including admin verification endpoints such as `POST /api/ai/patrol/preflight` whose response shape (`tool_call_observed`, `duration_ms`, classified `cause`/`summary`/`recommendation`, plus `recorded_at`/`recorded_at_unix` for the cached snapshot) is part of the canonical Patrol diagnostic surface, the `patrol_preflight` snapshot field on `/api/settings/ai` that hydrates the Verify Patrol panel on page load, the auto-trigger contract on `POST/PUT /api/settings/ai` whose handler dispatches preflight in the background only when the change actually moved Patrol transport so routine saves do not write a new `patrol_preflight` snapshot, the startup-seed contract where `NewAISettingsHandler` dispatches the same async preflight after `LoadConfig()` succeeds so the first `/api/settings/ai` poll after a Pulse restart already carries a populated `patrol_preflight` snapshot, and the GET-symmetry contract where `HandleGetAISettings` includes `patrol_readiness` (with the cached-preflight-augmented `tools` check) on the same response that already carries `patrol_preflight`, so the Patrol page picks up classified preflight evidence on first load instead of only after a save+1. Update contract tests when payloads change, including admin verification endpoints such as `POST /api/ai/patrol/preflight` whose response shape (`tool_call_observed`, `duration_ms`, classified `cause`/`summary`/`recommendation`, plus `recorded_at`/`recorded_at_unix` for the cached snapshot) is part of the canonical Patrol diagnostic surface, the `patrol_preflight` snapshot field on `/api/settings/ai` that hydrates the Check Patrol model panel on page load, the auto-trigger contract on `POST/PUT /api/settings/ai` whose handler dispatches preflight in the background only when the change actually moved Patrol transport so routine saves do not write a new `patrol_preflight` snapshot, the startup-seed contract where `NewAISettingsHandler` dispatches the same async preflight after `LoadConfig()` succeeds so the first `/api/settings/ai` poll after a Pulse restart already carries a populated `patrol_preflight` snapshot, and the GET-symmetry contract where `HandleGetAISettings` includes `patrol_readiness` (with the cached-preflight-augmented `tools` check) on the same response that already carries `patrol_preflight`, so the Patrol page picks up classified preflight evidence on first load instead of only after a save; readiness checks may keep stable machine IDs such as `configuration`, but user-facing labels in this payload must say Patrol mode rather than Patrol configuration, and the settings UI must summarize successful diagnostic snapshots as model readiness instead of rendering raw preflight/tool-call wording+ The same diagnostic payload may inform Patrol page setup banners, but the+ Patrol page must present it as setup/model-check state and must not render+ raw preflight or tool-call-observation copy in the header banner.2. Update frontend API types in the same slice3. Route runtime changes through the explicit API-contract proof policies in `registry.json`; default fallback proof routing is not allowed4. Update this contract when canonical payload ownership changes@@ -1643,7 +2413,9 @@ the canonical monitored-system blocked payload.`event_triggers_blocked_reason`, and`event_triggers_blocked_message` explain effective runtime policy withoutmaking the transport look like the operator turned alert or anomaly triggers- off+ off; default Patrol UI surfaces may use that payload to explain an+ actionable manual-run block, but must not promote a background-only policy+ pause as ordinary operator guidance when manual Patrol still worksand the split Patrol trigger settings contract, so `patrol_alert_triggers_enabled` and `patrol_anomaly_triggers_enabled` are the canonical AI settings fields while legacy `patrol_event_triggers_enabled` remains a compatibility aggregate rather than the primary control surfaceand the retired quickstart compatibility contract, so `/api/settings/ai` and`/api/ai/patrol/status` no longer carry `quickstart_credits_remaining`,@@ -1767,8 +2539,7 @@ the canonical monitored-system blocked payload.`recommendation`, and the Finding to UnifiedFinding conversion in`internal/api/router.go` must copy `f.PreviousResolvedFixSummary`alongside the other operator-facing strings.- The same shape also carries an optional `remind_at` timestamp (ISO- 8601) on both `UnifiedFindingRecord` and Patrol `Finding` shapes. It+ The same shape also carries an optional `remind_at` timestamp (ISO 8601) on both `UnifiedFindingRecord` and Patrol `Finding` shapes. Itis populated only when `dismissed_reason === 'will_fix_later'` andrepresents the wake-up deadline at which the next re-detection clearsthe dismissal — the operator-facing half of the canonical@@ -1782,7 +2553,7 @@ the canonical monitored-system blocked payload.time and badge dismissed-as-will_fix_later rows with the pendingremind-at, otherwise the new behavior is invisible until thereminder fires.- The Patrol operator-feedback endpoint surface also includes+ The Patrol manual-feedback endpoint surface also includes`POST /api/ai/patrol/resolve` (handled by `HandleResolveFinding` in`internal/api/ai_handlers.go`) for operator-driven manual resolutionwhen the operator has fixed an issue out-of-band. The TS client@@ -1809,10 +2580,11 @@ the canonical monitored-system blocked payload.`PatrolIntelligenceHeader` shell on the Patrol API surface readsthe title, description, and title tooltip from`getPatrolPageHeaderMeta()` rather than carrying inline copy, so the- operator-facing framing of what Patrol owns (scheduled probing,- context assembly for the configured model, and approval-bound action)- stays tied to the contract instead of drifting between hover and- inline.+ operator-facing framing of what Patrol owns (watching infrastructure,+ detecting issues, recording findings, and escalating into governed+ investigation/action only when the selected Patrol mode+ allows it) stays tied to the contract instead of drifting between+ hover and inline.The Patrol page must not introduce header or workspace trust strips overthis payload. High-signal trust facts from`state.patrolStatus()?.trust` (the `FindingsTrustSummary` block already@@ -1828,7 +2600,7 @@ the canonical monitored-system blocked payload.new API surface. The label stays optional when coverage is zero, saysverified only for successful full patrols, and uses neutral checked wordingfor errored full patrols or scoped activity.- The primary Patrol assessment copy uses that same run-history-backed+ The Patrol Current work empty-state copy uses that same run-history-backedcoverage truth when reconciling AI summary coverage factors: a successfulfull run with non-zero `resources_checked` suppresses stalecoverage-incomplete wording, while scoped, missing, zero-coverage, or errored@@ -1922,8 +2694,8 @@ the canonical monitored-system blocked payload.and must not expose raw command text or raw execution output. Frontendhandoff briefings must derive from the same shared investigation payloadrather than inventing a second finding-context transport shape.-7. Keep Patrol summary payload consumers aligned on one assessment hierarchy: transport-driven Patrol summary surfaces may show supporting counts and outcomes, but the canonical assessment and verification states must remain singular and not be repeated as a second compact verdict strip. The collapsed readout should describe current operator state and score directly rather than combining reassuring grade labels with active-issue copy.-8. Keep Patrol verification and activity facts unified on one transport-backed secondary status area: when frontend consumers combine Patrol status payloads (`runtime_state`, `last_patrol_at`, `last_activity_at`, `trigger_status`) with run-history transport, the latest run result, activity mix, scoped-trigger state, and circuit-breaker context must read as one supporting explanation beneath the primary assessment instead of being re-expanded into a separate full-width status strip plus duplicate summary layers+7. Keep Patrol summary payload consumers aligned on one assessment hierarchy: transport-driven Patrol summary data may show supporting counts and outcomes, but the canonical assessment and verification states must remain singular and not be repeated as a second compact verdict strip. The collapsed readout should describe current operator state and score directly rather than combining reassuring grade labels with active-issue copy; recurrence and trust counters are historical evidence unless the active finding or approval payload marks current operator work. Patrol-owned status, finding, and run-history payloads are sufficient fallback evidence for Current issues when the broader intelligence summary payload is missing, slow, or unavailable. Frontend consumers of the operations-loop projection must present the compact progress label as current work state, not as a duplicate of the selected Patrol autonomy mode, and terminal verified/rejected outcomes with no active finding or pending approval must stay history detail behind `No active work`; native Patrol consumers must not render a separate proof strip solely to expose that history action. A first-party Patrol control starter may render a ready-to-run Patrol step only after subtracting the legacy `proActivationOperationsLoopStarterCount` alias from aggregate Patrol-control starter evidence, so a legacy activation-entry count alone cannot revive the old proof UI.+8. Keep Patrol verification and activity facts unified on one transport-backed secondary status area: when frontend consumers combine Patrol status payloads (`runtime_state`, `last_patrol_at`, `last_activity_at`, `trigger_status`) with run-history transport, the latest run result, activity mix, scoped-trigger state, and circuit-breaker context must read as one supporting explanation beneath Current issues or selected history instead of being re-expanded into a separate full-width status strip plus duplicate summary layersand the Patrol runtime-failure run-history contract, so backend payloads,persistence adapters, and `frontend-modern/src/api/patrol.ts` preserve`error_summary` and `error_detail` whenever an erroring run has structured@@ -1936,19 +2708,15 @@ the canonical monitored-system blocked payload.while forcing request-local approval-required mode and leaving retries,configuration changes, and remediation authority outside the chat payloadand the main Patrol page composition boundary, so once that governed- secondary area exists inside the summary shell the same payloads must not+ secondary area exists inside the Current issues and history workspace the same payloads must notalso drive a second page-level status strip elsewhere on the route- and the Patrol supporting-context disclosure rule, so recent changes,- learned correlations, and policy coverage stay secondary explanatory context- that opens only when degraded verification, active findings, or selected-run- investigation makes that evidence relevant instead of advertising a parallel- Patrol workflow on otherwise healthy fully verified states, and the- disclosure copy must explicitly tell operators that findings and run history- are the Patrol verification evidence while those supporting cards only add- explanation from the same governed payload family, and the Patrol-owned- helper `frontend-modern/src/features/patrol/patrolSupportingContextPresentation.ts`- must keep that transport-derived trust copy aligned across the workspace- disclosure rather than letting page shells invent local wording+ and the Patrol `Details` disclosure rule, so recent changes,+ learned correlations, and policy coverage stay backend and Assistant context+ instead of advertising a parallel Patrol workflow on otherwise healthy fully+ verified states or degraded summary health alone. First-party Patrol page+ consumers must not turn those payloads into a generic Details/supporting+ context panel; selected finding and run records remain the source of truth for+ what the operator can inspect or do next.9. Keep AI settings setup transport vendor-neutral: `/api/settings/ai/update`must accept provider credentials or base URLs without a baked vendor modelID, resolve the effective BYOK `model` through the canonical runtime@@ -1961,17 +2729,17 @@ the canonical monitored-system blocked payload.analysis preferences in config, but response payloads must expose only thecontrol level and paid Patrol settings currently allowed by runtimeentitlements.-10. Treat Patrol summary supporting metrics as readouts, not reinterpretations: when frontend consumers derive cards such as active findings, criticals, warnings, or fixes from the canonical payloads, those cards must stay numeric and must not synthesize new assessment labels like `Issues detected` or verification labels like `Partial verification` beneath the primary summary contract-11. Treat active Patrol runtime transport as compatible with factual activity surfaces: when the runtime is currently running, frontend consumers may surface in-progress activity context, but they must not replace the activity strip with a second assessment verdict derived from runtime state alone-12. Treat Patrol recency as a singular transport-driven fact: once header metadata, verification copy, or the findings footer already present the governed Patrol timing context, frontend summary consumers must not derive an extra timing pill from the same payloads inside the primary summary card-13. Treat Patrol findings counts as a singular supporting surface as well: when the summary shell already exposes count cards for active findings, warnings, criticals, and fixes, the primary assessment card must not repeat those same payload-derived counts as secondary badges-14. Treat Patrol schedule and recency as header-owned metadata on the main Patrol page: findings empty-state consumers should not receive or restate `next_patrol_at`, `last_patrol_at`, `last_activity_at`, or interval timing once those transport fields are already presented by the primary header and verification shell-15. Keep recovery payload filters canonical across `/api/recovery/rollups`, `/api/recovery/points`, `/api/recovery/series`, and `/api/recovery/facets`: when `internal/api/recovery_handlers.go` adds a governed recovery filter or display field such as provider-neutral `itemType`, the same normalized transport must land across all four endpoints and the contract tests must pin both outbound payload shape and accepted query aliases in the same slice-16. Keep recovery platform-query vocabulary canonical across that same `/api/recovery/*` surface: operator-facing transport must emit `platform` as the canonical query field, accepted legacy `provider` aliases must remain compatibility-only input, and `internal/api/contract_test.go` must pin that fallback behavior in the same slice as any handler change-17. Keep recovery payload platform vocabulary canonical across that same `/api/recovery/*` surface: point payloads must expose `platform`, rollup payloads must expose `platforms`, and any compatibility `provider` / `providers` aliases must remain secondary fallback fields rather than replacing the shared response model-18. Keep recovery linked-resource vocabulary canonical across that same `/api/recovery/*` surface: points and rollups must expose `itemResourceId` as the canonical linked-resource field, accepted legacy `subjectResourceId` aliases must remain compatibility-only input or secondary payload fields, and the shared proof surface must pin that normalization in the same slice as any handler change-19. Keep recovery external item-reference vocabulary canonical across that same `/api/recovery/*` surface: point and rollup payloads must expose `itemRef` as the canonical external item-reference field, accepted legacy `subjectRef` aliases must remain compatibility-only secondary payload fields, and the shared proof surface must pin that normalization in the same slice as any handler change-20. Keep first-host lookup completion explicit on the shared install-state API+11. Treat Patrol summary supporting metrics as readouts, not reinterpretations: when frontend consumers derive cards such as active findings, criticals, warnings, or fixes from the canonical payloads, those cards must stay numeric and must not synthesize new assessment labels like `Issues detected` or verification labels like `Partial verification` beneath the primary summary contract+12. Treat active Patrol runtime transport as compatible with factual activity surfaces: when the runtime is currently running, frontend consumers may surface in-progress activity context, but they must not replace the activity strip with a second assessment verdict derived from runtime state alone+13. Treat Patrol recency as a singular transport-driven fact: once header metadata, verification copy, or the findings footer already present the governed Patrol timing context, frontend summary consumers must not derive an extra timing pill from the same payloads inside the primary summary card+14. Treat Patrol findings counts as a singular supporting surface as well: when the summary shell already exposes count cards for active findings, warnings, criticals, and fixes, the primary assessment card must not repeat those same payload-derived counts as secondary badges+15. Treat Patrol schedule and recency as header-owned metadata on the main Patrol page: findings empty-state consumers should not receive or restate `next_patrol_at`, `last_patrol_at`, `last_activity_at`, or interval timing once those transport fields are already presented by the primary header and verification shell+16. Keep recovery payload filters canonical across `/api/recovery/rollups`, `/api/recovery/points`, `/api/recovery/series`, and `/api/recovery/facets`: when `internal/api/recovery_handlers.go` adds a governed recovery filter or display field such as provider-neutral `itemType`, the same normalized transport must land across all four endpoints and the contract tests must pin both outbound payload shape and accepted query aliases in the same slice+17. Keep recovery platform-query vocabulary canonical across that same `/api/recovery/*` surface: operator-facing transport must emit `platform` as the canonical query field, accepted legacy `provider` aliases must remain compatibility-only input, and `internal/api/contract_test.go` must pin that fallback behavior in the same slice as any handler change+18. Keep recovery payload platform vocabulary canonical across that same `/api/recovery/*` surface: point payloads must expose `platform`, rollup payloads must expose `platforms`, and any compatibility `provider` / `providers` aliases must remain secondary fallback fields rather than replacing the shared response model+19. Keep recovery linked-resource vocabulary canonical across that same `/api/recovery/*` surface: points and rollups must expose `itemResourceId` as the canonical linked-resource field, accepted legacy `subjectResourceId` aliases must remain compatibility-only input or secondary payload fields, and the shared proof surface must pin that normalization in the same slice as any handler change+20. Keep recovery external item-reference vocabulary canonical across that same `/api/recovery/*` surface: point and rollup payloads must expose `itemRef` as the canonical external item-reference field, accepted legacy `subjectRef` aliases must remain compatibility-only secondary payload fields, and the shared proof surface must pin that normalization in the same slice as any handler change+21. Keep first-host lookup completion explicit on the shared install-state APIboundary: when`frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`receives a successful connected-agent lookup result, the canonical install@@ -1979,14 +2747,14 @@ the canonical monitored-system blocked payload.first visible platform/runtime page rather than leaving the operator on atransport-only status readout or reviving the removed `/infrastructure`route.-21. Keep the shared first-host detection contract explicit on `/api/state` as+22. Keep the shared first-host detection contract explicit on `/api/state` asused by`frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`:the canonical `connectedInfrastructure` projection must stay suitable fordetecting the first active reporting system during install so brand-newoperators can receive the first success handoff without typing a hostnameor agent ID.-22. Keep the shared first-run install-token transport explicit on+23. Keep the shared first-run install-token transport explicit on`/api/security/tokens` as used by`frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`:once quick setup has produced the setup handoff credentials, the canonical@@ -1997,7 +2765,7 @@ the canonical monitored-system blocked payload.install-state surface must describe that prepared token path consistentlywith the live runtime behavior rather than directing the operator to createanother install token manually.-23. Keep connected-infrastructure surface vocabulary canonical across the+24. Keep connected-infrastructure surface vocabulary canonical across theshared `/api/state` and reporting/install consumers:`frontend-modern/src/types/api.ts` must treat `truenas` as a first-classconnected-infrastructure surface kind, and connected-infrastructure@@ -2015,13 +2783,20 @@ the canonical monitored-system blocked payload.`linkedContainerId`, so settings consumers can keep the top connectionsledger scoped to top-level infrastructure without re-deriving guest statusfrom names or local heuristics.-24. Keep AI settings payload continuity explicit on the shared `/api/settings/ai`+25. Keep AI settings payload continuity explicit on the shared `/api/settings/ai`surface: `internal/api/ai_handlers.go` and `internal/api/contract_test.go`must expose masked provider-auth state such as `ollama_username` and`ollama_password_set` without echoing raw stored secrets, and the samebackend contract must keep provider test routes bound to the selectedprovider's configured model instead of whichever other provider currentlyowns the default `model` field.+ Anthropic provider readiness on this shared settings payload is API-key+ backed only: legacy OAuth fields may be echoed as cleanup state, but they+ must not count toward `configured`, `anthropic_configured`,+ `configured_providers`, model listing, provider tests, or runtime provider+ construction. `/api/ai/oauth/start` and `/api/ai/oauth/exchange` fail closed+ with `unsupported_anthropic_oauth`, `/api/ai/oauth/callback` must not save+ tokens, and `/api/ai/oauth/disconnect` may clear stored legacy tokens.The Ollama provider payload also owns `ollama_keep_alive` as the canonicalrequest keep-alive field: GET and update responses must expose thenormalized configured value, update requests must reject malformed values,@@ -2039,7 +2814,7 @@ the canonical monitored-system blocked payload.closed before any agent command dispatch. The API progress payload mustdescribe discovery evidence analysis rather than presenting background workas a visible Pulse Assistant chat session.-25. Keep shared AI runtime reads centralized on that same governed contract:+26. Keep shared AI runtime reads centralized on that same governed contract:`frontend-modern/src/stores/aiRuntimeState.ts` is the canonical frontendread owner for `/api/settings/ai` and `/api/ai/models`. AI-owned consumerssuch as `frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts`,@@ -2059,7 +2834,7 @@ the canonical monitored-system blocked payload.live provider catalog reads fail, so Patrol and Assistant model selectorskeep saved `deepseek:` selections visible without inventing page-localcatalog entries or falling back to another provider's model.-26. Keep API-backed first-target onboarding canonical on that same shared+27. Keep API-backed first-target onboarding canonical on that same sharedinfrastructure-settings boundary:`frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`,`frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`,@@ -2077,7 +2852,7 @@ the canonical monitored-system blocked payload.normalize the browser back to `/settings/infrastructure`, but first-runcallers must not fall back to the retired `/settings/infrastructure/install`or `/settings/infrastructure/platforms` deep links.-27. Keep the shared agent-download fallback transport pinned to published+28. Keep the shared agent-download fallback transport pinned to publishedrelease lineage. The served install-script endpoints (/install.sh,/install.ps1) have no GitHub fallback at all (see item 8); they serve thelocally bundled agent installer or fail closed. The remaining GitHub fallback@@ -2087,7 +2862,7 @@ the canonical monitored-system blocked payload.prereleases such as `v6.0.0-dev`, git-described `+git...` builds, and otherunpublished prerelease identifiers must fail closed on that API boundaryinstead of generating fake release URLs from a local runtime version string.-28. Keep local trial-start transport retired from self-hosted v6 GA runtime+29. Keep local trial-start transport retired from self-hosted v6 GA runtimepaths. `POST /api/license/trial/start` must not be registered as an ordinaryin-app acquisition endpoint; browser API clients, route inventory, demomode, and feature gates must all treat it as absent. The retired@@ -2099,7 +2874,7 @@ the canonical monitored-system blocked payload.but ordinary self-hosted responses leave eligibility false and the reasonempty; active trial state is represented by `subscription_state`,`trial_expires_at`, and `trial_days_remaining` only.-29. Keep `/api/security/dev/reset-first-run` transport-backed and genuinely+30. Keep `/api/security/dev/reset-first-run` transport-backed and genuinelyunauthenticated: when the dev reset route clears first-run auth it mustalso clear any env-backed auth state that feeds `/api/security/status`, sothe status payload flips `hasAuthentication` to `false`, preserves@@ -2108,12 +2883,12 @@ the canonical monitored-system blocked payload.already-authenticated app state. That recovery transport may expose thebootstrap token file path, but it must not emit the token value intoautomatic runtime logs.-30. Keep shared SSO test and metadata-preview transport fail-closed: SAML+31. Keep shared SSO test and metadata-preview transport fail-closed: SAMLmetadata URLs and OIDC issuer URLs must reject non-HTTP or userinfo-bearinginputs before any outbound request is attempted, and OIDC discovery mustappend `/.well-known/openid-configuration` beneath the configured issuerbase path instead of resetting to the origin root.-31. Keep config-archive import reloads fail-closed on the shared API/runtime+32. Keep config-archive import reloads fail-closed on the shared API/runtimeboundary. `internal/api/config_export_import_handlers.go`,`internal/api/contract_test.go`, and adjacent config/runtime helpers musttolerate absent notification managers and other optional runtime managers@@ -2123,6 +2898,24 @@ the canonical monitored-system blocked payload.## Current State+Manifest-backed Patrol finding lifecycle schemas are the API source of truth+for Assistant provider-tool optionality as well as MCP/API discovery. Legacy+Assistant runtime paths may project those schemas into provider-tool JSON, but+they must not re-require optional lifecycle fields such as `resolution_note` or+dismissal `note` after `/api/agent/capabilities` and the Patrol lifecycle API+declare them optional.+Legacy native Assistant utility provider aliases for `run_command`, `fetch_url`,+and `set_resource_url`, plus their provider JSON schemas, are part of the same+shared API/runtime contract through+`agentcapabilities.LegacyAssistantUtilityProviderTools`. The older native+Assistant service may keep exposing those compatibility aliases, but it must not+own separate inline provider schema maps or local tool-input argument strings+while the registry-backed execution path continues to converge.+Native Assistant registry tools that expose Patrol finding lifecycle actions+must use the same `agentcapabilities` argument constants for `finding_id`,+`resolution_note`, `reason`, and `note`, so provider tool schemas, execution+maps, `/api/agent/capabilities`, and MCP projections stay on one API vocabulary.+That same shared API boundary now also owns the default-org token scopingrule and instance-wide notification settings propagation. A token explicitlybound to one or more organizations is scoped to those organizations only and@@ -2207,7 +3000,7 @@ investigation runtime in `internal/ai/patrol_findings.go` attachesthe projection to the Finding before calling the orchestrator. Thisis the one in-process write path that decides what the orchestratorsees about operator commitments; all consumers (in-process Patrol,-external Claude Code, future MCP) read the same enriched shape.+external Claude Code, and MCP-speaking clients) read the same enriched shape.`/api/agent/events` is the agent SSE stream — the substrate piecethat closes the agent-paradigm triangle (discovery + bundled reads +@@ -2249,9 +3042,13 @@ approval store's post-create callback, the executor'spost-completion callback, and the API action-execution terminalpublisher) cannot stall on consumer slowness. Thestream sits behind `monitoring:read` and runs through the same auth-path as the rest of the agent surface; the capabilities manifest declares the stream+path as the rest of the external-agent surface; the capabilities manifest declares the streamunder `subscribe_events` so external agents discover it withoutout-of-band documentation.+The stable event kind strings and the stream-local transport markers are owned+by `internal/agentcapabilities/events.go`; API constants may expose typed+aliases, but API handlers, manifest descriptions, MCP adapters, and probes must+not re-declare the vocabulary independently.The approval store exposes `SetOnApprovalCreated(cb)` so the APIlayer can install a fire-and-forget callback that runs after every@@ -2292,31 +3089,127 @@ refusal-token prefixes (`plan_drift:`, `action_plan_expired:`,`errorMessage` verbatim so agents branch on the stable codewithout parsing human messages.-`/api/agent/capabilities` is the discovery document for Pulse's-agent surface. The manifest declares each agent-consumable+`/api/agent/capabilities` is the discovery document for Pulse+Intelligence's external-agent surface. The manifest declares each+agent-consumablecapability with stable name (snake_case agent identifier),description, category (`context` / `provisioning` /`operator-state` / `finding` / `action`), HTTP method + path,-required auth scope, response shape name, optional JSON Schema-`inputSchema`, and the closed set of stable error codes the-response may carry. Agents 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,+required auth scope, action mode (`read`, `mixed`, `write`),+approval policy (`scope_only`, `action_plan`), response shape name,+optional JSON Schema `inputSchema`, and the closed set of stable+error codes the response may carry. Agents fetch this once at startup+to learn what's available; the `cmd/pulse-mcp` adapter reads the+manifest's Pulse MCP `surfaceToolContracts` entry to register MCP tools, and+any future adapter (HTTP-API SDK, Claude-Code custom toolkit, etc.) reads the+same manifest surface contract the same way:+manifest-driven projection is the substrate's deliberate single source+of truth for "what can an agent do here?". The canonical manifest declaration,+manifest wire type, registry tool-name vocabulary, external tool projection+helpers, typed capability lookup error, request/response capability resolver, call route/body+projection helpers, path-parameter substitution helpers, JSON Schema+object-envelope helpers, manifest HTTP fetch, authenticated agent request+builder, capability HTTP executor, named capability HTTP executor,+named request/response capability HTTP executor, shared MCP+request decoder, line-delimited request serving, notification response policy,+stable JSON-RPC encoding, manifest-backed tool server,+surface-tool contract lookup, surface-filtered tool projection and execution,+tool-server method dispatcher,+initialize-result builder, MCP resource URI projection, context-backed+resources/list and resources/read projection, stable error-envelope formatter,+MCP tool-result text/marker interpreter, provider tool-result constructor and+context projection,+approved-action argument handling for replayed tool execution, internal+tool-argument filtering before public body projection, SSE record parser,+SSE-to-MCP notification bridge, shared tool-governance defaulting, and+disabled-control guidance live in+`internal/agentcapabilities` and are consumed by Assistant tool governance, the+API, `cmd/pulse-mcp`, and the in-repo `cmd/agent-probe` reference client; new+Pulse-native or external agent surfaces must reuse that contract instead of+defining local manifest structs, local tool-description builders, local+request/response filters, local argument-to-body shapers, local path+placeholder parsers, local `/api/agent/capabilities` fetchers, local API-token+header spelling, local named capability execution, local MCP initialize-result+builders, local MCP manifest-backed tool handlers, local MCP request decoding,+local MCP line-framing loops, local JSON-RPC encoders, local MCP notification+response checks, local MCP method dispatch, local MCP+result interpretation, local provider tool-result struct assembly, local+request/response capability body readers, local non-2xx error formatting,+local MCP resource URI builders, local resources/list or resources/read+projectors, local SSE scanners, local SSE-to-MCP notification bridges, local+tool-governance defaulting, local approved-action argument keys, local+disabled-control guidance, or local schema wrappers. Native Assistant registry+declarations must also reuse that API identity contract: every registry+`Tool.Definition.Name`, including `pulse_summarize` and Patrol runtime tools,+must come from `internal/agentcapabilities/tool_names.go` so MCP and future+external-agent adapters project the same tool identities that Assistant+executes. The manifest-backed MCP+tool server must receive the whole manifest and derive its surface-specific+tool projection, execution allowlist, and initialize surface-contract+instructions from that single value; adapters must not pass only a capability+slice and then maintain a parallel surface relationship beside it. The manifest itself is unauthenticated+and cacheable (`Cache-Control: public,max-age=300`) — declared in the router's `publicPaths` list sothe global auth middleware does not gate it; the underlyingcapabilities keep their own auth scopes. The manifest's`unauthenticated` posture is the chicken-and-egg fix: an agentthat does not yet have a token must still be able to introspectPulse to learn how to ask for one. Adding a capability is a-deliberate "this is part of the agent surface" commitment — the+deliberate "this is part of the external-agent surface" commitment — themanifest is hand-authored rather than auto-generated so contractdecisions (which capabilities are agent-stable, what the stable-error codes are, what category each belongs to) cannot drift-behind code changes.+error codes are, what category and governance posture each belongs to) cannot+drift behind code changes. Capability `scope` values are not part of that+hand-authored vocabulary: they must come from `pkg/auth` via manifest-local+aliases, matching the constants API authorization uses, rather than literal+strings that can drift from the enforced route scopes.+Every manifest capability's method, path, and advertised scope must also be+proved against the live router by projecting a concrete request through+`agentcapabilities.ProjectCapabilityCall` and requiring a wrong-scope API token+to fail with the manifest's advertised missing scope. The proof is intentionally+router-owned rather than table-owned: manifest placeholder names may stay+agent-facing, but the concrete projected route must reach the API boundary that+enforces the same scope.+API-owned Pulse Assistant dependency seams must also keep MCP as an adapter+boundary, not an internal name for the native Assistant runtime. `AIService`+provider setter types, AI handler pass-throughs, router chat dependency wiring,+AI settings control-refresh callbacks, direct approved-tool replay into chat, and the native tool adapter family must+use Assistant/Pulse Intelligence terminology, while `MCP` remains valid only+for the external adapter, shared MCP wire/result contracts, and explicitly+deprecated API compatibility aliases. The cross-repo auto-fix dependency shape must+publish `ApprovedAssistantToolExecutor` / `AssistantToolExecutor` as the native+approved-tool execution contract. Callers must use+`AIAutoFixHandlerDeps.ResolveApprovedAssistantToolExecutor`, and that resolver+returns only the native Assistant executor; MCP-named executor compatibility is+not part of this boundary. Current public API relay wiring must populate only+`AssistantToolExecutor`.+API-visible Assistant runtime readiness and lifecycle messages must name the+first-party surface as Pulse Assistant rather than the legacy generic `Pulse AI`+runtime.+API-visible shared Intelligence messages such as profile-suggestion+unavailability, AI settings persistence failures, Patrol preflight copy, and+remediation-impact logs must not narrow the shared Assistant/Patrol substrate+back to `Pulse Assistant settings` or generic `Pulse AI`; they must use Pulse+Intelligence for shared runtime availability and Provider & Models for the+shared provider/model settings surface.+Patrol finding capability scopes are API-authorization-owned, not+adapter-owned. `list_findings`, `acknowledge_finding`, `snooze_finding`, and+`dismiss_finding` must match the relay/mobile runtime route inventory, and+`resolve_finding` must match the direct `POST /api/ai/patrol/resolve` route.+Those Patrol finding review and lifecycle routes are gated by `ai:execute`, so+the manifest and MCP projection must not advertise monitoring scopes for them+while the router enforces AI execution authorization.+Capabilities that replace operator-state, mutate Patrol finding lifecycle, or+participate in the action plan/decision/execute loop must publish typed+`inputSchema` definitions for their exact top-level tool arguments, including+path parameters such as `resourceId` / `actionId`, full-replacement flags such+as `intentionallyOffline` / `neverAutoRemediate`, and stable enums such as+criticality, dismissal reasons, or approval outcomes. External adapters may+project those schemas directly, but must not replace them with adapter-local+body wrappers or prose-only argument hints. Shared manifest schemas use the+shared strict object envelope; adapter fallback schemas use the same helper with+explicitly permissive additional properties when the endpoint contract is only+partially known.Infrastructure onboarding is part of that same manifest contract,not an MCP-only shim. The provisioning category projects the@@ -2330,7 +3223,7 @@ sources returns redacted credential state only; token or passwordsecret values may be accepted on write/test requests but must notcome back through `list_nodes` or any manifest metadata.-The agent surface uses one error-envelope shape across every+The external-agent surface uses one error-envelope shape across everyendpoint — `{"error": "<stable_code>", "message": "<human>","details"?: {"<field>": "<reason>"}}` — written via`writeJSONError` (no details) or `writeJSONErrorWithDetails`@@ -2340,6 +3233,15 @@ human-readable text agents can surface to operators withoutlosing the code; the optional `details` map carries field-levelfailure reasons on validation errors so agents do not parsehuman text to identify which field went wrong.+The envelope type, constructor, and parser live in+`internal/agentcapabilities/errors.go`; API handlers emit that shared type and+external-agent clients/probes parse it there instead of carrying local envelope+structs.+The same file owns the `AgentErrCode*` constants for every+capability-specific agent error code. The canonical manifest and the+agent-surface handlers must reference those constants rather than duplicate+string literals, so Assistant, MCP clients, probes, and API handlers share one+branching vocabulary.There are two layers of stable codes. First, **capability-specificcodes** are declared per capability in the manifest's `errorCodes`@@ -2347,7 +3249,12 @@ list and represent the closed set of failure modes thatcapability'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`).+`operator_state_invalid` (`set_operator_state`);+`invalid_finding_request`, `finding_not_found`,+`finding_action_not_allowed`, and `patrol_unavailable`+(`acknowledge_finding`, `snooze_finding`, `dismiss_finding`,+`resolve_finding`); and the action-governance codes declared on+`plan_action`, `decide_action`, and `execute_action`.Adding or renaming one requires both the handler emission and themanifest declaration to move together — drift between them is acontract regression. Second, **cross-cutting codes** apply to@@ -2360,10 +3267,11 @@ request. Agents must accept these alongside any capability'sdeclared codes; the manifest deliberately does not duplicate themon every entry.-The agent substrate is end-to-end exercised by two paired tests in+The external-agent substrate is end-to-end exercised by two paired tests in`internal/api/agent_substrate_e2e_test.go`. The first test bootsthe full router stack and walks discovery → triage → depth: fetch-the manifest unauthenticated, call `/api/agent/fleet-context`+the manifest unauthenticated, call `/api/agent/patrol-control/status`+authenticated, call `/api/agent/fleet-context`authenticated, drill into `/api/agent/resource-context/{id}`, andconfirm the SSE stream path is gated rather than absent. Thesecond test walks the operator-state intent loop end-to-end:@@ -2373,58 +3281,148 @@ manifest's declared error codes (`operator_state_not_set`,`operator_state_invalid`) reach the wire under the canonical`error` key and that the URL canonical id wins over anybody-supplied id (preventing scope-confusion writes). Together-the two tests are the substantive proof for the agent surface —+the two tests are the substantive proof for the external-agent surface —read, write, push — as one substrate.The companion worked example lives at `cmd/agent-probe/main.go` —a small standalone Go program that walks the same discovery →triage → depth → push flow against a running Pulse instance.-The probe depends only on the standard library so it doubles as-a reference implementation: anyone building MCP servers, Claude-Code integrations, or custom agents on top of Pulse can read it-top-to-bottom to see how the substrate fits together. The probe-resolves paths from the manifest rather than hardcoding them, so-discovery moves automatically follow.+The probe avoids API handler and AI-runtime imports; it reuses only the tiny+`internal/agentcapabilities` wire/projection/HTTP contract so the in-repo+reference client cannot drift from the manifest shape, named capability HTTP+execution rule, request/response body-return helper, path projection+semantics, API-token header convention, or stable error envelope behavior; it+also consumes the shared SSE subscription+transport, record parser, and actionable-record filter so the push walkthrough+uses the same event-stream request, status, framing, and transport-event+filtering rules as the MCP bridge. External agents can define the same JSON shape from the+manifest or a generated client. Anyone building MCP servers, Claude Code+integrations, or custom agents on top of Pulse can read it top-to-bottom to see+how the substrate fits together. The probe resolves capabilities and paths from+the manifest rather than hardcoding them, so discovery moves automatically+follow.A second adapter lives at `cmd/pulse-mcp/main.go` — a minimal-MCP (Model Context Protocol) server that exposes the agent-substrate as MCP tools so Claude Desktop, Claude Code, and other-MCP-speaking clients can drive Pulse natively. The adapter is-the test for whether the substrate's contracts were really cheap-to project: each MCP tool is one entry in the hand-authored-manifest. When the manifest supplies an `inputSchema`, MCP must-use it verbatim; otherwise the adapter falls back to deriving a-minimal schema from path placeholders and method (path `{name}`-segments become required string properties; non-GET/DELETE tools-accept a `body` object). Adding a capability to the manifest-automatically extends the MCP tool surface without changes in the-adapter. `subscribe_events` is+MCP (Model Context Protocol) server that exposes Pulse Intelligence's+external-agent substrate as MCP tools so Claude Desktop, Claude Code,+OpenCode, and other MCP-speaking clients can drive Pulse+natively. The adapter is the test for whether the substrate's contracts+were really cheap to project: each MCP tool is a manifest capability allowed+by the manifest-owned Pulse MCP surface tool contract. `cmd/pulse-mcp` must use the shared+`internal/agentcapabilities` projection helpers for the complete+surface-filtered request/response tool-list projection, tools/call params+decode, surface-filtered capability lookup translation, initialize-result+construction through the target surface affordance contract, manifest fetch, neutral+capability tool HTTP execution (including path placeholder substitution,+argument-to-route/body projection, agent request construction, and capability+HTTP dispatch), MCP JSON-RPC request decoding, notification response policy,+manifest-backed MCP tool-server handlers, MCP JSON-RPC method dispatch, MCP+result wrapping, MCP resource URI projection, context-backed `resources/list`+and `resources/read` projection through `get_fleet_context` and+`get_resource_context`, shared result text projection at execution sites,+shared result text/marker interpretation, and the shared SSE-to-MCP notification+bridge. When the manifest supplies an `inputSchema`, the shared helper forwards+it verbatim; otherwise it derives a minimal fallback from path placeholders and+method (path `{name}` segments become required string properties;+non-GET/DELETE tools accept a `body` object). Adding a request/response+capability to the manifest-owned Pulse MCP surface tool contract automatically+extends the MCP tool surface without changes in the adapter. Adding a raw+manifest capability without adding it to that surface contract must not alter+MCP `tools/list` or `tools/call`. Pulse Assistant remains the first-party+in-app surface over the same+governed contracts; MCP is the external-agent adapter and must not grow a+parallel action pipeline.+MCP resource browsing follows that same rule: the adapter may advertise+resources when the target surface affordance allows resources and the manifest+carries the canonical context capabilities, but `resources/list` is only a+fleet-context projection and `resources/read` is only a resource-context+projection. Resource projection must enter through+`ManifestSurfaceResourceCapabilities`,+`ListMCPManifestSurfaceResourcesHTTP`, and+`ReadMCPManifestSurfaceResourceHTTP`; raw-capability resource helpers must not+define a second MCP resource surface. Prompt advertising and `prompts/get`+follow the same surface affordance gate before the shared workflow-prompt+catalogue is projected; initialize and `prompts/list` must use+`MCPManifestSurfacePromptProjectionSupported`, and `prompts/get` must use+`GetMCPPromptFromManifestSurface`, so disabled prompt affordances cannot be+re-enabled by raw workflow prompt presence.+The global `pulse_operations_loop` prompt is a Patrol work API manifest contract as much+as an Assistant starter: it is advertised only when the manifest includes fleet+operations-loop status, fleet context, resource context, finding list, action+planning, action decision, action execution, and finding resolution+capabilities. Its rendered instructions+must keep external agents on the same governed Patrol work flow as Pulse+Assistant by explaining Patrol evidence in context, planning first, asking for+approval or rejection only when the returned policy requires a decision,+executing when policy allows, re-reading Patrol status, context, and findings+for verification, and resolving the finding only after the outcome has been checked.+Resource URIs use the shared `pulse://resource/<resource-id>` shape and must+not become an adapter-local resource registry.+`subscribe_events` isintentionally excluded — SSE streaming doesn't fit therequest/response tool shape; agents that need real-time pushconsume the SSE stream directly. The adapter speaks JSON-RPC 2.0over stdio with line-delimited framing, and preserves thesubstrate's stable error envelope (`{"error": "code", "message":-"..."}`) verbatim through MCP's content-and-isError result so-agents on the MCP side branch on the same stable codes.+"..."}`) verbatim through the shared `HTTPCallResponse` to MCP+content-and-isError result helper so agents on the MCP side branch on the same+stable codes without the adapter reinterpreting response bodies or statuses.Optionally, with `--emit-notifications`, the adapter also-subscribes to `/api/agent/events` and translates each-non-transport SSE event into a JSON-RPC notification on stdout+uses the shared initialize-result builder to advertise+`experimental.pulseNotifications.kinds`, then uses the shared event bridge to+subscribe to `/api/agent/events` and write each non-transport SSE event as a+JSON-RPC notification on stdout(`notifications/finding.created`, `notifications/approval.pending`,`notifications/action.completed`); the notification's `params` isthe SSE `data` payload verbatim so MCP-bound autonomous agentsreact to pushes without holding a separate HTTP connection. Theflag is off by default because not every MCP client surfacesserver-initiated notifications; transport plumbing-(`stream.connected`, `heartbeat`) is filtered.+(`stream.connected`, `heartbeat`) is filtered through the shared+agent-capabilities event vocabulary.The integration guide for `cmd/pulse-mcp` lives at-`cmd/pulse-mcp/README.md`. It carries the canonical Claude Desktop-and Claude Code config snippets, the env-var contract for the API-token, the published list of tools the manifest currently-exposes, and the documented limitations (no `subscribe_events`,-manifest fetched once at startup). External maintainers wiring+`cmd/pulse-mcp/README.md`. It carries the canonical reusable MCP runtime facts,+OpenCode's native top-level `mcp` config shape for `opencode.json` /+`opencode.jsonc`, the common `mcpServers` block for Claude-style clients, the+env-var contract for the API token, manifest-derived generated scope,+surface-filtered request/response tool, workflow prompt, and stable error-code inventories, the+context-backed MCP resource browsing behavior, and the documented limitations+(`subscribe_events` is not a callable tool; manifest fetched once at startup).+`scripts/generate-pulse-intelligence-docs.go` owns the generated public+overview and README scope/tool/prompt/error-code blocks and must use+`internal/agentcapabilities` projections rather than a second catalogue. README+tool and capability-specific error-code blocks must use the same manifest-owned+Pulse MCP surface contract as runtime `tools/list` and `tools/call`.+Manifest-owned capability titles, workflow prompt definitions,+manifest-owned `workflowPrompts` catalogue selection, MCP tool/prompt title+projection, presentation kind hints, Patrol work availability gating, and+prompt argument validation are owned by the neutral+`ManifestPulseWorkflowPrompts` / `ProjectPulseWorkflowPrompts` /+`BuildPulseWorkflowPromptFromManifest` contract; MCP keeps only protocol wire+projection and surface-specific resource URI hints.+documentation-local capability table. External maintainers wiringPulse into their MCP-speaking client read that document, not thepackage source.+`docs/AGENT_SUBSTRATE.md` is the current high-level operator and integrator+summary for the same substrate. It must reflect the in-app+`Settings -> API Access -> Agent integrations` surface, both the OpenCode+native `opencode.json` / `mcp` shape and the common `mcpServers` block, and the+published `install-mcp.sh` / `install-mcp.ps1` release path; it must not+preserve old gap copy claiming there is no Pulse settings surface, no config+snippet, or no `pulse-mcp` distribution path.+`docs/releases/AGENT_PARADIGM.md` is the release-facing projection of the same+contract. It must frame `cmd/pulse-mcp` as a generic MCP adapter for+MCP-speaking clients, include OpenCode-native `mcp` setup alongside the common+`mcpServers` shape, and point full surface token guidance at the manifest-owned+`requiredScopes` list rather than hand-maintained partial scope examples.+The public `/api/agent/capabilities` manifest must also expose+`requiredScopes`, the canonical deduplicated scope list derived from its+declared capabilities through `internal/agentcapabilities.RequiredCapabilityScopes`.+Browser settings surfaces, `cmd/pulse-mcp` startup errors, MCP documentation,+probes, and future clients must consume that manifest-owned list for+full-surface token guidance instead of rebuilding a scope list from local+hardcoded assumptions.`/api/agent/resource-context/{id}` is the agent-consumable bundledcontext endpoint. One read returns the full situated picture of a@@ -2577,13 +3575,15 @@ that the frontend has historically called (zero current frontendconsumers, verified) now back the manifest entries; thesubstrate's "manifest projection is cheap" promise has adocumented footnote that bringing an existing endpoint into the-agent surface may require migrating its error envelope from the+external-agent surface may require migrating its error envelope from theplatform-wide `APIError` shape to the agent-stable shape. That-migration was the slice 58 work for these three handlers; future-agent-surface additions on existing endpoints will pay the same-cost. The trade-off is intentional: the agent surface keeps a-single envelope contract rather than carrying a wrapper layer to-translate per capability.+migration now covers the action governance handlers and the Patrol+finding lifecycle handlers (`acknowledge_finding`, `snooze_finding`,+`dismiss_finding`, `resolve_finding`). Future external-agent additions+on existing endpoints will pay the same cost. The trade-off is+intentional: the external-agent surface keeps a single envelope+contract rather than carrying a wrapper layer to translate per+capability.Deploy-job monitored-system volume denials are retired. API routes may stillaccept historical payloads that mention old license-slot terminology for@@ -2628,9 +3628,145 @@ published-release truth from raw build strings.That same preview contract now includes the complete anonymous telemetrypayload shape, including aggregate self-hosted adoption counters for monitoredplatforms, workloads, storage, and availability targets plus coarse feature-booleans. Browser callers may display or copy the exact payload, but they must-not derive hostnames, infrastructure identifiers, prompt/chat content, license-tiers, or API-token counts from it.+booleans and content-free Patrol, Assistant, and external-agent usage counters.+The frontend `TelemetryPingPreview` type in+`frontend-modern/src/api/settings.ts` must mirror every browser-visible JSON+field from `internal/telemetry.Ping`, including the resolved operations-loop,+approved-execution, first-party Assistant, external-agent, and Pulse MCP adapter+variants used by Pro value reporting, plus source-specific operations-loop+starter request counts including the Pro activation entry point.+Those Pulse Intelligence fields may describe only configured/active/governed-action+adoption state plus Assistant, Patrol detection, Patrol investigation, Patrol+resolution, aggregate external-agent use, adapter-origin MCP use, approval,+and governed-action counts inside the+rotating telemetry window. Browser callers+may display or copy the exact payload, but they must not derive hostnames,+infrastructure identifiers, prompt/chat content, command text, action output,+license tiers, token values, token counts, resource IDs, finding IDs, or+approval identities from it.+Approved action decision telemetry is part of that same anonymous API+contract: `pulse_intelligence_approved_action_decisions_30d` must count+distinct action IDs with approved-decision lifecycle evidence in the telemetry+window, or approval records whose approved decision timestamp is inside the+window for older rows that lack lifecycle events. It may count toward completed+operations-loop proof, but it must not be conflated with approved execution+attempts or approved action successes, and it must never expose action IDs,+actors, reasons, resource IDs, command text, action output, or verification+detail.+Approved execution attempt telemetry is part of that same anonymous API+contract: `pulse_intelligence_approved_action_attempts_30d` must be counted as+distinct action IDs with execution-attempt lifecycle evidence (`executing`,+`completed`, or `failed`) resolved back to an approved action audit, with final+audit-state fallback only for older rows that lack lifecycle events. It must+not be derived from generic action-plan, approval-request, token-use, Assistant+chat, or MCP call counts, and it must never expose action IDs, actors, reasons,+resource IDs, command text, or action output.+Approved action success telemetry is the stricter completion proof in that same+contract: `pulse_intelligence_approved_action_successes_30d` must count only+distinct approved action audits that reached completed state successfully, with+lifecycle-backed attribution where lifecycle evidence exists and final+audit-state fallback only for older rows. Failed or refused approved actions may+count as attempts but must not count as successes, and the success counter must+not expose action IDs, actors, reasons, resource IDs, command text, verification+detail, or action output.+Rejected action decision telemetry is the declined-governance proof in that same+contract: `pulse_intelligence_rejected_action_decisions_30d` must count distinct+action IDs with rejection-decision lifecycle evidence in the telemetry window,+with final rejected audit-state fallback only for older rows that lack lifecycle+events. It may count toward governed-action activity, but it must not count as+an approved execution attempt, approved success, or resolved operations loop+proof, and it must never expose action IDs, actors, reasons, resource IDs,+command text, or action output.+Completed operations-loop telemetry is the coarse approve/reject journey proof+in that same contract. `pulse_intelligence_complete_operations_loop_30d` and+the source-specific operations-loop booleans may be true only when the same+rotating telemetry window contains Patrol issue evidence, contextual+Assistant/MCP/external-agent collaboration, and either a rejected action+decision, an approved action decision, or approved execution-attempt evidence.+Generic Patrol runs, Patrol AI calls, action plans, and approval requests may+activate or reach the loop, but they must not complete it without issue-backed+Patrol evidence and a real decision/outcome signal.+Patrol resolution telemetry is the content-free outcome proof in that same+contract. `pulse_intelligence_patrol_resolved_findings_30d` may count only+findings whose own lifecycle reached resolved state in the telemetry window, or+findings whose investigation outcome reached `resolved` or `fix_verified` with+investigation completion evidence in that window. It must not count generic+Patrol runs, new findings, model calls, action approvals, or successful actions+without a resolved/fix-verified Patrol finding outcome, and it must never expose+finding IDs, resource IDs, finding text, remediation details, verification+detail, actors, command text, or action output.+Resolved operations loop telemetry is a derived content-free boolean:+`pulse_intelligence_resolved_operations_loop_30d` may be true only when the+same telemetry window contains Patrol resolution plus Assistant governed-context+or governed-tool collaboration or MCP/external-agent collaboration, and at+least one approved action success. In this contract, approved action success is+the shared verified-outcome predicate used by the operations-loop status route:+the approved action must have `VerificationOutcome.Status=verified` or a+canonical verification result that ran and succeeded. A bare successful+execution result is not sufficient. It is co-occurrence proof for value+reporting, not causality proof, and it must not carry any identifiers, prompts,+tool names, command payloads, action outputs, or finding text.+Patrol control completed-loop telemetry is the primary derived content-free+paid-value boolean:+`pulse_intelligence_patrol_control_completed_operations_loop_30d` may be true+only when the same telemetry window contains Patrol control starter evidence+from `pulse_patrol`, `patrol_control`, legacy `patrol_autonomy`, or legacy+`pulse_pro_activation`, Patrol issue evidence, contextual Assistant or+MCP/external-agent collaboration, and either a rejected governed decision or an+approved governed decision with verified outcome proof. It is terminal-loop+Patrol control proof, not causality proof, and it must not carry+checkout/account identity, token identity, prompt content, resource IDs,+finding IDs, action IDs, command payloads, action outputs, or verification+detail.+Patrol control resolved-loop telemetry is stricter:+`pulse_intelligence_patrol_control_resolved_operations_loop_30d` may be true+only when the same content-free window also contains an approved governed+decision and verified outcome proof. It must not treat rejected decisions as+resolved-loop proof. These telemetry booleans must use the same+`internal/telemetry.ClassifyPulseIntelligencePatrolControlProof` count-only+classifier as `GET /api/agent/patrol-control/status`, so native status, MCP+status consumers, telemetry preview, and outbound telemetry cannot diverge on+what completed, resolved, or governed-decision proof means. Legacy+`pulse_intelligence_pro_activation_completed_operations_loop_30d` and+`pulse_intelligence_pro_activation_resolved_operations_loop_30d` are+compatibility mirrors of those primary Patrol control booleans.+Paid Patrol control telemetry is a derived content-free cohort:+`pulse_intelligence_patrol_control_paid_completed_operations_loop_30d` may be+true only when the same payload also reports `paid_license=true` and+`pulse_intelligence_patrol_control_completed_operations_loop_30d=true`.+`pulse_intelligence_patrol_control_paid_resolved_operations_loop_30d` may be+true only when the same payload also reports `paid_license=true` and+`pulse_intelligence_patrol_control_resolved_operations_loop_30d=true`. Legacy+`pulse_intelligence_pro_activation_paid_completed_operations_loop_30d` and+`pulse_intelligence_pro_activation_paid_resolved_operations_loop_30d` mirror+those primary paid Patrol-control fields for cohort continuity. These fields+are paid-cohort proof for aggregate activation, retention, and free-to-paid+comparison, not causality proof; they must not carry exact plan tier,+checkout/account identity, license IDs, token identity, prompts, resources,+findings, action IDs, command payloads, action outputs, or verification detail.+External-agent recent-use telemetry is a content-free capability-activity marker+for authenticated calls into the agent/MCP contract. Every request/response+capability published through the Pulse MCP surface must map to one coarse+activity class before the route handler runs, and the marker must require the+called capability's manifest-declared scope rather than the entire manifest+scope set. Read-only external agents using `monitoring:read` must therefore+count for context/event-stream activity without being treated as action,+settings, or approval-capable callers. Generic API token last-use timestamps+are not canonical proof that the external-agent surface was used.+The `pulse-mcp` adapter may stamp the content-free+`X-Pulse-Agent-Surface: pulse_mcp` header on those same capability requests so+the telemetry snapshot can expose adapter-specific recent use while keeping the+aggregate external-agent recent-use bit valid for both direct HTTP agents and+the adapter. Route handlers must normalize unknown or absent surface markers+back to direct `agent_api` use and must never persist client identity, prompts,+request bodies, route parameters, or local resource identifiers as part of the+surface marker.+Pulse MCP `prompts/get` starter activity uses the same surface marker but a+separate route-specific payload: `POST /api/agent/workflow-prompt-activity`+records only the manifest prompt name after successful local prompt rendering.+It does not count as a capability-class request and must not infer+external-agent contextual collaboration or action execution from prompt access+alone.That same browser-transport contract now tolerates sparse previewpayloads without changing the runtime truth. Patrol transport may omit`finding_ids`, and infrastructure removal previews may stage optimistic rows@@ -3512,7 +4648,7 @@ projection layer instead of by handler-local heuristics. It must not return anenforced-limit verdict or make persistence depend on a commercial volumedecision.Configured Proxmox, PBS, and PMG update handlers in-internal/api/config_node_handlers.go may use that same structured+internal/api/config*node_handlers.go may use that same structuredreplacement-selector contract when they explain monitored-system grouping:source-owned names, host URLs, hostnames, and resource identifiers may crossthe API boundary, but handler-local matcher closures must not become the@@ -3573,7 +4709,11 @@ shared access layer instead of routing directly to Patrol-local correlationstate.That store now also owns the Patrol page load bundle, so the page refresh pathstays aligned on one store-owned orchestration layer instead of re-encoding-the AI bundle inline.+the AI bundle inline. Frontend Patrol load orchestration must treat first-load+transport or settings failures as stale-data state rather than throwing through+the route: the page stays mounted, preserves any last-known Patrol evidence,+and exposes a retry affordance while backend/API failures remain available to+debug logging and API-level diagnostics.The AI summary page now also renders the canonical`frontend-modern/src/components/Infrastructure/ResourcePolicySummary.tsx`card for policy posture, so sensitivity, routing, and redaction counts are@@ -3769,7 +4909,10 @@ customer frontend state. `frontend-modern/scripts/settings-diagnostics-boundary-now checks `internal/api/diagnostics.go` alongside the Settings diagnosticsfrontend boundary through the canonical frontend audit runner, so thisadmin-analytics payload class cannot return as a customer-visible diagnostics-contract.+contract. The same diagnostics boundary also keeps the first-party Assistant+surface out of MCP transport vocabulary: `AIChatDiagnostic` may report native+Assistant runtime availability through `assistantRuntimeConnected`, but+`mcpConnected` and `mcpToolCount` must stay out of `/api/diagnostics`.That same admin-analytics boundary now retires the local commercial metricsroutes from the normal customer product API: `/api/upgrade-metrics/events`,`/api/upgrade-metrics/stats`, `/api/upgrade-metrics/health`,@@ -3796,7 +4939,7 @@ command-execution flags between display and clipboard transport.That same shared infrastructure-settings boundary now also consumes the canonical`connectedInfrastructure` projection from the backend state contract instead ofreconstructing reporting rows by merging raw unified-resource facets and-removed-_ arrays in the browser. v6 clients no longer receive those removed-_+removed-* arrays in the browser. v6 clients no longer receive those removed-\_arrays at all for this surface; Connected infrastructure rowidentity, reporting-surface labels, and ignore/reconnect scope must be ownedby the backend payload contract, with frontend rendering limited to@@ -4699,12 +5842,12 @@ handoff context as secondary to durable finding context, not a replacement forserver-refreshed approval, resource, action, or requester authority. Frontend Patrolhandoff helpers may consume current pendingapproval list payloads only as safe metadata for that visible briefing and any- structured `handoff_actions`: approval ID, status, risk, request/expiry- timestamps, target label, requester identity, action ID, approval policy,- plan expiry, and dry-run summary are allowed. Assessment-level visible- briefings may reuse that same safe metadata for factual action labels and safety notes,- while approval command text remains inside the governed approval/remediation- surface.+structured `handoff_actions`: approval ID, status, risk, request/expiry+timestamps, target label, requester identity, action ID, approval policy,+plan expiry, and dry-run summary are allowed. Assessment-level visible+briefings may reuse that same safe metadata for factual action labels and safety notes,+while approval command text remains inside the governed approval/remediation+surface.Patrol approval-row Assistant handoffs must use the same safe metadata boundaryand set `autonomousMode:false` for the request-local chat handoff; they must notpaste raw approval or action command text into a chat prompt.@@ -4739,6 +5882,11 @@ context. When a Patrol run records `error_count > 0`, the backend may include`frontend-modern/src/api/patrol.ts` must preserve those fields so the Patrol UIcan explain provider/model/tool runtime failures without scraping findingcopy or inferring meaning from a generic error status.+Frontend run-history presentation must derive the collapsed operator record+from the canonical run payload rather than from page-local telemetry strings:+runtime errors may read as `Patrol needs attention`, finding counts may read as+found/fixed/open/resolved work, and technical fields such as trigger reason,+tool-call count, tokens, and raw traces remain secondary forensic context.Patrol status payloads no longer carry quickstart credit state as an ordinaryv6 GA API contract. `quickstart_credits_remaining`,`quickstart_credits_total`, and `using_quickstart` are retired public fields;@@ -4763,7 +5911,9 @@ source preferences from effective runtime policy. `alert_triggers_enabled` and`event_triggers_blocked`, `event_triggers_blocked_reason`, and`event_triggers_blocked_message` describe a runtime policy pause such as thelocal development background-automation guard. Runtime policy must not make the-transport look like the operator turned alert or anomaly triggers off.+transport look like the operator turned alert or anomaly triggers off, and the+default Patrol UI must not treat a background-only policy pause as actionable+operator guidance unless it also explains why manual Patrol is blocked.Patrol mutate endpoints that depend on the background service must also failclosed with `503 Service Unavailable` when AI service initialization is absentrather than dereferencing a nil service and crashing before a contract response@@ -5316,7 +6466,9 @@ provider-scoped test selection. `internal/api/ai_handlers.go` and`ollama_username` and `ollama_password_set`, accept provider-auth updateswithout echoing raw secrets back into the payload, and keep provider testroutes bound to the provider's own configured model instead of whichever-other provider currently owns the default `model` selection.+other provider currently owns the default `model` selection. Legacy Anthropic+OAuth fields are cleanup-only compatibility state on that same contract and+must never revive an OAuth-backed Anthropic provider path.That same shared `/api/settings/ai` contract now also owns vendor-neutral BYOKsetup. Frontend callers may submit provider credentials or base URLs without aconcrete vendor model ID, and `internal/api/ai_handlers.go` must resolve and@@ -5422,12 +6574,14 @@ owners must not rely on that 402 as normal control flow for stale local state:when the current entitlement locks safe remediation, they submit `monitor` evenif older persisted settings or a previous entitlement left `approval`,`assisted`, or `full` in memory.-The Patrol header presentation for that API boundary must compose the shared-`frontend-modern/src/components/shared/FilterButtonGroup.tsx` segmented-selector: the endpoint contract still owns the accepted autonomy values and-license-required response shape, while the frontend owns only the option-mapping and entitlement-derived disabled state. Local Patrol selector styling-must not become a second source of truth for the API's monitor-only clamp.+The Patrol header and configuration-dialog presentation for that API boundary+must compose the shared+`frontend-modern/src/components/shared/FilterButtonGroup.tsx` selector: the+endpoint contract still owns the accepted autonomy values and license-required+response shape, while the frontend owns only the option mapping,+entitlement-derived disabled state, and layout choice needed to keep labels+readable in the current container. Local Patrol selector styling must not become+a second source of truth for the API's monitor-only clamp.The reporting transport contract now also carries an optional narrativeinterpretation layer alongside the deterministic data surface. The Go-side`pkg/reporting.MetricReportRequest` gains optional `Narrator` anddiff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.mdindex 5c4717f605..4246cfa4ca 100644--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md@@ -20,6 +20,69 @@ agreement, the Pulse Cloud control plane, provider-hosted MSP accountbootstrap/licensing, hosted tenant lifecycle, and cloud-specific enforcementrules.+Pulse Pro commercial Pulse Intelligence value reporting is a cloud-paid proof+surface. It must compare full-loop, approved-execution-loop, Assistant-loop,+Assistant-resolved-loop, external-agent-loop, external-agent-resolved-loop,+Patrol-resolution, resolved-operations-loop, Patrol-guided resolved-loop,+Patrol-control completed-loop, Patrol-control resolved-loop, paid Patrol-control+completed-loop, paid Patrol-control resolved-loop, legacy Pro activation+compatibility mirrors, MCP adapter+operations-loop, MCP adapter approved-execution-loop, MCP adapter+resolved-operations-loop, and+MCP/external-agent capability-class cohorts against the generic Assistant chat+baseline with activation, retention, paid-rate, free-start conversion, and+signal-to-paid deltas.+The Patrol-guided resolved-loop cohort is the first-party completion signal:+it requires the `pulse_patrol` operations-loop starter marker plus resolved+operations-loop proof, so Patrol starter interest is not mistaken for a+completed activation loop.+The Patrol-control completed-loop cohort is a first-class telemetry signal for+historical conversion and retention analysis. It requires the Patrol control+starter or its legacy Pro activation entry-point alias, Patrol issue evidence,+contextual Assistant or external-agent collaboration, and either a rejected+governed decision or an approved governed decision with verified outcome proof,+so a deliberate operator rejection can complete the decision loop without being+misreported as an approved-and-resolved outcome. Local self-hosted Pro+operations-status presentation must apply the same distinction through the+shared operations-loop `patrolControlValueState`, falling back to+`patrolAutonomyValueState` and then `proActivationValueProofState` only for+compatibility: `governed_decision_recorded` remains partial decision status+with a continue path, legacy `verified_needs_mcp` is treated as verified+first-party Patrol value with MCP readiness left as optional external-agent+context, and `verified` may be presented as a verified Patrol operations+outcome or suppress a new starter marker. Paid-plan status rows must describe+missing or partial Pro action entitlements as Patrol investigation/remediation+capability, not as generic `Pro operations capability`, so the commercial+surface tells users which governed Patrol behavior is affected.+The Patrol-control resolved-loop cohort is a first-class telemetry signal for+paid Patrol control value, not a report-time intersection of generic starter+interest and generic resolved-loop proof. Pulse emits it only when a Patrol+control or legacy Pro activation starter, Patrol issue evidence, contextual+Assistant or external-agent collaboration, an approved governed decision, and+verified outcome proof are present, and the license-server value report must+consume that explicit primary flag.+The paid Patrol-control completed-loop and resolved-loop cohorts are also+first-class telemetry signals. Pulse emits them only when the current coarse+`paid_license` posture coexists with the corresponding Patrol-control+completed-loop or resolved-loop proof in the same telemetry payload. Legacy Pro+activation completed/resolved and paid cohort fields may mirror those primary+Patrol-control values for continuity. The value report must use those explicit+booleans for paid-rate, retention, and free-to-paid comparisons, and must not+infer paid Patrol-control value from exact tiers, account links, checkout+sessions, license IDs, or a report-time join against customer identity.+Approved-execution-loop+metrics mean Patrol issue evidence plus Assistant governed-context, direct+external-agent, or MCP collaboration plus at least one approved governed-action+attempt; complete-loop metrics mean Patrol issue evidence plus contextual collaboration plus an+approved or rejected governed-action decision signal. Those metrics must remain+separate from broader governed-action activity so action plans and approval+requests are not mistaken for completed operations-loop proof. Capability-class signal-to-paid+metrics must use the first time that specific capability was observed while+the install was still free, then count conversion only when paid activation+happened after that capability signal; paid installs that first use a+capability after purchase must not be counted as capability-driven conversion+proof.+Provider-hosted MSP bootstrap output is part of the cloud-paid operatorcontract. It must carry the resolved MSP plan version, plan source, workspacelimit, and validated provider MSP license id/email so installability proof can@@ -88,7 +151,7 @@ Stripe-free and avoids a cloud-control-plane report data path across clients.27. `internal/cloudcp/entitlements/service.go`28. `internal/cloudcp/portal/handlers.go`29. `internal/cloudcp/portal/page.go`-29a. `internal/cloudcp/portal/setup_facts.go`+ 29a. `internal/cloudcp/portal/setup_facts.go`30. `internal/cloudcp/public_cloud_signup_handlers.go`31. `internal/cloudcp/registry/models.go`32. `internal/cloudcp/registry/registry.go`@@ -97,7 +160,7 @@ Stripe-free and avoids a cloud-control-plane report data path across clients.35. `internal/hosted/provisioner.go`36. `frontend-modern/src/App.tsx`37. `frontend-modern/src/AppLayout.tsx`-37a. `frontend-modern/src/components/CommercialMigrationBanner.tsx`+ 37a. `frontend-modern/src/components/CommercialMigrationBanner.tsx`38. `frontend-modern/src/useAppRuntimeState.ts`39. `frontend-modern/src/components/Settings/BillingAdminPanel.tsx`40. `frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx`@@ -129,20 +192,20 @@ Stripe-free and avoids a cloud-control-plane report data path across clients.66. `pkg/licensing/testing_helpers.go`67. `pkg/licensing/self_hosted_feature_catalog.go`68. `frontend-modern/src/utils/selfHostedFeatureCatalog.generated.ts`-80. `internal/cloudcp/server.go`, `internal/cloudcp/authz.go`, `internal/cloudcp/commercial_identity.go`, `internal/cloudcp/security.go`-81. `internal/cloudcp/health_monitor.go`, `internal/cloudcp/health_stuck_provisioning.go`, `internal/cloudcp/tenant_state_metrics.go`, `internal/cloudcp/ratelimit.go`-81a. `internal/cloudcp/proxytrust/client_ip.go`-82. `internal/cloudcp/hosted_entitlement_handlers.go`, `internal/cloudcp/url_helpers.go`-83. `internal/cloudcp/admin/handlers.go`, `internal/cloudcp/admin/status.go`, `internal/cloudcp/auditlog/auditlog.go`-84. `internal/cloudcp/cpmetrics/metrics.go`, `internal/cloudcp/cpsec/nonce.go`, `internal/cloudcp/static_assets.go`, `internal/cloudcp/favicon.svg`-85. `internal/cloudcp/email/sender.go`, `internal/cloudcp/email/templates.go`-86. `internal/cloudcp/handoff/handler.go`, `internal/cloudcp/handoff/handoff.go`-87. `internal/cloudcp/stripe/grace_enforcer.go`, `internal/cloudcp/stripe/helpers.go`, `internal/cloudcp/stripe/reconciler.go`, `internal/cloudcp/stripe/webhook.go`-88. `internal/hosted/hosted_metrics.go`, `internal/hosted/reaper.go`-89. `internal/cloudcp/public_msp_signup_handlers.go`-90. `internal/cloudcp/provider_msp_bootstrap.go`-91. `internal/cloudcp/provider_msp_backup.go`-92. `internal/cloudcp/provider_msp_recovery.go`+69. `internal/cloudcp/server.go`, `internal/cloudcp/authz.go`, `internal/cloudcp/commercial_identity.go`, `internal/cloudcp/security.go`+70. `internal/cloudcp/health_monitor.go`, `internal/cloudcp/health_stuck_provisioning.go`, `internal/cloudcp/tenant_state_metrics.go`, `internal/cloudcp/ratelimit.go`+ 81a. `internal/cloudcp/proxytrust/client_ip.go`+71. `internal/cloudcp/hosted_entitlement_handlers.go`, `internal/cloudcp/url_helpers.go`+72. `internal/cloudcp/admin/handlers.go`, `internal/cloudcp/admin/status.go`, `internal/cloudcp/auditlog/auditlog.go`+73. `internal/cloudcp/cpmetrics/metrics.go`, `internal/cloudcp/cpsec/nonce.go`, `internal/cloudcp/static_assets.go`, `internal/cloudcp/favicon.svg`+74. `internal/cloudcp/email/sender.go`, `internal/cloudcp/email/templates.go`+75. `internal/cloudcp/handoff/handler.go`, `internal/cloudcp/handoff/handoff.go`+76. `internal/cloudcp/stripe/grace_enforcer.go`, `internal/cloudcp/stripe/helpers.go`, `internal/cloudcp/stripe/reconciler.go`, `internal/cloudcp/stripe/webhook.go`+77. `internal/hosted/hosted_metrics.go`, `internal/hosted/reaper.go`+78. `internal/cloudcp/public_msp_signup_handlers.go`+79. `internal/cloudcp/provider_msp_bootstrap.go`+80. `internal/cloudcp/provider_msp_backup.go`+81. `internal/cloudcp/provider_msp_recovery.go`## Shared Boundaries@@ -198,94 +261,94 @@ Stripe-free and avoids a cloud-control-plane report data path across clients.syntactically valid `/api/public/signup` requests resolve to one uniform`202 Accepted` Pulse Account response whether provisioning/email sideeffects ran or were suppressed by owner-email throttling.-7. `internal/cloudcp/auth/magiclink.go` shared with `security-privacy`: control-plane magic-link HMAC handling is both a Pulse Cloud account-access boundary and a security/privacy token-secrecy boundary.-8. `internal/cloudcp/auth/magiclink_store.go` shared with `security-privacy`: control-plane magic-link persistence is both a Pulse Cloud account-access boundary and a security/privacy storage-hardening boundary.-9. `internal/cloudcp/docker/labels.go` shared with `deployment-installability`: hosted tenant Docker labels are both a Pulse Cloud runtime contract boundary and a deployment-installability rollout boundary.-10. `internal/cloudcp/docker/manager.go` shared with `deployment-installability`: hosted tenant container management is both a Pulse Cloud runtime contract boundary and a deployment-installability rollout boundary.- Hosted tenant container creation must also bound Docker `json-file` logs- through the control-plane Docker manager so tenant runtime logging cannot- fill the live Pulse Cloud host independently of tenant data quotas.- Hosted tenant container creation must also stamp tenant identity into the- runtime environment: the Docker manager resolves the workspace display name- from the tenant registry at container-create time and injects- `PULSE_TENANT_NAME` alongside `PULSE_TENANT_ID`, so alert webhook payloads- from hosted client runtimes carry a human-readable workspace label instead- of falling back to the tenant ID. Display-name changes after creation apply- on the next tenant runtime rollout, which recreates the container with- freshly resolved environment.- Provider-hosted MSP and Pulse-hosted tenant creation must also prepare or- fail closed on the configured tenant runtime image before mutating the- workspace into a state that expects a live runtime container; readiness- checks must surface missing Docker daemon, network, image, and storage- prerequisites as operator-facing failures.- Hosted checkout and MSP workspace provisioning must also pass the- control-plane storage admission guard before tenant/account mutation: root- filesystem, tenant data, Docker runtime store, and Docker build-cache- thresholds are part of the Cloud paid readiness contract rather than an- operator-only cleanup script.- The same cloud audit contract must fail on stale proof/canary account rows- and paid hosted entitlements whose tenant rows are missing, because either- residue can recreate or mask hosted runtime state after a cleanup.- Disposable proof-account cleanup must use the control-plane registry as the- source of truth rather than ad hoc SQL: account deletion must refuse accounts- that still own tenant rows, remove account-owned membership, invitation, and- Stripe account metadata in one registry transaction, and leave user identity- rows intact unless a separately governed identity-retention rule says- otherwise.- The live production host must run that cloud audit through the private- Pulse Pro operations bundle on a recurring systemd timer, write durable- status/log output, and emit Prometheus textfile metrics so a clean GA- baseline is continuously monitored rather than manually rediscovered.- Provider-hosted MSP runtime isolation must keep client tenant runtimes off- the shared provider ingress/support network. The Docker manager must derive- a per-client tenant bridge, label it with tenant identity, pin Traefik- routing to that tenant bridge, attach only provider support containers- selected by provider MSP labels, start the tenant runtime only after those- support attachments succeed, prefer the tenant bridge for health checks, and- remove tenant bridges when the owning runtime is removed.- Tenant runtime containers must also start with the provider-hosted escape- hardening defaults owned by the Docker manager: no-new-privileges, dropped- Linux capabilities unless explicitly reintroduced by a governed need,- Docker's default seccomp profile still active, a read-only root filesystem,- and bounded writable tmpfs mounts only for runtime scratch paths. These- defaults are part of the client isolation contract, not optional compose- decoration.- Tenant runtime containers must also start as the rootless Pulse runtime user- instead of entering the image's root-owned chown and `su-exec` branch. The- Docker manager owns host-side preparation of the tenant data directory,- including recursive ownership alignment to the configured tenant UID/GID and- strict permissions on tenant key files, so `CapDrop: ["ALL"]` and- read-only root filesystems remain compatible with first workspace startup.- Client-bound proof must cover the boundary itself: workspace limits must not- be raceable past the licensed cap, handoff tokens must not be replayed or- retargeted across workspaces, org-bound agent install/report tokens must not- write into another client runtime, and rotated-out install tokens must fail- immediately.- Provider-default report branding is part of the same tenant environment- contract: `internal/cloudcp/docker/manager.go` may inject- `PULSE_REPORT_PROVIDER_BRAND_DISPLAY_NAME`, logo path/data, and logo format- into each tenant container, but it must not collect report data or render- PDFs in the control plane. Tenant-local reporting and tenant-local licensing- decide whether that configured brand appears.- `pulse_hosted_msp` is the Pulse-operated form of the same Stripe-free MSP- control-plane family, not the public Pulse-hosted SaaS checkout path. It- must share the license-backed MSP plan source, workspace limit policy,- disabled public signup and Stripe billing routes, isolated tenant runtime- networks, tenant-local report branding, and provider MSP operator commands- with `provider_hosted_msp` while preserving its own control-plane mode value- for status, backup manifests, and operational audit.-11. `internal/cloudcp/provider_msp_backup.go` shared with `deployment-installability`: provider-hosted MSP backup is both a cloud-paid license/account/runtime continuity boundary and a deployment-installability recovery artifact boundary.+9. `internal/cloudcp/auth/magiclink.go` shared with `security-privacy`: control-plane magic-link HMAC handling is both a Pulse Cloud account-access boundary and a security/privacy token-secrecy boundary.+10. `internal/cloudcp/auth/magiclink_store.go` shared with `security-privacy`: control-plane magic-link persistence is both a Pulse Cloud account-access boundary and a security/privacy storage-hardening boundary.+11. `internal/cloudcp/docker/labels.go` shared with `deployment-installability`: hosted tenant Docker labels are both a Pulse Cloud runtime contract boundary and a deployment-installability rollout boundary.+12. `internal/cloudcp/docker/manager.go` shared with `deployment-installability`: hosted tenant container management is both a Pulse Cloud runtime contract boundary and a deployment-installability rollout boundary.+ Hosted tenant container creation must also bound Docker `json-file` logs+ through the control-plane Docker manager so tenant runtime logging cannot+ fill the live Pulse Cloud host independently of tenant data quotas.+ Hosted tenant container creation must also stamp tenant identity into the+ runtime environment: the Docker manager resolves the workspace display name+ from the tenant registry at container-create time and injects+ `PULSE_TENANT_NAME` alongside `PULSE_TENANT_ID`, so alert webhook payloads+ from hosted client runtimes carry a human-readable workspace label instead+ of falling back to the tenant ID. Display-name changes after creation apply+ on the next tenant runtime rollout, which recreates the container with+ freshly resolved environment.+ Provider-hosted MSP and Pulse-hosted tenant creation must also prepare or+ fail closed on the configured tenant runtime image before mutating the+ workspace into a state that expects a live runtime container; readiness+ checks must surface missing Docker daemon, network, image, and storage+ prerequisites as operator-facing failures.+ Hosted checkout and MSP workspace provisioning must also pass the+ control-plane storage admission guard before tenant/account mutation: root+ filesystem, tenant data, Docker runtime store, and Docker build-cache+ thresholds are part of the Cloud paid readiness contract rather than an+ operator-only cleanup script.+ The same cloud audit contract must fail on stale proof/canary account rows+ and paid hosted entitlements whose tenant rows are missing, because either+ residue can recreate or mask hosted runtime state after a cleanup.+ Disposable proof-account cleanup must use the control-plane registry as the+ source of truth rather than ad hoc SQL: account deletion must refuse accounts+ that still own tenant rows, remove account-owned membership, invitation, and+ Stripe account metadata in one registry transaction, and leave user identity+ rows intact unless a separately governed identity-retention rule says+ otherwise.+ The live production host must run that cloud audit through the private+ Pulse Pro operations bundle on a recurring systemd timer, write durable+ status/log output, and emit Prometheus textfile metrics so a clean GA+ baseline is continuously monitored rather than manually rediscovered.+ Provider-hosted MSP runtime isolation must keep client tenant runtimes off+ the shared provider ingress/support network. The Docker manager must derive+ a per-client tenant bridge, label it with tenant identity, pin Traefik+ routing to that tenant bridge, attach only provider support containers+ selected by provider MSP labels, start the tenant runtime only after those+ support attachments succeed, prefer the tenant bridge for health checks, and+ remove tenant bridges when the owning runtime is removed.+ Tenant runtime containers must also start with the provider-hosted escape+ hardening defaults owned by the Docker manager: no-new-privileges, dropped+ Linux capabilities unless explicitly reintroduced by a governed need,+ Docker's default seccomp profile still active, a read-only root filesystem,+ and bounded writable tmpfs mounts only for runtime scratch paths. These+ defaults are part of the client isolation contract, not optional compose+ decoration.+ Tenant runtime containers must also start as the rootless Pulse runtime user+ instead of entering the image's root-owned chown and `su-exec` branch. The+ Docker manager owns host-side preparation of the tenant data directory,+ including recursive ownership alignment to the configured tenant UID/GID and+ strict permissions on tenant key files, so `CapDrop: ["ALL"]` and+ read-only root filesystems remain compatible with first workspace startup.+ Client-bound proof must cover the boundary itself: workspace limits must not+ be raceable past the licensed cap, handoff tokens must not be replayed or+ retargeted across workspaces, org-bound agent install/report tokens must not+ write into another client runtime, and rotated-out install tokens must fail+ immediately.+ Provider-default report branding is part of the same tenant environment+ contract: `internal/cloudcp/docker/manager.go` may inject+ `PULSE_REPORT_PROVIDER_BRAND_DISPLAY_NAME`, logo path/data, and logo format+ into each tenant container, but it must not collect report data or render+ PDFs in the control plane. Tenant-local reporting and tenant-local licensing+ decide whether that configured brand appears.+ `pulse_hosted_msp` is the Pulse-operated form of the same Stripe-free MSP+ control-plane family, not the public Pulse-hosted SaaS checkout path. It+ must share the license-backed MSP plan source, workspace limit policy,+ disabled public signup and Stripe billing routes, isolated tenant runtime+ networks, tenant-local report branding, and provider MSP operator commands+ with `provider_hosted_msp` while preserving its own control-plane mode value+ for status, backup manifests, and operational audit.+13. `internal/cloudcp/provider_msp_backup.go` shared with `deployment-installability`: provider-hosted MSP backup is both a cloud-paid license/account/runtime continuity boundary and a deployment-installability recovery artifact boundary.License-backed provider MSP backups must include the signed MSP licensefile as a recovery artifact while exposing only license metadata in commandoutput, restore must recover that license as an explicit operator artifact,and the archive must stay Stripe-free so provider-hosted MSP recovery doesnot inherit Pulse-hosted SaaS billing assumptions.-12. `internal/cloudcp/provider_msp_recovery.go` shared with `deployment-installability`: provider-hosted MSP failed-workspace recovery is both a cloud-paid license/account/runtime continuity boundary and a deployment-installability recovery artifact boundary.+14. `internal/cloudcp/provider_msp_recovery.go` shared with `deployment-installability`: provider-hosted MSP failed-workspace recovery is both a cloud-paid license/account/runtime continuity boundary and a deployment-installability recovery artifact boundary.Provider-hosted MSP recovery must require the signed provider MSP licensesource by default, preserve the client workspace boundary, refuse to startfrom empty tenant data, and mark a workspace active only after the canonicaltenant-runtime rollout path has produced a healthy runtime.-13. `internal/cloudcp/tenant_runtime_rollout.go` shared with `deployment-installability`: hosted tenant runtime rollout is both a Pulse Cloud runtime contract boundary and a deployment-installability release-rollout boundary.+15. `internal/cloudcp/tenant_runtime_rollout.go` shared with `deployment-installability`: hosted tenant runtime rollout is both a Pulse Cloud runtime contract boundary and a deployment-installability release-rollout boundary.Hosted tenant runtime reconciliation must treat a registered tenant withpreserved tenant data but no live Docker runtime as a recoverable managedstate, not as a terminal skip. The control-plane-owned reconcile path must@@ -303,7 +366,7 @@ Stripe-free and avoids a cloud-control-plane report data path across clients.must print the target-image rollout plan before mutation, `--all` mustselect active tenants only, and apply must still use the canonicalper-tenant snapshot, health-check, and rollback path. `tenant-runtime- reconcile --all` remains contract/routing drift repair for each tenant's+reconcile --all` remains contract/routing drift repair for each tenant'scurrent image line, not an image-line upgrade path.The real `pulse-pro` license-server legacy checkout issuance, recurring@@ -323,6 +386,112 @@ site deploys; active paid-feature proof must stay on checkout creation,portal-handoff state, pricing/catalog truth, download delivery, and license orrelay entitlement behavior rather than requiring the removed funnel monitoringfiles.+Pulse Intelligence paid-value evidence is a separate private admin aggregate,+not a revival of those retired funnel stores. The `pulse-pro` license server+may expose `/v1/admin/pulse-intelligence/value` and the matching admin-console+strip only as coarse install cohorts over anonymous telemetry pings: paid+install rate, free-to-paid conversion, returning-install retention, and whether+the full Patrol -> contextual collaboration -> governed action loop, the+stricter Patrol -> contextual collaboration -> approved execution loop, and+the approved-action-success and adapter-specific Pulse MCP loop variants are+active, including the stricter resolved operations loop split by first-party+Assistant collaboration, external-agent collaboration, and Pulse MCP adapter+use.+The same aggregate may expose an `operations_funnel` object that keeps the+loop proof readable as a staged anonymous cohort sequence: loop configured,+Patrol activity, Assistant or external-agent collaboration, governed action,+approved execution, approved action success, Patrol resolution, resolved+operations loop, Assistant resolved loop, external-agent resolved loop, active+30-day use, retained installs, Patrol-control completed-loop and resolved-loop+proof, paid Patrol-control cohorts, and full-loop free-to-paid conversion compared with generic+Assistant-only chat. That funnel is a projection over the same coarse telemetry+counters and value cohorts; it must not introduce per-install drilldowns or raw+commercial account links. Source-specific guided starter cohorts may split the+same anonymous operations-loop starter count into Assistant, Patrol, primary+Patrol-control, legacy Pro activation entry-point, and Pulse MCP sources so+conversion reporting can tell which entry point led to loop entry, but those cohorts+remain starter evidence only and must not be counted as completed+operations-loop, approved execution, or resolved-loop proof.+Patrol-control completed-loop and resolved-loop funnel stages must come from+the explicit content-free Patrol-control booleans; resolved proof may satisfy+completed proof, but a rejected terminal completed loop must never be counted as+resolved proof. Legacy Pro activation completed/resolved booleans may be+retained only as mirrors for historical cohort continuity.+The self-hosted Pro plan surface may consume the authenticated, content-free+`GET /api/agent/operations-loop/status` projection only to choose the primary+Patrol handoff in the current-plan summary: set Patrol control when no work is+active, continue unfinished Patrol work, or review a pending governed decision.+The plan capability details disclosure must stay entitlement/runtime+diagnostics only. It must not add a `Patrol work`, started,+decision-recorded, verified, external-agent readiness, or compatibility+operations-loop status row from Patrol starter/completed/resolved counts,+legacy `proActivation*` aliases, legacy `patrolAutonomy*` mirrors, shared+status `nextAction`, or shared status `progressLabel`; those fields are+Patrol-page context and telemetry, not paid-plan detail copy. The plan surface+must not expose prompts, accounts, resource names, finding IDs, action IDs,+commands, token metadata, or any per-install drilldown, and lack of that+projection must not block entitlement or plan rendering. The visible Pro plan+card must keep the paid user's first-party task clear: choose Patrol mode and+let Patrol handle infrastructure work. The first-party commercial copy owns+the product framing: stale activation-loop, operations-loop, or MCP setup+progress text from the projection must not become the visible paid CTA when+the correct next step is Patrol control or Patrol work.+Commercial, plan, and activation-success copy must use `Choose Patrol mode`+for the paid operator boundary and frame it as setting how autonomous Patrol+should be. Self-hosted Community copy should state the features available on+that install, such as watch-only Patrol, instead of explaining unavailable+fix classes. Pro plan cards may describe hands-on Patrol modes and verified+fixes, but they must not revive activation-loop, MCP readiness, or internal+proof vocabulary as the paid user's default setup story; route-backed anchors,+telemetry, and compatibility wire fields may retain stable names such as+`patrol_control` and `patrolControl*`.+Routine self-hosted Plans and capability-status copy must describe what is+available on the instance and route recovery as `refresh the plan` or `open+recovery`; it must not describe normal setup as activation or expose raw+entitlement-payload wording to the operator.+That external-agent readiness boolean means the manifest-owned Pulse MCP+operations-loop contract is available and one non-expired API token covers the+full published operations-loop scope set; a partial MCP token is not paid value+proof, missing MCP readiness must not downgrade verified Patrol value, and it+must not become an activation/setup step on the default plan surface.+The completed-loop count consumed here is the API-owned terminal-loop proof: it+requires Patrol control starter evidence, Patrol issue evidence, contextual+Assistant or external-agent collaboration, and either a rejected governed+decision or an approved governed decision with verified outcome proof.+The resolved-loop count consumed here is already the API-owned full-loop proof:+it requires Patrol control starter evidence, Patrol issue evidence, contextual+Assistant or external-agent collaboration, an approved governed decision, and a+verified outcome in the same evidence window.+The steady-state current-plan action may use that same first-party Patrol+control projection to label the Patrol handoff as start, continue, or review,+but it must still route to the Patrol-owned Patrol control anchor rather than+creating a separate commercial activation state machine. Legacy Pro activation+evidence alone must leave the action as a fresh Patrol control handoff.+Start and continue paid Patrol control handoffs from+`frontend-modern/src/utils/licensePresentation.ts` must compose the+route-backed Patrol control URL from+`frontend-modern/src/routing/resourceLinks.ts`; the settings panel must not+write the starter marker from a local click handler before navigation, and its+presentation model must not carry a `recordActivity` switch for that handoff.+Patrol owns consuming that route flag and writing the content-free+`patrol_control` marker; `patrol_autonomy` and `pulse_pro_activation` remain+accepted only as legacy route/activity aliases. Once the action has become verified review,+`licensePresentation.ts` must route to the plain Patrol control anchor and+keep marker recording disabled.+When that action has become a completed-loop review, it must not write another+Patrol control starter marker; starter telemetry remains for start/continue+entry into the guided journey rather than for post-completion review clicks.+The value report may also expose a `value_driver_evidence` summary derived only+from those same anonymous cohort deltas. That summary may state whether the+available evidence is insufficient, positive on paid conversion, positive on+activation or retention, or has no positive delta against the generic+Assistant-only baseline; it must not claim causality, store per-install+drilldowns, or introduce a second analytics data source outside telemetry+pings.+That report must not expose install IDs, customer emails, prompts, finding IDs,+resource IDs, or action payloads, and generic Assistant-only chat must remain a+separate cohort so it cannot be counted as proof that the proactive operations+loop is driving paid value.That same public-pricing boundary also owns the machine-readable v6 pricingvalidator and launch checklist in `pulse-pro:scripts/validate_public_pricing_model.py`and `pulse-pro:V6_LAUNCH_CHECKLIST.md`. Those operator surfaces must describe@@ -602,7 +771,27 @@ or other self-hosted uncapped continuity plans.actions are cloud-paid behaviors, but their button chrome must compose thefrontend-primitives `Button` family instead of carrying Pro-license-localprimary, secondary, or warning action class strings.-18. Add or change paid relay settings and pairing presentation through `frontend-modern/src/components/Settings/RelaySettingsPanel.tsx`, `frontend-modern/src/components/Settings/RelayPairingSection.tsx`, and `frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts`. The retired Dashboard shell must not be restored to carry a Relay onboarding card or equivalent blanket upsell — relay discovery stays inside its owning settings surface.+ The self-hosted Pro plan and activation-success surfaces must keep Patrol+ actions tied to current operator work: set Patrol control when no work is+ active, open Patrol for current work, or review a pending governed+ decision. Self-hosted Pro plan status and readiness payloads are support+ diagnostics: the default Plan surface must keep the current plan and Patrol+ mode action primary, while capability details render behind a disclosure+ for troubleshooting unavailable controls or missing capabilities. That+ disclosure must not duplicate Patrol-page work progress, decisions,+ verified outcomes, or external-agent setup readiness.+ Completed verified Patrol outcomes are history/telemetry and must not+ appear as a default `Patrol history` CTA or a `Patrol work` verified+ status row in the Plan surface. Frontend presentation models must call+ this a Patrol control action/status boundary; `operations-loop` wording is+ only acceptable at backend API or telemetry compatibility edges.+ The Plan surface may fetch Patrol operator status from the compatibility+ `/api/agent/operations-loop/status` endpoint only after the current+ self-hosted plan resolves to a Pro-family tier through+ `getSelfHostedPlanDefinitionForBillingTier`. Community and Relay plans+ must render their included capabilities without loading paid Patrol+ operator-status plumbing.+17. Add or change paid relay settings and pairing presentation through `frontend-modern/src/components/Settings/RelaySettingsPanel.tsx`, `frontend-modern/src/components/Settings/RelayPairingSection.tsx`, and `frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts`. The retired Dashboard shell must not be restored to carry a Relay onboarding card or equivalent blanket upsell — relay discovery stays inside its owning settings surface.Public demo and other read-only presentation policy states must suppressrelay setup and upsell onboarding instead of inviting pairing or commercialaction from a governed non-manageable surface.@@ -613,8 +802,8 @@ or other self-hosted uncapped continuity plans.Relay settings and public commercial docs must also keep Remote Accesspositioned as a Relay-and-higher capability, not a Pro-only feature, so theRelay tier remains a tangible standalone paid product.-20. Add contract tests where runtime and pricing need to stay aligned-21. Add or change hosted browser org-context bootstrap through `frontend-modern/src/App.tsx`, `frontend-modern/src/AppLayout.tsx`, `frontend-modern/src/useAppRuntimeState.ts`, and `frontend-modern/src/utils/apiClient.ts`+18. Add contract tests where runtime and pricing need to stay aligned+19. Add or change hosted browser org-context bootstrap through `frontend-modern/src/App.tsx`, `frontend-modern/src/AppLayout.tsx`, `frontend-modern/src/useAppRuntimeState.ts`, and `frontend-modern/src/utils/apiClient.ts`That same hosted bootstrap boundary also owns the runtime-capability JSONshape that the app shell consumes before it decides whether organizationchrome and multi-tenant routes exist. `pkg/licensing/entitlement_payload.go`@@ -637,7 +826,7 @@ or other self-hosted uncapped continuity plans.compatibility routes must not revive hosted signup, public Cloud trial,pricing, or commercial acquisition surfaces inside the local productruntime.-22. Keep the hosted account portal shell task-first and compact. Section+20. Keep the hosted account portal shell task-first and compact. Sectionheaders, billing action rows, and the maintained portal bundle under`internal/cloudcp/portal/` may surface the facts an operator needs, but theshell should not spend vertical space on duplicate context-chip strips when@@ -646,7 +835,7 @@ or other self-hosted uncapped continuity plans.the section, but that summary treatment must stay inside the same tasksurface instead of reviving a separate overview panel, summary strip, ormetric deck ahead of the real workspace list.-23. Keep monitored-system volume out of the commercial product model.+21. Keep monitored-system volume out of the commercial product model.Recognized self-hosted and hosted v6 tiers must treat legacymonitored-system limit, continuity, or `max_monitored_systems` metadata asscrub-only compatibility input rather than as support/audit policy or a@@ -662,12 +851,13 @@ or other self-hosted uncapped continuity plans.narrative across the in-app billing shell, Pulse Account handoff, publicpricing contract, and owned upgrade reasons. Customer-facing self-hostedcopy must keep the ladder explicit as `Community = monitor`, `Relay = reach- Pulse from anywhere plus pair Pulse Mobile for handoff`, and `Pro = investigate root cause, use safe- remediation workflows, and retain 90-day history`. Team/admin extras such as+Pulse from anywhere plus pair Pulse Mobile for handoff`, and `Pro =+hands-on Patrol modes, issue investigation, verified fixes, and 90-day history`.+ Team/admin extras such asRBAC, SSO, audit logging, reporting, and agent profiles may remain present,but they are secondary included value and must not displace that operatoroutcome framing on owned commercial surfaces.-24. Keep public-demo route bootstrap owned on the adjacent+22. Keep public-demo route bootstrap owned on the adjacentcommercial/runtime boundary. `frontend-modern/src/useAppRuntimeState.ts`may prewarm shared infrastructure summary caches for route-owned surfaces,but public-demo arrival must not front-run a broader infrastructure-summary@@ -685,25 +875,36 @@ or other self-hosted uncapped continuity plans.browser entrypoint must remain only a thin authenticated redirect ratherthan a second public handoff or a route that invites separate commercialposture logic.-25. Keep self-hosted commercial plan copy aligned with the v6 operator-value+23. Keep self-hosted commercial plan copy aligned with the v6 operator-valuemodel instead of mirroring raw entitlement keys. `frontend-modern/src/- utils/selfHostedPlans.ts` may still map onto internal capabilities such as+utils/selfHostedPlans.ts` may still map onto internal capabilities such as`ai_patrol`, `ai_alerts`, `ai_autofix`, and `kubernetes_ai`, but thecustomer-facing plan cards, top-summary highlights, and comparison rowsmust lead with the canonical plan story: `Community = monitor`, `Relay =- reach Pulse from anywhere plus pair Pulse Mobile for handoff`, and `Pro = root-cause analysis, safe- remediation workflows, and longer history`. Team/admin capabilities such as+reach Pulse from anywhere plus pair Pulse Mobile for handoff`, and `Pro =+hands-on Patrol modes, issue investigation, verified fixes, and longer history`.+ Team/admin capabilities such asRBAC, audit logging, reporting, and agent profiles may appear as- secondary included extras, while platform-specific compatibility keys such+ secondary included extras. Their customer-facing plan summary label is+ `admin controls`, not `admin tools`, because Pro is sold as Patrol handling+ infrastructure within a chosen mode rather than as a bag of operator+ utilities. Platform-specific compatibility keys suchas `kubernetes_ai` must not be elevated into a marquee marketed Pro line- item on the self-hosted Plans surface. Legacy packaging nouns such as+ item. Pro comparison and plan-selection copy must frame Patrol around what+ it may handle automatically, issue investigation, policy-bounded action,+ verified fixes, and history rather than as an abstract governed operator or+ a choice about how much control Patrol has.+ When free-plan copy mentions Patrol, it must describe watch-only/background+ health checks; investigation, approval-backed fixes, autonomous action,+ outcome verification, and extended history are Pro value.+ Legacy packaging nouns such as`incident memory`, `scheduled remediations`, and `execution audit trail`must likewise stay out of current v6 commercial copy unless Pulse ships afirst-class product surface that makes those names truthful again. The rawentitlement key `ai_autofix` may remain the internal capability identifier,but owned plan cards, comparison rows, and upgrade reasons must present it- as safe remediation workflows rather than `Patrol Auto-Fix` or other- stronger automation-first labels. Pulse Account preview/handoff pricing+ as Patrol fixing safe issues within the selected Patrol mode rather than+ as `Patrol Auto-Fix` or an abstract remediation-workflow label. Pulse Account preview/handoff pricingcopy, public plan docs, and the in-app self-hosted billing shell must sharethat same free-first ladder so release-candidate and public purchase pathsdo not drift into a separate commercial story.@@ -720,7 +921,7 @@ or other self-hosted uncapped continuity plans.also treat `compatibility_only` entries as non-marketed compatibilitycapabilities by returning only the generic pricing destination rather thana feature-specific paid upgrade URL.-26. Keep hosted trial-activation verifier source selection compile-time owned.+24. Keep hosted trial-activation verifier source selection compile-time owned.`pkg/licensing/trial_activation.go`,`pkg/licensing/trial_activation_public_key_override_dev.go`, and`pkg/licensing/trial_activation_public_key_override_release.go` together@@ -728,7 +929,7 @@ or other self-hosted uncapped continuity plans.builds may keep the local override path, but release builds must resolvethe verifier from the embedded build-time source of truth instead ofhonoring `PULSE_HOSTED_MODE` or other runtime wiring.-27. Add or change the Cloud control-plane runtime, public signup lifecycle,+25. Add or change the Cloud control-plane runtime, public signup lifecycle,tenant health/reconciliation, control-plane metrics, email delivery,hosted handoff, hosted entitlement refresh, or hosted tenant reaping through`internal/cloudcp/` and `internal/hosted/`. Those paths must stay governed@@ -813,50 +1014,50 @@ or other self-hosted uncapped continuity plans.volume telemetry must not become runtime status, entitlement enforcement,customer-facing support context, or self-hosted Plans presentation.10. Keep organization billing loading placeholders on the shared- `SettingsLoadingSkeleton` primitive. Cloud-paid owns billing and usage- semantics; frontend-primitives owns the loading skeleton animation, fill- tokens, and metric/progress/card placeholder shells.-10. Keep Stripe webhook idempotency state bounded in the control-plane- registry: `internal/cloudcp/registry/registry.go` may retain `stripe_events`- rows long enough to suppress duplicate deliveries and reclaim stale- in-flight work, but it must prune expired processed or abandoned rows so- webhook dedupe does not grow without bound on disk.-11. Keep the maintained Pulse Account portal bundle source-synced with- `internal/cloudcp/portal/frontend/`: any slice that changes the portal- frontend hash or emitted manifest must rebuild- `internal/cloudcp/portal/dist/build_manifest.json` and keep- `internal/cloudcp/portal/frontend_sync_test.go` green in the same change.-12. Before GA, treat infrastructure monitoring volume as unmetered:- monitored systems remain the canonical inventory grouping unit, but paid- value must come from optional extras, hosted convenience, business- workflow, support, or similar non-core surfaces rather than using- monitored-system volume itself as a paid gate.- Child-resource volume, including guest capacity, must follow the same- self-hosted rule instead of becoming a replacement paid gate for core- monitoring.- Monitored-system impact-preview copy must follow the same rule: ordinary- connection previews may describe count impact and grouping changes, but- they must not use capacity-style titles or slash-style quota summaries that- imply self-hosted monitoring volume is the product being sold.-13. Keep v6 billing state uncapped even when persisted state still carries- legacy commercial volume-limit keys:- `pkg/licensing/models.go`,- `pkg/licensing/service.go`,- `pkg/licensing/entitlement_payload.go`,- `pkg/licensing/billing_state_normalization.go`,- `pkg/licensing/database_source.go`,- `pulse-pro:license-server/v6_store.go`, and- `pulse-pro:license-server/v6_schema.go` must scrub stale- `max_monitored_systems` values for Community/free, Relay, Pro, Pro+, Pro- Annual, lifetime, eligible grandfathered recurring, Cloud, and MSP plan- labels before runtime-capability, entitlement, grant, lease, billing, or- browser-facing payloads are built.- The same boundary must merge sparse legacy, configured-plan, or manually- supplied feature lists with canonical recognized-tier defaults before- storage, API response, or grant signing so Lifetime, Pro, Pro+, and- grandfathered recurring customers cannot be downgraded to the partial- feature list carried by an old JWT or legacy plan row.-14. Keep self-hosted commercial funnel stage ownership out of the customer+ `SettingsLoadingSkeleton` primitive. Cloud-paid owns billing and usage+ semantics; frontend-primitives owns the loading skeleton animation, fill+ tokens, and metric/progress/card placeholder shells.+11. Keep Stripe webhook idempotency state bounded in the control-plane+ registry: `internal/cloudcp/registry/registry.go` may retain `stripe_events`+ rows long enough to suppress duplicate deliveries and reclaim stale+ in-flight work, but it must prune expired processed or abandoned rows so+ webhook dedupe does not grow without bound on disk.+12. Keep the maintained Pulse Account portal bundle source-synced with+ `internal/cloudcp/portal/frontend/`: any slice that changes the portal+ frontend hash or emitted manifest must rebuild+ `internal/cloudcp/portal/dist/build_manifest.json` and keep+ `internal/cloudcp/portal/frontend_sync_test.go` green in the same change.+13. Before GA, treat infrastructure monitoring volume as unmetered:+ monitored systems remain the canonical inventory grouping unit, but paid+ value must come from optional extras, hosted convenience, business+ workflow, support, or similar non-core surfaces rather than using+ monitored-system volume itself as a paid gate.+ Child-resource volume, including guest capacity, must follow the same+ self-hosted rule instead of becoming a replacement paid gate for core+ monitoring.+ Monitored-system impact-preview copy must follow the same rule: ordinary+ connection previews may describe count impact and grouping changes, but+ they must not use capacity-style titles or slash-style quota summaries that+ imply self-hosted monitoring volume is the product being sold.+14. Keep v6 billing state uncapped even when persisted state still carries+ legacy commercial volume-limit keys:+ `pkg/licensing/models.go`,+ `pkg/licensing/service.go`,+ `pkg/licensing/entitlement_payload.go`,+ `pkg/licensing/billing_state_normalization.go`,+ `pkg/licensing/database_source.go`,+ `pulse-pro:license-server/v6_store.go`, and+ `pulse-pro:license-server/v6_schema.go` must scrub stale+ `max_monitored_systems` values for Community/free, Relay, Pro, Pro+, Pro+ Annual, lifetime, eligible grandfathered recurring, Cloud, and MSP plan+ labels before runtime-capability, entitlement, grant, lease, billing, or+ browser-facing payloads are built.+ The same boundary must merge sparse legacy, configured-plan, or manually+ supplied feature lists with canonical recognized-tier defaults before+ storage, API response, or grant signing so Lifetime, Pro, Pro+, and+ grandfathered recurring customers cannot be downgraded to the partial+ feature list carried by an old JWT or legacy plan row.+15. Keep self-hosted commercial funnel stage ownership out of the customerproduct runtime. The customer frontend must not contain `upgradeMetrics`,`conversionEvents`, or infrastructure onboarding metrics wrappers or callsites at all. In-app `Plans & Billing`, pricing, checkout, paywall, or@@ -867,7 +1068,7 @@ or other self-hosted uncapped continuity plans.Pulse must not infer those portal stages from referrer state, and thecommercial service must keep those self-hosted handoffs on release track`v6` even while the public site remains on `v5` before GA.-15. Keep retired local commercial funnel reporting out of customer diagnostics,+16. Keep retired local commercial funnel reporting out of customer diagnostics,settings, and product startup: `internal/api/diagnostics.go`,`frontend-modern/src/components/Settings/DiagnosticsResultsPanel.tsx`,`frontend-modern/src/components/Settings/diagnosticsModel.ts`,@@ -878,7 +1079,7 @@ or other self-hosted uncapped continuity plans.pricing/checkout, upgrade-metrics, or infrastructure-onboarding analyticsfields, controls, routes, stores, or startup DB artifacts to normal productusers.-16. Keep ordinary self-hosted v6 commercial prompts opt-in. Cloud-paid runtime+17. Keep ordinary self-hosted v6 commercial prompts opt-in. Cloud-paid runtimemay keep checkout, activation, recovery, and support-only trial plumbingavailable for explicit handoffs and entitled installs, but defaultself-hosted browser surfaces must honor `presentationPolicy.hideUpgrade`@@ -889,18 +1090,18 @@ or other self-hosted uncapped continuity plans.`/api/license/commercial-posture` bootstrap while `presentationPolicy.hideUpgrade`is true; explicit self-hosted plan, activation/recovery, and hosted orprompt-allowed flows may still refresh the shared posture store.-17. Keep hosted and trial billing construction separate from retired hosted-AI+18. Keep hosted and trial billing construction separate from retired hosted-AIquickstart inventory: `pkg/licensing/trial_start.go` and hostedentitlement refresh paths may preserve historical billing fields for oldstate, but new trial or hosted workspaces must not mint quickstart creditsor imply a managed-model allowance as part of the commercial contract.-18. Keep Cloud signup acquisition owned by the Cloud control plane and public+19. Keep Cloud signup acquisition owned by the Cloud control plane and publicaccount surfaces, not by the ordinary self-hosted app shell. The defaultself-hosted frontend must not register unauthenticated `/cloud` or`/cloud/signup` routes, and self-hosted pricing fallbacks must route Cloudinterest to Pulse Account/public Cloud ownership rather than rendering anin-product trial or checkout page.-19. Keep the `unlimited` feature key neutral in shared metadata. It is a+20. Keep the `unlimited` feature key neutral in shared metadata. It is ahosted/MSP capacity-policy marker, not a self-hosted monitoring-volumeproduct promise. Runtime and generated feature catalogs must label it ashosted capacity policy, keep it hidden from self-hosted plan cards, and@@ -1681,8 +1882,8 @@ returning to the owned plan state through the runtime-owned activationcallback. Pulse product routeskeep ownership of license status, usage, and activation state; `Pulse Account`owns the commerce flow itself. That same self-hosted settings surface is-plan-owned rather than tier-owned: the navigation label is `Plans`, the-surface title is `Self-hosted plan`, and the canonical plan state must make+plan-owned rather than tier-owned: the navigation label and surface title are+`Plans & Billing`, and the canonical plan state must makethe current tier plus capabilities immediately obvious so existing paidupgrades can confirm what their new key enabled without hunting throughgeneric billing details. That capability-first summary must stay tier-specific@@ -1706,6 +1907,31 @@ surface must show an explicit success summary that names the active tier andthe marquee capabilities now available on this instance, rather thanfalling back to a generic "activated" banner that leaves the user to inferwhat changed from the steady-state billing card alone.+For active Pulse Pro/Lifetime tiers with the private Pro runtime available,+both the current-plan summary and the activation-success body must make the+next setup decision explicit: set Patrol mode, then let Patrol investigate,+act within that policy, verify outcomes, and keep context/history. Completed+verified Patrol outcomes are telemetry on this surface, not a reason to replace+the plan action with a default `Patrol history` CTA; when no active Patrol work+or pending governed decision exists, the paid-plan action returns to+`Choose Patrol mode`.+When the activated entitlement includes the governed Pulse Intelligence+operations-loop capability, that success summary may hand the user directly to+Patrol with a "Choose Patrol mode" action. The cloud-paid presentation contract+must name the action URL and action intent as Patrol-control concepts+(`PATROL_CONTROL_STARTER_URL` and `patrol_control`) rather than exposing+operations-loop names in the Plan surface. That action is still+cloud-paid-owned activation UX, but its destination must use the route-owned+Patrol control target+(`/patrol?patrolControlStarter=patrol_control#patrol-control`) so Patrol+owns starter recording through the shared Pulse Intelligence starter contract.+The legacy `patrol_autonomy` and `pulse_pro_activation` route and activity+markers remain compatibility input only, and the shared+`pulse_operations_loop` telemetry workflow marker may remain behind the Patrol+control surface. The Plans surface must not create a commercial-only analytics+counter, must not record prompt text or resource context, and must not treat the+click as proof that Patrol found an issue, Assistant explained it, a governed+action was approved, or the outcome was verified.That same router-owned billing contract now also includes recovery as a plandetail state instead of a fragment alias. The canonical recovery arrival is`/settings/system/billing/plan?details=recovery`, while@@ -1827,7 +2053,7 @@ commercial surface differently.That same shared presentation owner also carries the canonical cross-surfacereferral copy used outside the billing shell itself. When infrastructure orother adjacent settings surfaces need to point operators toward Plans & Billing-for billing, license status, or paid feature activation, they must consume the+for billing, license status, or paid feature access, they must consume thesettings-owned referral strings from`frontend-modern/src/components/Settings/selfHostedBillingPresentation.ts`instead of drafting route-local commercial guidance or reaching directly into@@ -1838,7 +2064,7 @@ is the canonical settings-shell adapter for self-hosted Plans & Billing shellframing and referral copy, while`frontend-modern/src/utils/licensePresentation.ts` remains the sharedcommercial notice/label owner for activation, trial, purchase, and recovery-language such as `License or Activation Key`. Hosted settings surfaces must+language such as `License key`. Hosted settings surfaces mustnot import self-hosted billing framing straight from the generic helper modulewhen doing so would reintroduce top-level bundle-init cycles into hostedtenant settings routes.@@ -1886,8 +2112,8 @@ the no-cap monitored-system model as well. `ProLicensePanel.tsx`,self-hosted packages as core monitoring included in every self-hosted tier plusplan-specific extras: Community stays free for core monitoring, Relay addsremote access/Pulse Mobile handoff/push convenience and 14-day history, Pro adds Relay plus-AI operations, automation, root-cause analysis, safe remediation, advanced-administration, and 90-day history, while Pro+ remains legacy continuity only.+hands-on Patrol modes, issue investigation, verified fixes, advanced administration,+and 90-day history, while Pro+ remains legacy continuity only.Cloud/MSP pricing semantics stay separate, and grandfathered v5 continuity copymust describe legacy continuity and recorded baselines rather than currentself-hosted monitored-system caps, capacity, or policy boundaries.@@ -1921,11 +2147,11 @@ self-hosted plan surface should imply monitored-system volume is a paid tier.That same pricing boundary now also owns the shared frontend plan-definitionmodels. `frontend-modern/src/utils/cloudPlans.ts` and`frontend-modern/src/utils/selfHostedPlans.ts` are the canonical frontend-sources for cloud and self-hosted plan copy, limits, and comparison metadata,-while `frontend-modern/src/pages/CloudPricing.tsx`,+sources for cloud and self-hosted plan copy, limits, and comparison metadata.+`frontend-modern/src/pages/CloudPricing.tsx`,`frontend-modern/src/pages/HostedSignup.tsx`, and the self-hosted billing-settings surfaces must consume those shared owners instead of redefining-retail plan facts or counted-unit policy locally.+settings surfaces must consume those shared plan-definition sources instead of+redefining retail plan facts or counted-unit policy locally.That shared ownership also includes display-ready price semantics. Monthlyheadline price, founding-rate override, compare-at strike-through copy,campaign badge copy, and annual summary text must come from the shared@@ -2012,8 +2238,8 @@ for that feature's owning subsystem — those are user-initiated discoverypaths, not blanket funnels, and are not required to be removed.Public AI and entitlement docs must use the same boundary: Community/Relay maydescribe Patrol background findings with BYOK, while investigation, proposed-remediation, safe remediation execution, and higher autonomy remain paid-AI-operations features.+fixes, governed fix execution, and higher autonomy remain paid AI-operations+features.Those docs should describe moving between available modes, not tell readers to"upgrade" as part of an ordinary safety progression.That same retired counted-unit boundary also owns the disclosure rule fordiff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.mdindex f161956df6..f09e8ea88f 100644--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md@@ -88,7 +88,6 @@ TLS floor in the dynamic config.51. `scripts/install.sh`52. `scripts/install-mcp.sh`53. `scripts/install-mcp.ps1`-54. `cmd/pulse-mcp/`55. `scripts/pulse-auto-update.sh`56. `scripts/release_control/internal/record_rc_to_ga_rehearsal.py`57. `scripts/release_control/record_rc_to_ga_rehearsal.py`@@ -288,6 +287,11 @@ TLS floor in the dynamic config.1. Add or change deployment-type detection, update planning, or apply behavior through `internal/updates/`2. Add or change release-build metadata injection, Docker build-context allowlists, release artifact assembly, governed promotion metadata resolution, the canonical version file, operator-facing release packet content, prerelease feedback intake wording, historical published-release integrity backfill, release asset validation status publication, download endpoint checksum/signature header proof, end-to-end install.sh smoke against the published release, or the canonical in-repo v6 upgrade guide through `scripts/build-release.sh`, `scripts/release_asset_common.sh`, `scripts/backfill-release-assets.sh`, `scripts/release_ldflags.sh`, `scripts/check-workflow-dispatch-inputs.py`, `scripts/release_control/render_release_body.py`, `scripts/release_control/resolve_release_promotion.py`, `scripts/release_control/record_rc_to_ga_rehearsal.py`, `scripts/release_control/internal/record_rc_to_ga_rehearsal.py`, `scripts/release_control/release_promotion_policy_support.py`, `.dockerignore`, `Dockerfile`, `.github/ISSUE_TEMPLATE/v6_rc_feedback.yml`, `docs/RELEASE_NOTES.md`, `docs/releases/`, `docs/UPGRADE_v6.md`, `docs/release-control/v6/internal/RELEASE_PROMOTION_POLICY.md`, `docs/release-control/v6/internal/PRE_RELEASE_CHECKLIST.md`, `docs/release-control/v6/internal/RC_TO_GA_REHEARSAL_TEMPLATE.md`, `scripts/validate-release.sh`, `scripts/validate-published-release.sh`, the operator dispatch helpers `scripts/trigger-release.sh` and `scripts/trigger-release-dry-run.sh`, and the governed release workflows `.github/workflows/backfill-release-assets.yml`, `.github/workflows/create-release.yml`, `.github/workflows/deploy-demo-server.yml`, `.github/workflows/helm-pages.yml`, `.github/workflows/install-sh-smoke.yml`, `.github/workflows/publish-docker.yml`, `.github/workflows/publish-helm-chart.yml`, `.github/workflows/promote-floating-tags.yml`, `.github/workflows/release-dry-run.yml`, `.github/workflows/update-demo-server.yml`, and `.github/workflows/validate-release-assets.yml`+ Release-facing agent-paradigm blurbs under `docs/releases/` must describe+ `pulse-mcp` as a generic MCP adapter for MCP-speaking clients, not a+ client-specific release artifact, and full-surface token guidance must come+ from the manifest-owned `requiredScopes` list so release notes cannot drift+ away from the shipped adapter.The `install-sh-smoke.yml` workflow runs end-to-end against thepublished release in a privileged systemd container: it downloads`install.sh` and `install.sh.sshsig` from the GitHub Release URL,@@ -397,6 +401,13 @@ TLS floor in the dynamic config.workspace package and Makefile must delegate their lab-agent targets throughthose same repo-root npm wrappers rather than duplicating raw launchercommands or teaching developers to paste one-off environment strings.+ After a developer explicitly starts lab-agent mode, the managed and+ foreground hot-dev launchers may remember that local workspace opt-in in+ ignored `tmp/` state so ordinary managed restarts do not silently strand+ already-installed LAN agents or lose the Proxmox guest Docker inventory+ flags. Clean checkouts must still default to loopback-only development, and+ an explicit `PULSE_DEV_LAB_AGENTS=false` / `PULSE_DEV_LAN=false` launch must+ clear the remembered opt-in and return the workspace to local-only binding.The hot-dev supervisor must also recover its managed PID file from a live`hot-dev-bg.sh supervise` process before treating the runtime as unmanaged.Backend health monitoring must distinguish HTTP startup grace from a missing@@ -1149,8 +1160,9 @@ shell and Windows installers also sit on the shared agent-lifecycle boundary.`scripts/install-mcp.sh` and `scripts/install-mcp.ps1` extend theinstaller family with a fourth entry point: a stdio MCP serveradapter (`cmd/pulse-mcp/`) that integrators run on their own-machine to drive Pulse from Claude Desktop, Claude Code, or other-MCP-speaking clients. The installers fetch a published+machine to expose the same Pulse Intelligence capability manifest+used by Pulse Assistant to OpenCode, Claude Desktop, Claude Code, or+other MCP-speaking clients. The installers fetch a published`pulse-mcp-<os>-<arch>` binary from the latest GitHub Release,verify SHA256 against the same `checksums.txt` the rest of therelease uses, and place the binary at `~/.local/bin/pulse-mcp`@@ -1169,6 +1181,98 @@ installers consume. macOS notarization is intentionally skippedfor v1: the README documents the Gatekeeper bypass and theinstall-script flow downloads the same unsigned binary, with theaudit trail of SHA256 verification preserved.+The adapter's complete request/response tool-list projection, manifest+projection, capability and governance metadata formatting, request/response+tool filtering, typed input-schema projection, and API route/body call+projection semantics remain owned by `ai-runtime` and `api-contracts`;+deployment-installability owns building, publishing, installing, and launching+the same binary. README guidance may describe the manifest-provided typed+`inputSchema` arguments that MCP clients receive, including operator-state,+finding, and action tools, but those schemas remain an API/AI contract rather+than an installer or release-asset behavior.+README and startup guidance may describe API-token setup for the installed+adapter, but the set and order of advertised token scopes must be derived from+the manifest-owned `internal/agentcapabilities.RequiredCapabilityScopeList`+helper or the README generator's Markdown projection over that helper, not from+a deployment-local hardcoded scope list. Packaging may ship that guidance, but+it must not become a second owner of which scopes the current Pulse+Intelligence surface requires.+README guidance may also describe client setup for the installed adapter, but+server name, command, base URL flag/default, token environment variable, and+supported config families must be derived from+`internal/agentcapabilities.MCPClientConfigMarkdown` over+`Manifest.MCPAdapter`, not from deployment-local OpenCode, Claude, or+`pulse-mcp` setup snippets. Packaging may ship the generated prose and+installers, but it must not become a second owner of MCP client configuration.+Patrol finding tool scopes follow the same boundary: release assets may ship+the generated guidance, but the `ai:execute` requirement for Patrol finding+review and lifecycle calls comes from the manifest/API authorization contract,+not deployment-local monitoring-scope wording.+README guidance may also describe MCP workflow prompts, but the prompt+inventory must be derived from the shared `internal/agentcapabilities`+`ProjectPulseWorkflowPrompts` / `MCPPromptInventoryMarkdown` path. Packaging+may ship the generated prose, but it must not carry a deployment-local prompt+catalog.+README guidance may also describe capability-specific stable error codes, but+the error-code inventory must be derived from the shared+`internal/agentcapabilities` manifest through `MCPErrorCodeInventoryMarkdown`.+Packaging may ship the generated prose, but it must not carry a+deployment-local error-code catalog.+The shared manifest declaration and wire type in `internal/agentcapabilities/`+follow the same split: deployment-installability may package `cmd/pulse-mcp`,+but it must not fork or reinterpret the capability schema, shared+`ProjectedTool`/`ProjectTools` projection, shared `FindCapability` /+`ResolveCapability` lookup contract, shared named capability HTTP execution,+shared structured tool schema, provider-projection helpers, schema-envelope+helper, typed action-mode, approval-policy, or stable error-code contract+locally.+The shared event vocabulary follows that same split. Deployment-installability+may document and package MCP notification support, but event names advertised+by `cmd/pulse-mcp`, the `subscribe_events` manifest description, and+transport-event filtering, SSE record parsing, SSE-to-MCP notification+bridging, and MCP notification method projection remain owned by+`internal/agentcapabilities` plus the API/AI+contracts; release/install artifacts must not carry a separate event registry+or stream parser. The same boundary owns the event-stream HTTP subscription+primitive, including the `Accept: text/event-stream` request convention and+subscribe status handling; packaging may launch `cmd/pulse-mcp` but must not+fork that transport or notification-bridge behavior into install scripts or+release artifacts.+The shared MCP JSON-RPC, request decoding, line-delimited stdio request+serving, notification response policy, stable JSON-RPC encoding,+manifest-backed tool-server semantics, tool-server method dispatch,+initialize instruction/tool-call/resource/prompt payloads, `tools/call` params decode, tool-call+parameter normalization/validation, tool-server initialize result construction,+capability lookup translation, named HTTP invocation, MCP resource URI+projection, context-backed `resources/list` / `resources/read` projection,+manifest-backed `prompts/list` / `prompts/get` workflow prompt projection, and+result envelopes follow the same boundary. Deployment-installability may+document, package, and launch+`cmd/pulse-mcp`, but protocol versions, JSON-RPC error codes,+event-notification projection, method payload JSON, initialize+operating-instruction projection, MCP content/result JSON,+request decoding, line-framing loops, JSON-RPC response serialization,+notification response policy, SSE-to-MCP notification bridging,+manifest-backed tool handlers, method dispatch, initialize response+construction, the MCP tools/call raw bridge, neutral capability tool HTTP+execution, resource URI construction, context-capability resource projection,+prompt catalog and rendering, prompt-argument validation, `HTTPCallResponse` to+shared tool-result wrapping, text/marker interpretation, and the shared rule+that trims/requires tool names while cloning/initializing argument maps must+remain owned by `internal/agentcapabilities` so the installed adapter cannot+drift from Assistant method, tool-call parameter, resource, prompt, or+tool-result execution.+The same split applies to governed Assistant tool markers: packaging may+document approval-required and policy-blocked outcomes, but marker prefixes,+payload `type` values, formatting, and parsing remain owned by+`internal/agentcapabilities`.+The shared agent HTTP substrate follows the same boundary:+deployment-installability may describe how to pass a token and base URL to the+installed adapter, but manifest fetch paths, API-token header spelling, request+content-type behavior, capability HTTP execution, request/response body-return+helpers, status-derived MCP `isError` behavior, and stable non-2xx+error-envelope formatting remain owned by+`internal/agentcapabilities`.That same installer boundary now owns instance identity for side-by-side serverinstalls too: the root `install.sh`, generated update helper, and`scripts/pulse-auto-update.sh` must preserve an explicitly selected servicediff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex 3cf83c6bdb..2b1529447e 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -9,10 +9,7 @@"contract_file": "docs/release-control/v6/internal/subsystems/frontend-primitives.md","status_file": "docs/release-control/v6/internal/status.json","registry_file": "docs/release-control/v6/internal/subsystems/registry.json",- "dependency_subsystem_ids": [- "agent-lifecycle",- "storage-recovery"- ]+ "dependency_subsystem_ids": ["agent-lifecycle", "cloud-paid", "storage-recovery"]}```@@ -29,7 +26,7 @@ work extends shared components instead of creating new local variants.4. `frontend-modern/src/components/Settings/SettingsPageShell.tsx`5. `frontend-modern/src/components/Settings/settingsPanelRegistry.ts`6. `frontend-modern/src/components/Settings/APIAccessPanel.tsx`-6a. `frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx`+ 6a. `frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx`7. `frontend-modern/src/components/Settings/AIChatMaintenanceSection.tsx`8. `frontend-modern/src/components/Settings/AIModelSelectionSection.tsx`9. `frontend-modern/src/components/Settings/AIProviderConfigurationSection.tsx`@@ -66,7 +63,7 @@ work extends shared components instead of creating new local variants.40. `frontend-modern/src/utils/systemSettingsPresentation.ts`41. `frontend-modern/src/utils/aiSettingsPresentation.ts`42. `frontend-modern/src/utils/settingsShellPresentation.ts`-42a. `frontend-modern/src/i18n/`+ 42a. `frontend-modern/src/i18n/`43. `frontend-modern/src/utils/textPresentation.ts`44. `frontend-modern/src/components/Settings/UpdateInstallGuide.tsx`45. `frontend-modern/src/components/Settings/updatesSettingsModel.ts`@@ -84,11 +81,11 @@ work extends shared components instead of creating new local variants.57. `frontend-modern/src/components/shared/FilterBar/AddFilterMenu.tsx`58. `frontend-modern/src/components/shared/FilterBar/filterCatalog.ts`59. `frontend-modern/src/components/shared/FilterBar/index.ts`-59a. `frontend-modern/src/components/shared/FilterBar/SavedViewsMenu.tsx`-59b. `frontend-modern/src/components/shared/FilterBar/useSavedViews.ts`-59c. `frontend-modern/src/components/shared/FilterBar/filterOptionPresentation.tsx`+ 59a. `frontend-modern/src/components/shared/FilterBar/SavedViewsMenu.tsx`+ 59b. `frontend-modern/src/components/shared/FilterBar/useSavedViews.ts`+ 59c. `frontend-modern/src/components/shared/FilterBar/filterOptionPresentation.tsx`60. `frontend-modern/src/components/shared/TypeColumn.guardrails.test.ts`-61. `frontend-modern/src/features/`+61. `frontend-modern/src/features/` (including Patrol presentation, where Patrol control starter counts are context only even when mirrored through `patrolAutonomy*` compatibility fields, successful direct Patrol control saves may record the content-free `patrol_control` starter only when paid control is available and the effective control posture changes and must then refresh Patrol status, findings, approvals, and run history before the operator waits for polling, legacy `proActivation*` starter aliases must not render a separate proof strip by themselves, Patrol control completed/resolved counts may only project backend-owned terminal proof, current active findings and pending approvals outrank historical completion proof in the primary operator state, selected run history must read as a Patrol run record rather than a findings filter or snapshot workflow, terminal verified/rejected outcomes with no active finding or pending approval must stay history detail without rendering a no-op proof strip, resolved-only issue history must not be promoted into current-work copy or actions, compact recurrence/trust counters must read as historical evidence rather than current issue state, Patrol-owned status/history evidence must keep the assessment visible when the broader intelligence summary is missing, the default Patrol workspace must lead with current work while run history stays a deliberate secondary review surface, setup-only Patrol runtime failures must instead use `Fix Patrol setup` framing with a dedicated setup task and direct provider-settings action while suppressing generic issue-row chips and filter chrome, Patrol must not expose a generic Details/supporting-context panel for nearby activity, related patterns, or policy limits, locked-control copy must state the watch-only boundary in positive capability language by saying Patrol watches infrastructure and shows current issues, avoid repeating the same sentence across the header and control, and avoid repeatedly restating infrastructure-unchanged caveats or relying on disabled controls, compact Pro badges, Limits controls, or manual-review framing, `patrolControlValueState` decides whether a terminal decision is partial review context or verified value proof while `patrolAutonomyValueState` remains a compatibility mirror, legacy `proActivation*` fields are compatibility fallback only, native Patrol state must not load the operations-loop status projection to decide current work, local Patrol state must expose issue-backed `patrolWork*` evidence rather than legacy proof naming, Patrol mode labels remain domain copy that must describe backend-owned risk policy without creating page-local safety thresholds, the Patrol schedule and model drawer must stay separate from the always-visible Patrol mode selector instead of duplicating the four control choices or reintroducing save/apply configuration framing, and Patrol header refresh controls must call an explicit operator-refresh handler whose spinning/disabled state is separate from background polling and initial data loads)62. `frontend-modern/src/components/SetupWizard/SetupWizard.tsx`63. `frontend-modern/src/components/Settings/useSettingsInfrastructurePanelProps.ts`64. `frontend-modern/src/components/SetupWizard/SetupCompletionPreview.tsx`@@ -144,8 +141,8 @@ work extends shared components instead of creating new local variants.114. `frontend-modern/src/components/shared/useUpgradeNavigation.ts`115. `frontend-modern/src/utils/upgradeNavigation.ts`116. `frontend-modern/src/components/DemoBanner.tsx`-116a. `frontend-modern/src/components/CommercialMigrationBanner.tsx`-116b. `frontend-modern/src/components/GitHubStarBanner.tsx`+ 116a. `frontend-modern/src/components/CommercialMigrationBanner.tsx`+ 116b. `frontend-modern/src/components/GitHubStarBanner.tsx`117. `frontend-modern/src/components/Login.tsx`118. `frontend-modern/src/stores/sessionCapabilities.ts`119. `frontend-modern/src/stores/sessionPresentationPolicy.ts`@@ -161,9 +158,9 @@ work extends shared components instead of creating new local variants.129. `frontend-modern/scripts/shared-template-audit.mjs`130. `frontend-modern/scripts/shared-template-registry.json`131. `frontend-modern/src/features/platformPage/sharedPlatformPage.tsx`-131a. `frontend-modern/src/features/platformPage/PlatformResourceDetailTableRow.tsx`-131b. `frontend-modern/src/features/platformPage/PlatformOutdatedAgentNotice.tsx`-131c. `frontend-modern/src/features/platformPage/PlatformOutdatedSensorSetupNotice.tsx`+ 131a. `frontend-modern/src/features/platformPage/PlatformResourceDetailTableRow.tsx`+ 131b. `frontend-modern/src/features/platformPage/PlatformOutdatedAgentNotice.tsx`+ 131c. `frontend-modern/src/features/platformPage/PlatformOutdatedSensorSetupNotice.tsx`132. `frontend-modern/src/utils/platformSupportManifest.generated.ts`133. `frontend-modern/src/utils/platformSupportManifest.ts`134. `frontend-modern/src/utils/sourcePlatformOptions.ts`@@ -172,10 +169,10 @@ work extends shared components instead of creating new local variants.137. `frontend-modern/src/components/shared/Button.tsx`138. `frontend-modern/src/components/shared/buttonModel.ts`139. `frontend-modern/src/components/shared/Button.test.tsx`-139a. `frontend-modern/src/components/shared/InlineNotice.tsx`-139b. `frontend-modern/src/components/shared/InlineNotice.test.tsx`-139c. `frontend-modern/src/components/shared/ExternalTextLink.tsx`-139d. `frontend-modern/src/components/shared/ExternalTextLink.test.tsx`+ 139a. `frontend-modern/src/components/shared/InlineNotice.tsx`+ 139b. `frontend-modern/src/components/shared/InlineNotice.test.tsx`+ 139c. `frontend-modern/src/components/shared/ExternalTextLink.tsx`+ 139d. `frontend-modern/src/components/shared/ExternalTextLink.test.tsx`140. `frontend-modern/src/components/shared/CopyableCodeRow.tsx`141. `frontend-modern/src/components/shared/DetailSectionTable.tsx`142. `frontend-modern/src/components/shared/detailSectionModel.ts`@@ -184,6 +181,13 @@ work extends shared components instead of creating new local variants.## Shared Boundaries+Settings navigation discoverability is part of the shared settings-shell+boundary. A settings route that is available in normal commercial presentation+must be reachable through the sidebar unless it is explicitly a hidden+deep-link flow. The self-hosted `Plans` page is not a deep-link-only flow:+`system-billing` stays visible whenever commercial presentation is allowed,+while demo or commercial-suppressed sessions may still hide it.+Frontend localization is a shared primitive boundary. Locale support must flowthrough typed message catalogs with an English fallback and explicit seedlocale coverage rather than page-local string switches.@@ -198,9 +202,20 @@ settings, first-run, empty-state, and alert copy may be localized, butmachine-facing values must remain stable: commands, environment variables, APIfields, config keys, log lines, error codes, hostnames, resource names, productidentifiers, and vendor object names stay untranslated unless the owning-runtime contract explicitly says otherwise. Migrated settings surfaces must-render customer-facing copy through the catalog and shared presentation helpers-rather than reintroducing panel-local English. Migrated first-session surfaces,+runtime contract explicitly says otherwise. Shared settings-shell header copy+for the self-hosted plan must keep first-wave locale catalogs aligned with the+English product stance: on Pro, the operator chooses how autonomous Patrol+should be. The settings shell must not teach a separate activation loop, MCP+readiness, or operations-loop proof model as the default plan setup story.+Pulse Intelligence external-agent setup uses the same shell language with a+`Choose Patrol mode` handoff before scoped-token setup, and the expanded setup+checklist must say to set how autonomous Patrol should be before connected+agents request work rather than repeating internal automation/proof wording.+Developer-only external-agent posture uses `External agents` plus Patrol mode+before surfacing MCP or workflow prompt wire names.+Migrated settings surfaces must render customer-facing copy through the catalog+and shared presentation helpers rather than reintroducing panel-local English.+Migrated first-session surfaces,including the Setup Wizard shell, welcome/security steps, setup completionhandoff, and runtime-home loading handoff, follow the same catalog path; theirguardrails must fail if the migrated journey returns to page-local English or@@ -385,88 +400,183 @@ attention/running/other filters so large bridge or overlay networks remainscan-friendly without hiding any container from drilldown.1. `frontend-modern/src/components/CommercialMigrationBanner.tsx` shared with `cloud-paid`: the global commercial migration notice is both a cloud-paid entitlement recovery surface and a shared app-shell notice primitive consumer.-2. `frontend-modern/src/components/Settings/APIAccessPanel.tsx` shared with `security-privacy`: the API Access settings intro is both a security/privacy token-management trust surface and a canonical settings-shell presentation boundary.+2. `frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx` shared with `ai-runtime`, `api-contracts`: the External agents settings panel is the optional settings-shell projection of Pulse MCP onboarding, the AI runtime connected-agent onboarding surface, and a presentation consumer of the shared agent capabilities frontend client.+3. `frontend-modern/src/components/Settings/APIAccessPanel.tsx` shared with `security-privacy`: the API Access settings intro is both a security/privacy token-management trust surface and a canonical settings-shell presentation boundary.The panel may own shell placement and local action layout, buttoken-specific Docker / Podman copy must come from`frontend-modern/src/utils/apiTokenPresentation.ts` rather than page-localtext.-3. `frontend-modern/src/components/Settings/DataHandlingPanel.tsx` shared with `security-privacy`: the data-handling settings surface is both a security/privacy trust surface and a canonical settings-shell presentation boundary.-4. `frontend-modern/src/components/Settings/dataHandlingPanelModel.ts` shared with `security-privacy`: the data-handling settings model is both a security/privacy posture projection and a canonical settings-shell presentation boundary.-5. `frontend-modern/src/components/Settings/GeneralSettingsPanel.tsx` shared with `security-privacy`: the general settings privacy panel is both a security/privacy control surface and a canonical settings-shell presentation boundary.+ `frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx` stays+ under Pulse Intelligence Assistant settings because connected agents are an+ optional access path to Patrol work, while API Access remains the token+ minting surface linked from setup. Its setup copy must present one shared+ `pulse-mcp` runtime contract with client-native wrappers: OpenCode's top-level+ `opencode.json` / `mcp` shape and the common `mcpServers` shape for+ Claude-style clients. The server name, command, base URL flag/default,+ token environment variable, supported config families, and copied config+ snippets must flow through `frontend-modern/src/api/agentCapabilities.ts`+ from `/api/agent/capabilities.mcpAdapter`; the component may arrange and+ label them, but must keep setup mechanics, raw client config snippets, and+ developer details behind deliberate disclosures so the default Assistant+ settings view stays focused on chat command access and optional external+ access rather than raw JSON. External-agent posture should present+ `External agents` as the visible surface and reserve `Pulse MCP` or+ `pulse_operations_loop` for wire-name/debugging detail. The Patrol control handoff must route to the+ Patrol operator surface where the inline control level is configured. When+ setup is opened, the setup order must put Patrol control before scoped-token+ creation and client connection, while installer commands, client config+ snippets, and developer details remain deliberate disclosures.+ It must not frame+ Pulse MCP as a Claude-only surface, force OpenCode through a Claude-style+ wrapper, or duplicate a client-specific tool list. Full-surface token guidance in that panel must render the manifest-provided+ `requiredScopes` list through+ `frontend-modern/src/api/agentCapabilities.ts`; it must not hardcode a+ partial scope set in browser copy. Capability category order, labels, and+ descriptions must also come from the same manifest client; the settings+ panel may provide compatibility fallback rendering through that client, but+ it must not own a local category presentation table or+ `/api/agent/capabilities` fetcher. The panel's Pulse Intelligence surface+ summary is the same manifest projection: Pulse Intelligence Core, Patrol,+ Assistant, and MCP labels/descriptions plus surface affordance badges must flow through+ `frontend-modern/src/api/agentCapabilities.ts` from+ `/api/agent/capabilities.surfaceContract`, leaving the component to own only+ settings-shell layout. The visible external-adapter label in onboarding copy+ must also come from that manifest-derived capability posture instead of a+ hard-coded panel-local product label, so the settings shell cannot drift from+ the published agent surface contract. MCP capability-posture chips in that same panel must also+ flow through `getAgentManifestSurfaceToolContract(manifest,+AGENT_SURFACE_ID_PULSE_MCP)` and `getAgentSurfaceToolPosturePresentation`,+ with the static inventory read only from+ `/api/agent/capabilities.surfaceToolContracts`; missing+ `surfaceToolContracts` entries must not make the browser infer MCP tools+ from raw capabilities. The panel must not own request / response capability+ filtering, call a per-surface projection alias, know the `subscribe_events`+ streaming exception, or maintain a local MCP tool count. The shared frontend+ manifest client must keep MCP onboarding on the generic surface resolver+ rather than exporting a Pulse-MCP-specific tool-contract helper. The panel's+ settings shell may arrange the external-agent setup hierarchy, but it must+ keep connected agents framed as optional access to Pulse context and Patrol+ work, with Patrol as the built-in operator that watches, acts within Patrol+ mode, asks when approval is required, verifies outcomes, and records+ history, state that external agents use that same boundary, and make the canonical+ `/settings/pulse-intelligence/assistant#external-agent-setup` route land on+ and briefly focus this panel with setup open rather than leaving the user at+ the generic API token inventory. Legacy `/settings/security/api#external-agent-setup` and+ `/settings/security/api#pulse-mcp-setup` links must remain accepted and may+ redirect to the canonical Pulse Intelligence Assistant route. Normal API+ Access visits remain token-management first, and external-agent setup must+ not reorder the API token inventory because it no longer lives on that page.+ The Assistant settings default must keep setup mechanics behind a `Show connector setup`+ disclosure so it does not introduce a separate external-agent operator+ journey or make copied MCP config blocks or tool-contract proof badges the+ default visual weight of Pulse Intelligence settings. Its Developer details+ disclosure may show posture and policy summaries behind Patrol+ access model, but prompt, scope, failure-code, and tool inventories must sit+ behind a nested Live manifest details disclosure so the advanced surface+ remains navigable. The panel's+ manifest-owned `pulse_operations_loop` prompt row may expose the stable+ prompt id for client builders, but its visible label, description, and badge+ must keep the user-facing Patrol framing from the manifest instead+ of reintroducing operations-loop proof wording in the settings shell. The panel's+ explanatory onboarding copy must name published manifest-owned surface+ contracts as the publication boundary rather than suggesting raw backend+ capabilities become visible automatically.+ The visible token preset name in that setup must be `Patrol external agent`,+ not `Pulse Intelligence agent`; the latter may survive only as a route/model+ compatibility id.+ Manifest-backed stable failure-code+ summaries may use settings-shell chips or compact lists, but code selection+ and capability attribution stay owned by the API manifest client. Token+ setup handoff buttons or anchors in+ the Agent integrations panel are settings-shell chrome only: they may route+ to the API Access token creation section, but token preset semantics and+ required-scope derivation remain owned by the API/security boundary.+4. `frontend-modern/src/components/Settings/DataHandlingPanel.tsx` shared with `security-privacy`: the data-handling settings surface is both a security/privacy trust surface and a canonical settings-shell presentation boundary.+5. `frontend-modern/src/components/Settings/dataHandlingPanelModel.ts` shared with `security-privacy`: the data-handling settings model is both a security/privacy posture projection and a canonical settings-shell presentation boundary.+6. `frontend-modern/src/components/Settings/GeneralSettingsPanel.tsx` shared with `security-privacy`: the general settings privacy panel is both a security/privacy control surface and a canonical settings-shell presentation boundary.The panel owns compact settings-shell framing for anonymous telemetry, butits vocabulary must stay aligned with `security-privacy`: aggregate- self-hosted adoption counts and coarse feature flags may be named, while+ self-hosted adoption counts, coarse feature flags, and coarse Patrol,+ Assistant, and external-agent usage counters may be named, whilehostnames, credentials, infrastructure identifiers, prompts, chat messages,- and personal information must stay explicitly excluded.-6. `frontend-modern/src/components/Settings/SecurityAuthPanel.tsx` shared with `security-privacy`: the authentication settings surface is both a security/privacy control surface and a canonical settings-shell presentation boundary.-7. `frontend-modern/src/components/Settings/SecurityOverviewPanel.tsx` shared with `security-privacy`: the security overview settings surface is both a security/privacy control surface and a canonical settings-shell presentation boundary.-8. `frontend-modern/src/routing/routePreload.ts` shared with `performance-and-scalability`: the app-shell route preload registry is both a canonical frontend shell boundary and an authenticated hot-path performance boundary.-9. `frontend-modern/src/stores/aiChat.ts` shared with `ai-runtime`: the assistant drawer and session store is both an AI runtime control surface and a canonical app-shell presentation boundary.- Assistant session pickers and reloads must restore only safe- `handoff_summary` presentation state from the session list. Loading a plain- session or starting a new conversation must clear stale scoped handoff- briefing state so Patrol and alert context does not visually leak between- conversations. Browser-originated model handoff payloads are one-shot- request seeds: after the first successful chat send, this store must clear- `handoffContext`, `handoffResources`, `handoffActions`, and safe- `handoffMetadata` while preserving the safe visible briefing and scoped- approval-required posture, so later turns rely on backend session hydration- instead of resending stale browser context. Patrol handoffs must not include- Persisted Assistant redo availability is safe session chrome, not transcript- content. The drawer may consume `ChatSession.can_redo` from the backend- session list to re-enable Redo after reload or session refresh, but it must- not read or duplicate the redo stack in frontend state. Undo restores the- editable prompt draft and safe structured send metadata into the composer;- Redo clears that recovered draft only after the backend restores the turn.- Patrol handoffs must not include- safe next-step labels, action kinds, or whitelisted app-route hrefs in- `handoffMetadata`; the drawer must treat- `handoff_summary.requires_approval` as a current pending-decision flag, not a- historical action marker, so completed or rejected handoff actions render as- action context rather than pending approval. A restored Patrol run summary- must remain visibly sourced to Pulse Patrol, restore a `patrol-run` target- plus run ID/type/status/runtime-failure presentation only, and must not- rehydrate model-only runtime failure detail into browser context. New Patrol- run requests follow the same drawer boundary: source-owned context and- briefing copy may show classified, redacted failure summaries for operator- review, but `handoffContext`, `handoffResources`, and `handoffActions` for- run-history context must stay absent from the browser request so the backend- can rebuild model-bound context from the stored Patrol run. Restored- Patrol assessment, Patrol finding, and Patrol configuration-failure sessions- follow the same safe-summary rule: the drawer may restore source label,- title, target type, status badge, bounded resource facts, and approval/action- status from `handoff_summary`, but- it must not infer a finding target from bounded action references or- reconstruct hidden model context, provider details, retry payloads, commands,- preflight output, or action results in the browser. If the safe summary- was created by a legacy build that stored Patrol next-step metadata,- recommendation detail, action labels, safe action kind, or whitelisted- app-route href, the session picker plus restored drawer must ignore those- fields rather than carrying them forward as hidden context or visible- recommendation copy.- Session-load and new-conversation transitions must be success-bound: if the- underlying session operation fails, the shared drawer store must not clear or- replace the current scoped handoff context.- Live Patrol assessment drawer opens must use that same- `patrol-assessment`/`pulse-patrol-assessment` target identity rather than a- retired dashboard target, so first-open and restored-session chrome remain- source-named.- The shared `frontend-modern/src/components/shared/AIModelPicker.tsx`- primitive must keep model route presentation delegated to the AI runtime- label helpers. Pulse-owned local Assistant routes such as- `pulse:local-inventory` and `pulse:mock-assistant` are implementation- routes and must render as named choices without secondary raw route IDs,- while external provider route IDs may remain visible where they disambiguate- catalog entries.-10. `frontend-modern/src/utils/platformSupportManifest.generated.ts` shared with `unified-resources`: the generated platform support projection is both a canonical unified-resource platform union boundary and a shared frontend source/platform vocabulary boundary.- It must expose the manifest `surface_kind` field so runtime lenses such as- `docker` are not collapsed back into owning platform semantics.- It must also preserve canonical projection lists from the governed manifest- without page-local narrowing; for example, TrueNAS exposes both native- `vm`, `network-share`, and `app-container` workloads through the same- generated platform projection used by route helpers, badges, source- filters, reportable-resource pickers, and type unions.-11. `frontend-modern/src/utils/sourcePlatforms.ts` shared with `unified-resources`: the source platform normalizer is both a canonical unified-resource source adapter boundary and a shared frontend source/platform vocabulary boundary.+ command text, action output, token values, and personal information must+ stay explicitly excluded.+7. `frontend-modern/src/components/Settings/SecurityAuthPanel.tsx` shared with `security-privacy`: the authentication settings surface is both a security/privacy control surface and a canonical settings-shell presentation boundary.+8. `frontend-modern/src/components/Settings/SecurityOverviewPanel.tsx` shared with `security-privacy`: the security overview settings surface is both a security/privacy control surface and a canonical settings-shell presentation boundary.+9. `frontend-modern/src/routing/routePreload.ts` shared with `performance-and-scalability`: the app-shell route preload registry is both a canonical frontend shell boundary and an authenticated hot-path performance boundary.+10. `frontend-modern/src/stores/aiChat.ts` shared with `ai-runtime`: the assistant drawer and session store is both an AI runtime control surface and a canonical app-shell presentation boundary.+ Assistant session pickers and reloads must restore only safe+ `handoff_summary` presentation state from the session list. Loading a plain+ session or starting a new conversation must clear stale scoped handoff+ briefing state so Patrol and alert context does not visually leak between+ conversations. Browser-originated model handoff payloads are one-shot+ request seeds: after the first successful chat send, this store must clear+ `handoffContext`, `handoffResources`, `handoffActions`, and safe+ `handoffMetadata`; it must also clear any preferred workflow prompt request+ once the manifest-rendered starter has seeded the composer and the first+ scoped send succeeds. The store must preserve the safe visible briefing and+ scoped approval-required posture, so later turns rely on backend session+ hydration instead of resending stale browser context. Patrol handoffs must not include+ Persisted Assistant redo availability is safe session chrome, not transcript+ content. The drawer may consume `ChatSession.can_redo` from the backend+ session list to re-enable Redo after reload or session refresh, but it must+ not read or duplicate the redo stack in frontend state. Undo restores the+ editable prompt draft and safe structured send metadata into the composer;+ Redo clears that recovered draft only after the backend restores the turn.+ Browser-owned session-management comments, command request handling, and+ question-answer plumbing in this store and the adjacent chat hook must name+ the native drawer surface as Pulse Assistant rather than reviving the+ retired generic `Pulse AI` label. Shared model/provider settings guidance+ still belongs to Pulse Intelligence > Provider & Models.+ Patrol handoffs must not include+ safe next-step labels, action kinds, or whitelisted app-route hrefs in+ `handoffMetadata`; the drawer must treat+ `handoff_summary.requires_approval` as a current pending-decision flag, not a+ historical action marker, so completed or rejected handoff actions render as+ action context rather than pending approval. A restored Patrol run summary+ must remain visibly sourced to Pulse Patrol, restore a `patrol-run` target+ plus run ID/type/status/runtime-failure presentation only, and must not+ rehydrate model-only runtime failure detail into browser context. New Patrol+ run requests follow the same drawer boundary: source-owned context and+ briefing copy may show classified, redacted failure summaries for operator+ review, but `handoffContext`, `handoffResources`, and `handoffActions` for+ run-history context must stay absent from the browser request so the backend+ can rebuild model-bound context from the stored Patrol run. Restored+ Patrol assessment, Patrol finding, and Patrol control save-failure sessions+ follow the same safe-summary rule: the drawer may restore source label,+ title, target type, status badge, bounded resource facts, and approval/action+ status from `handoff_summary`, but+ it must not infer a finding target from bounded action references or+ reconstruct hidden model context, provider details, retry payloads, commands,+ preflight output, or action results in the browser. If the safe summary+ was created by a legacy build that stored Patrol next-step metadata,+ recommendation detail, action labels, safe action kind, or whitelisted+ app-route href, the session picker plus restored drawer must ignore those+ fields rather than carrying them forward as hidden context or visible+ recommendation copy.+ Session-load and new-conversation transitions must be success-bound: if the+ underlying session operation fails, the shared drawer store must not clear or+ replace the current scoped handoff context.+ Live Patrol assessment drawer opens must use that same+ `patrol-assessment`/`pulse-patrol-assessment` target identity rather than a+ retired dashboard target, so first-open and restored-session chrome remain+ source-named.+ The shared `frontend-modern/src/components/shared/AIModelPicker.tsx`+ primitive must keep model route presentation delegated to the AI runtime+ label helpers. Pulse-owned local Assistant routes such as+ `pulse:local-inventory` and `pulse:mock-assistant` are implementation+ routes and must render as named choices without secondary raw route IDs,+ while external provider route IDs may remain visible where they disambiguate+ catalog entries.+11. `frontend-modern/src/utils/platformSupportManifest.generated.ts` shared with `unified-resources`: the generated platform support projection is both a canonical unified-resource platform union boundary and a shared frontend source/platform vocabulary boundary.+ It must expose the manifest `surface_kind` field so runtime lenses such as+ `docker` are not collapsed back into owning platform semantics.+ It must also preserve canonical projection lists from the governed manifest+ without page-local narrowing; for example, TrueNAS exposes both native+ `vm`, `network-share`, and `app-container` workloads through the same+ generated platform projection used by route helpers, badges, source+ filters, reportable-resource pickers, and type unions.+12. `frontend-modern/src/utils/sourcePlatforms.ts` shared with `unified-resources`: the source platform normalizer is both a canonical unified-resource source adapter boundary and a shared frontend source/platform vocabulary boundary.That shared boundary must preserve `availability` as the agentlessmonitoring source for `network-endpoint` resources and settings presets,so source badges and platform/source type resolution do not fall back to@@ -488,6 +598,27 @@ Feature surfaces under `frontend-modern/src/features/` may own product-specificassessment semantics, but they must keep those semantics in their governedpresentation helpers and render them inside the shared neutral Pulse surfacelanguage rather than introducing page-local verdict bands or nested cards.+Feature-owned runtime hooks may also own non-visual side effects when those+effects are part of the governed feature workflow. For Patrol, current-work+action chrome must keep active findings in the Patrol findings workflow first;+Assistant handoffs stay contextual actions on selected findings, approvals, or+history records rather than the primary current-work CTA. When provider/model+readiness blocks manual Patrol, the feature header must render the shared+primary-action chrome as a Provider & Models setup link instead of a disabled+run button that looks primary but cannot act. The Patrol hook owns the+content-free `pulse_operations_loop` starter marker so render components do not+fork telemetry or privacy behavior.+When the shared operations-loop status projection reports contextual+Assistant/external-agent collaboration inside the Assistant step, Assistant or+Pulse MCP starter counts, Patrol control starter evidence, or Patrol control+completed-loop or resolved-loop proof, feature presentation helpers may render+those facts as compact title or step detail inside the existing journey layout.+They must read primary `patrolControl*` fields first, then fall back to legacy+`patrolAutonomy*` compatibility fields, and may fall back to legacy+`proActivation*` fields only when the Patrol-control projections are absent.+They must keep the neutral shared surface chrome stable and must not add+page-local badges, nested cards, or alternate progress widgets for the same+evidence.Feature-owned table drawers use shared disclosure and inline-detail primitivesas local interaction state. Unless a surface has a separately governed deep-linkwrite contract, opening or closing a row drawer must preserve the current@@ -603,6 +734,10 @@ not a replacement status card, CTA band, or page-local nested card.entitlement state, and click handlers, while `Button`, `ButtonLink`, and`UpgradeButtonLink` own the primary, outline, warning, and upgrade/linkchrome.+ Manual self-hosted key recovery is a secondary detail in that same boundary:+ settings surfaces may expose the fallback, but they must label it as license+ recovery/key recovery and keep normal checkout plus the Pro Patrol-mode setup+ path ahead of recovery mechanics or activation-key terminology.Hosted billing admin organization row actions follow the same boundary:cloud-paid surfaces own Suspend, Activate, Reload, tenant state, and mutationsemantics, while `Button` owns the row-action chrome through the secondary@@ -749,11 +884,11 @@ not a replacement status card, CTA band, or page-local nested card.Native select state belongs to the shared`frontend-modern/src/components/shared/FormSelect.tsx` primitive. It mustapply controlled `value` props after options are mounted so settings panels- such as workload discovery show the persisted option instead of falling back+ such as Discovery show the persisted option instead of falling backto the first option while the collapsed summary shows a different value.The Assistant runtime controls in`frontend-modern/src/components/Settings/AIRuntimeControlsSection.tsx` — e.g. the- workload discovery `Toggle` — are settings-shell chrome bound to the canonical+ service context scan `Toggle` — are settings-shell chrome bound to the canonical`useAISettingsState` form and `/api/settings/ai` payload, not local browserstate. Each must bind to a `state.form.*` field, round-trip through thefield-by-field settings payload, and source its label, help, and summary copy@@ -761,7 +896,7 @@ not a replacement status card, CTA band, or page-local nested card.strings or reaching for a bespoke fetch outside the canonical payload. There isno cloud-context-privacy control here: cloud context behavior is a fixed posture(see `ai-runtime`), not an operator setting.-3. Add feature-specific presentation only when no shared primitive should own it.+2. Add feature-specific presentation only when no shared primitive should own it.Feature surfaces under `frontend-modern/src/features/` that displayproduct labels must consume the owning subsystem's presentation utilitiesrather than hard-coding divergent page-local copy. Shared primitives and@@ -830,7 +965,7 @@ not a replacement status card, CTA band, or page-local nested card.hard-to-scan strip. Narrow consumers such as`ColumnPicker` must opt into their panel width through that primitive ratherthan layering competing width classes page by page.-4. Add guardrail tests when a new shared pattern is introduced.+3. Add guardrail tests when a new shared pattern is introduced.Shared monitored-system primitives must prove they remain informationalgrouping or ledger surfaces rather than admission-freeze banners, capsummaries, or `current / limit` quota math.@@ -848,7 +983,7 @@ not a replacement status card, CTA band, or page-local nested card.from a platform-owned product surface such as a recovery tab, the firsthighlighted step should match that route instead of always restarting atDashboard.-5. Keep shared infrastructure shell state on the reusable settings boundary: `frontend-modern/src/components/Settings/useSettingsInfrastructurePanelProps.ts` and `frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx` must continue to derive provider counts and shared subtab copy from one infrastructure-settings source — via the unified aggregator through `frontend-modern/src/components/Settings/useConnectionsLedger.ts` — instead of creating provider-local summary fetches or VMware-only shell vocabulary. Phase 9 retired the old `PlatformConnectionsWorkspace` per-type shell; setup guidance should now use `Add infrastructure` plus source-strategy language for API-backed onboarding. The standalone connections-table presenter is retired; `frontend-modern/src/components/Settings/InfrastructureSourceManager.tsx` is the only landing-ledger presenter for configured infrastructure rows, and it must exclude agentless availability probes because those belong to `frontend-modern/src/components/Settings/AvailabilitySettingsPanel.tsx`.+4. Keep shared infrastructure shell state on the reusable settings boundary: `frontend-modern/src/components/Settings/useSettingsInfrastructurePanelProps.ts` and `frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx` must continue to derive provider counts and shared subtab copy from one infrastructure-settings source — via the unified aggregator through `frontend-modern/src/components/Settings/useConnectionsLedger.ts` — instead of creating provider-local summary fetches or VMware-only shell vocabulary. Phase 9 retired the old `PlatformConnectionsWorkspace` per-type shell; setup guidance should now use `Add infrastructure` plus source-strategy language for API-backed onboarding. The standalone connections-table presenter is retired; `frontend-modern/src/components/Settings/InfrastructureSourceManager.tsx` is the only landing-ledger presenter for configured infrastructure rows, and it must exclude agentless availability probes because those belong to `frontend-modern/src/components/Settings/AvailabilitySettingsPanel.tsx`.The first-run setup wizard inherits that same source-strategy vocabulary:step labels and completion copy must frame the final setup step as choosingthe first infrastructure source, not installing a host. Successful token@@ -862,7 +997,7 @@ not a replacement status card, CTA band, or page-local nested card.and no redundant monitored-systems ledger beneath it. The landing route mayinclude a dedicated first-viewport toolbar that explains platform APIs andPulse Agent telemetry as infrastructure sources and exposes `Add- infrastructure`, `Run discovery`, and `Discovery settings` inside the+infrastructure`, `Run discovery`, and `Discovery settings` inside thesource manager. Per-source add actions, including `Install Pulse Agent`,belong on the governed source rows, and `Detect address` stays inside thesingle API-platform probe path instead of a duplicate toolbar action. It may@@ -890,7 +1025,7 @@ not a replacement status card, CTA band, or page-local nested card.`useConnectionsLedger.ts`, `InfrastructureSourceManager.tsx`, and`InfrastructureWorkspace.tsx` must render attached collection methods as aplain-language row subtitle on the owning row (`via platform API`, `via- Pulse Agent`, or `via platform API and Pulse Agent`), with fuller detail in+Pulse Agent`, or `via platform API and Pulse Agent`), with fuller detail inthe edit dialog, instead of duplicating the same machine across multiplepeer groups or forcing operators to decode badge jargon.The table-level product/system group rows in@@ -923,7 +1058,7 @@ not a replacement status card, CTA band, or page-local nested card.that destination. `InfrastructureSourceManager.tsx` exposes one Networkdiscovery status/action band from the shared landing shell with scan state,saved scope, last result metadata, errors, `Run discovery`, `Discovery- settings`, and candidate review when discovered sources are waiting. It must+settings`, and candidate review when discovered sources are waiting. It mustnot start a network scan just because the page rendered. New-sourceadmission belongs on the table's per-platform `Add` actions, the compactfirst-run/readiness actions, or the discovery band's explicit review action,@@ -1027,8 +1162,8 @@ not a replacement status card, CTA band, or page-local nested card.become the primary top-level system wording when a provider/API platform orreported host OS/appliance identity better explains what the operator islooking at.-6. Keep Proxmox deep-link route selection on the shared settings-navigation boundary. `frontend-modern/src/components/Settings/settingsNavigationModel.ts` and `frontend-modern/src/components/Settings/useSettingsNavigation.ts` must treat the canonical PBS and PMG Proxmox deep links as agent-selection authority even though those URLs resolve to the shared `infrastructure-operations` tab. Reloading or remounting on a PBS or PMG deep link must not silently fall back to the PVE selector state.-7. Keep shared storage feature presenters on canonical platform truth. When reusable storage presenters under `frontend-modern/src/features/storageBackups/` classify canonical resources for the shared storage route, API-backed virtualization datastores such as VMware must stay inventory-only datastores instead of inheriting PBS-specific backup-repository or protected-target copy from older fallback branches.+5. Keep settings deep-link route selection on the shared settings-navigation boundary. `frontend-modern/src/components/Settings/settingsNavigationModel.ts` and `frontend-modern/src/components/Settings/useSettingsNavigation.ts` must treat the canonical PBS and PMG Proxmox deep links as agent-selection authority even though those URLs resolve to the shared `infrastructure-operations` tab. Reloading or remounting on a PBS or PMG deep link must not silently fall back to the PVE selector state. Assistant OAuth callback compatibility queries such as `ai_oauth_error` and `ai_oauth_success` must route the bare settings root to Pulse Intelligence > Provider & Models while preserving the query long enough for `useAISettingsState` to consume and clear it, rather than normalizing the user back to Infrastructure and dropping the callback result.+6. Keep shared storage feature presenters on canonical platform truth. When reusable storage presenters under `frontend-modern/src/features/storageBackups/` classify canonical resources for the shared storage route, API-backed virtualization datastores such as VMware must stay inventory-only datastores instead of inheriting PBS-specific backup-repository or protected-target copy from older fallback branches.Those reusable storage presenters must also keep primary issue copy separatefrom contextual impact copy. Composite posture fields may include dependentresource or protected workload impact, but shared table/presenter primitives@@ -1083,7 +1218,7 @@ not a replacement status card, CTA band, or page-local nested card.Jobs, and CronJobs, including targets, active/current counts,ready/succeeded counts, availability, exceptions, service names, schedules,and last run metadata.-8. Keep shared source/platform vocabulary on the governed manifest boundary. `frontend-modern/src/utils/platformSupportManifest.generated.ts` must be the tracked frontend projection of `docs/release-control/v6/internal/PLATFORM_SUPPORT_MANIFEST.json`, `frontend-modern/src/utils/platformSupportManifest.ts`, `frontend-modern/src/utils/sourcePlatforms.ts`, and `frontend-modern/src/utils/sourcePlatformOptions.ts` must consume that generated projection instead of embedding divergent future-label lists, setup/onboarding path allowlists, host-profile labels, surface-kind guesses, readiness-state guesses, or presentation-only guesses, and `frontend-modern/scripts/canonical-platform-audit.mjs` must fail when the generated projection drifts from the governed manifest. The generated governance/readiness split is authoritative: supported platform arrays drive current support claims, while admitted platform arrays may keep route/navigation and add-flow vocabulary available without turning `first-lab-ready` entries such as VMware into supported-source copy. Kubernetes manifest projections must enumerate the native API-backed page sections the shared tab shell can expose, including controllers, networking, storage, config, policy, autoscaling, and events, so platform pages do not invent local support claims outside the governed JSON. The generated `surface_kind` is the machine-readable boundary between owning platform entries and runtime lenses: `docker` is a `runtime-lens`, not a `platform`, even when the container-runtime route stays available as a primary shell destination. The generic `docker` source-platform label is "Docker / Podman" in shared selectors, badges, and filter options so v5 Docker users can find the runtime surface while Podman-backed rows are not mislabeled as Docker-only; "Container runtime" remains the governed runtime family, not the primary customer-facing label. Identity colour is semantic, not page-local decoration: shared source/platform badges, host identity badges, and container runtime badges must use the shared presentation helpers so Docker remains on the Docker/Podman blue runtime tone, Podman uses its distinct runtime tone, Proxmox PVE remains orange, and those meanings do not drift across table rows, filters, drawers, or platform pages. Agent host-profile entries, including Unraid, stay in the generated `agentHostProfiles` projection and shared wrapper helpers; frontend primitives may render those labels for Pulse Agent install/identity copy but must not add them to the first-class platform union.+7. Keep shared source/platform vocabulary on the governed manifest boundary. `frontend-modern/src/utils/platformSupportManifest.generated.ts` must be the tracked frontend projection of `docs/release-control/v6/internal/PLATFORM_SUPPORT_MANIFEST.json`, `frontend-modern/src/utils/platformSupportManifest.ts`, `frontend-modern/src/utils/sourcePlatforms.ts`, and `frontend-modern/src/utils/sourcePlatformOptions.ts` must consume that generated projection instead of embedding divergent future-label lists, setup/onboarding path allowlists, host-profile labels, surface-kind guesses, readiness-state guesses, or presentation-only guesses, and `frontend-modern/scripts/canonical-platform-audit.mjs` must fail when the generated projection drifts from the governed manifest. The generated governance/readiness split is authoritative: supported platform arrays drive current support claims, while admitted platform arrays may keep route/navigation and add-flow vocabulary available without turning `first-lab-ready` entries such as VMware into supported-source copy. Kubernetes manifest projections must enumerate the native API-backed page sections the shared tab shell can expose, including controllers, networking, storage, config, policy, autoscaling, and events, so platform pages do not invent local support claims outside the governed JSON. The generated `surface_kind` is the machine-readable boundary between owning platform entries and runtime lenses: `docker` is a `runtime-lens`, not a `platform`, even when the container-runtime route stays available as a primary shell destination. The generic `docker` source-platform label is "Docker / Podman" in shared selectors, badges, and filter options so v5 Docker users can find the runtime surface while Podman-backed rows are not mislabeled as Docker-only; "Container runtime" remains the governed runtime family, not the primary customer-facing label. Identity colour is semantic, not page-local decoration: shared source/platform badges, host identity badges, and container runtime badges must use the shared presentation helpers so Docker remains on the Docker/Podman blue runtime tone, Podman uses its distinct runtime tone, Proxmox PVE remains orange, and those meanings do not drift across table rows, filters, drawers, or platform pages. Agent host-profile entries, including Unraid, stay in the generated `agentHostProfiles` projection and shared wrapper helpers; frontend primitives may render those labels for Pulse Agent install/identity copy but must not add them to the first-class platform union.The generated host-profile projection also carries runtime platform fallbackmetadata for shared explanation and parity with backend normalization, butfrontend primitives must still render host-profile labels through@@ -1106,11 +1241,11 @@ not a replacement status card, CTA band, or page-local nested card.system badge names a platform with its version, source/method context maystill add collection labels such as Pulse Agent, but it must not repeat thesame platform again as an unversioned source badge.-10. Keep summary chart interaction identity on one shared helper. Summary surfaces that expose row-hover, group-hover, chart-hover, or route-focus-driven chart emphasis must derive page/group/entity scope through `frontend-modern/src/components/shared/summaryCardInteraction.ts` and pass that same resolved scope into card-state, sparkline, and density-map primitives, rather than letting cards read `hovered || focused` while charts listen to a different page-local ID source. Hovering one summary chart must promote that series into the shared active entity so sibling cards highlight the same object instead of keeping chart-local hover islands, and hovering or pinning a workload group header, infrastructure cluster header, or storage pool-group header must scope the matching summary cards through that same shared contract instead of forking a page-local summary filter path. Sibling cards should surface that synchronized hover as one compact header readout through the shared summary-card contract, while the chart under the pointer keeps the only floating tooltip. Recovery is explicitly outside this interaction dialect: its retired posture-card strip must not return with row/group/chart hover behavior without a separate governed product decision.-11. Keep page summaries page-scoped when table rows enter contextual focus. Route-backed row selection may add a focused label and shared series emphasis, but infrastructure, workloads, and storage summary cards must continue to render the page-level series set instead of collapsing the summary down to the selected row or replacing the global trend view with row-local empty states.-12. Keep contextual row focus on the shared summary primitive. Summary surfaces and same-route table drill-ins must reuse `frontend-modern/src/components/shared/contextualFocus.ts` for interactive-series filtering, focused-name lookup, active-series derivation, local scroll preservation, and deliberate inline-detail reveal instead of rebuilding page-local `Set` filters, focused-label scans, drawer-aware scroll math, or ad hoc scroll restoration in each surface.-13. Keep summary-linked table row emphasis on the shared primitive contract. Workloads, infrastructure, and storage rows that mirror the active summary entity must expose that state through `data-summary-row-active` and let the shared presentation in `frontend-modern/src/index.css` render the row emphasis, rather than carrying page-local sky or blue fill classes inside each row renderer. Group-scoped preview and pin must use that same shared presentation boundary: child rows that belong to a hovered or pinned summary group should expose `data-summary-group-member-active="preview|pinned"` so the block-level emphasis stays subtle, consistent, and reversible instead of each table inventing its own outline, badge, or full-strength fill treatment. Static grouped row headers on workloads, infrastructure, storage, recovery, and future grouped tables must use `frontend-modern/src/components/shared/groupedTableRowPresentation.ts` plus the `.grouped-table-row` CSS contract in `frontend-modern/src/index.css`, rather than rebuilding local `bg-surface-alt` variants with subtly different light/dark behavior or page-local left-accent markers. That shared grouped-table primitive owns the subgroup cell padding, typography, small metadata, and badge treatment as well as the row background token, so a future adjustment to the subgroup visual language changes every grouped product table from one owner. Inline table detail rows on platform, workload, and infrastructure tables must compose `frontend-modern/src/components/shared/InlineDetailTableRow.tsx` for the full-width row, surface-alt cell, detail padding, and row-click containment instead of rebuilding page-local `TableRow` / `TableCell` / `div` shells around each drawer. Storage-backed reusable row presenters under `frontend-modern/src/features/storageBackups/` must also keep row height and alert accents on class/data-attribute presentation instead of runtime inline style maps, so the shared table contract stays CSP-safe on both steady-state and alert-highlighted routes.-14. Keep retained-value data loading honest at the ownership boundary. Helpers+8. Keep summary chart interaction identity on one shared helper. Summary surfaces that expose row-hover, group-hover, chart-hover, or route-focus-driven chart emphasis must derive page/group/entity scope through `frontend-modern/src/components/shared/summaryCardInteraction.ts` and pass that same resolved scope into card-state, sparkline, and density-map primitives, rather than letting cards read `hovered || focused` while charts listen to a different page-local ID source. Hovering one summary chart must promote that series into the shared active entity so sibling cards highlight the same object instead of keeping chart-local hover islands, and hovering or pinning a workload group header, infrastructure cluster header, or storage pool-group header must scope the matching summary cards through that same shared contract instead of forking a page-local summary filter path. Sibling cards should surface that synchronized hover as one compact header readout through the shared summary-card contract, while the chart under the pointer keeps the only floating tooltip. Recovery is explicitly outside this interaction dialect: its retired posture-card strip must not return with row/group/chart hover behavior without a separate governed product decision.+9. Keep page summaries page-scoped when table rows enter contextual focus. Route-backed row selection may add a focused label and shared series emphasis, but infrastructure, workloads, and storage summary cards must continue to render the page-level series set instead of collapsing the summary down to the selected row or replacing the global trend view with row-local empty states.+10. Keep contextual row focus on the shared summary primitive. Summary surfaces and same-route table drill-ins must reuse `frontend-modern/src/components/shared/contextualFocus.ts` for interactive-series filtering, focused-name lookup, active-series derivation, local scroll preservation, and deliberate inline-detail reveal instead of rebuilding page-local `Set` filters, focused-label scans, drawer-aware scroll math, or ad hoc scroll restoration in each surface.+11. Keep summary-linked table row emphasis on the shared primitive contract. Workloads, infrastructure, and storage rows that mirror the active summary entity must expose that state through `data-summary-row-active` and let the shared presentation in `frontend-modern/src/index.css` render the row emphasis, rather than carrying page-local sky or blue fill classes inside each row renderer. Group-scoped preview and pin must use that same shared presentation boundary: child rows that belong to a hovered or pinned summary group should expose `data-summary-group-member-active="preview|pinned"` so the block-level emphasis stays subtle, consistent, and reversible instead of each table inventing its own outline, badge, or full-strength fill treatment. Static grouped row headers on workloads, infrastructure, storage, recovery, and future grouped tables must use `frontend-modern/src/components/shared/groupedTableRowPresentation.ts` plus the `.grouped-table-row` CSS contract in `frontend-modern/src/index.css`, rather than rebuilding local `bg-surface-alt` variants with subtly different light/dark behavior or page-local left-accent markers. That shared grouped-table primitive owns the subgroup cell padding, typography, small metadata, and badge treatment as well as the row background token, so a future adjustment to the subgroup visual language changes every grouped product table from one owner. Inline table detail rows on platform, workload, and infrastructure tables must compose `frontend-modern/src/components/shared/InlineDetailTableRow.tsx` for the full-width row, surface-alt cell, detail padding, and row-click containment instead of rebuilding page-local `TableRow` / `TableCell` / `div` shells around each drawer. Storage-backed reusable row presenters under `frontend-modern/src/features/storageBackups/` must also keep row height and alert accents on class/data-attribute presentation instead of runtime inline style maps, so the shared table contract stays CSP-safe on both steady-state and alert-highlighted routes.+12. Keep retained-value data loading honest at the ownership boundary. Helpersthat prevent a feature surface from falling through the app-level Suspenseboundary during in-flight refresh should stay feature-local until multiplegoverned surfaces truly share the behavior. Once that boundary is shared,@@ -1118,7 +1253,7 @@ not a replacement status card, CTA band, or page-local nested card.`frontend-modern/src/hooks/createNonSuspendingQuery.ts` rather thanre-copying suspense-escape logic into each feature area or burying itinside one feature's private state model.-15. Keep shared commercial warning banners truthful about destination intent.+13. Keep shared commercial warning banners truthful about destination intent.When a shared banner renders both explanatory and commercial CTAs, thoselabels must resolve to distinct owned destinations or section anchorsinstead of presenting two different labels that land on the same@@ -1129,7 +1264,7 @@ not a replacement status card, CTA band, or page-local nested card.review destination for a current paid feature, it must scope the operator into theusage-owned policy ledger rather than plan-selection intent or CTA copythat frames the flow as monitored-system-cap expansion.-16. Keep assistant availability bootstrap on the shared app-shell boundary.+14. Keep assistant availability bootstrap on the shared app-shell boundary.`frontend-modern/src/useAppRuntimeState.ts`,`frontend-modern/src/App.tsx`,`frontend-modern/src/stores/aiChat.ts`, and@@ -1159,22 +1294,19 @@ not a replacement status card, CTA band, or page-local nested card.must stay on the app-shell assistant-availability fact instead ofre-reading raw AI settings just to decide whether assistant affordancesshould render.-18. Keep Patrol shell composition and product-first provider vocabulary on the+15. Keep Patrol shell composition and product-first provider vocabulary on theshared feature-presentation boundary.- `frontend-modern/src/features/patrol/PatrolIntelligenceSummary.tsx`,`frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx`,`frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx`,`frontend-modern/src/features/patrol/PatrolIntelligenceBanners.tsx`,`frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts`,`frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts`,- `frontend-modern/src/features/patrol/patrolSupportingContextPresentation.ts`,- `frontend-modern/src/components/patrol/PatrolStatusBar.tsx`, and+ `frontend-modern/src/components/patrol/RunHistoryEntry.tsx`, and`frontend-modern/src/utils/patrolRuntimeActions.ts` must keepPatrol assessment, verification, and findings primary; surface recent- changes, learned correlations, and policy coverage only as explicitly- secondary supporting context when degraded or incomplete verification,- active findings, or selected-run investigation makes that evidence- relevant; and use Patrol/provider wording for the shared provider settings,+ changes, learned correlations, and policy coverage only as backend,+ Assistant, selected-finding, or selected-run context when investigation+ makes that evidence relevant; and use Patrol/provider wording for the shared provider settings,provider model, and provider circuit-breaker affordances instead ofgeneric AI labels inside Patrol-owned shells. The shared app shell in`frontend-modern/src/App.tsx` and `frontend-modern/src/AppLayout.tsx` must@@ -1183,33 +1315,65 @@ not a replacement status card, CTA band, or page-local nested card.second Patrol-branded primary route. `PatrolIntelligenceHeader.tsx`must also keep the page heading's accessible name singular: when the`PulsePatrolLogo` appears beside visible Patrol heading text, it is- decorative rather than a second label source. The Patrol-owned supporting-context- presenter must also keep the disclosure toggle plus evidence-boundary copy- centralized instead of letting the workspace reintroduce inline shell-local- trust wording, while the Patrol investigation-context owner normalizes- same-state recent-change records into changed-substate wording before the- workspace or Assistant handoff renders them. The same shared feature-shell+ decorative rather than a second label source. The Patrol workspace must not+ expose a generic Details/supporting-context panel for nearby activity,+ learned correlations, or policy buckets; those payloads stay backend and+ Assistant context rather than a default page section. Patrol initial data+ refresh failures must stay inside the Patrol feature shell as one compact+ stale-data retry banner; they must not replace the route with Suspense,+ blank loading, raw transport errors, or page-local diagnostic panels. The Patrol+ investigation-context owner normalizes same-state recent-change records into+ changed-substate wording before Assistant handoff renders them. The same shared feature-shellboundary owns the- commercial-facing Patrol capability language: Pro-locked helper copy,- autonomy segmented controls, and run-history/result labels must use- `Remediate`, `remediated`, or safe remediation wording while legacy API- names remain hidden from operators. The Patrol configuration popover is part- of that shared feature-presentation boundary: it must stay viewport-bounded,- expose an accessible dialog label, and pass backend save rejection reasons- through as inline dialog state instead of replacing them with generic toast- copy. When the failure includes Patrol readiness context, the inline state- must expose the provider, model, and readiness summary next to a direct- provider-settings action instead of hiding that diagnosis behind Assistant- alone. The provider-model selector in that popover must stay bound to the- shared runtime settings/model catalog even when the popover mounts after- async catalog loading, so a saved direct-provider Patrol model renders as+ commercial-facing Patrol capability language: autonomy segmented controls+ and run-history/result labels must present the operator-facing policy levels+ as `Watch only`, `Ask first`, `Safe auto-fix`, and `Autopilot`, while legacy+ API names remain hidden from operators and compact controls do not collapse+ into unexplained shorthand. Patrol run-history rows must lead with what+ Patrol did or could not do before exposing trigger, token, tool-call, or raw+ trace details. Plan-locked Patrol controls may badge paid levels as Pro and+ may show one compact `Plans & Billing` handoff beside the selector when+ upgrade prompts are allowed, but the default watch-only surface must not+ render a Pro-absence explainer. Visible product copy calls the selector `Patrol mode`; compatibility route and wire identifiers may keep stable names+ such as `patrol_control` and `patrolControl*`. Plan-locked Patrol controls+ may keep paid levels visible as disabled buttons, and may badge them as Pro+ only when upgrade prompts are allowed. The always-visible Patrol mode selector must stay on+ the selected mode and one plain summary, without a separate `Limits`+ disclosure or hard-limit matrix beside the picker. Shared feature shells must not invent their own Patrol safety+ thresholds, policy labels, or disabled-control explanations. The Patrol page+ header must consume the same effective control state, using watch-and-report+ copy for locked or `Watch only` mode and full governed-operations copy only+ for modes where that capability is actually available. Paid-control+ availability and commercial-plan copy must describe the same decision as+ choosing what Patrol may handle automatically; they must not ask users to+ decide how far Patrol can go or how much control Patrol has. The+ Current work workspace copy belongs to that same product-facing boundary:+ empty and descriptive text must explain what Patrol-found problems will+ appear there, what the selected control level allows, and the next useful+ operator action; it must not fall back to activation-loop, proof, queue, or+ verification-accounting language. The+ Patrol schedule and model drawer is part of that shared+ feature-presentation boundary: it must stay viewport-bounded, expose an+ accessible dialog label, keep the four-level control policy on the default+ Patrol header, and keep provider model, schedule, trigger tuning, and+ readiness validation inside the secondary disclosure. Backend save rejection reasons must pass+ through as inline dialog state instead of being replaced with generic toast+ copy, and that advanced disclosure must open when the inline state exists.+ When the failure includes+ Patrol readiness context, the inline state must expose the provider, model,+ and readiness summary next to a direct provider-settings action instead of+ hiding that diagnosis behind Assistant alone. The provider-model selector in+ that popover must stay bound to the shared runtime settings/model catalog+ even when the popover mounts after async catalog loading, but the full+ catalog must stay behind an explicit change action so the default advanced+ drawer leads with the current effective model summary rather than a raw+ provider route list. A saved direct-provider Patrol model still renders asthat model instead of visually falling back to the default selection.Successful provider-model saves that return a not-ready Patrolreadiness snapshot must use that same inline surface with `needs attention`wording, while Assistant receives a saved configuration issue rather than a- failed-save handoff. When safe remediation is locked, the same popover- state owner must- clear stale full-mode unlock state before Apply Configuration submits the+ failed-save handoff. When governed fixes are locked, the same Patrol state+ owner must clear stale full-mode unlock state before persisting themonitor-only autonomy payload, so disabled paid controls cannot leak stalepermission into a save. If that inline state opens Assistant, the Patrolfeature must hand off@@ -1222,14 +1386,35 @@ not a replacement status card, CTA band, or page-local nested card.findings tab, run-scoped findings panels, and tab badges so shared featurecomposition does not rebuild Patrol state by filtering the cross-productunified findings feed.-19. Keep the shared `system-ai` settings shell product-first.+16. Keep Pulse Intelligence settings product-first and page-scoped.`frontend-modern/src/components/Settings/AISettings.tsx`,`frontend-modern/src/components/Settings/settingsHeaderMeta.ts`,`frontend-modern/src/components/Settings/settingsNavCatalog.ts`,+ `frontend-modern/src/components/Settings/settingsNavigationModel.ts`,+ `frontend-modern/src/components/Settings/settingsPanelRegistry.ts`,+ `frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx`,`frontend-modern/src/components/Settings/useAISettingsState.ts`, and`frontend-modern/src/utils/aiSettingsPresentation.ts` must present that- surface to operators as `Assistant & Patrol` plus provider/model- configuration rather than as a generic `AI Services` shell. Settings-save+ surface to operators under the `Pulse Intelligence` settings group as+ separate focused pages rather than as a generic `AI Services` shell or one+ oversized mixed form. `Provider & Models` owns API keys, default model+ selection, provider health/preflight, provider runtime budget/timeout, and+ usage/cost visibility. `Patrol` owns schedule, alert/anomaly triggers,+ runtime readiness, Patrol model override, and a simple `Open Patrol` handoff+ to the `/patrol` operator page; the actual watch/investigate/act/verify/record+ operator loop stays on `/patrol`. `Assistant` owns chat/tool permission,+ command-access, model override, and session maintenance. Service context may+ exist under Pulse Intelligence only for model-backed or continuous service+ discovery that supplies Assistant and Patrol context; normal infrastructure+ discovery and onboarding remain under Infrastructure, and the Pulse+ Intelligence navigation item, route header, model override, reset/save+ affordances, and setup copy must use the `Service Context` label so+ operators do not confuse it with infrastructure discovery. The+ `Provider & Models` page must not carry a discovery summary,+ Patrol-control banner, or Patrol CTA; the Patrol-control handoff belongs on+ the `Patrol` settings page and `/patrol`, where copy describes Patrol+ autonomy in plain operator terms rather than exposing an internal+ `operations policy` concept. Settings-savefeedback must preserve provider-specific preflight failures and successfulsave responses that carry Patrol readiness warnings, including the provider,selected Patrol model, failure cause, safe recommendation, and readiness@@ -1239,37 +1424,57 @@ not a replacement status card, CTA band, or page-local nested card.setup cards must describe provider families through the currentbackend-owned provider contract; DeepSeek setup copy is the V4 family andmust not regress to old V3 or compatibility-alias wording.+ Provider connection controls are page-scoped: the global Pulse+ Intelligence enable toggle, provider readiness strip, and Test Connection+ action belong to `Provider & Models`; Patrol, Assistant, and Service Context+ subpages keep their focused settings plus reset/save actions without+ repeating provider health chrome. Those reset/save actions and save+ notifications must be page-scoped as well: saving `Patrol`, `Assistant`,+ or `Service Context` settings must not report+ `Provider & Models settings saved` or render a generic `Save changes`+ affordance that hides which Pulse+ Intelligence page owns the change.Runtime controls inside `frontend-modern/src/components/Settings/AIRuntimeControlsSection.tsx`- must likewise describe discovery as workload discovery that supplies- concrete service context to Pulse Assistant and Patrol, not as a generic- AI context feature. `frontend-modern/src/components/Settings/useAISettingsState.ts`- must save workload discovery enablement and interval as one explicit+ must stay split by page-specific exports: provider runtime controls on+ `Provider & Models`, Assistant chat actions on `Assistant`, and service+ context controls on `Service Context`. Assistant chat-action copy+ must name Patrol control as configured on the Patrol page, not as an+ Assistant command mode, because `/patrol` remains the operator surface for+ choosing how much autonomy Patrol has. Service context copy must describe+ the model-backed loop that supplies concrete service facts to Pulse+ Assistant and Patrol, not as generic discovery or AI context.+ `frontend-modern/src/components/Settings/useAISettingsState.ts`+ must save service context scan enablement and interval as one explicitsettings pair so selecting "Every 6 hours" or "Manual only" round-tripsthrough `/api/settings/ai` without depending on stale read-side diffing.- The same workload-discovery settings section must expose a manual- "Run discovery now" action wired through `/api/discovery/run` when- workload discovery is enabled in manual-only mode, while resource-drawer+ The same Service Context settings section must expose a manual+ context-scan action wired through `/api/discovery/run` when+ service context scanning is enabled in manual-only mode, while resource-drawerdiscovery remains the forced single-resource refresh path. The collapsedsection and run-action copy must make automatic scheduling visible bydistinguishing `Auto <interval>`, `Manual only`, and `Off`, and the run- action must describe whether it is executing the scheduled sweep or a+ action must describe whether it is running the scheduled scan or aone-off manual-only sweep rather than implying recurring scans wereenabled.- Assistant-only controls inside the shared shell, such- as execution permissions and session maintenance, must stay explicitly- labeled as Pulse Assistant controls, while Patrol schedule and autonomy- continue to live on Patrol-owned surfaces rather than drifting back into- the shared settings shell. Session maintenance in that shell is limited to+ Assistant-only controls such as execution permissions and session+ maintenance must stay explicitly labeled as Pulse Assistant controls, while+ Patrol schedule and trigger readiness live on the Patrol settings page and+ Patrol autonomy/control level lives on the `/patrol` operator page rather+ than drifting back into the provider shell. Session maintenance is limited toPulse-owned conversation operations such as summarization; OpenCode-stylefile diff, revert, or unrevert actions must not appear in Settings unlessPulse owns a real governed infrastructure action-history/reversal contract- for the affected resources. Shared/default model choices may remain on the- combined shell only when Assistant, Patrol, and Discovery overrides are- presented as explicit per-surface overrides instead of a generic advanced- AI bucket. Each per-surface override must fall back to the shared default- when left empty rather than silently using a hard-coded backend default,- so the shared shell stays the single place an operator picks the model- for any of the three surfaces.+ for the affected resources. Shared/default model choice belongs on+ `Provider & Models`, while Assistant, Patrol, and service context model+ overrides belong on their respective settings pages instead of a generic+ advanced AI bucket. Each per-surface override must fall back to the shared+ default when+ left empty rather than silently using a hard-coded backend default, so+ `Provider & Models` stays the single place an operator picks the default+ model for all three surfaces. Assistant model copy must describe chat,+ explanation, and review support; it must not present Assistant as the+ approved-fix executor because Patrol is the hands-on operator for checks,+ governed fixes, and verification.The shared shell must not show Pro-only autonomous execution as a defaultfree-user control when upgrade prompts are suppressed; it may surface thatoption only when the entitlement is present, commercial prompts are@@ -1317,7 +1522,7 @@ not a replacement status card, CTA band, or page-local nested card.selected route also carries a shared-default or override badge, the sharedpicker owns that badge as separate metadata in both visible text and thebutton accessible name; labels must render as `model via OpenRouter ·- default` instead of fusing provider and badge text such as+default` instead of fusing provider and badge text such as`OpenRouterdefault`.Platform-first top-level pages registered through`frontend-modern/src/App.tsx` must stay chrome-only and route through the@@ -1376,6 +1581,47 @@ not a replacement status card, CTA band, or page-local nested card.first/default positions only when the current estate has standalone PulseAgent machines or agentless availability endpoints and noprovider/runtime platform evidence.+ Patrol workflow components under+ `frontend-modern/src/features/patrol/` may compose shared `Button` and+ `ButtonLink` chrome for issue actions, but the workflow state, route+ anchors, single-finding direct-action selection, Assistant handoff, autonomy+ label, and multi-finding fallback semantics stay with `patrol-intelligence`;+ the canonical Patrol control anchor belongs on the visible selector, not the+ workspace shell. Setup-only readiness may hide run, schedule, model, trigger,+ and provider-repair controls, but it must not hide that selector or replace+ it with a setup/status explainer. Shared primitives must not grow+ Patrol-specific activation, autonomy, provider-settings, or+ Assistant-routing behavior. The default loop is a+ Patrol-owned watch / investigate / act under policy / verify / record loop.+ Active current-issue expansion is a task surface, not a history transcript:+ raw finding lifecycle rows may render in explicit all/resolved/history or+ selected-run review states, but not in the default active Patrol issue+ expansion.+ Compact Patrol status chrome may render work/health evidence passed by+ Patrol, but trigger/scheduling status remains header/control context and+ must not be repeated by shared default status primitives. Shared primitives+ must preserve that plain visible label instead of exposing internal+ assessment terminology on the default page.+ External-agent readiness from Pulse MCP may remain compact optional context+ derived from the shared manifest-client contract verdict and backend+ operations-loop `externalAgentReady` signal, but shared primitives must not+ create page-local MCP setup constants, token-scope checks, tool filters,+ readiness shortcuts, MCP readiness props, or a visible external-agent stage+ as the primary first-party loop. The journey's loaded progress state must come from the+ canonical operations-loop status projection exposed by the shared+ agent-capabilities frontend client, while shared primitives remain passive+ renderers of the state Patrol passes them. Patrol control starter,+ completed-loop, or resolved-loop evidence may change compact journey copy+ only after Patrol has derived it from that projection; shared primitives must+ not infer Patrol control or legacy Pro activation state from route anchors,+ billing state, generic Patrol recency, or MCP readiness alone.+ Shared presentation+ helpers may render the operations-loop state they receive, but they must+ not infer operations-loop progress from a generic Patrol run, recency+ timestamp, or MCP readiness alone; Patrol owns the issue-backed evidence+ model that decides when the loop can advance through Assistant, approval,+ rejected no-execution terminal decisions, approved-action verification, and+ external-agent parity.## Forbidden Paths@@ -1390,7 +1636,12 @@ not a replacement status card, CTA band, or page-local nested card.conversion, or infrastructure onboarding telemetry. Those signals belong inadmin-owned metrics surfaces, not the product diagnostics UI or customerfrontend event emission.-6. Settings route models normalizing retired aliases such as+6. User-facing diagnostics panels rendering the native Pulse Assistant runtime+ as an MCP connection. Settings diagnostics must consume+ `assistantRuntimeConnected` and label it as Assistant runtime availability;+ `mcpConnected`, `mcpToolCount`, and "MCP Connection" are forbidden on the+ first-party diagnostics surface.+7. Settings route models normalizing retired aliases such as`/settings/operations/*`, `/settings/integrations/api`,`/settings/system-pro`, `/settings/workloads/*`, or nested`/settings/infrastructure/*` paths back into current settings panels.@@ -1424,28 +1675,32 @@ not a replacement status card, CTA band, or page-local nested card.placeholders must stay on `LoadingSpinner` and the `loading-spinner-shell`registry rule instead of local `border-t-transparent` or `border-b-2`animate-spin shells.-3. Update this contract when a new canonical UI pattern is adopted-4. Remove local forks after the shared primitive is introduced-5. Keep shared feature-level presenters on capability truth. When reusable+4. Update this contract when a new canonical UI pattern is adopted+5. Remove local forks after the shared primitive is introduced+6. Keep shared feature-level presenters on capability truth. When reusablepresenters under `frontend-modern/src/features/` explain why a control,chart, or detail surface is unavailable, they must describe the ownedidentity or capability gap instead of prescribing a provider-local installpath that conflicts with API-backed platforms like TrueNAS.-6. When a settings route header and a top-level settings shell describe the same+7. When a settings route header and a top-level settings shell describe the samecommercial surface, keep them on the same shared presentation owner insteadof allowing route metadata in `settingsHeaderMeta.ts` or labels in`settingsNavCatalog.ts` to drift into independent title or description copy,and keep adjacent settings-shell referrals such as`InfrastructureWorkspace.tsx` on that same shared owner instead ofreintroducing local “go to Pulse Pro” variants.- That same shared owner must also support explicit IA/title separation for- self-hosted commercial settings: the nav label may stay product-IA-first- (`Plans`) while the page shell stays task-first (`Self-hosted plan`), and- the owned plan shell must foreground the active plan name plus available+ That same shared owner must also keep self-hosted commercial settings+ discoverable: the nav label and page shell title use the shared+ `Plans & Billing` label, and the owned plan shell must foreground the active+ plan name plus availablecapabilities before secondary billing or recovery detail so paid upgradescan confirm their entitlement immediately after activation without makingdefault Community look like it is missing an activation key.-7. When settings surfaces need informational, warning, success, or danger+ Routine plan and capability-status copy must stay product-facing: describe+ what is available on the instance, point failed capability checks to refresh+ the plan or open recovery, and avoid raw entitlement-payload phrasing or+ activation language as the normal setup story.+8. When settings surfaces need informational, warning, success, or dangercallouts, compose `frontend-modern/src/components/shared/CalloutCard.tsx`and register the consumer in`frontend-modern/scripts/shared-template-registry.json` instead of adding@@ -1462,7 +1717,7 @@ not a replacement status card, CTA band, or page-local nested card.boundary. The update flow owns version, prerequisite, root-access, restart,and error copy; `CalloutCard` owns the info/warning/danger shell, spacing,dark-mode tone, and icon layout.-8. Keep hosted settings-shell framing imports safe for bundle initialization.+9. Keep hosted settings-shell framing imports safe for bundle initialization.Self-hosted billing titles, descriptions, and referral copy used by`settingsHeaderMeta.ts`, `settingsNavCatalog.ts`, and adjacent settingsshells must flow through@@ -1474,28 +1729,32 @@ not a replacement status card, CTA band, or page-local nested card.badge titles, Pro-suffixed option labels, monitored-system limit claims, orbrowser-local commercial/onboarding metrics wrappers in SSO, audit,reporting, AI controls, agent profiles, or shared warning banners.-9. Keep shared settings-shell AI control copy capability-scoped rather than- upsell-scoped. `AIRuntimeControlsSection.tsx` may describe read-only,- approval-required, and autonomous action posture, but option labels and- helper text must avoid tier labels or broad "executes everything" wording;- paid capability availability belongs to entitlement-backed visibility and- lock state, not local select copy.-10. Keep first-session dashboard empty-state copy on- `frontend-modern/src/utils/workloadEmptyStatePresentation.ts`, and make- infrastructure setup guidance name the canonical destination explicitly- instead of falling back to generic settings CTA labels.-9. Keep the live first-session wizard on the canonical three-step runtime- shape in `frontend-modern/src/components/SetupWizard/SetupWizard.tsx`- (`Welcome`, `Security`, then `Install`), and keep the step indicator plus- completion CTA language aligned with the governed infrastructure install- workspace instead of regressing to a route jump that leaves the next action- implicit. Preview-only follow-up surfaces such as- `frontend-modern/src/components/SetupWizard/SetupCompletionPreview.tsx`- must stay deterministic and scenario-driven: they may not poll the live- `/api/state` runtime or inherit whatever connected systems happen to exist- on the current backend, and browser proof for `/preview/setup-complete`- must select explicit preview scenarios instead of ambient runtime state.-10. Keep AI settings setup UI backend-driven:+10. Keep shared settings-shell AI control copy capability-scoped rather than+ upsell-scoped. `AIRuntimeControlsSection.tsx` may describe read-only,+ approval-required, and autonomous action posture, but option labels and+ helper text must avoid tier labels or broad "executes everything" wording;+ paid capability availability belongs to entitlement-backed visibility and+ lock state, not local select copy. Provider & Models settings copy must keep+ Patrol autonomy distinct from Assistant chat actions: Patrol's+ hands-on control level belongs on the Patrol page, while the shared settings+ shell may only describe whether Assistant chat can run eligible chat+ actions.+11. Keep first-session dashboard empty-state copy on+ `frontend-modern/src/utils/workloadEmptyStatePresentation.ts`, and make+ infrastructure setup guidance name the canonical destination explicitly+ instead of falling back to generic settings CTA labels.+12. Keep the live first-session wizard on the canonical three-step runtime+ shape in `frontend-modern/src/components/SetupWizard/SetupWizard.tsx`+ (`Welcome`, `Security`, then `Install`), and keep the step indicator plus+ completion CTA language aligned with the governed infrastructure install+ workspace instead of regressing to a route jump that leaves the next action+ implicit. Preview-only follow-up surfaces such as+ `frontend-modern/src/components/SetupWizard/SetupCompletionPreview.tsx`+ must stay deterministic and scenario-driven: they may not poll the live+ `/api/state` runtime or inherit whatever connected systems happen to exist+ on the current backend, and browser proof for `/preview/setup-complete`+ must select explicit preview scenarios instead of ambient runtime state.+13. Keep AI settings setup UI backend-driven:`frontend-modern/src/components/Settings/useAISettingsState.ts` and`frontend-modern/src/components/Settings/AISettingsDialogs.tsx` may collectprovider credentials or runtime URLs, but they must not bake vendor model@@ -1608,19 +1867,19 @@ not a replacement status card, CTA band, or page-local nested card.or proposed fix, must pass `autonomousMode:false` as a request-localoverride so the drawer shows approval-required posture without mutating thepersistent Assistant control setting.-11. Keep shared filter primitives coherent with source-owned option hydration.+14. Keep shared filter primitives coherent with source-owned option hydration.Active platform/runtime pages and Settings infrastructure surfaces must keepcanonical options visible in shared filter controls even when currentresults do not contain that option, so provider- or endpoint-scopedhandoffs do not flash back to generic host-only language.-12. Keep the first welcome screen in+15. Keep the first welcome screen in`frontend-modern/src/components/SetupWizard/steps/WelcomeStep.tsx`explicit about operator context. The shell must explain that the bootstraptoken only unlocks first-run setup, state where the command should run, andadapt command/help text to detected Docker or containerized deploymentsinstead of assuming the operator already knows which host or container ownsthe Pulse install.-13. Keep the settings-shell infrastructure landing path aligned with that same+16. Keep the settings-shell infrastructure landing path aligned with that samefirst-session story. `frontend-modern/src/components/Settings/settingsNavigationModel.ts`must treat `/settings` and the infrastructure settings tab as the canonicalpath to the bare `/settings/infrastructure`, which renders the unified@@ -1629,7 +1888,7 @@ not a replacement status card, CTA band, or page-local nested card.and the `Add infrastructure` entry point on it, not by a second landing route,so first-time operators and returning operators see one consistentinfrastructure surface by default.-14. Keep Infrastructure and Workloads onboarding copy on the shared+17. Keep Infrastructure and Workloads onboarding copy on the sharedpresentation owner in`frontend-modern/src/utils/workloadEmptyStatePresentation.ts`. Both theinfrastructure empty state and the Workloads no-resources state must route@@ -1643,28 +1902,37 @@ not a replacement status card, CTA band, or page-local nested card.operators at credentials, permissions, and collection status in thecanonical infrastructure workspace instead of reusing first-run onboardingcopy.-15. Keep cross-surface investigation handoffs on shared route ownership.+18. Keep cross-surface investigation handoffs on shared route ownership.Feature shells such as Alerts and Patrol may decide which governeddestination chips to render, but canonical href, label, dedupe, andinfrastructure-fallback truth must stay in`frontend-modern/src/routing/resourceLinks.ts` instead of freezing rawroute strings or provider-local link builders inside feature panels.-16. Keep shared summary-card emphasis coherent. When shared summary primitives enter an `inactive` state, `SummaryMetricCard`, `InteractiveSparkline`, and `DensityMap` must all demote background context together so storage, infrastructure, and workloads read as one interaction model instead of mixing page-local opacity, sticky-shell, or highlight rules.-17. Keep density-map summaries overview-first. When a shared summary density map receives row focus or chart-hover emphasis, `frontend-modern/src/components/shared/DensityMap.tsx`, `frontend-modern/src/components/shared/useDensityMapState.ts`, and `frontend-modern/src/components/shared/densityMapModel.ts` must preserve the multi-entity overview rows and keep focused-entity detail in the hover tooltip instead of swapping the card into a single-series chart, dimming the rest of the map into unusable background noise, duplicating cursor-value tooltip copy, or adding persistent card chrome that steals heatmap space. The card body must stay overview-first; the tooltip may carry the active entity identity, current value, and peak, shared tooltip shells must follow semantic surface tokens instead of forcing a dark palette in light mode, the tooltip header must let long entity names consume the available width before truncating rather than clipping against an arbitrary fixed label cap, numeric metric readouts such as `16.9 MB/s` or `37.4 MB/s` must stay single-line instead of wrapping the unit onto a second row, and density-map detail that cannot fit cleanly inside the canonical tooltip shell must be omitted rather than introducing tooltip-specific chrome or a secondary chart inside the hover surface.-18. Keep retired self-hosted hosted-model and trial acquisition surfaces out of+ Patrol workflow handoffs follow the same rule: start/continue Patrol+ control links must compose the route-backed `patrol_control` helper from+ `resourceLinks.ts`, single-finding direct action links must use canonical+ finding-presentation destinations such as the Patrol provider-settings+ route, while `patrol_autonomy` and legacy Pro activation URLs remain parser+ aliases only and verified review links use the plain Patrol history anchor.+ UI surfaces must not duplicate the `patrolControlStarter` query string or+ write Patrol control or legacy entry-point starter telemetry from local+ click handlers.+19. Keep shared summary-card emphasis coherent. When shared summary primitives enter an `inactive` state, `SummaryMetricCard`, `InteractiveSparkline`, and `DensityMap` must all demote background context together so storage, infrastructure, and workloads read as one interaction model instead of mixing page-local opacity, sticky-shell, or highlight rules.+20. Keep density-map summaries overview-first. When a shared summary density map receives row focus or chart-hover emphasis, `frontend-modern/src/components/shared/DensityMap.tsx`, `frontend-modern/src/components/shared/useDensityMapState.ts`, and `frontend-modern/src/components/shared/densityMapModel.ts` must preserve the multi-entity overview rows and keep focused-entity detail in the hover tooltip instead of swapping the card into a single-series chart, dimming the rest of the map into unusable background noise, duplicating cursor-value tooltip copy, or adding persistent card chrome that steals heatmap space. The card body must stay overview-first; the tooltip may carry the active entity identity, current value, and peak, shared tooltip shells must follow semantic surface tokens instead of forcing a dark palette in light mode, the tooltip header must let long entity names consume the available width before truncating rather than clipping against an arbitrary fixed label cap, numeric metric readouts such as `16.9 MB/s` or `37.4 MB/s` must stay single-line instead of wrapping the unit onto a second row, and density-map detail that cannot fit cleanly inside the canonical tooltip shell must be omitted rather than introducing tooltip-specific chrome or a secondary chart inside the hover surface.+21. Keep retired self-hosted hosted-model and trial acquisition surfaces out ofnormal v6 GA runtime. Shared shells and helper-driven badges may continue toparse legacy payload fields, but ordinary self-hosted Assistant, Patrol, andsettings flows must present provider setup as BYOK/local/self-managed andmust not surface hosted-model credits, in-app trial starts, or genericmanaged-model claims.-19. Keep sparkline scrubbing source-local and sibling-sync timestamp-based. The chart a user is actively scrubbing in `frontend-modern/src/components/shared/InteractiveSparkline.tsx` and `frontend-modern/src/components/shared/useInteractiveSparklineState.ts` must keep its dashed hover cursor on the real local mouse `x`, while sibling cards may map the shared hover timestamp onto their own timelines. Shared cursor sync must not snap the source chart back onto the nearest sample timestamp, the rendered SVG/canvas hover cursor must bind to the actual numeric cursor coordinate rather than a boolean guard state, the time cursor must span the chart viewport instead of collapsing to the series height, and the hover tooltip must track the pointer instead of anchoring to the chart top edge while following the active theme rather than a hardcoded dark shell. The hover tooltip must stay side-offset from the active scrub cursor and flip to the available side near viewport edges so it does not cover the highlighted guide or graph point.-20. Keep shared contextual focus canonical after adoption. Once a summary or table surface enters route-backed contextual focus, future additions must extend `frontend-modern/src/components/shared/contextualFocus.ts` and its guardrail tests rather than forking another helper for workload IDs, resource IDs, or scroll-preserving same-route selection.-21. Keep shared infrastructure/resource selectors on the canonical agent-facet+22. Keep sparkline scrubbing source-local and sibling-sync timestamp-based. The chart a user is actively scrubbing in `frontend-modern/src/components/shared/InteractiveSparkline.tsx` and `frontend-modern/src/components/shared/useInteractiveSparklineState.ts` must keep its dashed hover cursor on the real local mouse `x`, while sibling cards may map the shared hover timestamp onto their own timelines. Shared cursor sync must not snap the source chart back onto the nearest sample timestamp, the rendered SVG/canvas hover cursor must bind to the actual numeric cursor coordinate rather than a boolean guard state, the time cursor must span the chart viewport instead of collapsing to the series height, and the hover tooltip must track the pointer instead of anchoring to the chart top edge while following the active theme rather than a hardcoded dark shell. The hover tooltip must stay side-offset from the active scrub cursor and flip to the available side near viewport edges so it does not cover the highlighted guide or graph point.+23. Keep shared contextual focus canonical after adoption. Once a summary or table surface enters route-backed contextual focus, future additions must extend `frontend-modern/src/components/shared/contextualFocus.ts` and its guardrail tests rather than forking another helper for workload IDs, resource IDs, or scroll-preserving same-route selection.+24. Keep shared infrastructure/resource selectors on the canonical agent-facettruth. Shared primitives and settings-facing selector helpers must treattop-level TrueNAS appliances as agent-facet infrastructure via sharedhelper ownership instead of reviving a direct `resource.type === 'truenas'`branch inside page shells, selectors, or reporting-resource type helpers.-22. Keep shared feature-shell Patrol run fixtures on the canonical run-record+25. Keep shared feature-shell Patrol run fixtures on the canonical run-recordcontract. When `frontend-modern/src/features/patrol/` consumes Patrol runhistory, the shared normalized record must preserve provider-backed countssuch as `truenas_checked` instead of letting feature-local fixtures or@@ -1684,7 +1952,7 @@ not a replacement status card, CTA band, or page-local nested card.dashboard route is retired, that audit must also discover live top-levelpages from `src/pages/` and may not keep a hard required-header entry for`frontend-modern/src/pages/Dashboard.tsx`.-23. Keep the authenticated app root aligned with that same first-session path.+26. Keep the authenticated app root aligned with that same first-session path.That same shared-primitive ownership now includes contextual row focus.`frontend-modern/src/components/shared/contextualFocus.ts` is the canonicalowner for interactive-series filtering, focused-label lookup, active-series@@ -1724,35 +1992,35 @@ not a replacement status card, CTA band, or page-local nested card.renders the chart. `frontend-modern/src/useAppRuntimeState.ts` must notprewarm retired Infrastructure summary-chart caches or eager Workloadschart caches as a generic authenticated-shell side effect.-24. Keep relay settings shell copy on the shared presentation owner in+27. Keep relay settings shell copy on the shared presentation owner in`frontend-modern/src/utils/relayPresentation.ts`. The route metadata in`settingsHeaderMeta.ts` and the leading `SettingsPanel` in`RelaySettingsPanel.tsx` must reuse the same description and availabilitycopy instead of drifting into separate rollout or pairing wording. Relayavailability copy must describe the Relay tier boundary as Relay and higherplans rather than collapsing Remote Access back into a Pro-only feature.-25. Keep shared settings-shell legal and docs referrals on+28. Keep shared settings-shell legal and docs referrals on`frontend-modern/src/utils/docsLinks.ts`. Shared settings surfaces such as`AIRuntimeControlsSection.tsx` must not hardcode GitHub `main` doc URLs forprivacy, security, proxy-auth, scope-reference, or Terms-of-Service links.-26. Keep shared settings-shell telemetry transparency controls on the governed+29. Keep shared settings-shell telemetry transparency controls on the governedgeneral settings panel. Preview/reset affordances for anonymous telemetrymust stay rendered inside`frontend-modern/src/components/Settings/GeneralSettingsPanel.tsx`instead of drifting into route-local modals, hidden dev tools, or shellchrome that operators would not naturally inspect.-27. Keep the short telemetry/privacy summary copy on that same shared surface+30. Keep the short telemetry/privacy summary copy on that same shared surfaceaccurate to the governed privacy doc. If the trust boundary depends on aspecific retention window or on “IP addresses are not stored” rather than“IPs are never seen,” the summary copy in`GeneralSettingsPanel.tsx` must state those facts plainly instead ofreverting to a stronger but inaccurate shorthand.-28. Keep maintainer commercial-event controls out of customer settings.+31. Keep maintainer commercial-event controls out of customer settings.The shared general settings privacy panel may expose anonymous outboundtelemetry controls, preview, and reset affordances, but it must not renderlocal commercial handoff event toggles, `PULSE_DISABLE_LOCAL_UPGRADE_METRICS`,or other commercial-debug controls as normal customer-facing preferences.-29. Keep shared storage-route feature presentation on neutral capability truth.+32. Keep shared storage-route feature presentation on neutral capability truth.Reusable mappers and presenters in `frontend-modern/src/features/storageBackups/`must distinguish inventory datastores from backup repositories so VMwarerows on the shared storage route stay canonical to the admitted phase-1 floor instead of@@ -1774,7 +2042,7 @@ not a replacement status card, CTA band, or page-local nested card.must only carry fields the row actually renders; per-row source-platformbadges and other identical-on-every-row decorations belong in the rowexpansion, not in `StoragePoolRowModel`.-30. Keep infrastructure settings-shell API alternatives on the shared shell+33. Keep infrastructure settings-shell API alternatives on the shared shellcontract. `frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx`,`frontend-modern/src/components/Settings/settingsHeaderMeta.ts`, and`frontend-modern/src/components/Settings/settingsNavigationModel.ts` must@@ -1786,7 +2054,7 @@ not a replacement status card, CTA band, or page-local nested card.and no per-type `ProxmoxSettingsPanel` / `TrueNASSettingsPanel` /`VMwareSettingsPanel` to route through; the provider is a field insideone `ConnectionEditor`, not a destination.-31. Keep the infrastructure settings connection inventory on one shared+34. Keep the infrastructure settings connection inventory on one sharedsource. `frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx`composes rows exclusively from`frontend-modern/src/components/Settings/useConnectionsLedger.ts`,@@ -1796,14 +2064,14 @@ not a replacement status card, CTA band, or page-local nested card.`PlatformConnectionsWorkspace` / `TrueNASSettingsPanel` /`VMwareSettingsPanel` panels must not be reintroduced as a secondfetch path.-32. Keep alert-history feature composition on the current owned state contract.+35. Keep alert-history feature composition on the current owned state contract.`frontend-modern/src/features/alerts/tabs/HistoryTab.tsx` must react to theshared `alertData()` history state instead of reviving deleted aliases, andit must pass unified-resource resolution through to`frontend-modern/src/features/alerts/AlertResourceIncidentsPanel.tsx` sothe panel can render shared route chips without creating another page-localresource lookup or provider-specific handoff layer.-33. Keep the alert-thresholds containers surface on the canonical shared owner.+36. Keep the alert-thresholds containers surface on the canonical shared owner.`alertOverridesModel.ts`, `useAlertOverridesState.ts`, and`useAlertsConfigurationState.ts` must surface API-backed `app-container`parents such as TrueNAS as first-class `Container Runtimes`, while@@ -1812,7 +2080,7 @@ not a replacement status card, CTA band, or page-local nested card.props that can collapse functions on the live Solid surface. Docker-onlycontrols in `ThresholdsTableDockerTab.tsx` must remain gated to real`docker-host` resources instead of leaking onto platform-managed runtimes.-34. Keep shared commercial upgrade navigation typed and destination-aware.+37. Keep shared commercial upgrade navigation typed and destination-aware.Shared paywall shells and upgrade actions must route internal billing orcloud destinations through `frontend-modern/src/utils/upgradeNavigation.ts`,`frontend-modern/src/components/shared/UpgradeLink.tsx`, and@@ -1823,24 +2091,25 @@ not a replacement status card, CTA band, or page-local nested card.width, tone, focus, route/new-tab behavior, and opener preservation stay onthe shared `ButtonLink` primitive instead of page-local Tailwind anchors orcommercial helper class strings.-35. Keep same-shell platform/runtime route transitions on retained shared state.+38. Keep same-shell platform/runtime route transitions on retained shared state.Active infrastructure consumers may show full-page loading only before thefirst compatible resource snapshot exists; once a fresh canonical snapshotis already present in the shared app shell, top-level platform/runtime tabswitches must reuse that state boundary instead of flashing a transientpage takeover between tabs.-36. Keep self-hosted paid-service prompts opt-in at the shared shell layer.+39. Keep self-hosted paid-service prompts opt-in at the shared shell layer.`settingsNavCatalog.ts`, `settingsNavVisibility.ts`, shared upgrade linkprimitives, trial banners, monitored-system warning banners, history-lockoverlays, and Patrol lock helpers must honor `presentationPolicy.hideUpgrade`by hiding paid prompts by default on ordinary self-hosted installs. Directactivation/recovery routes may render their owned content, but sidebar- discovery, trial CTAs, plan upsells, monitored-system limit pressure, and- feature upgrade links must require hosted mode, explicit handoff, or active- entitlement. Cloud interest links from self-hosted plan surfaces must hand+ discovery, trial CTAs, plan upsells, monitored-system limit pressure,+ feature upgrade links, and plan-lock Patrol banners must require hosted+ mode, explicit handoff, or active entitlement. Cloud interest links from+ self-hosted plan surfaces must handoff to Pulse Account/public Cloud ownership rather than route to anin-product Cloud trial/signup page.-37. Keep the identified-service reducer on `discoveryPresentation.ts`. Any+40. Keep the identified-service reducer on `discoveryPresentation.ts`. Anysurface that wants to label a workload with the AI-identified service(drawer overview card, future row chips, MCP capability payloads) mustconsume `getDiscoveryIdentifiedSummary` rather than re-implement the@@ -1870,6 +2139,33 @@ not a replacement status card, CTA band, or page-local nested card.## Current State+Patrol `fix_rejected` presentation is owned by the Patrol/AI finding surfaces+that render the governed-action loop, while the surrounding badge, button,+loading, and icon composition still uses shared frontend primitives. Shared+primitive code must not special-case rejected Patrol fixes outside the standard+metadata badge, button, and lucide-icon contracts.+Setup-only Patrol action chrome is also governed by the shared Patrol workspace+composition contract: provider-blocked states may show only the setup task and+direct `Open Provider & Models` action, must suppress the duplicate readiness+banner, and must not expose run-history buttons as a competing primary action+before Patrol can check infrastructure.+Patrol page setup banners must stay at operator level: render Patrol readiness+payloads as `Patrol setup issue` or `Patrol setup warning`, keep provider/model+context visible, and keep preflight/tool-call diagnostic wording inside+Provider & Models rather than the first-party Patrol header.+Pulse Intelligence settings now keep `Provider & Models` focused on provider+setup, default model selection, health, budget, usage, and provider checks; it+must not reintroduce the Patrol-control banner or `Open Patrol control` CTA+that belongs to the `Patrol` settings page and `/patrol` operator surface.+The Patrol settings page may still hydrate the cached Patrol diagnostic+snapshot, but the rendered model-check panel must summarize it as model+readiness rather than exposing preflight/tool-call implementation wording.+The canonical Provider & Models browser route is+`/settings/pulse-intelligence/provider`; `/settings/system-ai` remains a+routeable compatibility alias for old deep links, while new settings+navigation, OAuth callback redirects, Assistant repair actions, and Patrol+provider-repair CTAs must emit the Pulse Intelligence route.+Shared loading indicators are part of the active frontend primitive contract.`LoadingSpinner` owns pure loading and action-pending spinner shells for sharedprimitive internals such as `Button`, `PulseDataGrid`, and@@ -1907,9 +2203,11 @@ The Patrol alert-trigger severity selector under`frontend-modern/src/features/patrol/` is built on the shared `FormSelect`primitive (label-for/id wiring, `selectBaseClass` styling hook) rather than ahand-rolled `<select>`, so its labeling and disabled-state affordances stay-consistent with the rest of the AI settings surface.+consistent with the rest of the AI settings surface. That selector belongs in the+advanced Patrol settings disclosure, below the control policy that defines what+Patrol may do.-The Patrol configuration toggles in the same surface bind each `Toggle`+The advanced Patrol control toggles in the same surface bind each `Toggle`primitive's accessible name through `ariaLabelledBy` pointing at the row'sheading span, so renaming a control's visible label (for example"Alert-Triggered Analysis" to "Container Update Risk") updates the accessible@@ -1997,8 +2295,9 @@ The Patrol page header copy lives in a single canonical helper attooltip on `PatrolIntelligenceHeader.tsx` must read from`PATROL_PAGE_TITLE_TOOLTIP` exported alongside the description ratherthan carrying an inline copy, so hover and inline never drift apart on-what Patrol actually owns: scheduled probing, context assembly for the-configured model, and approval-bound action.+what Patrol actually owns: watching infrastructure, detecting issues,+recording findings, and escalating into governed investigation/action+only when the selected Patrol mode allows it.The same `PatrolIntelligenceHeader.tsx` shell also renders a compacttrust-at-a-glance summary directly under the page title (arender-only consumer of `state.patrolStatus()?.trust`), gated on at@@ -2341,13 +2640,16 @@ states: shared section shells under `frontend-modern/src/features/patrol/`must not render a green healthy empty state from `0 active findings` alonewhen the owning Patrol runtime or overall-health summary is degraded, blocked,or not fully verified.+The same empty-state helper must consume Patrol trust-history evidence so a+historical regression reads as history review context, not as a current issue+and not as a healthy all-clear.The same hierarchy also applies inside the Patrol summary shell: once theprimary assessment strip states Patrol's current risk and verification basis,supporting metrics under that strip must stay metric-oriented and must notrepeat assessment or verification labels as a second compact verdict row.The collapsed Patrol assessment strip itself must remain a compact readoutrather than a headline-plus-paragraph block; explanatory assessment and-recommendation copy belongs in the owning Findings, Runs, Supporting context,+recommendation copy belongs in the owning Findings, Runs, `Details`,or Assistant chat surfaces rather than a normal-path summary details expansion.That readout should lead with current operator state and score rather thanmixing a reassuring grade label with issue-state copy in the same line.@@ -2359,6 +2661,12 @@ That same summary-shell rule also applies to timing metadata: if the header,verification card, or findings footer already presents the governed Patrolactivity timestamp, the summary chip row must not add another recency badgethat competes with those owned timing surfaces.+The same default-readout rule applies to collapsed Patrol issue rows:+`MetadataBadge` may carry severity, recurrence, and active decision/work states,+but the default Patrol page must not render raw lifecycle or investigation+process badges such as `detected`, `review finding`, loop state, status, outcome,+or confidence as row chrome. Those details belong in expansion, run history,+Assistant handoff context, or diagnostics.The same ownership split applies to supporting counts: if the Patrol summarysurface renders the metric strip for active findings, warnings, criticals, andfixes, the primary assessment strip should not repeat those same counts in badge@@ -2617,14 +2925,11 @@ behavior, and whitespace handling. Product surfaces such as Patrol findingsmay own the labels and state-to-tone mapping in their presentation helpers, butthey must render visible metadata chips through `MetadataBadge` instead ofrecreating local bordered xs spans.-Patrol run-history, status-bar, and runtime-summary status labels follow this-state-badge boundary: Patrol may derive the status label and typed variant in+Patrol run-history labels follow this state-badge boundary:+Patrol may derive the status label and typed variant in`patrolRunPresentation.ts` or `patrolSummaryPresentation.ts`, but-`RunHistoryEntry.tsx`, `PatrolStatusBar.tsx`, and-`PatrolIntelligenceSummary.tsx` must render visible state badges through-`StatusIndicatorBadge` rather than `runStatus.badgeClass`,-`lastRunStatus.badgeClass`, `runtimeShellPresentation().badgeClass`, or a local-span.+`RunHistoryEntry.tsx` must render visible state badges through+`StatusIndicatorBadge` rather than `runStatus.badgeClass` or a local span.The shared segmented selector now follows that same owner split.`frontend-modern/src/components/shared/FilterButtonGroup.tsx` stays the rendershell, `frontend-modern/src/components/shared/useFilterButtonGroupState.ts`@@ -3019,7 +3324,7 @@ handoff lifecycle, andutility tab ordering, alert badge counts, fade-state derivation, and tabbutton class policy. Future mobile-nav work should extend those owners insteadof pushing tab-order or DOM lifecycle logic back into the shared shell. With-support/admin tools moved under Settings, that utility ordering must no longer+support/admin controls moved under Settings, that utility ordering must no longerreserve a standalone `operations` slot; alerts, Patrol, and Settings are theremaining authenticated utility tabs.The shared command palette now follows that same owner split.@@ -3453,7 +3758,10 @@ top-level settings shell, whiledeployment-specific install guide, copy-command block, and update-channel/installmodel data plus customer-facing update status/action copy. The panel shell mustnot rebuild copy-to-clipboard command cards, deployment instruction trees, or-update-surface wording inline.+update-surface wording inline. `CopyCommandBlock` must use the shared+`copyToClipboard` helper so install/update/agent snippets keep the same+Clipboard API fallback path and only report copied state after the shared copy+path succeeds.The reporting operations surface now follows the same shell-state-model rule.`frontend-modern/src/components/Settings/ReportingPanel.tsx` stays the@@ -3708,52 +4016,74 @@ recency/verification helpers already prove a successful full patrol withnon-zero resource coverage.That same Patrol shell ownership includes refresh affordance state:`frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts` must keep-operator refresh controls generation-aware and timeout-bounded, so a slow-supporting intelligence read cannot permanently disable the shared Patrol header-Refresh button while Patrol findings and status remain visible.+operator refresh controls generation-aware, timeout-bounded, and separate from+background polling state, so a slow supporting intelligence read cannot make the+shared Patrol header Refresh Patrol action spin indefinitely or stay disabled+while Patrol findings and status remain visible.That same Patrol shell should make scoped trigger policy legible withoutanother navigation step. `frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx`-should present alert-triggered and anomaly-triggered Patrol toggles as distinct-controls, and `frontend-modern/src/components/patrol/PatrolStatusBar.tsx`-should render compact activity breakdown and scoped-trigger-state copy from the-shared transport rather than leaving busy Patrol periods as unexplained noise.+should keep actionable scoped-trigger state legible without promoting+background-only policy pauses as default operator guidance; run-trigger details+belong in run history or explicit secondary context.That same Patrol-facing primitive vocabulary must stay product-first. Patrolsummary actions, runtime banners, run-history runtime-failure actions,-runtime-finding actions, circuit-breaker copy, and Patrol configuration controls+runtime-finding actions, circuit-breaker copy, and Patrol control/provider controlsmay point at the shared provider settings route or model catalog, but theyshould describe those controls as Patrol/provider surfaces through`frontend-modern/src/utils/patrolRuntimeActions.ts` rather than falling back togeneric `AI Settings`, `AI Model`, or `AI circuit breaker` copy inside thePatrol shell itself.-That same product-first naming rule also applies to the shared `system-ai`-settings shell: `frontend-modern/src/components/Settings/AISettings.tsx`,+That same product-first naming rule also applies to Pulse Intelligence settings:+`frontend-modern/src/components/Settings/AISettings.tsx`,`frontend-modern/src/components/Settings/settingsHeaderMeta.ts`,`frontend-modern/src/components/Settings/settingsNavCatalog.ts`,`frontend-modern/src/components/Settings/useAISettingsState.ts`, and-`frontend-modern/src/utils/aiSettingsPresentation.ts` must present that surface-to operators as `Assistant & Patrol` plus provider/model configuration rather-than as a generic `AI Services` shell.-On the main Patrol page, though, that same governed activity context belongs-inside `frontend-modern/src/features/patrol/PatrolIntelligenceSummary.tsx`-alongside the verification readout rather than as a second full-width band-above the findings workspace. If `PatrolStatusBar.tsx` is reused elsewhere, it-must stay a compact factual support surface and must not reintroduce a parallel-page-level verdict strip once the summary shell already owns that explanation.-That same composition rule applies to `frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx`:-once the summary shell carries the operator-facing verification and activity-story, the workspace should move directly into findings and run history instead-of repeating that same runtime context through a second pre-tab status strip.-Supporting context follows that same composition rule. Recent changes, learned-correlations, and policy coverage belong behind an explicitly secondary-supporting-context disclosure that only appears when Patrol has active-findings, degraded or incomplete verification, or a selected run that needs-explanation; healthy fully verified Patrol states must not advertise that-supporting evidence as a peer workflow. When that disclosure expands, the-workspace must explicitly label findings and run history as Patrol verification-evidence and frame the supporting cards as explanatory context rather than as a-fresh Patrol result. `frontend-modern/src/features/patrol/patrolSupportingContextPresentation.ts`-must own that disclosure copy and toggle wording so the Patrol workspace does-not regress into inline shell-local trust language.+`frontend-modern/src/utils/aiSettingsPresentation.ts` must present the provider+surface to operators under the `Pulse Intelligence` settings group as+`Provider & Models` provider/model configuration rather than as a generic+`AI Services` shell. The canonical browser route for that surface is+`/settings/pulse-intelligence/provider`; legacy `/settings/system-ai` links may+remain routeable compatibility aliases, but new navigation, setup, Assistant,+and Patrol repair CTAs must emit the Pulse Intelligence route.+On the main Patrol page, though, governed activity context belongs inside+`frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx` as current+work, selected run history, or explicit details. Do not reintroduce a+parallel page-level status strip above the current-work workspace.+That same composition rule applies to the workspace: the default path should+move directly into findings and run history instead of repeating runtime+context through a second pre-tab status strip.+`Details` follows that same composition rule. Recent changes,+learned correlations, and policy coverage belong behind an explicitly secondary+supporting-context affordance that only appears when Patrol has active findings+or a selected run that needs explanation; healthy fully verified Patrol states+and degraded summary health by themselves must not advertise that supporting+evidence as a peer workflow. The default workspace may show the compact+`Details` control, but the full panel must render only after the operator+opens it. When that disclosure expands, the workspace must explicitly label the+selected finding or run as Patrol's record and frame the supporting cards as+explanatory context rather than as a fresh Patrol result or raw evidence+console.+Selected-run history should also suppress generic findings filter chrome and+read as a Patrol run record. Missing legacy `finding_ids` remains an internal+fail-closed scoping condition, but the visible caveat should say the finding+record is unavailable rather than exposing snapshot/filter vocabulary.+Workspace section descriptions must use Patrol-owned mode presentation copy+that reflects the selected mode and lock state; they must not hardcode+an all-mode sentence that tells watch-only users Patrol can investigate, ask for+approval, or fix issues. The Patrol workspace must not add a generic Details+panel to explain learned correlations, recent changes, or policy buckets; those+signals may support Assistant and backend reasoning without becoming default+operator chrome. Setup-only Patrol runtime failures must use the Patrol-owned+`Fix Patrol setup` workspace title and setup description plus a dedicated setup+task with the direct provider-settings action, rather than presenting that state+as a normal `Current issues` infrastructure queue, and they must suppress+generic issue-row chips, expand chevrons, and `Active` / `All` / `Resolved`+filter chrome in that setup-only state. That setup-only workspace must also be+the only visible provider-repair CTA for that state: it should use the+`Open Provider & Models` action and suppress the readiness banner so setup does+not appear twice. Run history must stay hidden as a competing action until+Patrol can check infrastructure or an operator is already reviewing a specific+run record.Shared primitive consumers that split status-dot tone and status-text tonemust now keep both values routed through the same exported presentation helper.@@ -4047,9 +4377,12 @@ runtime lifecycle and persistence flow, model/provider setup now routesthrough `AIModelSelectionSection.tsx`, discovery, budget, timeout, andpermission controls route through `AIRuntimeControlsSection.tsx`, chatmaintenance routes through `AIChatMaintenanceSection.tsx`, and readiness plus-save/test actions route through `AISettingsStatusAndActions.tsx`. Future AI-settings work must extend those section owners instead of re-inlining large-runtime subsections into the shell.+save/test actions route through `AISettingsStatusAndActions.tsx`.+`AISettingsStatusAndActions.tsx` may expose provider connection status and+test actions only for the Provider & Models page; section pages reuse the save+bar without making Patrol, Assistant, or Discovery look like provider setup+screens. Future AI settings work must extend those section owners instead of+re-inlining large runtime subsections into the shell.Provider-specific settings fields inside`AIProviderConfigurationSection.tsx` must remain model-driven through`aiSettingsModel.ts` `extraFields`, including Ollama `keep_alive`, so the@@ -4096,21 +4429,20 @@ the `system-billing` navigation label, header title/description, and billingshell framing must all route through `SELF_HOSTED_PRO_BILLING_PRESENTATION`instead of drifting independently. The owned split is now explicit: thenavigation label comes from `navLabel`, while the route header and billing-shell reuse `shellTitle` plus `shellDescription`, so the settings IA can stay-plan-owned (`Plans`) while the page itself still names the concrete job-(`Self-hosted plan`) without reintroducing local label drift.+shell reuse `shellTitle` plus `shellDescription`, so the settings IA and page+shell stay aligned on `Plans & Billing` without reintroducing local label drift.That same settings-shell framing boundary also covers adjacent top-levelsettings references to the self-hosted commercial surface. When`InfrastructureWorkspace.tsx` or other settings-shell surfaces point operators-toward Plans for billing, license status, or paid feature activation, they+toward Plans & Billing for billing, license status, Patrol mode, or paid feature access, theymust reuse the shared referral copy from`SELF_HOSTED_PRO_BILLING_PRESENTATION` rather than drafting local “go therefor billing” variants.That same shared presentation owner now also carries the entitlement-firstcommercial summary contract for self-hosted settings. The top-level navigation-entry stays product-IA owned through `navLabel` (`Plans`), while the page-header and shell title stay task-owned through `shellTitle`-(`Self-hosted plan`), and the billing shell must foreground the active plan+entry stays product-IA owned through `navLabel` (`Plans & Billing`), while the+page header and shell title stay owned through `shellTitle`+(`Plans & Billing`), and the billing shell must foreground the active planname plus available capabilities before secondary billing or recovery detail.Paid upgrades should be able to confirm “Current plan: Pulse Pro” immediatelyafter activation without hunting through generic billing language or a second@@ -4217,9 +4549,11 @@ external URLs.That same shared-shell framing also covers the concise telemetry summary inGeneral settings. The shell may present the privacy contract in compact productcopy, but the vocabulary for anonymous outbound telemetry must stay aligned-with `security-privacy`: aggregate self-hosted adoption counts and coarse-feature flags are allowed, while hostnames, credentials, infrastructure-identifiers, prompts, chat messages, and personal information are not.+with `security-privacy`: aggregate self-hosted adoption counts, coarse feature+flags, and coarse Patrol, Assistant, and external-agent usage counters are+allowed, while hostnames, credentials, infrastructure identifiers, prompts,+chat messages, command text, action output, token values, and personal+information are not.That same docs-link boundary also governs local legal docs surfaced from thesettings shell: shared settings surfaces such as`AIRuntimeControlsSection.tsx` must route Terms-of-Service links through thediff --git a/docs/release-control/v6/internal/subsystems/organization-settings.md b/docs/release-control/v6/internal/subsystems/organization-settings.mdindex a52d7e4e2f..3530b01c71 100644--- a/docs/release-control/v6/internal/subsystems/organization-settings.md+++ b/docs/release-control/v6/internal/subsystems/organization-settings.md@@ -282,7 +282,10 @@ context. `frontend-modern/src/components/Settings/settingsPanelRegistryContext.tmust pass the effective authenticated username from `SecurityStatus` into theorganization overview, access, and sharing panels so membership-derived ownerand admin actions render consistently for local auth, proxy-auth, and SSO-sessions.+sessions. Non-organization settings composition, including Pulse Intelligence+panel splits, may share the same registry context only when it does not fork or+reorder that current-user projection for organization overview, access, or+sharing panels.The RBAC settings area now follows the same extracted-owner pattern as theother modernized settings surfaces: `RBACFeatureGateSection.tsx` owns theshared paywall CTA rendering, `useRBACFeatureGateState.ts` owns the shareddiff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.mdindex 7a5c3eac28..6f147ddc7d 100644--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md@@ -22,33 +22,35 @@ Patrol-specific presentation helpers.## Canonical Files1. `frontend-modern/src/features/patrol/PatrolIntelligenceSurface.tsx`-2. `frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts`-3. `frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx`-4. `frontend-modern/src/features/patrol/PatrolIntelligenceBanners.tsx`-5. `frontend-modern/src/features/patrol/PatrolIntelligenceSummary.tsx`-6. `frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx`-7. `frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts`-8. `frontend-modern/src/pages/AIIntelligence.tsx`-9. `frontend-modern/src/stores/aiIntelligence.ts`-10. `frontend-modern/src/stores/aiIntelligenceSummaryModel.ts`-11. `frontend-modern/src/types/aiIntelligence.ts`-12. `frontend-modern/src/components/AI/FindingsPanel.tsx`-13. `frontend-modern/src/components/Brand/PulsePatrolLogo.tsx`-14. `frontend-modern/src/components/patrol/`-15. `frontend-modern/src/utils/aiFindingPresentation.ts`-16. `frontend-modern/src/utils/approvalRiskPresentation.ts`-17. `frontend-modern/src/utils/approvalState.ts`-18. `frontend-modern/src/utils/aiPatrolSchedulePresentation.ts`-19. `frontend-modern/src/utils/findingAlertIdentity.ts`-20. `frontend-modern/src/utils/remediationPresentation.ts`-21. `frontend-modern/src/utils/patrolEmptyStatePresentation.ts`-22. `frontend-modern/src/utils/patrolFormat.ts`-23. `frontend-modern/src/utils/patrolRunPresentation.ts`-24. `frontend-modern/src/utils/patrolSummaryPresentation.ts`-25. `frontend-modern/src/utils/patrolRuntimePresentation.ts`-26. `frontend-modern/src/utils/patrolRuntimeActions.ts`-27. `frontend-modern/src/utils/textPresentation.ts`-28. `tests/integration/tests/73-patrol-assistant-operator-briefing.spec.ts`+2. `frontend-modern/src/features/patrol/patrolAutonomyAvailability.ts`+3. `frontend-modern/src/features/patrol/patrolControlPresentation.ts`+4. `frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts`+5. `frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx`+6. `frontend-modern/src/features/patrol/PatrolIntelligenceBanners.tsx`+7. `frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx`+8. `frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts`+9. `frontend-modern/src/pages/AIIntelligence.tsx`+10. `frontend-modern/src/stores/aiIntelligence.ts`+11. `frontend-modern/src/stores/aiIntelligenceSummaryModel.ts`+12. `frontend-modern/src/types/aiIntelligence.ts`+13. `frontend-modern/src/components/AI/FindingsPanel.tsx`+14. `frontend-modern/src/components/Brand/PulsePatrolLogo.tsx`+15. `frontend-modern/src/components/patrol/`+16. `frontend-modern/src/utils/aiFindingPresentation.ts`+17. `frontend-modern/src/utils/approvalRiskPresentation.ts`+18. `frontend-modern/src/utils/approvalState.ts`+19. `frontend-modern/src/utils/aiPatrolSchedulePresentation.ts`+20. `frontend-modern/src/utils/findingAlertIdentity.ts`+21. `frontend-modern/src/utils/remediationPresentation.ts`+22. `frontend-modern/src/utils/patrolEmptyStatePresentation.ts`+23. `frontend-modern/src/utils/patrolFormat.ts`+24. `frontend-modern/src/utils/patrolPagePresentation.ts`+25. `frontend-modern/src/utils/patrolRunPresentation.ts`+26. `frontend-modern/src/utils/patrolSummaryPresentation.ts`+27. `frontend-modern/src/utils/patrolRuntimePresentation.ts`+28. `frontend-modern/src/utils/patrolRuntimeActions.ts`+29. `frontend-modern/src/utils/textPresentation.ts`+30. `tests/integration/tests/73-patrol-assistant-operator-briefing.spec.ts`## Shared Boundaries@@ -57,6 +59,232 @@ Patrol-specific presentation helpers.## Extension Points1. Add or change Patrol page orchestration through `frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts`, keep `frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts` as the canonical investigation-context derivation owner, keep `frontend-modern/src/features/patrol/PatrolIntelligenceSurface.tsx` as the feature shell, keep the Patrol-owned section files under `frontend-modern/src/features/patrol/` as the heavy render owners, keep `frontend-modern/src/pages/AIIntelligence.tsx` as the route shell, keep `frontend-modern/src/stores/aiIntelligenceSummaryModel.ts` as the canonical AI summary normalization owner, and update `frontend-modern/src/stores/aiIntelligence.ts` together+ The default Patrol workspace is the current-issues list. It must not add a+ second proof strip that restates the same finding, approval, or setup+ problem above the list. When active Patrol findings are the next operator+ step, the finding row owns the canonical primary action, contextual+ Assistant handoffs, approvals, verification, and manual controls. Because a+ contextual Assistant handoff from that workflow is still a first-party Patrol+ starter for the same governed journey, it must record content-free workflow+ prompt activity through the shared marker route with the `pulse_patrol`+ surface before the drawer opens; it must not include finding IDs, prompt+ text, resource context, model output, or direct-action payloads in that+ marker.+ Runtime/setup findings are still active Patrol work, but setup-only runtime+ failures must read as one setup task rather than an infrastructure issue+ queue. The header may suppress run and schedule/model controls while setup is+ the only active work, but it must keep the Patrol mode selector visible+ because the operator's autonomy boundary remains a primary product choice+ even before Patrol can run. The workspace must replace the generic findings+ row with a dedicated provider/runtime setup task, one current issue label,+ and the direct provider-settings action. It must not show runtime severity+ chips, loop-state chips, recurrence badges, expand chevrons, or finding+ filters in this state because those controls do not help the operator fix+ Patrol setup.+ The Patrol page must not expose a generic Details/supporting-context evidence+ panel for nearby activity, learned correlations, or policy buckets. Those+ payloads may still feed Assistant context, backend investigation, and explicit+ run or finding records, but the default first-party Patrol page stays on the+ issue, consequence, and next action.+ Initial Patrol data refresh failures are degraded data state, not a route+ failure: `usePatrolIntelligenceState.ts` must fail soft, keep the Patrol+ workspace visible, and let `PatrolIntelligenceBanners.tsx` show one short+ stale-data retry banner without leaking raw transport errors.+ Watch-only and locked-control copy must describe Patrol as watching+ infrastructure and showing current issues, while the selected Watch only+ mode must describe the capability positively, such as Patrol watching+ infrastructure and reporting issues only.+ It must not frame the free/monitor boundary as evidence recording,+ proof collection, or a disabled version of remediation. Paid mode labels+ must stay short operator choices (`Ask first`, `Safe auto-fix`,+ `Autopilot`) and must not reintroduce Pro-matrix labels such as+ `Ask before changes`, `Auto-fix safe issues`, or `Policy autopilot`.+ Plan-locked Patrol controls may keep the paid choices visible as disabled+ buttons; compact Pro badges and a `Plans & Billing` action may appear only+ when upgrade prompts are allowed. That billing action is a compact handoff+ beside the mode controls, not a separate upsell panel. The selected mode must+ remain Watch only and the default copy must not become a feature-matrix or+ absence explainer.+ Paid Patrol control handoffs that start or continue the same+ journey must reach Patrol through the route-backed+ `/patrol?patrolControlStarter=patrol_control#patrol-control` affordance.+ `usePatrolIntelligenceState.ts` owns consuming that coarse starter query+ before the initial Patrol data load, writing the same content-free workflow+ prompt activity through the `patrol_control` surface, and then replacing+ the URL with the clean Patrol control anchor. The legacy+ `operationsLoopStarter=patrol_autonomy` and+ `operationsLoopStarter=pulse_pro_activation` values must remain accepted as+ compatibility aliases that normalize to the current Patrol control marker,+ and `#operations-loop` may exist only as an inbound compatibility anchor.+ That route flag is only a first-party starter marker; it must not carry+ finding IDs, prompt arguments, resource context, model output, or+ completed-work proof.+ Direct Patrol control selection from the Patrol page is also a first-party+ starter for that paid Patrol operator journey. After a successful autonomy+ settings save, `usePatrolIntelligenceState.ts` must record the same+ content-free `patrol_control` marker when the effective autonomy level or+ full-control acknowledgement actually changes and the paid Patrol control+ feature is available, then refresh Patrol status, findings, approvals, and+ run history so the next Patrol operator step is visible without waiting for a+ later poll or page reload. Locked Community/runtime saves and repeated no-op selections must+ not record paid starter activity.+ The same journey may count a generic Patrol run or recency timestamp as+ readiness to start, but it must not advance the current operator state until+ it has issue-backed Patrol evidence: an active or resolved finding,+ investigation state, pending approval, governed action, verified fix, or+ Patrol status trust signal. A healthy no-finding run stays on the Patrol+ watch state instead of masquerading as Assistant-ready work.+ The current operator state must consume the canonical+ `/api/agent/operations-loop/status` projection through the shared+ agent-capabilities frontend client when that status is available; page-local+ Patrol counts may remain only as resilience fallback and UI affordance state+ for whether Patrol can run or which single finding can be opened. Patrol page+ components must not maintain a second progress state machine+ once the backend projection has loaded. The loaded and fallback current-work+ models must keep approved and rejected governed-action decisions distinct:+ approved decisions continue to the verified-outcome step, while a rejected+ only decision is a terminal no-execution outcome and must not strand the+ operator on a verification step that cannot run.+ The same model must treat active findings and pending approvals as current+ operator work. Older completed or resolved Patrol control proof carried by+ primary `patrolControl*` fields may tailor history copy, but it must+ not make the primary action, title, or step status say the work is done+ while an active finding or approval remains. Current+ active findings must route the primary current-work action to the canonical+ finding primary action when exactly one active finding exposes one, or back+ into the Patrol findings workflow first when no direct action exists, even+ when the backend projection still says `open_assistant`; Assistant remains a+ contextual handoff from the selected finding or approval rather than the+ primary Patrol investigation CTA. The primary current-work state and+ compact progress label must describe current work state (`ready`, `needs+attention`, `approval needed`, `outcome verified`, `no active work`) instead+ of repeating the selected mode; the Patrol mode selector/header+ owns current-mode copy, and local Patrol state must expose work evidence as+ Patrol-owned issue/work counts rather than legacy proof counts.+ When no active finding or pending approval remains, terminal verified or+ rejected outcomes must read as history behind a `no active work` current+ state; current-state copy must not ask operators to reconcile old approved+ work with the current autonomy boundary. Historical verified outcomes with+ no current operator action must not render a separate proof strip+ solely to link to history; the Patrol workspace owns the deliberate history+ review affordance.+ Resolved-only issue history and trust counters are not current operator work:+ they may support history or analytics copy, but they must not make the+ primary Patrol status say Patrol found a current issue when the active+ finding and pending-approval counts are zero. Compact Patrol summaries must+ label recurrence/trust counters as past evidence rather than placing+ bare `regressed` copy beside current healthy or active-finding state, and+ health scores must be named as a `health score` instead of rendering as+ unexplained `95/100` telemetry.+ The Patrol workspace must default to current operator work: current findings,+ active investigations, approval decisions, and selected finding snapshots.+ Its default visible title must be `Current work`, because that is the+ plain user-facing answer to what Patrol is handling or asking about now. The exception is a+ setup-only Patrol runtime failure: that state must use the `Fix Patrol setup`+ title and setup description while rendering a dedicated setup task instead of+ the generic finding row. When the list is empty, Patrol-owned empty-state copy+ must say there are no current issues and may reference past regressions only+ as history, not as current work.+ Run history is evidence and audit trail, not a peer top-level mode; expose it+ through an explicit history review affordance, keep the ledger visually+ bounded, and return the user to the findings snapshot when a historical run is+ selected. Broad supporting context such as recent changes, correlations, and+ policy coverage may be offered only as a compact `Details` affordance+ when there is an active Patrol finding or an explicitly selected history+ snapshot to explain. The full `Details` panel must render only+ after that affordance is opened; its copy must tell operators it explains+ Patrol's recorded finding or run state and must not present the data as a+ separate raw evidence console. Degraded health or historical recurrence alone+ must not surface a page-level forensic context block.+ The default Patrol surface must stay simple: the header, control selector,+ and current-work workspace own the ordinary operator state. Patrol must not+ render a separate always-visible status/activity/health strip just to prove+ the loop exists. Actionable runtime, setup, or coverage failures may still+ surface as concise warnings, and detailed status/trust/history evidence+ belongs behind the queue, history, or explicit context affordances.+ Manual page data sync is a secondary read-model affordance, not a Patrol+ operation. The Patrol header may expose it only as explicit page data sync+ for status, queue, approvals, and run history; it must not read as another+ Patrol run, must not be labeled `Refresh Patrol`, and must not use an+ endlessly animated spinner that competes with the actual Run Patrol action.+ The Patrol page must still remain understandable when the broader+ intelligence summary is missing or slow: keep the page title, selected Patrol+ mode, and current-work label visible instead of reintroducing a generic+ status strip.+ Plan-locked Patrol mode copy must present the effective Watch only+ capability as the current product state: Patrol watches resources, detects+ issues, and records findings. It must not render a default entitlement+ matrix, disabled paid-mode buttons, or compact Pro badges that tell ordinary+ free users what this install cannot do. Runtime-locked Pro installs may still+ show explicit blocking copy because the operator already has the entitlement+ and needs the correct runtime.+ User-facing copy names this choice `Patrol mode`; stable route markers,+ telemetry fields, and API wire names may retain `patrol_control`,+ `patrolControl*`, and older autonomy aliases for compatibility.+ Patrol mode must default to a simple user choice when paid control is+ available: show the current mode, one short sentence, and the four+ available modes. The+ control-specific policy contract, hard limits, and who-approves-what details are+ useful, but they must sit behind an explicit details/limits affordance rather+ than appearing as a default matrix on every page load.+ Paid-control availability copy must frame that decision as choosing what+ Patrol may handle automatically. It must not describe the user's choice as+ deciding how far Patrol can go or how much control Patrol has, because those+ phrases imply raw authority rather than governed scope.+ The Patrol page header is part of that same boundary: when the install is+ plan-locked to Watch only, the header description must present the current+ install capability rather than a disabled Pro matrix. When a Pro operator+ selects `Watch only`, the header must describe that selected mode as a+ no-change boundary, not as the whole Patrol product promise. Governed paid+ modes may use mode-specific watch/investigate/act/verify/record copy that+ matches the selected mode.+ Manual `Run Patrol` state must distinguish the start request from follow-up+ status refresh: `Starting` is only the short-lived request-to-start phase,+ while accepted or streaming runs move into the run-in-progress state and must+ not stay blocked behind slower dashboard/status reloads.+ Operations-loop starter counts from that backend projection are evidence+ that the Assistant, Patrol mode/autonomy compatibility entry point, legacy+ Pro activation entry point, or Pulse MCP entry point was used. A first-party+ Patrol control starter may help telemetry and entry-point routing, but it+ must not render a separate ready-to-run proof strip. The visible ready state+ belongs to the header control and `Run Patrol` action; it must not read as+ configuration proof such as+ `Patrol mode ready`. Legacy Pro activation starter aliases must stay+ compatibility evidence and must not render that ready-to-run strip by+ themselves. The+ Assistant step count from that projection is different: it is contextual+ collaboration evidence from Assistant context/tool usage or external-agent+ activity, and it should take precedence over starter counts when shown.+ Patrol must not use starter evidence to bypass the issue-evidence,+ governed-decision, or verification stages.+ The same first-party journey must not treat external-agent readiness as the+ operator's primary success condition. Pulse MCP contract availability still+ comes from the shared agent-capabilities manifest exposing the operations-loop+ workflow prompt and the required governed tools through the Pulse MCP surface+ contract, and loaded readiness still comes from the backend operations-loop+ status field after the server has checked for a non-expired API token covering+ at least one Pulse MCP-published capability scope. Patrol may use those facts+ for telemetry, settings handoff, and external-agent readiness, but the default+ Patrol page loop is governed operations: watch, investigate, act under policy,+ verify, and record. The first-party Patrol workflow state must not+ load manifest-backed MCP readiness or require MCP readiness props; Pulse+ Intelligence settings and external-agent surfaces own MCP setup/readiness,+ while API security owns only the scoped-token creation surface they link to.+ Patrol mode labels and details must match the backend execution policy:+ assisted mode may say it can run low or medium-risk fixes allowed by policy,+ but it must not imply that warning severity alone makes a command safe;+ high-risk, critical, destructive, or unknown-risk fixes remain approval-bound+ unless the operator has selected a broader autonomy level. Compact Patrol+ mode labels must remain understandable mode decisions (`Watch only`,+ `Ask first`, `Safe auto-fix`, `Autopilot`), not shorthand such as `Ask` or+ `Safe` that makes the operator infer what Patrol will do.+ The current-work and findings-workspace descriptions must derive from the+ active Patrol mode and lock state, not from a generic all-capability+ sentence. Watch-only installs must not advertise investigation, approvals, or+ fixes in the default findings copy. The default workspace description should+ tell the operator what Patrol-found problems will appear there and what+ Patrol may do under the selected mode; it must not describe internal+ queue mechanics, activation proof, or verification accounting.2. Add or change Patrol findings, approvals, investigation, status-bar, or run-history presentation through `frontend-modern/src/components/AI/FindingsPanel.tsx` and `frontend-modern/src/components/patrol/`Patrol owns run-history labels, counts, status variants, and domain copy, butvisible run-history, status-bar, and runtime-summary state badges must@@ -73,22 +301,85 @@ Patrol-specific presentation helpers.tone, loading indicator variant, or empty-state shell variant, extend theshared primitive and registry guard instead of adding page-local rounded pillspans, spinner spans, or empty-state wrappers.+ `RunHistoryPanel` is body content inside the Patrol workspace heading. It+ may show the selection hint and selected-run reset action, but it must not+ render a second `History` heading under the workspace's `Patrol history`+ heading.+ Current-findings empty states must reserve warning or error tones for active+ runtime/coverage/run problems; historical regressions without active+ findings remain informational history-review context, not an active-warning+ empty state.+ The default current-findings empty state must stay action-led and plain:+ use a verified `No current issues` state only when Patrol evidence supports+ it, use `Run Patrol to check everything` when coverage is incomplete, and do+ not reintroduce `Nothing needs attention` or all-clear phrasing for a view+ that is not fully verified. Degraded or incomplete checks should say Patrol+ could not finish a clean check and ask the operator to run Patrol to refresh+ current issues, rather than exposing verification/proof terminology.+ Visible Patrol summaries, runtime text, and run-history labels should use+ operator vocabulary such as `Patrol check`, `Targeted check`,+ `Follow-up check`, `Last check`, current issues, and outcomes. Backend+ fields may retain full-run, scoped-run, verification, and compatibility+ terminology where needed for cadence, audit, or API stability, but the+ default page must not ask ordinary operators to learn those internal proof+ distinctions before they can decide what to do next.+ Active Patrol finding expansion must stay action-led: description, impact,+ recurrence summary, primary action, Assistant handoff, approval, and manual+ controls are acceptable default content, but raw lifecycle telemetry belongs+ to explicit all/resolved/history/run-review contexts instead of the default+ current-issues expansion. Current active Patrol issue rows must also surface+ the canonical primary next action, when one exists, without requiring the+ operator to expand details first. The collapsed issue row is not a Patrol+ process log: it may show severity, resource, recency, recurrence, and+ actionable states such as approval required, investigation running,+ verification needed, failed fix, or setup attention, but it must not expose+ generic `detected`, `review finding`, raw loop-state, investigation-status,+ investigation-outcome, or confidence badges on the default Patrol page.Patrol approval and remediation actions own approval, denial, reapproval,review, and Assistant handoff semantics, but their visible action chrome mustcompose the shared `Button` primitive for success, warning-solid, primary,secondary, ghost, disabled, focus, and compact action behavior instead ofpage-local button shells.3. Keep remediation execution badge copy and severity styling aligned through `frontend-modern/src/components/patrol/RemediationStatus.tsx` and `frontend-modern/src/utils/remediationPresentation.ts`-4. Add or change Patrol header, summary, status runtime-state presentation, or runtime provider action presentation through `frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx`, `frontend-modern/src/features/patrol/PatrolIntelligenceSummary.tsx`, `frontend-modern/src/components/patrol/PatrolStatusBar.tsx`, `frontend-modern/src/utils/patrolRuntimePresentation.ts`, and `frontend-modern/src/utils/patrolRuntimeActions.ts`- Patrol summary presentation may show recent activity mix and trigger mode as- compact factual context sourced from Patrol run history and- `status.trigger_status`; it must not reintroduce status cards, suggested- actions, or a separate activity tab to explain the same facts. Effective- runtime blocks on event-triggered Patrol must also surface in the- always-visible Patrol header status line through the same- `status.trigger_status` presentation helper, so users can tell that- automatic alert/anomaly-triggered checks are paused without opening the- configuration popover or inspecting backend settings.+4. Add or change Patrol header, status runtime-state presentation, or runtime provider action presentation through `frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx`, `frontend-modern/src/features/patrol/PatrolIntelligenceBanners.tsx`, `frontend-modern/src/components/patrol/RunHistoryEntry.tsx`, `frontend-modern/src/utils/patrolRuntimePresentation.ts`, and `frontend-modern/src/utils/patrolRuntimeActions.ts`+ The header's primary run control must not become an unexplained disabled+ `Run Patrol` button when provider/model readiness blocks manual Patrol.+ In that state it becomes a direct `Fix setup` action to Provider & Models,+ while busy, disabled, unavailable, and already-running states can remain+ button states with their current reason attached.+ Patrol may show trigger mode and recent activity as compact factual context+ only inside explicit context/detail surfaces or actionable warnings sourced+ from Patrol run history and `status.trigger_status`; it must not reintroduce+ default status cards, suggested actions, or a separate activity tab to+ explain the same facts.+ Effective runtime blocks on event-triggered Patrol must pass through the same+ `status.trigger_status` presentation helper, but the default header and+ activity strip may surface them only when they explain an actionable manual+ Patrol block; background-only trigger pauses belong in secondary schedule and+ model diagnostics when manual Patrol still works.+ Patrol mode selection belongs to the always-visible header control;+ the header drawer is the secondary Schedule & model surface and may expose+ provider model, schedule, trigger tuning, and readiness errors, but it must+ not duplicate the four Patrol mode choices or reintroduce a save button+ for already auto-saving secondary fields. The provider model setting must lead with the effective+ Patrol/default model summary; the full model catalog is power-user detail+ behind an explicit change action, not the default content of the drawer.+ When Patrol mode is available, the Patrol mode selector must keep the+ default view to the selected mode and one short sentence. It must not render a+ secondary `Limits` disclosure, hard-limit matrix, or policy explainer on the+ primary operator surface; detailed policy configuration belongs in Patrol+ settings and governed action review, not beside the mode picker. That+ selected-mode sentence belongs in `patrolControlPresentation.ts`, not inline+ header markup, so the paid operator contract stays testable and does not+ drift into another activation/proof checklist. Plan-locked watch-only installs+ must not render that boundary as a Pro absence explainer. Watch-only copy in+ `patrolPagePresentation.ts`, `patrolControlPresentation.ts`, and+ `patrolAutonomyAvailability.ts` must describe Watch only in positive,+ capability-first language: Patrol watches infrastructure, records current+ issues, or records issues as it finds them. They must not repeat the same+ sentence across the header and mode control, repeatedly restate+ infrastructure-unchanged caveats in the default view, or imply Patrol's main+ value is a manual review chore.5. Add or change Patrol header schedule and runtime presentation through `frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx`, `frontend-modern/src/utils/aiPatrolSchedulePresentation.ts`, and `frontend-modern/src/utils/patrolRuntimePresentation.ts`.Patrol must not surface retired hosted-model credit badges or trial-like activation prompts in the normal self-hosted GA app, even when legacy transport fields are still present.6. Keep Patrol and chat identifier-label presentation aligned through the shared `frontend-modern/src/utils/textPresentation.ts`@@ -117,10 +408,66 @@ Patrol-specific presentation helpers.mask direct Patrol evidence that has already loaded. Background Patrolrefreshes must preserve already-loaded findings instead of replacing theworkspace with a blocking loading state.- Patrol page refresh state must also be generation-aware and timeout-bounded:- slow or stalled supporting intelligence reads may continue in the background,- but they must not permanently disable the operator's Refresh control once- Patrol findings and status remain visible.+ Selected run-history snapshots must render their recorded empty or+ unavailable finding state immediately; a global Patrol findings refresh may+ only block the selected run view while the run references finding ids that+ still need the direct Patrol findings payload.+ Patrol page refresh state must also separate background data loads from the+ operator-clicked Update status action: slow or stalled supporting+ intelligence reads may continue in the background, but they must not make the+ shared header action spin or stay disabled once Patrol findings and status+ remain visible. The header action is a status/history sync affordance; it+ must not read like another Patrol run or imply that it changes+ infrastructure.+ Patrol trigger-status copy in the default header and activity strip must stay+ actionable. Runtime policy pauses for alert/anomaly-triggered background+ checks, such as the local development safety guard, may explain a blocked+ manual run or advanced diagnostics, but must not be presented as ordinary+ operator guidance when manual Patrol still works. The Patrol page header+ labels this line as `Automation`, not `Trigger status`, and when a run is+ already in progress the summary must say new automatic and manual runs are+ paused until the current run finishes. The Patrol enabled toggle label must+ remain distinct from run progress; a running Patrol still labels the toggle+ state as `Patrol enabled`, while the run button and current-issues list own+ `Running`/`Patrol running` copy.+ `PatrolIntelligenceHeader.tsx` owns the `patrol-control` route target and+ the `operations-loop` compatibility anchor used by Patrol mode entry-point+ handoffs; the page must keep those anchors on the actual always-visible+ Patrol mode selector rather than on a separate onboarding banner or+ generic Patrol container. The Patrol surface must preserve the+ issue-evidence rule: Patrol mode can start from a generic Patrol run+ state, but investigation, approval, verification, and external-agent parity+ require a real finding, investigation, or governed outcome signal. The native+ Patrol workspace must derive current work from Patrol status, findings,+ approvals, and run history rather than loading the authenticated+ operations-loop status projection. That projection may remain available to+ API, MCP, telemetry, and adjacent commercial surfaces, but it must not create+ a separate default proof strip or bypass the current-issues workflow.+ Legacy `patrolAutonomy*` and `proActivation*` fields may be consumed only at+ compatibility edges, not as first-party Patrol workspace state.+ Current active finding detail must use the current active-finding count for+ operator copy instead of the aggregate historical issue-evidence count, so a+ page with one live finding and older verified history reads as current work,+ not as a pile of old issues.+ The journey must also consume `patrolControlValueState` from that+ projection when present, falling back to `patrolAutonomyValueState` and then+ `proActivationValueProofState` only for compatibility. A+ `governed_decision_recorded` state is a safe+ terminal rejection/decision to review, not a verified value outcome, and its+ primary action must return the operator to decision context rather than the+ resolved-outcome list. A `verified` state may be presented as verified Patrol+ operations value; legacy `verified_needs_mcp` payloads must be interpreted as+ already verified first-party Patrol value with MCP readiness left as optional+ external-agent context.+ Run history is secondary review context: the default history panel must lead+ with recent snapshots and keep older runs behind an explicit expansion, while+ preserving full forensic access for operators who deliberately open it.+ Individual run entries must read as an operator action record first (`All+ clear`, `Found N new issues`, `Fixed N issues`, `N issues still open`, or+ `Patrol needs attention`) with checked-resource coverage as supporting+ detail. Trigger reason, duration, tool-call counts, tokens, triage flags,+ and raw tool traces are forensic context and must stay secondary to what+ Patrol did.2. Keep Patrol-specific copy and badge logic inside the governed Patrol presentation helpers instead of page-local branchesPatrol assessment copy must not present an all-clear health prediction whileactive Patrol findings or Patrol runtime issues are still present. The@@ -129,6 +476,9 @@ Patrol-specific presentation helpers.current findings state. Patrol-owned runtime issues must staydistinct from infrastructure findings in assessment copy rather than beingdescribed as infrastructure warning findings about Patrol itself.+ Historical Patrol trust regressions must also suppress a green all-clear in+ the current findings empty state: `0 active findings` means no current Patrol+ work, while prior regressions remain Patrol history review context.Assessment coverage caveats must also reconcile against current run-historyproof: a stale coverage factor or prediction must not claim recent coverageis incomplete when the latest completed full Patrol run successfully checked@@ -148,6 +498,11 @@ Patrol-specific presentation helpers.visible and actionable while blocking manual, scheduled, and scoped Patrolruns instead of letting operators discover provider/model/toolincompatibility through a failed run.+ On the Patrol page, that state must render as `Patrol setup issue` or+ `Patrol setup warning`, with provider/model context and the direct+ `Open Provider & Models` action. Raw diagnostic terms such as preflight,+ tool-call observation, or readiness internals belong in Provider & Models+ and backend/test contracts, not in the first-party Patrol operator banner.5. Keep customer-facing Patrol naming product-first: page titles, route chrome,summary copy, actions, and empty states should lead with `Patrol` or`Pulse Patrol` rather than generic `AI` branding. Reserve `AI` terminology@@ -330,9 +685,11 @@ Patrol-specific presentation helpers.renderer for that operator-facing impact text on the unified findingssurface: when an expanded finding card has populated `impact`, the panelrenders an `Impact:` line between `Description` and `Recommendation`.- The same panel also surfaces `investigation_record.confidence` as a- badge in the collapsed finding row (next to the investigation outcome- badge) so operators can scan trust without expanding every card.+ On non-Patrol findings views, the same panel may surface+ `investigation_record.confidence` as a collapsed-row badge beside the+ investigation outcome. The default Patrol page keeps that process evidence in+ the expanded issue, run history, or Assistant context so current issue rows+ stay readable.Finding rows must keep their disclosure control separate from inline manualcontrols: the row summary may be a keyboard-accessible expand/collapsebutton, but acknowledge, snooze, dismiss, and other per-finding actions must@@ -374,7 +731,7 @@ Patrol-specific presentation helpers.one, mirroring the impact rule that absent metadata is not fabricated.Expanded Patrol finding cards must keep action density product-grade: oneprimary Assistant intent button is visible inline (`Investigate`, `Verify- fix`, or `Explain` based on current finding state), while secondary+fix`, or `Explain` based on current finding state), while secondaryAssistant intents and operator management controls live behind compactin-flow `Assistant` and `Manage` menus. Those menus must render inside theexpanded finding detail rather than as clipped floating panels, and the@@ -448,19 +805,25 @@ Patrol-specific presentation helpers.approval-required mode, present a source-named visible drawer briefing, andframe Assistant as explanation and next-step review rather than execution orautomatic retry authority.-9. Keep the normal Patrol assessment summary plain and operator-first rather+9. Keep the normal Patrol status summary plain and operator-first ratherthan a hero-style or decorative card surface. The default collapsed state is- a compact readout, not a headline block: show the Patrol assessment label,+ a compact readout, not a headline block: show the Patrol status label,current operator state, concise high-signal trust posture such asregressions when present, and score. Do not combine reassuring grade labels such as`Health A` with issue-state copy such as `Issues detected` in the collapsedline. Do not add a normal-path assessment details expansion: assessmentexplanation, verification detail, activity mix, and supporting metrics belong in the- owning Findings, Runs, or Supporting context surfaces+ owning Findings, Runs, or `Details` surfacesinstead of reopening the compact strip into a sparse status panel.## Current State+Patrol provider-repair actions now use the canonical Pulse Intelligence >+Provider & Models route `/settings/pulse-intelligence/provider`. The legacy+`/settings/system-ai` route remains a compatibility alias for old deep links,+not a href emitted by new Patrol setup, finding, run-history, or summary+repair actions.+The finding lifecycle timeline renders backend lifecycle event types throughthe shared label map in`frontend-modern/src/utils/aiFindingPresentation.ts`@@ -492,7 +855,7 @@ surface for Patrol intelligence. This contract now owns that orchestration andpresentation boundary while leaving shared transport and payload-shapeownership in the governed AI runtime and API contract surfaces.-The Patrol configuration panel (`PatrolIntelligenceHeader.tsx`,+The Patrol control panel (`PatrolIntelligenceHeader.tsx`,`usePatrolIntelligenceState.ts`) exposes the per-rule alert-trigger policydirectly under the Alert-Triggered Patrols toggle. A minimum-severity selector("Investigate alerts at or above": Critical only / Warning and critical) renders@@ -503,16 +866,24 @@ selector reads `patrol_alert_trigger_min_severity` from the settings response,defaulting to critical-only, and must keep using the shared AI settings shaperather than forking a patrol-local form.-That same configuration panel disambiguates the two alert-driven AI toggles by+The Patrol page now keeps the Patrol mode policy inline on the main surface,+not inside the secondary Schedule & model drawer: the first configurable decision remains+what Patrol may handle automatically (`Watch only`, `Ask before changes`,+`Auto-fix safe issues`, `Policy autopilot`), and there must be only one visible+chooser for that decision.+Commercial, runtime, and documentation copy that describes this same decision+must also use those visible labels and the umbrella name `Patrol mode`, not+the retired `Only watch`, `Fix safe issues`, `Full control`, or generic+`Patrol control level` vocabulary.+Provider model, run schedule, trigger tuning, readiness checks, and saved+readiness issues belong to the secondary Schedule & model drawer. Within that+secondary drawer, the panel disambiguates the two alert-driven AI toggles byscope rather than by near-identical names. The genuinely general path isAlert-Triggered Patrols, which runs a focused Patrol investigation of the-alert's own issue. The Pro-gated `AlertTriggeredAnalysis` toggle now presents as+alert's own issue. The Pro-gated `AlertTriggeredAnalysis` toggle presents as"Container Update Risk" with copy scoped to container-update alerts, because theenterprise `AlertTriggeredAnalyzer` only assesses `docker-container-update`-alerts and returns nil for every other alert type. The panel is ordered-explanatory box first, then Alert-Triggered Patrols plus its severity selector,-then Anomaly-Triggered Patrols, then Container Update Risk plus its locked-upgrade note, then Autonomous critical remediation. New copy must keep the+alerts and returns nil for every other alert type. New copy must keep thecontainer-update toggle scoped to its real Docker-update-risk capability insteadof drifting back to a generically named "Alert-Triggered Analysis" control thatcollides with Patrol's own alert investigation.@@ -548,8 +919,8 @@ own `/api/settings/ai` or `/api/ai/models` reads. Patrol-specific state stillowns local toggle optimism, run-status orchestration, and Patrol-only copy,including runtime-availability messaging that stays Patrol-first inoperator-facing shells and uses provider/API-key wording only for the actual-configuration boundary, but the underlying AI runtime catalog must stay shared-with chat and AI settings. The Patrol configuration model selector must remain+provider settings boundary, but the underlying AI runtime catalog must stay shared+with chat and AI settings. The advanced Patrol model selector must remainstate-driven across async settings/catalog loading: a saved direct-providermodel such as `deepseek:deepseek-v4-flash` must render as that provider modelonce the shared catalog supplies it, not fall back visually to the default@@ -590,47 +961,53 @@ suppress stale healthy summary headlines such as `Health A · 100/100` even ifthe last summary payload still looks healthy. Legacy `/ai` entry points mustredirect into that same Patrol-owned shell rather than preserving a secondcanonical route.-That same browser proof now covers the Patrol configuration save contract.-The advanced Patrol panel must stay within the desktop viewport, scroll its-own contents to the Apply control, and surface the backend's concrete-license/validation reason when a save is rejected instead of replacing it with-a generic `Failed to save advanced settings` toast. That inline failure may+That same browser proof now covers the Patrol control and advanced-settings+split. The advanced Patrol settings drawer must stay within the desktop+viewport, avoid duplicating the inline Patrol control policy, expose+provider/model, schedule, trigger, and user-level model checks directly, and surface+the backend's concrete license/validation reason when a settings change is+rejected instead of replacing it with a generic `Failed to save advanced+settings` toast. That inline failure mayhandoff to Assistant only as model-only explanation context: raw command,script, credential, and provider-detail payloads stay redacted, Assistant opens-with `autonomousMode:false`, and the configuration panel closes so the operator-is not left behind an overlapping popover. Configuration-failure handoffs-must send safe `handoff_metadata.kind=patrol_configuration_failure` plus only+with `autonomousMode:false`, and the Patrol control panel closes so the operator+is not left behind an overlapping popover. Patrol-control save-failure handoffs+must keep the compatible `handoff_metadata.kind=patrol_configuration_failure` plus onlythe runtime-failure boolean needed for drawer/session presentation, so the-saved session restores as a Patrol configuration issue without carrying raw+saved session restores as a Patrol control issue without carrying rawprovider, credential, command, or retry payloads into the browser.Successful provider-model saves that return-`patrol_readiness.status=not_ready` are still configuration issues, not silent+`patrol_readiness.status=not_ready` are still Patrol control issues, not silentsuccesses: the Patrol popover must keep the saved provider/model visible,-render a `Patrol configuration needs attention` inline state with the returned+render a `Patrol control needs attention` inline state with the returnedreadiness cause and summary, and hand off to Assistant as a model-only Patrol-configuration issue rather than as a save failure.+control issue rather than as a save failure.The readiness contract now applies before Patrol work is admitted, not onlyafter a page render: recoverable Patrol provider/model settings saves mustpersist and echo structured readiness cause metadata, manual run requests mustreturn the structured readiness reason if a stale UI still submits, andscheduled or scoped alert/anomaly runs must skip before calling the model whilepreserving the blocked reason and cause in Patrol status. The Patrol-configuration state owner must also clamp stale investigation/remediation+control state owner must also clamp stale investigation/remediationautonomy back to findings-only `monitor` and clear stale full-mode unlock state-before submitting Apply Configuration when the safe-remediation entitlement is-not effective, so an expired or downgraded plan cannot turn a recoverable-configuration review into a Pro-only save failure. The same inline error+before persisting Patrol control when the safe-remediation entitlement is not+effective, so an expired or downgraded plan cannot turn a recoverable control+review into a Pro-only save failure. The same inline errorsurface must render any Patrol readinessprovider, model, and summary carried by the failure object, and keep theprovider-settings action immediately available before the operator chooses toopen the Assistant handoff.-The Patrol autonomy selector in that header must compose the shared-`frontend-modern/src/components/shared/FilterButtonGroup.tsx` segmented-variant instead of rebuilding a local active-button group. Patrol owns only-the domain options (`Monitor`, `Investigate`, `Remediate`), entitlement locks,-and the `full`-as-remediate presentation mapping; the shared primitive owns-the equal-width segmented shell, pressed-state semantics, disabled-option-behavior, and active/inactive selector styling.+The Patrol mode selector in that header and configuration dialog must+compose the shared `frontend-modern/src/components/shared/FilterButtonGroup.tsx`+instead of rebuilding a local active-button group. The wide default Patrol+header uses the segmented layout; the constrained configuration dialog may use+the shared prominent layout so all four mode labels remain readable without+inventing a Patrol-local selector. Patrol owns the default visible four-level+policy presentation (`Watch only`, `Ask before changes`, `Auto-fix safe issues`,+`Policy autopilot`), entitlement locks, and the rule that choosing the highest+policy-autopilot level sends `full_mode_unlocked:true` while choosing any lower level clears that+acknowledgement. The shared primitive owns pressed-state semantics,+disabled-option behavior, and active/inactive selector styling.That same Patrol-owned presentation rule also applies to the findings emptystate: `frontend-modern/src/components/AI/FindingsPanel.tsx` must not treat`0 active findings` as equivalent to "your infrastructure looks healthy" when@@ -688,37 +1065,34 @@ timing or reintroduce local trial-start actions.Under ordinary self-hosted v6, Patrol commercial affordances must also honorthe shared `presentationPolicy.hideUpgrade` contract. A free self-hostedinstall may show Patrol runtime availability and configuration gaps, but it-must not show Pro trial CTAs, upgrade links, or paid helper copy unless hosted-mode, an explicit commercial handoff, or an active entitlement makes those-actions relevant.+must not show Pro trial CTAs, upgrade links, paid helper copy, or a plan-lock+upsell banner in the default Patrol workflow unless hosted mode, an explicit+commercial handoff, or an active entitlement makes those actions relevant.That degraded empty-state copy must also interpret the finding state ratherthan simply replaying the primary assessment sentence verbatim: when coverage-is incomplete, the findings panel should tell the operator that Patrol has not-surfaced active findings but that this is not a full all-clear, so the page-does not duplicate the summary prediction as if it were a second independent-status surface.-The Patrol summary surface must follow that same hierarchy. The primary summary-headline in `frontend-modern/src/features/patrol/PatrolIntelligenceSummary.tsx`-should state Patrol's current assessment first, such as verified healthy,-issues detected, or coverage incomplete, with the health grade only as-supporting evidence. Secondary metric strips must not render `No issues found`-when the same governed overall-health summary says coverage is incomplete or-health still requires attention; that compact summary state now belongs to the-shared `frontend-modern/src/utils/patrolSummaryPresentation.ts` helper.-That primary assessment shell must also stay inside the shared Pulse card-language. The top summary should use the same neutral `bg-surface` page-card-base as adjacent Pulse surfaces, carrying severity through compact header-accents, icon treatments, and badges instead of tinting the entire full-width-assessment panel as a one-off warning banner.+is incomplete, the findings panel should tell the operator to run Patrol to+complete coverage before trusting the all-clear. The page must not duplicate+the assessment prediction as a second independent status surface above current+issues.+Secondary metric strips must not render `No issues found` when the same+governed overall-health summary says coverage is incomplete or health still+requires attention; compact assessment derivation belongs to the shared+`frontend-modern/src/utils/patrolSummaryPresentation.ts` helper for Assistant,+history, and explicit context consumers rather than the default Patrol page.+Any explicit context assessment shell must also stay inside the shared Pulse+card language. It should use the same neutral `bg-surface` page-card base as+adjacent Pulse surfaces, carrying severity through compact header accents, icon+treatments, and badges instead of tinting an entire full-width assessment panel+as a one-off warning banner.That supporting score chip must also avoid overstating infrastructure truth.When the current state is dominated by incomplete coverage or Patrol-ownedruntime failures, the chip should read as an `Assessment` grade rather than an`Health` grade; `Health` belongs to verified healthy infrastructure states.-That same helper also owns the primary assessment explanation. The summary card-must not pair an `Issues detected` headline with a raw coverage-only+That same helper also owns explicit assessment explanations. Assessment+consumers must not pair an `Issues detected` headline with a raw coverage-only`overall_health.prediction` sentence from a separate source; when active-findings and incomplete verification are both true, the Patrol summary should-describe both in one canonical assessment message.+findings and incomplete verification are both true, the assessment should+describe both in one canonical message.The same precedence applies to Patrol-to-Assistant assessment handoffs. Anactive finding, pending approval, or governed action reference must remain theprimary Assistant prompt and briefing posture even when the attached model@@ -763,6 +1137,10 @@ the same Patrol runtime classification with a runtime-qualified severity badgesuch as `Runtime issue` or `Runtime critical`, rather than pairing a genericinfrastructure severity chip like `warning` with a second Patrol-runtimelabel.+Runtime setup copy from that helper must stay neutral across watch-only and+paid control modes: it should explain that Patrol needs runtime or provider+setup before it can check infrastructure reliably, not promise investigation,+approval-backed fixes, or autonomous action from a locked install.Patrol run history must follow the same operator-facing runtime failurecontract. Expanded erroring runs should show the backend-provided`error_summary`, bounded `error_detail`, and the shared direct `Open Patrol@@ -794,15 +1172,35 @@ rather than repeating the product prefix or legacy `Insufficient API credits`wording once the surrounding UI already makes the Patrol context explicit.That same finding presentation contract should own the primary remediation pathfor Patrol-owned runtime findings as well. Expanded runtime-finding rows should-offer the same direct `Open Patrol provider settings` action that the top-assessment uses, instead of falling back to only generic acknowledge, snooze,-or dismiss controls.+lead with the same direct `Open Provider & Models` action that the top+assessment uses, and that action must use the canonical Pulse Intelligence+route `/settings/pulse-intelligence/provider` rather than the legacy+`/settings/system-ai` compatibility alias. Runtime/setup findings in the+default current-issues flow must stay primary-action-only: they should not add+a visible `Open in Assistant` secondary button or a generic `Manage` menu+beside the direct setup action.+Assistant can still receive runtime context from the broader Patrol/Assistant+handoff paths, but a setup impairment should not read as a menu of workflows.+When setup is the only active Patrol work, the Patrol page should collapse that+state into one `Fix Patrol setup` workspace task with the direct+`Open Provider & Models` action; the readiness banner must not duplicate that+same action above it.+The current-issues list must consume that same canonical primary action for+exactly one active runtime finding, so the visible next step opens Patrol+provider settings directly instead of making the operator first click through a+generic findings review CTA.+The setup-only Patrol workspace must keep that same single-path focus: when+Patrol cannot check infrastructure because provider setup is blocked, the+workspace may show the current setup issue and the provider-settings action, but+must not expose run history as a competing action until Patrol can actually+check infrastructure or the operator has opened a specific run record.That same contract must fail closed on manual lifecycle controls too. Patrolruntime findings are Patrol-owned impairment signals, not ordinary estatefindings, so the findings list must not offer generic acknowledge, snooze,dismiss, resolve, or suppress controls for them. The correct operator path is-to fix Patrol provider configuration in Assistant & Patrol settings and rerun-Patrol, optionally adding context notes, rather than hiding the runtime issue.+to fix Patrol provider configuration in Pulse Intelligence > Provider & Models+settings and rerun Patrol, optionally adding context notes, rather than hiding+the runtime issue.That same runtime-versus-infrastructure split must carry through the summarymetrics strip as well. When Patrol-owned runtime issues are active, thesupporting metrics must stop counting them under generic infrastructure@@ -845,44 +1243,45 @@ That summary-card/metrics-strip split also applies to findings counts. Theprimary assessment card may keep health as supporting context, but activefindings, warning counts, and critical counts belong to the supporting metricstrip rather than being repeated as duplicate badges inside the primary card.-That same summary surface must also explain what Patrol actually verified.-Recent run history should drive a visible verification summary that tells the-operator whether Patrol recently completed a successful full patrol, only ran-scoped alert-triggered checks, or ended its most recent full patrol with-errors, so the page does not leave trust and coverage as implicit background-knowledge.-When same-day run history shows both a recent full patrol and a burst of-scoped follow-up activity, that same verification surface should expose the-recent activity mix explicitly instead of leaving operators to reconcile a+That same summary surface must also explain what Patrol actually checked+without turning coverage mechanics into the default product language. Recent+run history should drive a visible check summary that tells the operator+whether Patrol recently completed a clean broad check, only ran targeted alert+or anomaly-triggered checks, or ended its most recent broad check with errors,+so the page does not leave trust and coverage as implicit background knowledge.+When same-day run history shows both a recent broad check and a burst of+targeted or follow-up activity, that same surface should expose the recent+activity mix in check language instead of asking operators to reconcile a`Recently verified` headline with a busy Patrol strip elsewhere on the page.-Fix-verification checks belong to that same explanation layer as targeted-activity, not as evidence of a fresh full-estate sweep.-The same hierarchy applies to supporting context. Correlations, recent-changes, and policy posture are secondary evidence for deeper investigation, so-the supporting-context disclosure belongs beneath the primary findings/history-workspace rather than inside the assessment card itself.-When that disclosure is expanded, the page must explicitly tell operators that-findings and run history are Patrol verification evidence, while recent-changes, learned correlations, and policy posture are explanatory context and-do not count as a fresh Patrol run.+Fix-verification checks belong to that same explanation layer as follow-up+checks, not as evidence of a fresh full-estate sweep.+The same hierarchy applies to the `Details` supporting context.+Correlations, recent changes, and policy posture are secondary explanation for+deeper investigation, so the default workspace may expose only the compact+context affordance near the findings/history controls. When that disclosure is+expanded, the page must render the panel as the immediate next workspace content+and explicitly tell operators that the selected finding or run record remains+the source of truth, while nearby activity, related patterns, and inspection+boundaries are context Patrol considered and do not change the finding or count+as a fresh Patrol run.When Patrol is healthy and fully verified, that supporting-context disclosureshould stay out of the main page flow instead of advertising a second parallelPatrol workflow with nothing active to explain.-That same operational context belongs inside the same secondary status area as-verification, not as a separate full-width strip that competes with the-findings workspace. `frontend-modern/src/features/patrol/PatrolIntelligenceSummary.tsx`-plus the shared `frontend-modern/src/utils/patrolRunPresentation.ts` helpers-should carry the latest run kind/result, recent activity mix, scoped-trigger-state, and any circuit-breaker warning as factual support beneath the primary-assessment instead of letting Patrol explain itself through multiple parallel-status bands.+That same operational context belongs behind the same secondary disclosure as+verification, not as a default full-width strip that competes with the findings+workspace. The workspace and shared+`frontend-modern/src/utils/patrolRunPresentation.ts` helpers may carry latest+run kind/result, scoped-trigger state, and circuit-breaker warnings as factual+support when the user opens the relevant context or when the page must surface+an actionable warning. They must not make activity-mix labels, raw run-count+breakdowns, health scores, or loop-proof counters default-page content.That same secondary area should simplify by consolidation rather than-deletion. Patrol should keep meaningful run and trigger facts visible, but it+deletion. Patrol should keep meaningful run and trigger facts available, but itshould stop repeating the same runtime story as a summary card, a metric row,and a separate status strip all at once.-If `frontend-modern/src/components/patrol/PatrolStatusBar.tsx` is reused in a-compact context elsewhere, it must stay factual and operational within that-same hierarchy rather than introducing a second Patrol verdict label.+Do not reintroduce a separate Patrol status strip for this context. Compact+activity facts belong in run history, selected finding details, or explicit+secondary context, not as a second Patrol verdict label.That same activity explanation should handle noisy Patrol behavior concretely.When same-day history shows a mix of full sweeps, verification checks, andscoped alert- or anomaly-triggered patrols, the verification/activity surface@@ -899,7 +1298,7 @@ plain-text renders: the latest-run segment must keep an explicit textualseparator between run kind and result, so degraded entries read as`Scoped run · error` rather than collapsing into concatenated strings like`Scoped runerror`.-Those runtime facts must stay aligned with Patrol configuration copy. The+Those runtime facts must stay aligned with Patrol mode copy. Theheader settings surface should expose alert-triggered and anomaly-triggeredscoped patrols as separate controls, with the legacy aggregate event-triggertoggle treated as compatibility-only transport rather than the primary product@@ -910,62 +1309,62 @@ Patrol page, `frontend-modern/src/components/AI/FindingsPanel.tsx` shouldexplain the absence of active findings without repeating `Last activity`,`Next run`, or interval schedule details that already belong to the header andverification hierarchy above.-That same empty-state contract must become run-snapshot-aware when the user is-filtering findings to an explicit Patrol run. A selected run with an explicit-empty `finding_ids` snapshot should explain that no findings were recorded for-that run and, when applicable, carry the canonical run coverage summary and-issue caveat instead of falling back to the generic `No Patrol findings to-display` copy.-That same snapshot scoping must apply to the findings control bar too. When the-user is looking at an explicit run snapshot, filter pills and their attention-or approval counts must derive from that snapshot-scoped finding set rather-than borrowing global Patrol finding counts from outside the selected run.-That same snapshot scoping must also apply to the `Findings` tab badge itself.-When the selected run carries an explicit empty `finding_ids` snapshot, or when-the run lacks snapshot ids entirely, the tab must fail closed instead of+That same empty-state contract must become run-record-aware when the user is+reviewing an explicit Patrol run. A selected run with an explicit empty+`finding_ids` record should explain that no findings were recorded for that run+and, when applicable, carry the canonical run coverage summary and issue caveat+instead of falling back to the generic `No Patrol findings to display` copy.+That same internal `finding_ids` scoping must apply to the findings control bar+too. When the user is looking at an explicit run record, filter pills and their+attention or approval counts must derive from that run-scoped finding set+rather than borrowing global Patrol finding counts from outside the selected+run.+That same run-scoped model must also apply to the `Findings` tab badge itself.+When the selected run carries an explicit empty `finding_ids` record, or when+the run lacks `finding_ids` entirely, the tab must fail closed instead ofborrowing global active-finding counts and tones from outside the selected run.That same scoped count model must drive conditional findings filters too. The`Needs Attention` and `Approvals` buckets, their counts, and the auto-resetlogic that returns the operator to `Active` when a bucket disappears must all-read from the same snapshot-aware count source rather than mixing-snapshot-scoped pills with global queue truth.-That same fail-closed snapshot rule applies to inline run-history findings as-well. Expanded run cards should route through the same snapshot-aware findings+read from the same run-scoped count source rather than mixing run-record pills+with global queue truth.+That same fail-closed `finding_ids` rule applies to inline run-history findings+as well. Expanded run cards should route through the same run-aware findingssurface as the primary workspace, so legacy runs without `finding_ids` still-show an explicit snapshot-unavailable state instead of disappearing or being-coerced into an empty findings snapshot.+show an explicit finding-record-unavailable state instead of disappearing or+being coerced into an empty findings record.That same rule applies to the primary findings workspace when a run isselected. A selected run without `finding_ids` must not borrow global Patrolfindings, filter buckets, or queue counts; the findings surface should enter an-explicit snapshot-unavailable state instead.-That same unknown-snapshot state should be visible in the selected-run shell-too. When the operator is filtered to a legacy run without findings snapshot-ids, the selected-run banner should explicitly say that findings snapshot data-is unavailable instead of implying a fully verifiable run-scoped findings view.+explicit finding-record-unavailable state instead.+That same unknown-record state should be visible in the selected-run shell too.+When the operator is reviewing a legacy run without `finding_ids`, the+selected-run banner should explicitly say that the finding record is unavailable+instead of implying a fully verifiable run-scoped findings view.That same trust rule applies inside expanded run-history narratives. A legacy-run without findings snapshot ids must not render an `All clear` conclusion+run without `finding_ids` must not render an `All clear` conclusionjust because its aggregate counters are zero; the narrative should explicitlystate that run-specific findings could not be fully verified.That same truthfulness rule applies to the expanded run outcomes strip. Legacy-runs without findings snapshot ids must not render a green `All clear` outcome-badge from zero aggregate counters; they should show an explicit snapshot+runs without `finding_ids` must not render a green `All clear` outcome badge+from zero aggregate counters; they should show an explicit finding-recordunavailable state instead.That same caveat belongs in compact latest-run summaries too. When the most-recent Patrol run predates findings snapshots, the status bar's latest-run-segment should say that findings snapshot data is unavailable instead of+recent Patrol run lacks `finding_ids`, the status bar's latest-run segment+should say that the finding record is unavailable instead offlattening the run into a plain healthy-looking summary.That same caveat belongs in collapsed run-history rows. Legacy runs without-findings snapshot ids must carry an explicit snapshot-unavailable marker in the+`finding_ids` must carry an explicit finding-record-unavailable marker in thetop row instead of looking like a clean zero-findings run until expanded.That same rule applies to run-status badges. A legacy run without findings-snapshot ids must not keep a green `healthy` badge when the surrounding UI is+records must not keep a green `healthy` badge when the surrounding UI issaying findings verification is unavailable; the canonical run-statuspresentation should downgrade that state to a neutral `completed` badge.That same truthfulness rule applies to the run-history shell copy. The `Recent-patrol runs` helper text must not promise that every visible run can filter-findings to a concrete snapshot; when visible runs include legacy entries-without `finding_ids`, or when the selected run itself predates findings-snapshots, the shell should say so explicitly.+patrol runs` helper text must not present run review as a findings filter; it+should frame history as Patrol run records, and when visible runs include+legacy entries without `finding_ids`, or when the selected run itself lacks a+finding record, the shell should say so explicitly.That same findings surface should keep its section chrome functional ratherthan promotional. Inside the Patrol findings tab, the selected tab alreadynames the surface, so the findings card should not add another in-card product@@ -988,17 +1387,27 @@ Patrol findings. Recurring active issues should read as `last seen ...` andsort by current observation recency rather than presenting only the original`detected_at`, which makes still-active Patrol service issues look stale whenthey were re-observed on recent runs.-That same finding row should avoid redundant state stacking. When an active-finding is already explicitly marked `Acknowledged`, the UI should not also add-the baseline `detected` loop-state badge beside it; loop-state badges only add-value there when they communicate a more specific Patrol state.+That same finding row should avoid redundant state stacking. Active Patrol issue+rows must not add baseline `detected` or raw loop-state badges; non-Patrol+finding rows may still use loop-state badges only when they communicate a more+specific state than acknowledged/current observation metadata.Collapsed finding-row badges now follow the shared metadata badge boundary:`frontend-modern/src/utils/aiFindingPresentation.ts` owns Patrol-specific-status/source/severity/investigation/confidence state-to-tone mapping, while-`frontend-modern/src/components/AI/FindingsPanel.tsx` renders those chips-through `MetadataBadge` with the shared outlined compact appearance. New+status/source/severity/investigation/confidence/workflow state-to-tone mapping,+while `frontend-modern/src/components/AI/FindingsPanel.tsx` renders those chips+through `MetadataBadge` with the shared outlined compact appearance. Patrol+workflow chips may appear only for specific actionable or recorded states such+as `Review approval`, `Verify outcome`, and `Outcome recorded`. Plain active or+detected findings must not add passive `Detected`, `Review finding`, or other+generic workflow badges beside the severity badge. Grouped current findings+must use issue/resource language, not internal signal-count language. Newfinding-row badges must extend the Patrol presentation helper and`MetadataBadge` tone vocabulary rather than restoring local bordered xs spans.+The visible finding summary is also the default disclosure target for the+issue: clicking it, pressing Enter, pressing Space, or using the explicit+View details/Hide details control must open the same detail panel. Inline+approval, setup, and manual action controls stay separate siblings so those+actions do not accidentally toggle the issue details.The inline investigation surface follows the same boundary:`frontend-modern/src/components/patrol/InvestigationSection.tsx` must compose`MetadataBadge` for live investigation status/outcome chips, durable Patrol@@ -1138,7 +1547,11 @@ Assistant handoffs and resource timelines can hydrate the same canonicalaction record before any operator decision or execution occurs. Those queuedfix records must carry `pulse_patrol` as the requester and lifecycle actor soresource timelines preserve the product source of the proposal instead of-flattening proactive Patrol work into generic Assistant chat activity. Pending+flattening proactive Patrol work into generic Assistant chat activity. Rejected+Patrol fix approvals must remain first-class Patrol outcomes: the backend+denial path records the shared action-audit decision, marks the owning finding+`fix_rejected`, and the Patrol control loop counts that state as a governed+action rejection while keeping approved-action verification separate. Pendingapproval payloads and Patrol Assistant handoff actions must carry the samerequester identity as safe metadata, without copying the approval commandpayload into Assistant.@@ -1159,21 +1572,23 @@ card, so the data-governance posture counts stay rendered from one governedfrontend component on the page instead of being duplicated in the resourcedrawer.That same Patrol summary surface now keeps health and findings primary while-rendering recent changes, learned correlations, and policy posture only as-supporting context behind an explicit disclosure, so expansion lane concepts-stay available for deeper investigation without reading as the headline Patrol-product story.+making recent changes, learned correlations, and policy posture available only+through the on-demand `Details` context inspector, so expansion+lane concepts stay available for deeper investigation without reading as the+headline Patrol product story.That secondary investigation-context summary now also routes through thededicated `frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts`owner, so the Patrol hook composes one canonical payload-to-summary derivationinstead of rebuilding recent-change, correlation, and governed-resource countcopy inline.The Patrol page's run-history tab label is now also tightened to `Runs`, while-the underlying run-history panel remains canonical for snapshot filtering and-tool-call inspection. That copy change is intentional: run history is support-context for Patrol findings, not a peer primary workflow beside findings.+the underlying run-history panel remains canonical for run-record review,+internal `finding_ids` scoping, and tool-call inspection. That copy change is+intentional: run history is support context for Patrol findings, not a peer+primary workflow beside findings, and visible copy should frame selected runs+as Patrol records rather than snapshot filters.Within that same run-history surface, coverage copy must stay canonical across-the header chips, narrative summary, and selected-run snapshot. Scoped runs+the header chips, narrative summary, and selected-run record. Scoped runsmust not present scope size and checked-resource count as contradictoryindependent facts; the shared run presenter should collapse them into onecoverage statement such as `Checked 1 of 2 scoped resources`, and zero-coverage@@ -1411,3 +1826,20 @@ operator dismissals (no `operator_state_cause` metadata) areunaffected by this wake path because the helper that detects thecause stops at the first `dismissed` event when scanning newestfirst, treating that as the authoritative state.+Patrol control may receive a starter count from the canonical operations-loop+status projection through `patrolAutonomy*` compatibility fields, with the+legacy entry-point starter count treated as the same entry-point context+when the primary field is absent. That count is only+journey copy; Patrol must still require active finding, pending approval,+governed action, or verified outcome evidence before it marks the Patrol issue+step complete or opens the Assistant handoff as a completed loop stage. Current+active findings and pending approvals must keep the journey on current work even+when older completed/resolved proof is present. The+projection may also report Patrol control completed-loop and resolved-loop+counts through compatibility fields, with legacy Pro activation counts as fallback aliases. Patrol may use+the completed-loop count only as content-free terminal decision detail after+the loop already has Patrol issue evidence, contextual collaboration, and+either a rejected governed decision or an approved governed decision with+verified outcome evidence. Patrol may use the resolved-loop count only as+stricter approved-and-verified detail after the loop also has an approved+governed decision and verified outcome evidence.diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex d3026e0667..449fcd0ea6 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -148,6 +148,22 @@ regression protection.1. Add performance budgets through SLO or contract tests2. Add query-plan guardrails for DB-backed hot paths3. Optimize hot paths only when backed by benchmarks or proven query issues+ The operations-loop status endpoint is performance-adjacent because it+ aggregates fleet, action-audit, workflow-starter, AI-usage, and+ external-agent activity evidence for every request. Starter and contextual+ collaboration evidence on that endpoint must come from persisted+ count-oriented histories in the existing evidence window, not from prompt+ payload scans, per-session transcript reads, model-response reads, or+ unbounded route/request history.+ Aggregate active finding precedence on that endpoint may read the existing+ in-memory Patrol findings store once for issue-level active counts, but it+ must not add a second per-resource registry walk or call the sorted UI+ presentation list just to decide current work.+ External-agent readiness on that same endpoint may inspect only the already+ loaded in-memory API token registry against manifest-derived Pulse MCP+ surface scopes; it must not add persistence scans, token usage history+ walks, transcript reads, or per-capability route probes to the protected+ request hot path.Workload platform-scope filtering and option derivation are part of theworkload table hot path. Shared selectors in`frontend-modern/src/components/Workloads/workloadSelectors.ts`,@@ -278,6 +294,13 @@ regression protection.action audit record to the agent SSE projection, but it must not performexecutor dispatch, resource rescans, model calls, or persistence fan-out onthe protected request setup path.+ Native Pulse Assistant tool provider and adapter wiring in+ `internal/api/router.go` follows that same protected hot-path rule: router+ setup may inject already-constructed Assistant `ToolAdapter` dependencies,+ while native Assistant naming and MCP protocol projection remain AI/runtime+ plus API-contract concerns. Performance-owned code must not use MCP-named+ native seams to justify extra model calls, persistence walks, or tool+ registry scans during route setup or generic request admission.Docker / Podman lifecycle execution uses the same bounded setup rule:`internal/api/router.go` may wire the API action executor once at startup,while per-action resource refresh, policy validation, agent command dispatch,diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.jsonindex 5ece4bc963..7ce8d781e5 100644--- a/docs/release-control/v6/internal/subsystems/registry.json+++ b/docs/release-control/v6/internal/subsystems/registry.json@@ -1,6 +1,30 @@{"version": 13,"shared_ownerships": [+ {+ "path": "cmd/pulse-mcp/main.go",+ "rationale": "the Pulse MCP adapter runtime is both an AI runtime surface for external-agent access to Pulse Intelligence and a canonical API contract projection over the agent capabilities manifest and Pulse MCP surface tool contract",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "cmd/pulse-mcp/README.md",+ "rationale": "the Pulse MCP adapter guide is both an AI runtime surface for external-agent access to Pulse Intelligence and a canonical API contract projection over the agent capabilities manifest",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "frontend-modern/src/api/agentCapabilities.ts",+ "rationale": "the agent capabilities frontend client is both the Pulse Intelligence external-agent manifest consumer and a canonical API payload contract boundary",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },{"path": "frontend-modern/src/api/agentProfiles.ts","rationale": "the agent profiles frontend client is both an agent lifecycle control surface and a canonical API payload contract boundary",@@ -17,6 +41,22 @@"api-contracts"]},+ {+ "path": "frontend-modern/src/api/aiChat.ts",+ "rationale": "the Assistant chat frontend client is both the first-party Assistant transport surface and a canonical API payload contract boundary",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "frontend-modern/src/api/generated/agentCapabilities.ts",+ "rationale": "the generated agent capabilities frontend types are both the Pulse Intelligence manifest TypeScript projection and a canonical API payload contract boundary",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },{"path": "frontend-modern/src/api/nodes.ts","rationale": "the shared Proxmox node client is both an agent lifecycle setup/install control surface and a canonical API payload contract boundary",@@ -169,6 +209,15 @@"unified-resources"]},+ {+ "path": "frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx",+ "rationale": "the External agents settings panel is the optional settings-shell projection of Pulse MCP onboarding, the AI runtime connected-agent onboarding surface, and a presentation consumer of the shared agent capabilities frontend client",+ "subsystems": [+ "ai-runtime",+ "api-contracts",+ "frontend-primitives"+ ]+ },{"path": "frontend-modern/src/components/Settings/APIAccessPanel.tsx","rationale": "the API Access settings intro is both a security/privacy token-management trust surface and a canonical settings-shell presentation boundary",@@ -441,6 +490,206 @@"unified-resources"]},+ {+ "path": "internal/agentcapabilities/action_target.go",+ "rationale": "the Pulse Intelligence governed action target type and resource-to-action-target mapping vocabulary are both the Assistant approval/runtime routing contract and the canonical API/agent target contract for governed actions",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/control_level.go",+ "rationale": "the Pulse Intelligence control-level vocabulary and control-tool availability predicate are both the Assistant runtime gating contract and the canonical API/agent permission posture for governed action tools",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/errors.go",+ "rationale": "the Pulse Intelligence agent error envelope is both the canonical API failure payload contract and the AI runtime adapter error-parsing contract for Assistant and external-agent surfaces",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/events.go",+ "rationale": "the Pulse Intelligence event vocabulary is both the canonical API SSE event contract and the AI runtime adapter notification contract for Assistant and external-agent surfaces",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/governance_prompt.go",+ "rationale": "the Pulse Intelligence surface-affordance-resolved model-facing operating-instruction, tool-governance prompt, reusable provider-tool governance description, Assistant-native offered-tool filtering, and Assistant-native interactive question-tool governance projections are both the Assistant system-prompt governance section and the shared API/agent vocabulary for action mode, approval posture, MCP affordance advertisement, and non-registry interaction-tool boundaries",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/http.go",+ "rationale": "the Pulse Intelligence agent HTTP substrate is both the API capabilities invocation contract and the shared AI runtime adapter execution primitive for MCP and reference agent clients",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/manifest.go",+ "rationale": "the canonical Pulse Intelligence agent capabilities manifest declaration, including capability display titles, manifest-owned finding lifecycle schemas, manifest-owned governed action schemas and routes, manifest-owned external-adapter surface tool contracts, and manifest-owned structured output schemas, is both the API discovery payload source and the AI runtime projection contract for Pulse Assistant and MCP-facing agent tools",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/markdown.go",+ "rationale": "the Pulse Intelligence manifest Markdown projection, including manifest-owned capability titles, surface-filtered Pulse MCP tool/error inventories, and prompt labels, is both the canonical API/agent documentation projection and the AI runtime onboarding projection for Assistant-compatible external-agent surfaces",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/mcp.go",+ "rationale": "the Pulse Intelligence MCP protocol version, JSON-RPC, method dispatch, method payload, surface-tool-contract-gated initialize operating-instruction and capability advertisement payload, manifest surface-filtered tools/list and tools/call execution bridge, manifest surface-gated resources/list and resources/read bridge, manifest-owned and surface-affordance-gated workflow prompt projection, protocol wire aliases, resource and prompt handler gates, and notification projection collectively define the external-agent adapter wire contract over the shared Pulse Intelligence tool core; MCP initialize, tools/call execution, resource list/read projection, and prompt list/get projection must enter through manifest-owned surface and workflow-prompt contracts so raw capability slices cannot bypass the published external-adapter contract",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/mcp_adapter.go",+ "rationale": "the Pulse MCP adapter setup contract defaults and normalization are both the canonical API manifest setup projection and the AI runtime onboarding contract for Assistant-compatible external-agent surfaces",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/projection.go",+ "rationale": "the agent capability external-tool projection helper, normalized manifest-owned surface tool contract resolution and tools-affordance gating, manifest-owned resource-context route and argument vocabulary, operator-state capability and route vocabulary, finding workflow capability and lifecycle argument vocabulary including resolution and dismissal notes, governed action capability, route, and argument vocabulary, manifest-owned tool title and outputSchema projection, structured Pulse capability _meta, and shared tool behavior hints are both the canonical API manifest projection contract and the AI runtime adapter projection for Pulse Assistant and MCP-facing agent tools, with MCP annotation and metadata wire names confined to adapter-edge aliases",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/provider_tool_artifacts.go",+ "rationale": "the provider tool-call artifact detector and streaming tool-name prefix splitter are both the Assistant stream-sanitization boundary and the shared external-adapter leak guard for provider-native tool-call markup that escaped the structured channel",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/schema.go",+ "rationale": "the agent capability input schema contract is both the canonical API manifest schema envelope and the AI runtime structured tool-schema, governance-aware provider-projection with neutral behavior hints and Pulse governance metadata, offered-tool governance extraction for Assistant prompt policy, manifest-affordance-gated Assistant provider-surface composition, manifest raw-schema to Assistant provider-schema projection for capability tools, legacy native Assistant utility provider aliases and schemas, provider-call normalization, provider-result context projection, Assistant-native interaction provider-tool declaration, and live Assistant execution-normalization contract for Pulse Assistant and MCP-facing agent tools",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/scopes.go",+ "rationale": "the manifest-derived required-scope summary is both the canonical API/agent token guidance contract and the AI runtime adapter startup/onboarding contract for Assistant-compatible external-agent surfaces",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/sse.go",+ "rationale": "the Pulse Intelligence SSE subscription transport and record parser are both the canonical API event-stream consumption contract and the AI runtime adapter push bridge contract for MCP and reference agent clients",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/surface_contract.go",+ "rationale": "the Pulse Intelligence operator-surface affordance contract, shared surface-affordance, surface-tool identity, Assistant surface tool filtering, normalized external surface tool resolver, surface lookup, affordance labels, and manifest-published external-adapter surface tool allowlist projection are both the canonical API manifest surface model and the AI runtime prompt and onboarding guardrail for Assistant and MCP-facing surfaces",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/text_tool_invocation.go",+ "rationale": "the Pulse Intelligence text tool invocation parser, internal approval argument, and current_resource handle vocabulary are both the Assistant approved-action execution projection and the shared tool-call params bridge for governed Pulse Intelligence tool calls, with MCP tools/call compatibility staying at the adapter edge",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/tool_call.go",+ "rationale": "the Pulse Intelligence shared tool-call params, normalization, validation, direct registry preparation, registry-entrypoint failure result helpers, and provider/registry tool-call safety classification are both the native Assistant execution/FSM contract and the canonical API/agent tools/call compatibility contract for governed Pulse Intelligence tool calls",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/tool_execution.go",+ "rationale": "the Pulse Intelligence neutral capability tool HTTP execution helper and direct tool execution output/error mapper are both the Assistant-native direct execution contract and the canonical API/agent request/response execution contract, with MCP adapters consuming the neutral helpers only after the shared MCP manifest-surface execution bridge has applied the published surface tool contract",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/tool_marker.go",+ "rationale": "the Pulse Intelligence Assistant tool marker vocabulary and approval/policy marker parser are both the Assistant structured tool-result compatibility contract and the canonical API/agent branching contract for governed tool outcomes",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/tool_names.go",+ "rationale": "the Pulse Intelligence registry tool-name vocabulary is both the native Assistant execution/display contract and the canonical API/agent tool identity contract for MCP-facing external-agent adapters",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/tool_response.go",+ "rationale": "the shared tool response envelope, tool error-code vocabulary, and tool-result error-code and verification evidence parsers are both the Assistant structured tool-result contract and the canonical API/agent branching contract for Pulse Intelligence tool failures, recovery tracking, and write self-verification",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/tool_result.go",+ "rationale": "the Pulse Intelligence shared tool-result content/result envelope, structuredContent projection, result constructors, HTTP response-to-result mapping, text projection, and result interpretation helpers are both the Assistant registry result contract and the canonical API/agent result projection contract for governed tool outcomes",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/types.go",+ "rationale": "the agent capabilities manifest wire type, manifest-owned external-adapter surface tool contract field, capability display title and structured output schema fields, approval-policy vocabulary, capability governance normalization, and tool-governance descriptor shape are both the canonical API payload contract and the AI runtime projection contract for Pulse Assistant and MCP-facing agent tools",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "internal/agentcapabilities/workflow_prompt.go",+ "rationale": "the Pulse Intelligence workflow prompt catalogue, manifest-owned `workflowPrompts` projection, MCP prompt title projection, presentation kind hints, shared resource-context and finding argument vocabulary, Patrol issue-handling capability gating, argument validation, and manifest-gated shared prompt rendering rules are both the AI runtime starter contract for Assistant-compatible surfaces and the canonical API/agent prompt projection contract for MCP-facing clients",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },{"path": "internal/api/access_control_handlers.go","rationale": "RBAC role and user-assignment handlers are both an organization settings control surface and a canonical API payload contract boundary",@@ -699,6 +948,46 @@"storage-recovery"]},+ {+ "path": "pkg/aicontracts/fix_execution.go",+ "rationale": "the public approved-fix execution contract is both an AI runtime approved-action boundary and a canonical API dependency contract for Patrol and enterprise auto-fix binders",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "pkg/aicontracts/investigation.go",+ "rationale": "the public Patrol investigation record and finding contract is both an AI runtime handoff boundary and a canonical API payload contract for Patrol, Assistant, unified findings, persistence, and audit surfaces",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "pkg/aicontracts/orchestrator_deps.go",+ "rationale": "the public investigation orchestrator dependency contract is both an AI runtime handoff boundary and a canonical API payload contract for Assistant and Patrol tool-call history",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "pkg/extensions/ai_autofix.go",+ "rationale": "the enterprise auto-fix extension dependency seam is both an AI runtime approved-action boundary and a canonical API extension contract over Assistant and Patrol execution dependencies",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },+ {+ "path": "scripts/generate-pulse-intelligence-docs.go",+ "rationale": "the Pulse Intelligence manifest docs generator is both an AI runtime docs/onboarding projection and a canonical API contract projection over the agent capabilities manifest and Pulse MCP surface tool contract",+ "subsystems": [+ "ai-runtime",+ "api-contracts"+ ]+ },{"path": "scripts/install.ps1","rationale": "the Windows installer is both a deployment installability entry point and a canonical agent lifecycle runtime continuity boundary",@@ -1124,14 +1413,22 @@"lane": "L6","contract": "docs/release-control/v6/internal/subsystems/ai-runtime.md","owned_prefixes": [+ "cmd/pulse-mcp/","frontend-modern/src/components/AI/Chat/",+ "internal/agentcapabilities/","internal/ai/"],"owned_files": [+ "cmd/pulse-mcp/main.go",+ "cmd/pulse-mcp/README.md","docs/AI.md",+ "frontend-modern/src/api/agentCapabilities.ts","frontend-modern/src/api/ai.ts",+ "frontend-modern/src/api/aiChat.ts",+ "frontend-modern/src/api/generated/agentCapabilities.ts","frontend-modern/src/api/patrol.ts","frontend-modern/src/components/AI/AICostDashboard.tsx",+ "frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx","frontend-modern/src/stores/aiChat.ts","frontend-modern/src/stores/aiRuntimeState.ts","frontend-modern/src/utils/aiChatPresentation.ts",@@ -1142,7 +1439,12 @@"internal/api/ai_handler.go","internal/api/ai_handlers.go","internal/api/ai_intelligence_handlers.go",- "internal/config/ai.go"+ "internal/config/ai.go",+ "pkg/aicontracts/fix_execution.go",+ "pkg/aicontracts/investigation.go",+ "pkg/aicontracts/orchestrator_deps.go",+ "pkg/extensions/ai_autofix.go",+ "scripts/generate-pulse-intelligence-docs.go"],"verification": {"allow_same_subsystem_tests": false,@@ -1150,12 +1452,46 @@"exact_files": [],"require_explicit_path_policy_coverage": true,"path_policies": [+ {+ "id": "pulse-mcp-adapter",+ "label": "Pulse MCP adapter proof",+ "match_prefixes": [+ "cmd/pulse-mcp/"+ ],+ "match_files": [+ "cmd/pulse-mcp/main.go",+ "cmd/pulse-mcp/README.md"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "cmd/pulse-mcp/main_test.go",+ "internal/agentcapabilities/markdown_test.go",+ "internal/api/contract_test.go"+ ]+ },+ {+ "id": "pulse-intelligence-docs-generator",+ "label": "Pulse Intelligence manifest docs generator proof",+ "match_prefixes": [],+ "match_files": [+ "scripts/generate-pulse-intelligence-docs.go"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "internal/agentcapabilities/markdown_test.go",+ "internal/api/contract_test.go",+ "scripts/release_control/ai_runtime_docs_policy_test.py"+ ]+ },{"id": "ai-api-surface","label": "AI transport and handler proof","match_prefixes": [],"match_files": ["frontend-modern/src/api/ai.ts",+ "frontend-modern/src/api/aiChat.ts","frontend-modern/src/api/patrol.ts","internal/api/ai_handler.go","internal/api/ai_handlers.go",@@ -1184,7 +1520,8 @@"exact_files": ["frontend-modern/src/components/AI/__tests__/AICostDashboard.test.tsx","frontend-modern/src/utils/__tests__/aiCostPresentation.test.ts",- "frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts"+ "frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts",+ "frontend-modern/src/utils/__tests__/patrolRuntimePresentation.test.ts"]},{@@ -1227,6 +1564,87 @@"frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts"]},+ {+ "id": "agent-capabilities-wire-contract",+ "label": "agent capabilities shared wire-contract proof",+ "match_prefixes": [+ "internal/agentcapabilities/"+ ],+ "match_files": [],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "cmd/pulse-mcp/main_test.go",+ "internal/agentcapabilities/action_target_test.go",+ "internal/agentcapabilities/manifest_test.go",+ "internal/agentcapabilities/mcp_test.go",+ "internal/agentcapabilities/schema_test.go",+ "internal/agentcapabilities/types_test.go",+ "internal/api/agent_capabilities_test.go",+ "internal/api/contract_test.go"+ ]+ },+ {+ "id": "agent-integrations-manifest-projection",+ "label": "Agent integrations manifest projection proof",+ "match_prefixes": [],+ "match_files": [+ "frontend-modern/src/api/agentCapabilities.ts",+ "frontend-modern/src/api/generated/agentCapabilities.ts",+ "frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "frontend-modern/src/api/__tests__/agentCapabilities.test.ts",+ "frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts",+ "internal/api/contract_test.go"+ ]+ },+ {+ "id": "ai-investigation-contract",+ "label": "AI investigation record contract proof",+ "match_prefixes": [],+ "match_files": [+ "pkg/aicontracts/investigation.go"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "internal/api/contract_test.go",+ "pkg/aicontracts/contracts_test.go"+ ]+ },+ {+ "id": "ai-orchestrator-dependency-contract",+ "label": "AI orchestrator dependency contract proof",+ "match_prefixes": [],+ "match_files": [+ "pkg/aicontracts/orchestrator_deps.go"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "internal/api/ai_handlers_test.go",+ "internal/api/contract_test.go",+ "pkg/aicontracts/contracts_test.go"+ ]+ },+ {+ "id": "ai-approved-fix-execution-contract",+ "label": "AI approved fix execution contract proof",+ "match_prefixes": [],+ "match_files": [+ "pkg/aicontracts/fix_execution.go",+ "pkg/extensions/ai_autofix.go"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "internal/api/contract_test.go",+ "pkg/extensions/ai_autofix_test.go"+ ]+ },{"id": "ai-runtime-engine","label": "AI runtime engine proof",@@ -1560,10 +1978,16 @@"lane": "L6","contract": "docs/release-control/v6/internal/subsystems/api-contracts.md","owned_prefixes": [+ "cmd/pulse-mcp/","frontend-modern/src/api/",+ "internal/agentcapabilities/","internal/api/"],"owned_files": [+ "cmd/agent-probe/main.go",+ "cmd/pulse-mcp/main.go",+ "cmd/pulse-mcp/README.md",+ "frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx","frontend-modern/src/components/Settings/APITokenManager.tsx","frontend-modern/src/components/Settings/apiTokenManagerModel.ts","frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/AvailabilityTargetSlot.tsx",@@ -1589,10 +2013,15 @@"frontend-modern/src/utils/infrastructureSettingsPresentation.ts","internal/api/setup_script_render.go","internal/websocket/hub.go",+ "pkg/aicontracts/fix_execution.go",+ "pkg/aicontracts/investigation.go",+ "pkg/aicontracts/orchestrator_deps.go",+ "pkg/extensions/ai_autofix.go","pkg/pulsecli/actions.go","pkg/pulsecli/api_client.go","pkg/pulsecli/fleet.go","pkg/pulsecli/root.go",+ "scripts/generate-pulse-intelligence-docs.go","scripts/generate-types.go"],"verification": {@@ -1605,6 +2034,78 @@],"require_explicit_path_policy_coverage": true,"path_policies": [+ {+ "id": "agent-capabilities-manifest-contract",+ "label": "agent capabilities manifest contract proof",+ "match_prefixes": [+ "internal/agentcapabilities/"+ ],+ "match_files": [+ "cmd/agent-probe/main.go",+ "cmd/pulse-mcp/main.go"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "cmd/pulse-mcp/main_test.go",+ "internal/agentcapabilities/action_target_test.go",+ "internal/agentcapabilities/manifest_test.go",+ "internal/agentcapabilities/mcp_test.go",+ "internal/agentcapabilities/schema_test.go",+ "internal/agentcapabilities/types_test.go",+ "internal/api/agent_capabilities_test.go",+ "internal/api/contract_test.go"+ ]+ },+ {+ "id": "agent-integrations-manifest-projection",+ "label": "Agent integrations manifest projection proof",+ "match_prefixes": [],+ "match_files": [+ "frontend-modern/src/api/agentCapabilities.ts",+ "frontend-modern/src/api/generated/agentCapabilities.ts",+ "frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "frontend-modern/src/api/__tests__/agentCapabilities.test.ts",+ "frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts",+ "internal/api/contract_test.go"+ ]+ },+ {+ "id": "pulse-mcp-manifest-adapter",+ "label": "Pulse MCP manifest adapter proof",+ "match_prefixes": [+ "cmd/pulse-mcp/"+ ],+ "match_files": [+ "cmd/pulse-mcp/main.go",+ "cmd/pulse-mcp/README.md"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "cmd/pulse-mcp/main_test.go",+ "internal/agentcapabilities/markdown_test.go",+ "internal/api/contract_test.go"+ ]+ },+ {+ "id": "pulse-intelligence-docs-generator",+ "label": "Pulse Intelligence manifest docs generator proof",+ "match_prefixes": [],+ "match_files": [+ "scripts/generate-pulse-intelligence-docs.go"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "internal/agentcapabilities/markdown_test.go",+ "internal/api/contract_test.go"+ ]+ },{"id": "ai-chat-stream-event-types","label": "AI chat SSE generated type proof",@@ -1620,6 +2121,50 @@"internal/api/contract_test.go"]},+ {+ "id": "ai-investigation-contract",+ "label": "AI investigation record API contract proof",+ "match_prefixes": [],+ "match_files": [+ "pkg/aicontracts/investigation.go"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "internal/api/contract_test.go",+ "pkg/aicontracts/contracts_test.go"+ ]+ },+ {+ "id": "ai-orchestrator-dependency-contract",+ "label": "AI orchestrator dependency API contract proof",+ "match_prefixes": [],+ "match_files": [+ "pkg/aicontracts/orchestrator_deps.go"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "internal/api/ai_handlers_test.go",+ "internal/api/contract_test.go",+ "pkg/aicontracts/contracts_test.go"+ ]+ },+ {+ "id": "ai-approved-fix-execution-contract",+ "label": "AI approved fix execution API contract proof",+ "match_prefixes": [],+ "match_files": [+ "pkg/aicontracts/fix_execution.go",+ "pkg/extensions/ai_autofix.go"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "internal/api/contract_test.go",+ "pkg/extensions/ai_autofix_test.go"+ ]+ },{"id": "auth-state-persistence-compatibility","label": "session and CSRF persistence migration proof",@@ -1971,6 +2516,7 @@"frontend-modern/src/components/Settings/ProLicensePlanSection.tsx","frontend-modern/src/components/Settings/RelayPairingSection.tsx","frontend-modern/src/components/Settings/RelaySettingsPanel.tsx",+ "frontend-modern/src/components/Settings/selfHostedBillingPresentation.ts","frontend-modern/src/components/Settings/SelfHostedCommercialRecoverySection.tsx","frontend-modern/src/components/Settings/useBillingAdminPanelState.ts","frontend-modern/src/components/Settings/useOrganizationBillingPanelState.ts",@@ -2006,6 +2552,7 @@"pulse-pro:.github/workflows/deploy-v6-preview-demo.yml","pulse-pro:landing-page/thanks.html","pulse-pro:license-server/grandfathering.go",+ "pulse-pro:license-server/intelligence_value.go","pulse-pro:license-server/main.go","pulse-pro:license-server/self_hosted_feature_catalog.generated.go","pulse-pro:license-server/v6_checkout.go",@@ -2137,6 +2684,21 @@"pkg/licensing/service_activate_test.go"]},+ {+ "id": "pulse-intelligence-value-report",+ "label": "Pulse Intelligence value reporting proof",+ "match_prefixes": [],+ "match_files": [+ "pulse-pro:license-server/intelligence_value.go"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "pulse-pro:license-server/intelligence_value_test.go",+ "pulse-pro:license-server/main_test.go",+ "pulse-pro:license-server/telemetry_test.go"+ ]+ },{"id": "hosted-entitlement-issuer","label": "hosted entitlement issuer proof",@@ -2790,6 +3352,8 @@"scripts/hot-dev.sh","scripts/install-container-agent.sh","scripts/install-docker.sh",+ "scripts/install-mcp.ps1",+ "scripts/install-mcp.sh","scripts/install.ps1","scripts/install.sh","scripts/lib/hot-dev-auth.sh",@@ -2943,6 +3507,20 @@"scripts/installtests/release_ldflags_test.go"]},+ {+ "id": "pulse-mcp-installer-release-runtime",+ "label": "Pulse MCP installer release proof",+ "match_prefixes": [],+ "match_files": [+ "scripts/install-mcp.ps1",+ "scripts/install-mcp.sh"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "scripts/installtests/build_release_assets_test.go"+ ]+ },{"id": "cloud-public-signup-smoke-runtime","label": "Cloud public signup smoke proof",@@ -3197,6 +3775,9 @@"frontend-modern/src/features/platformPage/PlatformResourceDetailTableRow.tsx","frontend-modern/src/features/platformPage/sharedPlatformPage.tsx","frontend-modern/src/hooks/createNonSuspendingQuery.ts",+ "frontend-modern/src/i18n/messages.de.ts",+ "frontend-modern/src/i18n/messages.es.ts",+ "frontend-modern/src/i18n/messages.ts","frontend-modern/src/index.css","frontend-modern/src/routing/routePreload.ts","frontend-modern/src/stores/aiChat.ts",@@ -3365,6 +3946,22 @@"frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts"]},+ {+ "id": "localized-settings-message-catalog",+ "label": "localized settings message catalog proof",+ "match_prefixes": [],+ "match_files": [+ "frontend-modern/src/i18n/messages.de.ts",+ "frontend-modern/src/i18n/messages.es.ts",+ "frontend-modern/src/i18n/messages.ts"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "frontend-modern/src/components/Settings/__tests__/settingsLocalization.test.ts",+ "frontend-modern/src/i18n/__tests__/i18n.test.ts"+ ]+ },{"id": "environment-lock-primitives","label": "environment lock primitive proof",@@ -4284,14 +4881,14 @@"frontend-modern/src/components/patrol/index.ts","frontend-modern/src/components/patrol/InvestigationMessages.tsx","frontend-modern/src/components/patrol/InvestigationSection.tsx",- "frontend-modern/src/components/patrol/PatrolStatusBar.tsx","frontend-modern/src/components/patrol/RemediationStatus.tsx","frontend-modern/src/components/patrol/RunHistoryEntry.tsx","frontend-modern/src/components/patrol/RunHistoryPanel.tsx","frontend-modern/src/components/patrol/RunToolCallTrace.tsx",+ "frontend-modern/src/features/patrol/patrolAutonomyAvailability.ts",+ "frontend-modern/src/features/patrol/patrolControlPresentation.ts","frontend-modern/src/features/patrol/PatrolIntelligenceBanners.tsx","frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx",- "frontend-modern/src/features/patrol/PatrolIntelligenceSummary.tsx","frontend-modern/src/features/patrol/PatrolIntelligenceSurface.tsx","frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx","frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts",@@ -4307,6 +4904,7 @@"frontend-modern/src/utils/findingAlertIdentity.ts","frontend-modern/src/utils/patrolEmptyStatePresentation.ts","frontend-modern/src/utils/patrolFormat.ts",+ "frontend-modern/src/utils/patrolPagePresentation.ts","frontend-modern/src/utils/patrolRunPresentation.ts","frontend-modern/src/utils/patrolRuntimeActions.ts","frontend-modern/src/utils/patrolRuntimePresentation.ts",@@ -4331,9 +4929,10 @@"match_files": ["frontend-modern/src/components/Brand/PulsePatrolLogo.tsx","frontend-modern/src/components/patrol/index.ts",+ "frontend-modern/src/features/patrol/patrolAutonomyAvailability.ts",+ "frontend-modern/src/features/patrol/patrolControlPresentation.ts","frontend-modern/src/features/patrol/PatrolIntelligenceBanners.tsx","frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx",- "frontend-modern/src/features/patrol/PatrolIntelligenceSummary.tsx","frontend-modern/src/features/patrol/PatrolIntelligenceSurface.tsx","frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx","frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts",@@ -4341,17 +4940,20 @@"frontend-modern/src/pages/AIIntelligence.tsx","frontend-modern/src/stores/aiIntelligence.ts","frontend-modern/src/stores/aiIntelligenceSummaryModel.ts",- "frontend-modern/src/types/aiIntelligence.ts"+ "frontend-modern/src/types/aiIntelligence.ts",+ "frontend-modern/src/utils/patrolPagePresentation.ts"],"allow_same_subsystem_tests": false,"test_prefixes": [],"exact_files": ["frontend-modern/src/components/Brand/__tests__/PulsePatrolLogo.test.tsx",+ "frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceHeader.test.ts","frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts","frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx","frontend-modern/src/stores/__tests__/aiIntelligence.test.ts","frontend-modern/src/stores/__tests__/aiIntelligenceSummaryModel.test.ts","frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts",+ "frontend-modern/src/utils/__tests__/patrolPagePresentation.test.ts","tests/integration/tests/18-patrol-runtime-state.spec.ts","tests/integration/tests/73-patrol-assistant-operator-briefing.spec.ts"]@@ -4425,7 +5027,6 @@"match_prefixes": [],"match_files": ["frontend-modern/src/components/patrol/CountdownTimer.tsx",- "frontend-modern/src/components/patrol/PatrolStatusBar.tsx","frontend-modern/src/components/patrol/RunHistoryEntry.tsx","frontend-modern/src/components/patrol/RunHistoryPanel.tsx","frontend-modern/src/components/patrol/RunToolCallTrace.tsx",@@ -4437,8 +5038,8 @@"allow_same_subsystem_tests": false,"test_prefixes": [],"exact_files": [- "frontend-modern/src/components/patrol/__tests__/PatrolStatusBar.test.tsx","frontend-modern/src/components/patrol/__tests__/RunHistoryEntry.test.tsx",+ "frontend-modern/src/components/patrol/__tests__/RunHistoryPanel.test.tsx","frontend-modern/src/components/patrol/__tests__/RunToolCallTrace.test.tsx","frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx","frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts",@@ -4827,6 +5428,7 @@],"owned_files": ["docs/PRIVACY.md",+ "frontend-modern/public/docs/PRIVACY.md","frontend-modern/src/api/security.ts","frontend-modern/src/components/Settings/APIAccessPanel.tsx","frontend-modern/src/components/Settings/APITokenManager.tsx",@@ -4860,6 +5462,7 @@"pkg/audit/async_logger.go","pkg/audit/audit.go","pkg/audit/sqlite_logger.go",+ "pkg/server/telemetry_pulse_intelligence.go","pkg/tlsutil/fingerprint.go","scripts/telemetry_adoption_report.py","SECURITY.md"@@ -4883,6 +5486,7 @@"internal/config/config_load_test.go","internal/config/watcher_test.go","internal/telemetry/telemetry_test.go",+ "pkg/server/telemetry_pulse_intelligence_test.go","pkg/tlsutil/tlsutil_test.go","scripts/tests/test_telemetry_adoption_report.py"],@@ -4894,8 +5498,10 @@"match_prefixes": [],"match_files": ["docs/PRIVACY.md",+ "frontend-modern/public/docs/PRIVACY.md","frontend-modern/src/components/Settings/useSystemSettingsState.ts","internal/telemetry/telemetry.go",+ "pkg/server/telemetry_pulse_intelligence.go","scripts/telemetry_adoption_report.py","SECURITY.md"],@@ -4905,6 +5511,7 @@"frontend-modern/src/stores/__tests__/systemSettings.test.ts","internal/api/system_settings_telemetry_test.go","internal/telemetry/telemetry_test.go",+ "pkg/server/telemetry_pulse_intelligence_test.go","scripts/tests/test_telemetry_adoption_report.py"]},@@ -5228,6 +5835,7 @@"internal/unifiedresources/"],"owned_files": [+ "frontend-modern/src/components/Discovery/discoveryReadiness.ts","frontend-modern/src/components/Discovery/DiscoveryTab.tsx","frontend-modern/src/components/Discovery/useDiscoveryTabState.ts","frontend-modern/src/components/Docker/SwarmServicesDrawer.tsx",@@ -5398,6 +6006,7 @@"label": "unified resource consumer proof","match_prefixes": [],"match_files": [+ "frontend-modern/src/components/Discovery/discoveryReadiness.ts","frontend-modern/src/components/Discovery/DiscoveryTab.tsx","frontend-modern/src/components/Discovery/useDiscoveryTabState.ts","frontend-modern/src/components/Docker/SwarmServicesDrawer.tsx",diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex 8ba69a30b3..52e3fc7b34 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -54,19 +54,20 @@ controls as normal product settings.26. `internal/config/config.go`27. `internal/config/watcher.go`28. `internal/telemetry/telemetry.go`-29. `internal/api/router_routes_auth_security.go`-30. `internal/crypto/crypto.go`-31. `internal/securityutil/secure_storage_dir.go`-32. `internal/cloudcp/auth/magiclink.go`-33. `internal/cloudcp/auth/magiclink_store.go`-34. `pkg/tlsutil/fingerprint.go`-35. `pkg/audit/audit.go`-36. `pkg/audit/async_logger.go`-37. `pkg/audit/sqlite_logger.go`-38. `scripts/telemetry_adoption_report.py`-39. `frontend-modern/src/components/Settings/DataHandlingPanel.tsx`-40. `frontend-modern/src/components/Settings/dataHandlingPanelModel.ts`-41. `internal/api/agent_exec_token_binding.go`+29. `pkg/server/telemetry_pulse_intelligence.go`+30. `internal/api/router_routes_auth_security.go`+31. `internal/crypto/crypto.go`+32. `internal/securityutil/secure_storage_dir.go`+33. `internal/cloudcp/auth/magiclink.go`+34. `internal/cloudcp/auth/magiclink_store.go`+35. `pkg/tlsutil/fingerprint.go`+36. `pkg/audit/audit.go`+37. `pkg/audit/async_logger.go`+38. `pkg/audit/sqlite_logger.go`+39. `scripts/telemetry_adoption_report.py`+40. `frontend-modern/src/components/Settings/DataHandlingPanel.tsx`+41. `frontend-modern/src/components/Settings/dataHandlingPanelModel.ts`+42. `internal/api/agent_exec_token_binding.go`## Shared Boundaries@@ -87,6 +88,12 @@ controls as normal product settings.API token scope selectors follow the same split: security/privacy ownsthe wildcard, preset, and custom scope semantics, while frontend-primitivesowns the pressed selector pill chrome through `SelectablePillButton`.+ Full access is a deliberate wildcard choice, not the default empty+ selection. The token creation form must require an explicit scoped preset,+ custom scope, or Full access selection before a credential can be minted.+ Stable in-page anchors for sibling API Access onboarding panels are allowed+ only as navigation into the token creation section; those sibling panels do+ not own token scope derivation or preset contents.4. `frontend-modern/src/components/Settings/apiTokenManagerModel.ts` shared with `api-contracts`: the pure API token settings model is both a security/privacy control surface and a canonical API payload contract boundary.5. `frontend-modern/src/components/Settings/DataHandlingPanel.tsx` shared with `frontend-primitives`: the data-handling settings surface is both a security/privacy trust surface and a canonical settings-shell presentation boundary.6. `frontend-modern/src/components/Settings/dataHandlingPanelModel.ts` shared with `frontend-primitives`: the data-handling settings model is both a security/privacy posture projection and a canonical settings-shell presentation boundary.@@ -107,6 +114,10 @@ controls as normal product settings.Scope labels and descriptions are visible security controls. Docker /Podman scopes must use the shared source-platform label rather thangeneric `container` copy.+ The `ai:execute` scope must stay labeled and described as Pulse+ Intelligence actions for governed Patrol actions: plans, approvals,+ policy-allowed fixes, verification, and history. Security-facing token+ setup must not present it as generic operations workflow access.12. `frontend-modern/src/utils/apiTokenPresentation.ts` shared with `api-contracts`: the API token presentation helper is both a security/privacy control surface and a canonical API token management boundary.It owns Docker / Podman token copy for API Access, token presets, usagesummaries, and revoke warnings so security-facing copy does not drift into@@ -139,7 +150,74 @@ controls as normal product settings.17. `internal/cloudcp/auth/magiclink_store.go` shared with `cloud-paid`: control-plane magic-link persistence is both a Pulse Cloud account-access boundary and a security/privacy storage-hardening boundary.## Extension Points-1. Change privacy disclosures, usage-data vocabulary, or outbound-data guarantees through `docs/PRIVACY.md` and `internal/telemetry/telemetry.go` together.+1. Change privacy disclosures, usage-data vocabulary, or outbound-data guarantees through `docs/PRIVACY.md`, `frontend-modern/public/docs/PRIVACY.md`, `internal/telemetry/telemetry.go`, and `pkg/server/telemetry_pulse_intelligence.go` together.+ Pulse Intelligence external-agent/MCP telemetry may expose only content-free+ adapter-origin usage and capability-class counters for context, event+ stream, provisioning, operator state, finding, and action requests. It must+ not expose token identity, route parameters, resource IDs, finding text,+ command text, action output, prompts, responses, or request bodies.+ External-agent activity markers may be recorded for narrow tokens that+ satisfy the called manifest capability's own scope, such as+ `monitoring:read` for context reads, but that does not widen token+ permissions or export token identity. The emitted telemetry remains only the+ coarse activity class.+ External-agent/MCP readiness for the operations loop may likewise be true+ only when a single non-expired API token satisfies every scope required by+ the published Pulse MCP operations-loop capability set; readiness must not+ require the full manifest scope set and must not export token identity,+ token name, token counts, or matched scopes.+ The broad external-agent configured signal may remain true for a narrower+ read-only MCP token, but Patrol autonomy completed/resolved loop telemetry no+ longer uses MCP readiness as a value gate; readiness remains optional+ external-agent setup telemetry and settings handoff context.+ Pulse Intelligence guided operations-loop starter telemetry may expose only+ content-free 30-day request counts for the total starter flow and the+ coarse Assistant, Pulse Patrol, Patrol control, legacy Patrol autonomy+ compatibility, legacy Pro activation+ entry-point, and Pulse MCP source surfaces. It must not expose prompt text,+ prompt arguments, resource+ IDs, finding IDs, session IDs, token identity, checkout/account identity,+ request bodies, model output, remediation command text, or+ infrastructure-specific details.+ Pulse Intelligence Patrol control completed-loop telemetry may expose only a+ content-free boolean derived from the Patrol control starter or legacy Patrol+ autonomy/Pro activation entry-point aliases, Patrol issue evidence,+ contextual Assistant or external-agent collaboration, and either a rejected+ governed decision or an approved governed decision with verified outcome+ proof. Pulse Intelligence Patrol control resolved-loop telemetry remains+ stricter: it may expose only a content-free boolean derived from the same+ evidence plus an approved governed decision and verified outcome proof. Paid+ Patrol control completed/resolved loop cohorts may expose only whether the+ current coarse paid-license posture coexists with those same primary Patrol+ control completed/resolved booleans. Legacy Pro activation completed,+ resolved, and paid cohort fields may remain as mirrors for longitudinal+ commercial analysis, but they must not add exact tier, checkout, account,+ license, token, or customer identity. None of these fields may expose prompt text,+ prompt arguments, checkout/account identity, token details, resource IDs,+ finding IDs, session IDs, request bodies, remediation command text, action+ output, or infrastructure-specific details.+ The shared count-only classifier in+ `internal/telemetry.ClassifyPulseIntelligencePatrolControlProof` is the+ privacy boundary for those Patrol control booleans and the native+ `patrolControlValueState` string. The legacy+ `ClassifyPulseIntelligencePatrolAutonomyProof` and+ `ClassifyPulseIntelligenceProActivationProof` wrappers plus+ `patrolAutonomyValueState` and `proActivationValueProofState` aliases may+ remain for metric/storage continuity, but callers may pass aggregate+ evidence counts only, never external-agent readiness, prompt text, request+ bodies, resource/finding identifiers, token metadata, actors, commands, or+ outputs.+ The agent operations-loop status endpoint may mirror that same starter+ evidence and contextual Assistant/external-agent collaboration evidence only+ as aggregate count fields in its content-safe payload; it must not expose the+ underlying workflow-prompt event records, AI prompt or response content,+ Assistant session IDs, external-agent route parameters, surfaces beyond the+ approved coarse categories, token metadata, prompt names, or request context.+ The same endpoint may expose aggregate active Patrol finding counts and let+ active findings or pending approvals outrank historical completed/resolved+ proof in `nextAction`, but that precedence must remain count-only and must+ not expose finding IDs, resource IDs, commands, prompt text, actors, token+ metadata, or remediation output.2. Change security policy, hardening guidance, or supported auth boundaries through `SECURITY.md`.3. Change telemetry/privacy settings state handling through `frontend-modern/src/components/Settings/useSystemSettingsState.ts`.4. Change security/auth/token transport behavior through the shared `frontend-modern/src/api/security.ts`, `frontend-modern/src/components/Settings/APITokenManager.tsx`, `frontend-modern/src/components/Settings/apiTokenManagerModel.ts`, `frontend-modern/src/components/Settings/useAPITokenManagerState.ts`, `internal/api/security.go`, `internal/api/security_tokens.go`, and `internal/api/system_settings.go` boundary.@@ -163,7 +241,15 @@ controls as normal product settings.email can support display, delivery, or migration, but request access mustmatch the authenticated principal against stored `OwnerUserID` or member`UserID`.-5. Change security/privacy settings presentation through the shared `frontend-modern/src/components/Settings/APIAccessPanel.tsx`, `frontend-modern/src/components/Settings/GeneralSettingsPanel.tsx`, `frontend-modern/src/components/Settings/SecurityAuthPanel.tsx`, `frontend-modern/src/components/Settings/SecurityOverviewPanel.tsx`, `frontend-modern/src/components/Settings/QuickSecuritySetup.tsx`, `frontend-modern/src/components/Settings/SecurityPostureSummary.tsx`, `frontend-modern/src/components/Settings/SSOProviderTypeIcon.tsx`, `frontend-modern/src/constants/apiScopes.ts`, `frontend-modern/src/utils/apiTokenPresentation.ts`, `frontend-modern/src/utils/securityAuthPresentation.ts`, `frontend-modern/src/utils/securityScorePresentation.ts`, `frontend-modern/src/utils/auditLogPresentation.ts`, `frontend-modern/src/utils/auditWebhookPresentation.ts`, and the localized catalog/policy boundary in `frontend-modern/src/i18n/`.+5. Change security/privacy settings presentation through the shared `frontend-modern/src/components/Settings/APIAccessPanel.tsx`, `frontend-modern/src/components/Settings/GeneralSettingsPanel.tsx`, `frontend-modern/src/components/Settings/SecurityAuthPanel.tsx`, `frontend-modern/src/components/Settings/SecurityOverviewPanel.tsx`, `frontend-modern/src/components/Settings/QuickSecuritySetup.tsx`, `frontend-modern/src/components/Settings/SecurityPostureSummary.tsx`, `frontend-modern/src/components/Settings/SSOProviderTypeIcon.tsx`, `frontend-modern/src/constants/apiScopes.ts`, `frontend-modern/src/utils/apiTokenPresentation.ts`, `frontend-modern/src/utils/securityAuthPresentation.ts`, `frontend-modern/src/utils/securityScorePresentation.ts`, `frontend-modern/src/utils/auditLogPresentation.ts`, `frontend-modern/src/utils/auditWebhookPresentation.ts`, and the localized catalog/policy boundary in `frontend-modern/src/i18n/`. Locale-catalog edits owned by another product surface may share this boundary only if they preserve API token names, token preset ids, privacy disclosures, and non-translatable security terms exactly; changing those security/privacy strings requires the security/privacy owner and tests.+ Pulse Intelligence Provider & Models, Patrol, Assistant, and Service Context+ settings labels may use the same localized catalog boundary, but those edits+ must stay product-settings copy only and must not change token scope names,+ preset ids, privacy disclosures, or security control terminology. Self-hosted+ Plans & Billing header and navigation localization may share that same catalog+ boundary when it frames Pro setup as choosing Patrol autonomy; it must not+ alter API Access, authentication, privacy, or token-management terminology in+ the same edit.6. Change operator-facing telemetry/adoption reporting through `scripts/telemetry_adoption_report.py` together with the privacy disclosure whenever release-identity interpretation changes.7. Change data-at-rest encryption-key or control-plane magic-link HMAC key and storage-root hardening semantics through `internal/crypto/crypto.go`, `internal/cloudcp/auth/magiclink.go`, `internal/cloudcp/auth/magiclink_store.go`, and `internal/securityutil/secure_storage_dir.go` together so writable-but-not-owned runtime storage mounts stay supported without weakening file-level secrecy.8. Change auth-env password normalization, hosted commercial base URL@@ -199,7 +285,7 @@ controls as normal product settings.prompt text, removed/restored message counts, and `can_redo`; they mustnot expose redo-stack internals, provider reasoning, raw tool output,model-only handoff text, approval payload internals, environment data, or- command-bearing remediation details.+ command-bearing fix details.## Forbidden Paths@@ -243,6 +329,14 @@ controls as normal product settings.HTTP(S) URLs, with plain HTTP limited to loopback development origins.8. Keep the Resource Privacy/Data Handling settings surface neutral and non-commercial: it may show resource policy posture, local-only counts, and redaction coverage, but it must not advertise trials, upgrades, paid plans, or monitoring limits, and it must remain route-backed rather than promoted in the normal Settings sidebar while it is informational only.9. Keep operator-facing Resource Privacy/Data Handling posture aligned with runtime AI/context enforcement: `local-only` resource details must not be sent to external model prompts, and sensitive free-form alert, tool-result, investigation, handoff context, and any retained legacy managed-model compatibility text must use the shared resource-policy redaction helper before leaving the local trust boundary. Assistant handoffs may surface canonical policy handling guidance and current resource-state summaries for product-originated resources, but that guidance and state are model-only context and must not become disclosure authority. Product-originated Assistant handoff text must also be policy-cleaned before prompt injection, including operator briefings and finding/action context, so raw governed resource identity cannot leak through local-model briefing prose while non-local transport still receives the final provider-bound sanitizer. All provider-bound AI requests to non-local models must use the shared resource-policy sanitizer immediately before transport so later agentic turns cannot bypass the advertised handling posture.+ Native Pulse Assistant provider seams and native tool-adapter names in the+ shared AI/API route wiring are part of that same trust boundary. `MCP`+ remains an external protocol, manifest, and wire-schema term; the in-app+ Assistant `ToolAdapter` family must stay governed by the same sanitizer,+ approval, auth, and action-audit checks as the rest of AI/runtime. Security+ and privacy code must not treat MCP-named native seams as a separate trust+ boundary, and must not bypass provider-bound redaction or approval controls+ because a tool call is replayed through Assistant route wiring.10. Keep the canonical and frontend-served privacy disclosures aligned withthe actual AI transport boundary: self-managed installs must describe localproviders as staying on the operator network, non-local providers as direct@@ -291,11 +385,45 @@ vocabulary for anonymous outbound telemetry. Local commercial activation andlicense-recovery runtime records must stay out of ordinary Settings, supportdiagnostics, outbound telemetry disclosure copy, and public configurationreference tables.+Customer-facing telemetry disclosures and telemetry-enabled log copy must+describe the governed AI counters as coarse Patrol, Assistant, and+external-agent usage counters, not as Pulse Intelligence loop-adoption,+activation-loop, operations-loop, or value-proof internals.That same operator-reporting boundary now also owns reusable latest-installadoption baselines. `scripts/telemetry_adoption_report.py` must emitwindowed 24h, 72h, and 7d latest-install snapshots that split publishedversions from unpublished or development builds, so RC adoption reads stopdepending on ad hoc SQL or one-off local helper scripts.+Pulse Intelligence derived governed-operation booleans must treat content-free MCP /+external-agent capability-class counters as external-agent collaboration+activity, not only the legacy `pulse_intelligence_external_agent_used_30d`+boolean. The `pulse_intelligence_mcp_adapter_used_30d` bit is an adapter-origin+marker for the `pulse-mcp` surface, while the aggregate external-agent+recent-use bit still represents direct HTTP and MCP adapter use together. The+runtime telemetry snapshot, checked-in adoption report, and commercial value+report must agree on that interpretation so class-only MCP usage and+adapter-specific MCP usage still contribute to governed-operation activity,+completed/resolved compatibility metrics, retention, and signal-to-paid proof+without adding prompts,+request bodies, command output, resource IDs, finding IDs, token identity, or+route parameters. Source-specific Pulse Intelligence loop booleans for native+Assistant, external-agent, and `pulse-mcp` adapter operations-loop,+approved-execution, approved-action-success, and resolved-loop stages are+allowed only as content-free 30-day adoption evidence over those same+privacy-safe counters; they must not introduce separate prompt, request,+approval, resource, finding, action-output, or token-identifying payloads.+The checked-in Pulse Intelligence adoption report must expose machine-readable+rate fields beside the privacy-safe counts for cohort and operations-funnel+outcomes: retention, latest-paid posture, observed free-to-paid conversion, and+signal-to-paid conversion. Text output may format those rates for humans, but+JSON consumers must not need to parse prose or recompute denominators to tell+whether Patrol, Assistant, MCP, and governed action usage drives activation,+retention, and paid conversion.+That same report must treat Patrol control as the primary paid value cohort and+operations-funnel stage. Legacy Pro activation telemetry may contribute to+Patrol-control cohorts as a compatibility source and may remain visible as a+legacy entry-point count, but report keys and funnel stages must not present+Pro activation as the first-class product loop.That same storage hardening boundary now also owns secure regular-filehandling for secret-bearing local trust material and the control-planemagic-link storage root. `internal/crypto/crypto.go`,@@ -422,11 +550,16 @@ deployment's own origin so an operator wiring Claude Desktop orClaude Code sees the right base URL automatically. The sectiondoes NOT introduce a new token-mint flow or auth path: tokensstill flow through the API Token Manager, and the snippet-documents the `monitoring:read` / `monitoring:write` scopes the-agent surface requires. Keeping token minting and agent-surface-disclosure on the same tab means an operator gets a single-"machine-driven access" mental model rather than two surfaces-to reconcile.+documents the manifest-derived scopes the agent surface requires.+Pulse Intelligence owns the agent-surface disclosure so the operator sees MCP as+an access path over governed Patrol actions, while API Access owns the scoped+credential minted for that access path. Normal API Access visits keep the token+manager first; `/settings/security/api?tokenPreset=pulse-intelligence-agent#api-token-create`+may open token creation for the external-agent preset, but+`/settings/security/api#external-agent-setup` and legacy+`/settings/security/api#pulse-mcp-setup` links must redirect to the canonical+Pulse Intelligence Assistant setup route instead of placing Agent Integrations+inside the API Access trust surface.That same token-management boundary also reserves token-owner identity for theserver-authenticated principal. Token-minting helpers must derive@@ -470,7 +603,127 @@ workloads, storage resources, physical disks, Ceph clusters, network shares,TrueNAS and VMware resource categories, availability targets, and activealerts. Those counts may describe scale and feature adoption, but they must notinclude hostnames, resource IDs, infrastructure identifiers, credentials,-prompts, chat messages, or personal information.+prompts, chat messages, command text, action output, token values, or personal+information.+That same anonymous telemetry floor now also permits only content-free Pulse+Patrol control and governed Pulse Intelligence operations adoption flags and+counters inside the same rotating 30-day telemetry window:+configured/active/completed/resolved governed-operation and approved-execution+adoption booleans, primary Patrol-control completed/resolved and paid-cohort+adoption booleans, legacy Pro activation mirrors where needed for cohort continuity,+source-specific native+Assistant, external-agent, and `pulse-mcp` adapter operations-loop,+approved-execution, approved-action-success, and resolved-loop adoption+booleans, governed-operation workflow starter request counts for the canonical+`pulse_operations_loop` prompt split by total, native Assistant, first-party+Patrol, primary Patrol-control, legacy Pro entry-point, and Pulse MCP surfaces, Assistant AI call+counts, Assistant governed-context AI call counts, Assistant governed-tool call counts, Patrol AI call counts, Patrol run/+new-finding/investigation/resolved-finding/autofix counts, external-agent/MCP+readiness and recent-use booleans including the adapter-origin `pulse-mcp`+recent-use boolean, action-plan counts, approval-request counts,+rejected-action-decision counts, approved-action-decision counts,+approved-action-attempt counts, and approved-action-success counts. Those fields may measure whether Patrol,+Assistant, external agents, approvals, and governed actions form an adopted+governed operation, whether an operator entered the guided Patrol-control+starter, which source carried the stage, whether the Patrol control journey+reached a terminal approve/reject decision or the stricter+approved-and-verified resolved outcome, whether that path reached approved+action-execution depth, and+whether approved governed actions completed successfully, were rejected before+execution, or coincided with content-free Patrol resolution,+but they must not include tool names, tool inputs, tool outputs, prompts,+responses, chat messages, command text, action output, approval actors,+approval reasons, token values, token counts, resource IDs, finding IDs, or+other local identifiers.+Governed-operation workflow starter telemetry is entry-point evidence only: a+successful starter render may make the coarse active-loop boolean true, but it+must not by itself count as contextual collaboration, approved execution,+verification, resolved finding evidence, or a completed governed operation.+Completed governed-operation telemetry is approve/reject evidence, not a pending+request shortcut: `pulse_intelligence_complete_operations_loop_30d` and the+source-specific operations-loop booleans may be true only when the same+content-free telemetry window contains Patrol issue evidence, contextual+Assistant/MCP/external-agent collaboration, and either a rejected action+decision, an approved action decision, or approved execution evidence. Generic+Patrol runs, Patrol AI calls, action plans, and approval requests may contribute+to activity or governed-action reach, but they must not complete the loop+without issue-backed Patrol evidence and a real decision/outcome signal.+The public privacy disclosure table is the operator-facing inventory for that+same payload. `docs/PRIVACY.md` and+`frontend-modern/public/docs/PRIVACY.md` must name every+`pulse_intelligence_*` field exported by `internal/telemetry.Ping` using Patrol+control and governed-operation vocabulary, including source-specific Assistant,+direct external-agent, and `pulse-mcp` governed-operation booleans, workflow+starter counts including primary Patrol control and legacy Pro entry-point counts,+Patrol-control completed/resolved booleans, paid Patrol-control cohort booleans,+legacy Pro activation mirrors, rejected decisions, and+approved-action outcome counts, so runtime telemetry can never grow a Patrol+control or legacy activation signal that is invisible to operators inspecting+outbound usage data.+External-agent/MCP recent-use is derived from content-free authenticated+agent-surface capability activity by a manifest-capable API token, not from+broad API token last-use metadata. The activity class may identify only the+coarse manifest category being used, never resource IDs, finding IDs, node IDs,+request bodies, outputs, token identity, or prompt/chat content.+The `pulse-mcp` adapter may additionally mark requests with a content-free+surface-origin header so telemetry can distinguish adapter use from direct+HTTP agent use without recording the client identity, prompt, request payload,+route parameters, or local resource identifiers.+External-agent/MCP readiness is derived from a non-expired API token that+covers every scope required by the published Pulse MCP operations-loop+capability set. This keeps OpenCode, Claude Code, Claude Desktop, `pulse-mcp`,+and direct HTTP agent setups measurable only when they can run the same+governed loop, without treating generic `ai:chat` tokens as external-agent+readiness and without requiring the operator to grant every manifest scope.+The operations-loop status endpoint may expose only the resulting boolean; it+must not expose token identity, token names, token counts, token last-use+metadata, or the specific matching scopes.+The Pulse Pro license-server telemetry ingest may persist those same+content-free Pulse Intelligence fields only alongside the canonical coarse+`paid_license` posture and received timestamp, so+`scripts/telemetry_adoption_report.py` can summarize Patrol-control and governed-operation adoption,+7-day retention windows, latest paid/free posture, source-window+entry-to-retention cohorts, paid Patrol-control completed/resolved+cohorts, and observed free-to-paid conversion counts without linking telemetry+to customer accounts or storing exact commercial tiers. The report may also+derive or persist a completed governed-operation signal from those same anonymous+fields, but completion may only mean observed Patrol+issue evidence plus Assistant governed-context or MCP collaboration activity+plus approved/rejected governed-action decision evidence inside the source window;+approved action success may only mean a content-free successful completion+counter derived from approved action audit state. Neither signal may imply that+Pulse stored prompts, findings, resource identifiers, command payloads,+verification detail, or action outputs to prove that linkage.+The stricter approved-execution loop signal may only mean that the same Patrol+issue evidence and Assistant governed-context or MCP collaboration+signals also coincided with at least one approved governed-action attempt in+the source window. It may not encode action targets, command text, execution+output, verification detail, approver identity, or approval rationale.+The resolved governed-operation signal is stricter again: it may only mean that+Patrol resolved or fix-verified at least one finding in the source window, the+same window had Assistant governed-context/tool or MCP/external-agent+collaboration, and at least one approved governed action completed+successfully. It may not encode finding IDs, resource IDs, fix details,+verification detail, command text, action output, approver identity, or a+causal claim that the approved action directly resolved the finding.+The Patrol control completed-loop status count follows that same anonymous+evidence contract: it may only mean the same content-free window also had+Patrol issue evidence, contextual collaboration, and either a rejected governed+decision or an approved governed decision with verified outcome proof. Legacy+Patrol autonomy and Pro activation completed-loop fields may mirror that value+for compatibility, but must not add checkout/account identity, prompt content,+action identity, resource identity, finding identity, token identity, or a+causality claim.+The Patrol control resolved-loop status count follows that same anonymous+evidence contract: it may only mean the same content-free window also had+Patrol issue evidence, contextual collaboration, an approved governed decision,+and verified outcome proof. It must not require MCP readiness, treat rejected+decisions as resolved proof, or add checkout/account identity, prompt content,+action identity, resource identity, finding identity, or token identity. Both+the status projection and outbound telemetry must derive these Patrol control+completed/resolved values through the shared `internal/telemetry` proof+classifier so privacy-sensitive reporting cannot drift into a richer runtime+event join in one caller.That same anonymous telemetry contract also treats `install_id` as a rotatingpseudonymous identifier, not a lifetime install handle. The runtime may keep alocal rotating UUID so startup and heartbeat pings can still represent an@@ -804,6 +1057,13 @@ canonical scope constants. `apiTokenManagerModel.ts` may expose a`getAPITokenScopePresets()` factory, but it must not freeze preset scope dataat module-load time in a way that can break security settings initialization inproduction chunks.+The manifest-derived full-surface preset may keep the internal+`pulse_intelligence_agent` id for route compatibility, but its visible label and+default token name must be `Patrol external agent` so API Access presents the+token as connected-agent access to Patrol work rather than an internal+Pulse Intelligence proof surface. Its description must frame the preset as+scopes for connected agents that use Pulse MCP or HTTP to read context and+request Patrol work, not as generic external-client access.That same revoke/usage surface must also preserve canonical local operatoridentity for the runtimes currently bound to a token. When token usage isattributed to Docker hosts, agents, PBS, PMG, or similar monitored systems,diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex fd6af12197..bc11d224c8 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -76,6 +76,26 @@ token may allow agent reporting for the scoped tenant workspace, but it must notgrant backup visibility, recovery authority, or storage health privileges; thoseremain governed by the setup-script and source-specific backup API boundariesbelow.+Operations-loop status wiring in `internal/api/agent_resource_context.go` is+storage/recovery-adjacent only through the shared action-audit and verification+projection. Starter counts, contextual Assistant/external-agent collaboration+counts, Patrol control completed-loop or resolved-loop outcome evidence,+`patrolControlValueState`, legacy `patrolAutonomy*` compatibility aliases, and+the operator-readable `progressLabel` on that+status are API-contract orientation evidence+for Assistant, Patrol control, the legacy Pro activation entry point, and MCP+entry points; they must not be treated as recovery coverage, backup+verification, storage-health proof, recovery-job state, or a reason to surface+verification stdout, command text, resource IDs, or backup identities. The legacy+`proActivationOperationsLoopStarterCount` field is entry-point-specific, while+the legacy completed/resolved/value `proActivation*` fields mirror the same+Patrol control outcome classifier as compatibility aliases and do not create a+second storage/recovery signal.+First-party workflow starter activity recorded through shared `internal/api/`+handlers, including Pro activation entry-point telemetry for the same+operations-loop prompt, is likewise API/privacy/commercial activation evidence+only; storage and recovery surfaces must not treat it as backup readiness,+restore capability, recovered-state proof, or storage-health verification.Proxmox page stale-agent notices are adjacent frontend and agent-lifecycleplumbing even though `ProxmoxPageSurface` is a storage/recovery canonical file.Those notices may link an operator to scoped agent update commands for@@ -250,6 +270,12 @@ driver runs. Dry-run-only plans remain planningevidence only; storage and recovery surfaces must not present them asexecutable, dispatch them through provider-local restore/remediation paths, orbypass the API fail-closed execution gate.+Storage/recovery consumers of agent-surface action failures must use the+shared `internal/agentcapabilities` error envelope and+`agentcapabilities.AgentErrCode*` vocabulary emitted by `internal/api/`; they+may explain `action_plan_drift`, missing resources, unavailable executors, or+approval-state failures, but must not mint storage-local error codes or branch+on handler-local string copies outside the canonical manifest vocabulary.Docker / Podman start, stop, and restart actions are adjacent runtime actions,not storage or recovery controls: storage/recovery consumers may render theirredacted action history as context, but must not treat container lifecycle@@ -294,6 +320,13 @@ state only. A restored prompt or restored message count may help an operatorcontinue a protected-item investigation, but it must not become backup coverageevidence, recovery freshness, restore entitlement, storage-owner identity,approval policy, or a provider-local recovery command handoff.+Approved Assistant tool execution through `internal/api/router_routes_ai_relay.go`+is also adjacent API/AI action plumbing for storage/recovery consumers.+`AssistantToolExecutor` / `ApprovedAssistantToolExecutor` may execute an already+approved native Assistant tool. MCP remains an external adapter term, not an+approved-fix execution dependency; neither name grants backup visibility,+restore authority, storage-owner identity, or a storage-local command+transport.Legacy OpenCode-style Assistant file-change routes under`/api/ai/sessions/{id}/diff`, `/revert`, and `/unrevert` are notstorage/recovery rollback operations. If those routes are called directly, the@@ -355,6 +388,12 @@ recovery scope, or a storage/recovery-owned secret source.the resulting update state if a future settings flow links to recoverypreparation, but they must not reinterpret agent-token,agent-migration-security, or server-update readiness checks as backup+ readiness. Governed AI action-target normalization in+ `internal/api/ai_handlers.go` and `internal/api/ai_resource_types.go` is+ likewise adjacent AI/API ownership: storage and recovery may consume+ resulting Assistant context if exposed by another surface, but must not+ treat resource-to-action-target coercion as recovery scope, backup+ ownership, restore authorization, or storage-provider identity.freshness, restore capability, or storage-provider health.Shared API-token transport helpers may be consumed by storage/recovery-adjacent flows, but `owner_user_id` remains server-authored token identity@@ -409,6 +448,11 @@ recovery scope, or a storage/recovery-owned secret source.surfaces may read it as adjacent operator context but must not derivebackup, restore, or storage remediation authority from any of itscounters.+ Patrol finding lifecycle payloads exposed by shared AI handlers follow+ that same adjacent boundary: fields such as an operator resolution note are+ AI-runtime/API-contract vocabulary and persistence context, not backup+ metadata, restore evidence, storage remediation authority, or a recovery+ execution contract.Shared Patrol autonomy routes may also touch broad `internal/api/` wiring,but monitor-mode AI configuration and remediation entitlement responses stayAI runtime/API-contract owned and must not become recovery-local policy,@@ -589,6 +633,18 @@ recovery scope, or a storage/recovery-owned secret source.consume the repaired context only as read-only explanation; that repair doesnot create backup visibility, restore authority, storage ownership, or arecovery-local endpoint contract.+ Approved-action tool invocation parsing in `internal/api/router_routes_ai_relay.go`+ is also adjacent API infrastructure rather than storage/recovery grammar:+ storage and recovery surfaces may consume governed Pulse tool execution+ results, but parsing `pulse_*` text invocations, `default_api:` prefixes, and+ quoted arguments must stay in `internal/agentcapabilities`.+ Native Assistant workflow-prompt rendering through+ `POST /api/ai/workflow-prompts/render` is the same kind of adjacent+ AI-runtime/API-contract transport: storage and recovery may provide context+ that makes a manifest-owned Assistant starter usable, but the shared+ `BuildPulseWorkflowPromptFromManifest` render contract, rendered prompt+ text, prompt argument validation, and starter availability must not become+ recovery-local route state, restore authority, or backup workflow grammar.That same adjacent `internal/api/` boundary also keeps public hosted signupcommercial-only: storage and recovery surfaces must not infer tenantexistence, email issuance, or readiness from `/api/public/signup` response@@ -651,13 +707,23 @@ recovery scope, or a storage/recovery-owned secret source.hosted diagnostics do not collapse into false free-tier behavior.19. Preserve shipped local security-doc guidance in shared `internal/api/` config/setup helpers so storage- and recovery-adjacent transport surfaces do not reintroduce GitHub `main` security links when the running build already serves its own local security documentation route.20. Keep shared `internal/api/` Patrol transport and alert-trigger edits feature-isolated: Patrol-specific recency fields, callback fan-out, or alert-bridge wiring changes must not leak into recovery queries, storage links, or recovery-adjacent install/setup flows unless this contract changes in the same slice.- The same adjacency rule applies to AI settings transport in `internal/api/ai_handlers.go`: provider auth state, masked-secret payload fields, provider-test model selection, and safe provider preflight diagnostics remain AI/runtime plus API-contract concerns and must not be absorbed into storage/recovery transport ownership just because those handlers live under the shared backend API tree.+ The same adjacency rule applies to AI settings transport in `internal/api/ai_handlers.go`: provider auth state, masked-secret payload fields, provider-test model selection, safe provider preflight diagnostics, and legacy Anthropic OAuth cleanup fields remain AI/runtime plus API-contract concerns and must not be absorbed into storage/recovery transport ownership just because those handlers live under the shared backend API tree. Storage/recovery-adjacent consumers may preserve or clear legacy OAuth tokens only through the shared AI settings owner; they must not treat stored OAuth tokens or `auth_method=oauth` as recovery capability, provider readiness, restore authority, or an AI-backed storage support signal.+ Patrol readiness labels on the same settings payload, including the+ user-facing Patrol control label for the stable `configuration` check ID,+ are AI/runtime plus API-contract wording and must not be reinterpreted as+ backup visibility, restore authority, recovery readiness, or storage-source+ health.The same adjacency rule applies to Pulse Assistant chat SSE progress in`internal/api/ai_handler.go`: neutral `workflow_state` transport livenesssuch as `stream_idle`, provider startup, retry, fallback, andmodel-thinking status is Assistant/API progress only, not recoveryacquisition, restore identity, backup task freshness, storage-providerhealth, or storage/recovery job progress.+ The native Assistant surface-tool inventory at+ `GET /api/ai/assistant/surface-tools` follows the same adjacent boundary:+ storage/recovery surfaces may display Assistant tool availability, but must+ not treat it as backup visibility, restore authority, recovery readiness,+ storage-health evidence, or storage/recovery job progress.Direct alert-investigation execution controls in `internal/api/ai_handlers.go`follow that same split: request-scoped `AutonomousMode:false` and`RequireCommandApproval:true` are AI action-governance constraints, not@@ -767,11 +833,66 @@ recovery scope, or a storage/recovery-owned secret source.raw `pulse_*` / `patrol_*` tool-call prose, token accounting text, andprovider thinking text are not recovery evidence, backup freshness, restoreeligibility, storage-local approval state, or recovery execution authority.+ API-facing Assistant chat tool calls projected through+ `internal/api/chat_service_adapter.go` must stay on the shared+ `agentcapabilities` provider-call shape; storage and recovery consumers must+ not reinterpret Assistant transcript tool-call IDs, inputs, output, success+ flags, or provider continuation metadata as backup coverage, recovery+ freshness, restore support, or storage-local action authority.Searchable Assistant session-list queries on `GET /api/ai/sessions` remainthe same adjacent browser-safe history navigation projection: storage andrecovery surfaces may not reinterpret search hits, handoff summaries, ormessage counts as backup coverage, recovery freshness, restore capability,or storage-local action authority.+ The Pulse Intelligence agent capability manifest in+ `internal/agentcapabilities/manifest.go`+ follows the same adjacency rule: external-agent tool metadata,+ action-mode governance, shared external-tool projection helpers, shared+ schema-envelope helpers, and typed MCP argument schemas may mention+ storage-adjacent resources, but they are not recovery-point sources,+ restore authority, storage ownership, or+ storage/recovery-owned API contracts.+ Native Pulse Assistant provider seams and native tool-adapter names in+ shared `internal/api/ai_handler.go`, `internal/api/agent_profiles_tools.go`,+ `internal/api/router.go`, and `internal/api/router_routes_ai_relay.go`+ follow that same adjacent boundary. `MCP` remains an external protocol,+ manifest, and wire-schema term, while the in-app Assistant `ToolAdapter`+ family is AI/runtime plus API-contract state; storage and recovery may+ consume the resulting governed context, but must not fork a recovery-local+ tool transport or reinterpret native Assistant adapter naming as backup+ coverage, restore support, recovery freshness, or storage-local action+ authority.+ Pulse Intelligence operations-loop external-agent readiness in+ `internal/api/agent_resource_context.go` is likewise adjacent+ AI-runtime/API-contract state only: storage and recovery surfaces may+ observe the resulting content-free readiness boolean when explaining a+ guided investigation, but they must not reinterpret the Pulse MCP token+ scope check as backup access, restore authority, provider credential+ readiness, or recovery-job capability.+ Patrol control completed/resolved outcome evidence exposed through+ `patrolAutonomy*` compatibility fields, `patrolAutonomyValueState`, and+ the operator-readable `progressLabel` on that same status projection are+ derived from API-contract owned Patrol status and the shared+ `internal/telemetry` count-only classifier without external-agent readiness+ as an input. The+ legacy Pro activation starter field is entry-point-specific, while legacy+ completed/resolved/value `proActivation*` status fields are compatibility+ aliases only. Storage and+ recovery may not fork those branch rules or status labels, enrich them with+ backup or appliance identifiers, or treat MCP readiness, status wording, or+ any completed/resolved Patrol state as recovery coverage, restore verification, storage health, or+ recovery-job authority.+ Assistant runtime identity strings exposed by those shared API handlers+ follow the same ownership boundary: they must name the first-party surface+ as Pulse Assistant, not a legacy generic `Pulse AI` runtime, and+ storage/recovery surfaces may not reinterpret that naming as recovery-local+ readiness or execution authority.+ Shared AI settings persistence, Patrol preflight, profile-suggestion, and+ remediation-impact copy exposed through those same adjacent handlers must+ keep Pulse Intelligence and Assistant & Patrol naming at the AI/API+ boundary; storage/recovery surfaces may observe that copy but must not+ reinterpret it as backup coverage, restore support, recovery freshness, or+ storage-local action authority.The `can_redo` flag on that same session-list projection is only Assistantconversation repair state. It must not be interpreted as recoveryreversibility, restore availability, backup freshness, or any storage-local@@ -837,6 +958,10 @@ recovery scope, or a storage/recovery-owned secret source.the shared workload query state rather than an opaque unified resource id,so recovery/storage drill-downs reopen the intended platform-ownedworkload drawer instead of landing on an unselected table state.+ Non-storage route constants in that same shared helper, including the+ Patrol control anchor, must stay owned by their product surface and+ must not be reused as recovery entry points or storage/recovery navigation+ aliases.27. Keep alert-side recovery drill-ins on that same embedded-owner route-state contract. When alert investigation surfaces such as resource-incident panels expose recovery follow-up links for TrueNAS or future API-backed platforms, they must route through an owning platform/runtime destination using canonical recovery query vocabulary instead of freezing alert-local recovery URLs, reviving the retired Recovery aggregate route, or introducing another provider-shaped recovery handoff vocabulary.28. Keep VMware onboarding runtime and recovery semantics separate on that same adjacent platform-connections contract. When `internal/api/router.go`, `internal/api/router_routes_registration.go`, or `internal/api/vmware_handlers.go` evolve VMware connection CRUD, poller-owned `poll` / `observed` summary payloads, saved-test refresh, or observed datastore/VM snapshot visibility, storage and recovery may consume the resulting shared context but must not treat those onboarding/runtime payloads as canonical recovery artifacts, restore capability, or recovery-local control transport.29. Keep VMware datastore projection on the shared unified-resource and storage-source contracts. When `frontend-modern/src/hooks/useUnifiedResources.ts` or shared `internal/api/router.go` wiring starts surfacing VMware-backed canonical `storage` resources, storage and recovery may expose those datastores through the owned `vmware-vsphere` source/platform vocabulary for inventory, capacity, and handoff flows only; they must not reinterpret that projection as VMware recovery support, restore semantics, or a provider-local protection surface.@@ -1081,6 +1206,8 @@ recovery scope, or a storage/recovery-owned secret source.11a. Letting adjacent workload route-state changes in shared `frontend-modern/src/routing/resourceLinks.ts` perturb recovery parse/build semantics; expanding canonical workload platform scoping must not alter the owned recovery `platform` and `itemType` vocabulary, legacy alias rewrites, or recovery drill-down workspace selection11b. Letting adjacent storage route-state additions in shared `frontend-modern/src/routing/resourceLinks.ts` perturb recovery route semantics; expanding canonical storage deep links for unified resources must not reuse recovery-owned query names or alter the owned recovery parse/build contract while those surfaces continue sharing the same route-helper module11e. Letting adjacent platform-route additions in shared `frontend-modern/src/routing/resourceLinks.ts` perturb storage or recovery route semantics; adding canonical `/standalone/machines`, `/standalone/availability`, or other platform paths must not reuse storage/recovery query names, alter storage or recovery parse/build behavior, or convert agent-platform membership into storage/recovery ownership+ 11f. Letting adjacent Patrol control starter route state in shared `frontend-modern/src/routing/resourceLinks.ts` perturb storage or recovery route semantics; `patrolControlStarter=patrol_control` is a first-party Patrol control handoff flag only, legacy `operationsLoopStarter=patrol_control`, `operationsLoopStarter=patrol_autonomy`, and `operationsLoopStarter=pulse_pro_activation` are only compatibility aliases, and storage/recovery parse-build contracts must not consume any of them as recovery state, storage focus, platform scope, or proof of backup/recovery posture+ 11g. Letting adjacent Pulse Intelligence external-agent setup anchors in shared `frontend-modern/src/routing/resourceLinks.ts` perturb storage or recovery route semantics; `/settings/pulse-intelligence/assistant#external-agent-setup` is the canonical external-agent setup hash, `/settings/security/api#external-agent-setup` and `/settings/security/api#pulse-mcp-setup` are legacy compatibility hashes, and storage/recovery parse-build contracts must not consume any of them as recovery state, storage focus, platform scope, or proof of backup/recovery posture12. Letting protected-inventory protection posture overload recovery-event outcome filtering; the protected inventory protection-state control must drive the route-backed `state` field and local rollup posture filtering, while the recovery events `status` field remains the canonical outcome filter for points, series, and facets transport filters13. Letting visible protected-item filters fall out of shared recovery links; protected inventory state such as stale, failed, warning, running, unknown, healthy, and never-succeeded must restore from the canonical recovery URL and rewrite to the owned `state=<value>` route form, with legacy `stale=1` accepted only as compatibility input14. Reintroducing stacked full-width recovery tables as the primary desktop layout; the governed recovery surface must expose one primary data region at a time with recovery events as the default workspace and protection coverage as an explicit secondary review so Pulse does not collapse back into a single-platform backup screen@@ -1094,6 +1221,70 @@ recovery scope, or a storage/recovery-owned secret source.## Completion Obligations1. Update this contract when canonical storage or recovery entry points move. Routes added under the shared `internal/api/` extension point that are clearly outside storage/recovery ownership (for example `POST /api/ai/patrol/preflight`, the `patrol_preflight` snapshot field added to `/api/settings/ai`, the auto-trigger preflight dispatch on settings save, the startup-seed dispatch in `NewAISettingsHandler`, and the cached-preflight integration into the Patrol `tools` readiness check — all owned by ai-runtime) do not extend this subsystem's contract; they live in their owning subsystem.+ Content-free Pulse Intelligence telemetry rollups under shared+ `internal/api/` are also adjacent-only. Storage and recovery may consume+ underlying recovery artifacts, action outcomes, or Patrol context through+ their owned surfaces, but anonymous action-plan, approval,+ approved-action-decision, rejected-action-decision, external-agent,+ Assistant, or Patrol usage counters are not backup inventory, restore+ capability, recovery freshness, or storage ownership evidence.+ External-agent activity may be counted for narrow tokens that satisfy the+ called manifest capability scope, including read-only context calls. That+ keeps MCP collaboration measurable, but storage and recovery must not treat+ the resulting counter as evidence that a backup, restore, dataset, or+ storage endpoint was read or mutated.+ Approved action decision telemetry may use shared action lifecycle evidence+ or approved approval records, but the exported rollup remains an anonymous+ approve/reject journey counter. Storage and recovery must not reinterpret+ that counter as proof that a backup, restore, dataset, storage appliance, or+ recovery endpoint was approved, changed, inspected, or verified.+ Approved execution attempt telemetry may be backed by shared action+ lifecycle events, including refused-before-dispatch failures, but the+ exported rollup remains an anonymous operations-loop counter. Storage and+ recovery must not reinterpret that counter as proof that a backup, restore,+ dataset, storage appliance, or recovery endpoint was changed or verified.+ Approved action success telemetry may use the same governed audit stream+ only as a content-free count of approved actions that completed+ successfully. The approved execution counter remains attempt-based, and the+ success counter must not export resource identifiers, actor identifiers,+ command text, command output, verification details, backup scope, restore+ proof, or storage appliance state.+ Rejected action decision telemetry may use the same governed audit stream+ only as a content-free count of actions rejected before execution. It must+ not be treated as backup denial, restore denial, storage policy state, or+ proof that a recovery target was inspected or changed.+ The external-agent recent-use counter is backed by content-free authenticated+ agent/MCP capability activity for manifest-capable API tokens; storage and+ recovery must not reinterpret it as proof that a backup, restore, dataset,+ or recovery endpoint was used.+ The MCP adapter recent-use counter is likewise only adapter-origin+ collaboration telemetry for `pulse-mcp` requests. Storage and recovery may+ use the resulting reports for aggregate Pulse Intelligence adoption, but+ must not treat that bit as evidence that a backup, restore, dataset, storage+ appliance, or recovery endpoint was read, mutated, or verified.+ The operations-loop status projection is also adjacent-only. Its content-free+ stage, next-action, Patrol evidence, contextual collaboration, pending+approval, governed action, verified outcome, and optional token-backed MCP+readiness fields may describe Pulse Intelligence activation progress, but storage and+recovery must not treat them as backup coverage, restore readiness, storage+health verification, appliance access, dataset access, API-token authority+for recovery paths, or recovery mutation proof.+If an aggregate active Patrol finding or pending approval outranks older+completed/resolved loop proof in that projection, that precedence remains only+current operator orientation; it is not backup freshness, restore authority, or+storage-local remediation proof.+Operations-loop workflow starter request counts are even narrower: they are+content-free markers that a native Assistant surface rendered, a first-party+Patrol control handoff started, a legacy Pro activation entry-point handoff+started, or a Pulse MCP surface rendered the manifest-owned+`pulse_operations_loop` starter. The aggregate Patrol control starter count may+include native Patrol, legacy Patrol autonomy, and legacy Pro activation starts,+while `proActivationOperationsLoopStarterCount` remains the legacy entry-point+count. Storage and recovery may observe those aggregate activation reports, but+must not treat starter+ access as backup coverage, recovery freshness, restore readiness, storage+ health verification, dataset access, appliance access, or evidence that any+ recovery endpoint was used.2. Keep recovery store/runtime changes aligned with the storage and recovery frontend proofs in `registry.json`3. Tighten guardrails when legacy storage or recovery presentation paths are removed4. Preserve the dependency split: API payload ownership stays in `api-contracts`, settings shell ownership stays in `frontend-primitives`, and canonical resource truth stays in `unified-resources`@@ -1104,6 +1295,10 @@ recovery scope, or a storage/recovery-owned secret source.must keep that logic on the canonical`internal/unifiedresources/hostname_equivalence.go` contract instead ofwidening it into a broad short-name collapse across distinct FQDNs.+ Approved-action replay through `internal/api/router_routes_ai_relay.go`+ is likewise API/AI-owned transport: storage and recovery may consume the+ resulting incident context, but must not define storage-local approval+ argument keys or bypass the shared `internal/agentcapabilities` helper.5. Keep recovery history table width budgeting derived from the canonical column specs in `frontend-modern/src/utils/recoveryTablePresentation.ts`, not from raw visible-column counts, so normalized subject labels and optional column sets cannot drift the right-edge badges and controls off-screen6. Keep at least one browser-level desktop recovery proof in the governed `recovery-product-surface` policy so right-edge column visibility and wrapper-fit regressions are caught at rendered layout time instead of only through unit-level width math7. Keep the retired dashboard route from becoming a passive no-resources@@ -1180,19 +1375,26 @@ recovery scope, or a storage/recovery-owned secret source.payload must not include local commercial funnel summaries orinfrastructure-onboarding analytics, so recovery-adjacent diagnostics donot inherit commerce telemetry, cross-tenant leakage, or hosted/local- semantic drift through the shared backend route.+ semantic drift through the shared backend route. Pulse Assistant runtime+ status in that shared payload must remain native Assistant availability+ (`assistantRuntimeConnected`), not MCP transport state, and storage/recovery+ consumers must not reinterpret it as backup coverage, recovery readiness,+ or storage-local action authority.16. Keep storage summary interaction scoped through the same canonical IDs.17. Keep adjacent AI settings persistence vendor-neutral on the shared`internal/api/` boundary. When storage- or recovery-adjacent hosted flowsload or save AI settings through shared helpers, any historical hostedquickstart model IDs must be cleared before adjacent surfaces read or- re-emit that state.+ re-emit that state. Legacy Anthropic OAuth tokens follow the same shared-owner rule: adjacent storage/recovery code may not use them as provider configuration and must leave cleanup to the AI settings contract.17a. Keep adjacent AI paid-control state entitlement-effective on that shared`internal/api/` boundary. Storage- and recovery-adjacent flows may preservestored Assistant or Patrol preferences in config, but they must not treatstored autonomous, auto-remediation, or alert-triggered analysis settingsas active restore, recovery, or support capability unless the shared AIruntime entitlement clamp exposes them as currently effective.+ AI settings control-refresh callbacks in `internal/api/ai_handlers.go` are+ likewise native Assistant tool-visibility plumbing, not MCP transport+ state and not storage/recovery execution authority.When operators hover or focus pools versus physical disks, the storagesummary must reuse one resolved active-series ID across card state andchart highlighting so pool-only cards demote cleanly during disk focus and@@ -1283,6 +1485,13 @@ recovery scope, or a storage/recovery-owned secret source.## Current State+Denied Patrol investigation-fix approvals passing through shared+`internal/api/` handlers are adjacent AI-runtime/action-governance state only.+The `fix_rejected` finding outcome means an operator declined a proposed Patrol+fix before execution; it must not become protection state, recovery-point+state, backup verification state, or storage/recovery-local remediation+semantics.+Default-org token scoping and notification-settings fan-out on shared`internal/api/` handlers are likewise adjacent only: they areapi-contract/security owned and create no storage, recovery-point, or@@ -1362,11 +1571,25 @@ or storage/recovery freshness evidence. The verification projection onrecover from /api/actions/{id} after a reconnect — the eventcarries a copy, not the original, so the durable record remainsthe canonical source.+Storage/recovery consumers must treat the event vocabulary as a shared+API/AI-owned contract from `internal/agentcapabilities`. Event names and+transport markers may be used to distinguish doorbells from keepalives, but+storage/recovery must not define local event-name registries or infer recovery+freshness from `stream.connected` or `heartbeat`.The agent capabilities manifest at `/api/agent/capabilities` isread-only and stateless — no persistence is involved. The manifest-is hand-authored in `internal/api/agent_capabilities.go`; storage-flows are not affected.+is hand-authored in `internal/agentcapabilities/manifest.go` and served by+the API handler; storage flows are not affected.+Its action mode and approval policy metadata are API/AI-owned governance+posture for agent tool selection. Storage and recovery may observe that+metadata when agents explain available tools, but must not reinterpret it as+backup ownership, restore capability, recovery freshness, or storage-local+action authority.+Manifest `inputSchema` metadata is likewise an API-owned agent argument+contract. It may help an external agent call action or finding lifecycle tools,+or replace operator-state, but it does not introduce storage/recovery+persistence, restore authority, or backup-specific mutation semantics.When that manifest exposes provisioning tools over `/api/discover`and `/api/config/nodes`, storage and recovery may observe the resultingconfigured sources and backup evidence only after the canonical node@@ -1387,6 +1610,16 @@ platform-wide `APIError` shape). Recovery posture is identical:when the action audit store rehydrates on startup, the actionendpoints recover the same lifecycle records they always did.+The Patrol finding lifecycle endpoints advertised in the agent+capabilities manifest (`acknowledge_finding`, `snooze_finding`,+`dismiss_finding`, `resolve_finding`) follow the same storage boundary:+their agent-facing stable error envelope is an API/AI-runtime wire+contract only and is shared through `internal/agentcapabilities`.+Successful calls still mutate the existing Patrol finding store, unified+finding store, and learning feedback store exactly as the UI path does; no+MCP-specific, agent-specific, or recovery-specific persistence is introduced+by the manifest error-code declarations or by the shared error envelope.+The agent-consumable bundled context endpoint`/api/agent/resource-context/{id}` reads the same durable`resource_operator_state` table and `action_audits` table through the@@ -1412,6 +1645,34 @@ store and the approval store rehydrate on startup, the fleet viewrecovers the same situated picture without any fleet-specificrehydration step.+The Patrol-control status endpoint at+`/api/agent/patrol-control/status` introduces no new persistence. The legacy+`/api/agent/operations-loop/status` URL remains a compatibility alias. It reads the+registry, active findings, pending approval counts, recent action-audit records,+and recent action lifecycle events over the existing evidence window, then+returns only aggregate stage state and counts. Lifecycle events may rehydrate a+recent approval or rejection for a plan created before the window, but the+projection still resolves the event back to the canonical action audit before+counting governance or verification; approved and rejected decision counts stay+separate so a rejected-only decision can complete the no-execution branch+without being mistaken for verified remediation. The four-step operator rollup+follows the same adjacent-only evidence boundary: governance step counts may+reflect pending approvals or later decision evidence, active aggregate Patrol+findings may keep the next action on current operator work, the Assistant step+count may reflect contextual collaboration, and verification step counts may+reflect verified outcomes or terminal rejected decisions. Optional MCP readiness+stays in `externalAgentReady`, but storage and recovery must not treat those+counts or readiness as backup freshness, restore authority, or storage-local+remediation proof. The approved-success telemetry predicate follows that same+boundary: execution success alone is not verified outcome proof unless the+approved action also carries `VerificationOutcome.Status=verified` or a+canonical verification result that ran and succeeded, and storage/recovery+surfaces must not use those Patrol-control values as backup, restore, or+protected-state evidence. Recovery posture is therefore identical to the underlying+stores: once unified resources, findings, approvals, action audits, and+lifecycle events have rehydrated, the status projection is available without an+Patrol-control specific recovery artifact.+The agent capabilities manifest at `/api/agent/capabilities` ishand-authored static data. There is no persistence to recover —the manifest is a constant compiled into the binary; on every@@ -1500,6 +1761,20 @@ fields and nullable mode/kind metadata before presenting canonical item labels,while storage detail drawers and filter controls must route summary series IDs,source tones, and disk metrics through the shared storage helpers instead ofreconstructing them from local table state.+Storage and recovery may depend on the adjacent Patrol-control status+projection staying content-free, including its Patrol control starter count,+completed/resolved loop counts, `patrolControlValueState`, legacy+`patrolAutonomy*` aliases, and legacy `proActivation*` compatibility fields+when shared API helpers are touched. The legacy Pro activation starter field is+entry-point-specific, while the legacy completed/resolved/value fields mirror+Patrol control values. Those values are classified by the shared+`internal/telemetry` Patrol control proof helper and are not recovery+verification, storage health, backup coverage, restore readiness, or+action-outcome proof, and storage/recovery surfaces must not use them to imply a+protected or resolved state. Approved-success telemetry is likewise+Patrol-control proof only when the action has verified post-action evidence;+successful command completion without canonical verification remains outside+storage/recovery readiness.Storage and recovery's adjacent `internal/api/` contract must also preservethe product-facing remediation vocabulary used by shared API denials. Whenstorage/recovery-adjacent browser sessions encounter AI or Patrol remediation@@ -2682,6 +2957,10 @@ and onboarding analytics remain outside the shared diagnostics payload, sorecovery-adjacent diagnostics surfaces can safely share the backend routewithout inheriting commerce telemetry, cross-tenant leakage, or hosted/localsemantic drift.+That same shared diagnostics payload may expose native Pulse Assistant runtime+availability as `assistantRuntimeConnected`, but storage/recovery consumers+must not revive MCP diagnostic fields or treat Assistant runtime availability+as backup freshness, restore capability, or storage-local execution authority.That same shared `internal/api/` dependency now also assumes auth persistencecompatibility stays on an explicit migration/import boundary: legacyraw-token `sessions.json` and `csrf_tokens.json` files may load for upgradediff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex 6bb4d650e9..f311b692eb 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -89,15 +89,16 @@ cross-source deduplication.64. `frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts`65. `frontend-modern/src/components/Infrastructure/useUnifiedResourceTableState.ts`66. `frontend-modern/src/components/Infrastructure/useUnifiedResourceTableViewportSync.ts`-67. `frontend-modern/src/components/Discovery/DiscoveryTab.tsx`-68. `frontend-modern/src/components/Discovery/useDiscoveryTabState.ts`-69. `frontend-modern/src/utils/agentResources.ts`-70. `frontend-modern/src/utils/canonicalResourceTypes.ts`-71. `frontend-modern/src/utils/resourceBadgePresentation.ts`-72. `frontend-modern/src/utils/resourceChangePresentation.ts`-73. `frontend-modern/src/utils/actionAuditPresentation.ts`-74. `frontend-modern/src/utils/resourceCorrelationPresentation.ts`-75. `frontend-modern/src/utils/resourcePlatformData.ts`+67. `frontend-modern/src/components/Discovery/discoveryReadiness.ts`+68. `frontend-modern/src/components/Discovery/DiscoveryTab.tsx`+69. `frontend-modern/src/components/Discovery/useDiscoveryTabState.ts`+70. `frontend-modern/src/utils/agentResources.ts`+71. `frontend-modern/src/utils/canonicalResourceTypes.ts`+72. `frontend-modern/src/utils/resourceBadgePresentation.ts`+73. `frontend-modern/src/utils/resourceChangePresentation.ts`+74. `frontend-modern/src/utils/actionAuditPresentation.ts`+75. `frontend-modern/src/utils/resourceCorrelationPresentation.ts`+76. `frontend-modern/src/utils/resourcePlatformData.ts`76. `frontend-modern/src/utils/resourcePolicyPresentation.ts`77. `frontend-modern/src/utils/resourceStateAdapters.ts`78. `frontend-modern/src/utils/resourceTypeCompat.ts`@@ -823,7 +824,7 @@ AI-only summary payloads, or page-local heuristics.generic disk-count aggregate, so resource drawers and incidents do not hidethe actual protection boundary behind a broader count phrase.6. Add canonical governed name-resolution or policy-aware resource lookup behavior through `internal/unifiedresources/resolve.go` and `internal/unifiedresources/resolve_context.go`-8. Add or change discovery-support runtime under the resource drawer through `frontend-modern/src/components/Discovery/DiscoveryTab.tsx` for shell/presentation ownership and `frontend-modern/src/components/Discovery/useDiscoveryTabState.ts` for fetch, websocket-progress, manual-run triggering, and notes-mutation ownership. Embedded drawers may expose the top-level run action through this shared Discovery tab, but they must still call the canonical discovery trigger state path instead of introducing drawer-local API mutations.+8. Add or change discovery-support runtime under the resource drawer through `frontend-modern/src/components/Discovery/DiscoveryTab.tsx` for shell/presentation ownership, `frontend-modern/src/components/Discovery/useDiscoveryTabState.ts` for fetch, websocket-progress, manual-run triggering, and notes-mutation ownership, and `frontend-modern/src/components/Discovery/discoveryReadiness.ts` for the shared readiness verdict used by resource-drawer Discovery surfaces. Embedded drawers may expose the top-level run action through this shared Discovery tab, but they must still call the canonical discovery trigger state path instead of introducing drawer-local API mutations.Resource drawer secondary sections, action history, discovery run summaries,and other compact resource-detail cards may own their resource-specificlabels, rows, filters, and actions, but the repeated bordered compact frame@@ -898,12 +899,27 @@ AI-only summary payloads, or page-local heuristics.16. Keep platform/runtime top-level route paths on the canonical resource-linkhelper. `frontend-modern/src/routing/resourceLinks.ts` owns the`STANDALONE_PATH`, `DOCKER_PATH`, `KUBERNETES_PATH`, `TRUENAS_PATH`,- `VMWARE_PATH` constants and the `buildStandalonePath`, `buildDockerPath`,- `buildKubernetesPath`, `buildTrueNASPath`, `buildVmwarePath` builders.+ `VMWARE_PATH`, `PATROL_PATH`, `PATROL_CONTROL_ANCHOR`,+ `PATROL_CONTROL_PATH`, and `PATROL_CONTROL_STARTER_QUERY_PARAM` constants,+ the route-backed Patrol control starter helpers, and the `buildStandalonePath`,+ `buildDockerPath`, `buildKubernetesPath`, `buildTrueNASPath`,+ `buildVmwarePath` builders.Per-platform surfaces and tab specs mustderive every internal link from those builders so the canonical resourceURL vocabulary stays single-sourced; ad hoc string concatenation of- platform routes inside feature directories is not permitted.+ platform routes inside feature directories is not permitted. The canonical+ Pulse Intelligence external-agent hash+ `/settings/pulse-intelligence/assistant#external-agent-setup` and legacy+ `/settings/security/api#external-agent-setup` /+ `/settings/security/api#pulse-mcp-setup` compatibility hashes may live in+ the shared route helper, but they are adjacent settings route state, not+ unified-resource identity, platform scope, or drawer focus state.+ The Patrol `patrolControlStarter=patrol_control` query is an adjacent+ first-party Patrol control handoff flag, with legacy+ `operationsLoopStarter` values accepted only as compatibility aliases, not+ unified-resource filters or focus keys. Unified-resource consumers must not reuse those values for resource+ identity, list filtering, contextual focus, storage state, recovery state,+ or platform scoping.The user-facing Machines surface's default resource route is the machines projection(`/standalone/machines`); agentless endpoint rows use the`/standalone/availability` projection and must not be collapsed into a@@ -2094,7 +2110,10 @@ from raw resource fields or invent relationship-map fallbacks locally.The same surfaces now also render recent changes through the shared`frontend-modern/src/components/Infrastructure/ResourceChangeSummary.tsx`card, so canonical timeline wording and ordering stay governed by one-frontend feed instead of separate page-local loops.+frontend feed instead of separate page-local loops. Callers may suppress+resource-change metadata badges only for compact operator-context surfaces such+as Patrol's supporting context; the shared card still owns headline/reason+dedupe so prefixed backend reasons do not render as duplicated visible copy.Assistant finding handoffs are part of that same timeline contract: when the AIruntime needs recent changes for product-originated handoff resources, it shouldread the canonical unified-resource timeline and `FormatResourceRecentChangesContext`@@ -2812,14 +2831,17 @@ change-kind wording, source-type wording, source-adapter provenance labels,headline formatting, and timeline sort order. Future recent-change wording orbadge changes should extend those unified-resource owners instead of leavingrecent-change presentation unowned or rebuilding helper-local labels inside AI,-Patrol, performance, or infrastructure surfaces.+Patrol, performance, or infrastructure surfaces. The shared card must not repeat+a reason line when that reason already equals the canonical headline.The shared correlation and policy-posture presentation boundaries are alsoowned here now. `frontend-modern/src/components/Infrastructure/ResourceCorrelationSummary.tsx`is the canonical shared card for canonical resource relationships, dependency,dependent, and learned-correlation context, while`frontend-modern/src/utils/resourceCorrelationPresentation.ts` owns endpointlabels, relationship labels, headline formatting, summary wording, and canonical-relationship/correlation ordering.+relationship/correlation ordering. Correlation and relationship badge text must+preserve the formatter's human-readable title case instead of forcing visual+uppercase over enum-like payloads such as `ALERT → ALERT`.`frontend-modern/src/components/Infrastructure/ResourcePolicySummary.tsx`is the canonical shared card for governed policy-posture counts, while`frontend-modern/src/utils/resourcePolicyPresentation.ts` owns the canonicaldiff --git a/docs/releases/AGENT_PARADIGM.md b/docs/releases/AGENT_PARADIGM.mdindex db03fe7ec6..46d09ca89d 100644--- a/docs/releases/AGENT_PARADIGM.md+++ b/docs/releases/AGENT_PARADIGM.md@@ -9,8 +9,8 @@ Trim or expand as the cut requires; this file is the source draft._## HeadlinePulse v6 ships an agent-paradigm substrate so external agents-(Claude Desktop, Claude Code, custom MCP clients, plain HTTP-consumers) can drive Pulse with the same context an in-process+(Claude Desktop, Claude Code, OpenCode, other MCP clients, plain+HTTP consumers) can drive Pulse with the same context an in-processPatrol or Assistant has.## What an operator gets@@ -20,20 +20,23 @@ Patrol or Assistant has.running instance declares, grouped by category (Context,Operator state, Patrol findings, Action governance), withscope, method, path, and the stable error codes each emits.- The section also generates a Claude Desktop / Claude Code- config snippet pre-filled with the deployment's own URL, so- wiring an agent is copy, paste, and add a token.+ The section also generates client-ready MCP config snippets+ pre-filled with the deployment's own URL: OpenCode's native+ `opencode.json` / `mcp` shape plus the common `mcpServers` shape+ for Claude-style clients. Wiring an agent is copy, paste, and add a+ token.-- **Drivable from Claude in one command.** A new `pulse-mcp`+- **Drivable from MCP clients in one command.** A new `pulse-mcp`server adapter ships in the Pulse repo (`cmd/pulse-mcp/`)with a published distribution path. Install from the PulseGitHub Release using the one-line installer:`curl -fsSL https://github.com/rcourtman/Pulse/releases/latest/download/install-mcp.sh | bash`(or the matching `install-mcp.ps1` PowerShell installer on- Windows). Wire it into Claude Desktop or Claude Code per- [`cmd/pulse-mcp/README.md`](../../cmd/pulse-mcp/README.md) and- Pulse's tools appear natively. Each MCP tool is one entry in- the canonical capabilities manifest; adding a capability on+ Windows). Wire it into any MCP-speaking client per+ [`cmd/pulse-mcp/README.md`](../../cmd/pulse-mcp/README.md);+ the README carries the OpenCode-native `mcp` block plus the common+ `mcpServers` block for Claude-style clients. Each MCP tool is one entry+ in the canonical capabilities manifest; adding a capability onthe backend extends the MCP surface automatically. An optional`--emit-notifications` flag translates Pulse's SSE eventstream (`finding.created`, `approval.pending`,@@ -55,7 +58,7 @@ Patrol or Assistant has.## Four axes-- **Discovery.** `/api/agent/capabilities` is a hand-authored,+- **Discovery.** `/api/agent/capabilities` is a canonical,unauthenticated manifest agents fetch at startup to learnwhat's available.- **Read.** `/api/agent/resource-context/{id}` returns the@@ -84,11 +87,12 @@ Patrol or Assistant has.Reads as a worked example for anyone building a customintegration in any language.- **MCP server:** [`cmd/pulse-mcp`](../../cmd/pulse-mcp/). Stdio- JSON-RPC adapter for Claude Desktop and Claude Code. Mint a- Pulse API token with `monitoring:read` (and- `monitoring:write` for operator-state writes), set- `PULSE_API_TOKEN` in the client's env block, and Pulse's- capabilities appear as MCP tools.+ JSON-RPC adapter for MCP-speaking clients. For the full current+ surface, mint a Pulse API token with the manifest `requiredScopes`+ list shown in Settings → API Access and the README. Narrower+ read-only tokens such as `monitoring:read` remain valid for the+ read-only subset; set `PULSE_API_TOKEN` in the client's env block,+ and Pulse's capabilities appear as MCP tools.- **Contract reference:**[`docs/AGENT_SUBSTRATE.md`](../AGENT_SUBSTRATE.md) is thein-repo session marker. The full subsystem contract lives indiff --git a/internal/agentcapabilities/action_target.go b/internal/agentcapabilities/action_target.gonew file mode 100644index 0000000000..342cc8990b--- /dev/null+++ b/internal/agentcapabilities/action_target.go@@ -0,0 +1,83 @@+package agentcapabilities++import (+ "errors"+ "fmt"+ "strings"+)++const (+ ActionTargetTypeAgent = "agent"+ ActionTargetTypeSystemContainer = "system-container"+ ActionTargetTypeVM = "vm"+)++const (+ actionTargetTypeAllowedDescription = "agent, system-container, vm"+ actionResourceTypeAllowedDescription = "vm, system-container, oci-container, app-container, pod, agent, node, docker-host, k8s-cluster, k8s-node, k8s-deployment, k8s-service, storage, disk, pbs, pmg, proxmox, ceph"+)++// NormalizeActionTargetType returns the canonical governed action target type+// used by Pulse Assistant and external-agent adapters.+func NormalizeActionTargetType(raw string) string {+ return strings.ToLower(strings.TrimSpace(raw))+}++// IsActionTargetType reports whether targetType is one of the shared governed+// action target kinds.+func IsActionTargetType(targetType string) bool {+ switch NormalizeActionTargetType(targetType) {+ case ActionTargetTypeAgent, ActionTargetTypeSystemContainer, ActionTargetTypeVM:+ return true+ default:+ return false+ }+}++// ActionTargetTypeAllowedDescription returns the operator-facing list of+// action target kinds accepted by governed execution surfaces.+func ActionTargetTypeAllowedDescription() string {+ return actionTargetTypeAllowedDescription+}++// NormalizeAndValidateOptionalActionTargetType validates an optional action+// target type while preserving the empty value for callers that default later.+func NormalizeAndValidateOptionalActionTargetType(raw string) (string, error) {+ targetType := NormalizeActionTargetType(raw)+ if targetType == "" {+ return "", nil+ }+ if !IsActionTargetType(targetType) {+ return "", fmt.Errorf("invalid target_type")+ }+ return targetType, nil+}++// NormalizeActionResourceType canonicalizes resource type aliases that map to+// governed action targets. It is intentionally narrow to action-routing needs,+// not a general resource model normalizer.+func NormalizeActionResourceType(raw string) string {+ switch normalized := strings.ToLower(strings.TrimSpace(raw)); normalized {+ case "truenas":+ return ActionTargetTypeAgent+ default:+ return normalized+ }+}++// ActionTargetTypeForResourceType maps a Pulse resource type to the governed+// action target type used for Assistant approvals and external-agent actions.+func ActionTargetTypeForResourceType(raw string) (string, error) {+ switch resourceType := NormalizeActionResourceType(raw); resourceType {+ case ActionTargetTypeVM:+ return ActionTargetTypeVM, nil+ case ActionTargetTypeSystemContainer, "oci-container":+ return ActionTargetTypeSystemContainer, nil+ case ActionTargetTypeAgent, "node", "docker-host", "app-container", "pod", "k8s-node", "k8s-cluster", "k8s-deployment", "k8s-service", "storage", "disk", "pbs", "pmg", "proxmox", "ceph":+ return ActionTargetTypeAgent, nil+ case "":+ return "", errors.New("resource_type is required")+ default:+ return "", fmt.Errorf("unsupported resource_type %q (allowed: %s)", raw, actionResourceTypeAllowedDescription)+ }+}diff --git a/internal/agentcapabilities/action_target_test.go b/internal/agentcapabilities/action_target_test.gonew file mode 100644index 0000000000..fc9e388883--- /dev/null+++ b/internal/agentcapabilities/action_target_test.go@@ -0,0 +1,84 @@+package agentcapabilities++import (+ "strings"+ "testing"+)++func TestNormalizeAndValidateOptionalActionTargetTypeUsesSharedVocabulary(t *testing.T) {+ tests := []struct {+ name string+ in string+ want string+ wantErr string+ }{+ {name: "empty allowed", in: "", want: ""},+ {name: "agent", in: " AGENT ", want: ActionTargetTypeAgent},+ {name: "system container", in: "SYSTEM-CONTAINER", want: ActionTargetTypeSystemContainer},+ {name: "vm", in: "vm", want: ActionTargetTypeVM},+ {name: "legacy host rejected", in: "host", wantErr: "invalid target_type"},+ {name: "legacy container rejected", in: "container", wantErr: "invalid target_type"},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got, err := NormalizeAndValidateOptionalActionTargetType(tt.in)+ if tt.wantErr != "" {+ if err == nil || !strings.Contains(err.Error(), tt.wantErr) {+ t.Fatalf("NormalizeAndValidateOptionalActionTargetType(%q) error = %v, want substring %q", tt.in, err, tt.wantErr)+ }+ return+ }+ if err != nil {+ t.Fatalf("NormalizeAndValidateOptionalActionTargetType(%q) error = %v", tt.in, err)+ }+ if got != tt.want {+ t.Fatalf("NormalizeAndValidateOptionalActionTargetType(%q) = %q, want %q", tt.in, got, tt.want)+ }+ })+ }+}++func TestActionTargetTypeForResourceTypeMapsActionResources(t *testing.T) {+ tests := []struct {+ name string+ in string+ want string+ wantErr string+ }{+ {name: "vm", in: "vm", want: ActionTargetTypeVM},+ {name: "system container", in: "system-container", want: ActionTargetTypeSystemContainer},+ {name: "oci container", in: "oci-container", want: ActionTargetTypeSystemContainer},+ {name: "app container", in: "app-container", want: ActionTargetTypeAgent},+ {name: "pod", in: "pod", want: ActionTargetTypeAgent},+ {name: "k8s deployment", in: "k8s-deployment", want: ActionTargetTypeAgent},+ {name: "node", in: "node", want: ActionTargetTypeAgent},+ {name: "truenas alias", in: "truenas", want: ActionTargetTypeAgent},+ {name: "legacy host rejected", in: "host", wantErr: "unsupported resource_type"},+ {name: "missing type", in: "", wantErr: "resource_type is required"},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got, err := ActionTargetTypeForResourceType(tt.in)+ if tt.wantErr != "" {+ if err == nil || !strings.Contains(err.Error(), tt.wantErr) {+ t.Fatalf("ActionTargetTypeForResourceType(%q) error = %v, want substring %q", tt.in, err, tt.wantErr)+ }+ return+ }+ if err != nil {+ t.Fatalf("ActionTargetTypeForResourceType(%q) error = %v", tt.in, err)+ }+ if got != tt.want {+ t.Fatalf("ActionTargetTypeForResourceType(%q) = %q, want %q", tt.in, got, tt.want)+ }+ })+ }+}++func TestActionTargetTypeAllowedDescriptionMatchesStableAPIText(t *testing.T) {+ if got := ActionTargetTypeAllowedDescription(); got != "agent, system-container, vm" {+ t.Fatalf("ActionTargetTypeAllowedDescription() = %q", got)+ }+}diff --git a/internal/agentcapabilities/control_level.go b/internal/agentcapabilities/control_level.gonew file mode 100644index 0000000000..6f77e35017--- /dev/null+++ b/internal/agentcapabilities/control_level.go@@ -0,0 +1,48 @@+package agentcapabilities++// ControlLevel is the shared Pulse Intelligence permission level for governed+// tool/action surfaces. Assistant settings, Assistant tool availability, and+// external-agent adapters must use this vocabulary rather than local strings.+type ControlLevel string++const (+ // ControlLevelReadOnly allows read/query tools only.+ ControlLevelReadOnly ControlLevel = "read_only"+ // ControlLevelControlled allows control tools through approval-backed paths.+ ControlLevelControlled ControlLevel = "controlled"+ // ControlLevelAutonomous allows eligible control tools without per-command approval.+ ControlLevelAutonomous ControlLevel = "autonomous"+)++// NormalizeControlLevel fails closed to read_only for unset or unknown values.+func NormalizeControlLevel(level string) ControlLevel {+ switch ControlLevel(level) {+ case ControlLevelReadOnly, ControlLevelControlled, ControlLevelAutonomous:+ return ControlLevel(level)+ default:+ return ControlLevelReadOnly+ }+}++// IsValidControlLevel reports whether a value is in the stable shared+// vocabulary. Empty and legacy values are invalid and should be normalized by+// callers that need a runtime setting.+func IsValidControlLevel(level string) bool {+ switch ControlLevel(level) {+ case ControlLevelReadOnly, ControlLevelControlled, ControlLevelAutonomous:+ return true+ default:+ return false+ }+}++// ControlLevelAllowsControlTools reports whether the normalized level may expose+// tools that can change Pulse or target-side state. Unknown levels fail closed.+func ControlLevelAllowsControlTools(level ControlLevel) bool {+ switch NormalizeControlLevel(string(level)) {+ case ControlLevelControlled, ControlLevelAutonomous:+ return true+ default:+ return false+ }+}diff --git a/internal/agentcapabilities/control_level_test.go b/internal/agentcapabilities/control_level_test.gonew file mode 100644index 0000000000..3c3264a99d--- /dev/null+++ b/internal/agentcapabilities/control_level_test.go@@ -0,0 +1,58 @@+package agentcapabilities++import "testing"++func TestNormalizeControlLevelFailsClosed(t *testing.T) {+ tests := []struct {+ name string+ level string+ want ControlLevel+ }{+ {name: "empty", level: "", want: ControlLevelReadOnly},+ {name: "read only", level: "read_only", want: ControlLevelReadOnly},+ {name: "controlled", level: "controlled", want: ControlLevelControlled},+ {name: "autonomous", level: "autonomous", want: ControlLevelAutonomous},+ {name: "legacy suggest", level: "suggest", want: ControlLevelReadOnly},+ {name: "unknown", level: "bad", want: ControlLevelReadOnly},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := NormalizeControlLevel(tt.level); got != tt.want {+ t.Fatalf("NormalizeControlLevel(%q) = %q, want %q", tt.level, got, tt.want)+ }+ })+ }+}++func TestControlLevelAllowsControlTools(t *testing.T) {+ tests := []struct {+ level ControlLevel+ want bool+ }{+ {ControlLevelReadOnly, false},+ {ControlLevelControlled, true},+ {ControlLevelAutonomous, true},+ {ControlLevel(""), false},+ {ControlLevel("bad"), false},+ }++ for _, tt := range tests {+ if got := ControlLevelAllowsControlTools(tt.level); got != tt.want {+ t.Fatalf("ControlLevelAllowsControlTools(%q) = %v, want %v", tt.level, got, tt.want)+ }+ }+}++func TestIsValidControlLevel(t *testing.T) {+ for _, level := range []string{"read_only", "controlled", "autonomous"} {+ if !IsValidControlLevel(level) {+ t.Fatalf("IsValidControlLevel(%q) = false, want true", level)+ }+ }+ for _, level := range []string{"", "suggest", "bad"} {+ if IsValidControlLevel(level) {+ t.Fatalf("IsValidControlLevel(%q) = true, want false", level)+ }+ }+}diff --git a/internal/agentcapabilities/errors.go b/internal/agentcapabilities/errors.gonew file mode 100644index 0000000000..d22854d6bf--- /dev/null+++ b/internal/agentcapabilities/errors.go@@ -0,0 +1,66 @@+package agentcapabilities++import "encoding/json"++// AgentErrCode* constants are the snake_case values exposed by the+// agent-surface error envelope and advertised in manifest errorCodes.+const (+ AgentErrCodeResourceNotFound = "resource_not_found"+ AgentErrCodeOperatorStateNotSet = "operator_state_not_set"+ AgentErrCodeOperatorStateInvalid = "operator_state_invalid"+ AgentErrCodeInvalidFindingRequest = "invalid_finding_request"+ AgentErrCodeFindingNotFound = "finding_not_found"+ AgentErrCodeFindingActionNotAllowed = "finding_action_not_allowed"+ AgentErrCodePatrolUnavailable = "patrol_unavailable"+ AgentErrCodeInvalidActionRequest = "invalid_action_request"+ AgentErrCodeCapabilityNotFound = "capability_not_found"+ AgentErrCodeActionExecutionUnavailable = "action_execution_unavailable"+ AgentErrCodeMissingID = "missing_id"+ AgentErrCodeInvalidID = "invalid_id"+ AgentErrCodeInvalidActionDecision = "invalid_action_decision"+ AgentErrCodeActionNotFound = "action_not_found"+ AgentErrCodeActionNotPending = "action_not_pending"+ AgentErrCodeActionPlanExpired = "action_plan_expired"+ AgentErrCodeInvalidActionExecution = "invalid_action_execution"+ AgentErrCodeActionNotApproved = "action_not_approved"+ AgentErrCodeActionAlreadyExecuting = "action_already_executing"+ AgentErrCodeActionExecutionFinal = "action_execution_final"+ AgentErrCodeActionDryRunOnly = "action_dry_run_only"+ AgentErrCodeActionPlanDrift = "action_plan_drift"+ AgentErrCodeResourceRemediationLocked = "resource_remediation_locked"+ AgentErrCodeActionExecutorUnavailable = "action_executor_unavailable"+)++// ErrorEnvelope is the stable failure shape emitted by Pulse Intelligence+// agent-surface endpoints. Agents branch on Error, not on Message.+type ErrorEnvelope struct {+ Error string `json:"error"`+ Message string `json:"message"`+ Details map[string]string `json:"details,omitempty"`+}++// NewErrorEnvelope builds an agent-stable error envelope while preserving the+// two-field JSON shape when there are no structured details.+func NewErrorEnvelope(code, message string, details map[string]string) ErrorEnvelope {+ if len(details) == 0 {+ details = nil+ }+ return ErrorEnvelope{+ Error: code,+ Message: message,+ Details: details,+ }+}++// DecodeErrorEnvelope parses a response body as an agent-stable error envelope.+// The boolean is false when the body is not the shared shape.+func DecodeErrorEnvelope(body []byte) (ErrorEnvelope, bool) {+ var envelope ErrorEnvelope+ if err := json.Unmarshal(body, &envelope); err != nil {+ return ErrorEnvelope{}, false+ }+ if envelope.Error == "" || envelope.Message == "" {+ return ErrorEnvelope{}, false+ }+ return envelope, true+}diff --git a/internal/agentcapabilities/errors_test.go b/internal/agentcapabilities/errors_test.gonew file mode 100644index 0000000000..d58ce17280--- /dev/null+++ b/internal/agentcapabilities/errors_test.go@@ -0,0 +1,54 @@+package agentcapabilities++import (+ "encoding/json"+ "strings"+ "testing"+)++func TestNewErrorEnvelopeOmitsEmptyDetails(t *testing.T) {+ envelope := NewErrorEnvelope(AgentErrCodeResourceNotFound, "Resource not found", nil)+ body, err := json.Marshal(envelope)+ if err != nil {+ t.Fatalf("marshal envelope: %v", err)+ }+ if string(body) != `{"error":"resource_not_found","message":"Resource not found"}` {+ t.Fatalf("ErrorEnvelope JSON = %s", body)+ }+}++func TestNewErrorEnvelopePreservesDetails(t *testing.T) {+ envelope := NewErrorEnvelope(AgentErrCodeOperatorStateInvalid, "Invalid operator state", map[string]string{+ "intentionallyOffline": "must be boolean",+ })+ body, err := json.Marshal(envelope)+ if err != nil {+ t.Fatalf("marshal envelope: %v", err)+ }+ if !strings.Contains(string(body), `"details":{"intentionallyOffline":"must be boolean"}`) {+ t.Fatalf("ErrorEnvelope JSON must include details: %s", body)+ }+}++func TestDecodeErrorEnvelopeRecognizesSharedShape(t *testing.T) {+ envelope, ok := DecodeErrorEnvelope([]byte(`{"error":"resource_not_found","message":"missing"}`))+ if !ok {+ t.Fatal("DecodeErrorEnvelope did not recognize shared shape")+ }+ if envelope.Error != "resource_not_found" || envelope.Message != "missing" {+ t.Fatalf("decoded envelope = %+v", envelope)+ }++ if _, ok := DecodeErrorEnvelope([]byte(`{"code":"resource_not_found","error":"human text"}`)); ok {+ t.Fatal("DecodeErrorEnvelope recognized the platform-wide API error shape")+ }+ if _, ok := DecodeErrorEnvelope([]byte(`not-json`)); ok {+ t.Fatal("DecodeErrorEnvelope recognized non-JSON")+ }+ if _, ok := DecodeErrorEnvelope([]byte(`{"message":"missing error"}`)); ok {+ t.Fatal("DecodeErrorEnvelope recognized envelope without error code")+ }+ if _, ok := DecodeErrorEnvelope([]byte(`{"error":"missing_message"}`)); ok {+ t.Fatal("DecodeErrorEnvelope recognized envelope without message")+ }+}diff --git a/internal/agentcapabilities/events.go b/internal/agentcapabilities/events.gonew file mode 100644index 0000000000..4787089604--- /dev/null+++ b/internal/agentcapabilities/events.go@@ -0,0 +1,59 @@+package agentcapabilities++// EventKind is the stable Pulse Intelligence event identifier used by API SSE+// streams and external-agent adapters.+type EventKind string++const (+ // EventKindFindingCreated fires when Patrol records a new finding.+ EventKindFindingCreated EventKind = "finding.created"++ // EventKindApprovalPending fires when a governed action waits on operator+ // approval.+ EventKindApprovalPending EventKind = "approval.pending"++ // EventKindActionCompleted fires when an action audit reaches a terminal+ // state.+ EventKindActionCompleted EventKind = "action.completed"++ // EventKindStreamConnected is the one-shot SSE synchronization marker for a+ // newly opened stream.+ EventKindStreamConnected EventKind = "stream.connected"++ // EventKindHeartbeat is the stream-local SSE keepalive.+ EventKindHeartbeat EventKind = "heartbeat"+)++var agentActionableEventKinds = []string{+ string(EventKindFindingCreated),+ string(EventKindApprovalPending),+ string(EventKindActionCompleted),+}++// AgentActionableEventKinds returns the non-transport event kinds external+// agents should expect to handle as product notifications.+func AgentActionableEventKinds() []string {+ return append([]string(nil), agentActionableEventKinds...)+}++// IsTransportEventKind reports whether an event kind is stream plumbing rather+// than a product notification.+func IsTransportEventKind(kind string) bool {+ switch EventKind(kind) {+ case EventKindStreamConnected, EventKindHeartbeat:+ return true+ default:+ return false+ }+}++// SubscribeEventsDescription returns the manifest-owned description for the+// streaming capability. Event names are built from the shared constants so the+// API manifest, SSE producer, and external-agent adapters cannot drift apart.+func SubscribeEventsDescription() string {+ return "Subscribe to the SSE event stream for real-time notifications: " ++ string(EventKindFindingCreated) + " when a new finding is raised, " ++ string(EventKindApprovalPending) + " when a remediation request enters StatusPending and waits on operator decision, " ++ string(EventKindActionCompleted) + " when an action audit reaches a terminal state (Completed or Failed, including refused-before-dispatch failures with stable error-token prefixes; carries a verification block with the read-after-write probe outcome so agents close the certainty loop without polling /api/actions/{id}), stream-local " ++ string(EventKindHeartbeat) + " every 15s. Command fields are redacted for monitoring-read API tokens unless the token also has ai:execute. Long-lived connection; agents listen instead of polling."+}diff --git a/internal/agentcapabilities/events_test.go b/internal/agentcapabilities/events_test.gonew file mode 100644index 0000000000..b5155f4e89--- /dev/null+++ b/internal/agentcapabilities/events_test.go@@ -0,0 +1,47 @@+package agentcapabilities++import (+ "reflect"+ "strings"+ "testing"+)++func TestAgentActionableEventKindsReturnsDetachedKnownKinds(t *testing.T) {+ got := AgentActionableEventKinds()+ want := []string{+ string(EventKindFindingCreated),+ string(EventKindApprovalPending),+ string(EventKindActionCompleted),+ }+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("AgentActionableEventKinds() = %v, want %v", got, want)+ }++ got[0] = "mutated"+ second := AgentActionableEventKinds()+ if second[0] != string(EventKindFindingCreated) {+ t.Fatalf("AgentActionableEventKinds returned aliased slice: %v", second)+ }+}++func TestIsTransportEventKindPinsStreamPlumbing(t *testing.T) {+ for _, kind := range []EventKind{EventKindStreamConnected, EventKindHeartbeat} {+ if !IsTransportEventKind(string(kind)) {+ t.Fatalf("%s must be transport plumbing", kind)+ }+ }+ for _, kind := range AgentActionableEventKinds() {+ if IsTransportEventKind(kind) {+ t.Fatalf("%s must remain agent-actionable", kind)+ }+ }+}++func TestSubscribeEventsDescriptionUsesSharedEventKinds(t *testing.T) {+ description := SubscribeEventsDescription()+ for _, kind := range append(AgentActionableEventKinds(), string(EventKindHeartbeat)) {+ if !strings.Contains(description, kind) {+ t.Fatalf("subscribe_events description missing %q: %s", kind, description)+ }+ }+}diff --git a/internal/agentcapabilities/governance_prompt.go b/internal/agentcapabilities/governance_prompt.gonew file mode 100644index 0000000000..cc0cdb9c44--- /dev/null+++ b/internal/agentcapabilities/governance_prompt.go@@ -0,0 +1,437 @@+package agentcapabilities++import (+ "fmt"+ "strings"+)++// ToolGovernancePromptOptions controls how a surface projects a governed tool+// manifest into model-facing instructions.+type ToolGovernancePromptOptions struct {+ // OfferedToolNames is nil when every manifest tool should be described. A+ // non-nil empty slice explicitly means no tools are offered for this turn.+ OfferedToolNames []string++ // AdditionalToolGovernanceLines are pre-rendered surface-owned tool+ // governance lines for non-registry interaction tools. They are appended+ // after the shared manifest projection so native Assistant-only tools can+ // use the same prompt section without pretending to be manifest+ // capabilities.+ AdditionalToolGovernanceLines []string+}++// PulseIntelligenceOperatingInstructionOptions describes which affordances a+// Pulse Intelligence surface actually exposes. Shared operating instructions+// must not tell native Assistant models to use MCP-only resources or prompts,+// and external-agent adapters must not invent in-app affordances.+type PulseIntelligenceOperatingInstructionOptions struct {+ SurfaceID string+ SurfaceName string+ SupportsTools bool+ SupportsResources bool+ SupportsPrompts bool+ SupportsCapabilityMetadata bool+ SupportsInteractiveQuestions bool+ SurfaceContract SurfaceContract+}++// BuildToolGovernancePromptSection projects the shared tool-governance+// descriptors into the model-facing section used by Pulse Intelligence+// surfaces. Surface-specific pseudo-tools can be appended by the caller, but+// the generic mode/approval/summary wording stays here.+func BuildToolGovernancePromptSection(manifest []ToolGovernanceDescriptor, opts ToolGovernancePromptOptions) string {+ orderedOfferedNames, offeredFilter := normalizeOfferedToolNames(opts.OfferedToolNames)+ additionalLines := normalizeAdditionalToolGovernanceLines(opts.AdditionalToolGovernanceLines)+ additionalLineNames := additionalToolGovernanceLineNames(additionalLines)+ if offeredFilter != nil && len(offeredFilter) == 0 && len(additionalLines) == 0 {+ return strings.Join([]string{+ "## AVAILABLE TOOL GOVERNANCE",+ "No Pulse tools are offered for this turn. Answer directly from the user's message and safe conversation context.",+ "Do not claim to inspect infrastructure, run commands, or use Pulse data unless that evidence is already present in the conversation.",+ }, "\n")+ }++ var b strings.Builder+ b.WriteString("## AVAILABLE TOOL GOVERNANCE\n")+ b.WriteString("This manifest is generated from Pulse's governed tool registry. Use only tools that are actually offered by the provider for the current turn.\n")+ emitted := make(map[string]bool, len(manifest))+ for _, tool := range manifest {+ if offeredFilter != nil && !offeredFilter[tool.Name] {+ continue+ }+ if line := ToolGovernancePromptLine(tool); line != "" {+ b.WriteString("- ")+ b.WriteString(line)+ b.WriteByte('\n')+ emitted[tool.Name] = true+ }+ }++ if offeredFilter != nil {+ for _, name := range orderedOfferedNames {+ if emitted[name] || additionalLineNames[name] {+ continue+ }+ b.WriteString(fmt.Sprintf("- %s: mode=read; approval=%s (no approval required); Offered by Pulse for this turn.\n", name, ApprovalPolicyScopeOnly))+ emitted[name] = true+ }+ }+ for _, line := range additionalLines {+ if name := toolGovernanceLineName(line); name != "" && emitted[name] {+ continue+ }+ b.WriteString("- ")+ b.WriteString(line)+ b.WriteByte('\n')+ }+ return strings.TrimRight(b.String(), "\n")+}++// BuildAssistantToolGovernancePromptSection projects native Assistant tool+// governance from the shared manifest plus the Assistant-only interactive+// surface tools that are actually offered for the turn.+func BuildAssistantToolGovernancePromptSection(manifest []ToolGovernanceDescriptor, offeredToolNames []string) string {+ filteredOfferedNames, includeQuestionTool := AssistantGovernanceOfferedToolNames(offeredToolNames)+ promptOptions := ToolGovernancePromptOptions{OfferedToolNames: filteredOfferedNames}+ if includeQuestionTool {+ promptOptions.AdditionalToolGovernanceLines = []string{+ PulseQuestionToolGovernancePromptLine(),+ }+ }+ return BuildToolGovernancePromptSection(manifest, promptOptions)+}++// BuildPulseIntelligenceOperatingInstructions returns the shared model-facing+// operating posture for a fully manifest-backed Pulse Intelligence surface.+// Surface-specific callers should prefer BuildPulseAssistantOperatingInstructions+// or BuildPulseMCPOperatingInstructions so the advertised affordances match the+// current surface.+func BuildPulseIntelligenceOperatingInstructions() string {+ return BuildPulseIntelligenceOperatingInstructionsForSurface(PulseIntelligenceOperatingInstructionOptions{+ SurfaceName: "Pulse Intelligence",+ SupportsTools: true,+ SupportsResources: true,+ SupportsPrompts: true,+ SupportsCapabilityMetadata: true,+ })+}++// BuildPulseAssistantOperatingInstructions returns the native in-app Assistant+// operating posture. Assistant exposes provider tools and in-app context, but+// not MCP resources/prompts, so the source-of-truth instruction must stay+// surface-accurate.+func BuildPulseAssistantOperatingInstructions() string {+ manifest := CanonicalManifest()+ surface, _ := ResolveSurfaceAffordanceContract(manifest.SurfaceContract, SurfaceIDPulseAssistant, "")+ affordances := surface.Affordances+ return BuildPulseIntelligenceOperatingInstructionsForSurface(PulseIntelligenceOperatingInstructionOptions{+ SurfaceName: surface.SurfaceLabel,+ SurfaceID: surface.SurfaceID,+ SupportsTools: affordances.Tools,+ SupportsResources: affordances.Resources,+ SupportsPrompts: affordances.Prompts,+ SupportsCapabilityMetadata: affordances.CapabilityMetadata,+ SupportsInteractiveQuestions: affordances.InteractiveQuestions,+ SurfaceContract: manifest.SurfaceContract,+ })+}++// PulseMCPOperatingInstructionOptions describes the MCP affordances advertised+// during initialize for the current manifest.+type PulseMCPOperatingInstructionOptions struct {+ SurfaceID string+ SupportsTools bool+ SupportsResources bool+ SupportsPrompts bool+ SupportsCapabilityMetadata bool+ SurfaceContract SurfaceContract+}++// BuildPulseMCPOperatingInstructions returns the external-agent MCP operating+// posture with only the initialize-advertised affordances named.+func BuildPulseMCPOperatingInstructions(opts PulseMCPOperatingInstructionOptions) string {+ surfaceID := strings.TrimSpace(opts.SurfaceID)+ if surfaceID == "" {+ surfaceID = SurfaceIDPulseMCP+ }+ surface, _ := ResolveSurfaceAffordanceContract(opts.SurfaceContract, surfaceID, "")+ affordances := surface.Affordances+ return BuildPulseIntelligenceOperatingInstructionsForSurface(PulseIntelligenceOperatingInstructionOptions{+ SurfaceName: surface.SurfaceLabel,+ SurfaceID: surface.SurfaceID,+ SupportsTools: affordances.Tools && opts.SupportsTools,+ SupportsResources: affordances.Resources && opts.SupportsResources,+ SupportsPrompts: affordances.Prompts && opts.SupportsPrompts,+ SupportsCapabilityMetadata: affordances.CapabilityMetadata && opts.SupportsCapabilityMetadata,+ SurfaceContract: opts.SurfaceContract,+ })+}++// BuildPulseIntelligenceOperatingInstructionsForSurface returns the shared+// model-facing operating posture for Pulse Intelligence surfaces. Native+// Assistant can add richer in-app context around it, and MCP can advertise it+// during initialize, but the governed-action baseline stays one shared+// projection.+func BuildPulseIntelligenceOperatingInstructionsForSurface(opts PulseIntelligenceOperatingInstructionOptions) string {+ surfaceName := strings.TrimSpace(opts.SurfaceName)+ if surfaceName == "" {+ surfaceName = "this surface"+ }+ sourceOfTruth := pulseIntelligenceAffordanceList(opts)+ lines := []string{+ "## PULSE INTELLIGENCE OPERATING MODEL",+ "- Treat Pulse Intelligence as a governed infrastructure-operations surface, not an unrestricted shell.",+ fmt.Sprintf("- This surface is %s. Use %s as the source of truth for what this surface can do.", surfaceName, sourceOfTruth),+ }+ lines = append(lines, pulseIntelligenceSurfaceContractLines(opts)...)+ lines = append(lines, []string{+ "- Prefer read-only context first: inspect fleet or resource context before recommending deeper investigation or a state-changing action.",+ "- Run write-capable tools only when the operator explicitly asks for a state change, and follow the plan, approval, and execute flow exposed by the manifest.",+ "- Treat approval-required, policy-blocked, and unavailable-tool results as safety boundaries. Explain the boundary and choose a safer read or clarification path instead of bypassing it.",+ }...)+ return strings.Join(lines, "\n")+}++func pulseIntelligenceSurfaceContractLines(opts PulseIntelligenceOperatingInstructionOptions) []string {+ contract := opts.SurfaceContract+ coreLabel := strings.TrimSpace(contract.Core.Label)+ if coreLabel == "" {+ return nil+ }++ currentSurface, ok := FindOperatorSurfaceContract(contract, opts.SurfaceID, opts.SurfaceName)+ if !ok {+ return nil+ }+ currentLabel := strings.TrimSpace(currentSurface.Label)+ if currentLabel == "" {+ return nil+ }++ currentRole := operatorSurfaceContractRole(currentSurface)+ otherSurfacePhrases := make([]string, 0, len(contract.OperatorSurfaces))+ for _, surface := range contract.OperatorSurfaces {+ if OperatorSurfaceContractMatches(surface, currentSurface.ID, currentSurface.Label) {+ continue+ }+ label := strings.TrimSpace(surface.Label)+ if label == "" {+ continue+ }+ otherSurfacePhrases = append(otherSurfacePhrases, fmt.Sprintf("%s is %s", label, operatorSurfaceContractRole(surface)))+ }++ surfaceLine := fmt.Sprintf("- Surface contract: %s is %s over %s.", currentLabel, currentRole, coreLabel)+ if len(otherSurfacePhrases) > 0 {+ surfaceLine = strings.TrimSuffix(surfaceLine, ".") + "; " + oxfordJoin(otherSurfacePhrases) + " on the same core."+ }++ lines := []string{surfaceLine}+ if affordances := SurfaceAffordanceLabels(surfaceAffordancesFromOptions(opts)); len(affordances) > 0 {+ lines = append(lines, fmt.Sprintf("- Surface affordances: %s exposes %s.", currentLabel, oxfordJoin(affordances)))+ }+ if proactiveLabel := strings.TrimSpace(contract.ProactiveEngine.Label); proactiveLabel != "" {+ lines = append(lines, fmt.Sprintf("- %s is the primary built-in operator on %s; treat its findings, investigations, governed actions, and run context as governed Pulse evidence.", proactiveLabel, coreLabel))+ }+ return lines+}++func surfaceAffordancesFromOptions(opts PulseIntelligenceOperatingInstructionOptions) SurfaceAffordanceContract {+ return SurfaceAffordanceContract{+ Tools: opts.SupportsTools,+ Resources: opts.SupportsResources,+ Prompts: opts.SupportsPrompts,+ CapabilityMetadata: opts.SupportsCapabilityMetadata,+ InteractiveQuestions: opts.SupportsInteractiveQuestions,+ }+}++func operatorSurfaceContractRole(surface OperatorSurfaceContract) string {+ switch {+ case surface.Native && surface.ExternalAdapter:+ return "the native Pulse surface and external-agent adapter"+ case surface.Native:+ return "the native Pulse surface"+ case surface.ExternalAdapter:+ return "the external-agent adapter"+ default:+ return "an operator surface"+ }+}++func pulseIntelligenceAffordanceList(opts PulseIntelligenceOperatingInstructionOptions) string {+ items := []string{}+ if opts.SupportsTools {+ items = append(items, "offered tools")+ }+ if opts.SupportsResources {+ items = append(items, "resources")+ }+ if opts.SupportsPrompts {+ items = append(items, "prompts")+ }+ if opts.SupportsCapabilityMetadata {+ items = append(items, "capability metadata")+ }+ if opts.SupportsInteractiveQuestions {+ items = append(items, "interactive questions")+ }+ if len(items) == 0 {+ return "the explicit surface contract"+ }+ return oxfordJoin(items)+}++func oxfordJoin(items []string) string {+ switch len(items) {+ case 0:+ return ""+ case 1:+ return items[0]+ case 2:+ return items[0] + " and " + items[1]+ default:+ return strings.Join(items[:len(items)-1], ", ") + ", and " + items[len(items)-1]+ }+}++// ToolGovernancePromptLine returns the canonical one-line model-facing+// governance description for a single tool.+func ToolGovernancePromptLine(tool ToolGovernanceDescriptor) string {+ name := strings.TrimSpace(tool.Name)+ if name == "" {+ return ""+ }+ description := ToolGovernancePromptDescription(tool)+ if description == "" {+ return ""+ }+ return fmt.Sprintf("%s: %s", name, description)+}++// ToolGovernancePromptDescription returns the canonical model-facing+// mode/approval/summary fragment for one governed tool. Prompt sections, native+// provider tool declarations, and future agent surfaces use this helper instead+// of each carrying slightly different governance prose.+func ToolGovernancePromptDescription(tool ToolGovernanceDescriptor) string {+ mode := tool.ActionMode+ if mode == "" {+ mode = ActionModeRead+ }+ policy := strings.TrimSpace(string(tool.ApprovalPolicy))+ if policy == "" {+ policy = string(ApprovalPolicyScopeOnly)+ }+ approvalSummary := strings.TrimSpace(tool.ApprovalSummary)+ approval := policy+ if approvalSummary != "" {+ approval = fmt.Sprintf("%s (%s)", policy, approvalSummary)+ }+ summary := strings.TrimSpace(tool.Summary)+ if summary == "" {+ summary = firstToolGovernancePromptLine(tool.Description)+ }+ if summary != "" {+ return fmt.Sprintf("mode=%s; approval=%s; %s", mode, approval, summary)+ }+ return fmt.Sprintf("mode=%s; approval=%s", mode, approval)+}++// PulseQuestionToolName is the native Assistant-only structured clarification+// tool. It is not a manifest capability or MCP tool; it is governed prompt+// metadata for interactive in-app turns that can wait for user input.+const PulseQuestionToolName = "pulse_question"++// PulseQuestionToolGovernancePromptLine returns the shared governance line for+// the Assistant's interactive clarification tool.+func PulseQuestionToolGovernancePromptLine() string {+ return PulseQuestionToolName + ": mode=interactive; approval=user answer required; asks the user for missing information using a structured prompt in interactive chat only."+}++// AssistantGovernanceOfferedToolNames splits Assistant-native interaction+// tools out of the manifest-tool filter. This keeps pulse_question governed as+// an interactive surface tool without pretending it is a manifest capability.+func AssistantGovernanceOfferedToolNames(orderedOfferedNames []string) ([]string, bool) {+ if orderedOfferedNames == nil {+ return nil, true+ }+ filtered := make([]string, 0, len(orderedOfferedNames))+ includeQuestionTool := false+ seen := map[string]bool{}+ for _, name := range orderedOfferedNames {+ trimmed := strings.TrimSpace(name)+ if trimmed == "" || seen[trimmed] {+ continue+ }+ seen[trimmed] = true+ if trimmed == PulseQuestionToolName {+ includeQuestionTool = true+ continue+ }+ filtered = append(filtered, trimmed)+ }+ return filtered, includeQuestionTool+}++func normalizeOfferedToolNames(names []string) ([]string, map[string]bool) {+ if names == nil {+ return nil, nil+ }+ filter := make(map[string]bool, len(names))+ ordered := make([]string, 0, len(names))+ for _, name := range names {+ trimmed := strings.TrimSpace(name)+ if trimmed == "" || filter[trimmed] {+ continue+ }+ filter[trimmed] = true+ ordered = append(ordered, trimmed)+ }+ return ordered, filter+}++func normalizeAdditionalToolGovernanceLines(lines []string) []string {+ if len(lines) == 0 {+ return nil+ }+ normalized := make([]string, 0, len(lines))+ seen := map[string]bool{}+ for _, line := range lines {+ trimmed := strings.Join(strings.Fields(strings.TrimSpace(line)), " ")+ if trimmed == "" || seen[trimmed] {+ continue+ }+ seen[trimmed] = true+ normalized = append(normalized, trimmed)+ }+ return normalized+}++func additionalToolGovernanceLineNames(lines []string) map[string]bool {+ names := make(map[string]bool, len(lines))+ for _, line := range lines {+ if name := toolGovernanceLineName(line); name != "" {+ names[name] = true+ }+ }+ return names+}++func toolGovernanceLineName(line string) string {+ name, _, ok := strings.Cut(line, ":")+ if !ok {+ return ""+ }+ return strings.TrimSpace(name)+}++func firstToolGovernancePromptLine(description string) string {+ description = strings.TrimSpace(description)+ if description == "" {+ return ""+ }+ if idx := strings.Index(description, "\n"); idx >= 0 {+ description = strings.TrimSpace(description[:idx])+ }+ return strings.Join(strings.Fields(description), " ")+}diff --git a/internal/agentcapabilities/governance_prompt_test.go b/internal/agentcapabilities/governance_prompt_test.gonew file mode 100644index 0000000000..487fed12cf--- /dev/null+++ b/internal/agentcapabilities/governance_prompt_test.go@@ -0,0 +1,348 @@+package agentcapabilities++import (+ "strings"+ "testing"+)++func TestBuildToolGovernancePromptSectionProjectsSharedManifest(t *testing.T) {+ manifest := []ToolGovernanceDescriptor{+ {+ Name: "pulse_query",+ Description: "Query inventory.\nSecond line.",+ ActionMode: ActionModeRead,+ ApprovalPolicy: ApprovalPolicyScopeOnly,+ ApprovalSummary: "no approval required",+ Summary: "Read inventory.",+ },+ {+ Name: "pulse_control",+ Description: "Run controlled actions.",+ ActionMode: ActionModeWrite,+ ApprovalPolicy: ApprovalPolicyActionPlan,+ ApprovalSummary: "approval required in controlled mode",+ },+ }++ prompt := BuildToolGovernancePromptSection(manifest, ToolGovernancePromptOptions{})++ for _, expected := range []string{+ "## AVAILABLE TOOL GOVERNANCE",+ "Pulse's governed tool registry",+ "pulse_query: mode=read; approval=scope_only (no approval required); Read inventory.",+ "pulse_control: mode=write; approval=action_plan (approval required in controlled mode); Run controlled actions.",+ } {+ if !strings.Contains(prompt, expected) {+ t.Fatalf("expected prompt to include %q, got %q", expected, prompt)+ }+ }+}++func TestBuildToolGovernancePromptSectionHonorsOfferedTools(t *testing.T) {+ manifest := []ToolGovernanceDescriptor{+ {Name: "pulse_query", ActionMode: ActionModeRead, ApprovalPolicy: ApprovalPolicyScopeOnly},+ {Name: "pulse_control", ActionMode: ActionModeWrite, ApprovalPolicy: ApprovalPolicyActionPlan},+ }++ prompt := BuildToolGovernancePromptSection(manifest, ToolGovernancePromptOptions{+ OfferedToolNames: []string{" pulse_query ", "pulse_query", "provider_extra"},+ })++ if !strings.Contains(prompt, "pulse_query: mode=read; approval=scope_only") {+ t.Fatalf("expected offered manifest tool, got %q", prompt)+ }+ if strings.Contains(prompt, "pulse_control:") {+ t.Fatalf("did not expect non-offered manifest tool, got %q", prompt)+ }+ if !strings.Contains(prompt, "provider_extra: mode=read; approval=scope_only (no approval required); Offered by Pulse for this turn.") {+ t.Fatalf("expected fallback offered-tool line, got %q", prompt)+ }+ if strings.Count(prompt, "pulse_query:") != 1 {+ t.Fatalf("expected duplicate offered tool names to be collapsed, got %q", prompt)+ }+}++func TestBuildToolGovernancePromptSectionAppendsAdditionalSurfaceTools(t *testing.T) {+ prompt := BuildToolGovernancePromptSection([]ToolGovernanceDescriptor{+ {Name: "pulse_query", ActionMode: ActionModeRead, ApprovalPolicy: ApprovalPolicyScopeOnly},+ }, ToolGovernancePromptOptions{+ OfferedToolNames: []string{"pulse_query", PulseQuestionToolName},+ AdditionalToolGovernanceLines: []string{+ " " + PulseQuestionToolGovernancePromptLine() + " ",+ PulseQuestionToolGovernancePromptLine(),+ },+ })++ if !strings.Contains(prompt, "pulse_query: mode=read; approval=scope_only") {+ t.Fatalf("expected offered manifest tool, got %q", prompt)+ }+ if strings.Count(prompt, PulseQuestionToolName+":") != 1 {+ t.Fatalf("expected one shared question-tool governance line, got %q", prompt)+ }+ if !strings.Contains(prompt, "mode=interactive; approval=user answer required") {+ t.Fatalf("expected interactive question-tool governance, got %q", prompt)+ }+}++func TestBuildToolGovernancePromptSectionQuestionOnlyDoesNotUseNoToolsGuidance(t *testing.T) {+ prompt := BuildToolGovernancePromptSection(nil, ToolGovernancePromptOptions{+ OfferedToolNames: []string{},+ AdditionalToolGovernanceLines: []string{+ PulseQuestionToolGovernancePromptLine(),+ },+ })++ if strings.Contains(prompt, "No Pulse tools are offered for this turn") {+ t.Fatalf("question-only prompt must not use no-tools guidance, got %q", prompt)+ }+ if !strings.Contains(prompt, PulseQuestionToolGovernancePromptLine()) {+ t.Fatalf("expected shared question-tool governance line, got %q", prompt)+ }+}++func TestBuildAssistantToolGovernancePromptSectionProjectsQuestionAsInteractiveSurfaceTool(t *testing.T) {+ prompt := BuildAssistantToolGovernancePromptSection([]ToolGovernanceDescriptor{+ {Name: "pulse_query", ActionMode: ActionModeRead, ApprovalPolicy: ApprovalPolicyScopeOnly},+ }, []string{" pulse_query ", PulseQuestionToolName, PulseQuestionToolName})++ if !strings.Contains(prompt, "pulse_query: mode=read; approval=scope_only") {+ t.Fatalf("expected offered manifest tool, got %q", prompt)+ }+ if strings.Count(prompt, PulseQuestionToolName+":") != 1 {+ t.Fatalf("expected one Assistant question governance line, got %q", prompt)+ }+ if !strings.Contains(prompt, PulseQuestionToolGovernancePromptLine()) {+ t.Fatalf("expected Assistant question tool to use shared interactive governance, got %q", prompt)+ }+ if strings.Contains(prompt, PulseQuestionToolName+": mode=read") {+ t.Fatalf("question tool must not fall back to generic read governance, got %q", prompt)+ }+}++func TestAssistantGovernanceOfferedToolNamesSplitsNativeSurfaceTools(t *testing.T) {+ filtered, includeQuestion := AssistantGovernanceOfferedToolNames([]string{+ " pulse_query ",+ PulseQuestionToolName,+ "pulse_query",+ "",+ })+ if !includeQuestion {+ t.Fatal("expected Assistant question tool to be detected")+ }+ if len(filtered) != 1 || filtered[0] != "pulse_query" {+ t.Fatalf("filtered manifest names = %#v, want [pulse_query]", filtered)+ }++ allNames, includeQuestion := AssistantGovernanceOfferedToolNames(nil)+ if allNames != nil || !includeQuestion {+ t.Fatalf("nil offered names must preserve all-manifest plus interactive-question semantics, got %#v include=%v", allNames, includeQuestion)+ }++ none, includeQuestion := AssistantGovernanceOfferedToolNames([]string{})+ if none == nil || len(none) != 0 || includeQuestion {+ t.Fatalf("empty offered names must mean no tools, got %#v include=%v", none, includeQuestion)+ }+}++func TestBuildToolGovernancePromptSectionNoOfferedTools(t *testing.T) {+ prompt := BuildToolGovernancePromptSection([]ToolGovernanceDescriptor{+ {Name: "pulse_query", ActionMode: ActionModeRead, ApprovalPolicy: ApprovalPolicyScopeOnly},+ }, ToolGovernancePromptOptions{OfferedToolNames: []string{}})++ if !strings.Contains(prompt, "No Pulse tools are offered for this turn") {+ t.Fatalf("expected no-tools guidance, got %q", prompt)+ }+ if strings.Contains(prompt, "pulse_query:") {+ t.Fatalf("expected no manifest tools when offered list is empty, got %q", prompt)+ }+}++func TestToolGovernancePromptLineUsesSharedDefaults(t *testing.T) {+ got := ToolGovernancePromptLine(ToolGovernanceDescriptor{+ Name: " pulse_read ",+ Description: "Read data.\nLonger details.",+ })++ want := "pulse_read: mode=read; approval=scope_only; Read data."+ if got != want {+ t.Fatalf("ToolGovernancePromptLine = %q, want %q", got, want)+ }+}++func TestToolGovernancePromptDescriptionOmitsToolNameForProviderDeclarations(t *testing.T) {+ got := ToolGovernancePromptDescription(ToolGovernanceDescriptor{+ Name: "pulse_control",+ Description: "Run controlled actions.",+ ActionMode: ActionModeWrite,+ ApprovalPolicy: ApprovalPolicyActionPlan,+ ApprovalSummary: "approval required in controlled mode",+ })++ want := "mode=write; approval=action_plan (approval required in controlled mode); Run controlled actions."+ if got != want {+ t.Fatalf("ToolGovernancePromptDescription = %q, want %q", got, want)+ }+ if strings.Contains(got, "pulse_control:") {+ t.Fatalf("provider-facing governance description must not include tool name prefix: %q", got)+ }+}++func TestPulseQuestionToolGovernancePromptLineNamesInteractiveBoundary(t *testing.T) {+ line := PulseQuestionToolGovernancePromptLine()++ for _, expected := range []string{+ PulseQuestionToolName,+ "mode=interactive",+ "approval=user answer required",+ "interactive chat only",+ } {+ if !strings.Contains(line, expected) {+ t.Fatalf("expected question-tool governance line to include %q, got %q", expected, line)+ }+ }+}++func TestBuildPulseIntelligenceOperatingInstructionsNamesGovernedActionPosture(t *testing.T) {+ instructions := BuildPulseIntelligenceOperatingInstructions()++ for _, expected := range []string{+ "## PULSE INTELLIGENCE OPERATING MODEL",+ "governed infrastructure-operations surface",+ "offered tools, resources, prompts, and capability metadata",+ "Prefer read-only context first",+ "plan, approval, and execute flow",+ "approval-required, policy-blocked, and unavailable-tool results",+ } {+ if !strings.Contains(instructions, expected) {+ t.Fatalf("expected shared operating instructions to include %q, got %q", expected, instructions)+ }+ }+}++func TestBuildPulseAssistantOperatingInstructionsNamesOnlyAssistantAffordances(t *testing.T) {+ instructions := BuildPulseAssistantOperatingInstructions()++ for _, expected := range []string{+ "This surface is Pulse Assistant.",+ "Use offered tools and interactive questions as the source of truth",+ "Pulse Assistant is the native Pulse surface over Pulse Intelligence Core",+ "Pulse MCP is the external-agent adapter on the same core",+ "Surface affordances: Pulse Assistant exposes tools and interactive questions.",+ "Pulse Patrol is the primary built-in operator on Pulse Intelligence Core",+ "governed infrastructure-operations surface",+ "plan, approval, and execute flow",+ } {+ if !strings.Contains(instructions, expected) {+ t.Fatalf("expected Assistant operating instructions to include %q, got %q", expected, instructions)+ }+ }+ for _, forbidden := range []string{+ "resources, prompts",+ "capability metadata",+ } {+ if strings.Contains(instructions, forbidden) {+ t.Fatalf("Assistant operating instructions must not advertise MCP-only affordance %q: %q", forbidden, instructions)+ }+ }+}++func TestBuildPulseMCPOperatingInstructionsReflectsAdvertisedAffordances(t *testing.T) {+ minimal := BuildPulseMCPOperatingInstructions(PulseMCPOperatingInstructionOptions{+ SupportsTools: true,+ })+ if !strings.Contains(minimal, "This surface is Pulse MCP.") ||+ !strings.Contains(minimal, "Use offered tools as the source of truth") {+ t.Fatalf("expected minimal MCP instructions to name tool-only MCP affordance, got %q", minimal)+ }+ if strings.Contains(minimal, "resources") ||+ strings.Contains(minimal, "prompts") ||+ strings.Contains(minimal, "capability metadata") {+ t.Fatalf("minimal MCP instructions must not advertise unsupported affordances: %q", minimal)+ }++ manifestBacked := BuildPulseMCPOperatingInstructions(PulseMCPOperatingInstructionOptions{+ SupportsTools: true,+ SupportsResources: true,+ SupportsPrompts: true,+ SupportsCapabilityMetadata: true,+ SurfaceContract: CanonicalManifest().SurfaceContract,+ })+ if !strings.Contains(manifestBacked, "Use offered tools, resources, prompts, and capability metadata as the source of truth") {+ t.Fatalf("manifest-backed MCP instructions must include advertised resources/prompts/metadata, got %q", manifestBacked)+ }+ for _, expected := range []string{+ "Pulse MCP is the external-agent adapter over Pulse Intelligence Core",+ "Pulse Assistant is the native Pulse surface on the same core",+ "Surface affordances: Pulse MCP exposes tools, resources, prompts, and capability metadata.",+ "Pulse Patrol is the primary built-in operator on Pulse Intelligence Core",+ } {+ if !strings.Contains(manifestBacked, expected) {+ t.Fatalf("manifest-backed MCP instructions must include surface contract %q, got %q", expected, manifestBacked)+ }+ }++ noTools := BuildPulseMCPOperatingInstructions(PulseMCPOperatingInstructionOptions{+ SupportsResources: true,+ SurfaceContract: CanonicalManifest().SurfaceContract,+ })+ if strings.Contains(noTools, "offered tools") {+ t.Fatalf("MCP instructions must not advertise tools when initialize omitted the tools capability: %q", noTools)+ }+}++func TestBuildPulseMCPOperatingInstructionsUsesRequestedSurfaceContract(t *testing.T) {+ contract := SurfaceContract{+ Core: CanonicalManifest().SurfaceContract.Core,+ ProactiveEngine: CanonicalManifest().SurfaceContract.ProactiveEngine,+ OperatorSurfaces: []OperatorSurfaceContract{+ {+ ID: SurfaceIDPulseMCP,+ Label: "Pulse MCP",+ ExternalAdapter: true,+ Affordances: SurfaceAffordanceContract{+ Tools: true,+ Resources: true,+ Prompts: true,+ CapabilityMetadata: true,+ },+ },+ {+ ID: "custom_external_agent",+ Label: "Custom external agent",+ ExternalAdapter: true,+ Affordances: SurfaceAffordanceContract{+ Tools: true,+ Resources: true,+ },+ },+ },+ }++ instructions := BuildPulseMCPOperatingInstructions(PulseMCPOperatingInstructionOptions{+ SurfaceID: "custom_external_agent",+ SupportsTools: true,+ SupportsResources: true,+ SupportsPrompts: true,+ SupportsCapabilityMetadata: true,+ SurfaceContract: contract,+ })++ for _, expected := range []string{+ "This surface is Custom external agent.",+ "Use offered tools and resources as the source of truth",+ "Surface affordances: Custom external agent exposes tools and resources.",+ } {+ if !strings.Contains(instructions, expected) {+ t.Fatalf("expected custom-surface instructions to include %q, got %q", expected, instructions)+ }+ }+ for _, forbidden := range []string{+ "Use offered tools, resources, prompts",+ "Custom external agent exposes tools, resources, prompts",+ "capability metadata",+ } {+ if strings.Contains(instructions, forbidden) {+ t.Fatalf("custom-surface instructions must not fall back to Pulse MCP affordance %q: %q", forbidden, instructions)+ }+ }+}diff --git a/internal/agentcapabilities/http.go b/internal/agentcapabilities/http.gonew file mode 100644index 0000000000..7458d4d4a7--- /dev/null+++ b/internal/agentcapabilities/http.go@@ -0,0 +1,226 @@+package agentcapabilities++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "strings"+)++const (+ AgentCapabilitiesPath = "/api/agent/capabilities"+ AgentEventsPath = "/api/agent/events"+ AgentWorkflowPromptActivityPath = "/api/agent/workflow-prompt-activity"+ AgentAPITokenHeader = "X-API-Token"+ AgentSurfaceHeader = "X-Pulse-Agent-Surface"+ AgentSurfacePulseMCP = "pulse_mcp"+)++// HTTPDoer is the shared minimum interface for agent-surface HTTP clients.+type HTTPDoer interface {+ Do(*http.Request) (*http.Response, error)+}++// HTTPCallResponse is the raw response from invoking a manifest capability.+type HTTPCallResponse struct {+ Method string+ Path string+ StatusCode int+ Header http.Header+ Body []byte+}++// OK reports whether the upstream Pulse response was a 2xx.+func (r HTTPCallResponse) OK() bool {+ return r.StatusCode >= 200 && r.StatusCode < 300+}++// StableErrorEnvelope decodes the response body as the shared agent error+// envelope when the upstream used that shape.+func (r HTTPCallResponse) StableErrorEnvelope() (ErrorEnvelope, bool) {+ return DecodeErrorEnvelope(r.Body)+}++// FailureError returns the stable branchable error when a response is non-2xx.+func (r HTTPCallResponse) FailureError() error {+ if r.OK() {+ return nil+ }+ method := strings.TrimSpace(r.Method)+ if method == "" {+ method = "HTTP"+ }+ path := strings.TrimSpace(r.Path)+ if path == "" {+ path = "agent capability"+ }+ if env, ok := r.StableErrorEnvelope(); ok {+ return fmt.Errorf("%s %s: %d %s (%s)", method, path, r.StatusCode, env.Error, env.Message)+ }+ body := strings.TrimSpace(string(r.Body))+ if body == "" {+ return fmt.Errorf("%s %s: %d", method, path, r.StatusCode)+ }+ return fmt.Errorf("%s %s: %d %s", method, path, r.StatusCode, body)+}++// AgentURL joins a Pulse base URL and an agent-surface path.+func AgentURL(baseURL, path string) (string, error) {+ baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")+ if baseURL == "" {+ return "", fmt.Errorf("base URL is required")+ }+ path = strings.TrimSpace(path)+ if path == "" {+ return "", fmt.Errorf("agent path is required")+ }+ if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {+ return "", fmt.Errorf("agent path must be relative: %s", path)+ }+ if !strings.HasPrefix(path, "/") {+ path = "/" + path+ }+ fullURL := baseURL + path+ parsed, err := url.Parse(fullURL)+ if err != nil {+ return "", fmt.Errorf("parse agent URL %q: %w", fullURL, err)+ }+ if parsed.Scheme == "" || parsed.Host == "" {+ return "", fmt.Errorf("agent base URL must include scheme and host: %s", baseURL)+ }+ return parsed.String(), nil+}++// NewAgentHTTPRequest builds an agent-surface HTTP request with the shared API+// token header and JSON content-type convention.+func NewAgentHTTPRequest(ctx context.Context, method, baseURL, path, token string, body io.Reader) (*http.Request, error) {+ fullURL, err := AgentURL(baseURL, path)+ if err != nil {+ return nil, err+ }+ req, err := http.NewRequestWithContext(ctx, method, fullURL, body)+ if err != nil {+ return nil, err+ }+ if token = strings.TrimSpace(token); token != "" {+ req.Header.Set(AgentAPITokenHeader, token)+ }+ if body != nil {+ req.Header.Set("Content-Type", "application/json")+ }+ return req, nil+}++// FetchManifest pulls the public agent capabilities manifest from a Pulse+// instance using the shared discovery path.+func FetchManifest(ctx context.Context, client HTTPDoer, baseURL string) (*Manifest, error) {+ req, err := NewAgentHTTPRequest(ctx, http.MethodGet, baseURL, AgentCapabilitiesPath, "", nil)+ if err != nil {+ return nil, err+ }+ resp, err := httpClient(client).Do(req)+ if err != nil {+ return nil, fmt.Errorf("GET %s: %w", AgentCapabilitiesPath, err)+ }+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("GET %s: status %d", AgentCapabilitiesPath, resp.StatusCode)+ }+ var manifest Manifest+ if err := json.NewDecoder(resp.Body).Decode(&manifest); err != nil {+ return nil, fmt.Errorf("decode manifest: %w", err)+ }+ return &manifest, nil+}++// BuildCapabilityHTTPRequest projects a manifest capability invocation into an+// authenticated Pulse HTTP request.+func BuildCapabilityHTTPRequest(ctx context.Context, baseURL, token string, cap Capability, args map[string]any) (*http.Request, ProjectedCall, error) {+ projected, err := ProjectCapabilityCall(cap, args)+ if err != nil {+ return nil, ProjectedCall{}, err+ }+ var body io.Reader+ if projected.HasBody {+ body = bytes.NewReader(projected.Body)+ }+ req, err := NewAgentHTTPRequest(ctx, cap.Method, baseURL, projected.Path, token, body)+ if err != nil {+ return nil, ProjectedCall{}, err+ }+ return req, projected, nil+}++// CallCapabilityHTTP executes a manifest capability through the shared+// discovery/projection/auth header path. Callers own the surface-specific+// wrapping of the raw response.+func CallCapabilityHTTP(ctx context.Context, client HTTPDoer, baseURL, token string, cap Capability, args map[string]any) (HTTPCallResponse, error) {+ req, projected, err := BuildCapabilityHTTPRequest(ctx, baseURL, token, cap, args)+ if err != nil {+ return HTTPCallResponse{}, err+ }+ resp, err := httpClient(client).Do(req)+ if err != nil {+ return HTTPCallResponse{}, fmt.Errorf("%s %s: %w", cap.Method, projected.Path, err)+ }+ defer resp.Body.Close()+ body, err := io.ReadAll(resp.Body)+ if err != nil {+ return HTTPCallResponse{}, fmt.Errorf("read %s %s response: %w", cap.Method, projected.Path, err)+ }+ return HTTPCallResponse{+ Method: cap.Method,+ Path: projected.Path,+ StatusCode: resp.StatusCode,+ Header: resp.Header.Clone(),+ Body: body,+ }, nil+}++// CallCapabilityHTTPByName resolves and executes a named manifest capability+// through the shared discovery/projection/auth header path.+func CallCapabilityHTTPByName(ctx context.Context, client HTTPDoer, baseURL, token string, capabilities []Capability, name string, args map[string]any) (HTTPCallResponse, error) {+ cap, err := ResolveCapability(capabilities, name)+ if err != nil {+ return HTTPCallResponse{}, err+ }+ return CallCapabilityHTTP(ctx, client, baseURL, token, cap, args)+}++// CallRequestResponseCapabilityHTTPByName resolves and executes a named+// manifest capability only when it is eligible for request/response external+// tool adapters. Streaming capabilities are consumed through the SSE helpers.+func CallRequestResponseCapabilityHTTPByName(ctx context.Context, client HTTPDoer, baseURL, token string, capabilities []Capability, name string, args map[string]any) (HTTPCallResponse, error) {+ cap, err := ResolveRequestResponseCapability(capabilities, name)+ if err != nil {+ return HTTPCallResponse{}, err+ }+ return CallCapabilityHTTP(ctx, client, baseURL, token, cap, args)+}++// CallRequestResponseCapabilityHTTPBodyByName resolves and executes a named+// request/response manifest capability, requiring a 2xx upstream response+// before returning the raw body. Reference clients and probes use this when+// they want normal HTTP failure handling through the shared stable error+// envelope instead of MCP's isError result projection.+func CallRequestResponseCapabilityHTTPBodyByName(ctx context.Context, client HTTPDoer, baseURL, token string, capabilities []Capability, name string, args map[string]any) ([]byte, error) {+ resp, err := CallRequestResponseCapabilityHTTPByName(ctx, client, baseURL, token, capabilities, name, args)+ if err != nil {+ return nil, err+ }+ if err := resp.FailureError(); err != nil {+ return nil, err+ }+ return append([]byte(nil), resp.Body...), nil+}++func httpClient(client HTTPDoer) HTTPDoer {+ if client != nil {+ return client+ }+ return http.DefaultClient+}diff --git a/internal/agentcapabilities/http_test.go b/internal/agentcapabilities/http_test.gonew file mode 100644index 0000000000..25f6f0c405--- /dev/null+++ b/internal/agentcapabilities/http_test.go@@ -0,0 +1,311 @@+package agentcapabilities++import (+ "context"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func TestFetchManifestUsesSharedDiscoveryPath(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != AgentCapabilitiesPath {+ t.Fatalf("path = %q, want %q", r.URL.Path, AgentCapabilitiesPath)+ }+ if token := r.Header.Get(AgentAPITokenHeader); token != "" {+ t.Fatalf("manifest discovery must not send API token, got %q", token)+ }+ _ = json.NewEncoder(w).Encode(Manifest{+ Version: "v1",+ Capabilities: []Capability{{+ Name: "get_fleet_context",+ Method: http.MethodGet,+ Path: "/api/agent/fleet-context",+ }},+ })+ }))+ defer server.Close()++ manifest, err := FetchManifest(context.Background(), server.Client(), server.URL)+ if err != nil {+ t.Fatalf("FetchManifest: %v", err)+ }+ if manifest.Version != "v1" || len(manifest.Capabilities) != 1 {+ t.Fatalf("manifest = %+v", manifest)+ }+}++func TestBuildCapabilityHTTPRequestProjectsPathBodyAndAuth(t *testing.T) {+ cap := Capability{+ Name: SetOperatorStateCapabilityName,+ Method: http.MethodPost,+ Path: "/api/agent/operator-state/{resourceId}",+ }+ req, projected, err := BuildCapabilityHTTPRequest(context.Background(), "http://pulse.local/", "test-token", cap, map[string]any{+ ResourceIDArgumentName: "vm:101/console",+ "note": "maintenance",+ })+ if err != nil {+ t.Fatalf("BuildCapabilityHTTPRequest: %v", err)+ }++ if req.Method != http.MethodPost {+ t.Fatalf("method = %q, want POST", req.Method)+ }+ if req.URL.String() != "http://pulse.local/api/agent/operator-state/vm%3A101%2Fconsole" {+ t.Fatalf("url = %q", req.URL.String())+ }+ if got := req.Header.Get(AgentAPITokenHeader); got != "test-token" {+ t.Fatalf("%s = %q, want test-token", AgentAPITokenHeader, got)+ }+ if got := req.Header.Get("Content-Type"); got != "application/json" {+ t.Fatalf("Content-Type = %q, want application/json", got)+ }+ if projected.Path != "/api/agent/operator-state/vm%3A101%2Fconsole" || !projected.HasBody {+ t.Fatalf("projected = %+v", projected)+ }+ body, err := io.ReadAll(req.Body)+ if err != nil {+ t.Fatalf("read body: %v", err)+ }+ if strings.Contains(string(body), "resourceId") {+ t.Fatalf("body must not duplicate path args, got %s", body)+ }+ if !strings.Contains(string(body), `"note":"maintenance"`) {+ t.Fatalf("body = %s", body)+ }+}++func TestCallCapabilityHTTPExecutesManifestProjection(t *testing.T) {+ var got struct {+ Method string+ Path string+ Token string+ ContentType string+ Body string+ }+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ got.Method = r.Method+ got.Path = r.URL.EscapedPath()+ got.Token = r.Header.Get(AgentAPITokenHeader)+ got.ContentType = r.Header.Get("Content-Type")+ body, _ := io.ReadAll(r.Body)+ got.Body = string(body)+ w.WriteHeader(http.StatusAccepted)+ _, _ = w.Write([]byte(`{"ok":true}`))+ }))+ defer server.Close()++ resp, err := CallCapabilityHTTP(context.Background(), server.Client(), server.URL, "shared-token", Capability{+ Name: PlanActionCapabilityName,+ Method: http.MethodPost,+ Path: "/api/actions/{actionId}/plan",+ }, map[string]any{+ ActionIDArgumentName: "act:123",+ "body": map[string]any{+ "reason": "operator requested",+ },+ })+ if err != nil {+ t.Fatalf("CallCapabilityHTTP: %v", err)+ }+ if !resp.OK() || resp.StatusCode != http.StatusAccepted || string(resp.Body) != `{"ok":true}` {+ t.Fatalf("response = %+v body=%s", resp, resp.Body)+ }+ if got.Method != http.MethodPost || got.Path != "/api/actions/act%3A123/plan" {+ t.Fatalf("request method/path = %s %s", got.Method, got.Path)+ }+ if got.Token != "shared-token" {+ t.Fatalf("token = %q", got.Token)+ }+ if got.ContentType != "application/json" {+ t.Fatalf("content type = %q", got.ContentType)+ }+ if got.Body != `{"reason":"operator requested"}` {+ t.Fatalf("body = %s", got.Body)+ }+}++func TestCallCapabilityHTTPByNameResolvesAndExecutesManifestProjection(t *testing.T) {+ var got struct {+ Method string+ Path string+ Token string+ Body string+ }+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ got.Method = r.Method+ got.Path = r.URL.EscapedPath()+ got.Token = r.Header.Get(AgentAPITokenHeader)+ body, _ := io.ReadAll(r.Body)+ got.Body = string(body)+ w.WriteHeader(http.StatusAccepted)+ _, _ = w.Write([]byte(`{"ok":true}`))+ }))+ defer server.Close()++ resp, err := CallCapabilityHTTPByName(context.Background(), server.Client(), server.URL, "shared-token", []Capability{{+ Name: ResourceContextCapabilityName,+ Method: http.MethodPost,+ Path: "/api/agent/resource-context/{resourceId}/note",+ }}, ResourceContextCapabilityName, map[string]any{+ "resourceId": "vm:101/console",+ "note": "focus first",+ })+ if err != nil {+ t.Fatalf("CallCapabilityHTTPByName: %v", err)+ }+ if !resp.OK() || resp.StatusCode != http.StatusAccepted || string(resp.Body) != `{"ok":true}` {+ t.Fatalf("response = %+v body=%s", resp, resp.Body)+ }+ if got.Method != http.MethodPost || got.Path != "/api/agent/resource-context/vm%3A101%2Fconsole/note" {+ t.Fatalf("request method/path = %s %s", got.Method, got.Path)+ }+ if got.Token != "shared-token" {+ t.Fatalf("token = %q", got.Token)+ }+ if strings.Contains(got.Body, "resourceId") || got.Body != `{"note":"focus first"}` {+ t.Fatalf("body = %s", got.Body)+ }+}++func TestCallCapabilityHTTPByNameReturnsTypedLookupError(t *testing.T) {+ _, err := CallCapabilityHTTPByName(context.Background(), nil, "http://pulse.local", "token", []Capability{{+ Name: FleetContextCapabilityName,+ Method: http.MethodGet,+ Path: "/api/agent/fleet-context",+ }}, "missing_capability", nil)+ if err == nil {+ t.Fatal("expected missing capability error")+ }+ var lookupErr CapabilityLookupError+ if !errors.As(err, &lookupErr) {+ t.Fatalf("error type = %T %v, want CapabilityLookupError", err, err)+ }+ if lookupErr.Name != "missing_capability" || err.Error() != "unknown capability: missing_capability" {+ t.Fatalf("lookup error = %#v %q", lookupErr, err.Error())+ }+}++func TestCallRequestResponseCapabilityHTTPByNameRejectsStreamingCapabilities(t *testing.T) {+ called := false+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ called = true+ t.Fatalf("streaming capability must not be invoked through request/response HTTP helper")+ }))+ defer server.Close()++ _, err := CallRequestResponseCapabilityHTTPByName(context.Background(), server.Client(), server.URL, "shared-token", []Capability{{+ Name: EventSubscriptionCapabilityName,+ Method: http.MethodGet,+ Path: AgentEventsPath,+ }}, EventSubscriptionCapabilityName, nil)+ if err == nil {+ t.Fatal("expected streaming capability to be rejected")+ }+ var lookupErr CapabilityLookupError+ if !errors.As(err, &lookupErr) || lookupErr.Name != EventSubscriptionCapabilityName {+ t.Fatalf("error = %T %[1]v, want CapabilityLookupError for %s", err, EventSubscriptionCapabilityName)+ }+ if called {+ t.Fatal("streaming capability reached upstream HTTP server")+ }+}++func TestCallRequestResponseCapabilityHTTPBodyByNameReturnsSuccessfulBody(t *testing.T) {+ var got struct {+ Method string+ Path string+ Token string+ Body string+ }+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ got.Method = r.Method+ got.Path = r.URL.EscapedPath()+ got.Token = r.Header.Get(AgentAPITokenHeader)+ body, _ := io.ReadAll(r.Body)+ got.Body = string(body)+ w.WriteHeader(http.StatusAccepted)+ _, _ = w.Write([]byte(`{"resource":"ok"}`))+ }))+ defer server.Close()++ body, err := CallRequestResponseCapabilityHTTPBodyByName(+ context.Background(),+ server.Client(),+ server.URL,+ "body-token",+ []Capability{{+ Name: ResourceContextCapabilityName,+ Method: http.MethodPost,+ Path: "/api/agent/resource-context/{resourceId}/focus",+ }},+ ResourceContextCapabilityName,+ map[string]any{+ "resourceId": "vm:101/console",+ "reason": "critical finding",+ },+ )+ if err != nil {+ t.Fatalf("CallRequestResponseCapabilityHTTPBodyByName: %v", err)+ }+ if string(body) != `{"resource":"ok"}` {+ t.Fatalf("body = %s", body)+ }+ if got.Method != http.MethodPost || got.Path != "/api/agent/resource-context/vm%3A101%2Fconsole/focus" {+ t.Fatalf("request method/path = %s %s", got.Method, got.Path)+ }+ if got.Token != "body-token" {+ t.Fatalf("token = %q", got.Token)+ }+ if strings.Contains(got.Body, "resourceId") || got.Body != `{"reason":"critical finding"}` {+ t.Fatalf("body = %s", got.Body)+ }+}++func TestCallRequestResponseCapabilityHTTPBodyByNameReturnsStableFailure(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusForbidden)+ _, _ = w.Write([]byte(`{"error":"scope_required","message":"monitoring:read is required"}`))+ }))+ defer server.Close()++ _, err := CallRequestResponseCapabilityHTTPBodyByName(+ context.Background(),+ server.Client(),+ server.URL,+ "body-token",+ []Capability{{+ Name: FleetContextCapabilityName,+ Method: http.MethodGet,+ Path: "/api/agent/fleet-context",+ }},+ FleetContextCapabilityName,+ nil,+ )+ if err == nil {+ t.Fatal("expected stable non-2xx error")+ }+ if got := err.Error(); got != "GET /api/agent/fleet-context: 403 scope_required (monitoring:read is required)" {+ t.Fatalf("error = %q", got)+ }+}++func TestHTTPCallResponseFailureErrorUsesStableEnvelope(t *testing.T) {+ resp := HTTPCallResponse{+ Method: http.MethodGet,+ Path: "/api/agent/resource-context/vm%3A101",+ StatusCode: http.StatusForbidden,+ Body: []byte(`{"error":"scope_required","message":"monitoring:read is required"}`),+ }+ if resp.OK() {+ t.Fatal("forbidden response must not be OK")+ }+ if got := resp.FailureError().Error(); got != "GET /api/agent/resource-context/vm%3A101: 403 scope_required (monitoring:read is required)" {+ t.Fatalf("failure error = %q", got)+ }+}diff --git a/internal/agentcapabilities/manifest.go b/internal/agentcapabilities/manifest.gonew file mode 100644index 0000000000..2bd90e492f--- /dev/null+++ b/internal/agentcapabilities/manifest.go@@ -0,0 +1,1070 @@+package agentcapabilities++import (+ "encoding/json"+ "net/http"++ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"+)++func agentObjectInputSchemaMap(required []string, properties map[string]any) map[string]any {+ return StrictObjectInputSchemaMap(required, properties)+}++func agentInputSchema(schema map[string]any) json.RawMessage {+ return RawInputSchema(schema)+}++func agentObjectInputSchema(required []string, properties map[string]any) json.RawMessage {+ return StrictObjectInputSchema(required, properties)+}++func agentObjectOutputSchema(required []string, properties map[string]any) json.RawMessage {+ return ObjectInputSchema(required, properties, true)+}++func fleetContextOutputSchema() json.RawMessage {+ return agentObjectOutputSchema([]string{"resources", "generatedAt"}, map[string]any{+ "resources": objectArrayOption("Per-resource triage summaries visible to the authenticated agent."),+ "generatedAt": dateTimeOption("Server timestamp for this fleet context snapshot."),+ })+}++func operationsLoopStatusOutputSchema() json.RawMessage {+ return agentObjectOutputSchema([]string{"nextAction", "progressLabel", "steps", "patrolEvidenceCount", "patrolIssueEvidenceCount", "activeFindingCount", "pendingApprovalCount", "governedActionCount", "approvedDecisionCount", "rejectedDecisionCount", "verifiedOutcomeCount", "operationsLoopStarterCount", "assistantOperationsLoopStarterCount", "patrolOperationsLoopStarterCount", "patrolControlOperationsLoopStarterCount", "patrolControlCompletedOperationsLoopCount", "patrolControlResolvedOperationsLoopCount", "patrolControlValueState", "patrolAutonomyOperationsLoopStarterCount", "patrolAutonomyCompletedOperationsLoopCount", "patrolAutonomyResolvedOperationsLoopCount", "patrolAutonomyValueState", "proActivationOperationsLoopStarterCount", "proActivationCompletedOperationsLoopCount", "proActivationResolvedOperationsLoopCount", "proActivationValueProofState", "mcpOperationsLoopStarterCount", "externalAgentReady", "windowStart", "generatedAt"}, map[string]any{+ "nextAction": stringEnumOption([]string{"run_patrol", "review_findings", "open_assistant", "review_approvals", "open_mcp", "complete"}, "Next recommended Patrol work action an agent or UI should take."),+ "progressLabel": stringOption("Operator-readable status summary for the current Patrol work stage."),+ "steps": objectArrayOption("Four-stage Patrol, Assistant, governance, and verification status rollup. Step counts are content-free stage evidence: Assistant counts contextual collaboration, governance counts pending approvals until an approved/rejected decision exists, and verification counts verified outcomes or terminal rejected decisions. External-agent readiness is exposed separately through externalAgentReady."),+ "patrolEvidenceCount": integerOption("Count-only evidence that Pulse Intelligence has observed Patrol work activity in the current window."),+ "patrolIssueEvidenceCount": integerOption("Count-only evidence that Patrol has an actionable issue, approval, governed decision, or verified outcome."),+ "activeFindingCount": integerOption("Total active Patrol findings across the visible fleet."),+ "pendingApprovalCount": integerOption("Total pending governed-action approvals across the visible fleet."),+ "governedActionCount": integerOption("Count of recent decision-backed governed actions without action ids or command content."),+ "approvedDecisionCount": integerOption("Count of recent approved governed-action decisions without action ids or command content."),+ "rejectedDecisionCount": integerOption("Count of recent rejected governed-action decisions without action ids or command content."),+ "verifiedOutcomeCount": integerOption("Count of recent approved governed actions with a verified post-action outcome."),+ "operationsLoopStarterCount": integerOption("Count of content-free Patrol work prompt starter events in the evidence window."),+ "assistantOperationsLoopStarterCount": integerOption("Count of Patrol work prompt starters rendered by Pulse Assistant in the evidence window."),+ "patrolOperationsLoopStarterCount": integerOption("Count of Patrol work prompt starters launched from Pulse Patrol in the evidence window."),+ "patrolControlOperationsLoopStarterCount": integerOption("Count of Patrol work prompt starters launched from the first-party Patrol control journey in the evidence window."),+ "patrolControlCompletedOperationsLoopCount": integerOption("Count-only evidence that the Patrol control journey reached a terminal Patrol work result in the evidence window: Patrol issue evidence, contextual Assistant or external-agent collaboration, and either a rejected governed decision or an approved governed decision with a verified outcome."),+ "patrolControlResolvedOperationsLoopCount": integerOption("Count-only evidence that the Patrol control journey reached a verified Patrol work result in the evidence window: Patrol issue evidence, contextual Assistant or external-agent collaboration, approved governed decision, and verified outcome."),+ "patrolControlValueState": stringEnumOption([]string{"not_started", "in_progress", "governed_decision_recorded", "verified_needs_mcp", "verified"}, "Content-safe Patrol control value state. Only verified means Patrol completed a verified work outcome; governed_decision_recorded means a safe terminal decision exists without verified outcome evidence."),+ "patrolAutonomyOperationsLoopStarterCount": integerOption("Compatibility alias for patrolControlOperationsLoopStarterCount."),+ "patrolAutonomyCompletedOperationsLoopCount": integerOption("Compatibility alias for patrolControlCompletedOperationsLoopCount."),+ "patrolAutonomyResolvedOperationsLoopCount": integerOption("Compatibility alias for patrolControlResolvedOperationsLoopCount."),+ "patrolAutonomyValueState": stringEnumOption([]string{"not_started", "in_progress", "governed_decision_recorded", "verified_needs_mcp", "verified"}, "Compatibility alias for patrolControlValueState."),+ "proActivationOperationsLoopStarterCount": integerOption("Compatibility field retained for older external-agent clients; primary clients should use patrolControlOperationsLoopStarterCount."),+ "proActivationCompletedOperationsLoopCount": integerOption("Compatibility alias for patrolControlCompletedOperationsLoopCount."),+ "proActivationResolvedOperationsLoopCount": integerOption("Compatibility alias for patrolControlResolvedOperationsLoopCount."),+ "proActivationValueProofState": stringEnumOption([]string{"not_started", "in_progress", "governed_decision_recorded", "verified_needs_mcp", "verified"}, "Compatibility alias for patrolControlValueState."),+ "mcpOperationsLoopStarterCount": integerOption("Count of Patrol work prompt starters rendered by the Pulse MCP surface in the evidence window."),+ "externalAgentReady": booleanOption("Whether the Pulse MCP Patrol work contract is available and one non-expired API token covers every scope required by the published Pulse MCP Patrol work capability set."),+ "windowStart": dateTimeOption("Start of the action-audit evidence window used for governed/verified counts."),+ "generatedAt": dateTimeOption("Server timestamp for this Patrol work status snapshot."),+ })+}++func resourceContextOutputSchema() json.RawMessage {+ return agentObjectOutputSchema([]string{"canonicalId", "resourceType", "resourceName", "activeFindings", "pendingApprovals", "recentActions", "contextSections", "generatedAt"}, map[string]any{+ "canonicalId": stringOption("Canonical Pulse resource id."),+ "resourceType": stringOption("Canonical resource type."),+ "resourceName": stringOption("Display name for the resource."),+ "technology": stringOption("Platform or technology family when known."),+ "operatorState": openObjectOption("Operator-set resource state when present."),+ "activeFindings": objectArrayOption("Active Patrol finding summaries for this resource."),+ "pendingApprovals": objectArrayOption("Pending action approvals scoped to this resource."),+ "recentActions": objectArrayOption("Recent action attempts and outcomes scoped to this resource."),+ "contextSections": objectArrayOption("Additive typed context sections with provenance and redaction metadata."),+ "generatedAt": dateTimeOption("Server timestamp for this resource context snapshot."),+ })+}++func operatorStateOutputSchema() json.RawMessage {+ return agentObjectOutputSchema([]string{"canonicalId", "intentionallyOffline", "neverAutoRemediate", "setAt"}, map[string]any{+ "canonicalId": stringOption("Canonical Pulse resource id."),+ "intentionallyOffline": booleanOption("Whether this resource is expected to be offline."),+ "neverAutoRemediate": booleanOption("Whether automated remediation must be refused for this resource."),+ "maintenanceStartAt": dateTimeOption("Maintenance window start time when set."),+ "maintenanceEndAt": dateTimeOption("Maintenance window end time when set."),+ "maintenanceReason": stringOption("Operator note attached to the maintenance window."),+ "criticality": stringOption("Operator-set finding sort hint: high, medium, low, or empty."),+ "note": stringOption("Operator note for this resource."),+ "setAt": dateTimeOption("Server timestamp for the last state mutation."),+ "setBy": stringOption("Resolved actor id that last changed the state."),+ "maintenanceWindowActive": booleanOption("Whether the maintenance window is active at the server evaluation time when included in agent context."),+ })+}++func toolArrayOutputSchema(itemDescription string) json.RawMessage {+ return agentObjectOutputSchema([]string{"items", "count"}, map[string]any{+ "items": objectArrayOption(itemDescription),+ "count": integerOption("Number of items returned in the structured content wrapper."),+ })+}++func nodeMutationOutputSchema(required []string) json.RawMessage {+ return agentObjectOutputSchema(required, map[string]any{+ "status": stringEnumOption([]string{"success"}, "Status returned by node mutation routes when the normal save path is used."),+ "success": booleanOption("Whether the node mutation succeeded when the route returns the cluster-merge envelope."),+ "message": stringOption("Operator-readable mutation result when included."),+ })+}++func nodeConnectionTestOutputSchema() json.RawMessage {+ return agentObjectOutputSchema([]string{"status", "message"}, map[string]any{+ "status": stringEnumOption([]string{"success", "error"}, "Connection test result."),+ "message": stringOption("Operator-readable connection test result."),+ "latency": integerOption("Connection probe latency in milliseconds when measured."),+ "isCluster": booleanOption("Whether a proposed PVE source appears to be part of a cluster."),+ "nodeCount": integerOption("Number of PVE nodes observed during the probe."),+ "clusterNodeCount": integerOption("Number of PVE cluster endpoints observed during the probe."),+ "datastoreCount": integerOption("Number of PBS datastores observed during the probe."),+ "version": stringOption("Platform version returned by PMG when available."),+ "release": stringOption("Platform release returned by PMG when available."),+ "warnings": stringArrayOption("Non-fatal probe warnings for platform-specific monitoring endpoints."),+ })+}++func clusterRefreshOutputSchema() json.RawMessage {+ return agentObjectOutputSchema([]string{"status", "clusterName", "oldNodeCount", "newNodeCount", "nodesAdded", "clusterNodes"}, map[string]any{+ "status": stringEnumOption([]string{"success"}, "Cluster refresh result."),+ "clusterName": stringOption("Resolved PVE cluster name."),+ "oldNodeCount": integerOption("Endpoint count before refresh."),+ "newNodeCount": integerOption("Endpoint count after refresh."),+ "nodesAdded": integerOption("Number of newly detected endpoints."),+ "clusterNodes": objectArrayOption("Cluster endpoint records returned after refresh."),+ })+}++func discoveryOutputSchema() json.RawMessage {+ return agentObjectOutputSchema([]string{"servers", "errors", "structured_errors", "environment", "cached"}, map[string]any{+ "servers": nullableObjectArrayOption("Discovered infrastructure servers."),+ "errors": nullableStringArrayOption("Legacy human-readable discovery errors."),+ "structured_errors": nullableObjectArrayOption("Structured discovery errors with phase, type, message, and timestamp."),+ "environment": nullableOpenObjectOption("Detected environment metadata for the scan when available."),+ "cached": booleanOption("Whether this response came from the cached discovery result."),+ "scanning": booleanOption("Whether a manual scan is still running."),+ "updated": integerOption("Unix timestamp for the cached result."),+ "age": map[string]any{"type": "number", "description": "Age of the cached result in seconds."},+ })+}++func findingActionOutputSchema() json.RawMessage {+ return agentObjectOutputSchema([]string{"success", "message"}, map[string]any{+ "success": booleanOption("Whether the finding lifecycle action succeeded."),+ "message": stringOption("Operator-readable finding lifecycle result."),+ })+}++func actionPlanOutputSchema() json.RawMessage {+ return agentObjectOutputSchema([]string{ActionIDArgumentName, RequestIDArgumentName, "allowed", "requiresApproval", "approvalPolicy", "rollbackAvailable", "plannedAt", "expiresAt", "resourceVersion", "policyVersion", "planHash"}, map[string]any{+ ActionIDArgumentName: stringOption("Durable action id used by " + DecideActionCapabilityName + " and " + ExecuteActionCapabilityName + "."),+ RequestIDArgumentName: stringOption("Caller-provided idempotency key or external correlation id."),+ "allowed": booleanOption("Whether Pulse allows this action to be executed."),+ "requiresApproval": booleanOption("Whether the action must be approved before execution."),+ "approvalPolicy": stringOption("Approval policy required by the target capability."),+ "predictedBlastRadius": stringArrayOption("Related resources that could be affected by the action."),+ "rollbackAvailable": booleanOption("Whether Pulse has a rollback path for the planned action."),+ "message": stringOption("Operator-readable planning result."),+ "plannedAt": dateTimeOption("Server timestamp when the plan was created."),+ "expiresAt": dateTimeOption("Server timestamp when the plan expires."),+ "resourceVersion": stringOption("Resource version hash captured at plan time."),+ "policyVersion": stringOption("Capability policy version captured at plan time."),+ "planHash": stringOption("Hash binding request parameters, resource state, and policy state."),+ "preflight": openObjectOption("Deterministic pre-execution readout when available."),+ })+}++func actionDecisionOutputSchema() json.RawMessage {+ return agentObjectOutputSchema([]string{ActionIDArgumentName, "state", "approval", "audit"}, map[string]any{+ ActionIDArgumentName: stringOption("Durable action id that received the decision."),+ "state": stringOption("Action lifecycle state after the decision."),+ "approval": openObjectOption("Approval or rejection record persisted for this decision."),+ "audit": openObjectOption("Current action audit record after applying the decision."),+ })+}++func actionExecutionOutputSchema() json.RawMessage {+ return agentObjectOutputSchema([]string{ActionIDArgumentName, "state", "audit"}, map[string]any{+ ActionIDArgumentName: stringOption("Durable action id that was executed."),+ "state": stringOption("Action lifecycle state after execution."),+ "result": openObjectOption("Execution result when the action reached the executor."),+ "audit": openObjectOption("Current action audit record after execution."),+ })+}++func nodeIDInputSchema() json.RawMessage {+ return agentObjectInputSchema([]string{"nodeId"}, map[string]any{+ "nodeId": map[string]any{+ "type": "string",+ "description": "Configured node id from list_nodes, such as pve:lab or pve-0.",+ },+ })+}++func discoverLANInputSchema() json.RawMessage {+ return agentObjectInputSchema(nil, map[string]any{+ "subnet": map[string]any{+ "type": "string",+ "description": "CIDR to scan, such as 192.168.1.0/24, or auto to let Pulse choose the local subnet.",+ "default": "auto",+ },+ "use_cache": map[string]any{+ "type": "boolean",+ "description": "Return cached discovery results when available instead of starting a new scan.",+ "default": false,+ },+ })+}++func addNodeInputSchema() json.RawMessage {+ schema := agentObjectInputSchemaMap([]string{"type", "name", "host"}, nodeConfigInputProperties(false))+ schema["oneOf"] = []map[string]any{+ {"required": []string{"user", "password"}},+ {"required": []string{"tokenName", "tokenValue"}},+ }+ return agentInputSchema(schema)+}++func testNodeCredentialsInputSchema() json.RawMessage {+ schema := agentObjectInputSchemaMap([]string{"type", "host"}, nodeConfigInputProperties(false))+ schema["oneOf"] = []map[string]any{+ {"required": []string{"user", "password"}},+ {"required": []string{"tokenName", "tokenValue"}},+ }+ return agentInputSchema(schema)+}++func updateNodeInputSchema() json.RawMessage {+ properties := nodeConfigInputProperties(true)+ return agentObjectInputSchema([]string{"nodeId"}, properties)+}++func operatorStateInputSchema() json.RawMessage {+ schema := agentObjectInputSchemaMap([]string{ResourceIDArgumentName, "intentionallyOffline", "neverAutoRemediate"}, map[string]any{+ ResourceIDArgumentName: stringOption("Canonical resource id from get_fleet_context or get_resource_context. This path value wins over any body id."),+ "intentionallyOffline": map[string]any{+ "type": "boolean",+ "description": "Whether the resource is expected to be offline. This suppresses offline findings for this resource.",+ },+ "neverAutoRemediate": map[string]any{+ "type": "boolean",+ "description": "Whether governed automated remediation must be refused for this resource.",+ },+ "maintenanceStartAt": map[string]any{+ "type": "string",+ "format": "date-time",+ "description": "Maintenance window start time. Set together with maintenanceEndAt, or omit both.",+ },+ "maintenanceEndAt": map[string]any{+ "type": "string",+ "format": "date-time",+ "description": "Maintenance window end time. Must be after maintenanceStartAt when both are set.",+ },+ "maintenanceReason": stringOption("Optional reason shown when findings are quieted by the maintenance window."),+ "criticality": map[string]any{+ "type": "string",+ "enum": []string{"high", "medium", "low", ""},+ "description": "Optional finding-sort hint. Empty string clears the operator-set criticality.",+ },+ "note": stringOption("Optional operator note surfaced with the resource state."),+ })+ schema["dependencies"] = map[string][]string{+ "maintenanceStartAt": {"maintenanceEndAt"},+ "maintenanceEndAt": {"maintenanceStartAt"},+ }+ return agentInputSchema(schema)+}++func findingIDInputSchema(description string) json.RawMessage {+ return agentObjectInputSchema([]string{FindingIDArgumentName}, map[string]any{+ FindingIDArgumentName: stringOption(description),+ })+}++func resolveFindingInputSchema() json.RawMessage {+ return agentObjectInputSchema([]string{FindingIDArgumentName}, map[string]any{+ FindingIDArgumentName: stringOption("Patrol finding id to resolve, returned by " + ListFindingsCapabilityName + "."),+ ResolutionNoteArgumentName: stringOption("Optional operator-readable note describing why the finding is resolved."),+ })+}++func snoozeFindingInputSchema() json.RawMessage {+ return agentObjectInputSchema([]string{FindingIDArgumentName, "duration_hours"}, map[string]any{+ FindingIDArgumentName: stringOption("Patrol finding id returned by " + ListFindingsCapabilityName + "."),+ "duration_hours": map[string]any{+ "type": "integer",+ "minimum": 1,+ "maximum": 168,+ "description": "Number of hours to hide the finding. Pulse caps the value at 168 hours.",+ },+ })+}++func dismissFindingInputSchema() json.RawMessage {+ return agentObjectInputSchema([]string{FindingIDArgumentName, ReasonArgumentName}, map[string]any{+ FindingIDArgumentName: stringOption("Patrol finding id returned by " + ListFindingsCapabilityName + "."),+ ReasonArgumentName: map[string]any{+ "type": "string",+ "enum": []string{"not_an_issue", "expected_behavior", "will_fix_later"},+ "description": "Dismissal reason: not_an_issue suppresses a false positive, expected_behavior records known/accepted behavior, will_fix_later creates a reminder commitment.",+ },+ NoteArgumentName: stringOption("Optional operator note explaining the dismissal."),+ })+}++func actionPlanInputSchema() json.RawMessage {+ return agentObjectInputSchema([]string{RequestIDArgumentName, ResourceIDArgumentName, CapabilityNameArgumentName, ReasonArgumentName, RequestedByArgumentName}, map[string]any{+ RequestIDArgumentName: stringOption("Caller idempotency key or external correlation id for this plan request."),+ ResourceIDArgumentName: stringOption("Canonical resource id from get_fleet_context or get_resource_context."),+ CapabilityNameArgumentName: stringOption("Resource capability name to plan, as advertised on the target resource."),+ ReasonArgumentName: stringOption("Operator-readable reason for planning the action."),+ RequestedByArgumentName: stringOption("Stable requester identity, such as agent:oncall-helper."),+ "params": map[string]any{+ "type": "object",+ "description": "Capability-specific parameters. Use the target resource capability's parameter contract.",+ "additionalProperties": true,+ },+ })+}++func actionDecisionInputSchema() json.RawMessage {+ schema := agentObjectInputSchemaMap([]string{ActionIDArgumentName, OutcomeArgumentName}, map[string]any{+ ActionIDArgumentName: actionIDProperty(),+ OutcomeArgumentName: map[string]any{+ "type": "string",+ "enum": []string{"approved", "rejected"},+ "description": "Approval decision to record for the pending action.",+ },+ ReasonArgumentName: stringOption("Optional operator-readable decision reason."),+ })+ return agentInputSchema(schema)+}++func actionExecutionInputSchema() json.RawMessage {+ return agentObjectInputSchema([]string{ActionIDArgumentName}, map[string]any{+ ActionIDArgumentName: actionIDProperty(),+ ReasonArgumentName: stringOption("Optional operator-readable execution reason."),+ })+}++func actionIDProperty() map[string]any {+ return map[string]any{+ "type": "string",+ "pattern": "^[a-zA-Z0-9_-]+$",+ "maxLength": 128,+ "description": "Action id returned by plan_action.",+ }+}++func nodeConfigInputProperties(includeNodeID bool) map[string]any {+ properties := map[string]any{+ "type": map[string]any{+ "type": "string",+ "enum": []string{"pve", "pbs", "pmg"},+ "description": "Infrastructure source type: pve, pbs, or pmg.",+ },+ "name": map[string]any{+ "type": "string",+ "description": "Human-readable source name to show in Pulse.",+ },+ "host": map[string]any{+ "type": "string",+ "description": "Source endpoint URL or host, including scheme and port when needed.",+ },+ "guestURL": map[string]any{+ "type": "string",+ "description": "Optional guest-accessible URL for navigation.",+ },+ "user": map[string]any{+ "type": "string",+ "description": "Username for password authentication, or the token owner when needed by the platform.",+ },+ "password": map[string]any{+ "type": "string",+ "description": "Password used only for setup or password-backed monitoring.",+ },+ "tokenName": map[string]any{+ "type": "string",+ "description": "API token id or name, such as root@pam!pulse-monitor.",+ },+ "tokenValue": map[string]any{+ "type": "string",+ "description": "API token secret value. Pulse stores this as a credential and never returns it from list_nodes.",+ },+ "fingerprint": map[string]any{+ "type": "string",+ "description": "Optional TLS certificate fingerprint for pinned self-signed endpoints.",+ },+ "verifySSL": map[string]any{+ "type": "boolean",+ "description": "Whether Pulse should require normal TLS certificate validation.",+ },+ "monitorVMs": platformBool("PVE", "virtual machines"),+ "monitorContainers": platformBool("PVE", "containers"),+ "monitorStorage": platformBool("PVE", "storage"),+ "monitorBackups": platformBool("PVE or PBS", "backups"),+ "monitorPhysicalDisks": platformBool("PVE", "physical disks"),+ "physicalDiskPollingMinutes": integerOption("PVE physical disk polling interval in minutes. Use 0 or omit for the default."),+ "temperatureMonitoringEnabled": platformBool("All source types", "temperature monitoring"),+ "monitorDatastores": platformBool("PBS", "datastores"),+ "monitorSyncJobs": platformBool("PBS", "sync jobs"),+ "monitorVerifyJobs": platformBool("PBS", "verify jobs"),+ "monitorPruneJobs": platformBool("PBS", "prune jobs"),+ "monitorGarbageJobs": platformBool("PBS", "garbage collection jobs"),+ "monitorMailStats": platformBool("PMG", "mail statistics"),+ "monitorQueues": platformBool("PMG", "mail queues"),+ "monitorQuarantine": platformBool("PMG", "quarantine"),+ "monitorDomainStats": platformBool("PMG", "domain statistics"),+ "enabled": platformBool("All source types", "collection from this source"),+ "excludeDatastores": stringArrayOption("PBS datastore names to exclude from monitoring."),+ }+ if includeNodeID {+ properties["nodeId"] = map[string]any{+ "type": "string",+ "description": "Configured node id from list_nodes, such as pve:lab or pve-0.",+ }+ }+ return properties+}++func platformBool(platform, subject string) map[string]any {+ return map[string]any{+ "type": "boolean",+ "description": platform + " option for " + subject + ".",+ }+}++func integerOption(description string) map[string]any {+ return map[string]any{+ "type": "integer",+ "minimum": 0,+ "description": description,+ }+}++func booleanOption(description string) map[string]any {+ return map[string]any{+ "type": "boolean",+ "description": description,+ }+}++func stringOption(description string) map[string]any {+ return map[string]any{+ "type": "string",+ "description": description,+ }+}++func stringEnumOption(values []string, description string) map[string]any {+ return map[string]any{+ "type": "string",+ "enum": append([]string(nil), values...),+ "description": description,+ }+}++func dateTimeOption(description string) map[string]any {+ return map[string]any{+ "type": "string",+ "format": "date-time",+ "description": description,+ }+}++func stringArrayOption(description string) map[string]any {+ return map[string]any{+ "type": "array",+ "description": description,+ "items": map[string]any{+ "type": "string",+ },+ }+}++func openObjectOption(description string) map[string]any {+ return map[string]any{+ "type": "object",+ "description": description,+ "additionalProperties": true,+ }+}++func nullableOpenObjectOption(description string) map[string]any {+ return map[string]any{+ "description": description,+ "oneOf": []map[string]any{+ {+ "type": "object",+ "additionalProperties": true,+ },+ {"type": "null"},+ },+ }+}++func objectArrayOption(description string) map[string]any {+ return map[string]any{+ "type": "array",+ "description": description,+ "items": map[string]any{+ "type": "object",+ "additionalProperties": true,+ },+ }+}++func nullableObjectArrayOption(description string) map[string]any {+ return map[string]any{+ "description": description,+ "oneOf": []map[string]any{+ {+ "type": "array",+ "items": map[string]any{+ "type": "object",+ "additionalProperties": true,+ },+ },+ {"type": "null"},+ },+ }+}++func nullableStringArrayOption(description string) map[string]any {+ return map[string]any{+ "description": description,+ "oneOf": []map[string]any{+ {+ "type": "array",+ "items": map[string]any{+ "type": "string",+ },+ },+ {"type": "null"},+ },+ }+}++const (+ agentCapabilityActionModeRead = ActionModeRead+ agentCapabilityActionModeMixed = ActionModeMixed+ agentCapabilityActionModeWrite = ActionModeWrite++ agentCapabilityApprovalPolicyScopeOnly = ApprovalPolicyScopeOnly+ agentCapabilityApprovalPolicyActionPlan = ApprovalPolicyActionPlan++ agentCapabilityScopeMonitoringRead = auth.ScopeMonitoringRead+ agentCapabilityScopeMonitoringWrite = auth.ScopeMonitoringWrite+ agentCapabilityScopeSettingsRead = auth.ScopeSettingsRead+ agentCapabilityScopeSettingsWrite = auth.ScopeSettingsWrite+ agentCapabilityScopeAIExecute = auth.ScopeAIExecute+)++var (+ agentCapabilityFindingErrorCodes = []string{+ AgentErrCodeInvalidFindingRequest,+ AgentErrCodeFindingNotFound,+ AgentErrCodeFindingActionNotAllowed,+ AgentErrCodePatrolUnavailable,+ }+ agentCapabilityPlanActionErrorCodes = []string{+ AgentErrCodeInvalidActionRequest,+ AgentErrCodeResourceNotFound,+ AgentErrCodeCapabilityNotFound,+ AgentErrCodeActionExecutionUnavailable,+ }+ agentCapabilityDecisionActionErrorCodes = []string{+ AgentErrCodeMissingID,+ AgentErrCodeInvalidID,+ AgentErrCodeInvalidActionDecision,+ AgentErrCodeActionNotFound,+ AgentErrCodeActionNotPending,+ AgentErrCodeActionPlanExpired,+ }+ agentCapabilityExecuteActionErrorCodes = []string{+ AgentErrCodeMissingID,+ AgentErrCodeInvalidID,+ AgentErrCodeInvalidActionExecution,+ AgentErrCodeActionNotFound,+ AgentErrCodeActionNotApproved,+ AgentErrCodeActionAlreadyExecuting,+ AgentErrCodeActionExecutionFinal,+ AgentErrCodeActionDryRunOnly,+ AgentErrCodeActionPlanExpired,+ AgentErrCodeActionPlanDrift,+ AgentErrCodeResourceRemediationLocked,+ AgentErrCodeActionExecutorUnavailable,+ }+)++// canonicalManifest is the v1 declaration of Pulse's+// agent-consumable surface. Hand-authored rather than auto-generated+// because the contract decisions (which capabilities are+// agent-stable, what the stable error codes are, what category each+// belongs to) are product-shaping and must not drift behind code+// changes. Adding a capability here is a deliberate "this is part of+// the agent surface" commitment.+var canonicalManifest = Manifest{+ Version: "v1",+ SurfaceContract: SurfaceContract{+ Core: SurfaceContractComponent{+ ID: "pulse_intelligence_core",+ Label: "Pulse Intelligence Core",+ Description: "Canonical context, governed actions, safety gates, approval state, action audit, and verification shared by Pulse Assistant, Pulse MCP, and Pulse Patrol.",+ },+ ProactiveEngine: SurfaceContractComponent{+ ID: "pulse_patrol",+ Label: "Pulse Patrol",+ Description: "Patrol is the first-party operations surface: it watches, investigates, acts within the chosen Patrol mode, verifies outcomes, and records what happened.",+ },+ OperatorSurfaces: []OperatorSurfaceContract{+ {+ ID: SurfaceIDPulseAssistant,+ Label: "Pulse Assistant",+ Description: "The contextual explanation, approval, and handoff surface for Patrol findings, governed actions, verification, and operator questions.",+ Native: true,+ ExternalAdapter: false,+ Affordances: SurfaceAffordanceContract{+ Tools: true,+ InteractiveQuestions: true,+ },+ },+ {+ ID: SurfaceIDPulseMCP,+ Label: "Pulse MCP",+ Description: "The external-agent adapter that projects canonical Pulse Intelligence capabilities as MCP tools.",+ Native: false,+ ExternalAdapter: true,+ Affordances: SurfaceAffordanceContract{+ Tools: true,+ Resources: true,+ Prompts: true,+ CapabilityMetadata: true,+ },+ },+ },+ },+ SurfaceToolContracts: []SurfaceToolContract{+ {+ SurfaceID: SurfaceIDPulseMCP,+ ToolSource: SurfaceToolSourceCapabilityManifest,+ ToolNames: canonicalPulseMCPSurfaceToolNames(),+ },+ },+ MCPAdapter: DefaultMCPAdapterContract(),+ Categories: []CapabilityCategory{+ {+ ID: "context",+ Label: "Context (read-only)",+ Description: "Discovery and read-only situated reads. Agents start here.",+ },+ {+ ID: "operator-state",+ Label: "Operator state (per-resource intent)",+ Description: "Per-resource intent: intentionally-offline, never-auto-remediate, maintenance windows.",+ },+ {+ ID: "finding",+ Label: "Findings (Patrol lifecycle)",+ Description: "Acknowledge, snooze, dismiss, or resolve findings the Patrol runtime raised.",+ },+ {+ ID: "action",+ Label: "Actions (governed plan/approval/execute)",+ Description: "Plan, approve, and execute capability invocations against a resource.",+ },+ {+ ID: "provisioning",+ Label: "Provisioning (infrastructure onboarding)",+ Description: "List, test, add, update, or remove infrastructure sources through governed setup routes.",+ },+ },+ Capabilities: []Capability{+ {+ Name: "get_resource_context",+ Title: "Get resource context",+ Description: "Return the situated picture of a resource — identity, operator-set state with maintenance-window-active flag, active findings, pending approvals scoped to this resource, recent actions including refused dispatches. Command fields are redacted for monitoring-read API tokens unless the token also has ai:execute.",+ Category: "context",+ Method: http.MethodGet,+ Path: ResourceContextCapabilityPath,+ Scope: agentCapabilityScopeMonitoringRead,+ ActionMode: agentCapabilityActionModeRead,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ ResponseShape: "AgentResourceContext",+ OutputSchema: resourceContextOutputSchema(),+ ErrorCodes: []string{AgentErrCodeResourceNotFound},+ },+ {+ Name: "get_fleet_context",+ Title: "Get fleet context",+ Description: "Return a thin per-resource triage rollup across every resource visible to the org — identity, operator flags (intentionallyOffline, neverAutoRemediate, maintenanceWindowActive), per-severity finding counts (total/critical/warning/info), and pending-approval count. One read for 'where do I focus?'; follow up via get_resource_context for depth.",+ Category: "context",+ Method: http.MethodGet,+ Path: FleetContextCapabilityPath,+ Scope: agentCapabilityScopeMonitoringRead,+ ActionMode: agentCapabilityActionModeRead,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ ResponseShape: "AgentFleetContext",+ OutputSchema: fleetContextOutputSchema(),+ },+ {+ Name: OperationsLoopStatusCapabilityName,+ Title: "Get Patrol work status",+ Description: "Return the current content-safe Patrol work status: Patrol issue evidence, pending approvals, governed decisions/actions, verified outcomes, Patrol control outcome evidence, compatibility aliases, and optional MCP readiness. The payload is count-only and deliberately omits finding ids, action ids, prompts, commands, resource names, and output.",+ Category: "context",+ Method: http.MethodGet,+ Path: OperationsLoopStatusCapabilityPath,+ Scope: agentCapabilityScopeMonitoringRead,+ ActionMode: agentCapabilityActionModeRead,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ ResponseShape: "AgentOperationsLoopStatus",+ OutputSchema: operationsLoopStatusOutputSchema(),+ },+ {+ Name: ListNodesCapabilityName,+ Title: "List nodes",+ Description: "List configured infrastructure sources that Pulse can monitor or manage. Credential secret values are redacted; use the returned id with update_node, remove_node, test_node_connection, or refresh_node_cluster_membership.",+ Category: "provisioning",+ Method: http.MethodGet,+ Path: "/api/config/nodes",+ Scope: agentCapabilityScopeSettingsRead,+ ActionMode: agentCapabilityActionModeRead,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ ResponseShape: "NodeResponse[]",+ OutputSchema: toolArrayOutputSchema("Configured infrastructure source records visible to the agent."),+ },+ {+ Name: AddNodeCapabilityName,+ Title: "Add node",+ Description: "Add a Proxmox VE, Proxmox Backup Server, or Proxmox Mail Gateway source to Pulse after credentials have been collected, generated, or approved.",+ Category: "provisioning",+ Method: http.MethodPost,+ Path: "/api/config/nodes",+ Scope: agentCapabilityScopeSettingsWrite,+ ActionMode: agentCapabilityActionModeWrite,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ RequestBodyShape: "NodeConfigRequest",+ ResponseShape: "{ status?: \"success\", success?: true, message?: string }",+ InputSchema: addNodeInputSchema(),+ OutputSchema: nodeMutationOutputSchema(nil),+ },+ {+ Name: UpdateNodeCapabilityName,+ Title: "Update node",+ Description: "Update a configured infrastructure source. Omitted fields preserve the current value; tokenValue or password only changes when supplied.",+ Category: "provisioning",+ Method: http.MethodPut,+ Path: "/api/config/nodes/{nodeId}",+ Scope: agentCapabilityScopeSettingsWrite,+ ActionMode: agentCapabilityActionModeWrite,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ RequestBodyShape: "NodeConfigRequest",+ ResponseShape: "{ status: \"success\" }",+ InputSchema: updateNodeInputSchema(),+ OutputSchema: nodeMutationOutputSchema([]string{"status"}),+ },+ {+ Name: RemoveNodeCapabilityName,+ Title: "Remove node",+ Description: "Remove a configured infrastructure source from Pulse by node id.",+ Category: "provisioning",+ Method: http.MethodDelete,+ Path: "/api/config/nodes/{nodeId}",+ Scope: agentCapabilityScopeSettingsWrite,+ ActionMode: agentCapabilityActionModeWrite,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ ResponseShape: "{ status: \"success\" }",+ InputSchema: nodeIDInputSchema(),+ OutputSchema: nodeMutationOutputSchema([]string{"status"}),+ },+ {+ Name: TestNodeCredentialsCapabilityName,+ Title: "Test node credentials",+ Description: "Validate proposed source credentials and connection details without saving them to Pulse.",+ Category: "provisioning",+ Method: http.MethodPost,+ Path: "/api/config/nodes/test-config",+ Scope: agentCapabilityScopeSettingsWrite,+ ActionMode: agentCapabilityActionModeMixed,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ RequestBodyShape: "NodeConfigRequest",+ ResponseShape: "{ status: \"success\"|\"error\", message: string }",+ InputSchema: testNodeCredentialsInputSchema(),+ OutputSchema: nodeConnectionTestOutputSchema(),+ },+ {+ Name: TestNodeConnectionCapabilityName,+ Title: "Test node connection",+ Description: "Validate the saved connection for an existing configured infrastructure source.",+ Category: "provisioning",+ Method: http.MethodPost,+ Path: "/api/config/nodes/{nodeId}/test",+ Scope: agentCapabilityScopeSettingsWrite,+ ActionMode: agentCapabilityActionModeMixed,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ ResponseShape: "{ status: \"success\"|\"error\", message: string }",+ InputSchema: nodeIDInputSchema(),+ OutputSchema: nodeConnectionTestOutputSchema(),+ },+ {+ Name: RefreshNodeClusterMembershipCapabilityName,+ Title: "Refresh node cluster membership",+ Description: "Re-detect Proxmox VE cluster membership and endpoint metadata for a configured source.",+ Category: "provisioning",+ Method: http.MethodPost,+ Path: "/api/config/nodes/{nodeId}/refresh-cluster",+ Scope: agentCapabilityScopeSettingsWrite,+ ActionMode: agentCapabilityActionModeWrite,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ ResponseShape: "ClusterRefreshResponse",+ InputSchema: nodeIDInputSchema(),+ OutputSchema: clusterRefreshOutputSchema(),+ },+ {+ Name: DiscoverLANCapabilityName,+ Title: "Discover LAN",+ Description: "Scan a subnet, or return cached scan results, to find candidate infrastructure hosts before deciding which sources to add to Pulse.",+ Category: "provisioning",+ Method: http.MethodPost,+ Path: "/api/discover",+ Scope: agentCapabilityScopeSettingsWrite,+ ActionMode: agentCapabilityActionModeMixed,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ RequestBodyShape: "{ subnet?: string, use_cache?: boolean }",+ ResponseShape: "ManualDiscoveryResult",+ InputSchema: discoverLANInputSchema(),+ OutputSchema: discoveryOutputSchema(),+ },+ {+ Name: GetOperatorStateCapabilityName,+ Title: "Get operator state",+ Description: "Read the operator-set state for a resource (intentionally offline, never auto-remediate, maintenance window, criticality).",+ Category: "operator-state",+ Method: http.MethodGet,+ Path: OperatorStateCapabilityPath,+ Scope: agentCapabilityScopeMonitoringRead,+ ActionMode: agentCapabilityActionModeRead,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ ResponseShape: "ResourceOperatorState",+ OutputSchema: operatorStateOutputSchema(),+ ErrorCodes: []string{AgentErrCodeOperatorStateNotSet},+ },+ {+ Name: SetOperatorStateCapabilityName,+ Title: "Set operator state",+ Description: "Replace the operator-set state for a resource. URL canonicalId wins over body; server populates setAt and setBy from the authenticated identity.",+ Category: "operator-state",+ Method: http.MethodPut,+ Path: OperatorStateCapabilityPath,+ Scope: agentCapabilityScopeMonitoringWrite,+ ActionMode: agentCapabilityActionModeWrite,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ RequestBodyShape: "ResourceOperatorStateInput",+ ResponseShape: "ResourceOperatorState",+ OutputSchema: operatorStateOutputSchema(),+ ErrorCodes: []string{AgentErrCodeOperatorStateInvalid},+ InputSchema: operatorStateInputSchema(),+ },+ {+ Name: ClearOperatorStateCapabilityName,+ Title: "Clear operator state",+ Description: "Remove any operator-set state for a resource. Idempotent — succeeds whether or not an entry was present.",+ Category: "operator-state",+ Method: http.MethodDelete,+ Path: OperatorStateCapabilityPath,+ Scope: agentCapabilityScopeMonitoringWrite,+ ActionMode: agentCapabilityActionModeWrite,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ },+ {+ Name: "subscribe_events",+ Title: "Subscribe events",+ Description: SubscribeEventsDescription(),+ Category: "context",+ Method: http.MethodGet,+ Path: "/api/agent/events",+ Scope: agentCapabilityScopeMonitoringRead,+ ActionMode: agentCapabilityActionModeRead,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ ResponseShape: "text/event-stream of AgentEvent",+ },+ {+ Name: ListFindingsCapabilityName,+ Title: "List findings",+ Description: "List all Patrol findings (active, dismissed, resolved). Filter client-side on returned shape.",+ Category: "finding",+ Method: http.MethodGet,+ Path: "/api/ai/patrol/findings",+ Scope: agentCapabilityScopeAIExecute,+ ActionMode: agentCapabilityActionModeRead,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ ResponseShape: "Finding[]",+ OutputSchema: toolArrayOutputSchema("Patrol finding records returned by the lifecycle endpoint."),+ },+ {+ Name: AcknowledgeFindingCapabilityName,+ Title: "Acknowledge finding",+ Description: "Mark a finding as seen but keep it visible. Auto-resolves when the underlying condition clears.",+ Category: "finding",+ Method: http.MethodPost,+ Path: "/api/ai/patrol/acknowledge",+ Scope: agentCapabilityScopeAIExecute,+ ActionMode: agentCapabilityActionModeWrite,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ RequestBodyShape: "{ finding_id: string }",+ ResponseShape: "{ success: true, message: string }",+ ErrorCodes: agentCapabilityFindingErrorCodes,+ InputSchema: findingIDInputSchema("Patrol finding id to acknowledge, returned by " + ListFindingsCapabilityName + "."),+ OutputSchema: findingActionOutputSchema(),+ },+ {+ Name: SnoozeFindingCapabilityName,+ Title: "Snooze finding",+ Description: "Hide a finding for a defined duration in hours.",+ Category: "finding",+ Method: http.MethodPost,+ Path: "/api/ai/patrol/snooze",+ Scope: agentCapabilityScopeAIExecute,+ ActionMode: agentCapabilityActionModeWrite,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ RequestBodyShape: "{ finding_id: string, duration_hours: number }",+ ResponseShape: "{ success: true, message: string }",+ ErrorCodes: agentCapabilityFindingErrorCodes,+ InputSchema: snoozeFindingInputSchema(),+ OutputSchema: findingActionOutputSchema(),+ },+ {+ Name: DismissFindingCapabilityName,+ Title: "Dismiss finding",+ Description: "Dismiss a finding with a reason: not_an_issue (permanent suppression), expected_behavior (acknowledged forever), or will_fix_later (7-day reminder commitment).",+ Category: "finding",+ Method: http.MethodPost,+ Path: "/api/ai/patrol/dismiss",+ Scope: agentCapabilityScopeAIExecute,+ ActionMode: agentCapabilityActionModeWrite,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ RequestBodyShape: "{ finding_id: string, reason: \"not_an_issue\"|\"expected_behavior\"|\"will_fix_later\", note?: string }",+ ResponseShape: "{ success: true, message: string }",+ ErrorCodes: agentCapabilityFindingErrorCodes,+ InputSchema: dismissFindingInputSchema(),+ OutputSchema: findingActionOutputSchema(),+ },+ {+ Name: ResolveFindingCapabilityName,+ Title: "Resolve finding",+ Description: "Manually mark a finding as resolved when the underlying issue has been fixed out-of-band.",+ Category: "finding",+ Method: http.MethodPost,+ Path: "/api/ai/patrol/resolve",+ Scope: agentCapabilityScopeAIExecute,+ ActionMode: agentCapabilityActionModeWrite,+ ApprovalPolicy: agentCapabilityApprovalPolicyScopeOnly,+ RequestBodyShape: "{ finding_id: string, resolution_note?: string }",+ ResponseShape: "{ success: true, message: string }",+ ErrorCodes: agentCapabilityFindingErrorCodes,+ InputSchema: resolveFindingInputSchema(),+ OutputSchema: findingActionOutputSchema(),+ },+ {+ Name: PlanActionCapabilityName,+ Title: "Plan action",+ Description: "Plan an action against a resource. The planner validates the request, looks up the capability on the resource, checks executor-owned live availability, and returns an ActionPlan with the approval policy, blast radius, plan hash, and preflight summary. The plan is persisted to the audit history at the planned/pending state only after the live availability check passes, so subsequent decide_action and execute_action calls can reference it by id. Plan-and-execute is a two-step flow when the resulting plan requires approval, one-step otherwise.",+ Category: "action",+ Method: http.MethodPost,+ Path: PlanActionCapabilityPath,+ Scope: agentCapabilityScopeAIExecute,+ ActionMode: agentCapabilityActionModeWrite,+ ApprovalPolicy: agentCapabilityApprovalPolicyActionPlan,+ RequestBodyShape: "ActionRequest",+ ResponseShape: "ActionPlan",+ ErrorCodes: agentCapabilityPlanActionErrorCodes,+ InputSchema: actionPlanInputSchema(),+ OutputSchema: actionPlanOutputSchema(),+ },+ {+ Name: DecideActionCapabilityName,+ Title: "Decide action",+ Description: "Record an approval decision (approved or rejected) on a previously planned action. The actor is taken from the authenticated identity; an explicit reason can be passed in the body. Idempotent on the persisted decision: re-deciding a non-pending action surfaces the action_not_pending stable code so agents can branch on the conflict rather than retrying blindly.",+ Category: "action",+ Method: http.MethodPost,+ Path: ActionDecisionCapabilityPath,+ Scope: agentCapabilityScopeAIExecute,+ ActionMode: agentCapabilityActionModeWrite,+ ApprovalPolicy: agentCapabilityApprovalPolicyActionPlan,+ RequestBodyShape: "{ outcome: \"approved\"|\"rejected\", reason?: string }",+ ResponseShape: "ActionDecisionResponse",+ ErrorCodes: agentCapabilityDecisionActionErrorCodes,+ InputSchema: actionDecisionInputSchema(),+ OutputSchema: actionDecisionOutputSchema(),+ },+ {+ Name: ExecuteActionCapabilityName,+ Title: "Execute action",+ Description: "Execute a previously planned and (when required) approved action. Returns the persisted audit record with the execution result attached. Refuses with stable codes when the action is in the wrong lifecycle state (action_not_approved, action_already_executing, action_execution_final, action_dry_run_only, action_plan_expired), when the approved plan no longer matches the current resource/capability contract (action_plan_drift), when the target is operator-locked against automated remediation (resource_remediation_locked), or when the API instance has no executor wired (action_executor_unavailable). action.completed SSE events fire on every terminal state so agents watching the stream do not need to poll this endpoint after dispatch.",+ Category: "action",+ Method: http.MethodPost,+ Path: ActionExecutionCapabilityPath,+ Scope: agentCapabilityScopeAIExecute,+ ActionMode: agentCapabilityActionModeWrite,+ ApprovalPolicy: agentCapabilityApprovalPolicyActionPlan,+ RequestBodyShape: "{ reason?: string }",+ ResponseShape: "ActionExecutionResponse",+ ErrorCodes: agentCapabilityExecuteActionErrorCodes,+ InputSchema: actionExecutionInputSchema(),+ OutputSchema: actionExecutionOutputSchema(),+ },+ },+}++// CanonicalManifest returns Pulse's shared agent capabilities manifest. The+// returned value is detached from the package-owned manifest so callers cannot+// mutate the process-wide contract by accident.+func CanonicalManifest() Manifest {+ capabilities := CloneCapabilities(canonicalManifest.Capabilities)+ surfaceContract := CloneSurfaceContract(canonicalManifest.SurfaceContract)+ publishedSurfaceToolContracts := CloneSurfaceToolContracts(canonicalManifest.SurfaceToolContracts)+ surfaceToolContracts := ProjectManifestSurfaceToolContracts(Manifest{+ SurfaceContract: surfaceContract,+ SurfaceToolContracts: publishedSurfaceToolContracts,+ Capabilities: capabilities,+ })+ return Manifest{+ Version: canonicalManifest.Version,+ SurfaceContract: surfaceContract,+ SurfaceToolContracts: CloneSurfaceToolContracts(surfaceToolContracts),+ MCPAdapter: CloneMCPAdapterContract(canonicalManifest.MCPAdapter),+ RequiredScopes: RequiredCapabilityScopes(capabilities),+ Categories: CloneCapabilityCategories(canonicalManifest.Categories),+ WorkflowPrompts: ClonePulseWorkflowPrompts(ProjectPulseWorkflowPrompts(capabilities)),+ Capabilities: capabilities,+ }+}++func canonicalPulseMCPSurfaceToolNames() []string {+ return []string{+ ResourceContextCapabilityName,+ FleetContextCapabilityName,+ OperationsLoopStatusCapabilityName,+ ListNodesCapabilityName,+ AddNodeCapabilityName,+ UpdateNodeCapabilityName,+ RemoveNodeCapabilityName,+ TestNodeCredentialsCapabilityName,+ TestNodeConnectionCapabilityName,+ RefreshNodeClusterMembershipCapabilityName,+ DiscoverLANCapabilityName,+ GetOperatorStateCapabilityName,+ SetOperatorStateCapabilityName,+ ClearOperatorStateCapabilityName,+ ListFindingsCapabilityName,+ AcknowledgeFindingCapabilityName,+ SnoozeFindingCapabilityName,+ DismissFindingCapabilityName,+ ResolveFindingCapabilityName,+ PlanActionCapabilityName,+ DecideActionCapabilityName,+ ExecuteActionCapabilityName,+ }+}diff --git a/internal/agentcapabilities/manifest_test.go b/internal/agentcapabilities/manifest_test.gonew file mode 100644index 0000000000..47087a003d--- /dev/null+++ b/internal/agentcapabilities/manifest_test.go@@ -0,0 +1,927 @@+package agentcapabilities++import (+ "encoding/json"+ "net/http"+ "os"+ "reflect"+ "strings"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"+)++func TestCanonicalManifestOwnsAgentSurface(t *testing.T) {+ manifest := CanonicalManifest()+ if manifest.Version != "v1" {+ t.Fatalf("Version = %q, want v1", manifest.Version)+ }+ if len(manifest.Capabilities) == 0 {+ t.Fatal("CanonicalManifest must declare agent capabilities")+ }++ for _, name := range []string{+ FleetContextCapabilityName,+ ResourceContextCapabilityName,+ OperationsLoopStatusCapabilityName,+ SetOperatorStateCapabilityName,+ ListFindingsCapabilityName,+ PlanActionCapabilityName,+ ExecuteActionCapabilityName,+ } {+ if _, ok := FindCapability(manifest.Capabilities, name); !ok {+ t.Fatalf("CanonicalManifest missing %q", name)+ }+ }+}++func TestCanonicalManifestPinsPatrolControlStatusCapability(t *testing.T) {+ if PatrolControlStatusCapabilityName != "get_patrol_control_status" {+ t.Fatalf("PatrolControlStatusCapabilityName = %q, want get_patrol_control_status", PatrolControlStatusCapabilityName)+ }+ if PatrolControlStatusCapabilityPath != "/api/agent/patrol-control/status" {+ t.Fatalf("PatrolControlStatusCapabilityPath = %q, want /api/agent/patrol-control/status", PatrolControlStatusCapabilityPath)+ }+ if OperationsLoopStatusCapabilityName != PatrolControlStatusCapabilityName {+ t.Fatalf("OperationsLoopStatusCapabilityName must remain a source-compatible alias for %q", PatrolControlStatusCapabilityName)+ }+ if OperationsLoopStatusCapabilityPath != PatrolControlStatusCapabilityPath {+ t.Fatalf("OperationsLoopStatusCapabilityPath must remain a source-compatible alias for %q", PatrolControlStatusCapabilityPath)+ }+ if OperationsLoopStatusCompatibilityPath != "/api/agent/operations-loop/status" {+ t.Fatalf("OperationsLoopStatusCompatibilityPath = %q, want /api/agent/operations-loop/status", OperationsLoopStatusCompatibilityPath)+ }++ manifest := CanonicalManifest()+ cap, ok := FindCapability(manifest.Capabilities, PatrolControlStatusCapabilityName)+ if !ok {+ t.Fatalf("CanonicalManifest missing %q", PatrolControlStatusCapabilityName)+ }+ if cap.Path != PatrolControlStatusCapabilityPath {+ t.Fatalf("%s path = %q, want %q", PatrolControlStatusCapabilityName, cap.Path, PatrolControlStatusCapabilityPath)+ }+ if _, ok := FindCapability(manifest.Capabilities, "get_operations_loop_status"); ok {+ t.Fatal("CanonicalManifest must not publish legacy get_operations_loop_status as a primary capability")+ }+}++func TestCanonicalManifestUsesSharedResourceContextAddressing(t *testing.T) {+ if ResourceIDArgumentName != "resourceId" {+ t.Fatalf("ResourceIDArgumentName = %q, want resourceId", ResourceIDArgumentName)+ }++ manifest := CanonicalManifest()+ for name, path := range map[string]string{+ FleetContextCapabilityName: FleetContextCapabilityPath,+ ResourceContextCapabilityName: ResourceContextCapabilityPath,+ OperationsLoopStatusCapabilityName: OperationsLoopStatusCapabilityPath,+ GetOperatorStateCapabilityName: OperatorStateCapabilityPath,+ SetOperatorStateCapabilityName: OperatorStateCapabilityPath,+ ClearOperatorStateCapabilityName: OperatorStateCapabilityPath,+ } {+ cap, ok := FindCapability(manifest.Capabilities, name)+ if !ok {+ t.Fatalf("CanonicalManifest missing %q", name)+ }+ if cap.Path != path {+ t.Fatalf("%s path = %q, want %q", name, cap.Path, path)+ }+ }++ for _, name := range []string{GetOperatorStateCapabilityName, SetOperatorStateCapabilityName, ClearOperatorStateCapabilityName, PlanActionCapabilityName} {+ cap, ok := FindCapability(manifest.Capabilities, name)+ if !ok {+ t.Fatalf("CanonicalManifest missing %q", name)+ }+ var schema map[string]any+ if err := json.Unmarshal(ToolInputSchema(cap), &schema); err != nil {+ t.Fatalf("%s projected inputSchema must be valid JSON: %v", name, err)+ }+ properties, _ := schema["properties"].(map[string]any)+ if _, ok := properties[ResourceIDArgumentName]; !ok {+ t.Fatalf("%s projected inputSchema properties missing %q: %v", name, ResourceIDArgumentName, properties)+ }+ if !schemaRequiredContains(schema, ResourceIDArgumentName) {+ t.Fatalf("%s projected inputSchema required = %v, want %q", name, schema["required"], ResourceIDArgumentName)+ }+ }+}++func TestCanonicalManifestUsesSharedOperatorStateVocabulary(t *testing.T) {+ for name, want := range map[string]string{+ GetOperatorStateCapabilityName: "get_operator_state",+ SetOperatorStateCapabilityName: "set_operator_state",+ ClearOperatorStateCapabilityName: "clear_operator_state",+ } {+ if name != want {+ t.Fatalf("operator-state capability constant = %q, want %q", name, want)+ }+ }++ manifest := CanonicalManifest()+ for _, name := range []string{+ GetOperatorStateCapabilityName,+ SetOperatorStateCapabilityName,+ ClearOperatorStateCapabilityName,+ } {+ cap, ok := FindCapability(manifest.Capabilities, name)+ if !ok {+ t.Fatalf("CanonicalManifest missing %q", name)+ }+ if cap.Path != OperatorStateCapabilityPath {+ t.Fatalf("%s path = %q, want %q", name, cap.Path, OperatorStateCapabilityPath)+ }+ }+}++func TestCanonicalManifestUsesSharedFindingVocabulary(t *testing.T) {+ if FindingIDArgumentName != "finding_id" {+ t.Fatalf("FindingIDArgumentName = %q, want finding_id", FindingIDArgumentName)+ }+ if ResolutionNoteArgumentName != "resolution_note" {+ t.Fatalf("ResolutionNoteArgumentName = %q, want resolution_note", ResolutionNoteArgumentName)+ }+ if NoteArgumentName != "note" {+ t.Fatalf("NoteArgumentName = %q, want note", NoteArgumentName)+ }++ manifest := CanonicalManifest()+ for _, name := range []string{+ ListFindingsCapabilityName,+ AcknowledgeFindingCapabilityName,+ SnoozeFindingCapabilityName,+ DismissFindingCapabilityName,+ ResolveFindingCapabilityName,+ } {+ if _, ok := FindCapability(manifest.Capabilities, name); !ok {+ t.Fatalf("CanonicalManifest missing %q", name)+ }+ }++ for _, name := range []string{+ AcknowledgeFindingCapabilityName,+ SnoozeFindingCapabilityName,+ DismissFindingCapabilityName,+ ResolveFindingCapabilityName,+ } {+ cap, ok := FindCapability(manifest.Capabilities, name)+ if !ok {+ t.Fatalf("CanonicalManifest missing %q", name)+ }+ var schema map[string]any+ if err := json.Unmarshal(cap.InputSchema, &schema); err != nil {+ t.Fatalf("%s inputSchema must be valid JSON: %v", name, err)+ }+ properties, _ := schema["properties"].(map[string]any)+ if _, ok := properties[FindingIDArgumentName]; !ok {+ t.Fatalf("%s inputSchema properties missing %q: %v", name, FindingIDArgumentName, properties)+ }+ if !schemaRequiredContains(schema, FindingIDArgumentName) {+ t.Fatalf("%s inputSchema required = %v, want %q", name, schema["required"], FindingIDArgumentName)+ }+ }++ resolve, ok := FindCapability(manifest.Capabilities, ResolveFindingCapabilityName)+ if !ok {+ t.Fatalf("CanonicalManifest missing %q", ResolveFindingCapabilityName)+ }+ var resolveSchema map[string]any+ if err := json.Unmarshal(resolve.InputSchema, &resolveSchema); err != nil {+ t.Fatalf("%s inputSchema must be valid JSON: %v", ResolveFindingCapabilityName, err)+ }+ resolveProps, _ := resolveSchema["properties"].(map[string]any)+ if _, ok := resolveProps[ResolutionNoteArgumentName]; !ok {+ t.Fatalf("%s inputSchema properties missing %q: %v", ResolveFindingCapabilityName, ResolutionNoteArgumentName, resolveProps)+ }+ if schemaRequiredContains(resolveSchema, ResolutionNoteArgumentName) {+ t.Fatalf("%s inputSchema required = %v, %q must remain optional", ResolveFindingCapabilityName, resolveSchema["required"], ResolutionNoteArgumentName)+ }++ dismiss, ok := FindCapability(manifest.Capabilities, DismissFindingCapabilityName)+ if !ok {+ t.Fatalf("CanonicalManifest missing %q", DismissFindingCapabilityName)+ }+ var dismissSchema map[string]any+ if err := json.Unmarshal(dismiss.InputSchema, &dismissSchema); err != nil {+ t.Fatalf("%s inputSchema must be valid JSON: %v", DismissFindingCapabilityName, err)+ }+ dismissProps, _ := dismissSchema["properties"].(map[string]any)+ if _, ok := dismissProps[NoteArgumentName]; !ok {+ t.Fatalf("%s inputSchema properties missing %q: %v", DismissFindingCapabilityName, NoteArgumentName, dismissProps)+ }+ if schemaRequiredContains(dismissSchema, NoteArgumentName) {+ t.Fatalf("%s inputSchema required = %v, %q must remain optional", DismissFindingCapabilityName, dismissSchema["required"], NoteArgumentName)+ }+}++func TestCanonicalManifestUsesSharedActionVocabulary(t *testing.T) {+ for name, want := range map[string]string{+ RequestIDArgumentName: "requestId",+ ActionIDArgumentName: "actionId",+ CapabilityNameArgumentName: "capabilityName",+ ReasonArgumentName: "reason",+ RequestedByArgumentName: "requestedBy",+ OutcomeArgumentName: "outcome",+ } {+ if name != want {+ t.Fatalf("action argument constant = %q, want %q", name, want)+ }+ }++ manifest := CanonicalManifest()+ for name, path := range map[string]string{+ PlanActionCapabilityName: PlanActionCapabilityPath,+ DecideActionCapabilityName: ActionDecisionCapabilityPath,+ ExecuteActionCapabilityName: ActionExecutionCapabilityPath,+ } {+ cap, ok := FindCapability(manifest.Capabilities, name)+ if !ok {+ t.Fatalf("CanonicalManifest missing %q", name)+ }+ if cap.Path != path {+ t.Fatalf("%s path = %q, want %q", name, cap.Path, path)+ }+ }++ for name, required := range map[string][]string{+ PlanActionCapabilityName: {RequestIDArgumentName, ResourceIDArgumentName, CapabilityNameArgumentName, ReasonArgumentName, RequestedByArgumentName},+ DecideActionCapabilityName: {ActionIDArgumentName, OutcomeArgumentName},+ ExecuteActionCapabilityName: {ActionIDArgumentName},+ } {+ cap, ok := FindCapability(manifest.Capabilities, name)+ if !ok {+ t.Fatalf("CanonicalManifest missing %q", name)+ }+ var schema map[string]any+ if err := json.Unmarshal(cap.InputSchema, &schema); err != nil {+ t.Fatalf("%s inputSchema must be valid JSON: %v", name, err)+ }+ properties, _ := schema["properties"].(map[string]any)+ for _, field := range required {+ if _, ok := properties[field]; !ok {+ t.Fatalf("%s inputSchema properties missing %q: %v", name, field, properties)+ }+ if !schemaRequiredContains(schema, field) {+ t.Fatalf("%s inputSchema required = %v, want %q", name, schema["required"], field)+ }+ }+ }+}++func TestCanonicalManifestPinsPulseIntelligenceSurfaceContract(t *testing.T) {+ manifest := CanonicalManifest()+ contract := manifest.SurfaceContract++ if contract.Core.ID != "pulse_intelligence_core" || contract.Core.Label != "Pulse Intelligence Core" {+ t.Fatalf("manifest core contract = %+v", contract.Core)+ }+ if !strings.Contains(contract.Core.Description, "Canonical context, governed actions, safety gates, approval state, action audit, and verification") {+ t.Fatalf("manifest core description does not pin shared core ownership: %q", contract.Core.Description)+ }+ if contract.ProactiveEngine.ID != "pulse_patrol" || contract.ProactiveEngine.Label != "Pulse Patrol" {+ t.Fatalf("manifest Patrol operator component = %+v", contract.ProactiveEngine)+ }+ if !strings.Contains(contract.ProactiveEngine.Description, "first-party operations surface") ||+ !strings.Contains(contract.ProactiveEngine.Description, "Patrol mode") ||+ !strings.Contains(contract.ProactiveEngine.Description, "verifies outcomes") {+ t.Fatalf("manifest Patrol description must describe Patrol as the primary built-in operator, got %q", contract.ProactiveEngine.Description)+ }++ if len(contract.OperatorSurfaces) != 2 {+ t.Fatalf("access path count = %d, want Assistant and MCP", len(contract.OperatorSurfaces))+ }+ surfaces := map[string]OperatorSurfaceContract{}+ for _, surface := range contract.OperatorSurfaces {+ surfaces[surface.ID] = surface+ if surface.ID == "pulse_patrol" {+ t.Fatal("Pulse Patrol must stay the primary built-in operator component, not be flattened into the compatibility access-path list")+ }+ }++ assistant := surfaces["pulse_assistant"]+ if assistant.Label != "Pulse Assistant" || !assistant.Native || assistant.ExternalAdapter {+ t.Fatalf("Pulse Assistant surface contract = %+v", assistant)+ }+ if !strings.Contains(assistant.Description, "contextual explanation") ||+ !strings.Contains(assistant.Description, "Patrol findings") {+ t.Fatalf("Pulse Assistant description must preserve contextual access-path role, got %q", assistant.Description)+ }+ if !assistant.Affordances.Tools || !assistant.Affordances.InteractiveQuestions ||+ assistant.Affordances.Resources || assistant.Affordances.Prompts || assistant.Affordances.CapabilityMetadata {+ t.Fatalf("Pulse Assistant affordance contract = %+v", assistant.Affordances)+ }++ mcp := surfaces["pulse_mcp"]+ if mcp.Label != "Pulse MCP" || mcp.Native || !mcp.ExternalAdapter {+ t.Fatalf("Pulse MCP surface contract = %+v", mcp)+ }+ if !strings.Contains(mcp.Description, "external-agent adapter") {+ t.Fatalf("Pulse MCP description must preserve adapter role, got %q", mcp.Description)+ }+ if !mcp.Affordances.Tools || !mcp.Affordances.Resources || !mcp.Affordances.Prompts || !mcp.Affordances.CapabilityMetadata ||+ mcp.Affordances.InteractiveQuestions {+ t.Fatalf("Pulse MCP affordance contract = %+v", mcp.Affordances)+ }+}++func TestCanonicalManifestPublishesExternalSurfaceToolContracts(t *testing.T) {+ manifest := CanonicalManifest()+ if len(manifest.SurfaceToolContracts) != 1 {+ t.Fatalf("surface tool contracts = %+v, want static Pulse MCP contract only", manifest.SurfaceToolContracts)+ }++ mcp := manifest.SurfaceToolContracts[0]+ if mcp.SurfaceID != SurfaceIDPulseMCP || mcp.ToolSource != SurfaceToolSourceCapabilityManifest {+ t.Fatalf("surface tool contract identity = %+v", mcp)+ }+ if len(mcp.ToolNames) == 0 || !reflect.DeepEqual(mcp.ToolNames, mcp.CapabilityNames) {+ t.Fatalf("MCP surface tools must be manifest-published capability names, got tools=%#v capabilities=%#v", mcp.ToolNames, mcp.CapabilityNames)+ }+ want := canonicalPulseMCPSurfaceToolNames()+ if !reflect.DeepEqual(mcp.ToolNames, want) {+ t.Fatalf("MCP surface tools = %#v, want explicit canonical allowlist %#v", mcp.ToolNames, want)+ }+ for _, name := range mcp.ToolNames {+ switch name {+ case EventSubscriptionCapabilityName, PulseQuestionToolName:+ t.Fatalf("static external surface tools must not include %s: %#v", name, mcp.ToolNames)+ }+ if _, err := ResolveRequestResponseCapability(manifest.Capabilities, name); err != nil {+ t.Fatalf("static external surface tool %q must resolve to a request/response manifest capability: %v", name, err)+ }+ }+ if len(mcp.RegistryToolNames) != 0 || len(mcp.NativeToolNames) != 0 {+ t.Fatalf("static external surface must not expose Assistant runtime buckets: %+v", mcp)+ }+}++func TestCanonicalManifestPinsPulseMCPResolvedOperationsLoopCapabilities(t *testing.T) {+ manifest := CanonicalManifest()++ contract, ok := FindManifestSurfaceToolContract(manifest, SurfaceIDPulseMCP)+ if !ok {+ t.Fatal("Pulse MCP must publish a static surface tool contract")+ }+ if contract.ToolSource != SurfaceToolSourceCapabilityManifest {+ t.Fatalf("Pulse MCP tool source = %q, want %q", contract.ToolSource, SurfaceToolSourceCapabilityManifest)+ }++ surfaceCapabilities := ManifestSurfaceToolCapabilities(manifest, SurfaceIDPulseMCP)+ surfaceCapabilityNames := map[string]bool{}+ for _, cap := range surfaceCapabilities {+ surfaceCapabilityNames[cap.Name] = true+ }+ surfaceTools := ProjectManifestSurfaceTools(manifest, SurfaceIDPulseMCP)+ surfaceToolsByName := map[string]ProjectedTool{}+ for _, tool := range surfaceTools {+ surfaceToolsByName[tool.Name] = tool+ }++ requiredLoop := []struct {+ name string+ category string+ method string+ path string+ scope string+ mode ActionMode+ approval ApprovalPolicy+ errorCodes []string+ }{+ {+ name: FleetContextCapabilityName,+ category: "context",+ method: http.MethodGet,+ path: FleetContextCapabilityPath,+ scope: auth.ScopeMonitoringRead,+ mode: ActionModeRead,+ approval: ApprovalPolicyScopeOnly,+ },+ {+ name: OperationsLoopStatusCapabilityName,+ category: "context",+ method: http.MethodGet,+ path: OperationsLoopStatusCapabilityPath,+ scope: auth.ScopeMonitoringRead,+ mode: ActionModeRead,+ approval: ApprovalPolicyScopeOnly,+ },+ {+ name: ResourceContextCapabilityName,+ category: "context",+ method: http.MethodGet,+ path: ResourceContextCapabilityPath,+ scope: auth.ScopeMonitoringRead,+ mode: ActionModeRead,+ approval: ApprovalPolicyScopeOnly,+ errorCodes: []string{AgentErrCodeResourceNotFound},+ },+ {+ name: ListFindingsCapabilityName,+ category: "finding",+ method: http.MethodGet,+ path: "/api/ai/patrol/findings",+ scope: auth.ScopeAIExecute,+ mode: ActionModeRead,+ approval: ApprovalPolicyScopeOnly,+ },+ {+ name: ResolveFindingCapabilityName,+ category: "finding",+ method: http.MethodPost,+ path: "/api/ai/patrol/resolve",+ scope: auth.ScopeAIExecute,+ mode: ActionModeWrite,+ approval: ApprovalPolicyScopeOnly,+ errorCodes: []string{+ AgentErrCodeInvalidFindingRequest,+ AgentErrCodeFindingNotFound,+ AgentErrCodeFindingActionNotAllowed,+ AgentErrCodePatrolUnavailable,+ },+ },+ {+ name: PlanActionCapabilityName,+ category: "action",+ method: http.MethodPost,+ path: PlanActionCapabilityPath,+ scope: auth.ScopeAIExecute,+ mode: ActionModeWrite,+ approval: ApprovalPolicyActionPlan,+ errorCodes: []string{+ AgentErrCodeInvalidActionRequest,+ AgentErrCodeResourceNotFound,+ AgentErrCodeCapabilityNotFound,+ AgentErrCodeActionExecutionUnavailable,+ },+ },+ {+ name: DecideActionCapabilityName,+ category: "action",+ method: http.MethodPost,+ path: ActionDecisionCapabilityPath,+ scope: auth.ScopeAIExecute,+ mode: ActionModeWrite,+ approval: ApprovalPolicyActionPlan,+ errorCodes: []string{+ AgentErrCodeMissingID,+ AgentErrCodeInvalidID,+ AgentErrCodeInvalidActionDecision,+ AgentErrCodeActionNotFound,+ AgentErrCodeActionNotPending,+ AgentErrCodeActionPlanExpired,+ },+ },+ {+ name: ExecuteActionCapabilityName,+ category: "action",+ method: http.MethodPost,+ path: ActionExecutionCapabilityPath,+ scope: auth.ScopeAIExecute,+ mode: ActionModeWrite,+ approval: ApprovalPolicyActionPlan,+ errorCodes: []string{+ AgentErrCodeMissingID,+ AgentErrCodeInvalidID,+ AgentErrCodeInvalidActionExecution,+ AgentErrCodeActionNotFound,+ AgentErrCodeActionNotApproved,+ AgentErrCodeActionAlreadyExecuting,+ AgentErrCodeActionExecutionFinal,+ AgentErrCodeActionDryRunOnly,+ AgentErrCodeActionPlanExpired,+ AgentErrCodeActionPlanDrift,+ AgentErrCodeResourceRemediationLocked,+ AgentErrCodeActionExecutorUnavailable,+ },+ },+ }++ for _, want := range requiredLoop {+ if !containsString(contract.ToolNames, want.name) {+ t.Fatalf("Pulse MCP surface contract missing resolved-operations loop capability %q: %#v", want.name, contract.ToolNames)+ }+ if !surfaceCapabilityNames[want.name] {+ t.Fatalf("Pulse MCP surface capability projection missing %q: %#v", want.name, surfaceCapabilities)+ }+ tool, ok := surfaceToolsByName[want.name]+ if !ok {+ t.Fatalf("Pulse MCP tools/list projection missing %q: %#v", want.name, surfaceTools)+ }++ cap, ok := FindCapability(manifest.Capabilities, want.name)+ if !ok {+ t.Fatalf("CanonicalManifest missing %q", want.name)+ }+ if cap.Category != want.category || cap.Method != want.method || cap.Path != want.path || cap.Scope != want.scope {+ t.Fatalf("%s manifest route contract = category:%q method:%q path:%q scope:%q, want category:%q method:%q path:%q scope:%q",+ want.name, cap.Category, cap.Method, cap.Path, cap.Scope, want.category, want.method, want.path, want.scope)+ }+ if cap.ActionMode != want.mode || cap.ApprovalPolicy != want.approval {+ t.Fatalf("%s governance = %s/%s, want %s/%s", want.name, cap.ActionMode, cap.ApprovalPolicy, want.mode, want.approval)+ }+ for _, errorCode := range want.errorCodes {+ if !containsString(cap.ErrorCodes, errorCode) {+ t.Fatalf("%s errorCodes = %#v, missing %q", want.name, cap.ErrorCodes, errorCode)+ }+ }++ meta, ok := tool.Meta[ToolMetaPulseCapabilityKey].(map[string]any)+ if !ok {+ t.Fatalf("%s projected MCP tool missing Pulse capability metadata: %#v", want.name, tool.Meta)+ }+ if meta["name"] != want.name || meta["category"] != want.category || meta["scope"] != want.scope {+ t.Fatalf("%s projected MCP metadata = %#v, want name/category/scope from manifest", want.name, meta)+ }+ route, _ := meta["route"].(map[string]any)+ if route["method"] != want.method || route["path"] != want.path {+ t.Fatalf("%s projected MCP route metadata = %#v, want %s %s", want.name, route, want.method, want.path)+ }+ governance, _ := meta["governance"].(map[string]any)+ if governance["actionMode"] != string(want.mode) || governance["approvalPolicy"] != string(want.approval) {+ t.Fatalf("%s projected MCP governance metadata = %#v, want %s/%s", want.name, governance, want.mode, want.approval)+ }+ }+}++func TestCanonicalManifestProjectsWorkflowPromptsFromCapabilities(t *testing.T) {+ manifest := CanonicalManifest()+ want := ProjectPulseWorkflowPrompts(manifest.Capabilities)+ if len(manifest.WorkflowPrompts) == 0 {+ t.Fatal("CanonicalManifest must expose shared Pulse Intelligence workflow prompts")+ }+ if len(manifest.WorkflowPrompts) != len(want) {+ t.Fatalf("CanonicalManifest WorkflowPrompts length = %d, want %d", len(manifest.WorkflowPrompts), len(want))+ }++ gotNames := make([]string, 0, len(manifest.WorkflowPrompts))+ wantNames := make([]string, 0, len(want))+ for i := range manifest.WorkflowPrompts {+ got := manifest.WorkflowPrompts[i]+ expected := want[i]+ gotNames = append(gotNames, got.Name)+ wantNames = append(wantNames, expected.Name)+ if got.Name != expected.Name || got.Description != expected.Description {+ t.Fatalf("workflow prompt[%d] = %+v, want %+v", i, got, expected)+ }+ if len(got.Arguments) != len(expected.Arguments) {+ t.Fatalf("workflow prompt[%d] argument count = %d, want %d", i, len(got.Arguments), len(expected.Arguments))+ }+ }++ for _, name := range []string{+ PulseWorkflowPromptTriageFleet,+ PulseWorkflowPromptInvestigateResource,+ PulseWorkflowPromptReviewFinding,+ PulseWorkflowPromptOperationsLoop,+ } {+ if !containsString(gotNames, name) {+ t.Fatalf("CanonicalManifest workflow prompts = %v, missing %q; projected prompts = %v", gotNames, name, wantNames)+ }+ }+}++func TestCanonicalManifestReturnsDetachedCopy(t *testing.T) {+ first := CanonicalManifest()+ if len(first.Capabilities) == 0 {+ t.Fatal("CanonicalManifest must declare capabilities")+ }++ first.Version = "mutated"+ first.SurfaceContract.Core.Label = "mutated"+ if len(first.SurfaceContract.OperatorSurfaces) == 0 {+ t.Fatal("CanonicalManifest must declare operator surfaces")+ }+ first.SurfaceContract.OperatorSurfaces[0].Label = "mutated"+ if len(first.SurfaceToolContracts) == 0 {+ t.Fatal("CanonicalManifest must declare static external surface tool contracts")+ }+ if len(first.SurfaceToolContracts[0].ToolNames) == 0 || len(first.SurfaceToolContracts[0].CapabilityNames) == 0 {+ t.Fatal("CanonicalManifest must declare static external surface tool names")+ }+ first.SurfaceToolContracts[0].ToolNames[0] = "mutated"+ first.SurfaceToolContracts[0].CapabilityNames[0] = "mutated"+ first.MCPAdapter.Command = "mutated"+ if len(first.MCPAdapter.ConfigFamilies) == 0 {+ t.Fatal("CanonicalManifest must declare MCP adapter config families")+ }+ first.MCPAdapter.ConfigFamilies[0].Label = "mutated"+ if len(first.MCPAdapter.ConfigFamilies[0].FileHints) > 0 {+ first.MCPAdapter.ConfigFamilies[0].FileHints[0] = "mutated"+ }+ if len(first.MCPAdapter.ConfigFamilies[0].ClientLabels) > 0 {+ first.MCPAdapter.ConfigFamilies[0].ClientLabels[0] = "mutated"+ }+ first.Capabilities[0].Name = "mutated"+ if len(first.Capabilities[0].ErrorCodes) > 0 {+ first.Capabilities[0].ErrorCodes[0] = "mutated"+ }+ if len(first.RequiredScopes) == 0 {+ t.Fatal("CanonicalManifest must declare required scopes")+ }+ first.RequiredScopes[0] = "mutated"+ if len(first.Categories) == 0 {+ t.Fatal("CanonicalManifest must declare capability categories")+ }+ first.Categories[0].Label = "mutated"+ if len(first.WorkflowPrompts) == 0 {+ t.Fatal("CanonicalManifest must declare workflow prompts")+ }+ first.WorkflowPrompts[0].Name = "mutated"+ workflowPromptArgumentIndex := -1+ for i := range first.WorkflowPrompts {+ if len(first.WorkflowPrompts[i].Arguments) > 0 {+ workflowPromptArgumentIndex = i+ first.WorkflowPrompts[i].Arguments[0].Name = "mutated"+ break+ }+ }+ if workflowPromptArgumentIndex < 0 {+ t.Fatal("CanonicalManifest must declare at least one workflow prompt argument")+ }+ schemaIndex := -1+ for i := range first.Capabilities {+ if len(first.Capabilities[i].InputSchema) > 0 {+ schemaIndex = i+ first.Capabilities[i].InputSchema[0] = '['+ break+ }+ }+ if schemaIndex < 0 {+ t.Fatal("CanonicalManifest must include at least one authored input schema")+ }++ second := CanonicalManifest()+ if second.Version != "v1" {+ t.Fatalf("CanonicalManifest version was mutated: %q", second.Version)+ }+ if second.SurfaceContract.Core.Label == "mutated" {+ t.Fatal("CanonicalManifest returned aliased surface contract component")+ }+ if second.SurfaceContract.OperatorSurfaces[0].Label == "mutated" {+ t.Fatal("CanonicalManifest returned aliased operator surfaces")+ }+ if second.SurfaceToolContracts[0].ToolNames[0] == "mutated" {+ t.Fatal("CanonicalManifest returned aliased surface tool contract tool names")+ }+ if second.SurfaceToolContracts[0].CapabilityNames[0] == "mutated" {+ t.Fatal("CanonicalManifest returned aliased surface tool contract capability names")+ }+ if second.MCPAdapter.Command == "mutated" {+ t.Fatal("CanonicalManifest returned aliased MCP adapter contract")+ }+ if second.MCPAdapter.ConfigFamilies[0].Label == "mutated" {+ t.Fatal("CanonicalManifest returned aliased MCP adapter config families")+ }+ if len(second.MCPAdapter.ConfigFamilies[0].FileHints) > 0 && second.MCPAdapter.ConfigFamilies[0].FileHints[0] == "mutated" {+ t.Fatal("CanonicalManifest returned aliased MCP adapter config-family file hints")+ }+ if len(second.MCPAdapter.ConfigFamilies[0].ClientLabels) > 0 && second.MCPAdapter.ConfigFamilies[0].ClientLabels[0] == "mutated" {+ t.Fatal("CanonicalManifest returned aliased MCP adapter config-family client labels")+ }+ if second.Capabilities[0].Name == "mutated" {+ t.Fatal("CanonicalManifest returned aliased capability slice")+ }+ if len(first.Capabilities[0].ErrorCodes) > 0 && second.Capabilities[0].ErrorCodes[0] == "mutated" {+ t.Fatal("CanonicalManifest returned aliased error code slice")+ }+ if second.RequiredScopes[0] == "mutated" {+ t.Fatal("CanonicalManifest returned aliased required scope slice")+ }+ if second.Categories[0].Label == "mutated" {+ t.Fatal("CanonicalManifest returned aliased capability category slice")+ }+ if second.WorkflowPrompts[0].Name == "mutated" {+ t.Fatal("CanonicalManifest returned aliased workflow prompt slice")+ }+ if second.WorkflowPrompts[workflowPromptArgumentIndex].Arguments[0].Name == "mutated" {+ t.Fatal("CanonicalManifest returned aliased workflow prompt argument slice")+ }+ if string(second.Capabilities[schemaIndex].InputSchema) == string(first.Capabilities[schemaIndex].InputSchema) {+ t.Fatal("CanonicalManifest returned aliased input schema")+ }+}++func TestCanonicalManifestPinsMCPAdapterSetupContract(t *testing.T) {+ adapter := CanonicalManifest().MCPAdapter+ if adapter.ServerName != DefaultMCPAdapterServerName {+ t.Fatalf("MCP adapter server name = %q, want %q", adapter.ServerName, DefaultMCPAdapterServerName)+ }+ if adapter.Command != DefaultMCPAdapterCommand {+ t.Fatalf("MCP adapter command = %q, want %q", adapter.Command, DefaultMCPAdapterCommand)+ }+ if adapter.BaseURLFlag != DefaultMCPAdapterBaseURLFlag {+ t.Fatalf("MCP adapter base URL flag = %q, want %q", adapter.BaseURLFlag, DefaultMCPAdapterBaseURLFlag)+ }+ if adapter.DefaultBaseURL != DefaultMCPAdapterDefaultBaseURL {+ t.Fatalf("MCP adapter default base URL = %q, want %q", adapter.DefaultBaseURL, DefaultMCPAdapterDefaultBaseURL)+ }+ if adapter.TokenEnv != DefaultMCPAdapterTokenEnv {+ t.Fatalf("MCP adapter token env = %q, want %q", adapter.TokenEnv, DefaultMCPAdapterTokenEnv)+ }++ families := map[string]MCPAdapterConfigFamily{}+ for _, family := range adapter.ConfigFamilies {+ if family.ID == "" || family.Label == "" || family.Shape == "" {+ t.Fatalf("MCP adapter config family must declare id, label, and shape: %+v", family)+ }+ families[family.Shape] = family+ }+ for _, shape := range []string{+ MCPAdapterConfigShapeOpenCodeMCP,+ MCPAdapterConfigShapeMCPServers,+ MCPAdapterConfigShapeCustom,+ } {+ if _, ok := families[shape]; !ok {+ t.Fatalf("MCP adapter config family shape %q missing from manifest contract", shape)+ }+ }++ opencode := families[MCPAdapterConfigShapeOpenCodeMCP]+ if opencode.Label != "OpenCode" || !containsString(opencode.FileHints, "opencode.json") {+ t.Fatalf("OpenCode MCP adapter family = %+v", opencode)+ }+ mcpServers := families[MCPAdapterConfigShapeMCPServers]+ if !containsString(mcpServers.ClientLabels, "Claude Desktop") || !containsString(mcpServers.ClientLabels, "Claude Code") {+ t.Fatalf("mcpServers adapter family must cover Claude Desktop and Claude Code, got %+v", mcpServers)+ }+ custom := families[MCPAdapterConfigShapeCustom]+ if custom.Label != "custom MCP clients" {+ t.Fatalf("custom MCP adapter family = %+v", custom)+ }+}++func TestCanonicalManifestDeclaresCategoryPresentation(t *testing.T) {+ manifest := CanonicalManifest()+ if len(manifest.Categories) == 0 {+ t.Fatal("CanonicalManifest must declare category presentation metadata")+ }++ byID := map[string]CapabilityCategory{}+ for _, category := range manifest.Categories {+ if category.ID == "" {+ t.Fatal("category id must not be empty")+ }+ if category.Label == "" {+ t.Fatalf("category %q must declare a label", category.ID)+ }+ if category.Description == "" {+ t.Fatalf("category %q must declare a description", category.ID)+ }+ if _, exists := byID[category.ID]; exists {+ t.Fatalf("duplicate category id %q", category.ID)+ }+ byID[category.ID] = category+ }++ for _, cap := range manifest.Capabilities {+ if _, ok := byID[cap.Category]; !ok {+ t.Fatalf("capability %q category %q missing from manifest category metadata", cap.Name, cap.Category)+ }+ }+}++func TestCanonicalManifestDeclaresCapabilityTitles(t *testing.T) {+ for _, cap := range CanonicalManifest().Capabilities {+ if strings.TrimSpace(cap.Title) == "" {+ t.Fatalf("capability %q must declare a human-readable title", cap.Name)+ }+ if strings.EqualFold(strings.TrimSpace(cap.Title), strings.TrimSpace(cap.Name)) {+ t.Fatalf("capability %q title must be display copy, got %q", cap.Name, cap.Title)+ }+ }+}++func TestCanonicalManifestDeclaresStructuredOutputSchemasForJSONResponses(t *testing.T) {+ manifest := CanonicalManifest()+ byName := map[string]Capability{}+ for _, cap := range manifest.Capabilities {+ byName[cap.Name] = cap+ if !IsRequestResponseCapability(cap) || strings.TrimSpace(cap.ResponseShape) == "" {+ continue+ }+ if len(cap.OutputSchema) == 0 {+ t.Errorf("capability %q responseShape %q must declare outputSchema for structured tool results", cap.Name, cap.ResponseShape)+ continue+ }+ var schema map[string]any+ if err := json.Unmarshal(cap.OutputSchema, &schema); err != nil {+ t.Errorf("capability %q outputSchema must be valid JSON: %v", cap.Name, err)+ continue+ }+ if schema["type"] != "object" {+ t.Errorf("capability %q outputSchema type = %v, want object", cap.Name, schema["type"])+ }+ props, _ := schema["properties"].(map[string]any)+ if strings.HasSuffix(strings.TrimSpace(cap.ResponseShape), "[]") {+ if _, ok := props["items"]; !ok {+ t.Errorf("array-returning capability %q must declare items for the structured content wrapper: %v", cap.Name, props)+ }+ if _, ok := props["count"]; !ok {+ t.Errorf("array-returning capability %q must declare count for the structured content wrapper: %v", cap.Name, props)+ }+ if !schemaRequiredContains(schema, "items") || !schemaRequiredContains(schema, "count") {+ t.Errorf("array-returning capability %q outputSchema required = %v, want items and count", cap.Name, schema["required"])+ }+ }+ }++ for name, fragments := range map[string][]string{+ "list_nodes": {`"items"`, `"count"`},+ "discover_lan": {`"servers"`, `"structured_errors"`, `"cached"`},+ "test_node_credentials": {`"status"`, `"message"`},+ "refresh_node_cluster_membership": {`"clusterNodes"`, `"nodesAdded"`},+ ListFindingsCapabilityName: {`"items"`, `"count"`},+ AcknowledgeFindingCapabilityName: {`"success"`, `"message"`},+ OperationsLoopStatusCapabilityName: {+ `"steps"`,+ `Four-stage Patrol, Assistant, governance, and verification status rollup`,+ `Assistant counts contextual collaboration`,+ `External-agent readiness is exposed separately through externalAgentReady`,+ `Count-only evidence that the Patrol control journey reached a verified Patrol work result`,+ `Compatibility alias for patrolControlResolvedOperationsLoopCount`,+ `one non-expired API token covers every scope required by the published Pulse MCP Patrol work capability set`,+ },+ PlanActionCapabilityName: {`"actionId"`, `"planHash"`},+ DecideActionCapabilityName: {`"approval"`, `"audit"`},+ ExecuteActionCapabilityName: {`"result"`, `"audit"`},+ } {+ cap, ok := byName[name]+ if !ok {+ t.Fatalf("manifest missing capability %q", name)+ }+ raw, err := json.Marshal(cap.OutputSchema)+ if err != nil {+ t.Fatalf("%s outputSchema marshal: %v", name, err)+ }+ text := string(raw)+ for _, fragment := range fragments {+ if !strings.Contains(text, fragment) {+ t.Errorf("%s outputSchema missing %s: %s", name, fragment, text)+ }+ }+ }+}++func TestCanonicalManifestRequiredScopesReflectCapabilities(t *testing.T) {+ manifest := CanonicalManifest()+ want := RequiredCapabilityScopes(manifest.Capabilities)+ if strings.Join(manifest.RequiredScopes, "\n") != strings.Join(want, "\n") {+ t.Fatalf("CanonicalManifest RequiredScopes = %v, want %v", manifest.RequiredScopes, want)+ }+}++func TestCanonicalManifestScopesUseAuthVocabulary(t *testing.T) {+ known := map[string]bool{}+ for _, scope := range auth.AllKnownScopes {+ known[scope] = true+ }++ for _, cap := range CanonicalManifest().Capabilities {+ if !known[cap.Scope] {+ t.Errorf("capability %q scope = %q, want auth-owned scope vocabulary", cap.Name, cap.Scope)+ }+ }+}++func TestCanonicalManifestScopeDeclarationsStayPinnedToAuthConstants(t *testing.T) {+ source, err := os.ReadFile("manifest.go")+ if err != nil {+ t.Fatalf("read manifest.go: %v", err)+ }+ text := string(source)++ for _, required := range []string{+ `agentCapabilityScopeMonitoringRead = auth.ScopeMonitoringRead`,+ `agentCapabilityScopeMonitoringWrite = auth.ScopeMonitoringWrite`,+ `agentCapabilityScopeSettingsRead = auth.ScopeSettingsRead`,+ `agentCapabilityScopeSettingsWrite = auth.ScopeSettingsWrite`,+ `agentCapabilityScopeAIExecute = auth.ScopeAIExecute`,+ } {+ if !strings.Contains(text, required) {+ t.Fatalf("agent capabilities manifest must declare scope aliases from pkg/auth; missing %s", required)+ }+ }++ if strings.Contains(text, `Scope: "`) || strings.Contains(text, `Scope: "`) {+ t.Fatal("agent capabilities manifest scopes must use auth-owned constants, not literal strings")+ }+}++func schemaRequiredContains(schema map[string]any, want string) bool {+ required, _ := schema["required"].([]any)+ for _, raw := range required {+ if raw == want {+ return true+ }+ }+ return false+}++func containsString(values []string, want string) bool {+ for _, value := range values {+ if value == want {+ return true+ }+ }+ return false+}diff --git a/internal/agentcapabilities/markdown.go b/internal/agentcapabilities/markdown.gonew file mode 100644index 0000000000..d898292a06--- /dev/null+++ b/internal/agentcapabilities/markdown.go@@ -0,0 +1,640 @@+package agentcapabilities++import (+ "fmt"+ "sort"+ "strings"+)++const (+ // PulseIntelligenceOverviewStartMarker and+ // PulseIntelligenceOverviewEndMarker delimit the manifest-derived public+ // Pulse Intelligence surface relationship in docs/AI.md.+ PulseIntelligenceOverviewStartMarker = "<!-- pulse-intelligence-overview:start -->"+ PulseIntelligenceOverviewEndMarker = "<!-- pulse-intelligence-overview:end -->"++ // MCPReadmeSurfaceContractStartMarker and+ // MCPReadmeSurfaceContractEndMarker delimit the manifest-derived Pulse+ // Intelligence surface relationship in cmd/pulse-mcp/README.md.+ MCPReadmeSurfaceContractStartMarker = "<!-- pulse-mcp-surface-contract:start -->"+ MCPReadmeSurfaceContractEndMarker = "<!-- pulse-mcp-surface-contract:end -->"++ // MCPReadmeScopeListStartMarker and MCPReadmeScopeListEndMarker delimit+ // the manifest-derived scope list in cmd/pulse-mcp/README.md.+ MCPReadmeScopeListStartMarker = "<!-- pulse-mcp-scope-list:start -->"+ MCPReadmeScopeListEndMarker = "<!-- pulse-mcp-scope-list:end -->"++ // MCPReadmeClientConfigStartMarker and MCPReadmeClientConfigEndMarker+ // delimit the manifest-derived client setup examples in+ // cmd/pulse-mcp/README.md.+ MCPReadmeClientConfigStartMarker = "<!-- pulse-mcp-client-config:start -->"+ MCPReadmeClientConfigEndMarker = "<!-- pulse-mcp-client-config:end -->"++ // MCPReadmeToolInventoryStartMarker and MCPReadmeToolInventoryEndMarker+ // delimit the manifest-derived request/response tool inventory in+ // cmd/pulse-mcp/README.md.+ MCPReadmeToolInventoryStartMarker = "<!-- pulse-mcp-tools:start -->"+ MCPReadmeToolInventoryEndMarker = "<!-- pulse-mcp-tools:end -->"++ // MCPReadmePromptInventoryStartMarker and+ // MCPReadmePromptInventoryEndMarker delimit the manifest-derived workflow+ // prompt inventory in cmd/pulse-mcp/README.md.+ MCPReadmePromptInventoryStartMarker = "<!-- pulse-mcp-prompts:start -->"+ MCPReadmePromptInventoryEndMarker = "<!-- pulse-mcp-prompts:end -->"++ // MCPReadmeErrorInventoryStartMarker and+ // MCPReadmeErrorInventoryEndMarker delimit the manifest-derived stable+ // error-code inventory in cmd/pulse-mcp/README.md.+ MCPReadmeErrorInventoryStartMarker = "<!-- pulse-mcp-errors:start -->"+ MCPReadmeErrorInventoryEndMarker = "<!-- pulse-mcp-errors:end -->"+)++// RequiredScopeMarkdownList formats a manifest-owned scope set for+// operator-facing setup docs.+func RequiredScopeMarkdownList(scopes []string) string {+ scopes = NormalizeRequiredScopes(scopes)+ if len(scopes) == 0 {+ return "no scopes"+ }+ return markdownInlineCodeList(scopes)+}++// RequiredCapabilityScopeMarkdownList formats the capability-derived scope set+// for compatibility with older manifest payloads and tests.+func RequiredCapabilityScopeMarkdownList(capabilities []Capability) string {+ return RequiredScopeMarkdownList(RequiredCapabilityScopes(capabilities))+}++// ManifestRequiredScopeMarkdownList formats the manifest-owned requiredScopes+// summary for operator-facing setup docs. Older manifests fall back to the+// capability rows.+func ManifestRequiredScopeMarkdownList(manifest Manifest) string {+ if scopes := RequiredScopeMarkdownList(manifest.RequiredScopes); scopes != "no scopes" {+ return scopes+ }+ return RequiredCapabilityScopeMarkdownList(manifest.Capabilities)+}++// MCPClientConfigMarkdown renders manifest-owned Pulse MCP setup examples. The+// surrounding README can explain installation, but command, flag, token-env,+// server-name, and config-family facts come from the discovery contract.+func MCPClientConfigMarkdown(adapter MCPAdapterContract) string {+ adapter = NormalizeMCPAdapterContract(adapter)+ families := adapter.ConfigFamilies++ lines := []string{+ fmt.Sprintf("Most MCP clients need the same manifest-owned runtime facts: server name `%s`, command `%s`, base URL flag `%s`, default URL `%s`, and token environment variable `%s`.", adapter.ServerName, adapter.Command, adapter.BaseURLFlag, adapter.DefaultBaseURL, adapter.TokenEnv),+ }+ if familyList := mcpAdapterConfigFamilyMarkdownList(families); familyList != "" {+ lines = append(lines, fmt.Sprintf("The generated examples below cover the currently declared config families: %s.", familyList))+ }+ lines = append(lines,+ "If your client uses a different outer config format, keep those runtime facts and adapt only the wrapper.",+ "",+ )++ if family := firstMCPAdapterConfigFamilyByShape(families, MCPAdapterConfigShapeOpenCodeMCP); family != nil {+ lines = append(lines, mcpOpenCodeConfigMarkdown(adapter, *family), "")+ }+ if family := firstMCPAdapterConfigFamilyByShape(families, MCPAdapterConfigShapeMCPServers); family != nil {+ lines = append(lines, mcpServersConfigMarkdown(adapter, *family), "")+ }+ if family := firstMCPAdapterConfigFamilyByShape(families, MCPAdapterConfigShapeCustom); family != nil {+ lines = append(lines, mcpCustomClientConfigMarkdown(adapter, *family), "")+ }++ return strings.TrimSpace(strings.Join(lines, "\n"))+}++func mcpAdapterConfigFamilyMarkdownList(families []MCPAdapterConfigFamily) string {+ labels := make([]string, 0, len(families))+ for _, family := range families {+ if label := strings.TrimSpace(family.Label); label != "" {+ labels = append(labels, "`"+label+"`")+ }+ }+ return markdownInlineList(labels)+}++func firstMCPAdapterConfigFamilyByShape(families []MCPAdapterConfigFamily, shape string) *MCPAdapterConfigFamily {+ for i := range families {+ if families[i].Shape == shape {+ return &families[i]+ }+ }+ return nil+}++func mcpOpenCodeConfigMarkdown(adapter MCPAdapterContract, family MCPAdapterConfigFamily) string {+ fileHints := markdownInlineList(markdownCodeValues(family.FileHints))+ if fileHints == "" {+ fileHints = "`opencode.json` or `opencode.jsonc`"+ }+ description := strings.TrimSpace(family.Description)+ if description == "" {+ description = "Uses OpenCode's top-level `mcp` object."+ }+ return strings.Join([]string{+ fmt.Sprintf("#### %s", strings.TrimSpace(family.Label)),+ "",+ description,+ fmt.Sprintf("Add this to %s:", fileHints),+ "",+ "```json",+ fmt.Sprintf(`{+ "$schema": "https://opencode.ai/config.json",+ "mcp": {+ "%s": {+ "type": "local",+ "command": ["%s", "%s", "%s"],+ "enabled": true,+ "environment": {+ "%s": "your-token-here"+ }+ }+ }+}`, adapter.ServerName, adapter.Command, adapter.BaseURLFlag, adapter.DefaultBaseURL, adapter.TokenEnv),+ "```",+ "",+ fmt.Sprintf("Restart OpenCode or reload its config after saving. Pulse tools appear under the `%s` MCP server name.", adapter.ServerName),+ }, "\n")+}++func mcpServersConfigMarkdown(adapter MCPAdapterContract, family MCPAdapterConfigFamily) string {+ fileHints := markdownInlineList(markdownCodeValues(family.FileHints))+ if fileHints == "" {+ fileHints = "`mcpServers` client config"+ }+ description := strings.TrimSpace(family.Description)+ if description == "" {+ description = "Uses the common `mcpServers` object."+ }+ clientLabels := markdownInlineList(markdownCodeValues(family.ClientLabels))+ if clientLabels == "" {+ clientLabels = strings.TrimSpace(family.Label)+ }+ return strings.Join([]string{+ fmt.Sprintf("#### %s", strings.TrimSpace(family.Label)),+ "",+ description,+ fmt.Sprintf("Use this shape for %s in %s:", clientLabels, fileHints),+ "",+ "```json",+ fmt.Sprintf(`{+ "mcpServers": {+ "%s": {+ "command": "%s",+ "args": ["%s", "%s"],+ "env": {+ "%s": "your-token-here"+ }+ }+ }+}`, adapter.ServerName, adapter.Command, adapter.BaseURLFlag, adapter.DefaultBaseURL, adapter.TokenEnv),+ "```",+ "",+ fmt.Sprintf("Restart your client after saving the config. If the client cannot resolve `%s` from `PATH`, use the full binary path.", adapter.Command),+ }, "\n")+}++func mcpCustomClientConfigMarkdown(adapter MCPAdapterContract, family MCPAdapterConfigFamily) string {+ description := strings.TrimSpace(family.Description)+ if description == "" {+ description = "Keep the Pulse MCP runtime facts and adapt the outer config shape to the client."+ }+ return strings.Join([]string{+ fmt.Sprintf("#### %s", strings.TrimSpace(family.Label)),+ "",+ description,+ fmt.Sprintf("Use command `%s`, pass `%s %s`, set `%s` to the API token, and keep the server name `%s` when the client asks for one.", adapter.Command, adapter.BaseURLFlag, adapter.DefaultBaseURL, adapter.TokenEnv, adapter.ServerName),+ }, "\n")+}++func markdownCodeValues(values []string) []string {+ out := make([]string, 0, len(values))+ for _, value := range values {+ if trimmed := strings.TrimSpace(value); trimmed != "" {+ out = append(out, "`"+trimmed+"`")+ }+ }+ return out+}++// PulseIntelligenceOverviewMarkdown renders the public docs overview of the+// manifest-owned relationship between Pulse Intelligence Core, Patrol,+// Assistant, and Pulse MCP. The docs can add product detail around this block,+// but the surface labels and descriptions stay manifest-backed.+func PulseIntelligenceOverviewMarkdown(contract SurfaceContract) string {+ contract = CloneSurfaceContract(contract)+ coreLabel := strings.TrimSpace(contract.Core.Label)+ if coreLabel == "" {+ coreLabel = "Pulse Intelligence Core"+ }+ coreDescription := strings.TrimSpace(contract.Core.Description)+ if coreDescription == "" {+ coreDescription = "Canonical context, governed actions, safety gates, approval state, action audit, and verification."+ }++ surfaces := nonEmptyOperatorSurfaces(contract.OperatorSurfaces)+ lines := []string{+ fmt.Sprintf("Pulse Intelligence is built around a shared **%s**: %s", coreLabel, coreDescription),+ "",+ }++ if primaryLabel := strings.TrimSpace(contract.ProactiveEngine.Label); primaryLabel != "" {+ accessPathPhrase := pulseIntelligenceAccessPathPhrase(surfaces)+ lines = append(lines,+ fmt.Sprintf("That core is deliberately surfaced with %s as the primary built-in operator and %s as access paths over the same governed capabilities:", pulseIntelligenceShortSurfaceLabel(primaryLabel), accessPathPhrase),+ "",+ fmt.Sprintf("1. **%s**: %s", primaryLabel, primaryOperatorOverviewDescription(contract.ProactiveEngine, coreLabel)),+ )+ for i, surface := range surfaces {+ lines = append(lines, fmt.Sprintf("%d. **%s**: %s", i+2, strings.TrimSpace(surface.Label), operatorSurfaceOverviewDescription(surface, coreLabel)))+ }+ } else {+ lines = append(lines,+ fmt.Sprintf("That core is deliberately surfaced in %s supported operator-facing %s:", markdownCountWord(len(surfaces)), pluralize("surface", len(surfaces))),+ "",+ )+ if len(surfaces) == 0 {+ lines = append(lines, "- Supported operator-facing surfaces are declared by the agent capabilities manifest.")+ } else {+ for i, surface := range surfaces {+ lines = append(lines, fmt.Sprintf("%d. **%s**: %s", i+1, strings.TrimSpace(surface.Label), operatorSurfaceOverviewDescription(surface, coreLabel)))+ }+ }+ }+ return strings.Join(lines, "\n")+}++func pulseIntelligenceAccessPathPhrase(surfaces []OperatorSurfaceContract) string {+ labels := make([]string, 0, len(surfaces))+ for _, surface := range surfaces {+ label := pulseIntelligenceShortSurfaceLabel(surface.Label)+ if label != "" {+ labels = append(labels, label)+ }+ }+ if len(labels) == 0 {+ return "declared surfaces"+ }+ return strings.Join(labels, " plus ")+}++func pulseIntelligenceShortSurfaceLabel(label string) string {+ label = strings.TrimSpace(label)+ if strings.HasPrefix(label, "Pulse ") {+ return strings.TrimSpace(strings.TrimPrefix(label, "Pulse "))+ }+ return label+}++func primaryOperatorOverviewDescription(component SurfaceContractComponent, coreLabel string) string {+ description := strings.TrimSpace(component.Description)+ if description == "" {+ return fmt.Sprintf("The first-party operations surface running on %s.", coreLabel)+ }+ return description+}++func nonEmptyOperatorSurfaces(surfaces []OperatorSurfaceContract) []OperatorSurfaceContract {+ out := make([]OperatorSurfaceContract, 0, len(surfaces))+ for _, surface := range surfaces {+ if strings.TrimSpace(surface.Label) == "" {+ continue+ }+ out = append(out, surface)+ }+ return out+}++func operatorSurfaceOverviewDescription(surface OperatorSurfaceContract, coreLabel string) string {+ description := strings.TrimSpace(surface.Description)+ if description == "" {+ description = fmt.Sprintf("%s over %s.", operatorSurfaceContractRole(surface), coreLabel)+ }+ return appendSurfaceAffordanceSentence(description, surface)+}++func markdownCountWord(count int) string {+ switch count {+ case 0:+ return "zero"+ case 1:+ return "one"+ case 2:+ return "two"+ case 3:+ return "three"+ case 4:+ return "four"+ case 5:+ return "five"+ default:+ return fmt.Sprintf("%d", count)+ }+}++func pluralize(word string, count int) string {+ if count == 1 {+ return word+ }+ return word + "s"+}++// MCPSurfaceContractMarkdown renders the manifest-owned relationship between+// Pulse Intelligence Core, Patrol, Assistant, and Pulse MCP for MCP onboarding+// docs. It intentionally uses the same surface contract as the runtime+// initialize instructions so external-agent docs cannot drift from the API+// manifest.+func MCPSurfaceContractMarkdown(contract SurfaceContract) string {+ core := contract.Core+ coreLabel := strings.TrimSpace(core.Label)+ if coreLabel == "" {+ coreLabel = "Pulse Intelligence Core"+ }+ coreDescription := strings.TrimSpace(core.Description)+ if coreDescription == "" {+ coreDescription = "The shared context, governed tool, safety gate, approval, audit, and verification substrate."+ }++ lines := []string{+ fmt.Sprintf("- **%s**: %s", coreLabel, coreDescription),+ }++ if proactiveLabel := strings.TrimSpace(contract.ProactiveEngine.Label); proactiveLabel != "" {+ description := strings.TrimSpace(contract.ProactiveEngine.Description)+ if description == "" {+ description = fmt.Sprintf("The primary built-in operator running on %s.", coreLabel)+ }+ lines = append(lines, fmt.Sprintf("- **%s**: %s", proactiveLabel, description))+ }++ surfaces := CloneSurfaceContract(contract).OperatorSurfaces+ for _, surface := range surfaces {+ label := strings.TrimSpace(surface.Label)+ if label == "" {+ continue+ }+ description := strings.TrimSpace(surface.Description)+ description = appendSurfaceAffordanceSentence(description, surface)+ role := operatorSurfaceContractRole(surface)+ switch {+ case description != "" && surfaceDescriptionStartsWithRole(description, role):+ lines = append(lines, fmt.Sprintf("- **%s**: %s", label, description))+ case description != "":+ lines = append(lines, fmt.Sprintf("- **%s** (%s): %s", label, role, description))+ default:+ lines = append(lines, fmt.Sprintf("- **%s**: %s over %s.", label, role, coreLabel))+ }+ }++ if len(lines) == 1 {+ lines = append(lines, "- **Pulse MCP**: The external-agent adapter over the same manifest-backed Pulse Intelligence capabilities.")+ }+ return strings.Join(lines, "\n")+}++func appendSurfaceAffordanceSentence(description string, surface OperatorSurfaceContract) string {+ description = strings.TrimSpace(description)+ affordances := SurfaceAffordanceLabels(NormalizeSurfaceAffordances(surface))+ if len(affordances) == 0 {+ return description+ }+ affordanceSentence := fmt.Sprintf("Affordances: %s.", oxfordJoin(affordances))+ if description == "" {+ return affordanceSentence+ }+ return strings.TrimRight(description, ".") + ". " + affordanceSentence+}++func surfaceDescriptionStartsWithRole(description, role string) bool {+ description = strings.ToLower(strings.TrimSpace(description))+ role = strings.ToLower(strings.TrimSpace(role))+ return role != "" && strings.HasPrefix(description, role)+}++// MCPToolCapabilityInventoryMarkdown renders the Pulse MCP request/response+// tool inventory from the manifest-owned Pulse MCP surface contract. Streaming+// capabilities such as subscribe_events, and raw manifest capabilities omitted+// from the Pulse MCP surface, are intentionally excluded because MCP exposes+// only the shared surface-tool allowlist through tools/list and tools/call.+func MCPToolCapabilityInventoryMarkdown(manifest Manifest) string {+ return mcpToolCapabilityInventoryMarkdown(ManifestSurfaceToolCapabilities(manifest, SurfaceIDPulseMCP))+}++func mcpToolCapabilityInventoryMarkdown(capabilities []Capability) string {+ categories := CloneCapabilityCategories(canonicalManifest.Categories)+ groups := make(map[string][]Capability)+ for _, cap := range capabilities {+ if !IsRequestResponseCapability(cap) {+ continue+ }+ category := strings.TrimSpace(cap.Category)+ if category == "" {+ category = "uncategorized"+ }+ groups[category] = append(groups[category], CloneCapability(cap))+ }+ if len(groups) == 0 {+ return "No request/response MCP tools are currently advertised by the manifest."+ }++ orderedCategories := orderedMCPCapabilityCategories(groups, categories)+ sections := make([]string, 0, len(orderedCategories))+ for _, category := range orderedCategories {+ var b strings.Builder+ fmt.Fprintf(&b, "**%s:**\n\n", mcpCapabilityCategoryHeading(category, categories))+ for _, cap := range groups[category] {+ description := strings.TrimSpace(cap.Description)+ if description == "" {+ description = "Manifest-backed Pulse capability."+ }+ fmt.Fprintf(&b, "- `%s` (%s): %s\n", cap.Name, mcpCapabilityMetadataMarkdown(cap), description)+ }+ sections = append(sections, strings.TrimRight(b.String(), "\n"))+ }+ return strings.Join(sections, "\n\n")+}++// MCPPromptInventoryMarkdown renders the MCP workflow prompt inventory from the+// same manifest-owned surface affordance gate and catalogue projection used by+// prompts/list.+func MCPPromptInventoryMarkdown(manifest Manifest) string {+ if !MCPManifestSurfacePromptProjectionSupported(manifest, SurfaceIDPulseMCP) {+ return "No MCP workflow prompts are currently advertised by the manifest."+ }++ prompts := ProjectMCPWorkflowPrompts(ManifestPulseWorkflowPrompts(manifest))+ if len(prompts) == 0 {+ return "No MCP workflow prompts are currently advertised by the manifest."+ }++ lines := make([]string, 0, len(prompts))+ for _, prompt := range prompts {+ description := strings.TrimSpace(prompt.Description)+ if description == "" {+ description = "Manifest-backed Pulse workflow prompt."+ }+ metadata := make([]string, 0, 2)+ if label := strings.TrimSpace(prompt.Title); label != "" {+ metadata = append(metadata, label)+ }+ arguments := mcpPromptArgumentsMarkdown(prompt.Arguments)+ if arguments != "" {+ metadata = append(metadata, arguments)+ }+ if len(metadata) > 0 {+ lines = append(lines, fmt.Sprintf("- `%s` (%s): %s", prompt.Name, strings.Join(metadata, "; "), description))+ continue+ }+ lines = append(lines, fmt.Sprintf("- `%s`: %s", prompt.Name, description))+ }+ return strings.Join(lines, "\n")+}++// MCPErrorCodeInventoryMarkdown renders the manifest-advertised+// capability-specific stable error codes used by Pulse MCP docs. It follows+// the same manifest-owned Pulse MCP surface contract as tools/list so omitted+// raw manifest capabilities do not appear as documented MCP tools.+func MCPErrorCodeInventoryMarkdown(manifest Manifest) string {+ lines := make([]string, 0)+ for _, cap := range ManifestSurfaceToolCapabilities(manifest, SurfaceIDPulseMCP) {+ name := strings.TrimSpace(cap.Name)+ errorCodes := mcpCapabilityErrorCodes(cap)+ if name == "" || len(errorCodes) == 0 {+ continue+ }+ lines = append(lines, fmt.Sprintf("- `%s`: %s", name, markdownInlineCodeList(errorCodes)))+ }+ if len(lines) == 0 {+ return "No capability-specific stable error codes are currently advertised by the manifest."+ }+ return strings.Join(lines, "\n")+}++func orderedMCPCapabilityCategories(groups map[string][]Capability, categories []CapabilityCategory) []string {+ known := make(map[string]bool, len(categories))+ ordered := make([]string, 0, len(groups))+ for _, category := range categories {+ id := strings.TrimSpace(category.ID)+ if id == "" {+ continue+ }+ known[id] = true+ if len(groups[id]) > 0 {+ ordered = append(ordered, id)+ }+ }++ unknown := make([]string, 0)+ for category := range groups {+ if known[category] {+ continue+ }+ unknown = append(unknown, category)+ }+ sort.Strings(unknown)+ return append(ordered, unknown...)+}++func mcpCapabilityCategoryHeading(category string, categories []CapabilityCategory) string {+ for _, descriptor := range categories {+ if strings.TrimSpace(descriptor.ID) == category {+ if label := strings.TrimSpace(descriptor.Label); label != "" {+ return label+ }+ return category+ }+ }+ if category == "uncategorized" {+ return "Uncategorized"+ }+ return category+}++func mcpCapabilityMetadataMarkdown(cap Capability) string {+ governance := NormalizeCapabilityGovernance(cap)+ metadata := []string{}+ if title := CapabilityTitle(cap); title != "" {+ metadata = append(metadata, title)+ }+ method := strings.TrimSpace(cap.Method)+ path := strings.TrimSpace(cap.Path)+ switch {+ case method != "" && path != "":+ metadata = append(metadata, markdownInlineCode(method+" "+path))+ case path != "":+ metadata = append(metadata, markdownInlineCode(path))+ case method != "":+ metadata = append(metadata, markdownInlineCode(method))+ }+ if scope := strings.TrimSpace(cap.Scope); scope != "" {+ metadata = append(metadata, "scope "+markdownInlineCode(scope))+ }+ metadata = append(metadata, "mode "+markdownInlineCode(string(governance.ActionMode)))+ metadata = append(metadata, "approval "+markdownInlineCode(string(governance.ApprovalPolicy)))+ return strings.Join(metadata, ", ")+}++func mcpPromptArgumentsMarkdown(args []MCPPromptArgument) string {+ if len(args) == 0 {+ return ""+ }+ parts := make([]string, 0, len(args))+ for _, arg := range args {+ name := strings.TrimSpace(arg.Name)+ if name == "" {+ continue+ }+ if arg.Required {+ parts = append(parts, "required argument "+markdownInlineCode(name))+ continue+ }+ parts = append(parts, "optional argument "+markdownInlineCode(name))+ }+ return strings.Join(parts, ", ")+}++func mcpCapabilityErrorCodes(cap Capability) []string {+ seen := make(map[string]bool, len(cap.ErrorCodes))+ errorCodes := make([]string, 0, len(cap.ErrorCodes))+ for _, code := range cap.ErrorCodes {+ code = strings.TrimSpace(code)+ if code == "" || seen[code] {+ continue+ }+ seen[code] = true+ errorCodes = append(errorCodes, code)+ }+ return errorCodes+}++func markdownInlineCodeList(values []string) string {+ quoted := make([]string, 0, len(values))+ for _, value := range values {+ value = strings.TrimSpace(value)+ if value == "" {+ continue+ }+ quoted = append(quoted, markdownInlineCode(value))+ }+ if len(quoted) == 0 {+ return "none"+ }+ return oxfordJoin(quoted)+}++func markdownInlineList(values []string) string {+ trimmed := make([]string, 0, len(values))+ for _, value := range values {+ if value = strings.TrimSpace(value); value != "" {+ trimmed = append(trimmed, value)+ }+ }+ return oxfordJoin(trimmed)+}++func markdownInlineCode(value string) string {+ return "`" + strings.ReplaceAll(value, "`", "'") + "`"+}diff --git a/internal/agentcapabilities/markdown_test.go b/internal/agentcapabilities/markdown_test.gonew file mode 100644index 0000000000..7669ec2080--- /dev/null+++ b/internal/agentcapabilities/markdown_test.go@@ -0,0 +1,376 @@+package agentcapabilities++import (+ "strings"+ "testing"+)++func TestRequiredCapabilityScopeMarkdownListUsesManifestScopeSummary(t *testing.T) {+ got := RequiredCapabilityScopeMarkdownList([]Capability{+ {Name: "settings_write", Scope: "settings:write"},+ {Name: "monitoring_read", Scope: "monitoring:read"},+ {Name: "ai_execute", Scope: "ai:execute"},+ {Name: "duplicate_monitoring_read", Scope: "monitoring:read"},+ })+ want := "`monitoring:read`, `settings:write`, and `ai:execute`"+ if got != want {+ t.Fatalf("scope markdown list = %q, want %q", got, want)+ }+}++func TestManifestRequiredScopeMarkdownListPrefersRequiredScopes(t *testing.T) {+ got := ManifestRequiredScopeMarkdownList(Manifest{+ RequiredScopes: []string{+ "settings:write",+ "monitoring:read",+ "ai:execute",+ "monitoring:read",+ },+ Capabilities: []Capability{+ {Name: "legacy_extra", Scope: "monitoring:write"},+ },+ })+ want := "`monitoring:read`, `settings:write`, and `ai:execute`"+ if got != want {+ t.Fatalf("manifest scope markdown list = %q, want %q", got, want)+ }+}++func TestManifestRequiredScopeMarkdownListFallsBackForLegacyManifest(t *testing.T) {+ got := ManifestRequiredScopeMarkdownList(Manifest{+ Capabilities: []Capability{+ {Name: "settings_write", Scope: "settings:write"},+ {Name: "monitoring_read", Scope: "monitoring:read"},+ },+ })+ want := "`monitoring:read` and `settings:write`"+ if got != want {+ t.Fatalf("legacy manifest scope markdown list = %q, want %q", got, want)+ }+}++func TestMCPClientConfigMarkdownProjectsManifestAdapterContract(t *testing.T) {+ got := MCPClientConfigMarkdown(CanonicalManifest().MCPAdapter)++ for _, expected := range []string{+ "server name `pulse`, command `pulse-mcp`, base URL flag `--base-url`, default URL `http://localhost:7655`, and token environment variable `PULSE_API_TOKEN`",+ "currently declared config families: `OpenCode`, `Claude-style clients`, and `custom MCP clients`",+ "#### OpenCode",+ `"command": ["pulse-mcp", "--base-url", "http://localhost:7655"]`,+ `"PULSE_API_TOKEN": "your-token-here"`,+ "#### Claude-style clients",+ `"mcpServers": {`,+ `"args": ["--base-url", "http://localhost:7655"]`,+ "#### custom MCP clients",+ "Use command `pulse-mcp`, pass `--base-url http://localhost:7655`, set `PULSE_API_TOKEN` to the API token, and keep the server name `pulse`",+ } {+ if !strings.Contains(got, expected) {+ t.Fatalf("MCP client config markdown missing %q:\n%s", expected, got)+ }+ }+}++func TestMCPClientConfigMarkdownFallsBackForLegacyManifest(t *testing.T) {+ got := MCPClientConfigMarkdown(MCPAdapterContract{})++ for _, expected := range []string{+ "command `pulse-mcp`",+ "base URL flag `--base-url`",+ "token environment variable `PULSE_API_TOKEN`",+ "#### OpenCode",+ "#### Claude-style clients",+ } {+ if !strings.Contains(got, expected) {+ t.Fatalf("legacy MCP client config markdown missing %q:\n%s", expected, got)+ }+ }+}++func TestPulseIntelligenceOverviewMarkdownProjectsManifestSurfaceContract(t *testing.T) {+ got := PulseIntelligenceOverviewMarkdown(CanonicalManifest().SurfaceContract)++ for _, expected := range []string{+ "shared **Pulse Intelligence Core**: Canonical context, governed actions, safety gates, approval state, action audit, and verification shared by Pulse Assistant, Pulse MCP, and Pulse Patrol.",+ "Patrol as the primary built-in operator and Assistant plus MCP as access paths",+ "1. **Pulse Patrol**: Patrol is the first-party operations surface: it watches, investigates, acts within the chosen Patrol mode, verifies outcomes, and records what happened.",+ "2. **Pulse Assistant**: The contextual explanation, approval, and handoff surface for Patrol findings, governed actions, verification, and operator questions. Affordances: tools and interactive questions.",+ "3. **Pulse MCP**: The external-agent adapter that projects canonical Pulse Intelligence capabilities as MCP tools. Affordances: tools, resources, prompts, and capability metadata.",+ } {+ if !strings.Contains(got, expected) {+ t.Fatalf("overview markdown missing %q:\n%s", expected, got)+ }+ }+}++func TestPulseIntelligenceOverviewMarkdownFallsBackForLegacyManifest(t *testing.T) {+ got := PulseIntelligenceOverviewMarkdown(SurfaceContract{})++ for _, expected := range []string{+ "shared **Pulse Intelligence Core**: Canonical context, governed actions, safety gates, approval state, action audit, and verification.",+ "zero supported operator-facing surfaces",+ "Supported operator-facing surfaces are declared by the agent capabilities manifest.",+ } {+ if !strings.Contains(got, expected) {+ t.Fatalf("legacy overview markdown missing %q:\n%s", expected, got)+ }+ }+}++func TestMCPSurfaceContractMarkdownProjectsManifestSurfaceContract(t *testing.T) {+ got := MCPSurfaceContractMarkdown(CanonicalManifest().SurfaceContract)++ for _, expected := range []string{+ "**Pulse Intelligence Core**: Canonical context, governed actions, safety gates, approval state, action audit, and verification shared by Pulse Assistant, Pulse MCP, and Pulse Patrol.",+ "**Pulse Patrol**: Patrol is the first-party operations surface: it watches, investigates, acts within the chosen Patrol mode, verifies outcomes, and records what happened.",+ "**Pulse Assistant** (the native Pulse surface): The contextual explanation, approval, and handoff surface for Patrol findings, governed actions, verification, and operator questions. Affordances: tools and interactive questions.",+ "**Pulse MCP**: The external-agent adapter that projects canonical Pulse Intelligence capabilities as MCP tools. Affordances: tools, resources, prompts, and capability metadata.",+ } {+ if !strings.Contains(got, expected) {+ t.Fatalf("surface contract markdown missing %q:\n%s", expected, got)+ }+ }+}++func TestMCPSurfaceContractMarkdownFallsBackForLegacyManifest(t *testing.T) {+ got := MCPSurfaceContractMarkdown(SurfaceContract{})++ for _, expected := range []string{+ "**Pulse Intelligence Core**: The shared context, governed tool, safety gate, approval, audit, and verification substrate.",+ "**Pulse MCP**: The external-agent adapter over the same manifest-backed Pulse Intelligence capabilities.",+ } {+ if !strings.Contains(got, expected) {+ t.Fatalf("legacy surface contract markdown missing %q:\n%s", expected, got)+ }+ }+}++func TestMCPToolCapabilityInventoryMarkdownProjectsManifestTools(t *testing.T) {+ got := MCPToolCapabilityInventoryMarkdown(Manifest{+ SurfaceContract: CanonicalManifest().SurfaceContract,+ SurfaceToolContracts: []SurfaceToolContract{{+ SurfaceID: SurfaceIDPulseMCP,+ ToolNames: []string{+ FleetContextCapabilityName,+ SetOperatorStateCapabilityName,+ EventSubscriptionCapabilityName,+ },+ }},+ Capabilities: []Capability{+ {+ Name: FleetContextCapabilityName,+ Title: "Fleet triage",+ Description: "Return a fleet triage rollup.",+ Category: "context",+ Method: "GET",+ Path: "/api/agent/fleet-context",+ Scope: "monitoring:read",+ ActionMode: ActionModeRead,+ ApprovalPolicy: ApprovalPolicyScopeOnly,+ },+ {+ Name: ResourceContextCapabilityName,+ Description: "Raw manifest capability omitted from Pulse MCP surface.",+ Category: "context",+ Method: "GET",+ Path: ResourceContextCapabilityPath,+ Scope: "monitoring:read",+ ActionMode: ActionModeRead,+ ApprovalPolicy: ApprovalPolicyScopeOnly,+ },+ {+ Name: EventSubscriptionCapabilityName,+ Description: "Stream events.",+ Category: "context",+ Method: "GET",+ Path: "/api/agent/events",+ Scope: "monitoring:read",+ ActionMode: ActionModeRead,+ ApprovalPolicy: ApprovalPolicyScopeOnly,+ },+ {+ Name: SetOperatorStateCapabilityName,+ Title: "Set operator state",+ Description: "Replace the operator-set state for a resource.",+ Category: "operator-state",+ Method: "PUT",+ Path: OperatorStateCapabilityPath,+ Scope: "monitoring:write",+ ActionMode: ActionModeWrite,+ ApprovalPolicy: ApprovalPolicyScopeOnly,+ },+ },+ })+ want := strings.Join([]string{+ "**Context (read-only):**",+ "",+ "- `get_fleet_context` (Fleet triage, `GET /api/agent/fleet-context`, scope `monitoring:read`, mode `read`, approval `scope_only`): Return a fleet triage rollup.",+ "",+ "**Operator state (per-resource intent):**",+ "",+ "- `set_operator_state` (Set operator state, `PUT /api/resources/{resourceId}/operator-state`, scope `monitoring:write`, mode `write`, approval `scope_only`): Replace the operator-set state for a resource.",+ }, "\n")+ if got != want {+ t.Fatalf("MCP tool inventory markdown:\n%s\nwant:\n%s", got, want)+ }+ if strings.Contains(got, EventSubscriptionCapabilityName) {+ t.Fatal("streaming subscribe_events capability must not render as a request/response MCP tool")+ }+ if strings.Contains(got, ResourceContextCapabilityName) {+ t.Fatal("raw manifest capability omitted from Pulse MCP surface contract must not render as an MCP tool")+ }+}++func TestMCPToolCapabilityInventoryMarkdownHandlesEmptyManifest(t *testing.T) {+ got := MCPToolCapabilityInventoryMarkdown(Manifest{})+ want := "No request/response MCP tools are currently advertised by the manifest."+ if got != want {+ t.Fatalf("empty inventory = %q, want %q", got, want)+ }+}++func TestMCPPromptInventoryMarkdownProjectsManifestPrompts(t *testing.T) {+ got := MCPPromptInventoryMarkdown(Manifest{+ SurfaceContract: CanonicalManifest().SurfaceContract,+ Capabilities: []Capability{+ {Name: FleetContextCapabilityName},+ {Name: ResourceContextCapabilityName},+ {Name: ListFindingsCapabilityName},+ },+ WorkflowPrompts: []PulseWorkflowPrompt{+ {+ Name: PulseWorkflowPromptTriageFleet,+ Label: "Triage fleet",+ Description: "Triage the Pulse fleet using the canonical fleet context capability, then choose where deeper investigation is warranted.",+ },+ {+ Name: PulseWorkflowPromptOperationsLoop,+ Label: "Ask Patrol to handle an issue",+ Description: "Have Patrol investigate active findings, follow the configured Patrol mode, take approved actions, verify the outcome, and record what happened.",+ },+ {+ Name: PulseWorkflowPromptInvestigateResource,+ Label: "Investigate resource",+ Description: "Investigate one Pulse resource using the canonical resource context capability and resource URI projection.",+ Arguments: []PulseWorkflowPromptArgument{{+ Name: ResourceIDArgumentName,+ Required: true,+ }},+ },+ {+ Name: PulseWorkflowPromptReviewFinding,+ Label: "Review finding",+ Description: "Review one Patrol finding and propose the safest governed next step.",+ Arguments: []PulseWorkflowPromptArgument{{+ Name: FindingIDArgumentName,+ Required: true,+ }},+ },+ },+ })+ want := strings.Join([]string{+ "- `pulse_triage_fleet` (Triage fleet): Triage the Pulse fleet using the canonical fleet context capability, then choose where deeper investigation is warranted.",+ "- `pulse_operations_loop` (Ask Patrol to handle an issue): Have Patrol investigate active findings, follow the configured Patrol mode, take approved actions, verify the outcome, and record what happened.",+ "- `pulse_investigate_resource` (Investigate resource; required argument `resourceId`): Investigate one Pulse resource using the canonical resource context capability and resource URI projection.",+ "- `pulse_review_finding` (Review finding; required argument `finding_id`): Review one Patrol finding and propose the safest governed next step.",+ }, "\n")+ if got != want {+ t.Fatalf("MCP prompt inventory markdown:\n%s\nwant:\n%s", got, want)+ }+}++func TestMCPPromptInventoryMarkdownHonorsSurfacePromptAffordance(t *testing.T) {+ got := MCPPromptInventoryMarkdown(Manifest{+ SurfaceContract: SurfaceContract{+ OperatorSurfaces: []OperatorSurfaceContract{{+ ID: SurfaceIDPulseMCP,+ Label: "Pulse MCP",+ Affordances: SurfaceAffordanceContract{Tools: true},+ }},+ },+ WorkflowPrompts: []PulseWorkflowPrompt{{+ Name: PulseWorkflowPromptTriageFleet,+ Label: "Triage fleet",+ Description: "Triage the Pulse fleet.",+ }},+ })+ want := "No MCP workflow prompts are currently advertised by the manifest."+ if got != want {+ t.Fatalf("prompt-disabled inventory = %q, want %q", got, want)+ }+}++func TestMCPPromptInventoryMarkdownHandlesExplicitEmptyPromptCatalogue(t *testing.T) {+ got := MCPPromptInventoryMarkdown(Manifest{+ SurfaceContract: CanonicalManifest().SurfaceContract,+ Capabilities: []Capability{+ {Name: FleetContextCapabilityName},+ {Name: ResourceContextCapabilityName},+ {Name: ListFindingsCapabilityName},+ },+ WorkflowPrompts: []PulseWorkflowPrompt{},+ })+ want := "No MCP workflow prompts are currently advertised by the manifest."+ if got != want {+ t.Fatalf("empty prompt inventory = %q, want %q", got, want)+ }+}++func TestMCPErrorCodeInventoryMarkdownProjectsManifestCodes(t *testing.T) {+ got := MCPErrorCodeInventoryMarkdown(Manifest{+ SurfaceContract: CanonicalManifest().SurfaceContract,+ SurfaceToolContracts: []SurfaceToolContract{{+ SurfaceID: SurfaceIDPulseMCP,+ ToolNames: []string{+ ResourceContextCapabilityName,+ PlanActionCapabilityName,+ EventSubscriptionCapabilityName,+ },+ }},+ Capabilities: []Capability{+ {+ Name: FleetContextCapabilityName,+ ErrorCodes: []string{"not_documented_for_this_surface"},+ },+ {+ Name: ResourceContextCapabilityName,+ ErrorCodes: []string{"resource_not_found"},+ },+ {+ Name: EventSubscriptionCapabilityName,+ ErrorCodes: []string{"sse_unavailable"},+ },+ {+ Name: PlanActionCapabilityName,+ ErrorCodes: []string{"invalid_action_request", "resource_not_found", "invalid_action_request", ""},+ },+ },+ })+ want := strings.Join([]string{+ "- `get_resource_context`: `resource_not_found`",+ "- `plan_action`: `invalid_action_request` and `resource_not_found`",+ }, "\n")+ if got != want {+ t.Fatalf("MCP error-code inventory markdown:\n%s\nwant:\n%s", got, want)+ }+ if strings.Contains(got, FleetContextCapabilityName) {+ t.Fatal("raw manifest capability omitted from Pulse MCP surface contract must not render MCP error codes")+ }+ if strings.Contains(got, EventSubscriptionCapabilityName) {+ t.Fatal("streaming subscribe_events capability must not render MCP tool error codes")+ }+}++func TestMCPErrorCodeInventoryMarkdownHandlesNoErrorCodes(t *testing.T) {+ got := MCPErrorCodeInventoryMarkdown(Manifest{+ SurfaceContract: CanonicalManifest().SurfaceContract,+ SurfaceToolContracts: []SurfaceToolContract{{+ SurfaceID: SurfaceIDPulseMCP,+ ToolNames: []string{FleetContextCapabilityName},+ }},+ Capabilities: []Capability{{Name: FleetContextCapabilityName}},+ })+ want := "No capability-specific stable error codes are currently advertised by the manifest."+ if got != want {+ t.Fatalf("empty error-code inventory = %q, want %q", got, want)+ }+}diff --git a/internal/agentcapabilities/mcp.go b/internal/agentcapabilities/mcp.gonew file mode 100644index 0000000000..79a7fc85d7--- /dev/null+++ b/internal/agentcapabilities/mcp.go@@ -0,0 +1,1041 @@+package agentcapabilities++import (+ "bufio"+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/url"+ "strings"+)++const (+ JSONRPCVersion = "2.0"++ JSONRPCErrorParse = -32700+ JSONRPCErrorInvalidRequest = -32600+ JSONRPCErrorMethodNotFound = -32601+ JSONRPCErrorInvalidParams = -32602+ JSONRPCErrorInternal = -32603++ MCPProtocolVersion = "2025-06-18"++ MCPMethodInitialize = "initialize"+ MCPMethodToolsList = "tools/list"+ MCPMethodToolsCall = "tools/call"+ MCPMethodResourcesList = "resources/list"+ MCPMethodResourcesRead = "resources/read"+ MCPMethodPromptsList = "prompts/list"+ MCPMethodPromptsGet = "prompts/get"+ MCPMethodPing = "ping"++ MCPNotificationPrefix = "notifications/"++ MCPPulseNotificationsExperimentalKey = "pulseNotifications"++ MCPResourceContextURIHost = "resource"+ MCPResourceContextMIMEType = "application/json"+)++// JSONRPCRequest is the shared JSON-RPC 2.0 request envelope used by Pulse's+// MCP transport surfaces. ID stays raw so adapters can echo numeric, string, or+// structured client ids without interpreting them.+type JSONRPCRequest struct {+ JSONRPC string `json:"jsonrpc"`+ ID json.RawMessage `json:"id,omitempty"`+ Method string `json:"method"`+ Params json.RawMessage `json:"params,omitempty"`+}++// JSONRPCResponse is the shared JSON-RPC 2.0 response envelope used by Pulse's+// MCP transport surfaces.+type JSONRPCResponse struct {+ JSONRPC string `json:"jsonrpc"`+ ID json.RawMessage `json:"id,omitempty"`+ Result any `json:"result,omitempty"`+ Error *JSONRPCError `json:"error,omitempty"`+}++// JSONRPCError is the shared JSON-RPC 2.0 error envelope.+type JSONRPCError struct {+ Code int `json:"code"`+ Message string `json:"message"`+ Data any `json:"data,omitempty"`+}++// DecodeJSONRPCRequest parses one JSON-RPC request payload with the stable+// malformed-request message used by Pulse MCP adapters.+func DecodeJSONRPCRequest(raw []byte) (JSONRPCRequest, error) {+ var req JSONRPCRequest+ if err := json.Unmarshal(raw, &req); err != nil {+ return JSONRPCRequest{}, fmt.Errorf("malformed JSON-RPC request: %w", err)+ }+ return req, nil+}++// NewJSONRPCParseErrorResponse builds the shared parse-error response for+// request payloads that could not be decoded far enough to recover an id.+func NewJSONRPCParseErrorResponse(err error) JSONRPCResponse {+ message := "malformed JSON-RPC request"+ if err != nil {+ message = err.Error()+ }+ return NewJSONRPCErrorResponse(nil, JSONRPCErrorParse, message, nil)+}++// JSONRPCRequestExpectsResponse reports whether a request has a non-null id.+// JSON-RPC notifications deliberately receive no response.+func JSONRPCRequestExpectsResponse(req JSONRPCRequest) bool {+ id := bytes.TrimSpace(req.ID)+ return len(id) > 0 && !bytes.Equal(id, []byte("null"))+}++// JSONRPCLineDispatcher handles one decoded JSON-RPC request.+type JSONRPCLineDispatcher func(context.Context, JSONRPCRequest) JSONRPCResponse++// JSONRPCResponseWriter writes one JSON-RPC response envelope.+type JSONRPCResponseWriter func(JSONRPCResponse) error++// ServeJSONRPCLines scans a line-delimited JSON-RPC stream, decodes each+// request, writes parse errors with the shared envelope, dispatches valid+// requests, and suppresses responses for JSON-RPC notifications. Transport+// adapters own session policy and response serialization; request framing,+// parse-error mapping, and notification response rules stay here.+func ServeJSONRPCLines(ctx context.Context, reader io.Reader, dispatch JSONRPCLineDispatcher, write JSONRPCResponseWriter) error {+ scanner := bufio.NewScanner(reader)+ scanner.Buffer(make([]byte, 64*1024), 1<<22)+ for scanner.Scan() {+ line := strings.TrimSpace(scanner.Text())+ if line == "" {+ continue+ }+ req, err := DecodeJSONRPCRequest([]byte(line))+ if err != nil {+ if write != nil {+ if writeErr := write(NewJSONRPCParseErrorResponse(err)); writeErr != nil {+ return writeErr+ }+ }+ continue+ }+ if dispatch == nil {+ continue+ }+ resp := dispatch(ctx, req)+ if !JSONRPCRequestExpectsResponse(req) {+ continue+ }+ if write != nil {+ if err := write(resp); err != nil {+ return err+ }+ }+ }+ if err := scanner.Err(); err != nil && err != io.EOF {+ return err+ }+ return nil+}++// WriteJSONRPCMessage serializes a JSON-RPC envelope or notification with+// stable encoder settings used by Pulse MCP transports.+func WriteJSONRPCMessage(out io.Writer, v any) error {+ enc := json.NewEncoder(out)+ enc.SetEscapeHTML(false)+ return enc.Encode(v)+}++// MCPServerInfo describes the Pulse MCP server during initialize.+type MCPServerInfo struct {+ Name string `json:"name"`+ Version string `json:"version"`+ Capabilities *MCPCapabilities `json:"capabilities,omitempty"`+}++// MCPCapabilities describes capabilities advertised during initialize. The+// experimental map is deliberately flexible because MCP clients use+// implementation-specific extension keys for server-initiated notifications.+type MCPCapabilities struct {+ Tools *MCPToolsCapability `json:"tools,omitempty"`+ Resources *MCPResourcesCapability `json:"resources,omitempty"`+ Prompts *MCPPromptsCapability `json:"prompts,omitempty"`+ Experimental map[string]any `json:"experimental,omitempty"`+}++// MCPToolsCapability describes tool support.+type MCPToolsCapability struct {+ ListChanged bool `json:"listChanged,omitempty"`+}++// MCPResourcesCapability describes resource support.+type MCPResourcesCapability struct {+ Subscribe bool `json:"subscribe,omitempty"`+ ListChanged bool `json:"listChanged,omitempty"`+}++// MCPPromptsCapability describes prompt support.+type MCPPromptsCapability struct {+ ListChanged bool `json:"listChanged,omitempty"`+}++// MCPPulseNotificationsCapability is Pulse's namespaced initialize extension+// for adapters that translate Pulse Intelligence events into JSON-RPC+// notifications.+type MCPPulseNotificationsCapability struct {+ Kinds []string `json:"kinds"`+}++// MCPInitializeParams are the params for the initialize method.+type MCPInitializeParams struct {+ ProtocolVersion string `json:"protocolVersion"`+ Capabilities MCPCapabilities `json:"capabilities"`+ ClientInfo MCPClientInfo `json:"clientInfo"`+}++// MCPClientInfo describes the MCP client.+type MCPClientInfo struct {+ Name string `json:"name"`+ Version string `json:"version"`+}++// MCPInitializeResult is the result for the initialize method.+type MCPInitializeResult struct {+ ProtocolVersion string `json:"protocolVersion"`+ Capabilities MCPCapabilities `json:"capabilities"`+ ServerInfo MCPServerInfo `json:"serverInfo"`+ Instructions string `json:"instructions,omitempty"`+}++// NewMCPToolServerInitializeResult builds the shared initialize response for a+// Pulse MCP server that exposes tools and optionally advertises the Pulse+// Intelligence notification bridge.+func NewMCPToolServerInitializeResult(serverName, serverVersion string, emitPulseNotifications bool) MCPInitializeResult {+ return newMCPToolServerInitializeResult(serverName, serverVersion, emitPulseNotifications, true, false, false, false, SurfaceIDPulseMCP, SurfaceContract{})+}++// NewMCPManifestToolServerInitializeResult builds the shared initialize+// response for a manifest-backed Pulse MCP server. Resource support is+// advertised only when the manifest contains the canonical fleet and+// per-resource context capabilities needed to satisfy resources/list/read.+func NewMCPManifestToolServerInitializeResult(serverName, serverVersion string, emitPulseNotifications bool, manifest Manifest) MCPInitializeResult {+ return NewMCPManifestSurfaceToolServerInitializeResult(serverName, serverVersion, emitPulseNotifications, manifest, SurfaceIDPulseMCP)+}++// NewMCPManifestSurfaceToolServerInitializeResult builds the shared initialize+// response for a manifest-backed MCP server surface. The manifest's published+// surface tool contract decides whether request/response tools may be+// advertised; surface-aware resource and prompt helpers decide whether those+// affordances can be satisfied for this manifest snapshot.+func NewMCPManifestSurfaceToolServerInitializeResult(serverName, serverVersion string, emitPulseNotifications bool, manifest Manifest, surfaceID string) MCPInitializeResult {+ surfaceID = normalizeMCPManifestSurfaceID(surfaceID)+ affordances, _ := ManifestSurfaceAffordances(manifest, surfaceID)+ _, hasSurfaceToolContract := ResolveManifestSurfaceToolContract(manifest, surfaceID)+ return newMCPToolServerInitializeResult(+ serverName,+ serverVersion,+ emitPulseNotifications,+ affordances.Tools && hasSurfaceToolContract,+ MCPManifestResourceProjectionSupported(manifest, surfaceID),+ MCPManifestSurfacePromptProjectionSupported(manifest, surfaceID),+ affordances.CapabilityMetadata,+ surfaceID,+ manifest.SurfaceContract,+ )+}++func newMCPToolServerInitializeResult(serverName, serverVersion string, emitPulseNotifications, exposeTools, exposeResources, exposePrompts, exposeCapabilityMetadata bool, surfaceID string, surfaceContract SurfaceContract) MCPInitializeResult {+ caps := MCPCapabilities{}+ if exposeTools {+ caps.Tools = &MCPToolsCapability{}+ }+ if exposeResources {+ caps.Resources = &MCPResourcesCapability{}+ }+ if exposePrompts {+ caps.Prompts = &MCPPromptsCapability{}+ }+ if emitPulseNotifications {+ caps.Experimental = map[string]any{+ MCPPulseNotificationsExperimentalKey: MCPPulseNotificationsCapability{+ Kinds: AgentActionableEventKinds(),+ },+ }+ }+ return MCPInitializeResult{+ ProtocolVersion: MCPProtocolVersion,+ Capabilities: caps,+ ServerInfo: MCPServerInfo{+ Name: serverName,+ Version: serverVersion,+ },+ Instructions: BuildPulseMCPOperatingInstructions(PulseMCPOperatingInstructionOptions{+ SurfaceID: surfaceID,+ SupportsTools: exposeTools,+ SupportsResources: exposeResources,+ SupportsPrompts: exposePrompts,+ SupportsCapabilityMetadata: exposeCapabilityMetadata,+ SurfaceContract: surfaceContract,+ }),+ }+}++// MCPListToolsResult is the tools/list result shape for structured in-process+// registry tools.+type MCPListToolsResult struct {+ Tools []Tool `json:"tools"`+}++// MCPProjectedToolsResult is the tools/list result shape for external-agent+// adapters that project the canonical capabilities manifest.+type MCPProjectedToolsResult struct {+ Tools []ProjectedTool `json:"tools"`+}++// MCPCallToolParams is the protocol-facing compatibility name for the shared+// tool-call params envelope used by MCP tools/call.+type MCPCallToolParams = ToolCallParams++// MCPToolAnnotations is the protocol-facing compatibility name for the shared+// external-agent tool behavior hints projected into MCP tools/list.+type MCPToolAnnotations = ToolBehaviorHints++// MCPToolServerHandlers are the adapter-provided actions behind the shared MCP+// JSON-RPC method dispatcher. Transport/session concerns stay in the adapter;+// method semantics, result envelopes, and error mapping stay here.+type MCPToolServerHandlers struct {+ Initialize func() MCPInitializeResult+ ToolsList func() MCPProjectedToolsResult+ ToolsCall func(context.Context, json.RawMessage) (MCPToolResult, error)+ ResourcesList func(context.Context) (MCPListResourcesResult, error)+ ResourcesRead func(context.Context, json.RawMessage) (MCPReadResourceResult, error)+ PromptsList func() MCPListPromptsResult+ PromptsGet func(context.Context, json.RawMessage) (MCPGetPromptResult, error)+ OnInitialize func()+}++// MCPManifestToolServer is the shared manifest-backed MCP tool surface used by+// adapters that expose Pulse Intelligence capabilities as request/response MCP+// tools. Adapters provide transport/session policy; this type owns initialize,+// tools/list, and tools/call semantics over the canonical manifest.+type MCPManifestToolServer struct {+ ServerName string+ ServerVersion string+ SurfaceID string+ EmitPulseNotifications bool+ Client HTTPDoer+ BaseURL string+ Token string+ Manifest Manifest+ RecordWorkflowPromptActivity func(context.Context, string)+}++// Handlers returns the shared MCP dispatcher callbacks for this manifest-backed+// tool server.+func (s MCPManifestToolServer) Handlers(onInitialize func()) MCPToolServerHandlers {+ return MCPToolServerHandlers{+ Initialize: func() MCPInitializeResult {+ return s.Initialize()+ },+ ToolsList: func() MCPProjectedToolsResult {+ return s.ToolsList()+ },+ ToolsCall: func(ctx context.Context, raw json.RawMessage) (MCPToolResult, error) {+ return s.ToolsCall(ctx, raw)+ },+ ResourcesList: func(ctx context.Context) (MCPListResourcesResult, error) {+ return s.ResourcesList(ctx)+ },+ ResourcesRead: func(ctx context.Context, raw json.RawMessage) (MCPReadResourceResult, error) {+ return s.ResourcesRead(ctx, raw)+ },+ PromptsList: func() MCPListPromptsResult {+ return s.PromptsList()+ },+ PromptsGet: func(ctx context.Context, raw json.RawMessage) (MCPGetPromptResult, error) {+ return s.PromptsGet(ctx, raw)+ },+ OnInitialize: onInitialize,+ }+}++// Initialize returns the shared Pulse MCP initialize result.+func (s MCPManifestToolServer) Initialize() MCPInitializeResult {+ return NewMCPManifestSurfaceToolServerInitializeResult(s.ServerName, s.ServerVersion, s.EmitPulseNotifications, s.Manifest, s.surfaceID())+}++// ToolsList projects the canonical capabilities manifest into MCP tools.+func (s MCPManifestToolServer) ToolsList() MCPProjectedToolsResult {+ if !s.surfaceAffordances().Tools {+ return MCPProjectedToolsResult{Tools: []ProjectedTool{}}+ }+ return MCPProjectedToolsResult{Tools: ProjectManifestSurfaceTools(s.Manifest, s.surfaceID())}+}++// ToolsCall executes one manifest-backed MCP tool invocation.+func (s MCPManifestToolServer) ToolsCall(ctx context.Context, raw json.RawMessage) (MCPToolResult, error) {+ return ExecuteMCPManifestSurfaceToolHTTP(ctx, s.Client, s.BaseURL, s.Token, s.Manifest, s.surfaceID(), raw)+}++// ResourcesList projects the canonical fleet-context capability into MCP+// resource descriptors.+func (s MCPManifestToolServer) ResourcesList(ctx context.Context) (MCPListResourcesResult, error) {+ return ListMCPManifestSurfaceResourcesHTTP(ctx, s.Client, s.BaseURL, s.Token, s.Manifest, s.surfaceID())+}++// ResourcesRead projects a single MCP resource URI onto the canonical+// per-resource context capability.+func (s MCPManifestToolServer) ResourcesRead(ctx context.Context, raw json.RawMessage) (MCPReadResourceResult, error) {+ return ReadMCPManifestSurfaceResourceHTTP(ctx, s.Client, s.BaseURL, s.Token, s.Manifest, s.surfaceID(), raw)+}++// PromptsList projects manifest-backed Pulse workflow prompts.+func (s MCPManifestToolServer) PromptsList() MCPListPromptsResult {+ if !MCPManifestSurfacePromptProjectionSupported(s.Manifest, s.surfaceID()) {+ return MCPListPromptsResult{Prompts: []MCPPrompt{}}+ }+ return (MCPListPromptsResult{Prompts: ProjectMCPWorkflowPrompts(ManifestPulseWorkflowPrompts(s.Manifest))}).NormalizeCollections()+}++// PromptsGet returns one manifest-backed Pulse workflow prompt.+func (s MCPManifestToolServer) PromptsGet(ctx context.Context, raw json.RawMessage) (MCPGetPromptResult, error) {+ result, err := GetMCPPromptFromManifestSurface(s.Manifest, s.surfaceID(), raw)+ if err != nil {+ return MCPGetPromptResult{}, err+ }+ if s.RecordWorkflowPromptActivity != nil {+ if params, decodeErr := DecodeMCPGetPromptParams(raw); decodeErr == nil {+ s.RecordWorkflowPromptActivity(ctx, params.Name)+ }+ }+ return result, nil+}++func (s MCPManifestToolServer) surfaceAffordances() SurfaceAffordanceContract {+ affordances, _ := ManifestSurfaceAffordances(s.Manifest, s.surfaceID())+ return affordances+}++func (s MCPManifestToolServer) surfaceID() string {+ return normalizeMCPManifestSurfaceID(s.SurfaceID)+}++func normalizeMCPManifestSurfaceID(surfaceID string) string {+ if surfaceID := strings.TrimSpace(surfaceID); surfaceID != "" {+ return surfaceID+ }+ return SurfaceIDPulseMCP+}++// DispatchMCPToolServerRequest routes one JSON-RPC request through the shared+// Pulse MCP tool-server semantics so stdio, HTTP, or future adapters do not+// each own initialize/tools/list/tools/call branching or error-code mapping.+func DispatchMCPToolServerRequest(ctx context.Context, req JSONRPCRequest, handlers MCPToolServerHandlers) JSONRPCResponse {+ switch req.Method {+ case MCPMethodInitialize:+ if handlers.Initialize == nil {+ return NewJSONRPCErrorResponse(req.ID, JSONRPCErrorInternal, "initialize handler unavailable", nil)+ }+ resp := NewJSONRPCResponse(req.ID, handlers.Initialize())+ if handlers.OnInitialize != nil {+ handlers.OnInitialize()+ }+ return resp+ case MCPMethodToolsList:+ if handlers.ToolsList == nil {+ return NewJSONRPCErrorResponse(req.ID, JSONRPCErrorInternal, "tools/list handler unavailable", nil)+ }+ return NewJSONRPCResponse(req.ID, handlers.ToolsList())+ case MCPMethodToolsCall:+ if handlers.ToolsCall == nil {+ return NewJSONRPCErrorResponse(req.ID, JSONRPCErrorInternal, "tools/call handler unavailable", nil)+ }+ result, err := handlers.ToolsCall(ctx, req.Params)+ if err != nil {+ return NewJSONRPCErrorResponse(req.ID, JSONRPCErrorInternal, err.Error(), nil)+ }+ return NewJSONRPCResponse(req.ID, result.NormalizeCollections())+ case MCPMethodResourcesList:+ if handlers.ResourcesList == nil {+ return NewJSONRPCErrorResponse(req.ID, JSONRPCErrorInternal, "resources/list handler unavailable", nil)+ }+ result, err := handlers.ResourcesList(ctx)+ if err != nil {+ return NewJSONRPCErrorResponse(req.ID, JSONRPCErrorInternal, err.Error(), nil)+ }+ return NewJSONRPCResponse(req.ID, result.NormalizeCollections())+ case MCPMethodResourcesRead:+ if handlers.ResourcesRead == nil {+ return NewJSONRPCErrorResponse(req.ID, JSONRPCErrorInternal, "resources/read handler unavailable", nil)+ }+ result, err := handlers.ResourcesRead(ctx, req.Params)+ if err != nil {+ return NewJSONRPCErrorResponse(req.ID, JSONRPCErrorInternal, err.Error(), nil)+ }+ return NewJSONRPCResponse(req.ID, result.NormalizeCollections())+ case MCPMethodPromptsList:+ if handlers.PromptsList == nil {+ return NewJSONRPCErrorResponse(req.ID, JSONRPCErrorInternal, "prompts/list handler unavailable", nil)+ }+ return NewJSONRPCResponse(req.ID, handlers.PromptsList().NormalizeCollections())+ case MCPMethodPromptsGet:+ if handlers.PromptsGet == nil {+ return NewJSONRPCErrorResponse(req.ID, JSONRPCErrorInternal, "prompts/get handler unavailable", nil)+ }+ result, err := handlers.PromptsGet(ctx, req.Params)+ if err != nil {+ return NewJSONRPCErrorResponse(req.ID, JSONRPCErrorInternal, err.Error(), nil)+ }+ return NewJSONRPCResponse(req.ID, result.NormalizeCollections())+ case MCPMethodPing:+ return NewJSONRPCResponse(req.ID, map[string]any{})+ default:+ return NewJSONRPCErrorResponse(req.ID, JSONRPCErrorMethodNotFound, fmt.Sprintf("method not found: %s", req.Method), nil)+ }+}++// DecodeMCPCallToolParams parses raw tools/call params through the shared MCP+// envelope so adapters do not each own JSON error wording.+func DecodeMCPCallToolParams(raw json.RawMessage) (MCPCallToolParams, error) {+ var params MCPCallToolParams+ if err := json.Unmarshal(raw, ¶ms); err != nil {+ return MCPCallToolParams{}, fmt.Errorf("decode tools/call params: %w", err)+ }+ params = NormalizeToolCallParams(params)+ if err := ValidateToolCallParams(params); err != nil {+ return MCPCallToolParams{}, fmt.Errorf("decode tools/call params: %w", err)+ }+ return params, nil+}++// ExecuteMCPManifestSurfaceToolHTTP projects one MCP tools/call request onto+// the neutral manifest-backed tool execution helper after applying the same+// manifest-owned surface affordance and surface tool allowlist used by+// tools/list.+func ExecuteMCPManifestSurfaceToolHTTP(ctx context.Context, client HTTPDoer, baseURL, token string, manifest Manifest, surfaceID string, raw json.RawMessage) (MCPToolResult, error) {+ params, err := DecodeMCPCallToolParams(raw)+ if err != nil {+ return MCPToolResult{}, err+ }+ surfaceID = normalizeMCPManifestSurfaceID(surfaceID)+ affordances, _ := ManifestSurfaceAffordances(manifest, surfaceID)+ if !affordances.Tools {+ return MCPToolResult{}, fmt.Errorf("MCP tools are not enabled for surface %s", surfaceID)+ }+ return ExecuteCapabilityToolHTTP(ctx, client, baseURL, token, ManifestSurfaceToolCapabilities(manifest, surfaceID), params)+}++// MCPResource describes an available MCP resource.+type MCPResource struct {+ URI string `json:"uri"`+ Name string `json:"name"`+ Description string `json:"description,omitempty"`+ MimeType string `json:"mimeType,omitempty"`+}++// MCPListResourcesResult is the resources/list result.+type MCPListResourcesResult struct {+ Resources []MCPResource `json:"resources"`+}++// NormalizeCollections returns a detached resources/list result with stable+// empty collections.+func (r MCPListResourcesResult) NormalizeCollections() MCPListResourcesResult {+ r.Resources = append([]MCPResource(nil), r.Resources...)+ if r.Resources == nil {+ r.Resources = []MCPResource{}+ }+ return r+}++// MCPReadResourceParams are the params for resources/read.+type MCPReadResourceParams struct {+ URI string `json:"uri"`+}++// MCPReadResourceResult is the resources/read result.+type MCPReadResourceResult struct {+ Contents []MCPResourceContent `json:"contents"`+}++// NormalizeCollections returns a detached resources/read result with stable+// empty collections.+func (r MCPReadResourceResult) NormalizeCollections() MCPReadResourceResult {+ r.Contents = append([]MCPResourceContent(nil), r.Contents...)+ if r.Contents == nil {+ r.Contents = []MCPResourceContent{}+ }+ return r+}++// MCPResourceContent is one resource content block.+type MCPResourceContent struct {+ URI string `json:"uri"`+ MimeType string `json:"mimeType,omitempty"`+ Text string `json:"text,omitempty"`+ Blob string `json:"blob,omitempty"`+}++type mcpFleetContextPayload struct {+ Resources []mcpFleetResourcePayload `json:"resources"`+}++type mcpFleetResourcePayload struct {+ CanonicalID string `json:"canonicalId"`+ ResourceType string `json:"resourceType"`+ ResourceName string `json:"resourceName"`+ Technology string `json:"technology,omitempty"`+ PendingApprovalCount int `json:"pendingApprovalCount,omitempty"`+ Findings struct {+ Total int `json:"total"`+ Critical int `json:"critical"`+ Warning int `json:"warning"`+ Info int `json:"info"`+ } `json:"findings"`+}++// MCPManifestResourceProjectionSupported reports whether one manifest surface+// can satisfy MCP resources/list and resources/read through the canonical Pulse+// Intelligence context capabilities.+func MCPManifestResourceProjectionSupported(manifest Manifest, surfaceID string) bool {+ return len(ManifestSurfaceResourceCapabilities(manifest, surfaceID)) == 2+}++// ManifestSurfaceResourceCapabilities returns the canonical context+// capabilities allowed to back MCP resources for one manifest surface.+func ManifestSurfaceResourceCapabilities(manifest Manifest, surfaceID string) []Capability {+ surfaceID = normalizeMCPManifestSurfaceID(surfaceID)+ affordances, _ := ManifestSurfaceAffordances(manifest, surfaceID)+ if !affordances.Resources {+ return []Capability{}+ }+ fleet, err := ResolveRequestResponseCapability(manifest.Capabilities, FleetContextCapabilityName)+ if err != nil {+ return []Capability{}+ }+ resource, err := ResolveRequestResponseCapability(manifest.Capabilities, ResourceContextCapabilityName)+ if err != nil {+ return []Capability{}+ }+ return []Capability{fleet, resource}+}++// MCPResourceURI returns the stable MCP resource URI for a canonical Pulse+// resource id.+func MCPResourceURI(resourceID string) string {+ return "pulse://" + MCPResourceContextURIHost + "/" + url.PathEscape(strings.TrimSpace(resourceID))+}++// ResourceIDFromMCPResourceURI decodes a Pulse MCP resource URI into the+// canonical resource id passed to get_resource_context.+func ResourceIDFromMCPResourceURI(rawURI string) (string, error) {+ rawURI = strings.TrimSpace(rawURI)+ if rawURI == "" {+ return "", fmt.Errorf("resource URI is required")+ }+ parsed, err := url.Parse(rawURI)+ if err != nil {+ return "", fmt.Errorf("parse resource URI: %w", err)+ }+ if parsed.Scheme != "pulse" || parsed.Host != MCPResourceContextURIHost {+ return "", fmt.Errorf("unsupported resource URI: %s", rawURI)+ }+ if parsed.RawQuery != "" || parsed.Fragment != "" {+ return "", fmt.Errorf("resource URI must not include query or fragment: %s", rawURI)+ }+ encodedID := strings.TrimPrefix(parsed.EscapedPath(), "/")+ if strings.TrimSpace(encodedID) == "" {+ return "", fmt.Errorf("resource URI is missing a resource id")+ }+ resourceID, err := url.PathUnescape(encodedID)+ if err != nil {+ return "", fmt.Errorf("decode resource URI: %w", err)+ }+ resourceID = strings.TrimSpace(resourceID)+ if resourceID == "" {+ return "", fmt.Errorf("resource URI is missing a resource id")+ }+ return resourceID, nil+}++// DecodeMCPReadResourceParams parses and validates resources/read params.+func DecodeMCPReadResourceParams(raw json.RawMessage) (MCPReadResourceParams, error) {+ var params MCPReadResourceParams+ if err := json.Unmarshal(raw, ¶ms); err != nil {+ return MCPReadResourceParams{}, fmt.Errorf("decode resources/read params: %w", err)+ }+ params.URI = strings.TrimSpace(params.URI)+ if params.URI == "" {+ return MCPReadResourceParams{}, fmt.Errorf("decode resources/read params: resource URI is required")+ }+ if _, err := ResourceIDFromMCPResourceURI(params.URI); err != nil {+ return MCPReadResourceParams{}, fmt.Errorf("decode resources/read params: %w", err)+ }+ return params, nil+}++// ListMCPManifestSurfaceResourcesHTTP projects the canonical fleet-context+// response into MCP resource descriptors for one manifest-owned surface. The+// fleet context remains the source of truth; this helper only adapts identity+// fields into the MCP resources/list envelope.+func ListMCPManifestSurfaceResourcesHTTP(ctx context.Context, client HTTPDoer, baseURL, token string, manifest Manifest, surfaceID string) (MCPListResourcesResult, error) {+ capabilities, err := resolveMCPManifestSurfaceResourceCapabilities(manifest, surfaceID)+ if err != nil {+ return MCPListResourcesResult{}, err+ }+ body, err := CallRequestResponseCapabilityHTTPBodyByName(ctx, client, baseURL, token, capabilities, FleetContextCapabilityName, map[string]any{})+ if err != nil {+ return MCPListResourcesResult{}, err+ }+ var fleet mcpFleetContextPayload+ if err := json.Unmarshal(body, &fleet); err != nil {+ return MCPListResourcesResult{}, fmt.Errorf("decode %s response: %w", FleetContextCapabilityName, err)+ }+ resources := make([]MCPResource, 0, len(fleet.Resources))+ for _, resource := range fleet.Resources {+ resourceID := strings.TrimSpace(resource.CanonicalID)+ if resourceID == "" {+ continue+ }+ resources = append(resources, MCPResource{+ URI: MCPResourceURI(resourceID),+ Name: mcpResourceDisplayName(resource),+ Description: mcpResourceDescription(resource),+ MimeType: MCPResourceContextMIMEType,+ })+ }+ return (MCPListResourcesResult{Resources: resources}).NormalizeCollections(), nil+}++// ReadMCPManifestSurfaceResourceHTTP projects one MCP resource URI onto the+// canonical get_resource_context capability for one manifest-owned surface and+// returns the JSON bundle as resource content.+func ReadMCPManifestSurfaceResourceHTTP(ctx context.Context, client HTTPDoer, baseURL, token string, manifest Manifest, surfaceID string, raw json.RawMessage) (MCPReadResourceResult, error) {+ params, err := DecodeMCPReadResourceParams(raw)+ if err != nil {+ return MCPReadResourceResult{}, err+ }+ capabilities, err := resolveMCPManifestSurfaceResourceCapabilities(manifest, surfaceID)+ if err != nil {+ return MCPReadResourceResult{}, err+ }+ resourceID, err := ResourceIDFromMCPResourceURI(params.URI)+ if err != nil {+ return MCPReadResourceResult{}, err+ }+ body, err := CallRequestResponseCapabilityHTTPBodyByName(ctx, client, baseURL, token, capabilities, ResourceContextCapabilityName, map[string]any{+ ResourceIDArgumentName: resourceID,+ })+ if err != nil {+ return MCPReadResourceResult{}, err+ }+ return (MCPReadResourceResult{Contents: []MCPResourceContent{{+ URI: MCPResourceURI(resourceID),+ MimeType: MCPResourceContextMIMEType,+ Text: string(body),+ }}}).NormalizeCollections(), nil+}++func resolveMCPManifestSurfaceResourceCapabilities(manifest Manifest, surfaceID string) ([]Capability, error) {+ surfaceID = normalizeMCPManifestSurfaceID(surfaceID)+ affordances, _ := ManifestSurfaceAffordances(manifest, surfaceID)+ if !affordances.Resources {+ return nil, fmt.Errorf("MCP resources are not enabled for surface %s", surfaceID)+ }+ capabilities := ManifestSurfaceResourceCapabilities(manifest, surfaceID)+ if len(capabilities) != 2 {+ return nil, fmt.Errorf("MCP resources require %s and %s capabilities", FleetContextCapabilityName, ResourceContextCapabilityName)+ }+ return capabilities, nil+}++func mcpResourceDisplayName(resource mcpFleetResourcePayload) string {+ if name := strings.TrimSpace(resource.ResourceName); name != "" {+ return name+ }+ return strings.TrimSpace(resource.CanonicalID)+}++func mcpResourceDescription(resource mcpFleetResourcePayload) string {+ parts := []string{}+ if resourceType := strings.TrimSpace(resource.ResourceType); resourceType != "" {+ parts = append(parts, resourceType)+ }+ if technology := strings.TrimSpace(resource.Technology); technology != "" {+ parts = append(parts, technology)+ }+ if resource.Findings.Total > 0 {+ parts = append(parts, fmt.Sprintf("findings: %d total (%d critical, %d warning, %d info)", resource.Findings.Total, resource.Findings.Critical, resource.Findings.Warning, resource.Findings.Info))+ }+ if resource.PendingApprovalCount > 0 {+ parts = append(parts, fmt.Sprintf("pending approvals: %d", resource.PendingApprovalCount))+ }+ return strings.Join(parts, "; ")+}++// MCPPrompt describes an available prompt template.+type MCPPrompt struct {+ Name string `json:"name"`+ Title string `json:"title,omitempty"`+ Description string `json:"description,omitempty"`+ Arguments []MCPPromptArgument `json:"arguments,omitempty"`+}++// NormalizeCollections returns a prompt with detached argument metadata.+func (p MCPPrompt) NormalizeCollections() MCPPrompt {+ p.Name = strings.TrimSpace(p.Name)+ p.Title = strings.TrimSpace(p.Title)+ p.Description = strings.TrimSpace(p.Description)+ p.Arguments = append([]MCPPromptArgument(nil), p.Arguments...)+ if p.Arguments == nil {+ p.Arguments = []MCPPromptArgument{}+ }+ return p+}++// MCPPromptArgument describes an argument in a prompt template.+type MCPPromptArgument struct {+ Name string `json:"name"`+ Description string `json:"description,omitempty"`+ Required bool `json:"required,omitempty"`+}++// MCPListPromptsResult is the prompts/list result.+type MCPListPromptsResult struct {+ Prompts []MCPPrompt `json:"prompts"`+}++// NormalizeCollections returns a detached prompts/list result.+func (r MCPListPromptsResult) NormalizeCollections() MCPListPromptsResult {+ r.Prompts = append([]MCPPrompt(nil), r.Prompts...)+ if r.Prompts == nil {+ r.Prompts = []MCPPrompt{}+ }+ for i := range r.Prompts {+ r.Prompts[i] = r.Prompts[i].NormalizeCollections()+ }+ return r+}++// MCPGetPromptParams are the params for prompts/get.+type MCPGetPromptParams struct {+ Name string `json:"name"`+ Arguments map[string]string `json:"arguments,omitempty"`+}++// NormalizeCollections returns detached prompt params with stable maps.+func (p MCPGetPromptParams) NormalizeCollections() MCPGetPromptParams {+ p.Name = strings.TrimSpace(p.Name)+ if p.Arguments == nil {+ p.Arguments = map[string]string{}+ return p+ }+ args := make(map[string]string, len(p.Arguments))+ for k, v := range p.Arguments {+ args[k] = v+ }+ p.Arguments = args+ return p+}++// MCPGetPromptResult is the prompts/get result.+type MCPGetPromptResult struct {+ Description string `json:"description,omitempty"`+ Messages []MCPPromptMessage `json:"messages"`+}++// NormalizeCollections returns a detached prompt result.+func (r MCPGetPromptResult) NormalizeCollections() MCPGetPromptResult {+ r.Messages = append([]MCPPromptMessage(nil), r.Messages...)+ if r.Messages == nil {+ r.Messages = []MCPPromptMessage{}+ }+ return r+}++// MCPPromptMessage is a message in a prompt result.+type MCPPromptMessage struct {+ Role string `json:"role"`+ Content MCPContent `json:"content"`+}++// MCPManifestPromptProjectionSupported reports whether a manifest exposes+// workflow prompts for external agents.+func MCPManifestPromptProjectionSupported(manifest Manifest) bool {+ return mcpManifestPromptProjectionSupported(manifest)+}++// MCPManifestSurfacePromptProjectionSupported reports whether one manifest+// surface can satisfy MCP prompts/list and prompts/get from the manifest-owned+// Pulse workflow prompt catalogue.+func MCPManifestSurfacePromptProjectionSupported(manifest Manifest, surfaceID string) bool {+ surfaceID = normalizeMCPManifestSurfaceID(surfaceID)+ affordances, _ := ManifestSurfaceAffordances(manifest, surfaceID)+ return affordances.Prompts && mcpManifestPromptProjectionSupported(manifest)+}++func mcpManifestPromptProjectionSupported(manifest Manifest) bool {+ for _, prompt := range ManifestPulseWorkflowPrompts(manifest) {+ if strings.TrimSpace(prompt.Name) != "" {+ return true+ }+ }+ return false+}++// ProjectMCPWorkflowPrompts projects manifest-owned Pulse Intelligence workflow+// starters into MCP prompt templates.+func ProjectMCPWorkflowPrompts(workflowPrompts []PulseWorkflowPrompt) []MCPPrompt {+ prompts := make([]MCPPrompt, 0, len(workflowPrompts))+ for _, workflowPrompt := range workflowPrompts {+ prompts = append(prompts, MCPPrompt{+ Name: workflowPrompt.Name,+ Title: workflowPrompt.Label,+ Description: workflowPrompt.Description,+ Arguments: projectPulseWorkflowPromptArgumentsToMCP(workflowPrompt.Arguments),+ })+ }+ for i := range prompts {+ prompts[i] = prompts[i].NormalizeCollections()+ }+ return prompts+}++func projectPulseWorkflowPromptArgumentsToMCP(args []PulseWorkflowPromptArgument) []MCPPromptArgument {+ out := make([]MCPPromptArgument, 0, len(args))+ for _, arg := range args {+ out = append(out, MCPPromptArgument{+ Name: arg.Name,+ Description: arg.Description,+ Required: arg.Required,+ })+ }+ return out+}++// DecodeMCPGetPromptParams parses and validates prompts/get params.+func DecodeMCPGetPromptParams(raw json.RawMessage) (MCPGetPromptParams, error) {+ var params MCPGetPromptParams+ if len(bytes.TrimSpace(raw)) > 0 {+ if err := json.Unmarshal(raw, ¶ms); err != nil {+ return MCPGetPromptParams{}, fmt.Errorf("decode prompts/get params: %w", err)+ }+ }+ params = params.NormalizeCollections()+ if params.Name == "" {+ return MCPGetPromptParams{}, fmt.Errorf("decode prompts/get params: prompt name is required")+ }+ return params, nil+}++// GetMCPPromptFromManifest returns one manifest-owned workflow prompt result.+func GetMCPPromptFromManifest(manifest Manifest, raw json.RawMessage) (MCPGetPromptResult, error) {+ params, err := DecodeMCPGetPromptParams(raw)+ if err != nil {+ return MCPGetPromptResult{}, err+ }+ return BuildMCPPromptFromManifest(manifest, params)+}++// GetMCPPromptFromManifestSurface returns one manifest-owned workflow prompt+// result after applying the target MCP surface's prompt affordance and manifest+// prompt catalogue gate.+func GetMCPPromptFromManifestSurface(manifest Manifest, surfaceID string, raw json.RawMessage) (MCPGetPromptResult, error) {+ surfaceID = normalizeMCPManifestSurfaceID(surfaceID)+ if !MCPManifestSurfacePromptProjectionSupported(manifest, surfaceID) {+ return MCPGetPromptResult{}, fmt.Errorf("MCP prompts are not enabled for surface %s", surfaceID)+ }+ return GetMCPPromptFromManifest(manifest, raw)+}++// BuildMCPPromptFromManifest renders one manifest-declared workflow prompt for+// the MCP prompt envelope.+func BuildMCPPromptFromManifest(manifest Manifest, params MCPGetPromptParams) (MCPGetPromptResult, error) {+ params = params.NormalizeCollections()+ if !pulseWorkflowPromptDeclared(ManifestPulseWorkflowPrompts(manifest), params.Name) {+ return MCPGetPromptResult{}, fmt.Errorf("unknown prompt: %s", params.Name)+ }+ result, err := BuildPulseWorkflowPromptFromManifestWithOptions(manifest, PulseWorkflowPromptParams{+ Name: params.Name,+ Arguments: params.Arguments,+ }, PulseWorkflowPromptRenderOptions{+ ResourceContextInstruction: func(resourceID string) string {+ return fmt.Sprintf("Prefer resources/read on %s when resources are available, otherwise call %s with %s %q", MCPResourceURI(resourceID), ResourceContextCapabilityName, ResourceIDArgumentName, resourceID)+ },+ })+ if err != nil {+ return MCPGetPromptResult{}, err+ }+ return newMCPUserPrompt(result.Description, result.Text), nil+}++func newMCPUserPrompt(description, text string) MCPGetPromptResult {+ return (MCPGetPromptResult{+ Description: description,+ Messages: []MCPPromptMessage{{+ Role: "user",+ Content: NewToolTextContent(text),+ }},+ }).NormalizeCollections()+}++// NewJSONRPCResponse builds a success response with the shared protocol marker.+func NewJSONRPCResponse(id json.RawMessage, result any) JSONRPCResponse {+ return JSONRPCResponse{JSONRPC: JSONRPCVersion, ID: id, Result: result}+}++// NewJSONRPCErrorResponse builds an error response with the shared protocol+// marker and stable JSON-RPC code.+func NewJSONRPCErrorResponse(id json.RawMessage, code int, message string, data any) JSONRPCResponse {+ return JSONRPCResponse{+ JSONRPC: JSONRPCVersion,+ ID: id,+ Error: &JSONRPCError{+ Code: code,+ Message: message,+ Data: data,+ },+ }+}++// NewJSONRPCNotification builds a JSON-RPC notification. Notifications must not+// carry an id or clients will wait for a response.+func NewJSONRPCNotification(method string, params json.RawMessage) JSONRPCRequest {+ return JSONRPCRequest{+ JSONRPC: JSONRPCVersion,+ Method: method,+ Params: params,+ }+}++// MCPNotificationMethod projects a Pulse event kind onto the MCP notification+// method namespace.+func MCPNotificationMethod(kind string) string {+ return MCPNotificationPrefix + kind+}++// NewMCPEventNotification projects a Pulse Intelligence SSE event onto the MCP+// notification channel. Empty records and stream-local transport events do not+// produce client-facing notifications.+func NewMCPEventNotification(kind string, params json.RawMessage) (JSONRPCRequest, bool) {+ if !IsActionableSSERecord(SSERecord{Event: kind, Data: string(params)}) {+ return JSONRPCRequest{}, false+ }+ return NewJSONRPCNotification(MCPNotificationMethod(kind), params), true+}++// MCPContent is the protocol-facing compatibility name for the shared tool+// result content block used by MCP tools/call.+type MCPContent = ToolContent++// MCPToolResult is the protocol-facing compatibility name for the shared tool+// result envelope used by MCP tools/call.+type MCPToolResult = ToolResult++func (e JSONRPCError) Error() string {+ if e.Message == "" {+ return fmt.Sprintf("json-rpc error %d", e.Code)+ }+ return e.Message+}diff --git a/internal/agentcapabilities/mcp_adapter.go b/internal/agentcapabilities/mcp_adapter.gonew file mode 100644index 0000000000..2710af7100--- /dev/null+++ b/internal/agentcapabilities/mcp_adapter.go@@ -0,0 +1,138 @@+package agentcapabilities++import "strings"++const (+ DefaultMCPAdapterServerName = "pulse"+ DefaultMCPAdapterCommand = "pulse-mcp"+ DefaultMCPAdapterBaseURLFlag = "--base-url"+ DefaultMCPAdapterDefaultBaseURL = "http://localhost:7655"+ DefaultMCPAdapterTokenEnv = "PULSE_API_TOKEN"++ MCPAdapterConfigShapeOpenCodeMCP = "opencode_mcp"+ MCPAdapterConfigShapeMCPServers = "mcp_servers"+ MCPAdapterConfigShapeCustom = "custom"+)++// DefaultMCPAdapterContract returns the backwards-compatible Pulse MCP setup+// contract used when an older manifest payload lacks the mcpAdapter block.+func DefaultMCPAdapterContract() MCPAdapterContract {+ return MCPAdapterContract{+ ServerName: DefaultMCPAdapterServerName,+ Command: DefaultMCPAdapterCommand,+ BaseURLFlag: DefaultMCPAdapterBaseURLFlag,+ DefaultBaseURL: DefaultMCPAdapterDefaultBaseURL,+ TokenEnv: DefaultMCPAdapterTokenEnv,+ ConfigFamilies: defaultMCPAdapterConfigFamilies(),+ }+}++func defaultMCPAdapterConfigFamilies() []MCPAdapterConfigFamily {+ return []MCPAdapterConfigFamily{+ {+ ID: "opencode",+ Label: "OpenCode",+ Shape: MCPAdapterConfigShapeOpenCodeMCP,+ Description: "Uses OpenCode's top-level mcp object.",+ FileHints: []string{+ "opencode.json",+ "opencode.jsonc",+ "~/.config/opencode/opencode.json",+ },+ ClientLabels: []string{"OpenCode"},+ },+ {+ ID: "claude-style",+ Label: "Claude-style clients",+ Shape: MCPAdapterConfigShapeMCPServers,+ Description: "Uses the common mcpServers object supported by Claude Desktop and Claude Code.",+ FileHints: []string{+ "~/Library/Application Support/Claude/claude_desktop_config.json",+ ".mcp.json",+ },+ ClientLabels: []string{"Claude Desktop", "Claude Code"},+ },+ {+ ID: "custom-mcp",+ Label: "custom MCP clients",+ Shape: MCPAdapterConfigShapeCustom,+ Description: "Keeps the Pulse MCP command, base URL flag, and token environment variable while adapting the outer client config shape.",+ ClientLabels: []string{"custom MCP clients"},+ },+ }+}++// NormalizeMCPAdapterContract fills compatibility defaults for older manifest+// payloads while preserving manifest-owned values when they are present.+func NormalizeMCPAdapterContract(contract MCPAdapterContract) MCPAdapterContract {+ if strings.TrimSpace(contract.ServerName) == "" {+ contract.ServerName = DefaultMCPAdapterServerName+ }+ if strings.TrimSpace(contract.Command) == "" {+ contract.Command = DefaultMCPAdapterCommand+ }+ if strings.TrimSpace(contract.BaseURLFlag) == "" {+ contract.BaseURLFlag = DefaultMCPAdapterBaseURLFlag+ }+ if strings.TrimSpace(contract.DefaultBaseURL) == "" {+ contract.DefaultBaseURL = DefaultMCPAdapterDefaultBaseURL+ }+ if strings.TrimSpace(contract.TokenEnv) == "" {+ contract.TokenEnv = DefaultMCPAdapterTokenEnv+ }++ contract.ConfigFamilies = NormalizeMCPAdapterConfigFamilies(contract.ConfigFamilies)+ return contract+}++// NormalizeMCPAdapterConfigFamilies detaches config-family descriptors, removes+// empty entries, and falls back to the default supported config families when an+// older manifest does not declare them.+func NormalizeMCPAdapterConfigFamilies(families []MCPAdapterConfigFamily) []MCPAdapterConfigFamily {+ if len(families) == 0 {+ return defaultMCPAdapterConfigFamilies()+ }++ normalized := make([]MCPAdapterConfigFamily, 0, len(families))+ for _, family := range families {+ id := strings.TrimSpace(family.ID)+ label := strings.TrimSpace(family.Label)+ shape := strings.TrimSpace(family.Shape)+ if id == "" && label == "" && shape == "" {+ continue+ }+ if id == "" {+ id = label+ }+ if label == "" {+ label = id+ }+ if shape == "" {+ shape = id+ }+ family.ID = id+ family.Label = label+ family.Shape = shape+ family.Description = strings.TrimSpace(family.Description)+ family.FileHints = trimmedStringSlice(family.FileHints)+ family.ClientLabels = trimmedStringSlice(family.ClientLabels)+ normalized = append(normalized, family)+ }+ if len(normalized) == 0 {+ return defaultMCPAdapterConfigFamilies()+ }+ return normalized+}++func trimmedStringSlice(values []string) []string {+ if len(values) == 0 {+ return nil+ }+ out := make([]string, 0, len(values))+ for _, value := range values {+ if trimmed := strings.TrimSpace(value); trimmed != "" {+ out = append(out, trimmed)+ }+ }+ return out+}diff --git a/internal/agentcapabilities/mcp_test.go b/internal/agentcapabilities/mcp_test.gonew file mode 100644index 0000000000..2b75f75813--- /dev/null+++ b/internal/agentcapabilities/mcp_test.go@@ -0,0 +1,1641 @@+package agentcapabilities++import (+ "context"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func testPulseMCPSurfaceToolContracts(toolNames ...string) []SurfaceToolContract {+ return []SurfaceToolContract{+ {+ SurfaceID: SurfaceIDPulseMCP,+ ToolSource: SurfaceToolSourceCapabilityManifest,+ ToolNames: append([]string(nil), toolNames...),+ Affordances: DefaultSurfaceAffordancesForID(SurfaceIDPulseMCP),+ },+ }+}++func TestToolResultHelpersBuildSharedEnvelope(t *testing.T) {+ empty := EmptyToolResult()+ if empty.Content == nil {+ t.Fatal("EmptyToolResult must initialize content")+ }+ if len(empty.Content) != 0 {+ t.Fatalf("EmptyToolResult content = %#v, want empty list", empty.Content)+ }++ text := NewToolTextResult("ok")+ if text.IsError {+ t.Fatal("NewToolTextResult must default to success")+ }+ if len(text.Content) != 1 || text.Content[0].Type != "text" || text.Content[0].Text != "ok" {+ t.Fatalf("unexpected text result: %+v", text)+ }++ failed := NewToolErrorResult(errors.New("nope"))+ if !failed.IsError {+ t.Fatal("NewToolErrorResult must mark the result as an error")+ }+ if failed.Content[0].Text != "nope" {+ t.Fatalf("error text = %q, want nope", failed.Content[0].Text)+ }++ payload := NewToolJSONResultWithIsError(map[string]any{"error": "policy_blocked"}, true)+ if !payload.IsError {+ t.Fatal("explicit error JSON result must preserve isError=true")+ }+ if !strings.Contains(payload.Content[0].Text, `"error":"policy_blocked"`) {+ t.Fatalf("JSON result did not marshal payload: %+v", payload)+ }+ if payload.StructuredContent["error"] != "policy_blocked" {+ t.Fatalf("JSON result structuredContent = %+v, want policy_blocked error", payload.StructuredContent)+ }+ wire, err := json.Marshal(payload)+ if err != nil {+ t.Fatalf("marshal tool result: %v", err)+ }+ if !strings.Contains(string(wire), `"structuredContent":{"error":"policy_blocked"}`) {+ t.Fatalf("JSON result must expose structuredContent in the shared wire envelope: %s", string(wire))+ }+}++func TestToolResultNormalizeCollectionsDetachesContent(t *testing.T) {+ sourceContent := []ToolContent{{Type: "text", Text: "ok"}}+ sourceStructured := map[string]any{+ "nested": map[string]any{"value": "original"},+ "items": []any{map[string]any{"value": "first"}},+ }+ normalized := (ToolResult{Content: sourceContent, StructuredContent: sourceStructured}).NormalizeCollections()+ if normalized.Content == nil {+ t.Fatal("NormalizeCollections must initialize content")+ }+ if normalized.Content[0].Text != "ok" {+ t.Fatalf("normalized content = %+v", normalized.Content)+ }++ normalized.Content[0].Text = "changed"+ if sourceContent[0].Text != "ok" {+ t.Fatalf("NormalizeCollections returned aliased content: source=%+v normalized=%+v", sourceContent, normalized.Content)+ }++ normalized.StructuredContent["nested"].(map[string]any)["value"] = "changed"+ normalized.StructuredContent["items"].([]any)[0].(map[string]any)["value"] = "changed"+ if sourceStructured["nested"].(map[string]any)["value"] != "original" {+ t.Fatalf("NormalizeCollections returned aliased structured nested map: source=%+v normalized=%+v", sourceStructured, normalized.StructuredContent)+ }+ if sourceStructured["items"].([]any)[0].(map[string]any)["value"] != "first" {+ t.Fatalf("NormalizeCollections returned aliased structured nested list: source=%+v normalized=%+v", sourceStructured, normalized.StructuredContent)+ }++ empty := (ToolResult{}).NormalizeCollections()+ if empty.Content == nil {+ t.Fatal("NormalizeCollections must preserve empty content as [] rather than nil")+ }+}++func TestToolHTTPTextResultMarksNon2xxAsError(t *testing.T) {+ ok := NewToolHTTPTextResult([]byte(`{"ok":true}`), 200)+ if ok.IsError {+ t.Fatal("2xx upstream response must become isError=false")+ }+ if ok.Content[0].Text != `{"ok":true}` {+ t.Fatalf("2xx content = %q", ok.Content[0].Text)+ }+ if ok.StructuredContent["ok"] != true {+ t.Fatalf("2xx structuredContent = %+v, want ok=true", ok.StructuredContent)+ }++ errResult := NewToolHTTPTextResult([]byte(`{"error":"resource_not_found"}`), 404)+ if !errResult.IsError {+ t.Fatal("non-2xx upstream response must become isError=true")+ }+ if errResult.Content[0].Text != `{"error":"resource_not_found"}` {+ t.Fatalf("non-2xx content = %q", errResult.Content[0].Text)+ }+ if errResult.StructuredContent["error"] != "resource_not_found" {+ t.Fatalf("non-2xx structuredContent = %+v, want resource_not_found error", errResult.StructuredContent)+ }++ arrayResult := NewToolHTTPTextResult([]byte(`[{"ok":true},{"ok":false}]`), 200)+ if arrayResult.Content[0].Text != `[{"ok":true},{"ok":false}]` {+ t.Fatalf("array content text changed: %q", arrayResult.Content[0].Text)+ }+ if arrayResult.StructuredContent["count"] != 2 {+ t.Fatalf("array structuredContent count = %+v, want 2", arrayResult.StructuredContent)+ }+ items, itemsOK := arrayResult.StructuredContent["items"].([]any)+ if !itemsOK || len(items) != 2 {+ t.Fatalf("array structuredContent items = %+v, want two items", arrayResult.StructuredContent)+ }+ first, _ := items[0].(map[string]any)+ if first["ok"] != true {+ t.Fatalf("array structuredContent first item = %+v, want ok=true", first)+ }++ for _, body := range [][]byte{+ []byte(`plain text`),+ []byte(`{"ok":true}{"extra":true}`),+ } {+ result := NewToolHTTPTextResult(body, 200)+ if result.StructuredContent != nil {+ t.Fatalf("body %q produced structuredContent %+v, want text-only result", string(body), result.StructuredContent)+ }+ }+}++func TestCapabilityHTTPToolResultUsesSharedHTTPResponseState(t *testing.T) {+ ok := NewCapabilityHTTPToolResult(HTTPCallResponse{+ Method: "GET",+ Path: "/api/agent/fleet-context",+ StatusCode: 202,+ Body: []byte(`{"ok":true}`),+ })+ if ok.IsError {+ t.Fatal("2xx capability HTTP response must become isError=false")+ }+ if ok.Content[0].Text != `{"ok":true}` {+ t.Fatalf("2xx content = %q", ok.Content[0].Text)+ }+ if ok.StructuredContent["ok"] != true {+ t.Fatalf("2xx structuredContent = %+v, want ok=true", ok.StructuredContent)+ }++ failed := NewCapabilityHTTPToolResult(HTTPCallResponse{+ Method: "GET",+ Path: "/api/agent/resource-context/vm%3A101",+ StatusCode: 403,+ Body: []byte(`{"error":"scope_required","message":"monitoring:read is required"}`),+ })+ if !failed.IsError {+ t.Fatal("non-2xx capability HTTP response must become isError=true")+ }+ if failed.Content[0].Text != `{"error":"scope_required","message":"monitoring:read is required"}` {+ t.Fatalf("non-2xx content = %q", failed.Content[0].Text)+ }+ if failed.StructuredContent["error"] != "scope_required" {+ t.Fatalf("non-2xx structuredContent = %+v, want scope_required error", failed.StructuredContent)+ }+}++func TestToolResultTextFlattensTextBlocks(t *testing.T) {+ result := ToolResult{+ Content: []ToolContent{+ {Type: "text", Text: "first"},+ {Type: "resource", URI: "file://ignored"},+ {Type: "text"},+ {Type: "text", Text: "second"},+ },+ }+ if got := ToolResultText(result); got != "first\nsecond" {+ t.Fatalf("ToolResultText returned %q", got)+ }++ if got := ToolResultText(ToolResult{}); got != "" {+ t.Fatalf("empty ToolResultText returned %q, want empty", got)+ }+}++func TestInterpretToolResultFlattensTextAndDetectsSharedMarkers(t *testing.T) {+ approval := InterpretToolResult(ToolResult{+ Content: []ToolContent{+ NewToolTextContent(ApprovalRequiredToolMarker("qm start 101", "tool-1", "approval required", "approval-1", "Approve it.")),+ },+ })+ if approval.Text == "" || !approval.ApprovalRequired || approval.PolicyBlocked || approval.IsError {+ t.Fatalf("approval interpretation = %+v", approval)+ }++ policy := InterpretToolResult(ToolResult{+ Content: []ToolContent{+ NewToolTextContent(PolicyBlockedToolMarker("rm -rf /", "blocked by policy")),+ },+ IsError: true,+ })+ if policy.Text == "" || !policy.PolicyBlocked || policy.ApprovalRequired || !policy.IsError {+ t.Fatalf("policy interpretation = %+v", policy)+ }++ plain := InterpretToolResult(ToolResult{+ Content: []ToolContent{+ NewToolTextContent("first"),+ {Type: "resource", URI: "file://ignored"},+ NewToolTextContent("second"),+ },+ })+ if plain.Text != "first\nsecond" || plain.ApprovalRequired || plain.PolicyBlocked || plain.IsError {+ t.Fatalf("plain interpretation = %+v", plain)+ }+}++func TestMCPToolResultWireAliasesUseNeutralHelpers(t *testing.T) {+ result := MCPToolResult{+ Content: []MCPContent{+ NewToolTextContent("ok"),+ },+ }+ blocked := NewToolBlockedError(ErrCodeActionNotAllowed, "not available here", nil)+ neutral := NewToolResponseResult(blocked)+ if !neutral.IsError || ToolResultText(neutral) == "" {+ t.Fatalf("neutral tool response result = %+v", neutral)+ }+ if got := ToolResultText(result); got != "ok" {+ t.Fatalf("MCP wire alias text = %q", got)+ }+ structured := NewToolJSONResult(map[string]any{"ok": true})+ alias := MCPToolResult(structured)+ wire, err := json.Marshal(alias)+ if err != nil {+ t.Fatalf("marshal MCP alias: %v", err)+ }+ if !strings.Contains(string(wire), `"structuredContent":{"ok":true}`) {+ t.Fatalf("MCP alias must carry shared structuredContent on the wire: %s", string(wire))+ }+ interpreted := InterpretToolResult(result)+ if interpreted.Text != "ok" || interpreted.IsError || interpreted.ApprovalRequired || interpreted.PolicyBlocked {+ t.Fatalf("MCP wire alias interpretation = %+v", interpreted)+ }+}++func TestInterpretDirectToolExecutionMapsSharedOutcomes(t *testing.T) {+ opts := DirectToolExecutionOptions{+ FailurePrefix: "command execution failed",+ ApprovalRequiredMessage: "command requires approval (unexpected in autonomous mode)",+ PolicyBlockedMessage: "command blocked by security policy",+ }++ failed, err := InterpretDirectToolExecution(ToolResult{+ Content: []ToolContent{NewToolTextContent("stderr")},+ IsError: true,+ }, opts)+ if err == nil || err.Error() != "command execution failed: stderr" {+ t.Fatalf("failure error = %v", err)+ }+ if failed.OutputText != "stderr" || !failed.Interpretation.IsError {+ t.Fatalf("failure outcome = %+v", failed)+ }++ approval, err := InterpretDirectToolExecution(ToolResult{+ Content: []ToolContent{+ NewToolTextContent(ApprovalRequiredToolMarker("qm start 101", "tool-1", "approval required", "approval-1", "Approve it.")),+ },+ }, opts)+ if err == nil || err.Error() != "command requires approval (unexpected in autonomous mode)" {+ t.Fatalf("approval error = %v", err)+ }+ if approval.OutputText != "" || !approval.Interpretation.ApprovalRequired {+ t.Fatalf("approval outcome = %+v", approval)+ }++ policy, err := InterpretDirectToolExecution(ToolResult{+ Content: []ToolContent{+ NewToolTextContent(PolicyBlockedToolMarker("rm -rf /", "blocked by policy")),+ },+ }, opts)+ if err == nil || err.Error() != "command blocked by security policy" {+ t.Fatalf("policy error = %v", err)+ }+ if policy.OutputText != "" || !policy.Interpretation.PolicyBlocked {+ t.Fatalf("policy outcome = %+v", policy)+ }++ success, err := InterpretDirectToolExecution(ToolResult{+ Content: []ToolContent{+ NewToolTextContent("first"),+ {Type: "resource", URI: "file://ignored"},+ NewToolTextContent("second"),+ },+ }, opts)+ if err != nil || success.OutputText != "first\nsecond" {+ t.Fatalf("success outcome = %+v err=%v", success, err)+ }+}++func TestNewProviderToolResultFromToolResultUsesSharedInterpretation(t *testing.T) {+ result := NewProviderToolResultFromToolResult("call-1", ToolResult{+ Content: []ToolContent{+ NewToolTextContent("first"),+ {Type: "resource", URI: "file://ignored"},+ NewToolTextContent("second"),+ },+ IsError: true,+ })++ if result.ToolUseID != "call-1" || result.Content != "first\nsecond" || !result.IsError {+ t.Fatalf("provider result = %+v", result)+ }+}++func TestNewProviderToolResultHelpersBuildProviderShape(t *testing.T) {+ result := NewProviderToolResult("call-1", "ok", false)+ if result.ToolUseID != "call-1" || result.Content != "ok" || result.IsError {+ t.Fatalf("provider result = %+v", result)+ }++ failed := NewProviderToolErrorResult("call-2", "failed")+ if failed.ToolUseID != "call-2" || failed.Content != "failed" || !failed.IsError {+ t.Fatalf("provider error result = %+v", failed)+ }+}++func TestJSONRPCHelpersPreserveProtocolAndNotificationShape(t *testing.T) {+ resp := NewJSONRPCErrorResponse(json.RawMessage(`"abc"`), JSONRPCErrorMethodNotFound, "missing", nil)+ if resp.JSONRPC != JSONRPCVersion {+ t.Fatalf("JSONRPC = %q, want %q", resp.JSONRPC, JSONRPCVersion)+ }+ if string(resp.ID) != `"abc"` {+ t.Fatalf("response id = %s", resp.ID)+ }+ if resp.Error == nil || resp.Error.Code != JSONRPCErrorMethodNotFound || resp.Error.Message != "missing" {+ t.Fatalf("unexpected error response: %+v", resp)+ }++ notification := NewJSONRPCNotification(MCPNotificationMethod("finding.created"), json.RawMessage(`{"findingId":"f1"}`))+ wire, err := json.Marshal(notification)+ if err != nil {+ t.Fatalf("marshal notification: %v", err)+ }+ body := string(wire)+ if !strings.Contains(body, `"jsonrpc":"2.0"`) || !strings.Contains(body, `"method":"notifications/finding.created"`) {+ t.Fatalf("notification missing protocol or method: %s", body)+ }+ if strings.Contains(body, `"id"`) {+ t.Fatalf("notification must not carry an id: %s", body)+ }+}++func TestJSONRPCRequestDecodeAndResponsePolicyUseSharedSemantics(t *testing.T) {+ req, err := DecodeJSONRPCRequest([]byte(`{"jsonrpc":"2.0","id":"turn-1","method":"tools/list"}`))+ if err != nil {+ t.Fatalf("DecodeJSONRPCRequest: %v", err)+ }+ if req.Method != MCPMethodToolsList || string(req.ID) != `"turn-1"` {+ t.Fatalf("decoded request = %+v", req)+ }+ if !JSONRPCRequestExpectsResponse(req) {+ t.Fatal("request with string id must expect a response")+ }++ if JSONRPCRequestExpectsResponse(JSONRPCRequest{Method: "notifications/initialized"}) {+ t.Fatal("request without id must be treated as a notification")+ }+ if JSONRPCRequestExpectsResponse(JSONRPCRequest{ID: json.RawMessage(`null`), Method: "notifications/initialized"}) {+ t.Fatal("request with null id must be treated as a notification")+ }+ if !JSONRPCRequestExpectsResponse(JSONRPCRequest{ID: json.RawMessage(`0`), Method: MCPMethodPing}) {+ t.Fatal("request with numeric zero id must still expect a response")+ }++ _, err = DecodeJSONRPCRequest([]byte(`{"jsonrpc":"2.0","method":`))+ if err == nil || !strings.Contains(err.Error(), "malformed JSON-RPC request") {+ t.Fatalf("decode error = %v, want stable malformed JSON-RPC message", err)+ }+ parseResp := NewJSONRPCParseErrorResponse(err)+ if parseResp.JSONRPC != JSONRPCVersion || parseResp.Error == nil || parseResp.Error.Code != JSONRPCErrorParse {+ t.Fatalf("parse error response = %+v", parseResp)+ }+ if !strings.Contains(parseResp.Error.Message, "malformed JSON-RPC request") {+ t.Fatalf("parse error message = %q", parseResp.Error.Message)+ }+}++func TestServeJSONRPCLinesDispatchesResponsesAndSuppressesNotifications(t *testing.T) {+ input := strings.NewReader("\n" ++ `{"jsonrpc":"2.0","id":1,"method":"ping"}` + "\n" ++ `{"jsonrpc":"2.0","method":"notifications/initialized"}` + "\n" ++ `{"jsonrpc":` + "\n")++ var methods []string+ var responses []JSONRPCResponse+ err := ServeJSONRPCLines(+ context.Background(),+ input,+ func(ctx context.Context, req JSONRPCRequest) JSONRPCResponse {+ methods = append(methods, req.Method)+ return NewJSONRPCResponse(req.ID, map[string]any{"method": req.Method})+ },+ func(resp JSONRPCResponse) error {+ responses = append(responses, resp)+ return nil+ },+ )+ if err != nil {+ t.Fatalf("ServeJSONRPCLines: %v", err)+ }+ if len(methods) != 2 || methods[0] != "ping" || methods[1] != "notifications/initialized" {+ t.Fatalf("dispatched methods = %#v", methods)+ }+ if len(responses) != 2 {+ t.Fatalf("responses = %d, want ping response and parse error", len(responses))+ }+ if responses[0].Error != nil || string(responses[0].ID) != "1" {+ t.Fatalf("first response = %+v, want successful ping response", responses[0])+ }+ if responses[1].Error == nil || responses[1].Error.Code != JSONRPCErrorParse {+ t.Fatalf("second response = %+v, want shared parse error", responses[1])+ }+}++func TestWriteJSONRPCMessageUsesStableEncoderSettings(t *testing.T) {+ var out strings.Builder+ if err := WriteJSONRPCMessage(&out, NewJSONRPCResponse(json.RawMessage(`"id-1"`), map[string]string{+ "html": "<tag>&value",+ })); err != nil {+ t.Fatalf("WriteJSONRPCMessage: %v", err)+ }+ body := out.String()+ if !strings.Contains(body, `"jsonrpc":"2.0"`) || !strings.Contains(body, `"<tag>&value"`) {+ t.Fatalf("encoded message did not preserve protocol or unescaped text: %s", body)+ }+}++func TestNewMCPEventNotificationProjectsOnlyProductEvents(t *testing.T) {+ notification, ok := NewMCPEventNotification(string(EventKindFindingCreated), json.RawMessage(`{"findingId":"f1"}`))+ if !ok {+ t.Fatal("finding.created with data must become an MCP notification")+ }+ if notification.JSONRPC != JSONRPCVersion {+ t.Fatalf("JSONRPC = %q, want %q", notification.JSONRPC, JSONRPCVersion)+ }+ if notification.Method != "notifications/finding.created" {+ t.Fatalf("method = %q, want notifications/finding.created", notification.Method)+ }+ if string(notification.Params) != `{"findingId":"f1"}` {+ t.Fatalf("params = %s, want raw SSE data", notification.Params)+ }+ if len(notification.ID) != 0 {+ t.Fatalf("notification must not carry id: %+v", notification)+ }++ custom, ok := NewMCPEventNotification("custom.product.event", json.RawMessage(`{"x":1}`))+ if !ok {+ t.Fatal("unknown non-transport product events must still project")+ }+ if custom.Method != "notifications/custom.product.event" {+ t.Fatalf("custom method = %q", custom.Method)+ }++ for _, tc := range []struct {+ name string+ kind string+ params json.RawMessage+ }{+ {"empty kind", "", json.RawMessage(`{"x":1}`)},+ {"empty params", string(EventKindFindingCreated), nil},+ {"stream connected", string(EventKindStreamConnected), json.RawMessage(`{}`)},+ {"heartbeat", string(EventKindHeartbeat), json.RawMessage(`{}`)},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if got, ok := NewMCPEventNotification(tc.kind, tc.params); ok {+ t.Fatalf("NewMCPEventNotification(%q, %s) = %+v, true; want false", tc.kind, tc.params, got)+ }+ })+ }+}++func TestNewMCPToolServerInitializeResultAdvertisesToolsAndOptionalPulseNotifications(t *testing.T) {+ disabled := NewMCPToolServerInitializeResult("pulse-mcp", "0.1.0", false)+ if disabled.ProtocolVersion != MCPProtocolVersion {+ t.Fatalf("protocolVersion = %q, want %q", disabled.ProtocolVersion, MCPProtocolVersion)+ }+ if disabled.ServerInfo.Name != "pulse-mcp" || disabled.ServerInfo.Version != "0.1.0" {+ t.Fatalf("serverInfo = %+v", disabled.ServerInfo)+ }+ if disabled.Capabilities.Tools == nil {+ t.Fatal("initialize result must advertise tools capability")+ }+ if len(disabled.Capabilities.Experimental) != 0 {+ t.Fatalf("notifications disabled must not advertise experimental capabilities: %+v", disabled.Capabilities.Experimental)+ }+ if !strings.Contains(disabled.Instructions, "governed infrastructure-operations surface") ||+ !strings.Contains(disabled.Instructions, "plan, approval, and execute flow") {+ t.Fatalf("initialize result must advertise shared Pulse Intelligence operating instructions, got %q", disabled.Instructions)+ }+ if !strings.Contains(disabled.Instructions, "This surface is Pulse MCP.") ||+ !strings.Contains(disabled.Instructions, "Use offered tools as the source of truth") {+ t.Fatalf("generic MCP initialize instructions must describe the tool-only surface, got %q", disabled.Instructions)+ }+ for _, forbidden := range []string{"resources", "prompts", "capability metadata"} {+ if strings.Contains(disabled.Instructions, forbidden) {+ t.Fatalf("generic MCP initialize instructions must not advertise unsupported %q: %q", forbidden, disabled.Instructions)+ }+ }++ enabled := NewMCPToolServerInitializeResult("pulse-mcp", "0.1.0", true)+ exp := enabled.Capabilities.Experimental+ if len(exp) == 0 {+ t.Fatal("notifications enabled must advertise experimental capabilities")+ }+ pulseNotifications, ok := exp[MCPPulseNotificationsExperimentalKey].(MCPPulseNotificationsCapability)+ if !ok {+ t.Fatalf("experimental[%q] = %T, want MCPPulseNotificationsCapability", MCPPulseNotificationsExperimentalKey, exp[MCPPulseNotificationsExperimentalKey])+ }+ if len(pulseNotifications.Kinds) == 0 {+ t.Fatal("Pulse notification capability must list actionable event kinds")+ }+ for _, want := range AgentActionableEventKinds() {+ found := false+ for _, got := range pulseNotifications.Kinds {+ if got == want {+ found = true+ break+ }+ }+ if !found {+ t.Fatalf("Pulse notification capability missing %q: %+v", want, pulseNotifications.Kinds)+ }+ }+}++func TestNewMCPManifestToolServerInitializeResultAdvertisesResourcesWhenContextCapabilitiesExist(t *testing.T) {+ capabilities := []Capability{+ {Name: FleetContextCapabilityName, Path: FleetContextCapabilityPath, Method: http.MethodGet},+ {Name: ResourceContextCapabilityName, Path: ResourceContextCapabilityPath, Method: http.MethodGet},+ {Name: EventSubscriptionCapabilityName, Path: "/api/agent/events", Method: http.MethodGet},+ }+ workflowPrompts := ProjectPulseWorkflowPrompts(capabilities)++ result := NewMCPManifestToolServerInitializeResult("pulse-mcp", "0.1.0", false, Manifest{+ SurfaceContract: CanonicalManifest().SurfaceContract,+ SurfaceToolContracts: testPulseMCPSurfaceToolContracts(FleetContextCapabilityName, ResourceContextCapabilityName),+ Capabilities: capabilities,+ WorkflowPrompts: workflowPrompts,+ })+ if result.Capabilities.Tools == nil {+ t.Fatal("manifest-backed initialize result must keep tools capability")+ }+ if result.Capabilities.Resources == nil {+ t.Fatal("manifest-backed initialize result must advertise resources when context capabilities exist")+ }+ if result.Capabilities.Prompts == nil {+ t.Fatal("manifest-backed initialize result must advertise prompts when workflow capabilities exist")+ }+ if !strings.Contains(result.Instructions, "Use offered tools, resources, prompts, and capability metadata as the source of truth") {+ t.Fatalf("manifest-backed initialize instructions must name advertised resource/prompt/metadata affordances, got %q", result.Instructions)+ }+ for _, expected := range []string{+ "Pulse MCP is the external-agent adapter over Pulse Intelligence Core",+ "Pulse Assistant is the native Pulse surface on the same core",+ "Surface affordances: Pulse MCP exposes tools, resources, prompts, and capability metadata.",+ "Pulse Patrol is the primary built-in operator on Pulse Intelligence Core",+ } {+ if !strings.Contains(result.Instructions, expected) {+ t.Fatalf("manifest-backed initialize instructions must include surface contract line %q, got %q", expected, result.Instructions)+ }+ }++ withoutResourceContext := NewMCPManifestToolServerInitializeResult("pulse-mcp", "0.1.0", false, Manifest{+ Capabilities: capabilities[:1],+ WorkflowPrompts: ProjectPulseWorkflowPrompts(capabilities[:1]),+ })+ if withoutResourceContext.Capabilities.Tools != nil {+ t.Fatalf("initialize result must not advertise tools without a published surface tool contract: %+v", withoutResourceContext.Capabilities.Tools)+ }+ if withoutResourceContext.Capabilities.Resources != nil {+ t.Fatalf("initialize result must not advertise resources without both context capabilities: %+v", withoutResourceContext.Capabilities.Resources)+ }+ if withoutResourceContext.Capabilities.Prompts == nil {+ t.Fatal("fleet-context-only manifests should still advertise the fleet triage prompt")+ }+ if strings.Contains(withoutResourceContext.Instructions, "resources") {+ t.Fatalf("initialize instructions must not advertise resources when resources capability is absent: %q", withoutResourceContext.Instructions)+ }+ if !strings.Contains(withoutResourceContext.Instructions, "prompts and capability metadata") {+ t.Fatalf("initialize instructions must keep prompt/metadata affordances when they are advertised, got %q", withoutResourceContext.Instructions)+ }+ if strings.Contains(withoutResourceContext.Instructions, "offered tools") {+ t.Fatalf("initialize instructions must not advertise tools without a published surface tool contract: %q", withoutResourceContext.Instructions)+ }+ if strings.Contains(withoutResourceContext.Instructions, "Surface contract") {+ t.Fatalf("initialize instructions must not invent a surface contract when the manifest lacks one: %q", withoutResourceContext.Instructions)+ }++ withoutPrompts := NewMCPManifestToolServerInitializeResult("pulse-mcp", "0.1.0", false, Manifest{+ Capabilities: capabilities,+ WorkflowPrompts: []PulseWorkflowPrompt{},+ })+ if withoutPrompts.Capabilities.Prompts != nil {+ t.Fatalf("initialize result must not advertise prompts when workflowPrompts is explicitly empty: %+v", withoutPrompts.Capabilities.Prompts)+ }+}++func TestNewMCPManifestToolServerInitializeResultRequiresPublishedSurfaceToolContractForTools(t *testing.T) {+ capabilities := []Capability{+ {Name: FleetContextCapabilityName, Path: FleetContextCapabilityPath, Method: http.MethodGet},+ {Name: ResourceContextCapabilityName, Path: ResourceContextCapabilityPath, Method: http.MethodGet},+ }++ result := NewMCPManifestToolServerInitializeResult("pulse-mcp", "0.1.0", false, Manifest{+ SurfaceContract: CanonicalManifest().SurfaceContract,+ Capabilities: capabilities,+ WorkflowPrompts: ProjectPulseWorkflowPrompts(capabilities),+ })++ if result.Capabilities.Tools != nil {+ t.Fatalf("initialize result must not advertise tools without a published surface tool contract: %+v", result.Capabilities.Tools)+ }+ if result.Capabilities.Resources == nil {+ t.Fatal("resource affordance can still advertise when canonical context capabilities exist")+ }+ if strings.Contains(result.Instructions, "offered tools") {+ t.Fatalf("initialize instructions must not name offered tools without a published surface tool contract: %q", result.Instructions)+ }+ if !strings.Contains(result.Instructions, "resources") {+ t.Fatalf("initialize instructions must still name advertised non-tool affordances, got %q", result.Instructions)+ }+}++func TestMCPManifestToolServerHonorsSurfaceAffordanceGates(t *testing.T) {+ capabilities := []Capability{+ {Name: FleetContextCapabilityName, Path: FleetContextCapabilityPath, Method: http.MethodGet, Description: "triage"},+ {Name: ResourceContextCapabilityName, Path: ResourceContextCapabilityPath, Method: http.MethodGet, Description: "depth"},+ {Name: ListFindingsCapabilityName, Path: "/api/ai/patrol/findings", Method: http.MethodGet, Description: "findings"},+ }+ surfaceContract := CanonicalManifest().SurfaceContract+ for i := range surfaceContract.OperatorSurfaces {+ if surfaceContract.OperatorSurfaces[i].ID == SurfaceIDPulseMCP {+ surfaceContract.OperatorSurfaces[i].Affordances = SurfaceAffordanceContract{Tools: true}+ }+ }+ server := MCPManifestToolServer{+ ServerName: "pulse-mcp",+ ServerVersion: "0.1.0",+ Manifest: Manifest{+ SurfaceContract: surfaceContract,+ SurfaceToolContracts: testPulseMCPSurfaceToolContracts(ListFindingsCapabilityName),+ Capabilities: capabilities,+ WorkflowPrompts: ProjectPulseWorkflowPrompts(capabilities),+ },+ }++ init := server.Initialize()+ if init.Capabilities.Tools == nil {+ t.Fatal("surface with tool affordance must still advertise tools")+ }+ if init.Capabilities.Resources != nil || init.Capabilities.Prompts != nil {+ t.Fatalf("surface-disabled resources/prompts must not be advertised: %+v", init.Capabilities)+ }+ if strings.Contains(init.Instructions, "resources") ||+ strings.Contains(init.Instructions, "prompts") ||+ strings.Contains(init.Instructions, "capability metadata") {+ t.Fatalf("initialize instructions must not advertise disabled MCP affordances: %q", init.Instructions)+ }++ if _, err := server.ResourcesList(context.Background()); err == nil || !strings.Contains(err.Error(), "resources are not enabled") {+ t.Fatalf("ResourcesList disabled error = %v", err)+ }+ rawRead, err := json.Marshal(MCPReadResourceParams{URI: MCPResourceURI("vm:101")})+ if err != nil {+ t.Fatalf("marshal read params: %v", err)+ }+ if _, err := server.ResourcesRead(context.Background(), rawRead); err == nil || !strings.Contains(err.Error(), "resources are not enabled") {+ t.Fatalf("ResourcesRead disabled error = %v", err)+ }+ if prompts := server.PromptsList(); len(prompts.Prompts) != 0 {+ t.Fatalf("PromptsList disabled result = %+v, want empty list", prompts)+ }+ rawPrompt, err := json.Marshal(MCPGetPromptParams{Name: MCPPromptTriageFleet})+ if err != nil {+ t.Fatalf("marshal prompt params: %v", err)+ }+ if _, err := server.PromptsGet(context.Background(), rawPrompt); err == nil || !strings.Contains(err.Error(), "prompts are not enabled") {+ t.Fatalf("PromptsGet disabled error = %v", err)+ }+}++func TestDispatchMCPToolServerRequestRoutesMethodsAndErrors(t *testing.T) {+ initializeCount := 0+ handlerContent := []MCPContent{{Type: "text", Text: "ok"}}+ handlerResources := []MCPResource{{URI: MCPResourceURI("vm:101"), Name: "VM 101"}}+ handlerContents := []MCPResourceContent{{URI: MCPResourceURI("vm:101"), MimeType: MCPResourceContextMIMEType, Text: `{"canonicalId":"vm:101"}`}}+ handlerPrompts := []MCPPrompt{{Name: MCPPromptTriageFleet, Description: "triage"}}+ handlerPromptMessages := []MCPPromptMessage{{Role: "user", Content: NewToolTextContent("triage now")}}+ handlers := MCPToolServerHandlers{+ Initialize: func() MCPInitializeResult {+ return NewMCPToolServerInitializeResult("pulse-mcp", "0.1.0", false)+ },+ ToolsList: func() MCPProjectedToolsResult {+ return MCPProjectedToolsResult{Tools: []ProjectedTool{{Name: "get_fleet_context"}}}+ },+ ToolsCall: func(ctx context.Context, raw json.RawMessage) (MCPToolResult, error) {+ if string(raw) != `{"name":"get_fleet_context"}` {+ t.Fatalf("tools/call raw params = %s", raw)+ }+ return MCPToolResult{Content: handlerContent}, nil+ },+ ResourcesList: func(ctx context.Context) (MCPListResourcesResult, error) {+ return MCPListResourcesResult{Resources: handlerResources}, nil+ },+ ResourcesRead: func(ctx context.Context, raw json.RawMessage) (MCPReadResourceResult, error) {+ if string(raw) != `{"uri":"`+MCPResourceURI("vm:101")+`"}` {+ t.Fatalf("resources/read raw params = %s", raw)+ }+ return MCPReadResourceResult{Contents: handlerContents}, nil+ },+ PromptsList: func() MCPListPromptsResult {+ return MCPListPromptsResult{Prompts: handlerPrompts}+ },+ PromptsGet: func(ctx context.Context, raw json.RawMessage) (MCPGetPromptResult, error) {+ if string(raw) != `{"name":"`+MCPPromptTriageFleet+`"}` {+ t.Fatalf("prompts/get raw params = %s", raw)+ }+ return MCPGetPromptResult{Description: "Triage", Messages: handlerPromptMessages}, nil+ },+ OnInitialize: func() {+ initializeCount+++ },+ }++ initResp := DispatchMCPToolServerRequest(context.Background(), JSONRPCRequest{+ ID: json.RawMessage(`1`),+ Method: MCPMethodInitialize,+ }, handlers)+ if initResp.Error != nil || initializeCount != 1 {+ t.Fatalf("initialize response = %+v initializeCount=%d", initResp, initializeCount)+ }+ if _, ok := initResp.Result.(MCPInitializeResult); !ok {+ t.Fatalf("initialize result type = %T, want MCPInitializeResult", initResp.Result)+ }++ listResp := DispatchMCPToolServerRequest(context.Background(), JSONRPCRequest{+ ID: json.RawMessage(`2`),+ Method: MCPMethodToolsList,+ }, handlers)+ listResult, ok := listResp.Result.(MCPProjectedToolsResult)+ if listResp.Error != nil || !ok || len(listResult.Tools) != 1 {+ t.Fatalf("tools/list response = %+v", listResp)+ }++ callResp := DispatchMCPToolServerRequest(context.Background(), JSONRPCRequest{+ ID: json.RawMessage(`3`),+ Method: MCPMethodToolsCall,+ Params: json.RawMessage(`{"name":"get_fleet_context"}`),+ }, handlers)+ callResult, ok := callResp.Result.(MCPToolResult)+ if callResp.Error != nil || !ok || ToolResultText(callResult) != "ok" {+ t.Fatalf("tools/call response = %+v", callResp)+ }+ callResult.Content[0].Text = "changed"+ if handlerContent[0].Text != "ok" {+ t.Fatalf("tools/call response must detach handler content: source=%+v result=%+v", handlerContent, callResult.Content)+ }++ resourcesListResp := DispatchMCPToolServerRequest(context.Background(), JSONRPCRequest{+ ID: json.RawMessage(`7`),+ Method: MCPMethodResourcesList,+ }, handlers)+ resourcesList, ok := resourcesListResp.Result.(MCPListResourcesResult)+ if resourcesListResp.Error != nil || !ok || len(resourcesList.Resources) != 1 {+ t.Fatalf("resources/list response = %+v", resourcesListResp)+ }+ resourcesList.Resources[0].Name = "changed"+ if handlerResources[0].Name != "VM 101" {+ t.Fatalf("resources/list response must detach handler resources: source=%+v result=%+v", handlerResources, resourcesList.Resources)+ }++ resourcesReadResp := DispatchMCPToolServerRequest(context.Background(), JSONRPCRequest{+ ID: json.RawMessage(`8`),+ Method: MCPMethodResourcesRead,+ Params: json.RawMessage(`{"uri":"` + MCPResourceURI("vm:101") + `"}`),+ }, handlers)+ resourcesRead, ok := resourcesReadResp.Result.(MCPReadResourceResult)+ if resourcesReadResp.Error != nil || !ok || len(resourcesRead.Contents) != 1 {+ t.Fatalf("resources/read response = %+v", resourcesReadResp)+ }+ resourcesRead.Contents[0].Text = "changed"+ if handlerContents[0].Text != `{"canonicalId":"vm:101"}` {+ t.Fatalf("resources/read response must detach handler contents: source=%+v result=%+v", handlerContents, resourcesRead.Contents)+ }++ promptsListResp := DispatchMCPToolServerRequest(context.Background(), JSONRPCRequest{+ ID: json.RawMessage(`9`),+ Method: MCPMethodPromptsList,+ }, handlers)+ promptsList, ok := promptsListResp.Result.(MCPListPromptsResult)+ if promptsListResp.Error != nil || !ok || len(promptsList.Prompts) != 1 {+ t.Fatalf("prompts/list response = %+v", promptsListResp)+ }+ promptsList.Prompts[0].Description = "changed"+ if handlerPrompts[0].Description != "triage" {+ t.Fatalf("prompts/list response must detach handler prompts: source=%+v result=%+v", handlerPrompts, promptsList.Prompts)+ }++ promptsGetResp := DispatchMCPToolServerRequest(context.Background(), JSONRPCRequest{+ ID: json.RawMessage(`10`),+ Method: MCPMethodPromptsGet,+ Params: json.RawMessage(`{"name":"` + MCPPromptTriageFleet + `"}`),+ }, handlers)+ promptResult, ok := promptsGetResp.Result.(MCPGetPromptResult)+ if promptsGetResp.Error != nil || !ok || len(promptResult.Messages) != 1 {+ t.Fatalf("prompts/get response = %+v", promptsGetResp)+ }+ promptResult.Messages[0].Content.Text = "changed"+ if handlerPromptMessages[0].Content.Text != "triage now" {+ t.Fatalf("prompts/get response must detach handler messages: source=%+v result=%+v", handlerPromptMessages, promptResult.Messages)+ }++ pingResp := DispatchMCPToolServerRequest(context.Background(), JSONRPCRequest{+ ID: json.RawMessage(`4`),+ Method: MCPMethodPing,+ }, handlers)+ if pingResp.Error != nil {+ t.Fatalf("ping response = %+v", pingResp)+ }+ if _, ok := pingResp.Result.(map[string]any); !ok {+ t.Fatalf("ping result type = %T, want map[string]any", pingResp.Result)+ }++ callError := DispatchMCPToolServerRequest(context.Background(), JSONRPCRequest{+ ID: json.RawMessage(`5`),+ Method: MCPMethodToolsCall,+ }, MCPToolServerHandlers{+ ToolsCall: func(ctx context.Context, raw json.RawMessage) (MCPToolResult, error) {+ return MCPToolResult{}, errors.New("failed")+ },+ })+ if callError.Error == nil || callError.Error.Code != JSONRPCErrorInternal || callError.Error.Message != "failed" {+ t.Fatalf("tools/call error response = %+v", callError)+ }++ unknown := DispatchMCPToolServerRequest(context.Background(), JSONRPCRequest{+ ID: json.RawMessage(`6`),+ Method: "missing/method",+ }, handlers)+ if unknown.Error == nil || unknown.Error.Code != JSONRPCErrorMethodNotFound {+ t.Fatalf("unknown method response = %+v", unknown)+ }+}++func TestMCPResourceURIEncodesAndValidatesPulseResourceIDs(t *testing.T) {+ resourceID := "container:web/api"+ uri := MCPResourceURI(resourceID)+ if !strings.HasPrefix(uri, "pulse://resource/") {+ t.Fatalf("resource URI = %q, want pulse://resource/ prefix", uri)+ }+ got, err := ResourceIDFromMCPResourceURI(uri)+ if err != nil {+ t.Fatalf("ResourceIDFromMCPResourceURI(%q): %v", uri, err)+ }+ if got != resourceID {+ t.Fatalf("decoded resource id = %q, want %q", got, resourceID)+ }++ for _, rawURI := range []string{+ "",+ "https://pulse.example/api/agent/resource-context/vm:101",+ "pulse://resource/",+ "pulse://resource/vm:101?debug=true",+ "pulse://other/vm:101",+ } {+ if _, err := ResourceIDFromMCPResourceURI(rawURI); err == nil {+ t.Fatalf("ResourceIDFromMCPResourceURI(%q) unexpectedly succeeded", rawURI)+ }+ }+}++func TestMCPManifestToolServerProjectsManifestAndExecutesTools(t *testing.T) {+ type captured struct {+ method string+ path string+ token string+ }+ var got captured+ pulse := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ got.method = r.Method+ got.path = r.URL.Path+ got.token = r.Header.Get(AgentAPITokenHeader)+ w.WriteHeader(http.StatusAccepted)+ _, _ = w.Write([]byte(`{"accepted":true}`))+ }))+ defer pulse.Close()++ server := MCPManifestToolServer{+ ServerName: "pulse-mcp",+ ServerVersion: "0.1.0",+ EmitPulseNotifications: true,+ Client: pulse.Client(),+ BaseURL: pulse.URL,+ Token: "test-token",+ Manifest: Manifest{+ SurfaceContract: CanonicalManifest().SurfaceContract,+ SurfaceToolContracts: testPulseMCPSurfaceToolContracts(ResourceContextCapabilityName),+ Capabilities: []Capability{+ {Name: ResourceContextCapabilityName, Path: ResourceContextCapabilityPath, Method: http.MethodGet, Description: "depth"},+ {Name: SetOperatorStateCapabilityName, Path: OperatorStateCapabilityPath, Method: http.MethodPut, Description: "intent"},+ {Name: "subscribe_events", Path: "/api/agent/events", Method: http.MethodGet, Description: "stream"},+ },+ },+ }++ init := server.Initialize()+ if init.ServerInfo.Name != "pulse-mcp" || init.Capabilities.Tools == nil || len(init.Capabilities.Experimental) == 0 {+ t.Fatalf("initialize result = %+v", init)+ }+ if !strings.Contains(init.Instructions, "Pulse MCP is the external-agent adapter over Pulse Intelligence Core") {+ t.Fatalf("initialize instructions must carry manifest surface contract, got %q", init.Instructions)+ }++ list := server.ToolsList()+ if len(list.Tools) != 1 || list.Tools[0].Name != ResourceContextCapabilityName {+ t.Fatalf("tools/list result = %+v", list)+ }++ blockedRaw, err := json.Marshal(MCPCallToolParams{+ Name: SetOperatorStateCapabilityName,+ Arguments: map[string]any{ResourceIDArgumentName: "vm:101"},+ })+ if err != nil {+ t.Fatalf("marshal blocked params: %v", err)+ }+ if _, err := server.ToolsCall(context.Background(), blockedRaw); err == nil || !strings.Contains(err.Error(), "unknown tool: "+SetOperatorStateCapabilityName) {+ t.Fatalf("surface contract must block tools absent from Pulse MCP allowlist, err=%v", err)+ }++ raw, err := json.Marshal(MCPCallToolParams{+ Name: ResourceContextCapabilityName,+ Arguments: map[string]any{ResourceIDArgumentName: "vm:101"},+ })+ if err != nil {+ t.Fatalf("marshal params: %v", err)+ }+ result, err := server.ToolsCall(context.Background(), raw)+ if err != nil {+ t.Fatalf("ToolsCall: %v", err)+ }+ if got.method != http.MethodGet || got.path != "/api/agent/resource-context/vm:101" || got.token != "test-token" {+ t.Fatalf("upstream call = %+v", got)+ }+ if result.IsError || ToolResultText(result) != `{"accepted":true}` {+ t.Fatalf("tools/call result = %+v", result)+ }+ if result.StructuredContent["accepted"] != true {+ t.Fatalf("tools/call structuredContent = %+v, want accepted=true", result.StructuredContent)+ }++ onInitializeCount := 0+ handlers := server.Handlers(func() {+ onInitializeCount+++ })+ resp := DispatchMCPToolServerRequest(context.Background(), JSONRPCRequest{+ ID: json.RawMessage(`1`),+ Method: MCPMethodInitialize,+ }, handlers)+ if resp.Error != nil || onInitializeCount != 1 {+ t.Fatalf("dispatch initialize response = %+v onInitialize=%d", resp, onInitializeCount)+ }+}++func TestMCPManifestToolServerProjectsResourcesFromContextCapabilities(t *testing.T) {+ type captured struct {+ paths []string+ token string+ }+ var got captured+ pulse := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ got.paths = append(got.paths, r.URL.EscapedPath())+ got.token = r.Header.Get(AgentAPITokenHeader)+ w.Header().Set("Content-Type", "application/json")+ switch r.URL.EscapedPath() {+ case "/api/agent/fleet-context":+ _, _ = w.Write([]byte(`{+ "resources": [+ {+ "canonicalId": "vm:101",+ "resourceType": "virtual-machine",+ "resourceName": "Database VM",+ "technology": "proxmox",+ "pendingApprovalCount": 1,+ "findings": { "total": 2, "critical": 1, "warning": 1, "info": 0 }+ },+ { "canonicalId": "", "resourceName": "ignored" }+ ],+ "generatedAt": "2026-06-18T08:00:00Z"+ }`))+ case "/api/agent/resource-context/vm%3A101":+ _, _ = w.Write([]byte(`{"canonicalId":"vm:101","resourceName":"Database VM"}`))+ default:+ http.NotFound(w, r)+ }+ }))+ defer pulse.Close()++ server := MCPManifestToolServer{+ ServerName: "pulse-mcp",+ ServerVersion: "0.1.0",+ Client: pulse.Client(),+ BaseURL: pulse.URL,+ Token: "test-token",+ Manifest: Manifest{+ Capabilities: []Capability{+ {Name: FleetContextCapabilityName, Path: "/api/agent/fleet-context", Method: http.MethodGet, Description: "triage"},+ {Name: ResourceContextCapabilityName, Path: "/api/agent/resource-context/{resourceId}", Method: http.MethodGet, Description: "depth"},+ },+ },+ }++ init := server.Initialize()+ if init.Capabilities.Resources == nil {+ t.Fatalf("initialize result must advertise resources for context-capable manifest: %+v", init.Capabilities)+ }++ list, err := server.ResourcesList(context.Background())+ if err != nil {+ t.Fatalf("ResourcesList: %v", err)+ }+ if len(list.Resources) != 1 {+ t.Fatalf("resources/list = %+v, want one non-empty resource", list.Resources)+ }+ resource := list.Resources[0]+ if resource.URI != MCPResourceURI("vm:101") || resource.Name != "Database VM" || resource.MimeType != MCPResourceContextMIMEType {+ t.Fatalf("projected resource = %+v", resource)+ }+ for _, want := range []string{"virtual-machine", "proxmox", "findings: 2 total", "pending approvals: 1"} {+ if !strings.Contains(resource.Description, want) {+ t.Fatalf("resource description missing %q: %q", want, resource.Description)+ }+ }++ raw, err := json.Marshal(MCPReadResourceParams{URI: resource.URI})+ if err != nil {+ t.Fatalf("marshal read params: %v", err)+ }+ read, err := server.ResourcesRead(context.Background(), raw)+ if err != nil {+ t.Fatalf("ResourcesRead: %v", err)+ }+ if len(read.Contents) != 1 {+ t.Fatalf("resources/read contents = %+v", read.Contents)+ }+ content := read.Contents[0]+ if content.URI != resource.URI || content.MimeType != MCPResourceContextMIMEType {+ t.Fatalf("resource content = %+v", content)+ }+ if content.Text != `{"canonicalId":"vm:101","resourceName":"Database VM"}` {+ t.Fatalf("resource content text = %q", content.Text)+ }+ if got.token != "test-token" {+ t.Fatalf("upstream token = %q, want test-token", got.token)+ }+ if strings.Join(got.paths, ",") != "/api/agent/fleet-context,/api/agent/resource-context/vm%3A101" {+ t.Fatalf("upstream paths = %+v", got.paths)+ }+}++func TestMCPManifestResourceProjectionUsesSurfaceAffordanceAndContextCapabilities(t *testing.T) {+ capabilities := []Capability{+ {Name: FleetContextCapabilityName, Path: FleetContextCapabilityPath, Method: http.MethodGet},+ {Name: ResourceContextCapabilityName, Path: ResourceContextCapabilityPath, Method: http.MethodGet},+ }+ if !MCPManifestResourceProjectionSupported(Manifest{Capabilities: capabilities}, SurfaceIDPulseMCP) {+ t.Fatal("legacy Pulse MCP manifests with both context capabilities should support resources")+ }+ if got := ManifestSurfaceResourceCapabilities(Manifest{Capabilities: capabilities}, SurfaceIDPulseMCP); len(got) != 2 {+ t.Fatalf("surface resource capabilities = %+v, want fleet and resource context", got)+ }++ surfaceContract := CanonicalManifest().SurfaceContract+ for i := range surfaceContract.OperatorSurfaces {+ if surfaceContract.OperatorSurfaces[i].ID == SurfaceIDPulseMCP {+ surfaceContract.OperatorSurfaces[i].Affordances = SurfaceAffordanceContract{Tools: true}+ }+ }+ disabled := Manifest{SurfaceContract: surfaceContract, Capabilities: capabilities}+ if MCPManifestResourceProjectionSupported(disabled, SurfaceIDPulseMCP) {+ t.Fatal("surface-disabled resource affordance must block MCP resources")+ }+ if got := ManifestSurfaceResourceCapabilities(disabled, SurfaceIDPulseMCP); len(got) != 0 {+ t.Fatalf("surface-disabled resource capabilities = %+v, want none", got)+ }++ missingResourceContext := Manifest{Capabilities: capabilities[:1]}+ if MCPManifestResourceProjectionSupported(missingResourceContext, SurfaceIDPulseMCP) {+ t.Fatal("MCP resources must require both fleet and resource context capabilities")+ }+}++func TestMCPManifestToolServerProjectsWorkflowPromptsFromManifest(t *testing.T) {+ capabilities := []Capability{+ {Name: FleetContextCapabilityName, Path: FleetContextCapabilityPath, Method: http.MethodGet, Description: "triage"},+ {Name: ResourceContextCapabilityName, Path: ResourceContextCapabilityPath, Method: http.MethodGet, Description: "depth"},+ {Name: ListFindingsCapabilityName, Path: "/api/ai/patrol/findings", Method: http.MethodGet, Description: "findings"},+ }+ recordedPrompts := []string{}+ server := MCPManifestToolServer{+ ServerName: "pulse-mcp",+ ServerVersion: "0.1.0",+ Manifest: Manifest{+ Capabilities: capabilities,+ WorkflowPrompts: []PulseWorkflowPrompt{{+ Name: PulseWorkflowPromptInvestigateResource,+ Label: "Inspect this resource",+ Description: "Investigate one resource from manifest metadata.",+ Arguments: []PulseWorkflowPromptArgument{{+ Name: ResourceIDArgumentName,+ Description: "Canonical resource id.",+ Required: true,+ }},+ }},+ },+ RecordWorkflowPromptActivity: func(_ context.Context, promptName string) {+ recordedPrompts = append(recordedPrompts, promptName)+ },+ }++ init := server.Initialize()+ if init.Capabilities.Prompts == nil {+ t.Fatalf("initialize result must advertise prompts for prompt-capable manifests: %+v", init.Capabilities)+ }++ list := server.PromptsList()+ if len(list.Prompts) != 1 {+ t.Fatalf("prompts/list = %+v, want one manifest-backed prompt", list.Prompts)+ }+ names := map[string]MCPPrompt{}+ for _, prompt := range list.Prompts {+ names[prompt.Name] = prompt+ }+ if _, ok := names[MCPPromptTriageFleet]; ok {+ t.Fatalf("prompts/list must honor manifest workflowPrompts instead of reprojecting capabilities: %+v", list.Prompts)+ }+ resourcePrompt := names[MCPPromptInvestigateResource]+ if resourcePrompt.Title != "Inspect this resource" {+ t.Fatalf("resource prompt title = %q", resourcePrompt.Title)+ }+ if len(resourcePrompt.Arguments) != 1 || resourcePrompt.Arguments[0].Name != ResourceIDArgumentName || !resourcePrompt.Arguments[0].Required {+ t.Fatalf("resource prompt arguments = %+v", resourcePrompt.Arguments)+ }++ raw, err := json.Marshal(MCPGetPromptParams{+ Name: MCPPromptInvestigateResource,+ Arguments: map[string]string{ResourceIDArgumentName: "vm:101"},+ })+ if err != nil {+ t.Fatalf("marshal prompt params: %v", err)+ }+ result, err := server.PromptsGet(context.Background(), raw)+ if err != nil {+ t.Fatalf("PromptsGet: %v", err)+ }+ if result.Description != "Pulse resource investigation" || len(result.Messages) != 1 {+ t.Fatalf("prompts/get result = %+v", result)+ }+ if len(recordedPrompts) != 1 || recordedPrompts[0] != MCPPromptInvestigateResource {+ t.Fatalf("recorded prompts = %+v, want [%s]", recordedPrompts, MCPPromptInvestigateResource)+ }+ message := result.Messages[0]+ if message.Role != "user" || message.Content.Type != "text" {+ t.Fatalf("prompt message = %+v", message)+ }+ for _, want := range []string{`"vm:101"`, MCPResourceURI("vm:101"), ResourceContextCapabilityName, ResourceIDArgumentName, "Do not execute write tools"} {+ if !strings.Contains(message.Content.Text, want) {+ t.Fatalf("resource prompt missing %q: %q", want, message.Content.Text)+ }+ }++ raw, err = json.Marshal(MCPGetPromptParams{Name: MCPPromptTriageFleet})+ if err != nil {+ t.Fatalf("marshal prompt params: %v", err)+ }+ if _, err := server.PromptsGet(context.Background(), raw); err == nil || !strings.Contains(err.Error(), "unknown prompt") {+ t.Fatalf("PromptsGet must reject prompts not declared by workflowPrompts; err=%v", err)+ }+ if len(recordedPrompts) != 1 {+ t.Fatalf("failed prompts/get must not record activity, got %+v", recordedPrompts)+ }+}++func TestMCPManifestSurfacePromptProjectionSupportedHonorsSurfaceAffordances(t *testing.T) {+ manifest := Manifest{+ SurfaceContract: CanonicalManifest().SurfaceContract,+ Capabilities: []Capability{{+ Name: FleetContextCapabilityName,+ Path: FleetContextCapabilityPath,+ Method: http.MethodGet,+ }},+ WorkflowPrompts: []PulseWorkflowPrompt{{+ Name: PulseWorkflowPromptTriageFleet,+ }},+ }+ if !MCPManifestSurfacePromptProjectionSupported(manifest, SurfaceIDPulseMCP) {+ t.Fatal("Pulse MCP surface with prompt affordance and workflow prompts must support prompt projection")+ }++ promptsDisabled := manifest+ for i := range promptsDisabled.SurfaceContract.OperatorSurfaces {+ if promptsDisabled.SurfaceContract.OperatorSurfaces[i].ID == SurfaceIDPulseMCP {+ promptsDisabled.SurfaceContract.OperatorSurfaces[i].Affordances = SurfaceAffordanceContract{Tools: true}+ }+ }+ if MCPManifestSurfacePromptProjectionSupported(promptsDisabled, SurfaceIDPulseMCP) {+ t.Fatal("surface without prompt affordance must not support prompt projection")+ }++ withoutPrompts := manifest+ withoutPrompts.WorkflowPrompts = []PulseWorkflowPrompt{}+ if MCPManifestSurfacePromptProjectionSupported(withoutPrompts, SurfaceIDPulseMCP) {+ t.Fatal("surface with prompt affordance but no workflow prompts must not support prompt projection")+ }+}++func TestMCPManifestToolServerPromptsGetUsesSurfacePromptProjectionGate(t *testing.T) {+ rawPrompt, err := json.Marshal(MCPGetPromptParams{Name: MCPPromptTriageFleet})+ if err != nil {+ t.Fatalf("marshal prompt params: %v", err)+ }+ server := MCPManifestToolServer{+ ServerName: "pulse-mcp",+ ServerVersion: "0.1.0",+ Manifest: Manifest{+ SurfaceContract: CanonicalManifest().SurfaceContract,+ Capabilities: []Capability{{+ Name: FleetContextCapabilityName,+ Path: FleetContextCapabilityPath,+ Method: http.MethodGet,+ }},+ WorkflowPrompts: []PulseWorkflowPrompt{},+ },+ }++ if init := server.Initialize(); init.Capabilities.Prompts != nil {+ t.Fatalf("initialize must not advertise prompts for an explicitly empty workflow prompt catalogue: %+v", init.Capabilities.Prompts)+ }+ if prompts := server.PromptsList(); len(prompts.Prompts) != 0 {+ t.Fatalf("PromptsList = %+v, want empty prompts", prompts)+ }+ if _, err := server.PromptsGet(context.Background(), rawPrompt); err == nil || !strings.Contains(err.Error(), "prompts are not enabled") {+ t.Fatalf("PromptsGet must use the same surface prompt projection gate as initialize/list; err=%v", err)+ }+}++func TestMCPPromptParamsNormalizeAndRejectInvalidShape(t *testing.T) {+ source := map[string]string{ResourceIDArgumentName: "vm:101"}+ params := MCPGetPromptParams{+ Name: " " + MCPPromptInvestigateResource + " ",+ Arguments: source,+ }.NormalizeCollections()+ if params.Name != MCPPromptInvestigateResource || params.Arguments[ResourceIDArgumentName] != "vm:101" {+ t.Fatalf("normalized prompt params = %+v", params)+ }+ params.Arguments[ResourceIDArgumentName] = "vm:102"+ if source[ResourceIDArgumentName] != "vm:101" {+ t.Fatalf("normalized prompt params aliased source: source=%+v params=%+v", source, params.Arguments)+ }++ decoded, err := DecodeMCPGetPromptParams(json.RawMessage(`{"name":" ` + MCPPromptTriageFleet + ` "}`))+ if err != nil {+ t.Fatalf("DecodeMCPGetPromptParams: %v", err)+ }+ if decoded.Name != MCPPromptTriageFleet || decoded.Arguments == nil || len(decoded.Arguments) != 0 {+ t.Fatalf("decoded prompt params = %+v", decoded)+ }++ if _, err := DecodeMCPGetPromptParams(nil); err == nil || !strings.Contains(err.Error(), "prompt name is required") {+ t.Fatalf("missing prompt name error = %v", err)+ }++ declared, err := BuildMCPPromptFromManifest(Manifest{+ WorkflowPrompts: []PulseWorkflowPrompt{{+ Name: MCPPromptTriageFleet,+ }},+ }, MCPGetPromptParams{Name: MCPPromptTriageFleet})+ if err != nil {+ t.Fatalf("manifest-declared MCP prompt: %v", err)+ }+ if len(declared.Messages) != 1 || !strings.Contains(declared.Messages[0].Content.Text, FleetContextCapabilityName) {+ t.Fatalf("manifest-declared MCP prompt result = %+v", declared)+ }++ _, err = BuildMCPPromptFromManifest(Manifest{+ Capabilities: []Capability{{Name: ResourceContextCapabilityName}},+ WorkflowPrompts: []PulseWorkflowPrompt{{+ Name: MCPPromptInvestigateResource,+ }},+ }, MCPGetPromptParams{Name: MCPPromptInvestigateResource})+ if err == nil || err.Error() != "prompt argument "+ResourceIDArgumentName+" is required" {+ t.Fatalf("missing resourceId error = %v", err)+ }++ _, err = BuildMCPPromptFromManifest(Manifest{+ Capabilities: []Capability{{Name: FleetContextCapabilityName}},+ WorkflowPrompts: []PulseWorkflowPrompt{+ {Name: MCPPromptInvestigateResource},+ },+ }, MCPGetPromptParams{Name: MCPPromptTriageFleet})+ if err == nil || err.Error() != "unknown prompt: pulse_triage_fleet" {+ t.Fatalf("unknown prompt error = %v", err)+ }+}++func TestMCPMethodPayloadsUseSharedContracts(t *testing.T) {+ init := NewMCPToolServerInitializeResult("pulse-mcp", "0.1.0", true)+ body, err := json.Marshal(init)+ if err != nil {+ t.Fatalf("marshal initialize result: %v", err)+ }+ text := string(body)+ for _, want := range []string{+ `"protocolVersion":"2025-06-18"`,+ `"tools":{}`,+ `"pulseNotifications":{"kinds":`,+ `"finding.created"`,+ `"serverInfo":{"name":"pulse-mcp","version":"0.1.0"}`,+ } {+ if !strings.Contains(text, want) {+ t.Fatalf("initialize result missing %s: %s", want, text)+ }+ }++ call := MCPCallToolParams{+ Name: "get_resource_context",+ Arguments: map[string]any{"resourceId": "vm:101"},+ }+ body, err = json.Marshal(call)+ if err != nil {+ t.Fatalf("marshal call params: %v", err)+ }+ var decoded MCPCallToolParams+ if err := json.Unmarshal(body, &decoded); err != nil {+ t.Fatalf("unmarshal call params: %v", err)+ }+ if decoded.Name != call.Name || decoded.Arguments["resourceId"] != "vm:101" {+ t.Fatalf("call params did not round-trip through shared shape: %+v", decoded)+ }+}++func TestToolCallParamsNormalizeAndValidateSharedContract(t *testing.T) {+ source := map[string]any{+ "resourceId": "vm:101",+ "body": map[string]any{+ "note": "maintenance",+ "tags": []any{"planned"},+ },+ }+ normalized := NormalizeToolCallParams(ToolCallParams{+ Name: " get_resource_context ",+ Arguments: source,+ })+ if normalized.Name != "get_resource_context" {+ t.Fatalf("normalized name = %q, want get_resource_context", normalized.Name)+ }+ if normalized.Arguments["resourceId"] != "vm:101" {+ t.Fatalf("normalized arguments = %#v", normalized.Arguments)+ }+ normalized.Arguments["resourceId"] = "vm:102"+ if source["resourceId"] != "vm:101" {+ t.Fatalf("normalized arguments aliased source: source=%#v normalized=%#v", source, normalized.Arguments)+ }+ normalizedBody := normalized.Arguments["body"].(map[string]any)+ normalizedBody["note"] = "changed"+ normalizedBody["tags"].([]any)[0] = "changed"+ sourceBody := source["body"].(map[string]any)+ if sourceBody["note"] != "maintenance" || sourceBody["tags"].([]any)[0] != "planned" {+ t.Fatalf("normalized nested arguments aliased source: source=%#v normalized=%#v", source, normalized.Arguments)+ }++ emptyArgs := NormalizeToolCallParams(ToolCallParams{Name: "ping"})+ if emptyArgs.Arguments == nil || len(emptyArgs.Arguments) != 0 {+ t.Fatalf("missing arguments must normalize to empty object: %#v", emptyArgs.Arguments)+ }++ if err := ValidateToolCallParams(ToolCallParams{Name: " "}); err == nil || err.Error() != "tool name is required" {+ t.Fatalf("blank name validation error = %v", err)+ }+}++func TestPrepareToolRegistryExecutionUsesSharedFailureResults(t *testing.T) {+ source := map[string]any{+ "resourceId": "vm:101",+ "body": map[string]any{"note": "maintenance"},+ }+ params, invalid, ok := PrepareToolRegistryExecution(" read_resource ", source)+ if !ok {+ t.Fatalf("valid registry execution returned invalid result: %+v", invalid)+ }+ if params.Name != "read_resource" || params.Arguments["resourceId"] != "vm:101" {+ t.Fatalf("params = %+v", params)+ }+ params.Arguments["resourceId"] = "vm:102"+ params.Arguments["body"].(map[string]any)["note"] = "changed"+ if source["resourceId"] != "vm:101" || source["body"].(map[string]any)["note"] != "maintenance" {+ t.Fatalf("registry execution params aliased source: source=%#v params=%#v", source, params)+ }++ _, invalid, ok = PrepareToolRegistryExecution(" ", nil)+ if ok {+ t.Fatalf("blank tool name unexpectedly prepared")+ }+ interpreted := InterpretToolResult(invalid)+ if !interpreted.IsError || interpreted.Text != "invalid tools/call params: tool name is required" {+ t.Fatalf("invalid result = %+v interpreted=%+v", invalid, interpreted)+ }++ unknown := InterpretToolResult(NewUnknownToolResult(" missing "))+ if !unknown.IsError || unknown.Text != "unknown tool: missing" {+ t.Fatalf("unknown result = %+v", unknown)+ }++ disabled := InterpretToolResult(NewControlToolsDisabledToolResult())+ if disabled.IsError || disabled.Text != ControlToolsDisabledMessage {+ t.Fatalf("control-disabled result = %+v", disabled)+ }+}++func TestDecodeMCPCallToolParamsNormalizesAndRejectsInvalidShape(t *testing.T) {+ decoded, err := DecodeMCPCallToolParams(json.RawMessage(`{"name":" get_fleet_context "}`))+ if err != nil {+ t.Fatalf("DecodeMCPCallToolParams: %v", err)+ }+ if decoded.Name != "get_fleet_context" {+ t.Fatalf("decoded name = %q, want get_fleet_context", decoded.Name)+ }+ if decoded.Arguments == nil || len(decoded.Arguments) != 0 {+ t.Fatalf("decoded arguments = %#v, want empty object", decoded.Arguments)+ }++ for _, raw := range []json.RawMessage{+ json.RawMessage(`{}`),+ json.RawMessage(`{"name":" ","arguments":{}}`),+ } {+ if _, err := DecodeMCPCallToolParams(raw); err == nil || !strings.Contains(err.Error(), "decode tools/call params: tool name is required") {+ t.Fatalf("invalid params %s error = %v", raw, err)+ }+ }+}++func TestExecuteCapabilityToolHTTPProjectsManifestCallAndWrapsSharedResult(t *testing.T) {+ var got struct {+ Method string+ Path string+ Token string+ ContentType string+ Body string+ }+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ got.Method = r.Method+ got.Path = r.URL.EscapedPath()+ got.Token = r.Header.Get(AgentAPITokenHeader)+ got.ContentType = r.Header.Get("Content-Type")+ body, _ := io.ReadAll(r.Body)+ got.Body = string(body)+ w.WriteHeader(http.StatusAccepted)+ _, _ = w.Write([]byte(`{"accepted":true}`))+ }))+ defer server.Close()++ result, err := ExecuteCapabilityToolHTTP(context.Background(), server.Client(), server.URL, "test-token", []Capability{{+ Name: SetOperatorStateCapabilityName,+ Method: http.MethodPut,+ Path: OperatorStateCapabilityPath,+ }}, ToolCallParams{+ Name: SetOperatorStateCapabilityName,+ Arguments: map[string]any{+ ResourceIDArgumentName: "vm:101/console",+ "intentionallyOffline": true,+ "neverAutoRemediate": false,+ "maintenanceReference": "ticket-1",+ },+ })+ if err != nil {+ t.Fatalf("ExecuteCapabilityToolHTTP: %v", err)+ }++ if got.Method != http.MethodPut {+ t.Fatalf("method = %s, want PUT", got.Method)+ }+ if got.Path != "/api/resources/vm%3A101%2Fconsole/operator-state" {+ t.Fatalf("path = %s", got.Path)+ }+ if got.Token != "test-token" {+ t.Fatalf("%s = %q", AgentAPITokenHeader, got.Token)+ }+ if got.ContentType != "application/json" {+ t.Fatalf("Content-Type = %q, want application/json", got.ContentType)+ }+ if strings.Contains(got.Body, ResourceIDArgumentName) {+ t.Fatalf("body must not duplicate path arg: %s", got.Body)+ }+ for _, want := range []string{`"intentionallyOffline":true`, `"neverAutoRemediate":false`, `"maintenanceReference":"ticket-1"`} {+ if !strings.Contains(got.Body, want) {+ t.Fatalf("body missing %s: %s", want, got.Body)+ }+ }+ if result.IsError {+ t.Fatalf("2xx upstream response must become shared tool success: %+v", result)+ }+ if len(result.Content) != 1 || result.Content[0].Text != `{"accepted":true}` {+ t.Fatalf("tool result = %+v", result)+ }+}++func TestExecuteCapabilityToolHTTPPreservesNon2xxAsSharedError(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusForbidden)+ _, _ = w.Write([]byte(`{"error":"scope_required","message":"monitoring:write is required"}`))+ }))+ defer server.Close()++ result, err := ExecuteCapabilityToolHTTP(context.Background(), server.Client(), server.URL, "test-token", []Capability{{+ Name: SetOperatorStateCapabilityName,+ Method: http.MethodPut,+ Path: OperatorStateCapabilityPath,+ }}, ToolCallParams{+ Name: SetOperatorStateCapabilityName,+ Arguments: map[string]any{ResourceIDArgumentName: "vm:101", "body": map[string]any{"offline": true}},+ })+ if err != nil {+ t.Fatalf("ExecuteCapabilityToolHTTP: %v", err)+ }+ if !result.IsError {+ t.Fatalf("non-2xx upstream response must become shared tool error: %+v", result)+ }+ if len(result.Content) != 1 || result.Content[0].Text != `{"error":"scope_required","message":"monitoring:write is required"}` {+ t.Fatalf("tool result = %+v", result)+ }+}++func TestExecuteCapabilityToolHTTPRejectsStreamingCapabilities(t *testing.T) {+ called := false+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ called = true+ t.Fatalf("streaming capability must not be invoked through request/response tool execution")+ }))+ defer server.Close()++ _, err := ExecuteCapabilityToolHTTP(context.Background(), server.Client(), server.URL, "test-token", []Capability{{+ Name: EventSubscriptionCapabilityName,+ Method: http.MethodGet,+ Path: AgentEventsPath,+ }}, ToolCallParams{Name: "subscribe_events", Arguments: map[string]any{}})+ if err == nil {+ t.Fatal("expected streaming capability to be rejected")+ }+ if err.Error() != "unknown tool: subscribe_events" {+ t.Fatalf("error = %q, want unknown tool", err.Error())+ }+ if called {+ t.Fatal("streaming capability reached upstream HTTP server")+ }+}++func TestExecuteCapabilityToolHTTPReturnsStableValidationAndLookupErrors(t *testing.T) {+ _, err := ExecuteCapabilityToolHTTP(context.Background(), nil, "http://pulse.local", "token", nil, ToolCallParams{Name: " ", Arguments: map[string]any{}})+ if err == nil || err.Error() != "tool name is required" {+ t.Fatalf("invalid params error = %v", err)+ }++ _, err = ExecuteCapabilityToolHTTP(context.Background(), nil, "http://pulse.local", "token", []Capability{{+ Name: "get_fleet_context",+ Method: http.MethodGet,+ Path: "/api/agent/fleet-context",+ }}, ToolCallParams{Name: "missing_capability", Arguments: map[string]any{}})+ if err == nil || err.Error() != "unknown tool: missing_capability" {+ t.Fatalf("unknown tool error = %v", err)+ }+}++func TestExecuteMCPManifestSurfaceToolHTTPReturnsStableDecodeErrorsAndRequiresSurfaceContract(t *testing.T) {+ _, err := ExecuteMCPManifestSurfaceToolHTTP(context.Background(), nil, "http://pulse.local", "token", Manifest{}, SurfaceIDPulseMCP, json.RawMessage(`{"name":`))+ if err == nil || !strings.Contains(err.Error(), "decode tools/call params") {+ t.Fatalf("decode error = %v", err)+ }++ _, err = ExecuteMCPManifestSurfaceToolHTTP(context.Background(), nil, "http://pulse.local", "token", Manifest{}, SurfaceIDPulseMCP, json.RawMessage(`{"name":" ","arguments":{}}`))+ if err == nil || !strings.Contains(err.Error(), "decode tools/call params: tool name is required") {+ t.Fatalf("invalid params error = %v", err)+ }++ manifest := Manifest{+ SurfaceContract: CanonicalManifest().SurfaceContract,+ Capabilities: []Capability{{+ Name: ResourceContextCapabilityName,+ Method: http.MethodGet,+ Path: ResourceContextCapabilityPath,+ }},+ }+ _, err = ExecuteMCPManifestSurfaceToolHTTP(context.Background(), nil, "http://pulse.local", "token", manifest, SurfaceIDPulseMCP, json.RawMessage(`{"name":"get_resource_context","arguments":{"resourceId":"vm:101"}}`))+ if err == nil || err.Error() != "unknown tool: get_resource_context" {+ t.Fatalf("missing surface contract error = %v, want unknown tool", err)+ }++ manifest.SurfaceToolContracts = []SurfaceToolContract{{+ SurfaceID: SurfaceIDPulseMCP,+ ToolSource: SurfaceToolSourceCapabilityManifest,+ ToolNames: []string{FleetContextCapabilityName},+ Affordances: DefaultSurfaceAffordancesForID(SurfaceIDPulseMCP),+ }}+ manifest.Capabilities = []Capability{{+ Name: FleetContextCapabilityName,+ Method: http.MethodGet,+ Path: "/api/agent/fleet-context",+ }}+ _, err = ExecuteMCPManifestSurfaceToolHTTP(context.Background(), nil, "http://pulse.local", "token", manifest, SurfaceIDPulseMCP, json.RawMessage(`{"name":"missing_capability","arguments":{}}`))+ if err == nil || err.Error() != "unknown tool: missing_capability" {+ t.Fatalf("unknown tool error = %v", err)+ }+}diff --git a/internal/agentcapabilities/projection.go b/internal/agentcapabilities/projection.gonew file mode 100644index 0000000000..d3c7b78d20--- /dev/null+++ b/internal/agentcapabilities/projection.go@@ -0,0 +1,619 @@+package agentcapabilities++import (+ "encoding/json"+ "fmt"+ "net/http"+ "regexp"+ "strings"+)++const (+ // FleetContextCapabilityName is the manifest-owned fleet triage read.+ FleetContextCapabilityName = "get_fleet_context"+ // ResourceContextCapabilityName is the manifest-owned per-resource depth read.+ ResourceContextCapabilityName = "get_resource_context"+ // PatrolControlStatusCapabilityName is the manifest-owned Patrol control+ // status read. It is count-only and content-safe so external agents can+ // orient on the same Patrol -> Assistant -> governed action ->+ // verification loop without fetching finding/action identifiers or+ // command output first.+ PatrolControlStatusCapabilityName = "get_patrol_control_status"+ // OperationsLoopStatusCapabilityName is retained as a source compatibility+ // alias while the manifest projects Patrol control as the canonical+ // external-agent capability.+ OperationsLoopStatusCapabilityName = PatrolControlStatusCapabilityName+ // ResourceIDArgumentName is the shared path/body argument for canonical+ // resource identity in Pulse Intelligence context and action tools.+ ResourceIDArgumentName = "resourceId"+ // FleetContextCapabilityPath is the manifest-owned fleet triage route.+ FleetContextCapabilityPath = "/api/agent/fleet-context"+ // ResourceContextCapabilityPath is the manifest-owned per-resource context route.+ ResourceContextCapabilityPath = "/api/agent/resource-context/{" + ResourceIDArgumentName + "}"+ // PatrolControlStatusCapabilityPath is the manifest-owned Patrol control+ // status route.+ PatrolControlStatusCapabilityPath = "/api/agent/patrol-control/status"+ // OperationsLoopStatusCapabilityPath is retained as a source compatibility+ // alias while the manifest projects Patrol control as the canonical route.+ OperationsLoopStatusCapabilityPath = PatrolControlStatusCapabilityPath+ // OperationsLoopStatusCompatibilityPath is the legacy route kept for older+ // external-agent clients.+ OperationsLoopStatusCompatibilityPath = "/api/agent/operations-loop/status"+ // GetOperatorStateCapabilityName is the manifest-owned operator-state read.+ GetOperatorStateCapabilityName = "get_operator_state"+ // SetOperatorStateCapabilityName is the manifest-owned operator-state write.+ SetOperatorStateCapabilityName = "set_operator_state"+ // ClearOperatorStateCapabilityName is the manifest-owned operator-state clear.+ ClearOperatorStateCapabilityName = "clear_operator_state"+ // OperatorStateCapabilityPath is the shared operator-state route template.+ OperatorStateCapabilityPath = "/api/resources/{" + ResourceIDArgumentName + "}/operator-state"+ // ListNodesCapabilityName is the manifest-owned configured-source list read.+ ListNodesCapabilityName = "list_nodes"+ // AddNodeCapabilityName is the manifest-owned configured-source create action.+ AddNodeCapabilityName = "add_node"+ // UpdateNodeCapabilityName is the manifest-owned configured-source update action.+ UpdateNodeCapabilityName = "update_node"+ // RemoveNodeCapabilityName is the manifest-owned configured-source delete action.+ RemoveNodeCapabilityName = "remove_node"+ // TestNodeCredentialsCapabilityName is the manifest-owned proposed-source credential validation action.+ TestNodeCredentialsCapabilityName = "test_node_credentials"+ // TestNodeConnectionCapabilityName is the manifest-owned saved-source connection validation action.+ TestNodeConnectionCapabilityName = "test_node_connection"+ // RefreshNodeClusterMembershipCapabilityName is the manifest-owned Proxmox cluster endpoint refresh action.+ RefreshNodeClusterMembershipCapabilityName = "refresh_node_cluster_membership"+ // DiscoverLANCapabilityName is the manifest-owned LAN discovery scan action.+ DiscoverLANCapabilityName = "discover_lan"+ // ListFindingsCapabilityName is the manifest-owned Patrol finding list read.+ ListFindingsCapabilityName = "list_findings"+ // AcknowledgeFindingCapabilityName is the manifest-owned Patrol acknowledge write.+ AcknowledgeFindingCapabilityName = "acknowledge_finding"+ // SnoozeFindingCapabilityName is the manifest-owned Patrol snooze write.+ SnoozeFindingCapabilityName = "snooze_finding"+ // DismissFindingCapabilityName is the manifest-owned Patrol dismiss write.+ DismissFindingCapabilityName = "dismiss_finding"+ // ResolveFindingCapabilityName is the manifest-owned Patrol resolve write.+ ResolveFindingCapabilityName = "resolve_finding"+ // FindingIDArgumentName is the shared argument for Patrol finding identity.+ FindingIDArgumentName = "finding_id"+ // ResolutionNoteArgumentName is the shared operator/agent explanation for+ // why a Patrol finding is being marked resolved.+ ResolutionNoteArgumentName = "resolution_note"+ // NoteArgumentName is the shared optional operator note argument used by+ // Patrol finding lifecycle actions that accept freeform context.+ NoteArgumentName = "note"+ // PlanActionCapabilityName is the manifest-owned governed action planner.+ PlanActionCapabilityName = "plan_action"+ // DecideActionCapabilityName is the manifest-owned governed action decision writer.+ DecideActionCapabilityName = "decide_action"+ // ExecuteActionCapabilityName is the manifest-owned governed action executor.+ ExecuteActionCapabilityName = "execute_action"+ // RequestIDArgumentName is the shared idempotency/correlation argument.+ RequestIDArgumentName = "requestId"+ // ActionIDArgumentName is the shared durable governed action id argument.+ ActionIDArgumentName = "actionId"+ // CapabilityNameArgumentName is the shared target resource capability argument.+ CapabilityNameArgumentName = "capabilityName"+ // ReasonArgumentName is the shared operator-readable reason argument.+ ReasonArgumentName = "reason"+ // RequestedByArgumentName is the shared stable requester identity argument.+ RequestedByArgumentName = "requestedBy"+ // OutcomeArgumentName is the shared approval decision argument.+ OutcomeArgumentName = "outcome"+ // PlanActionCapabilityPath is the manifest-owned governed action planning route.+ PlanActionCapabilityPath = "/api/actions/plan"+ // ActionDecisionCapabilityPath is the manifest-owned governed action decision route template.+ ActionDecisionCapabilityPath = "/api/actions/{" + ActionIDArgumentName + "}/decision"+ // ActionExecutionCapabilityPath is the manifest-owned governed action execution route template.+ ActionExecutionCapabilityPath = "/api/actions/{" + ActionIDArgumentName + "}/execute"+ // EventSubscriptionCapabilityName is the manifest-owned streaming+ // capability. It is intentionally not projected as a request/response tool.+ EventSubscriptionCapabilityName = "subscribe_events"+ // ToolMetaPulseCapabilityKey is the namespaced _meta key containing+ // structured Pulse capability metadata for external-agent tools projected+ // from the canonical manifest.+ ToolMetaPulseCapabilityKey = "pulse.capability"+)++// ProjectedTool is the manifest-backed request/response tool shape consumed by+// MCP and other external-agent adapters.+type ProjectedTool struct {+ Name string `json:"name"`+ Title string `json:"title,omitempty"`+ Description string `json:"description"`+ InputSchema json.RawMessage `json:"inputSchema"`+ OutputSchema json.RawMessage `json:"outputSchema,omitempty"`+ Annotations *ToolBehaviorHints `json:"annotations,omitempty"`+ Meta map[string]any `json:"_meta,omitempty"`+}++// ToolBehaviorHints are the external-agent behavior hints projected from the+// manifest action-mode and approval-policy posture. They are hints for clients,+// not an authorization boundary; Pulse API scopes and governed action approval+// remain the enforcement layer.+type ToolBehaviorHints struct {+ Title string `json:"title,omitempty"`+ ReadOnlyHint *bool `json:"readOnlyHint,omitempty"`+ DestructiveHint *bool `json:"destructiveHint,omitempty"`+ IdempotentHint *bool `json:"idempotentHint,omitempty"`+ OpenWorldHint *bool `json:"openWorldHint,omitempty"`+}++// pathPlaceholderRE matches `{paramName}` in capability paths.+var pathPlaceholderRE = regexp.MustCompile(`\{([a-zA-Z][a-zA-Z0-9]*)\}`)++// OperationsLoopCapabilityNames returns the canonical capability set required+// for an external agent to run the Pulse Intelligence operations loop without+// falling back to native-only UI state.+func OperationsLoopCapabilityNames() []string {+ return []string{+ OperationsLoopStatusCapabilityName,+ FleetContextCapabilityName,+ ResourceContextCapabilityName,+ ListFindingsCapabilityName,+ PlanActionCapabilityName,+ DecideActionCapabilityName,+ ExecuteActionCapabilityName,+ ResolveFindingCapabilityName,+ }+}++// IsRequestResponseCapability reports whether a capability can be projected as+// a request/response external-agent tool.+func IsRequestResponseCapability(cap Capability) bool {+ return cap.Name != EventSubscriptionCapabilityName+}++// FindCapability returns the capability with the given manifest name.+func FindCapability(capabilities []Capability, name string) (Capability, bool) {+ for _, cap := range capabilities {+ if cap.Name == name {+ return CloneCapability(cap), true+ }+ }+ return Capability{}, false+}++// CapabilityLookupError is returned when a named manifest capability cannot be+// resolved. Adapters can translate the wording for their own surface while+// preserving the shared lookup semantics.+type CapabilityLookupError struct {+ Name string+}++func (e CapabilityLookupError) Error() string {+ return fmt.Sprintf("unknown capability: %s", e.Name)+}++// ResolveCapability returns the capability with the given manifest name or a+// typed lookup error when it is absent.+func ResolveCapability(capabilities []Capability, name string) (Capability, error) {+ cap, ok := FindCapability(capabilities, name)+ if !ok {+ return Capability{}, CapabilityLookupError{Name: name}+ }+ return cap, nil+}++// ResolveRequestResponseCapability returns a manifest capability only when it+// is eligible for request/response tool projection. Streaming capabilities+// intentionally look absent to tools/call-style adapters because they belong+// on the shared SSE subscription path instead.+func ResolveRequestResponseCapability(capabilities []Capability, name string) (Capability, error) {+ cap, err := ResolveCapability(capabilities, name)+ if err != nil {+ return Capability{}, err+ }+ if !IsRequestResponseCapability(cap) {+ return Capability{}, CapabilityLookupError{Name: name}+ }+ return cap, nil+}++// ProjectTool projects one request/response manifest capability into the common+// external-agent tool shape.+func ProjectTool(cap Capability) (ProjectedTool, bool) {+ if !IsRequestResponseCapability(cap) {+ return ProjectedTool{}, false+ }+ return ProjectedTool{+ Name: cap.Name,+ Title: CapabilityTitle(cap),+ Description: ToolDescription(cap),+ InputSchema: ToolInputSchema(cap),+ OutputSchema: ToolOutputSchema(cap),+ Annotations: ToolAnnotations(cap),+ Meta: ToolMeta(cap),+ }, true+}++// CapabilityTitle returns the manifest-owned human-readable title for a+// capability, falling back to a stable sentence-cased projection of the+// programmatic name for older manifests.+func CapabilityTitle(cap Capability) string {+ if title := strings.TrimSpace(cap.Title); title != "" {+ return title+ }+ name := strings.TrimSpace(cap.Name)+ if name == "" {+ return ""+ }+ title := strings.Join(strings.Fields(strings.ReplaceAll(name, "_", " ")), " ")+ return strings.ToUpper(title[:1]) + title[1:]+}++// ProjectTools projects request/response manifest capabilities into the common+// external-agent tool list shape. Streaming capabilities such as+// subscribe_events are intentionally filtered out.+func ProjectTools(capabilities []Capability) []ProjectedTool {+ tools := make([]ProjectedTool, 0, len(capabilities))+ for _, cap := range capabilities {+ tool, ok := ProjectTool(cap)+ if !ok {+ continue+ }+ tools = append(tools, tool)+ }+ return tools+}++// FindManifestSurfaceToolContract resolves a manifest-published surface tool+// contract by stable operator-surface id.+func FindManifestSurfaceToolContract(manifest Manifest, surfaceID string) (SurfaceToolContract, bool) {+ surfaceID = strings.TrimSpace(surfaceID)+ if surfaceID == "" {+ return SurfaceToolContract{}, false+ }+ for _, contract := range manifest.SurfaceToolContracts {+ if strings.EqualFold(strings.TrimSpace(contract.SurfaceID), surfaceID) {+ return contract.NormalizeCollections(), true+ }+ }+ return SurfaceToolContract{}, false+}++// ManifestSurfaceToolCapabilities returns the request/response capabilities+// that a manifest-published external-agent surface is allowed to expose as+// tools. The normalized surface tool contract is authoritative; missing+// surface tool contracts expose no tools rather than inferring from raw+// manifest capabilities.+func ManifestSurfaceToolCapabilities(manifest Manifest, surfaceID string) []Capability {+ contract, declared := ResolveManifestSurfaceToolContract(manifest, surfaceID)+ if !declared {+ return []Capability{}+ }+ affordances, _ := ManifestSurfaceAffordances(manifest, contract.SurfaceID)+ if !affordances.Tools {+ return []Capability{}+ }++ capabilities := make([]Capability, 0, len(contract.ToolNames))+ seen := map[string]struct{}{}+ for _, rawName := range contract.ToolNames {+ name := strings.TrimSpace(rawName)+ if name == "" {+ continue+ }+ if _, exists := seen[name]; exists {+ continue+ }+ seen[name] = struct{}{}+ capability, err := ResolveRequestResponseCapability(manifest.Capabilities, name)+ if err != nil {+ continue+ }+ capabilities = append(capabilities, capability)+ }+ return capabilities+}++// ProjectManifestSurfaceTools projects the manifest-owned tool allowlist for an+// external-agent surface into the shared tools/list shape.+func ProjectManifestSurfaceTools(manifest Manifest, surfaceID string) []ProjectedTool {+ return ProjectTools(ManifestSurfaceToolCapabilities(manifest, surfaceID))+}++// ToolDescription projects manifest-owned capability metadata into the+// description shown by external-agent tool surfaces.+func ToolDescription(cap Capability) string {+ governance := NormalizeCapabilityGovernance(cap)+ var b strings.Builder+ if desc := strings.TrimSpace(cap.Description); desc != "" {+ b.WriteString(desc)+ b.WriteString("\n\n")+ }+ b.WriteString("Pulse capability metadata:")+ if category := strings.TrimSpace(cap.Category); category != "" {+ b.WriteString("\n- category: ")+ b.WriteString(category)+ }+ route := strings.TrimSpace(strings.Join([]string{cap.Method, cap.Path}, " "))+ if route != "" {+ b.WriteString("\n- route: ")+ b.WriteString(route)+ }+ if scope := strings.TrimSpace(cap.Scope); scope != "" {+ b.WriteString("\n- required scope: ")+ b.WriteString(scope)+ }+ b.WriteString("\n- action mode: ")+ b.WriteString(string(governance.ActionMode))+ b.WriteString("\n- approval policy: ")+ b.WriteString(string(governance.ApprovalPolicy))+ if requestShape := strings.TrimSpace(cap.RequestBodyShape); requestShape != "" {+ b.WriteString("\n- request body: ")+ b.WriteString(requestShape)+ }+ if responseShape := strings.TrimSpace(cap.ResponseShape); responseShape != "" {+ b.WriteString("\n- response: ")+ b.WriteString(responseShape)+ }+ if len(cap.ErrorCodes) > 0 {+ b.WriteString("\n- stable error codes: ")+ b.WriteString(strings.Join(cap.ErrorCodes, ", "))+ }+ return b.String()+}++// ToolAnnotations projects manifest governance into external-agent tool+// behavior hints so clients can distinguish read-only, non-destructive+// scan/check, and write-capable operations without carrying a Pulse-specific+// policy table.+func ToolAnnotations(cap Capability) *ToolBehaviorHints {+ return toolBehaviorHintsForActionMode(NormalizeCapabilityGovernance(cap).ActionMode)+}++// ToolGovernanceBehaviorHints projects registry-owned governance into the same+// neutral behavior-hint vocabulary used by manifest-backed external tools.+func ToolGovernanceBehaviorHints(governance ToolGovernanceDescriptor) *ToolBehaviorHints {+ return toolBehaviorHintsForActionMode(NormalizeToolGovernanceDescriptor(governance).ActionMode)+}++func toolBehaviorHintsForActionMode(mode ActionMode) *ToolBehaviorHints {+ switch mode {+ case ActionModeRead, ActionModeMixed, ActionModeWrite:+ default:+ mode = ActionModeRead+ }+ readOnly := mode == ActionModeRead+ destructive := mode == ActionModeWrite+ idempotent := readOnly+ openWorld := true+ return &ToolBehaviorHints{+ ReadOnlyHint: boolRef(readOnly),+ DestructiveHint: boolRef(destructive),+ IdempotentHint: boolRef(idempotent),+ OpenWorldHint: boolRef(openWorld),+ }+}++// CloneToolBehaviorHints returns a detached behavior-hint struct for shared+// Assistant and external-agent tool projections.+func CloneToolBehaviorHints(hints *ToolBehaviorHints) *ToolBehaviorHints {+ if hints == nil {+ return nil+ }+ cloned := &ToolBehaviorHints{Title: hints.Title}+ cloned.ReadOnlyHint = cloneBoolRef(hints.ReadOnlyHint)+ cloned.DestructiveHint = cloneBoolRef(hints.DestructiveHint)+ cloned.IdempotentHint = cloneBoolRef(hints.IdempotentHint)+ cloned.OpenWorldHint = cloneBoolRef(hints.OpenWorldHint)+ return cloned+}++// ToolMeta projects Pulse-specific manifest metadata into the standard _meta+// extension object used by external-agent tools. The human description still+// carries this posture for model selection, while _meta gives clients a+// structured route/scope/governance contract without parsing prose.+func ToolMeta(cap Capability) map[string]any {+ governance := NormalizeCapabilityGovernance(cap)+ capability := map[string]any{}+ setMetaString(capability, "name", cap.Name)+ setMetaString(capability, "category", cap.Category)+ setMetaString(capability, "scope", cap.Scope)+ if requestShape := strings.TrimSpace(cap.RequestBodyShape); requestShape != "" {+ capability["requestBodyShape"] = requestShape+ }+ if responseShape := strings.TrimSpace(cap.ResponseShape); responseShape != "" {+ capability["responseShape"] = responseShape+ }+ if len(cap.ErrorCodes) > 0 {+ capability["errorCodes"] = append([]string(nil), cap.ErrorCodes...)+ }++ route := map[string]any{}+ setMetaString(route, "method", cap.Method)+ setMetaString(route, "path", cap.Path)+ if len(route) > 0 {+ capability["route"] = route+ }++ governanceMeta := map[string]any{}+ setMetaString(governanceMeta, "actionMode", string(governance.ActionMode))+ setMetaString(governanceMeta, "approvalPolicy", string(governance.ApprovalPolicy))+ setMetaString(governanceMeta, "approvalSummary", governance.ApprovalSummary)+ if len(governanceMeta) > 0 {+ capability["governance"] = governanceMeta+ }++ if len(capability) == 0 {+ return nil+ }+ return CloneToolArguments(map[string]any{+ ToolMetaPulseCapabilityKey: capability,+ })+}++func setMetaString(meta map[string]any, key, value string) {+ if trimmed := strings.TrimSpace(value); trimmed != "" {+ meta[key] = trimmed+ }+}++func boolRef(v bool) *bool {+ return &v+}++func cloneBoolRef(v *bool) *bool {+ if v == nil {+ return nil+ }+ cloned := *v+ return &cloned+}++// ToolInputSchema returns the agent-facing input schema for a capability. A+// manifest-owned schema is forwarded verbatim; otherwise a permissive adapter+// fallback is derived from path placeholders and request-body posture.+func ToolInputSchema(cap Capability) json.RawMessage {+ if len(cap.InputSchema) > 0 {+ return CloneRawMessage(cap.InputSchema)+ }++ properties := map[string]any{}+ required := []string{}+ for _, name := range PathParameterNames(cap.Path) {+ properties[name] = map[string]any{+ "type": "string",+ "description": "Canonical " + name + " (e.g. \"vm:101\", \"container:web-1\")",+ }+ required = append(required, name)+ }+ if CapabilityHasRequestBody(cap) {+ desc := "Request body fields"+ if cap.RequestBodyShape != "" {+ desc = "Request body fields. Shape hint: " + cap.RequestBodyShape+ }+ properties["body"] = map[string]any{+ "type": "object",+ "description": desc,+ "additionalProperties": true,+ }+ }+ return ObjectInputSchema(required, properties, true)+}++// ToolOutputSchema returns the manifest-owned structured output schema for a+// request/response capability. Unlike input schemas, there is no fallback: a+// responseShape string is a human-readable hint, not a validation contract for+// MCP structuredContent.+func ToolOutputSchema(cap Capability) json.RawMessage {+ return CloneRawMessage(cap.OutputSchema)+}++// ProjectedCall is the manifest-owned route/body projection for one capability+// invocation. Adapters still own their transport, auth headers, and response+// wrapping.+type ProjectedCall struct {+ Path string+ Body json.RawMessage+ HasBody bool+}++// ProjectCapabilityCall turns agent-facing tool arguments into the Pulse HTTP+// path and optional JSON body declared by the capability manifest.+func ProjectCapabilityCall(cap Capability, args map[string]any) (ProjectedCall, error) {+ path, err := SubstitutePathParameters(cap.Path, args)+ if err != nil {+ return ProjectedCall{}, err+ }++ projected := ProjectedCall{Path: path}+ if !CapabilityHasRequestBody(cap) {+ return projected, nil+ }++ bodyArg, ok := args["body"]+ if !ok {+ pathParams := PathParameterSet(cap.Path)+ cleaned := map[string]any{}+ for k, v := range PublicToolArguments(args) {+ if !pathParams[k] {+ cleaned[k] = v+ }+ }+ bodyArg = cleaned+ }++ body, err := json.Marshal(bodyArg)+ if err != nil {+ return ProjectedCall{}, err+ }+ projected.Body = body+ projected.HasBody = true+ return projected, nil+}++// CapabilityHasRequestBody reports whether adapters should send a JSON request+// body for a capability call.+func CapabilityHasRequestBody(cap Capability) bool {+ return !strings.EqualFold(cap.Method, http.MethodGet) && !strings.EqualFold(cap.Method, http.MethodDelete)+}++// PathParameterNames returns placeholder names declared by a capability path.+func PathParameterNames(path string) []string {+ matches := pathPlaceholderRE.FindAllStringSubmatch(path, -1)+ names := make([]string, 0, len(matches))+ for _, match := range matches {+ names = append(names, match[1])+ }+ return names+}++// PathParameterSet returns the set of placeholder names declared in a capability+// path. Used by adapters to keep path arguments out of JSON request bodies.+func PathParameterSet(path string) map[string]bool {+ set := map[string]bool{}+ for _, name := range PathParameterNames(path) {+ set[name] = true+ }+ return set+}++// SubstitutePathParameters replaces `{name}` segments in a capability path with+// the corresponding argument value, encoded as one path segment.+func SubstitutePathParameters(path string, args map[string]any) (string, error) {+ var missing []string+ out := pathPlaceholderRE.ReplaceAllStringFunc(path, func(match string) string {+ name := match[1 : len(match)-1] // strip { and }+ v, ok := args[name]+ if !ok {+ missing = append(missing, name)+ return match+ }+ s, ok := v.(string)+ if !ok {+ missing = append(missing, name+" (not a string)")+ return match+ }+ return EscapePathSegmentParameter(s)+ })+ if len(missing) > 0 {+ return "", fmt.Errorf("missing path argument(s): %s", strings.Join(missing, ", "))+ }+ return out, nil+}++// EscapePathSegmentParameter percent-encodes a path parameter as a single URL+// path segment. It intentionally escapes `/`, `:`, spaces, and other reserved+// bytes.+func EscapePathSegmentParameter(value string) string {+ var b strings.Builder+ for _, c := range []byte(value) {+ if isUnreservedPathByte(c) {+ b.WriteByte(c)+ continue+ }+ _, _ = fmt.Fprintf(&b, "%%%02X", c)+ }+ return b.String()+}++func isUnreservedPathByte(c byte) bool {+ return (c >= 'A' && c <= 'Z') ||+ (c >= 'a' && c <= 'z') ||+ (c >= '0' && c <= '9') ||+ c == '-' ||+ c == '.' ||+ c == '_' ||+ c == '~'+}diff --git a/internal/agentcapabilities/projection_test.go b/internal/agentcapabilities/projection_test.gonew file mode 100644index 0000000000..2f618b66f4--- /dev/null+++ b/internal/agentcapabilities/projection_test.go@@ -0,0 +1,811 @@+package agentcapabilities++import (+ "encoding/json"+ "net/http"+ "strings"+ "testing"+)++func TestIsRequestResponseCapabilitySkipsEventSubscription(t *testing.T) {+ if IsRequestResponseCapability(Capability{Name: EventSubscriptionCapabilityName}) {+ t.Fatal("subscribe_events must stay out of request/response tool projections")+ }+ if !IsRequestResponseCapability(Capability{Name: "get_resource_context"}) {+ t.Fatal("ordinary manifest capabilities must project as request/response tools")+ }+}++func TestFindCapabilityReturnsNamedCapability(t *testing.T) {+ capabilities := []Capability{+ {Name: "get_fleet_context", Path: "/api/agent/fleet-context"},+ {Name: "get_resource_context", Path: "/api/agent/resource-context/{resourceId}"},+ }++ got, ok := FindCapability(capabilities, "get_resource_context")+ if !ok {+ t.Fatal("FindCapability did not find get_resource_context")+ }+ if got.Path != "/api/agent/resource-context/{resourceId}" {+ t.Fatalf("FindCapability path = %q, want resource context path", got.Path)+ }++ if _, ok := FindCapability(capabilities, "missing"); ok {+ t.Fatal("FindCapability unexpectedly found missing capability")+ }+}++func TestFindCapabilityReturnsDetachedCapability(t *testing.T) {+ rawSchema := json.RawMessage(`{"type":"object","properties":{"mode":{"type":"string"}}}`)+ rawOutputSchema := json.RawMessage(`{"type":"object","properties":{"ok":{"type":"boolean"}}}`)+ wantSchema := string(rawSchema)+ wantOutputSchema := string(rawOutputSchema)+ capabilities := []Capability{+ {+ Name: "get_resource_context",+ InputSchema: rawSchema,+ OutputSchema: rawOutputSchema,+ ErrorCodes: []string{"resource_not_found"},+ },+ }++ got, ok := FindCapability(capabilities, "get_resource_context")+ if !ok {+ t.Fatal("FindCapability did not find get_resource_context")+ }++ got.InputSchema[0] = '['+ got.OutputSchema[0] = '['+ got.ErrorCodes[0] = "mutated"++ if string(capabilities[0].InputSchema) != wantSchema {+ t.Fatalf("FindCapability returned aliased input schema: source=%s got=%s", capabilities[0].InputSchema, got.InputSchema)+ }+ if string(capabilities[0].OutputSchema) != wantOutputSchema {+ t.Fatalf("FindCapability returned aliased output schema: source=%s got=%s", capabilities[0].OutputSchema, got.OutputSchema)+ }+ if capabilities[0].ErrorCodes[0] != "resource_not_found" {+ t.Fatalf("FindCapability returned aliased error codes: source=%v got=%v", capabilities[0].ErrorCodes, got.ErrorCodes)+ }+}++func TestResolveRequestResponseCapabilityRejectsStreamingCapabilities(t *testing.T) {+ capabilities := []Capability{+ {Name: EventSubscriptionCapabilityName, Path: "/api/agent/events", Method: http.MethodGet},+ {Name: ResourceContextCapabilityName, Path: "/api/agent/resource-context/{resourceId}", Method: http.MethodGet},+ }+ if _, err := ResolveRequestResponseCapability(capabilities, ResourceContextCapabilityName); err != nil {+ t.Fatalf("ResolveRequestResponseCapability rejected resource context: %v", err)+ }+ if _, err := ResolveRequestResponseCapability(capabilities, EventSubscriptionCapabilityName); err == nil {+ t.Fatal("ResolveRequestResponseCapability must reject streaming subscription capability")+ } else if lookupErr, ok := err.(CapabilityLookupError); !ok || lookupErr.Name != EventSubscriptionCapabilityName {+ t.Fatalf("streaming capability error = %T %[1]v, want CapabilityLookupError for %s", err, EventSubscriptionCapabilityName)+ }+}++func TestProjectToolsProjectsRequestResponseCapabilities(t *testing.T) {+ tools := ProjectTools([]Capability{+ {+ Name: "get_resource_context",+ Title: "Inspect resource",+ Description: "Read focused resource context.",+ Category: "context",+ Method: http.MethodGet,+ Path: "/api/agent/resource-context/{resourceId}",+ Scope: "monitoring:read",+ ActionMode: ActionModeRead,+ OutputSchema: json.RawMessage(`{+ "type": "object",+ "properties": {+ "canonicalId": { "type": "string" }+ },+ "required": ["canonicalId"],+ "additionalProperties": true+ }`),+ },+ {+ Name: EventSubscriptionCapabilityName,+ Description: "Stream Pulse Intelligence events.",+ Method: http.MethodGet,+ Path: "/api/agent/events",+ },+ {+ Name: SetOperatorStateCapabilityName,+ Title: "Set operator state",+ Description: "Set operator state.",+ Method: http.MethodPut,+ Path: OperatorStateCapabilityPath,+ Scope: "monitoring:write",+ ActionMode: ActionModeWrite,+ ApprovalPolicy: ApprovalPolicyScopeOnly,+ },+ })++ if len(tools) != 2 {+ t.Fatalf("ProjectTools length = %d, want 2 request/response tools", len(tools))+ }+ if tools[0].Name != "get_resource_context" {+ t.Fatalf("first projected tool = %q, want get_resource_context", tools[0].Name)+ }+ if tools[0].Title != "Inspect resource" {+ t.Fatalf("first projected tool title = %q, want manifest title", tools[0].Title)+ }+ if len(tools[0].OutputSchema) == 0 {+ t.Fatal("first projected tool must carry manifest-owned outputSchema")+ }+ if tools[1].Name != SetOperatorStateCapabilityName {+ t.Fatalf("second projected tool = %q, want %s", tools[1].Name, SetOperatorStateCapabilityName)+ }+ if strings.Contains(tools[1].Description, EventSubscriptionCapabilityName) {+ t.Fatalf("request/response projection leaked streaming capability description: %q", tools[1].Description)+ }+ if !strings.Contains(tools[1].Description, "required scope: monitoring:write") {+ t.Fatalf("projected tool description missing manifest metadata: %q", tools[1].Description)+ }+ meta, ok := tools[1].Meta[ToolMetaPulseCapabilityKey].(map[string]any)+ if !ok {+ t.Fatalf("projected tool missing structured Pulse capability metadata: %#v", tools[1].Meta)+ }+ if meta["scope"] != "monitoring:write" {+ t.Fatalf("projected metadata scope = %#v, want monitoring:write", meta["scope"])+ }+ route, _ := meta["route"].(map[string]any)+ if route["method"] != http.MethodPut || route["path"] != OperatorStateCapabilityPath {+ t.Fatalf("projected metadata route = %#v, want PUT operator-state route", route)+ }+ governance, _ := meta["governance"].(map[string]any)+ if governance["actionMode"] != string(ActionModeWrite) || governance["approvalPolicy"] != string(ApprovalPolicyScopeOnly) {+ t.Fatalf("projected metadata governance = %#v, want write/scope_only", governance)+ }+ assertToolAnnotations(t, tools[0].Annotations, true, false, true, true)+ assertToolAnnotations(t, tools[1].Annotations, false, true, false, true)++ var schema map[string]any+ if err := json.Unmarshal(tools[1].InputSchema, &schema); err != nil {+ t.Fatalf("projected tool input schema must be JSON: %v", err)+ }+ props, _ := schema["properties"].(map[string]any)+ if _, hasResourceID := props[ResourceIDArgumentName]; !hasResourceID {+ t.Fatalf("projected tool input schema missing path argument: %s", string(tools[1].InputSchema))+ }+}++func TestProjectManifestSurfaceToolsUsesPublishedSurfaceContract(t *testing.T) {+ manifest := Manifest{+ SurfaceContract: CanonicalManifest().SurfaceContract,+ SurfaceToolContracts: []SurfaceToolContract{+ {+ SurfaceID: SurfaceIDPulseMCP,+ ToolSource: SurfaceToolSourceCapabilityManifest,+ ToolNames: []string{SetOperatorStateCapabilityName, ResourceContextCapabilityName, EventSubscriptionCapabilityName, "missing_tool", SetOperatorStateCapabilityName},+ Affordances: DefaultSurfaceAffordancesForID(SurfaceIDPulseMCP),+ },+ },+ Capabilities: []Capability{+ {Name: ResourceContextCapabilityName, Path: ResourceContextCapabilityPath, Method: http.MethodGet, Description: "depth"},+ {Name: SetOperatorStateCapabilityName, Path: OperatorStateCapabilityPath, Method: http.MethodPut, Description: "intent"},+ {Name: EventSubscriptionCapabilityName, Path: "/api/agent/events", Method: http.MethodGet, Description: "stream"},+ {Name: FleetContextCapabilityName, Path: FleetContextCapabilityPath, Method: http.MethodGet, Description: "fleet"},+ },+ }++ contract, ok := FindManifestSurfaceToolContract(manifest, SurfaceIDPulseMCP)+ if !ok {+ t.Fatal("published Pulse MCP surface contract was not found")+ }+ if len(contract.ToolNames) != 5 || contract.ToolNames[0] != SetOperatorStateCapabilityName {+ t.Fatalf("published surface contract names = %#v", contract.ToolNames)+ }++ capabilities := ManifestSurfaceToolCapabilities(manifest, SurfaceIDPulseMCP)+ if len(capabilities) != 2 {+ t.Fatalf("surface capabilities = %#v, want two request/response capabilities from published contract", capabilities)+ }+ if capabilities[0].Name != SetOperatorStateCapabilityName || capabilities[1].Name != ResourceContextCapabilityName {+ t.Fatalf("surface capability order = %#v, want published contract order", []string{capabilities[0].Name, capabilities[1].Name})+ }++ capabilities[0].Name = "mutated"+ second := ManifestSurfaceToolCapabilities(manifest, SurfaceIDPulseMCP)+ if second[0].Name != SetOperatorStateCapabilityName {+ t.Fatalf("surface capability projection returned aliased capabilities: %#v", second)+ }++ tools := ProjectManifestSurfaceTools(manifest, SurfaceIDPulseMCP)+ if len(tools) != 2 {+ t.Fatalf("surface tools = %#v, want two projected tools from published contract", tools)+ }+ if tools[0].Name != SetOperatorStateCapabilityName || tools[1].Name != ResourceContextCapabilityName {+ t.Fatalf("surface tool order = %#v, want published contract order", []string{tools[0].Name, tools[1].Name})+ }+}++func TestProjectManifestSurfaceToolsUsesNormalizedContractAndToolAffordance(t *testing.T) {+ manifest := Manifest{+ SurfaceContract: CanonicalManifest().SurfaceContract,+ SurfaceToolContracts: []SurfaceToolContract{+ {+ SurfaceID: SurfaceIDPulseMCP,+ ToolSource: SurfaceToolSourceCapabilityManifest,+ CapabilityNames: []string{ResourceContextCapabilityName},+ },+ },+ Capabilities: []Capability{+ {Name: ResourceContextCapabilityName, Path: ResourceContextCapabilityPath, Method: http.MethodGet, Description: "depth"},+ },+ }++ capabilities := ManifestSurfaceToolCapabilities(manifest, SurfaceIDPulseMCP)+ if len(capabilities) != 1 || capabilities[0].Name != ResourceContextCapabilityName {+ t.Fatalf("surface capabilities = %#v, want normalized capabilityNames fallback", capabilities)+ }++ tools := ProjectManifestSurfaceTools(manifest, SurfaceIDPulseMCP)+ if len(tools) != 1 || tools[0].Name != ResourceContextCapabilityName {+ t.Fatalf("surface tools = %#v, want normalized capabilityNames fallback", tools)+ }++ disabledManifest := manifest+ disabledManifest.SurfaceContract = CloneSurfaceContract(manifest.SurfaceContract)+ for i := range disabledManifest.SurfaceContract.OperatorSurfaces {+ if disabledManifest.SurfaceContract.OperatorSurfaces[i].ID == SurfaceIDPulseMCP {+ disabledManifest.SurfaceContract.OperatorSurfaces[i].Affordances = SurfaceAffordanceContract{+ Resources: true,+ Prompts: true,+ CapabilityMetadata: true,+ }+ }+ }+ disabledManifest.SurfaceToolContracts = CloneSurfaceToolContracts(manifest.SurfaceToolContracts)+ disabledManifest.SurfaceToolContracts[0].Affordances = DefaultSurfaceAffordancesForID(SurfaceIDPulseMCP)++ if got := ManifestSurfaceToolCapabilities(disabledManifest, SurfaceIDPulseMCP); len(got) != 0 {+ t.Fatalf("surface with tools affordance disabled returned capabilities: %#v", got)+ }+ if got := ProjectManifestSurfaceTools(disabledManifest, SurfaceIDPulseMCP); len(got) != 0 {+ t.Fatalf("surface with tools affordance disabled returned tools: %#v", got)+ }+}++func TestProjectManifestSurfaceToolsRequiresPublishedPulseMCPContract(t *testing.T) {+ manifest := Manifest{+ SurfaceContract: CanonicalManifest().SurfaceContract,+ Capabilities: []Capability{+ {Name: ResourceContextCapabilityName, Path: ResourceContextCapabilityPath, Method: http.MethodGet, Description: "depth"},+ {Name: EventSubscriptionCapabilityName, Path: "/api/agent/events", Method: http.MethodGet, Description: "stream"},+ },+ }++ if tools := ProjectManifestSurfaceTools(manifest, SurfaceIDPulseMCP); len(tools) != 0 {+ t.Fatalf("missing Pulse MCP surface tool contract exposed tools: %#v", tools)+ }+ if capabilities := ManifestSurfaceToolCapabilities(manifest, SurfaceIDPulseMCP); len(capabilities) != 0 {+ t.Fatalf("missing Pulse MCP surface tool contract exposed capabilities: %#v", capabilities)+ }++ if got := ProjectManifestSurfaceTools(Manifest{}, "custom_external_agent"); len(got) != 0 {+ t.Fatalf("missing custom external surface fallback = %#v, want no tools", got)+ }+}++func TestProjectToolsReturnsDetachedInputAndOutputSchemas(t *testing.T) {+ rawSchema := json.RawMessage(`{"type":"object","additionalProperties":false}`)+ rawOutputSchema := json.RawMessage(`{"type":"object","properties":{"accepted":{"type":"boolean"}}}`)+ wantSchema := string(rawSchema)+ wantOutputSchema := string(rawOutputSchema)+ capabilities := []Capability{+ {+ Name: DecideActionCapabilityName,+ Description: "Decide an action.",+ Method: http.MethodPost,+ Path: ActionDecisionCapabilityPath,+ InputSchema: rawSchema,+ OutputSchema: rawOutputSchema,+ },+ }++ tools := ProjectTools(capabilities)+ if len(tools) != 1 {+ t.Fatalf("ProjectTools length = %d, want 1", len(tools))+ }++ tools[0].InputSchema[0] = '['+ tools[0].OutputSchema[0] = '['+ if string(capabilities[0].InputSchema) != wantSchema {+ t.Fatalf("ProjectTools returned aliased input schema: source=%s projected=%s", capabilities[0].InputSchema, tools[0].InputSchema)+ }+ if string(capabilities[0].OutputSchema) != wantOutputSchema {+ t.Fatalf("ProjectTools returned aliased output schema: source=%s projected=%s", capabilities[0].OutputSchema, tools[0].OutputSchema)+ }++ second := ProjectTools(capabilities)+ if string(second[0].InputSchema) != wantSchema {+ t.Fatalf("ProjectTools mutation leaked into later projection: %s", second[0].InputSchema)+ }+ if string(second[0].OutputSchema) != wantOutputSchema {+ t.Fatalf("ProjectTools output schema mutation leaked into later projection: %s", second[0].OutputSchema)+ }+}++func TestProjectToolsReturnsDetachedStructuredMetadata(t *testing.T) {+ capabilities := []Capability{+ {+ Name: PlanActionCapabilityName,+ Description: "Plan an action.",+ Category: "action",+ Method: http.MethodPost,+ Path: PlanActionCapabilityPath,+ Scope: "ai:execute",+ ActionMode: ActionModeWrite,+ ApprovalPolicy: ApprovalPolicyActionPlan,+ ResponseShape: "ActionPlan",+ ErrorCodes: []string{"invalid_action_request"},+ },+ }++ tools := ProjectTools(capabilities)+ if len(tools) != 1 {+ t.Fatalf("ProjectTools length = %d, want 1", len(tools))+ }+ meta, ok := tools[0].Meta[ToolMetaPulseCapabilityKey].(map[string]any)+ if !ok {+ t.Fatalf("projected metadata missing pulse capability object: %#v", tools[0].Meta)+ }+ errors, _ := meta["errorCodes"].([]string)+ if len(errors) != 1 || errors[0] != "invalid_action_request" {+ t.Fatalf("metadata errorCodes = %#v, want invalid_action_request", meta["errorCodes"])+ }++ errors[0] = "mutated"+ route, _ := meta["route"].(map[string]any)+ route["path"] = "/mutated"++ if capabilities[0].ErrorCodes[0] != "invalid_action_request" {+ t.Fatalf("projected metadata aliases manifest error codes: %v", capabilities[0].ErrorCodes)+ }+ second := ProjectTools(capabilities)+ secondMeta, _ := second[0].Meta[ToolMetaPulseCapabilityKey].(map[string]any)+ secondErrors, _ := secondMeta["errorCodes"].([]string)+ secondRoute, _ := secondMeta["route"].(map[string]any)+ if secondErrors[0] != "invalid_action_request" {+ t.Fatalf("metadata mutation leaked into later projection: %#v", secondErrors)+ }+ if secondRoute["path"] != "/api/actions/plan" {+ t.Fatalf("metadata route mutation leaked into later projection: %#v", secondRoute)+ }+}++func TestToolAnnotationsProjectsCapabilityActionModes(t *testing.T) {+ tests := []struct {+ name string+ cap Capability+ readOnly bool+ destructive bool+ idempotent bool+ openWorld bool+ }{+ {+ name: "read capability",+ cap: Capability{+ Method: http.MethodGet,+ ActionMode: ActionModeRead,+ },+ readOnly: true,+ destructive: false,+ idempotent: true,+ openWorld: true,+ },+ {+ name: "mixed scan capability",+ cap: Capability{+ Method: http.MethodPost,+ ActionMode: ActionModeMixed,+ },+ readOnly: false,+ destructive: false,+ idempotent: false,+ openWorld: true,+ },+ {+ name: "write capability",+ cap: Capability{+ Method: http.MethodPost,+ ActionMode: ActionModeWrite,+ },+ readOnly: false,+ destructive: true,+ idempotent: false,+ openWorld: true,+ },+ {+ name: "missing mode defaults GET to read",+ cap: Capability{+ Method: http.MethodGet,+ },+ readOnly: true,+ destructive: false,+ idempotent: true,+ openWorld: true,+ },+ {+ name: "missing mode defaults non-GET to write",+ cap: Capability{+ Method: http.MethodPut,+ },+ readOnly: false,+ destructive: true,+ idempotent: false,+ openWorld: true,+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ assertToolAnnotations(t, ToolAnnotations(tc.cap), tc.readOnly, tc.destructive, tc.idempotent, tc.openWorld)+ })+ }+}++func TestCapabilityTitleFallsBackToProgrammaticName(t *testing.T) {+ if got := CapabilityTitle(Capability{Name: "refresh_node_cluster_membership"}); got != "Refresh node cluster membership" {+ t.Fatalf("fallback capability title = %q", got)+ }+}++func TestProjectToolSerializesFalseAnnotationHints(t *testing.T) {+ tool, ok := ProjectTool(Capability{+ Name: SetOperatorStateCapabilityName,+ Method: http.MethodPut,+ Path: OperatorStateCapabilityPath,+ ActionMode: ActionModeWrite,+ })+ if !ok {+ t.Fatal("write capability did not project")+ }+ body, err := json.Marshal(tool)+ if err != nil {+ t.Fatalf("marshal projected tool: %v", err)+ }+ text := string(body)+ for _, want := range []string{+ `"title":"Set operator state"`,+ `"annotations":{`,+ `"readOnlyHint":false`,+ `"destructiveHint":true`,+ `"idempotentHint":false`,+ `"openWorldHint":true`,+ `"_meta":{`,+ `"pulse.capability":{`,+ `"actionMode":"write"`,+ } {+ if !strings.Contains(text, want) {+ t.Fatalf("projected tool JSON missing %s: %s", want, text)+ }+ }+}++func TestToolDescriptionProjectsCapabilityMetadata(t *testing.T) {+ desc := ToolDescription(Capability{+ Name: PlanActionCapabilityName,+ Description: "Plan an action against a resource.",+ Category: "action",+ Method: http.MethodPost,+ Path: PlanActionCapabilityPath,+ Scope: "ai:execute",+ ActionMode: ActionModeWrite,+ ApprovalPolicy: ApprovalPolicyActionPlan,+ RequestBodyShape: "ActionRequest",+ ResponseShape: "ActionPlan",+ ErrorCodes: []string{"invalid_action_request", "resource_not_found"},+ })++ for _, want := range []string{+ "Plan an action against a resource.",+ "Pulse capability metadata:",+ "category: action",+ "route: POST /api/actions/plan",+ "required scope: ai:execute",+ "action mode: write",+ "approval policy: action_plan",+ "request body: ActionRequest",+ "response: ActionPlan",+ "stable error codes: invalid_action_request, resource_not_found",+ } {+ if !strings.Contains(desc, want) {+ t.Fatalf("ToolDescription missing %q in %q", want, desc)+ }+ }+}++func TestToolMetaProjectsStructuredPulseCapabilityMetadata(t *testing.T) {+ meta := ToolMeta(Capability{+ Name: PlanActionCapabilityName,+ Description: "Plan an action against a resource.",+ Category: "action",+ Method: http.MethodPost,+ Path: PlanActionCapabilityPath,+ Scope: "ai:execute",+ ActionMode: ActionModeWrite,+ ApprovalPolicy: ApprovalPolicyActionPlan,+ RequestBodyShape: "ActionRequest",+ ResponseShape: "ActionPlan",+ ErrorCodes: []string{"invalid_action_request", "resource_not_found"},+ })++ capability, ok := meta[ToolMetaPulseCapabilityKey].(map[string]any)+ if !ok {+ t.Fatalf("ToolMeta missing %s object: %#v", ToolMetaPulseCapabilityKey, meta)+ }+ for key, want := range map[string]any{+ "name": PlanActionCapabilityName,+ "category": "action",+ "scope": "ai:execute",+ "requestBodyShape": "ActionRequest",+ "responseShape": "ActionPlan",+ } {+ if got := capability[key]; got != want {+ t.Fatalf("ToolMeta[%s] = %#v, want %#v", key, got, want)+ }+ }+ route, _ := capability["route"].(map[string]any)+ if route["method"] != http.MethodPost || route["path"] != "/api/actions/plan" {+ t.Fatalf("ToolMeta route = %#v, want POST /api/actions/plan", route)+ }+ governance, _ := capability["governance"].(map[string]any)+ if governance["actionMode"] != "write" || governance["approvalPolicy"] != "action_plan" {+ t.Fatalf("ToolMeta governance = %#v, want write/action_plan", governance)+ }+ errors, _ := capability["errorCodes"].([]string)+ if len(errors) != 2 || errors[0] != "invalid_action_request" || errors[1] != "resource_not_found" {+ t.Fatalf("ToolMeta errorCodes = %#v, want stable manifest errors", errors)+ }+}++func TestToolDescriptionProjectsNormalizedCapabilityGovernance(t *testing.T) {+ desc := ToolDescription(Capability{+ Name: "legacy_write",+ Description: "Legacy write capability.",+ Method: http.MethodPost,+ Path: "/api/legacy/write",+ })++ for _, want := range []string{+ "Legacy write capability.",+ "action mode: write",+ "approval policy: scope_only",+ } {+ if !strings.Contains(desc, want) {+ t.Fatalf("ToolDescription missing normalized governance %q in %q", want, desc)+ }+ }+}++func TestToolInputSchemaDerivesPermissiveFallback(t *testing.T) {+ raw := ToolInputSchema(Capability{+ Path: OperatorStateCapabilityPath,+ Method: http.MethodPut,+ RequestBodyShape: "ResourceOperatorStateInput",+ })++ var schema map[string]any+ if err := json.Unmarshal(raw, &schema); err != nil {+ t.Fatalf("unmarshal schema: %v", err)+ }+ if schema["additionalProperties"] != true {+ t.Fatalf("fallback schema additionalProperties = %v, want true", schema["additionalProperties"])+ }+ props, _ := schema["properties"].(map[string]any)+ if _, hasResourceID := props[ResourceIDArgumentName]; !hasResourceID {+ t.Fatalf("fallback schema must include path argument resourceId: %v", props)+ }+ body, _ := props["body"].(map[string]any)+ if !strings.Contains(body["description"].(string), "ResourceOperatorStateInput") {+ t.Fatalf("fallback body description must carry request-body shape hint: %v", body)+ }+ required, _ := schema["required"].([]any)+ if len(required) != 1 || required[0] != ResourceIDArgumentName {+ t.Fatalf("fallback schema required = %v, want [resourceId]", required)+ }+}++func TestToolInputSchemaPreservesManifestSchema(t *testing.T) {+ rawSchema := json.RawMessage(`{+ "type": "object",+ "properties": {+ "actionId": { "type": "string" },+ "outcome": { "enum": ["approved", "rejected"] }+ },+ "required": ["actionId", "outcome"],+ "additionalProperties": false+ }`)+ wantSchema := string(rawSchema)++ got := ToolInputSchema(Capability{+ Name: DecideActionCapabilityName,+ Path: ActionDecisionCapabilityPath,+ Method: http.MethodPost,+ InputSchema: rawSchema,+ })++ if string(got) != wantSchema {+ t.Fatalf("manifest-owned schema must be forwarded verbatim, got %s want %s", got, wantSchema)+ }++ got[0] = '['+ if string(rawSchema) != wantSchema {+ t.Fatalf("ToolInputSchema must not alias manifest-owned schema: source=%s got=%s", rawSchema, got)+ }+}++func TestToolOutputSchemaPreservesManifestSchemaWithoutFallback(t *testing.T) {+ rawSchema := json.RawMessage(`{+ "type": "object",+ "properties": {+ "accepted": { "type": "boolean" }+ },+ "required": ["accepted"],+ "additionalProperties": false+ }`)+ wantSchema := string(rawSchema)++ got := ToolOutputSchema(Capability{+ Name: "accept_action",+ ResponseShape: "ActionDecisionResponse",+ OutputSchema: rawSchema,+ })++ if string(got) != wantSchema {+ t.Fatalf("manifest-owned output schema must be forwarded verbatim, got %s want %s", got, wantSchema)+ }++ got[0] = '['+ if string(rawSchema) != wantSchema {+ t.Fatalf("ToolOutputSchema must not alias manifest-owned schema: source=%s got=%s", rawSchema, got)+ }++ fallback := ToolOutputSchema(Capability{Name: "legacy_shape", ResponseShape: "LegacyResponse"})+ if fallback != nil {+ t.Fatalf("ToolOutputSchema must not derive a schema from responseShape; got %s", string(fallback))+ }+}++func assertToolAnnotations(t *testing.T, annotations *ToolBehaviorHints, readOnly, destructive, idempotent, openWorld bool) {+ t.Helper()+ if annotations == nil {+ t.Fatal("annotations are nil")+ }+ assertBoolRef(t, "readOnlyHint", annotations.ReadOnlyHint, readOnly)+ assertBoolRef(t, "destructiveHint", annotations.DestructiveHint, destructive)+ assertBoolRef(t, "idempotentHint", annotations.IdempotentHint, idempotent)+ assertBoolRef(t, "openWorldHint", annotations.OpenWorldHint, openWorld)+}++func assertBoolRef(t *testing.T, name string, got *bool, want bool) {+ t.Helper()+ if got == nil {+ t.Fatalf("%s is nil, want %v", name, want)+ }+ if *got != want {+ t.Fatalf("%s = %v, want %v", name, *got, want)+ }+}++func TestSubstitutePathParametersEscapesAsSinglePathSegments(t *testing.T) {+ got, err := SubstitutePathParameters(+ "/api/config/nodes/{nodeId}/test/{resourceId}",+ map[string]any{+ "nodeId": "pve/lab node",+ "resourceId": "vm:101",+ },+ )+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if got != "/api/config/nodes/pve%2Flab%20node/test/vm%3A101" {+ t.Fatalf("got %q, want path params escaped as single segments", got)+ }+}++func TestPathParameterSetNamesDeclaredPathArgs(t *testing.T) {+ got := PathParameterSet("/api/resources/{resourceId}/actions/{actionId}")+ for _, want := range []string{ResourceIDArgumentName, ActionIDArgumentName} {+ if !got[want] {+ t.Fatalf("PathParameterSet missing %q in %v", want, got)+ }+ }+}++func TestProjectCapabilityCallProjectsPathAndNestedBody(t *testing.T) {+ got, err := ProjectCapabilityCall(Capability{+ Path: OperatorStateCapabilityPath,+ Method: http.MethodPut,+ }, map[string]any{+ ResourceIDArgumentName: "vm:101",+ "body": map[string]any{+ "intentionallyOffline": true,+ "note": "maintenance",+ },+ })+ if err != nil {+ t.Fatalf("ProjectCapabilityCall: %v", err)+ }+ if got.Path != "/api/resources/vm%3A101/operator-state" {+ t.Fatalf("projected path = %q, want escaped resource id", got.Path)+ }+ if !got.HasBody {+ t.Fatal("PUT capability must project a JSON body")+ }+ var body map[string]any+ if err := json.Unmarshal(got.Body, &body); err != nil {+ t.Fatalf("projected body must be JSON: %v", err)+ }+ if body["intentionallyOffline"] != true || body["note"] != "maintenance" {+ t.Fatalf("nested body did not round-trip: %v", body)+ }+}++func TestProjectCapabilityCallTopLevelArgsBecomeBodyWithoutPathArgs(t *testing.T) {+ got, err := ProjectCapabilityCall(Capability{+ Path: OperatorStateCapabilityPath,+ Method: http.MethodPut,+ }, map[string]any{+ ResourceIDArgumentName: "vm:101",+ "intentionallyOffline": true,+ })+ if err != nil {+ t.Fatalf("ProjectCapabilityCall: %v", err)+ }+ if got.Path != "/api/resources/vm%3A101/operator-state" {+ t.Fatalf("projected path = %q, want escaped resource id", got.Path)+ }+ var body map[string]any+ if err := json.Unmarshal(got.Body, &body); err != nil {+ t.Fatalf("projected body must be JSON: %v", err)+ }+ if _, hasPathArg := body[ResourceIDArgumentName]; hasPathArg {+ t.Fatalf("path argument must not be duplicated into request body: %v", body)+ }+ if body["intentionallyOffline"] != true {+ t.Fatalf("non-placeholder top-level argument missing from body: %v", body)+ }+}++func TestProjectCapabilityCallDoesNotLeakInternalArgumentsIntoBody(t *testing.T) {+ got, err := ProjectCapabilityCall(Capability{+ Path: OperatorStateCapabilityPath,+ Method: http.MethodPut,+ }, WithApprovalArgument(map[string]any{+ ResourceIDArgumentName: "vm:101",+ "intentionallyOffline": true,+ }, "approval-1"))+ if err != nil {+ t.Fatalf("ProjectCapabilityCall: %v", err)+ }+ var body map[string]any+ if err := json.Unmarshal(got.Body, &body); err != nil {+ t.Fatalf("projected body must be JSON: %v", err)+ }+ if _, leaked := body[ApprovalArgumentKey]; leaked {+ t.Fatalf("internal approval argument leaked into public request body: %v", body)+ }+ if body["intentionallyOffline"] != true {+ t.Fatalf("public top-level argument missing from body: %v", body)+ }+}++func TestProjectCapabilityCallReadCapabilityHasNoBody(t *testing.T) {+ got, err := ProjectCapabilityCall(Capability{+ Path: ResourceContextCapabilityPath,+ Method: http.MethodGet,+ }, map[string]any{ResourceIDArgumentName: "vm:101"})+ if err != nil {+ t.Fatalf("ProjectCapabilityCall: %v", err)+ }+ if got.Path != "/api/agent/resource-context/vm%3A101" {+ t.Fatalf("projected path = %q, want escaped resource id", got.Path)+ }+ if got.HasBody || len(got.Body) != 0 {+ t.Fatalf("GET capability must not project body, got hasBody=%v body=%s", got.HasBody, got.Body)+ }+}diff --git a/internal/agentcapabilities/provider_tool_artifacts.go b/internal/agentcapabilities/provider_tool_artifacts.gonew file mode 100644index 0000000000..49dd51a74d--- /dev/null+++ b/internal/agentcapabilities/provider_tool_artifacts.go@@ -0,0 +1,144 @@+package agentcapabilities++import (+ "regexp"+ "strings"+)++// Compiled regexes for structural provider tool-call artifacts from common LLM+// providers. These guards belong to the shared provider boundary so Assistant+// streaming and external adapter bridges do not diverge on what counts as raw+// tool-call leakage.+var (+ providerDSMLMarkers = []string{+ "<|DSML|",+ "</|DSML|",+ "<||DSML||",+ "</||DSML||",+ "<||DSML||",+ "</||DSML||",+ "<|DSML|",+ "</|DSML|",+ "<|/DSML|",+ "<||/DSML||",+ "<|/DSML|",+ "<||/DSML||",+ }++ providerXMLToolCallRe = regexp.MustCompile(`(?s)</?(?:tool_calls?|function_calls?)>`)+ providerPipeMarkerRe = regexp.MustCompile(`<\|(?:plugin|interpreter|tool_call)\|>`)+ providerMiniMaxRe = regexp.MustCompile(`(?m)^minimax:tool_call\b`)+ providerDSMLRe = regexp.MustCompile(`</?[\||]+/?DSML[\||]*`)++ providerJSONToolCallRe = regexp.MustCompile(+ `(?:^|\n)[ \t]*(?:` + "```" + `[ \t]*(?:json|JSON)?[ \t]*\n?[ \t]*)?\{[ \t\n]*"name"[ \t]*:[ \t]*"([a-zA-Z_][a-zA-Z0-9_]*)"`,+ )+ providerPlainFunctionToolCallRe = regexp.MustCompile(`(?:^|[^a-zA-Z0-9_])([a-zA-Z_][a-zA-Z0-9_]*)[ \t\r\n]*\(`)+)++// ProviderToolCallArtifactIndex returns the byte offset of the first known+// provider tool-call artifact in content, or -1 when content can be shown as+// normal assistant text. Tool-name-shaped leaks are gated by catalog so+// unrelated JSON and function examples are not treated as provider artifacts.+func ProviderToolCallArtifactIndex(content string, catalog ProviderToolNameCatalog) int {+ if content == "" {+ return -1+ }++ first := -1+ record := func(idx int) {+ if idx < 0 {+ return+ }+ if first < 0 || idx < first {+ first = idx+ }+ }++ for _, marker := range providerDSMLMarkers {+ if idx := strings.Index(content, marker); idx >= 0 {+ record(idx)+ }+ }++ if loc := providerDSMLRe.FindStringIndex(content); loc != nil {+ record(loc[0])+ }+ if loc := providerXMLToolCallRe.FindStringIndex(content); loc != nil {+ record(loc[0])+ }+ if loc := providerPipeMarkerRe.FindStringIndex(content); loc != nil {+ record(loc[0])+ }+ if loc := providerMiniMaxRe.FindStringIndex(content); loc != nil {+ record(loc[0])+ }+ record(providerJSONToolCallLeakIndex(content, catalog))+ record(providerPlainFunctionToolCallLeakIndex(content, catalog))++ return first+}++// SplitTrailingProviderToolNamePrefix holds a trailing token fragment when it+// can still become a known provider tool name. Streaming callers can keep the+// held suffix private until the next chunk proves whether it is prose or a raw+// provider tool call.+func SplitTrailingProviderToolNamePrefix(content string, catalog ProviderToolNameCatalog) (visible string, held string) {+ if content == "" {+ return "", ""+ }++ start := len(content)+ for start > 0 {+ ch := content[start-1]+ if (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '_' {+ start--+ continue+ }+ break+ }++ if start == len(content) {+ return content, ""+ }++ token := content[start:]+ if catalog.HasPrefix(token) {+ return content[:start], token+ }+ return content, ""+}++func providerJSONToolCallLeakIndex(content string, catalog ProviderToolNameCatalog) int {+ if content == "" {+ return -1+ }+ matches := providerJSONToolCallRe.FindAllStringSubmatchIndex(content, -1)+ for _, m := range matches {+ if len(m) < 4 || m[2] < 0 || m[3] < 0 {+ continue+ }+ name := content[m[2]:m[3]]+ if catalog.Has(name) {+ return m[0]+ }+ }+ return -1+}++func providerPlainFunctionToolCallLeakIndex(content string, catalog ProviderToolNameCatalog) int {+ if content == "" {+ return -1+ }+ matches := providerPlainFunctionToolCallRe.FindAllStringSubmatchIndex(content, -1)+ for _, m := range matches {+ if len(m) < 4 || m[2] < 0 || m[3] < 0 {+ continue+ }+ name := content[m[2]:m[3]]+ if catalog.Has(name) {+ return m[2]+ }+ }+ return -1+}diff --git a/internal/agentcapabilities/provider_tool_artifacts_test.go b/internal/agentcapabilities/provider_tool_artifacts_test.gonew file mode 100644index 0000000000..eb4522694d--- /dev/null+++ b/internal/agentcapabilities/provider_tool_artifacts_test.go@@ -0,0 +1,130 @@+package agentcapabilities++import (+ "strings"+ "testing"+)++func TestProviderToolCallArtifactIndexDetectsSharedProviderLeakShapes(t *testing.T) {+ catalog := NewProviderToolNameCatalog([]string{+ "pulse_query",+ "pulse_discovery",+ "pulse_read",+ PulseQuestionToolName,+ })++ tests := []struct {+ name string+ input string+ wantIndex int+ }{+ {+ name: "DeepSeek DSML marker",+ input: "Answer<|DSML|invoke>",+ wantIndex: strings.Index("Answer<|DSML|invoke>", "<|DSML|"),+ },+ {+ name: "XML tool_call envelope",+ input: "Answer\n<tool_call>{\"name\":\"pulse_query\"}</tool_call>",+ wantIndex: strings.Index("Answer\n<tool_call>{\"name\":\"pulse_query\"}</tool_call>", "<tool_call>"),+ },+ {+ name: "pipe marker",+ input: "Some text<|tool_call|>extra",+ wantIndex: strings.Index("Some text<|tool_call|>extra", "<|tool_call|>"),+ },+ {+ name: "minimax marker",+ input: "Response\nminimax:tool_call {\"name\":\"pulse_query\"}",+ wantIndex: strings.Index("Response\nminimax:tool_call {\"name\":\"pulse_query\"}", "minimax:tool_call"),+ },+ {+ name: "JSON tool call leak preserves prose before newline",+ input: "Looking up resource 233.\n{\"name\": \"pulse_query\", \"parameters\": {\"action\":\"get\"}}",+ wantIndex: strings.Index("Looking up resource 233.\n{\"name\": \"pulse_query\", \"parameters\": {\"action\":\"get\"}}", "\n"),+ },+ {+ name: "JSON native Assistant question leak",+ input: "Need one more detail.\n{\"name\":\"pulse_question\",\"input\":{\"questions\":[]}}",+ wantIndex: strings.Index("Need one more detail.\n{\"name\":\"pulse_question\",\"input\":{\"questions\":[]}}", "\n"),+ },+ {+ name: "code fenced JSON tool call leak",+ input: "Here's the call:\n```json\n{\"name\":\"pulse_discovery\",\"parameters\":{}}",+ wantIndex: strings.Index("Here's the call:\n```json\n{\"name\":\"pulse_discovery\",\"parameters\":{}}", "\n"),+ },+ {+ name: "function-style tool call leak",+ input: "I will check that now. pulse_read(target_host=\"current_resource\")",+ wantIndex: strings.Index("I will check that now. pulse_read(target_host=\"current_resource\")", "pulse_read"),+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := ProviderToolCallArtifactIndex(tt.input, catalog); got != tt.wantIndex {+ t.Fatalf("ProviderToolCallArtifactIndex() = %d, want %d", got, tt.wantIndex)+ }+ })+ }+}++func TestProviderToolCallArtifactIndexIgnoresNonToolJSONAndFunctions(t *testing.T) {+ catalog := NewProviderToolNameCatalog([]string{"pulse_query", "pulse_read"})+ for _, input := range []string{+ `{"name": "my-vm", "cpu": 50}`,+ `{"name": "frobnicate", "parameters": {}}`,+ `{"foo": "bar"}`,+ `helper(target_host="current_resource")`,+ `the pulse_query tool is useful`,+ } {+ if got := ProviderToolCallArtifactIndex(input, catalog); got != -1 {+ t.Fatalf("ProviderToolCallArtifactIndex(%q) = %d, want -1", input, got)+ }+ }+}++func TestSplitTrailingProviderToolNamePrefixUsesSharedCatalog(t *testing.T) {+ catalog := NewProviderToolNameCatalog([]string{"pulse_query", "pulse_read", "patrol_report_finding"})++ tests := []struct {+ name string+ input string+ wantVisible string+ wantHeld string+ }{+ {+ name: "partial tool name is held",+ input: "Let me check. pu",+ wantVisible: "Let me check. ",+ wantHeld: "pu",+ },+ {+ name: "complete tool name is held until next chunk proves prose or call",+ input: "pulse_read",+ wantVisible: "",+ wantHeld: "pulse_read",+ },+ {+ name: "unknown trailing token remains visible",+ input: "This is prose",+ wantVisible: "This is prose",+ wantHeld: "",+ },+ {+ name: "patrol prefix is held",+ input: "Investigating patrol_rep",+ wantVisible: "Investigating ",+ wantHeld: "patrol_rep",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ visible, held := SplitTrailingProviderToolNamePrefix(tt.input, catalog)+ if visible != tt.wantVisible || held != tt.wantHeld {+ t.Fatalf("SplitTrailingProviderToolNamePrefix() = (%q, %q), want (%q, %q)", visible, held, tt.wantVisible, tt.wantHeld)+ }+ })+ }+}diff --git a/internal/agentcapabilities/question_tool_test.go b/internal/agentcapabilities/question_tool_test.gonew file mode 100644index 0000000000..58ca411c75--- /dev/null+++ b/internal/agentcapabilities/question_tool_test.go@@ -0,0 +1,186 @@+package agentcapabilities++import "testing"++func TestParsePulseQuestionToolInputValid(t *testing.T) {+ input := map[string]interface{}{+ "questions": []interface{}{+ map[string]interface{}{+ "id": " q1 ",+ "question": " Pick one ",+ "options": []interface{}{+ map[string]interface{}{+ "label": " A ",+ "value": "",+ "description": " Alpha ",+ },+ },+ },+ map[string]interface{}{+ "id": "q2",+ "type": " TEXT ",+ "question": " Why? ",+ "header": " Context ",+ },+ },+ }++ questions, err := ParsePulseQuestionToolInput(input)+ if err != nil {+ t.Fatalf("ParsePulseQuestionToolInput returned error: %v", err)+ }+ if len(questions) != 2 {+ t.Fatalf("questions len = %d, want 2", len(questions))+ }++ first := questions[0]+ if first.ID != "q1" || first.Type != PulseQuestionToolTypeSelect || first.Question != "Pick one" {+ t.Fatalf("first question = %#v", first)+ }+ if len(first.Options) != 1 {+ t.Fatalf("first options len = %d, want 1", len(first.Options))+ }+ if first.Options[0] != (PulseQuestionToolOption{Label: "A", Value: "A", Description: "Alpha"}) {+ t.Fatalf("first option = %#v", first.Options[0])+ }++ second := questions[1]+ if second.ID != "q2" || second.Type != PulseQuestionToolTypeText || second.Question != "Why?" || second.Header != "Context" {+ t.Fatalf("second question = %#v", second)+ }+}++func TestParsePulseQuestionToolInputErrors(t *testing.T) {+ tests := []struct {+ name string+ input map[string]interface{}+ expectedErr string+ }{+ {+ name: "missing questions",+ input: map[string]interface{}{},+ expectedErr: "missing required field: questions",+ },+ {+ name: "questions must be array",+ input: map[string]interface{}{+ "questions": map[string]interface{}{},+ },+ expectedErr: "questions must be an array",+ },+ {+ name: "questions must not be empty",+ input: map[string]interface{}{+ "questions": []interface{}{},+ },+ expectedErr: "questions must not be empty",+ },+ {+ name: "invalid question entry",+ input: map[string]interface{}{+ "questions": []interface{}{"not-an-object"},+ },+ expectedErr: "invalid question entry",+ },+ {+ name: "missing question id",+ input: map[string]interface{}{+ "questions": []interface{}{+ map[string]interface{}{+ "question": "Pick one",+ },+ },+ },+ expectedErr: "question.id is required",+ },+ {+ name: "missing question text",+ input: map[string]interface{}{+ "questions": []interface{}{+ map[string]interface{}{+ "id": "q1",+ },+ },+ },+ expectedErr: "question.question is required",+ },+ {+ name: "invalid question type",+ input: map[string]interface{}{+ "questions": []interface{}{+ map[string]interface{}{+ "id": "q1",+ "type": "binary",+ "question": "Pick one",+ },+ },+ },+ expectedErr: "question.type must be 'text' or 'select'",+ },+ {+ name: "select requires options",+ input: map[string]interface{}{+ "questions": []interface{}{+ map[string]interface{}{+ "id": "q1",+ "type": "select",+ "question": "Pick one",+ },+ },+ },+ expectedErr: "select questions must include options",+ },+ {+ name: "options must be array",+ input: map[string]interface{}{+ "questions": []interface{}{+ map[string]interface{}{+ "id": "q1",+ "question": "Pick one",+ "options": map[string]interface{}{},+ },+ },+ },+ expectedErr: "question.options must be an array",+ },+ {+ name: "null options rejected",+ input: map[string]interface{}{+ "questions": []interface{}{+ map[string]interface{}{+ "id": "q1",+ "question": "Pick one",+ "options": nil,+ },+ },+ },+ expectedErr: "question.options must be an array",+ },+ {+ name: "option label required",+ input: map[string]interface{}{+ "questions": []interface{}{+ map[string]interface{}{+ "id": "q1",+ "question": "Pick one",+ "options": []interface{}{+ map[string]interface{}{+ "label": " ",+ },+ },+ },+ },+ },+ expectedErr: "option.label is required",+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ _, err := ParsePulseQuestionToolInput(tc.input)+ if err == nil || err.Error() != tc.expectedErr {+ t.Fatalf("ParsePulseQuestionToolInput error = %v, want %q", err, tc.expectedErr)+ }+ })+ }+}diff --git a/internal/agentcapabilities/schema.go b/internal/agentcapabilities/schema.gonew file mode 100644index 0000000000..72e74ec9df--- /dev/null+++ b/internal/agentcapabilities/schema.go@@ -0,0 +1,1061 @@+package agentcapabilities++import (+ "bytes"+ "encoding/json"+ "fmt"+ "strings"+)++// Tool describes a structured tool definition with a JSON object input schema.+// The Assistant registry owns concrete tool handlers, while this shared shape+// keeps registry-to-provider projection aligned with external agent adapters.+type Tool struct {+ Name string `json:"name"`+ Description string `json:"description,omitempty"`+ InputSchema InputSchema `json:"inputSchema"`+}++// NormalizeCollections keeps registry tool definitions stable when they cross+// Assistant, provider, and external-agent boundaries.+func (t Tool) NormalizeCollections() Tool {+ t.InputSchema = t.InputSchema.NormalizeCollections()+ return t+}++// ProviderTool is the neutral chat-provider tool declaration projected from the+// Assistant registry. Provider clients map this into their supported upstream+// function schema fields, while Pulse-owned metadata stays available to local+// runtime and contract checks without being blindly forwarded.+type ProviderTool struct {+ Type string `json:"type,omitempty"`+ Name string `json:"name"`+ Description string `json:"description,omitempty"`+ InputSchema map[string]interface{} `json:"input_schema"`+ MaxUses int `json:"max_uses,omitempty"`+ BehaviorHints *ToolBehaviorHints `json:"behavior_hints,omitempty"`+ PulseGovernance *ToolGovernanceDescriptor `json:"pulse_governance,omitempty"`+}++// AssistantProviderToolOptions controls native Assistant surface-tool+// projection. Registry tools are always projected from the shared governed+// manifest; native interactive tools are opt-in because Patrol/autonomous runs+// cannot wait on in-app user input.+type AssistantProviderToolOptions struct {+ IncludeQuestionTool bool+}++// EmptyProviderTool returns a provider tool with initialized collection fields.+func EmptyProviderTool() ProviderTool {+ return ProviderTool{}.NormalizeCollections()+}++// NormalizeCollections keeps provider tool JSON stable by preserving an empty+// input_schema object instead of marshaling it as null.+func (t ProviderTool) NormalizeCollections() ProviderTool {+ t.InputSchema = CloneProviderInputSchema(t.InputSchema)+ if t.InputSchema == nil {+ t.InputSchema = map[string]interface{}{}+ }+ t.BehaviorHints = CloneToolBehaviorHints(t.BehaviorHints)+ if t.PulseGovernance != nil {+ governance := *t.PulseGovernance+ t.PulseGovernance = &governance+ }+ return t+}++// ProviderToolCall is the provider-facing tool invocation shape returned by+// chat model clients. Keeping it here lets Assistant and external-agent+// adapters share the provider-call to tools/call bridge.+type ProviderToolCall struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Input map[string]interface{} `json:"input"`+ ThoughtSignature json.RawMessage `json:"thought_signature,omitempty"`+}++// EmptyProviderToolCall returns a provider tool call with initialized+// collection fields.+func EmptyProviderToolCall() ProviderToolCall {+ return ProviderToolCall{}.NormalizeCollections()+}++// NormalizeCollections keeps provider tool-call JSON stable by preserving an+// empty input object instead of marshaling it as null.+func (t ProviderToolCall) NormalizeCollections() ProviderToolCall {+ t.Input = CloneToolArguments(t.Input)+ t.ThoughtSignature = CloneRawMessage(t.ThoughtSignature)+ if t.Input == nil {+ t.Input = map[string]interface{}{}+ }+ return t+}++// ProviderToolResult is the provider-facing response shape sent back to model+// clients after a tool invocation is executed.+type ProviderToolResult struct {+ ToolUseID string `json:"tool_use_id"`+ Content string `json:"content"`+ IsError bool `json:"is_error,omitempty"`+}++// ProviderToolResultContextOptions controls how a provider tool result is+// projected into the model-facing context while preserving the full transcript+// result. A non-positive MaxModelContentChars disables truncation.+type ProviderToolResultContextOptions struct {+ MaxModelContentChars int+}++// ProviderToolResultTruncation describes the model-context truncation applied+// while projecting a provider tool result.+type ProviderToolResultTruncation struct {+ Applied bool+ OriginalChars int+ MaxChars int+ TruncatedChars int+}++// ProviderToolResultContextProjection carries the full transcript result and+// the result sent back to the model for the next provider turn.+type ProviderToolResultContextProjection struct {+ Transcript ProviderToolResult+ Model ProviderToolResult+ Truncation ProviderToolResultTruncation+}++// NewProviderToolResult builds the provider-facing result shape in one place so+// Assistant turns and external-agent adapters do not duplicate tool-result JSON.+func NewProviderToolResult(toolUseID, content string, isError bool) ProviderToolResult {+ return ProviderToolResult{+ ToolUseID: toolUseID,+ Content: content,+ IsError: isError,+ }+}++// NewProviderToolErrorResult builds a provider-facing synthetic error result.+func NewProviderToolErrorResult(toolUseID, content string) ProviderToolResult {+ return NewProviderToolResult(toolUseID, content, true)+}++// NewProviderToolResultFromToolResult projects a shared tool result into the+// provider context shape sent back to chat models.+func NewProviderToolResultFromToolResult(toolUseID string, result ToolResult) ProviderToolResult {+ interpreted := InterpretToolResult(result)+ return NewProviderToolResult(toolUseID, interpreted.Text, interpreted.IsError)+}++// NewProviderToolResultContextProjection builds the paired transcript/model+// provider results in one shared place. The transcript result retains full+// content; the model result applies the supplied model-context limit.+func NewProviderToolResultContextProjection(toolUseID, content string, isError bool, opts ProviderToolResultContextOptions) ProviderToolResultContextProjection {+ modelContent, truncation := ProviderToolResultModelContent(content, opts)+ return ProviderToolResultContextProjection{+ Transcript: NewProviderToolResult(toolUseID, content, isError),+ Model: NewProviderToolResult(toolUseID, modelContent, isError),+ Truncation: truncation,+ }+}++// NewProviderToolResultContextProjectionFromToolResult projects a shared tool+// result into the paired transcript/model provider results used by native+// Assistant execution and external adapters with provider context.+func NewProviderToolResultContextProjectionFromToolResult(toolUseID string, result ToolResult, opts ProviderToolResultContextOptions) ProviderToolResultContextProjection {+ interpreted := InterpretToolResult(result)+ return NewProviderToolResultContextProjection(toolUseID, interpreted.Text, interpreted.IsError, opts)+}++// ProviderToolResultModelContent applies the shared provider tool-result+// truncation notice used for model context. The caller supplies the limit so+// each surface keeps owning its model-context budget.+func ProviderToolResultModelContent(content string, opts ProviderToolResultContextOptions) (string, ProviderToolResultTruncation) {+ maxChars := opts.MaxModelContentChars+ if maxChars <= 0 || len(content) <= maxChars {+ return content, ProviderToolResultTruncation{}+ }++ truncatedChars := len(content) - maxChars+ truncated := content[:maxChars]+ return fmt.Sprintf("%s\n\n---\n[TRUNCATED: %d characters cut. The result was too large. If you need specific details that may have been cut, make a more targeted query (e.g., filter by specific resource or type).]", truncated, truncatedChars), ProviderToolResultTruncation{+ Applied: true,+ OriginalChars: len(content),+ MaxChars: maxChars,+ TruncatedChars: truncatedChars,+ }+}++// ProjectProviderToolCallToToolCall projects a model-chosen provider tool call+// into the shared tool-call parameter envelope used by Assistant tool execution+// and external-agent adapters.+func ProjectProviderToolCallToToolCall(tc ProviderToolCall) ToolCallParams {+ return NormalizeToolCallParams(ToolCallParams{+ Name: tc.Name,+ Arguments: tc.Input,+ })+}++// NormalizeProviderToolCallForExecution returns the provider call shape that+// Assistant should execute after projecting through the shared tools/call+// contract. The provider id and thought signature stay attached for transcript+// and provider-continuation use, while name/arguments are normalized exactly as+// the shared tool-call contract sees them.+func NormalizeProviderToolCallForExecution(tc ProviderToolCall) ProviderToolCall {+ normalized := tc.NormalizeCollections()+ params := ProjectProviderToolCallToToolCall(tc)+ normalized.Name = params.Name+ normalized.Input = params.Arguments+ return normalized+}++// NormalizeProviderToolCallsForExecution preserves provider order while+// normalizing every call through the shared tools/call projection.+func NormalizeProviderToolCallsForExecution(calls []ProviderToolCall) []ProviderToolCall {+ normalized := make([]ProviderToolCall, 0, len(calls))+ for _, call := range calls {+ normalized = append(normalized, NormalizeProviderToolCallForExecution(call))+ }+ return normalized+}++// NewPulseQuestionProviderTool returns the native Assistant structured+// clarification tool declaration. It is intentionally provider-facing only:+// pulse_question is not a manifest capability or MCP tool, but its identity and+// schema still belong to the shared Pulse Intelligence provider-tool contract+// so native chat does not hand-roll tool policy locally.+func NewPulseQuestionProviderTool() ProviderTool {+ return ProviderTool{+ Name: PulseQuestionToolName,+ Description: "Ask the user for missing information using a structured prompt. Use this when you must clarify before proceeding (e.g., choose a target, confirm a risky action, or select among options).",+ InputSchema: PulseQuestionProviderInputSchema(),+ }.NormalizeCollections()+}++const (+ // LegacyAssistantRunCommandToolName is the compatibility alias still used by+ // the older native Assistant service. New registry-backed chat uses+ // pulse_control with type=command, but the alias vocabulary remains shared so+ // provider schemas, execution, and approval handling cannot drift.+ LegacyAssistantRunCommandToolName = "run_command"+ // LegacyAssistantFetchURLToolName is the compatibility alias for the older+ // native Assistant URL fetch helper.+ LegacyAssistantFetchURLToolName = "fetch_url"+ // LegacyAssistantSetResourceURLToolName is the compatibility alias for the+ // older native Assistant resource URL metadata helper.+ LegacyAssistantSetResourceURLToolName = "set_resource_url"++ LegacyAssistantCommandArgumentName = "command"+ LegacyAssistantRunOnHostArgumentName = "run_on_host"+ LegacyAssistantTargetHostArgumentName = "target_host"+ LegacyAssistantURLArgumentName = "url"+ LegacyAssistantResourceTypeArgumentName = "resource_type"+ LegacyAssistantResourceIDArgumentName = "resource_id"+)++// LegacyAssistantUtilityProviderTools returns the provider-facing compatibility+// tools still exposed by the older native Assistant service. The definitions+// live in the shared provider-tool contract so legacy Assistant aliases can be+// bridged toward the registry-backed Pulse Intelligence core without local+// schema copies.+func LegacyAssistantUtilityProviderTools() []ProviderTool {+ return ProjectProviderTools([]Tool{+ legacyAssistantRunCommandTool(),+ legacyAssistantFetchURLTool(),+ legacyAssistantSetResourceURLTool(),+ })+}++func legacyAssistantRunCommandTool() Tool {+ return Tool{+ Name: LegacyAssistantRunCommandToolName,+ Description: "Execute a shell command. By default runs on the current target (container/VM), but set run_on_host=true for Proxmox host commands. IMPORTANT: For targets on different nodes, specify target_host to route to the correct PVE node.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ LegacyAssistantCommandArgumentName: {+ Type: "string",+ Description: "The shell command to execute (e.g., 'ps aux --sort=-%mem | head -20')",+ },+ LegacyAssistantRunOnHostArgumentName: {+ Type: "boolean",+ Description: "If true, run on the Proxmox/Docker host instead of inside the container/VM. Use for pct/qm commands like 'pct resize 101 rootfs +10G'. When true, you should also set target_host.",+ },+ LegacyAssistantTargetHostArgumentName: {+ Type: "string",+ Description: "Optional hostname of the specific host/node to run the command on. Use this to explicitly route pct/qm/docker commands to the correct host node or Docker host. Check the 'node' or 'Host Node' field in the target's context.",+ },+ },+ Required: []string{LegacyAssistantCommandArgumentName},+ },+ }+}++func legacyAssistantFetchURLTool() Tool {+ return Tool{+ Name: LegacyAssistantFetchURLToolName,+ Description: "Fetch content from a URL. Use this to check if web services are responding, read API endpoints, or fetch documentation. Works with local network URLs and public sites.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ LegacyAssistantURLArgumentName: {+ Type: "string",+ Description: "The URL to fetch (e.g., 'http://192.0.2.50:8080/api/health' or 'https://example.com/docs')",+ },+ },+ Required: []string{LegacyAssistantURLArgumentName},+ },+ }+}++func legacyAssistantSetResourceURLTool() Tool {+ return Tool{+ Name: LegacyAssistantSetResourceURLToolName,+ Description: "Set the web URL for a resource in Pulse after discovering a web service. Use this when you've found a web server running on a VM/container/host and want to save it for quick access. The URL will appear as a clickable link in the Pulse dashboard.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ LegacyAssistantResourceTypeArgumentName: {+ Type: "string",+ Description: "Canonical v6 resource type: 'vm', 'system-container', 'oci-container', 'app-container', 'agent', 'node', or 'docker-host'",+ Enum: []string{"vm", "system-container", "oci-container", "app-container", "agent", "node", "docker-host"},+ },+ LegacyAssistantResourceIDArgumentName: {+ Type: "string",+ Description: "The resource ID from context. For VMs/LXC, use the canonical resource ID shown by Pulse (for example 'homelab:pve-node:150'). For app containers, use the container resource ID (for example 'hostid:container:containerid').",+ },+ LegacyAssistantURLArgumentName: {+ Type: "string",+ Description: "The discovered URL (e.g., 'http://192.0.2.50:8096' for Jellyfin). Use an empty string to remove the URL.",+ },+ },+ Required: []string{LegacyAssistantResourceTypeArgumentName, LegacyAssistantResourceIDArgumentName},+ },+ }+}++// PulseQuestionToolType is the shared value vocabulary for the native+// Assistant structured clarification tool's `type` field.+type PulseQuestionToolType string++const (+ PulseQuestionToolTypeText PulseQuestionToolType = "text"+ PulseQuestionToolTypeSelect PulseQuestionToolType = "select"+)++// PulseQuestionToolTypeValues returns the provider-schema enum for+// pulse_question question types.+func PulseQuestionToolTypeValues() []string {+ return []string{string(PulseQuestionToolTypeText), string(PulseQuestionToolTypeSelect)}+}++// NormalizePulseQuestionToolType applies the shared pulse_question type+// defaulting and validation rule used by provider schemas and native Assistant+// input parsing.+func NormalizePulseQuestionToolType(rawType string, hasOptions bool) (PulseQuestionToolType, error) {+ normalizedType := strings.TrimSpace(strings.ToLower(rawType))+ if normalizedType == "" {+ if hasOptions {+ normalizedType = string(PulseQuestionToolTypeSelect)+ } else {+ normalizedType = string(PulseQuestionToolTypeText)+ }+ }++ switch PulseQuestionToolType(normalizedType) {+ case PulseQuestionToolTypeText:+ return PulseQuestionToolTypeText, nil+ case PulseQuestionToolTypeSelect:+ if !hasOptions {+ return "", fmt.Errorf("select questions must include options")+ }+ return PulseQuestionToolTypeSelect, nil+ default:+ return "", fmt.Errorf("question.type must be 'text' or 'select'")+ }+}++// PulseQuestionToolQuestion is the normalized in-app Assistant question payload+// parsed from the shared pulse_question provider tool input.+type PulseQuestionToolQuestion struct {+ ID string+ Type PulseQuestionToolType+ Header string+ Question string+ Options []PulseQuestionToolOption+}++// PulseQuestionToolOption is one normalized option for a select-style+// pulse_question entry.+type PulseQuestionToolOption struct {+ Label string+ Value string+ Description string+}++type pulseQuestionToolInputPayload struct {+ Questions json.RawMessage `json:"questions"`+}++type pulseQuestionToolInputQuestion struct {+ ID string `json:"id"`+ Type string `json:"type,omitempty"`+ Header string `json:"header,omitempty"`+ Question string `json:"question"`+ Options json.RawMessage `json:"options,omitempty"`+}++type pulseQuestionToolInputOption struct {+ Label string `json:"label"`+ Value string `json:"value,omitempty"`+ Description string `json:"description,omitempty"`+}++// ParsePulseQuestionToolInput applies the same validation and normalization as+// the advertised pulse_question provider schema. Native Assistant code should+// adapt the returned values into UI-specific question events rather than owning+// a second parser.+func ParsePulseQuestionToolInput(input map[string]interface{}) ([]PulseQuestionToolQuestion, error) {+ payloadBytes, err := json.Marshal(input)+ if err != nil {+ return nil, fmt.Errorf("invalid question payload: %w", err)+ }++ var payload pulseQuestionToolInputPayload+ if err := json.Unmarshal(payloadBytes, &payload); err != nil {+ return nil, fmt.Errorf("invalid question payload: %w", err)+ }++ if len(payload.Questions) == 0 {+ return nil, fmt.Errorf("missing required field: questions")+ }++ var rawQuestions []json.RawMessage+ if err := json.Unmarshal(payload.Questions, &rawQuestions); err != nil {+ return nil, fmt.Errorf("questions must be an array")+ }++ if len(rawQuestions) == 0 {+ return nil, fmt.Errorf("questions must not be empty")+ }++ questions := make([]PulseQuestionToolQuestion, 0, len(rawQuestions))+ for _, rawQuestion := range rawQuestions {+ var parsedQuestion pulseQuestionToolInputQuestion+ if err := json.Unmarshal(rawQuestion, &parsedQuestion); err != nil {+ return nil, fmt.Errorf("invalid question entry")+ }++ id := strings.TrimSpace(parsedQuestion.ID)+ questionText := strings.TrimSpace(parsedQuestion.Question)+ header := strings.TrimSpace(parsedQuestion.Header)++ if id == "" {+ return nil, fmt.Errorf("question.id is required")+ }+ if questionText == "" {+ return nil, fmt.Errorf("question.question is required")+ }++ opts, err := parsePulseQuestionToolOptions(parsedQuestion.Options)+ if err != nil {+ return nil, err+ }++ qType, err := NormalizePulseQuestionToolType(parsedQuestion.Type, len(opts) > 0)+ if err != nil {+ return nil, err+ }++ questions = append(questions, PulseQuestionToolQuestion{+ ID: id,+ Type: qType,+ Header: header,+ Question: questionText,+ Options: opts,+ })+ }+ return questions, nil+}++func parsePulseQuestionToolOptions(rawOptions json.RawMessage) ([]PulseQuestionToolOption, error) {+ if len(rawOptions) == 0 {+ return nil, nil+ }++ trimmed := bytes.TrimSpace(rawOptions)+ if bytes.Equal(trimmed, []byte("null")) {+ return nil, fmt.Errorf("question.options must be an array")+ }++ var decodedOptions []pulseQuestionToolInputOption+ if err := json.Unmarshal(rawOptions, &decodedOptions); err != nil {+ return nil, fmt.Errorf("question.options must be an array")+ }++ options := make([]PulseQuestionToolOption, 0, len(decodedOptions))+ for _, decodedOption := range decodedOptions {+ label := strings.TrimSpace(decodedOption.Label)+ value := strings.TrimSpace(decodedOption.Value)+ desc := strings.TrimSpace(decodedOption.Description)++ if label == "" {+ return nil, fmt.Errorf("option.label is required")+ }+ if value == "" {+ value = label+ }++ options = append(options, PulseQuestionToolOption{+ Label: label,+ Value: value,+ Description: desc,+ })+ }++ return options, nil+}++// PulseQuestionProviderInputSchema returns the provider-facing JSON Schema for+// the native Assistant structured clarification tool.+func PulseQuestionProviderInputSchema() map[string]interface{} {+ return CloneProviderInputSchema(map[string]interface{}{+ "type": "object",+ "properties": map[string]interface{}{+ "questions": map[string]interface{}{+ "type": "array",+ "items": map[string]interface{}{+ "type": "object",+ "properties": map[string]interface{}{+ "id": map[string]interface{}{+ "type": "string",+ "description": "Stable identifier for this question (used in the answer payload).",+ },+ "type": map[string]interface{}{+ "type": "string",+ "description": "Question type. Use 'text' for free-form input or 'select' for predefined options.",+ "enum": PulseQuestionToolTypeValues(),+ },+ "header": map[string]interface{}{+ "type": "string",+ "description": "Optional short context shown above the question.",+ },+ "question": map[string]interface{}{+ "type": "string",+ "description": "The question shown to the user.",+ },+ "options": map[string]interface{}{+ "type": "array",+ "items": map[string]interface{}{+ "type": "object",+ "properties": map[string]interface{}{+ "label": map[string]interface{}{"type": "string"},+ "value": map[string]interface{}{"type": "string"},+ "description": map[string]interface{}{+ "type": "string",+ "description": "Optional detail shown under the label.",+ },+ },+ "required": []string{"label"},+ },+ },+ },+ "required": []string{"id", "question"},+ },+ },+ },+ "required": []string{"questions"},+ })+}++// ParseProviderToolInput parses a provider-emitted tool input JSON object. It+// returns ok=false for incomplete streamed JSON, malformed JSON, empty input, or+// non-object values so stream progress surfaces can keep showing raw input while+// the provider is still emitting arguments.+func ParseProviderToolInput(raw string) (map[string]interface{}, bool) {+ if strings.TrimSpace(raw) == "" {+ return nil, false+ }+ var input map[string]interface{}+ if err := json.Unmarshal([]byte(raw), &input); err != nil || input == nil {+ return nil, false+ }+ return input, true+}++// ProviderToolInputOrRaw returns a parsed provider tool input object, or the+// legacy-compatible raw fallback used when a provider emits malformed,+// incomplete, or empty arguments at final tool-call assembly time.+func ProviderToolInputOrRaw(raw string) map[string]interface{} {+ if input, ok := ParseProviderToolInput(raw); ok {+ return input+ }+ return map[string]interface{}{"raw": raw}+}++// InputSchema describes the expected object input for a tool.+type InputSchema struct {+ Type string `json:"type"` // Always "object"+ Properties map[string]PropertySchema `json:"properties"`+ Required []string `json:"required,omitempty"`+}++// NormalizeCollections returns an independent JSON-object schema with stable+// empty collections.+func (s InputSchema) NormalizeCollections() InputSchema {+ if s.Type == "" {+ s.Type = "object"+ }+ s.Properties = ClonePropertySchemas(s.Properties)+ if s.Properties == nil {+ s.Properties = map[string]PropertySchema{}+ }+ s.Required = append([]string(nil), s.Required...)+ return s+}++// PropertySchema describes a property in a structured tool input schema.+type PropertySchema struct {+ Type string `json:"type"`+ Description string `json:"description,omitempty"`+ Enum []string `json:"enum,omitempty"`+ Default interface{} `json:"default,omitempty"`+}++// NormalizeCollections returns an independent property schema for use in+// cross-surface tool declarations.+func (p PropertySchema) NormalizeCollections() PropertySchema {+ p.Enum = append([]string(nil), p.Enum...)+ p.Default = cloneSchemaValue(p.Default)+ return p+}++// ClonePropertySchemas returns an independent copy of structured tool property+// schemas.+func ClonePropertySchemas(properties map[string]PropertySchema) map[string]PropertySchema {+ if properties == nil {+ return nil+ }+ cloned := make(map[string]PropertySchema, len(properties))+ for name, property := range properties {+ cloned[name] = property.NormalizeCollections()+ }+ return cloned+}++// CloneProviderInputSchema returns an independent copy of a provider JSON+// Schema map.+func CloneProviderInputSchema(schema map[string]interface{}) map[string]interface{} {+ if schema == nil {+ return nil+ }+ cloned := make(map[string]interface{}, len(schema))+ for name, value := range schema {+ cloned[name] = cloneSchemaValue(value)+ }+ return cloned+}++func cloneSchemaValue(value interface{}) interface{} {+ switch typed := value.(type) {+ case map[string]interface{}:+ cloned := make(map[string]interface{}, len(typed))+ for key, child := range typed {+ cloned[key] = cloneSchemaValue(child)+ }+ return cloned+ case []interface{}:+ cloned := make([]interface{}, len(typed))+ for i, child := range typed {+ cloned[i] = cloneSchemaValue(child)+ }+ return cloned+ case []string:+ return append([]string(nil), typed...)+ default:+ return value+ }+}++// ObjectInputSchemaMap builds the common JSON Schema object envelope used by+// Pulse Intelligence capability manifests and adapters. Strict manifest-owned+// schemas should pass additionalProperties=false; adapter fallback schemas may+// pass true when the underlying endpoint contract is only partially known.+func ObjectInputSchemaMap(required []string, properties map[string]any, additionalProperties bool) map[string]any {+ schema := map[string]any{+ "type": "object",+ "properties": properties,+ "additionalProperties": additionalProperties,+ }+ if len(required) > 0 {+ schema["required"] = required+ }+ return schema+}++// StrictObjectInputSchemaMap builds a closed object schema for manifest-owned+// tool arguments.+func StrictObjectInputSchemaMap(required []string, properties map[string]any) map[string]any {+ return ObjectInputSchemaMap(required, properties, false)+}++// RawInputSchema marshals a hand-authored JSON Schema map into the raw manifest+// field served by the API and forwarded by adapters.+func RawInputSchema(schema map[string]any) json.RawMessage {+ raw, err := json.Marshal(schema)+ if err != nil {+ panic(err)+ }+ return raw+}++// CloneRawMessage returns an independent copy of a raw JSON payload.+func CloneRawMessage(raw json.RawMessage) json.RawMessage {+ if raw == nil {+ return nil+ }+ return append(json.RawMessage(nil), raw...)+}++// ObjectInputSchema builds a raw JSON Schema object envelope.+func ObjectInputSchema(required []string, properties map[string]any, additionalProperties bool) json.RawMessage {+ return RawInputSchema(ObjectInputSchemaMap(required, properties, additionalProperties))+}++// StrictObjectInputSchema builds a closed raw JSON Schema object envelope for+// manifest-owned tool arguments.+func StrictObjectInputSchema(required []string, properties map[string]any) json.RawMessage {+ return ObjectInputSchema(required, properties, false)+}++// ProviderInputSchema projects a structured registry input schema into the+// generic JSON Schema map expected by chat providers.+func ProviderInputSchema(schema InputSchema) map[string]interface{} {+ schema = schema.NormalizeCollections()+ projected := map[string]interface{}{+ "type": "object",+ "properties": ProviderPropertySchemas(schema.Properties),+ }++ if len(schema.Required) > 0 {+ projected["required"] = append([]string(nil), schema.Required...)+ }++ return projected+}++// ProviderInputSchemaFromRaw projects a manifest-authored JSON Schema into the+// provider-facing schema map used by Assistant provider tools. Manifest schemas+// are already JSON Schema object envelopes; this helper keeps legacy Assistant+// callers from copying required-field lists by hand.+func ProviderInputSchemaFromRaw(raw json.RawMessage) map[string]interface{} {+ if len(raw) == 0 {+ return ProviderInputSchema(InputSchema{})+ }++ var schema map[string]interface{}+ if err := json.Unmarshal(raw, &schema); err != nil || schema == nil {+ return ProviderInputSchema(InputSchema{})+ }++ projected := CloneProviderInputSchema(schema)+ if _, ok := projected["type"]; !ok {+ projected["type"] = "object"+ }+ if _, ok := projected["properties"]; !ok {+ projected["properties"] = map[string]interface{}{}+ }+ if required, ok := projected["required"].([]interface{}); ok {+ normalized := make([]string, 0, len(required))+ allStrings := true+ for _, value := range required {+ item, ok := value.(string)+ if !ok {+ allStrings = false+ break+ }+ normalized = append(normalized, item)+ }+ if allStrings {+ projected["required"] = normalized+ }+ }++ return projected+}++// ProjectProviderTool projects one Assistant registry tool into the generic+// provider tool shape used by model clients.+func ProjectProviderTool(tool Tool) ProviderTool {+ tool = tool.NormalizeCollections()+ return ProviderTool{+ Name: tool.Name,+ Description: tool.Description,+ InputSchema: ProviderInputSchema(tool.InputSchema),+ }.NormalizeCollections()+}++// ProjectProviderToolWithGovernance projects one Assistant registry tool into+// the provider-facing shape and appends the shared governance posture to the+// tool description when a matching descriptor is available.+func ProjectProviderToolWithGovernance(tool Tool, governance ToolGovernanceDescriptor) ProviderTool {+ projected := ProjectProviderTool(tool)+ if !providerToolGovernanceMatches(projected.Name, governance.Name) {+ return projected+ }+ governance = NormalizeToolGovernanceDescriptor(governance)+ projected.Description = ProviderToolDescriptionWithGovernance(projected.Description, governance)+ projected.BehaviorHints = ToolGovernanceBehaviorHints(governance)+ projected.PulseGovernance = &governance+ return projected.NormalizeCollections()+}++// ProjectProviderTools projects Assistant registry tools into provider-facing+// tool declarations while preserving order.+func ProjectProviderTools(tools []Tool) []ProviderTool {+ projected := make([]ProviderTool, 0, len(tools))+ for _, tool := range tools {+ projected = append(projected, ProjectProviderTool(tool))+ }+ return projected+}++// ProjectProviderToolsWithGovernance projects Assistant registry tools into+// provider-facing declarations while attaching the matching registry-owned+// governance descriptor to each description.+func ProjectProviderToolsWithGovernance(tools []Tool, governance []ToolGovernanceDescriptor) []ProviderTool {+ governanceByName := make(map[string]ToolGovernanceDescriptor, len(governance))+ for _, descriptor := range governance {+ name := strings.TrimSpace(descriptor.Name)+ if name == "" {+ continue+ }+ governanceByName[name] = descriptor+ }++ projected := make([]ProviderTool, 0, len(tools))+ for _, tool := range tools {+ name := strings.TrimSpace(tool.Name)+ descriptor, ok := governanceByName[name]+ if !ok {+ projected = append(projected, ProjectProviderTool(tool))+ continue+ }+ projected = append(projected, ProjectProviderToolWithGovernance(tool, descriptor))+ }+ return projected+}++// ProjectAssistantProviderTools projects the native Assistant provider tool+// surface from shared Pulse Intelligence contracts. Chat chooses whether the+// current turn is interactive; the shared layer owns how Assistant registry+// tools and Assistant-native interaction tools are composed.+func ProjectAssistantProviderTools(tools []Tool, governance []ToolGovernanceDescriptor, opts AssistantProviderToolOptions) []ProviderTool {+ projected := ProjectProviderToolsWithGovernance(tools, governance)+ if opts.IncludeQuestionTool {+ projected = append(projected, AssistantNativeProviderTools()...)+ }+ return projected+}++// ProjectPulseAssistantProviderTools projects native Assistant provider tools+// through the manifest-owned Pulse Assistant surface affordances. The runtime+// registry remains the source of available handlers; the manifest decides+// whether the Assistant surface may advertise tools and interactive questions.+func ProjectPulseAssistantProviderTools(manifest Manifest, tools []Tool, governance []ToolGovernanceDescriptor, opts AssistantProviderToolOptions) []ProviderTool {+ affordances, _ := ManifestSurfaceAffordances(manifest, SurfaceIDPulseAssistant)+ if !affordances.Tools {+ return []ProviderTool{}+ }+ if !affordances.InteractiveQuestions {+ opts.IncludeQuestionTool = false+ }+ return ProjectAssistantProviderTools(tools, governance, opts)+}++// ProviderToolGovernanceDescriptors extracts registry-owned governance from an+// offered Assistant provider-tool list. A nil tool slice means the caller has no+// concrete offered-tool list, so no complete metadata projection can be proven.+// An empty non-nil slice is a valid "no tools offered" manifest.+func ProviderToolGovernanceDescriptors(tools []ProviderTool) ([]ToolGovernanceDescriptor, bool) {+ if tools == nil {+ return nil, false+ }++ descriptors := make([]ToolGovernanceDescriptor, 0, len(tools))+ seen := make(map[string]bool, len(tools))+ for _, tool := range tools {+ name := strings.TrimSpace(tool.Name)+ if name == "" || seen[name] {+ continue+ }+ seen[name] = true+ if name == PulseQuestionToolName {+ continue+ }+ if tool.PulseGovernance == nil {+ return nil, false+ }+ descriptor := NormalizeToolGovernanceDescriptor(*tool.PulseGovernance)+ if !providerToolGovernanceMatches(name, descriptor.Name) {+ return nil, false+ }+ descriptors = append(descriptors, descriptor)+ }+ return descriptors, true+}++// AssistantNativeProviderTools returns provider-facing tools owned by the+// native in-app Assistant surface rather than the registry-backed execution+// tools. These names still belong to the shared provider-tool contract because+// model clients, prompt governance, and leak sanitizers all need the same+// surface vocabulary.+func AssistantNativeProviderTools() []ProviderTool {+ return []ProviderTool{NewPulseQuestionProviderTool()}+}++// AssistantNativeProviderToolNames returns the canonical names for native+// Assistant provider tools.+func AssistantNativeProviderToolNames() []string {+ return ProviderToolNames(AssistantNativeProviderTools())+}++// ProviderToolNames returns the stable offered-tool name sequence for a+// provider tool list. A nil tool slice remains nil so callers can preserve the+// "all manifest tools" meaning used by prompt projections; an empty non-nil+// slice means no tools are offered.+func ProviderToolNames(tools []ProviderTool) []string {+ if tools == nil {+ return nil+ }+ names := make([]string, 0, len(tools))+ seen := make(map[string]bool, len(tools))+ for _, tool := range tools {+ name := strings.TrimSpace(tool.Name)+ if name == "" || seen[name] {+ continue+ }+ seen[name] = true+ names = append(names, name)+ }+ return names+}++// ProviderToolNameCatalog is a reusable exact/prefix lookup over provider-tool+// names. It keeps Assistant stream sanitizers and adapter leak guards on the+// same name normalization rules as provider tool projection.+type ProviderToolNameCatalog struct {+ names []string+ set map[string]struct{}+}++// NewProviderToolNameCatalog builds a detached tool-name catalog from one or+// more ordered name groups. Empty and duplicate names are removed while the+// first-seen order is preserved.+func NewProviderToolNameCatalog(nameGroups ...[]string) ProviderToolNameCatalog {+ total := 0+ for _, names := range nameGroups {+ total += len(names)+ }++ catalog := ProviderToolNameCatalog{+ names: make([]string, 0, total),+ set: make(map[string]struct{}, total),+ }+ for _, names := range nameGroups {+ for _, name := range names {+ trimmed := strings.TrimSpace(name)+ if trimmed == "" {+ continue+ }+ if _, ok := catalog.set[trimmed]; ok {+ continue+ }+ catalog.set[trimmed] = struct{}{}+ catalog.names = append(catalog.names, trimmed)+ }+ }+ return catalog+}++// NewAssistantProviderToolNameCatalog adds native Assistant provider tools to+// the registered runtime tool names so leak guards recognize the complete+// Assistant provider surface.+func NewAssistantProviderToolNameCatalog(registryToolNames []string) ProviderToolNameCatalog {+ return NewProviderToolNameCatalog(registryToolNames, AssistantNativeProviderToolNames())+}++// Names returns a detached ordered copy of the catalog names.+func (c ProviderToolNameCatalog) Names() []string {+ return append([]string(nil), c.names...)+}++// Has reports whether name is in the catalog.+func (c ProviderToolNameCatalog) Has(name string) bool {+ if name == "" {+ return false+ }+ _, ok := c.set[name]+ return ok+}++// HasPrefix reports whether prefix can still become a catalogued tool name.+func (c ProviderToolNameCatalog) HasPrefix(prefix string) bool {+ if prefix == "" {+ return false+ }+ for _, name := range c.names {+ if strings.HasPrefix(name, prefix) {+ return true+ }+ }+ return false+}++// ProviderToolDescriptionWithGovernance returns a provider-facing description+// that keeps the tool's functional description and the canonical governance+// posture adjacent in the same declaration the model sees.+func ProviderToolDescriptionWithGovernance(description string, governance ToolGovernanceDescriptor) string {+ governanceDescription := strings.TrimSpace(ToolGovernancePromptDescription(governance))+ description = strings.TrimSpace(description)+ if governanceDescription == "" {+ return description+ }+ line := "Pulse governance: " + governanceDescription+ if description == "" {+ return line+ }+ return description + "\n\n" + line+}++func providerToolGovernanceMatches(toolName, governanceName string) bool {+ return strings.TrimSpace(toolName) != "" && strings.TrimSpace(toolName) == strings.TrimSpace(governanceName)+}++// ProviderPropertySchemas projects structured registry properties into provider+// JSON Schema property definitions.+func ProviderPropertySchemas(properties map[string]PropertySchema) map[string]interface{} {+ projected := make(map[string]interface{}, len(properties))+ for name, property := range properties {+ projected[name] = ProviderPropertySchema(property)+ }+ return projected+}++// ProviderPropertySchema projects one structured registry property into a+// provider JSON Schema property definition.+func ProviderPropertySchema(property PropertySchema) map[string]interface{} {+ property = property.NormalizeCollections()+ projected := map[string]interface{}{+ "type": property.Type,+ }+ if property.Description != "" {+ projected["description"] = property.Description+ }+ if len(property.Enum) > 0 {+ projected["enum"] = append([]string(nil), property.Enum...)+ }+ if property.Default != nil {+ projected["default"] = property.Default+ }+ return projected+}diff --git a/internal/agentcapabilities/schema_test.go b/internal/agentcapabilities/schema_test.gonew file mode 100644index 0000000000..df7760b164--- /dev/null+++ b/internal/agentcapabilities/schema_test.go@@ -0,0 +1,998 @@+package agentcapabilities++import (+ "encoding/json"+ "reflect"+ "strings"+ "testing"+)++func TestStrictObjectInputSchemaBuildsClosedManifestSchema(t *testing.T) {+ raw := StrictObjectInputSchema([]string{"resourceId"}, map[string]any{+ "resourceId": map[string]any{"type": "string"},+ })++ var schema map[string]any+ if err := json.Unmarshal(raw, &schema); err != nil {+ t.Fatalf("unmarshal schema: %v", err)+ }+ if schema["additionalProperties"] != false {+ t.Fatalf("strict schema additionalProperties = %v, want false", schema["additionalProperties"])+ }+ required, _ := schema["required"].([]any)+ if len(required) != 1 || required[0] != "resourceId" {+ t.Fatalf("strict schema required = %v, want [resourceId]", required)+ }+}++func TestObjectInputSchemaCanBuildPermissiveAdapterFallback(t *testing.T) {+ raw := ObjectInputSchema(nil, map[string]any{+ "body": map[string]any{+ "type": "object",+ "additionalProperties": true,+ },+ }, true)++ var schema map[string]any+ if err := json.Unmarshal(raw, &schema); err != nil {+ t.Fatalf("unmarshal schema: %v", err)+ }+ if schema["additionalProperties"] != true {+ t.Fatalf("permissive schema additionalProperties = %v, want true", schema["additionalProperties"])+ }+ if _, hasRequired := schema["required"]; hasRequired {+ t.Fatalf("schema without required args must omit required, got %v", schema["required"])+ }+}++func TestProviderInputSchemaProjectsStructuredToolSchema(t *testing.T) {+ required := []string{"mode"}+ enum := []string{"summary", "detail"}++ schema := InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ "mode": {+ Type: "string",+ Description: "Response detail level",+ Enum: enum,+ Default: "summary",+ },+ "limit": {+ Type: "number",+ Default: 25,+ },+ },+ Required: required,+ }++ projected := ProviderInputSchema(schema)+ if projected["type"] != "object" {+ t.Fatalf("projected type = %v, want object", projected["type"])+ }++ props, ok := projected["properties"].(map[string]interface{})+ if !ok {+ t.Fatalf("projected properties type = %T, want map[string]interface{}", projected["properties"])+ }+ mode, ok := props["mode"].(map[string]interface{})+ if !ok {+ t.Fatalf("mode property type = %T, want map[string]interface{}", props["mode"])+ }+ if mode["type"] != "string" {+ t.Fatalf("mode type = %v, want string", mode["type"])+ }+ if mode["description"] != "Response detail level" {+ t.Fatalf("mode description = %v, want Response detail level", mode["description"])+ }+ if !reflect.DeepEqual(mode["enum"], []string{"summary", "detail"}) {+ t.Fatalf("mode enum = %#v, want summary/detail", mode["enum"])+ }+ if mode["default"] != "summary" {+ t.Fatalf("mode default = %v, want summary", mode["default"])+ }++ limit, ok := props["limit"].(map[string]interface{})+ if !ok {+ t.Fatalf("limit property type = %T, want map[string]interface{}", props["limit"])+ }+ if limit["default"] != 25 {+ t.Fatalf("limit default = %v, want 25", limit["default"])+ }++ if !reflect.DeepEqual(projected["required"], []string{"mode"}) {+ t.Fatalf("projected required = %#v, want mode", projected["required"])+ }+}++func TestProjectProviderToolsProjectsRegistryTools(t *testing.T) {+ tools := []Tool{+ {+ Name: "pulse_read",+ Description: "Read infrastructure",+ InputSchema: InputSchema{+ Properties: map[string]PropertySchema{+ "target_host": {Type: "string", Description: "Host to inspect"},+ },+ Required: []string{"target_host"},+ },+ },+ {+ Name: "pulse_query",+ Description: "Query inventory",+ },+ }++ projected := ProjectProviderTools(tools)+ if len(projected) != 2 {+ t.Fatalf("ProjectProviderTools length = %d, want 2", len(projected))+ }+ if projected[0].Name != "pulse_read" || projected[0].Description != "Read infrastructure" {+ t.Fatalf("first provider tool = %+v", projected[0])+ }+ if projected[0].InputSchema["type"] != "object" {+ t.Fatalf("provider input schema type = %v, want object", projected[0].InputSchema["type"])+ }+ props := projected[0].InputSchema["properties"].(map[string]interface{})+ targetHost := props["target_host"].(map[string]interface{})+ if targetHost["description"] != "Host to inspect" {+ t.Fatalf("target_host description = %v", targetHost["description"])+ }+ if !reflect.DeepEqual(projected[0].InputSchema["required"], []string{"target_host"}) {+ t.Fatalf("provider required = %#v", projected[0].InputSchema["required"])+ }+ if len(projected[1].InputSchema["properties"].(map[string]interface{})) != 0 {+ t.Fatalf("empty registry schema should project empty properties: %#v", projected[1].InputSchema)+ }+}++func TestProjectProviderToolsWithGovernanceAppendsSharedGovernanceDescriptions(t *testing.T) {+ tools := []Tool{+ {+ Name: "pulse_read",+ Description: "Read infrastructure.",+ },+ {+ Name: "pulse_control",+ Description: "Run controlled actions.",+ },+ {+ Name: "pulse_extra",+ Description: "Provider-only helper.",+ },+ }+ governance := []ToolGovernanceDescriptor{+ NewToolGovernanceDescriptor("pulse_read", "Read infrastructure.", false, ToolGovernance{+ ActionMode: ActionModeRead,+ ApprovalPolicy: ApprovalPolicyScopeOnly,+ ApprovalSummary: "no approval required",+ Summary: "Read infrastructure.",+ }),+ NewToolGovernanceDescriptor("pulse_control", "Run controlled actions.", true, ToolGovernance{+ ActionMode: ActionModeWrite,+ ApprovalPolicy: ApprovalPolicyActionPlan,+ ApprovalSummary: "approval required in controlled mode",+ Summary: "State-changing action.",+ }),+ }++ projected := ProjectProviderToolsWithGovernance(tools, governance)+ if len(projected) != 3 {+ t.Fatalf("ProjectProviderToolsWithGovernance length = %d, want 3", len(projected))+ }+ if !strings.Contains(projected[0].Description, "Read infrastructure.") ||+ !strings.Contains(projected[0].Description, "Pulse governance: mode=read; approval=scope_only (no approval required); Read infrastructure.") {+ t.Fatalf("read provider description missing shared governance: %q", projected[0].Description)+ }+ assertProviderToolBehaviorHints(t, projected[0].BehaviorHints, true, false, true, true)+ if projected[0].PulseGovernance == nil || projected[0].PulseGovernance.Name != "pulse_read" || projected[0].PulseGovernance.ActionMode != ActionModeRead {+ t.Fatalf("read provider governance metadata = %+v, want normalized pulse_read/read", projected[0].PulseGovernance)+ }+ if !strings.Contains(projected[1].Description, "Run controlled actions.") ||+ !strings.Contains(projected[1].Description, "Pulse governance: mode=write; approval=action_plan (approval required in controlled mode); State-changing action.") {+ t.Fatalf("write provider description missing shared governance: %q", projected[1].Description)+ }+ assertProviderToolBehaviorHints(t, projected[1].BehaviorHints, false, true, false, true)+ if projected[1].PulseGovernance == nil || projected[1].PulseGovernance.Name != "pulse_control" || projected[1].PulseGovernance.ApprovalPolicy != ApprovalPolicyActionPlan {+ t.Fatalf("write provider governance metadata = %+v, want normalized pulse_control/action_plan", projected[1].PulseGovernance)+ }+ if strings.Contains(projected[2].Description, "Pulse governance:") {+ t.Fatalf("provider tool without matching governance must keep original description, got %q", projected[2].Description)+ }+ if projected[2].BehaviorHints != nil || projected[2].PulseGovernance != nil {+ t.Fatalf("provider tool without matching governance must not invent metadata, got hints=%+v governance=%+v", projected[2].BehaviorHints, projected[2].PulseGovernance)+ }+}++func assertProviderToolBehaviorHints(t *testing.T, hints *ToolBehaviorHints, readOnly, destructive, idempotent, openWorld bool) {+ t.Helper()+ if hints == nil {+ t.Fatal("provider tool behavior hints missing")+ }+ assertBoolPtr := func(label string, got *bool, want bool) {+ t.Helper()+ if got == nil || *got != want {+ t.Fatalf("%s hint = %v, want %v", label, got, want)+ }+ }+ assertBoolPtr("readOnly", hints.ReadOnlyHint, readOnly)+ assertBoolPtr("destructive", hints.DestructiveHint, destructive)+ assertBoolPtr("idempotent", hints.IdempotentHint, idempotent)+ assertBoolPtr("openWorld", hints.OpenWorldHint, openWorld)+}++func TestProjectAssistantProviderToolsOwnsNativeQuestionToolComposition(t *testing.T) {+ registryTools := []Tool{{+ Name: "pulse_query",+ Description: "Query inventory.",+ }}+ governance := []ToolGovernanceDescriptor{+ NewToolGovernanceDescriptor("pulse_query", "Query inventory.", false, ToolGovernance{+ ActionMode: ActionModeRead,+ ApprovalPolicy: ApprovalPolicyScopeOnly,+ ApprovalSummary: "no approval required",+ Summary: "Read inventory.",+ }),+ }++ interactive := ProjectAssistantProviderTools(registryTools, governance, AssistantProviderToolOptions{+ IncludeQuestionTool: true,+ })+ if len(interactive) != 2 {+ t.Fatalf("interactive Assistant tools length = %d, want 2", len(interactive))+ }+ if interactive[0].Name != "pulse_query" || !strings.Contains(interactive[0].Description, "Pulse governance: mode=read; approval=scope_only (no approval required); Read inventory.") {+ t.Fatalf("registry tool must retain shared governance projection, got %+v", interactive[0])+ }+ if !reflect.DeepEqual(interactive[1], NewPulseQuestionProviderTool()) {+ t.Fatalf("interactive Assistant surface must append shared question tool, got %+v", interactive[1])+ }++ nonInteractive := ProjectAssistantProviderTools(registryTools, governance, AssistantProviderToolOptions{})+ if len(nonInteractive) != 1 || nonInteractive[0].Name != "pulse_query" {+ t.Fatalf("non-interactive Assistant tools must exclude question tool, got %+v", nonInteractive)+ }+}++func TestProjectPulseAssistantProviderToolsUsesSurfaceAffordances(t *testing.T) {+ registryTools := []Tool{{+ Name: PulseQueryToolName,+ Description: "Query inventory.",+ }}+ governance := []ToolGovernanceDescriptor{+ NewToolGovernanceDescriptor(PulseQueryToolName, "Query inventory.", false, ToolGovernance{ActionMode: ActionModeRead}),+ }++ manifest := CanonicalManifest()+ canonical := ProjectPulseAssistantProviderTools(manifest, registryTools, governance, AssistantProviderToolOptions{+ IncludeQuestionTool: true,+ })+ if names := ProviderToolNames(canonical); !reflect.DeepEqual(names, []string{PulseQueryToolName, PulseQuestionToolName}) {+ t.Fatalf("canonical Assistant provider tools = %#v, want registry plus question", names)+ }++ toolsDisabled := manifest+ for i := range toolsDisabled.SurfaceContract.OperatorSurfaces {+ if toolsDisabled.SurfaceContract.OperatorSurfaces[i].ID == SurfaceIDPulseAssistant {+ toolsDisabled.SurfaceContract.OperatorSurfaces[i].Affordances = SurfaceAffordanceContract{InteractiveQuestions: true}+ }+ }+ if got := ProjectPulseAssistantProviderTools(toolsDisabled, registryTools, governance, AssistantProviderToolOptions{IncludeQuestionTool: true}); len(got) != 0 {+ t.Fatalf("tools-disabled Assistant provider tools = %+v, want none", got)+ }++ questionsDisabled := manifest+ for i := range questionsDisabled.SurfaceContract.OperatorSurfaces {+ if questionsDisabled.SurfaceContract.OperatorSurfaces[i].ID == SurfaceIDPulseAssistant {+ questionsDisabled.SurfaceContract.OperatorSurfaces[i].Affordances = SurfaceAffordanceContract{Tools: true}+ }+ }+ nonInteractive := ProjectPulseAssistantProviderTools(questionsDisabled, registryTools, governance, AssistantProviderToolOptions{+ IncludeQuestionTool: true,+ })+ if names := ProviderToolNames(nonInteractive); !reflect.DeepEqual(names, []string{PulseQueryToolName}) {+ t.Fatalf("non-interactive Assistant provider tools = %#v, want registry tools only", names)+ }+}++func TestLegacyAssistantUtilityProviderToolsOwnCompatibilitySchemas(t *testing.T) {+ tools := LegacyAssistantUtilityProviderTools()+ if len(tools) != 3 {+ t.Fatalf("legacy Assistant utility tools = %+v, want three compatibility tools", tools)+ }++ byName := map[string]ProviderTool{}+ for _, tool := range tools {+ byName[tool.Name] = tool+ }++ runCommand := byName[LegacyAssistantRunCommandToolName]+ if !reflect.DeepEqual(runCommand.InputSchema["required"], []string{LegacyAssistantCommandArgumentName}) {+ t.Fatalf("run_command required = %#v, want command", runCommand.InputSchema["required"])+ }+ runProps := runCommand.InputSchema["properties"].(map[string]interface{})+ for _, field := range []string{+ LegacyAssistantCommandArgumentName,+ LegacyAssistantRunOnHostArgumentName,+ LegacyAssistantTargetHostArgumentName,+ } {+ if _, ok := runProps[field]; !ok {+ t.Fatalf("run_command schema missing %q: %#v", field, runProps)+ }+ }++ fetchURL := byName[LegacyAssistantFetchURLToolName]+ if !reflect.DeepEqual(fetchURL.InputSchema["required"], []string{LegacyAssistantURLArgumentName}) {+ t.Fatalf("fetch_url required = %#v, want url", fetchURL.InputSchema["required"])+ }++ setResourceURL := byName[LegacyAssistantSetResourceURLToolName]+ if !reflect.DeepEqual(setResourceURL.InputSchema["required"], []string{LegacyAssistantResourceTypeArgumentName, LegacyAssistantResourceIDArgumentName}) {+ t.Fatalf("set_resource_url required = %#v, want resource_type/resource_id", setResourceURL.InputSchema["required"])+ }+ setProps := setResourceURL.InputSchema["properties"].(map[string]interface{})+ resourceType := setProps[LegacyAssistantResourceTypeArgumentName].(map[string]interface{})+ if !reflect.DeepEqual(resourceType["enum"], []string{"vm", "system-container", "oci-container", "app-container", "agent", "node", "docker-host"}) {+ t.Fatalf("set_resource_url resource_type enum = %#v", resourceType["enum"])+ }+}++func TestProviderToolGovernanceDescriptorsProjectOfferedMetadata(t *testing.T) {+ descriptors, ok := ProviderToolGovernanceDescriptors([]ProviderTool{+ {+ Name: PulseQuestionToolName,+ },+ {+ Name: "pulse_query",+ PulseGovernance: &ToolGovernanceDescriptor{+ Name: "pulse_query",+ Description: "Query inventory.",+ ActionMode: ActionModeRead,+ ApprovalPolicy: ApprovalPolicyScopeOnly,+ Summary: "Inventory read.",+ },+ },+ {+ Name: "pulse_query",+ PulseGovernance: &ToolGovernanceDescriptor{+ Name: "pulse_query",+ ActionMode: ActionModeWrite,+ },+ },+ })+ if !ok {+ t.Fatal("ProviderToolGovernanceDescriptors rejected complete offered metadata")+ }+ if len(descriptors) != 1 {+ t.Fatalf("descriptors length = %d, want one registry descriptor", len(descriptors))+ }+ if descriptors[0].Name != "pulse_query" || descriptors[0].ActionMode != ActionModeRead || descriptors[0].Summary != "Inventory read." {+ t.Fatalf("projected descriptor = %+v, want normalized pulse_query read metadata", descriptors[0])+ }++ descriptors[0].Name = "mutated"+ again, ok := ProviderToolGovernanceDescriptors([]ProviderTool{{+ Name: "pulse_query",+ PulseGovernance: &ToolGovernanceDescriptor{+ Name: "pulse_query",+ ActionMode: ActionModeRead,+ },+ }})+ if !ok || again[0].Name != "pulse_query" {+ t.Fatalf("ProviderToolGovernanceDescriptors must return detached descriptors, got %+v ok=%v", again, ok)+ }+}++func TestProviderToolGovernanceDescriptorsPreserveOfferedToolSemantics(t *testing.T) {+ if descriptors, ok := ProviderToolGovernanceDescriptors(nil); ok || descriptors != nil {+ t.Fatalf("nil offered tools must not claim complete metadata, got %+v ok=%v", descriptors, ok)+ }+ if descriptors, ok := ProviderToolGovernanceDescriptors([]ProviderTool{}); !ok || len(descriptors) != 0 {+ t.Fatalf("empty offered tools must be a valid no-tools manifest, got %+v ok=%v", descriptors, ok)+ }+ if descriptors, ok := ProviderToolGovernanceDescriptors([]ProviderTool{{Name: PulseQuestionToolName}}); !ok || len(descriptors) != 0 {+ t.Fatalf("question-only offered tools must be valid Assistant-native metadata, got %+v ok=%v", descriptors, ok)+ }+ for _, tools := range [][]ProviderTool{+ {{Name: "pulse_query"}},+ {{Name: "pulse_query", PulseGovernance: &ToolGovernanceDescriptor{Name: "pulse_read"}}},+ } {+ if descriptors, ok := ProviderToolGovernanceDescriptors(tools); ok || descriptors != nil {+ t.Fatalf("incomplete offered registry metadata must fall back, got %+v ok=%v", descriptors, ok)+ }+ }+}++func TestAssistantNativeProviderToolNamesUseSharedQuestionTool(t *testing.T) {+ tools := AssistantNativeProviderTools()+ if len(tools) != 1 || tools[0].Name != PulseQuestionToolName {+ t.Fatalf("native Assistant provider tools = %+v, want shared question tool", tools)+ }++ names := AssistantNativeProviderToolNames()+ if !reflect.DeepEqual(names, []string{PulseQuestionToolName}) {+ t.Fatalf("native Assistant provider tool names = %#v, want [%s]", names, PulseQuestionToolName)+ }++ names[0] = "mutated"+ if got := AssistantNativeProviderToolNames(); !reflect.DeepEqual(got, []string{PulseQuestionToolName}) {+ t.Fatalf("native Assistant provider tool names must be detached, got %#v", got)+ }+}++func TestProviderToolNamesPreservesOfferedToolSemantics(t *testing.T) {+ if got := ProviderToolNames(nil); got != nil {+ t.Fatalf("nil tools must preserve nil offered-name semantics, got %#v", got)+ }++ empty := ProviderToolNames([]ProviderTool{})+ if empty == nil || len(empty) != 0 {+ t.Fatalf("empty tools must preserve explicit no-tools semantics, got %#v", empty)+ }++ got := ProviderToolNames([]ProviderTool{+ {Name: " pulse_query "},+ {Name: "pulse_query"},+ {Name: ""},+ {Name: PulseQuestionToolName},+ })+ want := []string{"pulse_query", PulseQuestionToolName}+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("ProviderToolNames = %#v, want %#v", got, want)+ }+}++func TestProviderToolNameCatalogNormalizesExactAndPrefixLookups(t *testing.T) {+ catalog := NewProviderToolNameCatalog(+ []string{" pulse_query ", "pulse_query", "", "pulse_read"},+ []string{"patrol_report_finding"},+ )++ if !reflect.DeepEqual(catalog.Names(), []string{"pulse_query", "pulse_read", "patrol_report_finding"}) {+ t.Fatalf("catalog names = %#v", catalog.Names())+ }+ if !catalog.Has("pulse_query") || !catalog.Has("pulse_read") || !catalog.Has("patrol_report_finding") {+ t.Fatalf("catalog missing expected exact names: %#v", catalog.Names())+ }+ for _, name := range []string{"", " pulse_query ", "PULSE_QUERY", "unknown"} {+ if catalog.Has(name) {+ t.Fatalf("catalog Has(%q) = true, want false", name)+ }+ }+ for _, prefix := range []string{"p", "pulse_", "pulse_q", "patrol_"} {+ if !catalog.HasPrefix(prefix) {+ t.Fatalf("catalog HasPrefix(%q) = false, want true", prefix)+ }+ }+ for _, prefix := range []string{"", "Pulse_", "helper"} {+ if catalog.HasPrefix(prefix) {+ t.Fatalf("catalog HasPrefix(%q) = true, want false", prefix)+ }+ }++ names := catalog.Names()+ names[0] = "mutated"+ if catalog.Has("mutated") || !catalog.Has("pulse_query") {+ t.Fatalf("catalog Names() must return a detached copy, got %#v", catalog.Names())+ }+}++func TestAssistantProviderToolNameCatalogIncludesNativeQuestionTool(t *testing.T) {+ catalog := NewAssistantProviderToolNameCatalog([]string{"pulse_query", PulseQuestionToolName})+ want := []string{"pulse_query", PulseQuestionToolName}+ if !reflect.DeepEqual(catalog.Names(), want) {+ t.Fatalf("assistant provider tool catalog names = %#v, want %#v", catalog.Names(), want)+ }+ if !catalog.Has(PulseQuestionToolName) || !catalog.HasPrefix("pulse_q") {+ t.Fatalf("assistant provider tool catalog must include shared native question tool: %#v", catalog.Names())+ }+}++func TestProviderToolDescriptionWithGovernanceHandlesEmptyDescription(t *testing.T) {+ got := ProviderToolDescriptionWithGovernance("", ToolGovernanceDescriptor{+ Name: "pulse_query",+ ActionMode: ActionModeRead,+ ApprovalPolicy: ApprovalPolicyScopeOnly,+ })++ want := "Pulse governance: mode=read; approval=scope_only"+ if got != want {+ t.Fatalf("ProviderToolDescriptionWithGovernance = %q, want %q", got, want)+ }+}++func TestToolNormalizeCollectionsReturnsIndependentInputSchema(t *testing.T) {+ required := []string{"mode"}+ enum := []string{"summary", "detail"}+ defaultValue := map[string]interface{}{+ "filters": []interface{}{"active"},+ }+ properties := map[string]PropertySchema{+ "mode": {+ Type: "string",+ Enum: enum,+ Default: defaultValue,+ },+ }++ normalized := (Tool{+ Name: "pulse_query",+ InputSchema: InputSchema{+ Properties: properties,+ Required: required,+ },+ }).NormalizeCollections()++ if normalized.InputSchema.Type != "object" {+ t.Fatalf("normalized schema type = %q, want object", normalized.InputSchema.Type)+ }+ if normalized.InputSchema.Properties == nil {+ t.Fatal("normalized schema properties must be an initialized object")+ }++ normalized.InputSchema.Required[0] = "changed"+ mode := normalized.InputSchema.Properties["mode"]+ mode.Enum[0] = "changed"+ mode.Default.(map[string]interface{})["filters"].([]interface{})[0] = "changed"+ normalized.InputSchema.Properties["mode"] = mode++ if required[0] != "mode" {+ t.Fatalf("source required was mutated to %q", required[0])+ }+ if enum[0] != "summary" {+ t.Fatalf("source enum was mutated to %q", enum[0])+ }+ if defaultValue["filters"].([]interface{})[0] != "active" {+ t.Fatalf("source default was mutated to %#v", defaultValue)+ }+ if properties["mode"].Enum[0] != "summary" {+ t.Fatalf("source property enum was mutated to %q", properties["mode"].Enum[0])+ }+}++func TestProviderToolNormalizeCollectionsKeepsInputSchemaObject(t *testing.T) {+ tool := EmptyProviderTool()+ if tool.InputSchema == nil {+ t.Fatal("EmptyProviderTool must initialize input_schema")+ }+ if len(tool.InputSchema) != 0 {+ t.Fatalf("EmptyProviderTool input_schema = %#v, want empty object", tool.InputSchema)+ }++ normalized := (ProviderTool{Name: "diagnose"}).NormalizeCollections()+ if normalized.InputSchema == nil {+ t.Fatal("NormalizeCollections must initialize input_schema")+ }++ inputSchema := map[string]interface{}{+ "properties": map[string]interface{}{+ "mode": map[string]interface{}{+ "enum": []interface{}{"summary", "detail"},+ },+ },+ }+ normalized = (ProviderTool{Name: "diagnose", InputSchema: inputSchema}).NormalizeCollections()+ properties := normalized.InputSchema["properties"].(map[string]interface{})+ mode := properties["mode"].(map[string]interface{})+ mode["enum"].([]interface{})[0] = "changed"+ if inputSchema["properties"].(map[string]interface{})["mode"].(map[string]interface{})["enum"].([]interface{})[0] != "summary" {+ t.Fatalf("NormalizeCollections must not alias provider input_schema: source=%#v normalized=%#v", inputSchema, normalized.InputSchema)+ }++ readOnly := true+ sourceGovernance := &ToolGovernanceDescriptor{+ Name: "pulse_query",+ ActionMode: ActionModeRead,+ }+ withMetadata := ProviderTool{+ Name: "pulse_query",+ BehaviorHints: &ToolBehaviorHints{+ ReadOnlyHint: &readOnly,+ },+ PulseGovernance: sourceGovernance,+ }.NormalizeCollections()+ *withMetadata.BehaviorHints.ReadOnlyHint = false+ withMetadata.PulseGovernance.Name = "mutated"+ if !readOnly {+ t.Fatal("NormalizeCollections must detach provider behavior hints")+ }+ if sourceGovernance.Name != "pulse_query" {+ t.Fatalf("NormalizeCollections must detach provider governance metadata, source name = %q", sourceGovernance.Name)+ }+}++func TestNewPulseQuestionProviderToolBuildsSharedAssistantTool(t *testing.T) {+ tool := NewPulseQuestionProviderTool()++ if tool.Name != PulseQuestionToolName {+ t.Fatalf("question provider tool name = %q, want %q", tool.Name, PulseQuestionToolName)+ }+ if !strings.Contains(tool.Description, "Ask the user for missing information") {+ t.Fatalf("question provider tool description = %q", tool.Description)+ }+ if tool.InputSchema["type"] != "object" {+ t.Fatalf("question provider input_schema type = %v, want object", tool.InputSchema["type"])+ }+ properties := tool.InputSchema["properties"].(map[string]interface{})+ questions := properties["questions"].(map[string]interface{})+ if questions["type"] != "array" {+ t.Fatalf("questions schema type = %v, want array", questions["type"])+ }+ items := questions["items"].(map[string]interface{})+ itemProperties := items["properties"].(map[string]interface{})+ if itemProperties["question"].(map[string]interface{})["type"] != "string" {+ t.Fatalf("question field schema = %#v", itemProperties["question"])+ }+ typeField := itemProperties["type"].(map[string]interface{})+ if !reflect.DeepEqual(typeField["enum"], PulseQuestionToolTypeValues()) {+ t.Fatalf("question type enum = %#v, want text/select", typeField["enum"])+ }+ if !reflect.DeepEqual(items["required"], []string{"id", "question"}) {+ t.Fatalf("question item required = %#v, want id/question", items["required"])+ }+ if !reflect.DeepEqual(tool.InputSchema["required"], []string{"questions"}) {+ t.Fatalf("question tool required = %#v, want questions", tool.InputSchema["required"])+ }+}++func TestNormalizePulseQuestionToolTypeUsesSharedDefaults(t *testing.T) {+ tests := []struct {+ name string+ rawType string+ hasOptions bool+ want PulseQuestionToolType+ wantErr string+ }{+ {name: "empty without options defaults to text", want: PulseQuestionToolTypeText},+ {name: "empty with options defaults to select", hasOptions: true, want: PulseQuestionToolTypeSelect},+ {name: "explicit text trims and lowercases", rawType: " TEXT ", want: PulseQuestionToolTypeText},+ {name: "explicit select with options", rawType: "select", hasOptions: true, want: PulseQuestionToolTypeSelect},+ {name: "explicit select requires options", rawType: "select", wantErr: "select questions must include options"},+ {name: "unknown type rejected", rawType: "binary", wantErr: "question.type must be 'text' or 'select'"},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got, err := NormalizePulseQuestionToolType(tt.rawType, tt.hasOptions)+ if tt.wantErr != "" {+ if err == nil || err.Error() != tt.wantErr {+ t.Fatalf("NormalizePulseQuestionToolType error = %v, want %q", err, tt.wantErr)+ }+ return+ }+ if err != nil {+ t.Fatalf("NormalizePulseQuestionToolType returned error: %v", err)+ }+ if got != tt.want {+ t.Fatalf("NormalizePulseQuestionToolType = %q, want %q", got, tt.want)+ }+ })+ }+}++func TestPulseQuestionProviderInputSchemaReturnsIndependentSchema(t *testing.T) {+ first := PulseQuestionProviderInputSchema()+ second := PulseQuestionProviderInputSchema()++ firstProperties := first["properties"].(map[string]interface{})+ firstQuestions := firstProperties["questions"].(map[string]interface{})+ firstQuestions["type"] = "changed"++ secondProperties := second["properties"].(map[string]interface{})+ secondQuestions := secondProperties["questions"].(map[string]interface{})+ if secondQuestions["type"] != "array" {+ t.Fatalf("question schema mutation leaked across calls: %#v", secondQuestions)+ }+}++func TestProviderToolCallNormalizeCollectionsKeepsInputObject(t *testing.T) {+ toolCall := EmptyProviderToolCall()+ if toolCall.Input == nil {+ t.Fatal("EmptyProviderToolCall must initialize input")+ }+ if len(toolCall.Input) != 0 {+ t.Fatalf("EmptyProviderToolCall input = %#v, want empty object", toolCall.Input)+ }++ normalized := (ProviderToolCall{Name: "diagnose"}).NormalizeCollections()+ if normalized.Input == nil {+ t.Fatal("NormalizeCollections must initialize input")+ }++ input := map[string]interface{}{"resource_id": "vm/100"}+ normalized = (ProviderToolCall{Name: "diagnose", Input: input}).NormalizeCollections()+ normalized.Input["resource_id"] = "vm/101"+ if input["resource_id"] != "vm/100" {+ t.Fatalf("NormalizeCollections must not alias provider input: source=%#v normalized=%#v", input, normalized.Input)+ }++ signature := json.RawMessage(`{"provider":"gemini"}`)+ normalized = (ProviderToolCall{+ Name: "diagnose",+ ThoughtSignature: signature,+ }).NormalizeCollections()+ normalized.ThoughtSignature[0] = '['+ if string(signature) != `{"provider":"gemini"}` {+ t.Fatalf("NormalizeCollections must not alias provider thought signature: source=%s normalized=%s", signature, normalized.ThoughtSignature)+ }+}++func TestProjectProviderToolCallToToolCallNormalizesNameAndInput(t *testing.T) {+ input := map[string]interface{}{+ "resource_id": "vm/100",+ "body": map[string]any{+ "note": "maintenance",+ "tags": []any{"planned"},+ },+ }+ projected := ProjectProviderToolCallToToolCall(ProviderToolCall{+ ID: "call-1",+ Name: " pulse_read ",+ Input: input,+ })++ if projected.Name != "pulse_read" {+ t.Fatalf("projected name = %q, want pulse_read", projected.Name)+ }+ if !reflect.DeepEqual(projected.Arguments, input) {+ t.Fatalf("projected arguments = %#v, want %#v", projected.Arguments, input)+ }+ projected.Arguments["resource_id"] = "vm/101"+ if input["resource_id"] != "vm/100" {+ t.Fatalf("projected arguments must not alias provider input: source=%#v projected=%#v", input, projected.Arguments)+ }+ projectedBody := projected.Arguments["body"].(map[string]any)+ projectedBody["note"] = "changed"+ projectedBody["tags"].([]any)[0] = "changed"+ inputBody := input["body"].(map[string]any)+ if inputBody["note"] != "maintenance" || inputBody["tags"].([]any)[0] != "planned" {+ t.Fatalf("projected nested arguments must not alias provider input: source=%#v projected=%#v", input, projected.Arguments)+ }++ empty := ProjectProviderToolCallToToolCall(ProviderToolCall{Name: "pulse_read"})+ if empty.Arguments == nil || len(empty.Arguments) != 0 {+ t.Fatalf("nil provider input must normalize to empty arguments: %#v", empty.Arguments)+ }+}++func TestNormalizeProviderToolCallForExecutionUsesSharedToolsCallProjection(t *testing.T) {+ input := map[string]interface{}{+ "resource_id": "vm/100",+ "body": map[string]any{+ "note": "maintenance",+ "tags": []any{"planned"},+ },+ }+ signature := json.RawMessage(`{"provider":"gemini"}`)+ normalized := NormalizeProviderToolCallForExecution(ProviderToolCall{+ ID: "call-1",+ Name: " pulse_read ",+ Input: input,+ ThoughtSignature: signature,+ })++ if normalized.ID != "call-1" {+ t.Fatalf("normalized id = %q, want call-1", normalized.ID)+ }+ if normalized.Name != "pulse_read" {+ t.Fatalf("normalized name = %q, want pulse_read", normalized.Name)+ }+ if !reflect.DeepEqual(normalized.Input, input) {+ t.Fatalf("normalized input = %#v, want %#v", normalized.Input, input)+ }+ if string(normalized.ThoughtSignature) != `{"provider":"gemini"}` {+ t.Fatalf("normalized thought signature = %s", normalized.ThoughtSignature)+ }++ normalized.Input["resource_id"] = "vm/101"+ if input["resource_id"] != "vm/100" {+ t.Fatalf("normalized input must not alias provider input: source=%#v normalized=%#v", input, normalized.Input)+ }+ normalizedBody := normalized.Input["body"].(map[string]any)+ normalizedBody["note"] = "changed"+ normalizedBody["tags"].([]any)[0] = "changed"+ inputBody := input["body"].(map[string]any)+ if inputBody["note"] != "maintenance" || inputBody["tags"].([]any)[0] != "planned" {+ t.Fatalf("normalized nested input must not alias provider input: source=%#v normalized=%#v", input, normalized.Input)+ }+ normalized.ThoughtSignature[0] = '['+ if string(signature) != `{"provider":"gemini"}` {+ t.Fatalf("normalized thought signature must not alias source: source=%s normalized=%s", signature, normalized.ThoughtSignature)+ }++ calls := NormalizeProviderToolCallsForExecution([]ProviderToolCall{+ {Name: " first ", Input: nil},+ {Name: " second ", Input: map[string]interface{}{"value": "ok"}},+ })+ if len(calls) != 2 || calls[0].Name != "first" || calls[1].Name != "second" {+ t.Fatalf("normalized calls = %+v", calls)+ }+ if calls[0].Input == nil || len(calls[0].Input) != 0 {+ t.Fatalf("nil provider input must normalize to empty input: %#v", calls[0].Input)+ }+}++func TestProviderToolInputParsingOwnsStreamAndFinalFallbacks(t *testing.T) {+ parsed, ok := ParseProviderToolInput(`{"resource_id":"vm/100","count":2}`)+ if !ok {+ t.Fatal("ParseProviderToolInput rejected complete JSON object")+ }+ if parsed["resource_id"] != "vm/100" || parsed["count"] != float64(2) {+ t.Fatalf("parsed input = %#v", parsed)+ }++ for _, raw := range []string{"", " ", `{"resource_id"`, `null`, `[]`} {+ if parsed, ok := ParseProviderToolInput(raw); ok || parsed != nil {+ t.Fatalf("ParseProviderToolInput(%q) = %#v, %v; want nil,false", raw, parsed, ok)+ }+ fallback := ProviderToolInputOrRaw(raw)+ if fallback["raw"] != raw {+ t.Fatalf("ProviderToolInputOrRaw(%q) = %#v, want raw fallback", raw, fallback)+ }+ }++ final := ProviderToolInputOrRaw(`{"host":"nas01"}`)+ if final["host"] != "nas01" {+ t.Fatalf("ProviderToolInputOrRaw parsed complete JSON as %#v", final)+ }+}++func TestProviderToolResultShape(t *testing.T) {+ payload, err := json.Marshal(ProviderToolResult{+ ToolUseID: "call-1",+ Content: "done",+ IsError: true,+ })+ if err != nil {+ t.Fatalf("marshal provider tool result: %v", err)+ }+ if string(payload) != `{"tool_use_id":"call-1","content":"done","is_error":true}` {+ t.Fatalf("provider tool result JSON = %s", payload)+ }+}++func TestProviderToolResultContextProjectionPreservesTranscriptAndTruncatesModel(t *testing.T) {+ content := strings.Repeat("a", 12)+ projection := NewProviderToolResultContextProjection("call-1", content, false, ProviderToolResultContextOptions{+ MaxModelContentChars: 5,+ })++ if projection.Transcript.ToolUseID != "call-1" || projection.Transcript.Content != content || projection.Transcript.IsError {+ t.Fatalf("transcript result = %+v", projection.Transcript)+ }+ if projection.Model.ToolUseID != "call-1" || projection.Model.IsError {+ t.Fatalf("model result metadata = %+v", projection.Model)+ }+ if !strings.HasPrefix(projection.Model.Content, "aaaaa\n\n---\n[TRUNCATED: 7 characters cut.") {+ t.Fatalf("model content = %q, want shared truncation notice", projection.Model.Content)+ }+ if !projection.Truncation.Applied || projection.Truncation.OriginalChars != 12 || projection.Truncation.MaxChars != 5 || projection.Truncation.TruncatedChars != 7 {+ t.Fatalf("truncation = %+v", projection.Truncation)+ }++ unlimited := NewProviderToolResultContextProjection("call-2", content, true, ProviderToolResultContextOptions{})+ if unlimited.Transcript.Content != content || unlimited.Model.Content != content || !unlimited.Model.IsError || unlimited.Truncation.Applied {+ t.Fatalf("unlimited projection = %+v", unlimited)+ }+}++func TestProviderToolResultContextProjectionFromToolResultUsesSharedInterpretation(t *testing.T) {+ projection := NewProviderToolResultContextProjectionFromToolResult("call-1", ToolResult{+ Content: []ToolContent{+ NewToolTextContent("first"),+ {Type: "resource", URI: "file://ignored"},+ NewToolTextContent("second"),+ },+ IsError: true,+ }, ProviderToolResultContextOptions{MaxModelContentChars: 8})++ if projection.Transcript.Content != "first\nsecond" || !projection.Transcript.IsError {+ t.Fatalf("transcript result = %+v", projection.Transcript)+ }+ if !strings.HasPrefix(projection.Model.Content, "first\nse\n\n---\n[TRUNCATED: 4 characters cut.") || !projection.Model.IsError {+ t.Fatalf("model result = %+v", projection.Model)+ }+}++func TestProviderInputSchemaIncludesEmptyPropertiesObject(t *testing.T) {+ projected := ProviderInputSchema(InputSchema{})+ if projected["type"] != "object" {+ t.Fatalf("projected type = %v, want object", projected["type"])+ }++ props, ok := projected["properties"].(map[string]interface{})+ if !ok {+ t.Fatalf("projected properties type = %T, want map[string]interface{}", projected["properties"])+ }+ if len(props) != 0 {+ t.Fatalf("projected properties length = %d, want 0", len(props))+ }+ if _, ok := projected["required"]; ok {+ t.Fatalf("projected required present for empty schema: %#v", projected["required"])+ }+}++func TestProviderInputSchemaFromRawPreservesManifestOptionality(t *testing.T) {+ raw := StrictObjectInputSchema([]string{FindingIDArgumentName}, map[string]any{+ FindingIDArgumentName: map[string]any{"type": "string"},+ ResolutionNoteArgumentName: map[string]any{"type": "string"},+ })++ projected := ProviderInputSchemaFromRaw(raw)+ props, ok := projected["properties"].(map[string]interface{})+ if !ok {+ t.Fatalf("projected properties type = %T, want map[string]interface{}", projected["properties"])+ }+ if _, ok := props[ResolutionNoteArgumentName]; !ok {+ t.Fatalf("projected properties missing %q: %#v", ResolutionNoteArgumentName, props)+ }+ required, ok := projected["required"].([]string)+ if !ok {+ t.Fatalf("projected required type = %T, want []string", projected["required"])+ }+ if !containsString(required, FindingIDArgumentName) {+ t.Fatalf("projected required = %v, want %q", required, FindingIDArgumentName)+ }+ if containsString(required, ResolutionNoteArgumentName) {+ t.Fatalf("projected required = %v, %q must remain optional", required, ResolutionNoteArgumentName)+ }++ required[0] = "changed"+ props[ResolutionNoteArgumentName] = map[string]interface{}{"type": "integer"}+ second := ProviderInputSchemaFromRaw(raw)+ secondRequired := second["required"].([]string)+ secondProps := second["properties"].(map[string]interface{})+ if !containsString(secondRequired, FindingIDArgumentName) {+ t.Fatalf("ProviderInputSchemaFromRaw returned aliased required slice: %v", secondRequired)+ }+ resolutionNote := secondProps[ResolutionNoteArgumentName].(map[string]interface{})+ if resolutionNote["type"] != "string" {+ t.Fatalf("ProviderInputSchemaFromRaw returned aliased properties: %#v", resolutionNote)+ }+}++func TestProviderInputSchemaReturnsIndependentSchemaValues(t *testing.T) {+ defaultValue := map[string]interface{}{+ "filters": []interface{}{"active"},+ }+ schema := InputSchema{+ Properties: map[string]PropertySchema{+ "mode": {Type: "string", Enum: []string{"summary", "detail"}, Default: defaultValue},+ },+ Required: []string{"mode"},+ }++ projected := ProviderInputSchema(schema)+ projected["required"].([]string)[0] = "changed"+ props := projected["properties"].(map[string]interface{})+ mode := props["mode"].(map[string]interface{})+ mode["enum"].([]string)[0] = "changed"+ mode["default"].(map[string]interface{})["filters"].([]interface{})[0] = "changed"++ if schema.Required[0] != "mode" {+ t.Fatalf("source required was mutated to %q", schema.Required[0])+ }+ if schema.Properties["mode"].Enum[0] != "summary" {+ t.Fatalf("source enum was mutated to %q", schema.Properties["mode"].Enum[0])+ }+ if defaultValue["filters"].([]interface{})[0] != "active" {+ t.Fatalf("source default was mutated to %#v", defaultValue)+ }+}++func TestProviderPropertySchemaReturnsIndependentDefault(t *testing.T) {+ defaultValue := map[string]interface{}{+ "labels": []interface{}{"prod"},+ }++ projected := ProviderPropertySchema(PropertySchema{+ Type: "object",+ Default: defaultValue,+ })+ projectedDefault := projected["default"].(map[string]interface{})+ projectedDefault["labels"].([]interface{})[0] = "changed"++ if defaultValue["labels"].([]interface{})[0] != "prod" {+ t.Fatalf("provider property default aliased source: source=%#v projected=%#v", defaultValue, projected)+ }+}diff --git a/internal/agentcapabilities/scopes.go b/internal/agentcapabilities/scopes.gonew file mode 100644index 0000000000..db72a6f0f0--- /dev/null+++ b/internal/agentcapabilities/scopes.go@@ -0,0 +1,78 @@+package agentcapabilities++import (+ "strings"++ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"+)++// NormalizeRequiredScopes returns the unique non-empty scopes ordered by the+// canonical auth vocabulary and then by input order for future scopes that have+// not yet landed in auth.AllKnownScopes.+func NormalizeRequiredScopes(scopes []string) []string {+ seen := make(map[string]bool)+ for _, raw := range scopes {+ scope := strings.TrimSpace(raw)+ if scope == "" {+ continue+ }+ seen[scope] = true+ }+ if len(seen) == 0 {+ return nil+ }++ ordered := make([]string, 0, len(seen))+ for _, scope := range auth.AllKnownScopes {+ if !seen[scope] {+ continue+ }+ ordered = append(ordered, scope)+ delete(seen, scope)+ }+ for _, raw := range scopes {+ scope := strings.TrimSpace(raw)+ if !seen[scope] {+ continue+ }+ ordered = append(ordered, scope)+ delete(seen, scope)+ }+ return ordered+}++// RequiredCapabilityScopes returns the unique non-empty scopes declared by a+// capability set, ordered by the canonical auth vocabulary and then by manifest+// order for any future scope that has not yet landed in auth.AllKnownScopes.+func RequiredCapabilityScopes(capabilities []Capability) []string {+ scopes := make([]string, 0, len(capabilities))+ for _, cap := range capabilities {+ scopes = append(scopes, cap.Scope)+ }+ return NormalizeRequiredScopes(scopes)+}++// RequiredScopeList formats a manifest-owned required-scope set for operator+// guidance and adapter startup errors.+func RequiredScopeList(scopes []string) string {+ return strings.Join(NormalizeRequiredScopes(scopes), ", ")+}++// RequiredCapabilityScopeList formats RequiredCapabilityScopes for operator+// guidance and adapter startup errors.+func RequiredCapabilityScopeList(capabilities []Capability) string {+ return RequiredScopeList(RequiredCapabilityScopes(capabilities))+}++// ManifestRequiredScopeList formats the manifest-owned requiredScopes summary.+// Older manifests did not expose requiredScopes, so callers get a compatibility+// fallback from the capability rows while current manifests stay field-owned.+func ManifestRequiredScopeList(manifest *Manifest) string {+ if manifest == nil {+ return ""+ }+ if scopeList := RequiredScopeList(manifest.RequiredScopes); scopeList != "" {+ return scopeList+ }+ return RequiredCapabilityScopeList(manifest.Capabilities)+}diff --git a/internal/agentcapabilities/scopes_test.go b/internal/agentcapabilities/scopes_test.gonew file mode 100644index 0000000000..f6a9a54f91--- /dev/null+++ b/internal/agentcapabilities/scopes_test.go@@ -0,0 +1,100 @@+package agentcapabilities++import (+ "reflect"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"+)++func TestRequiredCapabilityScopesUseAuthOrderAndDeduplicate(t *testing.T) {+ capabilities := []Capability{+ {Name: "settings_write", Scope: auth.ScopeSettingsWrite},+ {Name: "monitoring_read", Scope: auth.ScopeMonitoringRead},+ {Name: "empty_scope"},+ {Name: "monitoring_write", Scope: auth.ScopeMonitoringWrite},+ {Name: "unknown_one", Scope: "custom:alpha"},+ {Name: "duplicate_monitoring_read", Scope: " " + auth.ScopeMonitoringRead + " "},+ {Name: "ai_execute", Scope: auth.ScopeAIExecute},+ {Name: "unknown_two", Scope: "custom:beta"},+ }++ got := RequiredCapabilityScopes(capabilities)+ want := []string{+ auth.ScopeMonitoringRead,+ auth.ScopeMonitoringWrite,+ auth.ScopeSettingsWrite,+ auth.ScopeAIExecute,+ "custom:alpha",+ "custom:beta",+ }+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("RequiredCapabilityScopes = %v, want %v", got, want)+ }+}++func TestNormalizeRequiredScopesUseAuthOrderAndDeduplicate(t *testing.T) {+ got := NormalizeRequiredScopes([]string{+ auth.ScopeSettingsWrite,+ auth.ScopeMonitoringRead,+ "",+ " " + auth.ScopeMonitoringRead + " ",+ "custom:alpha",+ auth.ScopeAIExecute,+ "custom:alpha",+ "custom:beta",+ })+ want := []string{+ auth.ScopeMonitoringRead,+ auth.ScopeSettingsWrite,+ auth.ScopeAIExecute,+ "custom:alpha",+ "custom:beta",+ }+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("NormalizeRequiredScopes = %v, want %v", got, want)+ }+}++func TestRequiredCapabilityScopeListReflectsCanonicalManifest(t *testing.T) {+ got := RequiredCapabilityScopeList(CanonicalManifest().Capabilities)+ want := "monitoring:read, monitoring:write, settings:read, settings:write, ai:execute"+ if got != want {+ t.Fatalf("RequiredCapabilityScopeList(CanonicalManifest) = %q, want %q", got, want)+ }+}++func TestManifestRequiredScopeListPrefersManifestRequiredScopes(t *testing.T) {+ manifest := &Manifest{+ RequiredScopes: []string{+ auth.ScopeSettingsWrite,+ auth.ScopeMonitoringRead,+ auth.ScopeMonitoringRead,+ auth.ScopeAIExecute,+ },+ Capabilities: []Capability{+ {Name: "legacy_extra", Scope: auth.ScopeMonitoringWrite},+ },+ }++ got := ManifestRequiredScopeList(manifest)+ want := "monitoring:read, settings:write, ai:execute"+ if got != want {+ t.Fatalf("ManifestRequiredScopeList = %q, want %q", got, want)+ }+}++func TestManifestRequiredScopeListFallsBackToCapabilitiesForLegacyManifest(t *testing.T) {+ manifest := &Manifest{+ Capabilities: []Capability{+ {Name: "settings_write", Scope: auth.ScopeSettingsWrite},+ {Name: "monitoring_read", Scope: auth.ScopeMonitoringRead},+ },+ }++ got := ManifestRequiredScopeList(manifest)+ want := "monitoring:read, settings:write"+ if got != want {+ t.Fatalf("ManifestRequiredScopeList legacy fallback = %q, want %q", got, want)+ }+}diff --git a/internal/agentcapabilities/sse.go b/internal/agentcapabilities/sse.gonew file mode 100644index 0000000000..b594edfc00--- /dev/null+++ b/internal/agentcapabilities/sse.go@@ -0,0 +1,149 @@+package agentcapabilities++import (+ "bufio"+ "context"+ "fmt"+ "io"+ "net/http"+ "strings"+)++const AgentSSEAccept = "text/event-stream"++// SSERecord is one parsed Server-Sent Events record from the Pulse+// Intelligence event stream.+type SSERecord struct {+ Event string+ Data string+}++// MCPEventNotificationWriter writes one JSON-RPC notification projected from a+// Pulse Intelligence SSE record.+type MCPEventNotificationWriter func(JSONRPCRequest) error++// ScanSSERecords parses SSE records from reader and calls handle once per+// completed record. Returning false from handle stops the scan cleanly.+func ScanSSERecords(reader io.Reader, handle func(SSERecord) bool) error {+ scanner := bufio.NewScanner(reader)+ scanner.Buffer(make([]byte, 64*1024), 1<<22)++ var event string+ var dataLines []string+ dispatch := func() bool {+ if event == "" && len(dataLines) == 0 {+ return true+ }+ record := SSERecord{+ Event: event,+ Data: strings.Join(dataLines, "\n"),+ }+ event = ""+ dataLines = nil+ if handle == nil {+ return true+ }+ return handle(record)+ }++ for scanner.Scan() {+ line := strings.TrimSuffix(scanner.Text(), "\r")+ if line == "" {+ if !dispatch() {+ return nil+ }+ continue+ }+ if strings.HasPrefix(line, ":") {+ continue+ }++ field, value, hasValue := strings.Cut(line, ":")+ if !hasValue {+ value = ""+ } else {+ value = strings.TrimPrefix(value, " ")+ }+ switch field {+ case "event":+ event = value+ case "data":+ dataLines = append(dataLines, value)+ }+ }+ if err := scanner.Err(); err != nil {+ return err+ }+ dispatch()+ return nil+}++// StreamAgentSSERecords opens an authenticated Pulse Intelligence SSE stream+// and scans records through the shared parser. Callers still own connection+// lifetime, retry policy, and product-specific event handling.+func StreamAgentSSERecords(ctx context.Context, client HTTPDoer, baseURL, path, token string, handle func(SSERecord) bool) error {+ req, err := NewAgentHTTPRequest(ctx, http.MethodGet, baseURL, path, token, nil)+ if err != nil {+ return err+ }+ req.Header.Set("Accept", AgentSSEAccept)+ resp, err := httpClient(client).Do(req)+ if err != nil {+ return err+ }+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ return fmt.Errorf("subscribe: status %d", resp.StatusCode)+ }+ return ScanSSERecords(resp.Body, handle)+}++// IsActionableSSERecord reports whether a parsed Pulse Intelligence SSE record+// represents a product event an external agent should handle. Empty records and+// transport keepalives stay inside the shared substrate.+func IsActionableSSERecord(record SSERecord) bool {+ return record.Event != "" && record.Data != "" && !IsTransportEventKind(record.Event)+}++// StreamAgentActionableSSERecords opens an authenticated Pulse Intelligence SSE+// stream and only forwards actionable product records to handle. Reference+// clients use this when they need raw event/data records without owning+// transport-event filtering.+func StreamAgentActionableSSERecords(ctx context.Context, client HTTPDoer, baseURL, path, token string, handle func(SSERecord) bool) error {+ return StreamAgentSSERecords(ctx, client, baseURL, path, token, func(record SSERecord) bool {+ if !IsActionableSSERecord(record) {+ return true+ }+ if handle == nil {+ return true+ }+ return handle(record)+ })+}++// StreamMCPEventNotifications opens an authenticated Pulse Intelligence SSE+// stream and projects actionable product events into MCP JSON-RPC+// notifications. Transport keepalives and empty records stay filtered at the+// shared core boundary so adapters do not each carry their own event vocabulary+// or notification projection rules.+func StreamMCPEventNotifications(ctx context.Context, client HTTPDoer, baseURL, path, token string, write MCPEventNotificationWriter) error {+ var writeErr error+ err := StreamAgentActionableSSERecords(ctx, client, baseURL, path, token, func(record SSERecord) bool {+ notification, ok := NewMCPEventNotification(record.Event, []byte(record.Data))+ if !ok {+ return true+ }+ if write == nil {+ return true+ }+ if err := write(notification); err != nil {+ writeErr = err+ return false+ }+ return true+ })+ if writeErr != nil {+ return writeErr+ }+ return err+}diff --git a/internal/agentcapabilities/sse_test.go b/internal/agentcapabilities/sse_test.gonew file mode 100644index 0000000000..8995a607c3--- /dev/null+++ b/internal/agentcapabilities/sse_test.go@@ -0,0 +1,244 @@+package agentcapabilities++import (+ "context"+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func TestScanSSERecordsParsesCanonicalRecords(t *testing.T) {+ input := strings.Join([]string{+ ": connected comment",+ "event: stream.connected",+ "data: {}",+ "",+ "event: finding.created",+ "data: {\"findingId\":\"f1\"}",+ "data: {\"severity\":\"critical\"}",+ "",+ }, "\r\n")++ var got []SSERecord+ if err := ScanSSERecords(strings.NewReader(input), func(record SSERecord) bool {+ got = append(got, record)+ return true+ }); err != nil {+ t.Fatalf("ScanSSERecords: %v", err)+ }++ if len(got) != 2 {+ t.Fatalf("records len = %d, want 2: %+v", len(got), got)+ }+ if got[0] != (SSERecord{Event: "stream.connected", Data: "{}"}) {+ t.Fatalf("first record = %+v", got[0])+ }+ wantData := "{\"findingId\":\"f1\"}\n{\"severity\":\"critical\"}"+ if got[1] != (SSERecord{Event: "finding.created", Data: wantData}) {+ t.Fatalf("second record = %+v, want data %q", got[1], wantData)+ }+}++func TestScanSSERecordsStopsWhenHandlerReturnsFalse(t *testing.T) {+ input := "event: finding.created\ndata: {\"findingId\":\"f1\"}\n\nevent: action.completed\ndata: {\"actionId\":\"a1\"}\n\n"+ var got []SSERecord+ if err := ScanSSERecords(strings.NewReader(input), func(record SSERecord) bool {+ got = append(got, record)+ return false+ }); err != nil {+ t.Fatalf("ScanSSERecords: %v", err)+ }+ if len(got) != 1 {+ t.Fatalf("records len = %d, want 1: %+v", len(got), got)+ }+ if got[0].Event != string(EventKindFindingCreated) {+ t.Fatalf("first event = %q, want %q", got[0].Event, EventKindFindingCreated)+ }+}++func TestScanSSERecordsFlushesFinalRecordAtEOF(t *testing.T) {+ input := "event: action.completed\ndata: {\"actionId\":\"a1\"}"+ var got []SSERecord+ if err := ScanSSERecords(strings.NewReader(input), func(record SSERecord) bool {+ got = append(got, record)+ return true+ }); err != nil {+ t.Fatalf("ScanSSERecords: %v", err)+ }+ if len(got) != 1 {+ t.Fatalf("records len = %d, want 1: %+v", len(got), got)+ }+ if got[0] != (SSERecord{Event: string(EventKindActionCompleted), Data: "{\"actionId\":\"a1\"}"}) {+ t.Fatalf("record = %+v", got[0])+ }+}++func TestStreamAgentSSERecordsBuildsCanonicalSubscriptionRequest(t *testing.T) {+ stream := strings.Join([]string{+ "event: " + string(EventKindFindingCreated),+ "data: {\"findingId\":\"f1\"}",+ "",+ "event: " + string(EventKindActionCompleted),+ "data: {\"actionId\":\"a1\"}",+ "",+ }, "\n")++ requests := 0+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ requests+++ if r.Method != http.MethodGet {+ t.Errorf("method = %s, want GET", r.Method)+ }+ if r.URL.Path != AgentEventsPath {+ t.Errorf("path = %s, want %s", r.URL.Path, AgentEventsPath)+ }+ if r.Header.Get(AgentAPITokenHeader) != "test-token" {+ t.Errorf("%s header = %q", AgentAPITokenHeader, r.Header.Get(AgentAPITokenHeader))+ }+ if r.Header.Get("Accept") != AgentSSEAccept {+ t.Errorf("Accept header = %q, want %q", r.Header.Get("Accept"), AgentSSEAccept)+ }+ w.Header().Set("Content-Type", AgentSSEAccept)+ _, _ = w.Write([]byte(stream))+ }))+ defer server.Close()++ var got []SSERecord+ err := StreamAgentSSERecords(context.Background(), server.Client(), server.URL, AgentEventsPath, "test-token", func(record SSERecord) bool {+ got = append(got, record)+ return false+ })+ if err != nil {+ t.Fatalf("StreamAgentSSERecords: %v", err)+ }+ if requests != 1 {+ t.Fatalf("requests = %d, want 1", requests)+ }+ if len(got) != 1 || got[0].Event != string(EventKindFindingCreated) {+ t.Fatalf("got records = %+v, want first finding.created only", got)+ }+}++func TestStreamAgentSSERecordsReturnsStatusError(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusUnauthorized)+ }))+ defer server.Close()++ err := StreamAgentSSERecords(context.Background(), server.Client(), server.URL, AgentEventsPath, "bad-token", nil)+ if err == nil || !strings.Contains(err.Error(), "subscribe: status 401") {+ t.Fatalf("error = %v, want subscribe status error", err)+ }+}++func TestStreamAgentActionableSSERecordsFiltersTransportRecords(t *testing.T) {+ stream := strings.Join([]string{+ ": connected comment",+ "event: " + string(EventKindStreamConnected),+ "data: {}",+ "",+ "event: " + string(EventKindHeartbeat),+ "",+ "data: unnamed payload",+ "",+ "event: " + string(EventKindFindingCreated),+ "data: {\"findingId\":\"f1\"}",+ "",+ }, "\n")+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", AgentSSEAccept)+ _, _ = w.Write([]byte(stream))+ }))+ defer server.Close()++ var got []SSERecord+ err := StreamAgentActionableSSERecords(context.Background(), server.Client(), server.URL, AgentEventsPath, "test-token", func(record SSERecord) bool {+ got = append(got, record)+ return true+ })+ if err != nil {+ t.Fatalf("StreamAgentActionableSSERecords: %v", err)+ }+ if len(got) != 1 {+ t.Fatalf("actionable records len = %d, want 1: %+v", len(got), got)+ }+ if got[0] != (SSERecord{Event: string(EventKindFindingCreated), Data: "{\"findingId\":\"f1\"}"}) {+ t.Fatalf("actionable record = %+v", got[0])+ }+}++func TestStreamMCPEventNotificationsProjectsActionableEvents(t *testing.T) {+ stream := strings.Join([]string{+ ": connected comment",+ "event: " + string(EventKindStreamConnected),+ "data: {}",+ "",+ "event: " + string(EventKindFindingCreated),+ "data: {\"findingId\":\"f1\"}",+ "",+ "event: " + string(EventKindHeartbeat),+ "",+ "event: " + string(EventKindActionCompleted),+ "data: {\"actionId\":\"a1\"}",+ "",+ }, "\n")++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Header.Get(AgentAPITokenHeader) != "test-token" {+ t.Errorf("%s header = %q", AgentAPITokenHeader, r.Header.Get(AgentAPITokenHeader))+ }+ if r.Header.Get("Accept") != AgentSSEAccept {+ t.Errorf("Accept header = %q, want %q", r.Header.Get("Accept"), AgentSSEAccept)+ }+ w.Header().Set("Content-Type", AgentSSEAccept)+ _, _ = w.Write([]byte(stream))+ }))+ defer server.Close()++ var got []JSONRPCRequest+ err := StreamMCPEventNotifications(context.Background(), server.Client(), server.URL, AgentEventsPath, "test-token", func(notification JSONRPCRequest) error {+ got = append(got, notification)+ return nil+ })+ if err != nil {+ t.Fatalf("StreamMCPEventNotifications: %v", err)+ }+ if len(got) != 2 {+ t.Fatalf("notifications len = %d, want finding.created and action.completed: %+v", len(got), got)+ }+ if got[0].Method != MCPNotificationMethod(string(EventKindFindingCreated)) {+ t.Fatalf("first notification method = %q", got[0].Method)+ }+ if got[1].Method != MCPNotificationMethod(string(EventKindActionCompleted)) {+ t.Fatalf("second notification method = %q", got[1].Method)+ }+ if string(got[0].Params) != `{"findingId":"f1"}` {+ t.Fatalf("first notification params = %s", got[0].Params)+ }+ if len(got[0].ID) != 0 || len(got[1].ID) != 0 {+ t.Fatalf("notifications must not carry ids: %+v", got)+ }+}++func TestStreamMCPEventNotificationsReturnsWriterError(t *testing.T) {+ stream := strings.Join([]string{+ "event: " + string(EventKindFindingCreated),+ "data: {\"findingId\":\"f1\"}",+ "",+ }, "\n")+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", AgentSSEAccept)+ _, _ = w.Write([]byte(stream))+ }))+ defer server.Close()++ sentinel := errors.New("write notification")+ err := StreamMCPEventNotifications(context.Background(), server.Client(), server.URL, AgentEventsPath, "test-token", func(notification JSONRPCRequest) error {+ return sentinel+ })+ if !errors.Is(err, sentinel) {+ t.Fatalf("error = %v, want writer error", err)+ }+}diff --git a/internal/agentcapabilities/surface_contract.go b/internal/agentcapabilities/surface_contract.gonew file mode 100644index 0000000000..61b4a64579--- /dev/null+++ b/internal/agentcapabilities/surface_contract.go@@ -0,0 +1,392 @@+package agentcapabilities++import "strings"++const (+ SurfaceIDPulseAssistant = "pulse_assistant"+ SurfaceIDPulseMCP = "pulse_mcp"++ SurfaceToolSourceAssistantRegistry = "assistant_registry"+ SurfaceToolSourceCapabilityManifest = "capability_manifest"+)++// SurfaceToolContract describes the tool vocabulary projected for one+// operator-facing Pulse Intelligence surface. Assistant tools come from the+// native registry/provider-tool projection, while external-adapter tools come+// from the canonical manifest capability projection; keeping the source+// explicit stops supported surfaces from being treated as competing duplicate+// implementations.+type SurfaceToolContract struct {+ SurfaceID string `json:"surfaceId"`+ SurfaceLabel string `json:"surfaceLabel,omitempty"`+ ToolSource string `json:"toolSource"`+ ToolNames []string `json:"toolNames"`+ RegistryToolNames []string `json:"registryToolNames,omitempty"`+ CapabilityNames []string `json:"capabilityNames,omitempty"`+ NativeToolNames []string `json:"nativeToolNames,omitempty"`+ Affordances SurfaceAffordanceContract `json:"affordances,omitempty"`+}++// ResolvedSurfaceAffordanceContract is the normalized surface identity and+// affordance set that prompts, adapters, docs, and UI projections should use+// when they need one surface's supported Pulse Intelligence affordances.+type ResolvedSurfaceAffordanceContract struct {+ SurfaceID string+ SurfaceLabel string+ Affordances SurfaceAffordanceContract+}++// NormalizeCollections detaches slice fields and preserves a stable empty+// toolNames collection for JSON surfaces.+func (c SurfaceToolContract) NormalizeCollections() SurfaceToolContract {+ c.ToolNames = append([]string(nil), c.ToolNames...)+ if c.ToolNames == nil {+ c.ToolNames = []string{}+ }+ c.RegistryToolNames = append([]string(nil), c.RegistryToolNames...)+ c.CapabilityNames = append([]string(nil), c.CapabilityNames...)+ c.NativeToolNames = append([]string(nil), c.NativeToolNames...)+ return c+}++// CloneSurfaceToolContracts returns detached surface tool summaries in their+// original projection order.+func CloneSurfaceToolContracts(contracts []SurfaceToolContract) []SurfaceToolContract {+ cloned := make([]SurfaceToolContract, 0, len(contracts))+ for _, contract := range contracts {+ cloned = append(cloned, contract.NormalizeCollections())+ }+ return cloned+}++// DefaultSurfaceLabelForID returns the compatibility label for known Pulse+// Intelligence surfaces when older manifest payloads omit a surfaceContract+// block.+func DefaultSurfaceLabelForID(surfaceID string) string {+ switch strings.TrimSpace(surfaceID) {+ case SurfaceIDPulseAssistant:+ return "Pulse Assistant"+ case SurfaceIDPulseMCP:+ return "Pulse MCP"+ default:+ return ""+ }+}++// DefaultSurfaceAffordancesForID returns compatibility defaults for known+// Pulse Intelligence surfaces when older manifest payloads do not declare the+// affordance block.+func DefaultSurfaceAffordancesForID(surfaceID string) SurfaceAffordanceContract {+ switch strings.TrimSpace(surfaceID) {+ case SurfaceIDPulseAssistant:+ return SurfaceAffordanceContract{+ Tools: true,+ InteractiveQuestions: true,+ }+ case SurfaceIDPulseMCP:+ return SurfaceAffordanceContract{+ Tools: true,+ Resources: true,+ Prompts: true,+ CapabilityMetadata: true,+ }+ default:+ return SurfaceAffordanceContract{}+ }+}++// SurfaceAffordancesDeclared reports whether any affordance was explicitly+// enabled. It intentionally treats an all-false struct as missing/legacy for+// the known current surfaces, because older JSON payloads had no affordance+// field at all.+func SurfaceAffordancesDeclared(affordances SurfaceAffordanceContract) bool {+ return affordances.Tools ||+ affordances.Resources ||+ affordances.Prompts ||+ affordances.CapabilityMetadata ||+ affordances.InteractiveQuestions+}++// NormalizeSurfaceAffordances fills compatibility defaults for known surfaces+// while preserving explicit manifest-owned affordances when present.+func NormalizeSurfaceAffordances(surface OperatorSurfaceContract) SurfaceAffordanceContract {+ if SurfaceAffordancesDeclared(surface.Affordances) {+ return surface.Affordances+ }+ return DefaultSurfaceAffordancesForID(surface.ID)+}++// ResolveSurfaceAffordanceContract resolves one operator surface from the+// manifest surface contract and applies compatibility defaults for known first-+// party surfaces. The returned bool reports whether the surface was declared in+// the provided contract; callers can still use the returned compatibility+// defaults when false.+func ResolveSurfaceAffordanceContract(contract SurfaceContract, surfaceID, surfaceLabelFallback string) (ResolvedSurfaceAffordanceContract, bool) {+ surfaceID = strings.TrimSpace(surfaceID)+ if surfaceID == "" {+ return ResolvedSurfaceAffordanceContract{}, false+ }++ lookupLabel := strings.TrimSpace(surfaceLabelFallback)+ if lookupLabel == "" {+ lookupLabel = DefaultSurfaceLabelForID(surfaceID)+ }+ label := lookupLabel+ if label == "" {+ label = surfaceID+ }++ if surface, ok := FindOperatorSurfaceContract(contract, surfaceID, lookupLabel); ok {+ resolvedID := strings.TrimSpace(surface.ID)+ if resolvedID == "" {+ resolvedID = surfaceID+ }+ resolvedLabel := strings.TrimSpace(surface.Label)+ if resolvedLabel == "" {+ resolvedLabel = label+ }+ return ResolvedSurfaceAffordanceContract{+ SurfaceID: resolvedID,+ SurfaceLabel: resolvedLabel,+ Affordances: NormalizeSurfaceAffordances(surface),+ }, true+ }++ return ResolvedSurfaceAffordanceContract{+ SurfaceID: surfaceID,+ SurfaceLabel: label,+ Affordances: DefaultSurfaceAffordancesForID(surfaceID),+ }, false+}++// ManifestSurfaceAffordances resolves the affordance contract for one manifest+// surface. Known first-party surfaces retain compatibility defaults for older+// manifests that predate the surfaceContract block.+func ManifestSurfaceAffordances(manifest Manifest, surfaceID string) (SurfaceAffordanceContract, bool) {+ resolution, ok := ResolveSurfaceAffordanceContract(manifest.SurfaceContract, surfaceID, "")+ if SurfaceAffordancesDeclared(resolution.Affordances) {+ return resolution.Affordances, ok+ }+ return SurfaceAffordanceContract{}, false+}++// FindOperatorSurfaceContract resolves one manifest-owned operator surface by+// id or label.+func FindOperatorSurfaceContract(contract SurfaceContract, surfaceID, surfaceName string) (OperatorSurfaceContract, bool) {+ surfaceID = strings.TrimSpace(surfaceID)+ surfaceName = strings.TrimSpace(surfaceName)+ for _, surface := range contract.OperatorSurfaces {+ if OperatorSurfaceContractMatches(surface, surfaceID, surfaceName) {+ return surface, true+ }+ }+ return OperatorSurfaceContract{}, false+}++// OperatorSurfaceContractMatches reports whether a surface matches by stable id+// or display label.+func OperatorSurfaceContractMatches(surface OperatorSurfaceContract, surfaceID, surfaceName string) bool {+ if surfaceID != "" && strings.EqualFold(strings.TrimSpace(surface.ID), surfaceID) {+ return true+ }+ if surfaceName != "" && strings.EqualFold(strings.TrimSpace(surface.Label), surfaceName) {+ return true+ }+ return false+}++// SurfaceAffordanceLabels formats enabled affordances with stable,+// operator-facing labels.+func SurfaceAffordanceLabels(affordances SurfaceAffordanceContract) []string {+ labels := []string{}+ if affordances.Tools {+ labels = append(labels, "tools")+ }+ if affordances.Resources {+ labels = append(labels, "resources")+ }+ if affordances.Prompts {+ labels = append(labels, "prompts")+ }+ if affordances.CapabilityMetadata {+ labels = append(labels, "capability metadata")+ }+ if affordances.InteractiveQuestions {+ labels = append(labels, "interactive questions")+ }+ return labels+}++// ProjectPulseAssistantSurfaceToolContract projects the native Assistant+// provider-tool list into the shared surface summary. Registry-backed tools and+// Assistant-native interaction tools are separated deliberately: pulse_question+// is a native in-app affordance, not an MCP capability.+func ProjectPulseAssistantSurfaceToolContract(contract SurfaceContract, providerTools []ProviderTool) (SurfaceToolContract, bool) {+ surface, ok := ResolveSurfaceAffordanceContract(contract, SurfaceIDPulseAssistant, "")++ toolNames := ProviderToolNames(providerTools)+ if !surface.Affordances.Tools {+ toolNames = []string{}+ }+ nativeCatalog := NewProviderToolNameCatalog(AssistantNativeProviderToolNames())+ registryNames := make([]string, 0, len(toolNames))+ nativeNames := make([]string, 0, len(toolNames))+ offeredNames := make([]string, 0, len(toolNames))+ for _, name := range toolNames {+ if nativeCatalog.Has(name) {+ if !surface.Affordances.InteractiveQuestions {+ continue+ }+ nativeNames = append(nativeNames, name)+ offeredNames = append(offeredNames, name)+ continue+ }+ registryNames = append(registryNames, name)+ offeredNames = append(offeredNames, name)+ }++ return SurfaceToolContract{+ SurfaceID: surface.SurfaceID,+ SurfaceLabel: surface.SurfaceLabel,+ ToolSource: SurfaceToolSourceAssistantRegistry,+ ToolNames: offeredNames,+ RegistryToolNames: registryNames,+ NativeToolNames: nativeNames,+ Affordances: surface.Affordances,+ }.NormalizeCollections(), ok+}++// ProjectManifestSurfaceToolContract normalizes a manifest-published+// request/response tool allowlist into the shared surface summary for a+// manifest-declared external adapter. Streaming capabilities remain represented+// by resources, prompts, or notifications, not request/response tool entries.+func ProjectManifestSurfaceToolContract(manifest Manifest, surfaceID string) (SurfaceToolContract, bool) {+ surfaceID = strings.TrimSpace(surfaceID)+ if surfaceID == "" {+ return SurfaceToolContract{}, false+ }+ surface, ok := FindOperatorSurfaceContract(manifest.SurfaceContract, surfaceID, "")+ if !ok || !surface.ExternalAdapter {+ return SurfaceToolContract{}, false+ }+ if contract, ok := FindManifestSurfaceToolContract(manifest, surface.ID); ok {+ return normalizeManifestSurfaceToolContract(manifest, surface, contract), true+ }+ return SurfaceToolContract{}, false+}++func normalizeManifestSurfaceToolContract(manifest Manifest, surface OperatorSurfaceContract, contract SurfaceToolContract) SurfaceToolContract {+ resolvedSurface, _ := ResolveSurfaceAffordanceContract(manifest.SurfaceContract, surface.ID, surface.Label)+ contract = contract.NormalizeCollections()+ if strings.TrimSpace(contract.SurfaceID) == "" {+ contract.SurfaceID = resolvedSurface.SurfaceID+ }+ if strings.TrimSpace(contract.SurfaceLabel) == "" {+ contract.SurfaceLabel = resolvedSurface.SurfaceLabel+ }+ if strings.TrimSpace(contract.ToolSource) == "" {+ contract.ToolSource = SurfaceToolSourceCapabilityManifest+ }+ if SurfaceAffordancesDeclared(contract.Affordances) {+ contract.Affordances = IntersectSurfaceAffordances(resolvedSurface.Affordances, contract.Affordances)+ } else {+ contract.Affordances = resolvedSurface.Affordances+ }+ if len(contract.ToolNames) == 0 && len(contract.CapabilityNames) > 0 {+ contract.ToolNames = append([]string(nil), contract.CapabilityNames...)+ }+ if contract.Affordances.Tools {+ toolNames := requestResponseCapabilityNamesForNames(manifest.Capabilities, contract.ToolNames)+ contract.ToolNames = toolNames+ contract.CapabilityNames = append([]string(nil), toolNames...)+ } else {+ contract.ToolNames = []string{}+ contract.CapabilityNames = []string{}+ }+ contract.RegistryToolNames = nil+ contract.NativeToolNames = nil+ return contract.NormalizeCollections()+}++// IntersectSurfaceAffordances applies a surface-local narrowing contract without+// allowing that local contract to re-enable an affordance disabled by the+// operator surface.+func IntersectSurfaceAffordances(allowed SurfaceAffordanceContract, requested SurfaceAffordanceContract) SurfaceAffordanceContract {+ return SurfaceAffordanceContract{+ Tools: allowed.Tools && requested.Tools,+ Resources: allowed.Resources && requested.Resources,+ Prompts: allowed.Prompts && requested.Prompts,+ CapabilityMetadata: allowed.CapabilityMetadata && requested.CapabilityMetadata,+ InteractiveQuestions: allowed.InteractiveQuestions && requested.InteractiveQuestions,+ }+}++// ResolveManifestSurfaceToolContract returns the normalized request/response+// surface tool contract for a manifest-backed external-agent surface. Missing+// published surface tool contracts fail closed rather than inferring tools from+// raw manifest capabilities.+func ResolveManifestSurfaceToolContract(manifest Manifest, surfaceID string) (SurfaceToolContract, bool) {+ surfaceID = strings.TrimSpace(surfaceID)+ if surfaceID == "" {+ return SurfaceToolContract{}, false+ }+ return ProjectManifestSurfaceToolContract(manifest, surfaceID)+}++// ProjectManifestSurfaceToolContracts returns manifest-backed external-adapter+// surface tool summaries in manifest operator-surface order. Native Assistant+// tool availability is intentionally omitted because it is runtime-specific.+func ProjectManifestSurfaceToolContracts(manifest Manifest) []SurfaceToolContract {+ contracts := make([]SurfaceToolContract, 0, len(manifest.SurfaceContract.OperatorSurfaces))+ for _, surface := range manifest.SurfaceContract.OperatorSurfaces {+ if !surface.ExternalAdapter || strings.TrimSpace(surface.ID) == "" {+ continue+ }+ if contract, ok := ProjectManifestSurfaceToolContract(manifest, surface.ID); ok {+ contracts = append(contracts, contract)+ }+ }+ return contracts+}++// ProjectPulseIntelligenceSurfaceToolContracts returns the supported+// operator-facing surface tool summaries in manifest order. The function is+// intentionally a projection over the two canonical sources rather than a new+// tool registry.+func ProjectPulseIntelligenceSurfaceToolContracts(manifest Manifest, assistantTools []ProviderTool) []SurfaceToolContract {+ contracts := make([]SurfaceToolContract, 0, len(manifest.SurfaceContract.OperatorSurfaces))+ for _, surface := range manifest.SurfaceContract.OperatorSurfaces {+ switch strings.TrimSpace(surface.ID) {+ case SurfaceIDPulseAssistant:+ contract, _ := ProjectPulseAssistantSurfaceToolContract(manifest.SurfaceContract, assistantTools)+ contracts = append(contracts, contract)+ default:+ if surface.ExternalAdapter && strings.TrimSpace(surface.ID) != "" {+ if contract, ok := ProjectManifestSurfaceToolContract(manifest, surface.ID); ok {+ contracts = append(contracts, contract)+ }+ }+ }+ }+ return contracts+}++func requestResponseCapabilityNamesForNames(capabilities []Capability, names []string) []string {+ result := make([]string, 0, len(names))+ seen := map[string]struct{}{}+ for _, rawName := range names {+ name := strings.TrimSpace(rawName)+ if name == "" {+ continue+ }+ if _, exists := seen[name]; exists {+ continue+ }+ seen[name] = struct{}{}+ if _, err := ResolveRequestResponseCapability(capabilities, name); err != nil {+ continue+ }+ result = append(result, name)+ }+ return result+}diff --git a/internal/agentcapabilities/surface_contract_test.go b/internal/agentcapabilities/surface_contract_test.gonew file mode 100644index 0000000000..93f3241ff3--- /dev/null+++ b/internal/agentcapabilities/surface_contract_test.go@@ -0,0 +1,518 @@+package agentcapabilities++import (+ "reflect"+ "testing"+)++func TestDefaultSurfaceAffordancesPinSupportedSurfaces(t *testing.T) {+ assistant := DefaultSurfaceAffordancesForID(SurfaceIDPulseAssistant)+ if !assistant.Tools || !assistant.InteractiveQuestions {+ t.Fatalf("Pulse Assistant affordances = %+v, want tools and interactive questions", assistant)+ }+ if assistant.Resources || assistant.Prompts || assistant.CapabilityMetadata {+ t.Fatalf("Pulse Assistant must not default to MCP-only affordances: %+v", assistant)+ }++ mcp := DefaultSurfaceAffordancesForID(SurfaceIDPulseMCP)+ if !mcp.Tools || !mcp.Resources || !mcp.Prompts || !mcp.CapabilityMetadata {+ t.Fatalf("Pulse MCP affordances = %+v, want tools/resources/prompts/capability metadata", mcp)+ }+ if mcp.InteractiveQuestions {+ t.Fatalf("Pulse MCP must not default to native interactive questions: %+v", mcp)+ }+}++func TestNormalizeSurfaceAffordancesPreservesExplicitManifestValues(t *testing.T) {+ surface := OperatorSurfaceContract{+ ID: SurfaceIDPulseMCP,+ Affordances: SurfaceAffordanceContract{+ Tools: true,+ },+ }++ got := NormalizeSurfaceAffordances(surface)+ if !got.Tools {+ t.Fatalf("explicit tools affordance lost: %+v", got)+ }+ if got.Resources || got.Prompts || got.CapabilityMetadata || got.InteractiveQuestions {+ t.Fatalf("explicit affordances must not be expanded by defaults: %+v", got)+ }+}++func TestResolveSurfaceAffordanceContractResolvesLabelsAndDefaults(t *testing.T) {+ canonical, ok := ResolveSurfaceAffordanceContract(CanonicalManifest().SurfaceContract, SurfaceIDPulseMCP, "")+ if !ok {+ t.Fatal("canonical Pulse MCP surface must resolve from manifest")+ }+ if canonical.SurfaceID != SurfaceIDPulseMCP || canonical.SurfaceLabel != "Pulse MCP" {+ t.Fatalf("canonical Pulse MCP surface identity = %+v", canonical)+ }+ if !canonical.Affordances.Tools || !canonical.Affordances.Resources || !canonical.Affordances.Prompts || !canonical.Affordances.CapabilityMetadata {+ t.Fatalf("canonical Pulse MCP affordances = %+v", canonical.Affordances)+ }++ legacyAssistant, ok := ResolveSurfaceAffordanceContract(SurfaceContract{}, SurfaceIDPulseAssistant, "")+ if ok {+ t.Fatal("legacy Assistant fallback must not report a declared surface")+ }+ if legacyAssistant.SurfaceLabel != "Pulse Assistant" || !legacyAssistant.Affordances.Tools || !legacyAssistant.Affordances.InteractiveQuestions {+ t.Fatalf("legacy Assistant fallback = %+v", legacyAssistant)+ }+ if legacyAssistant.Affordances.Resources || legacyAssistant.Affordances.Prompts || legacyAssistant.Affordances.CapabilityMetadata {+ t.Fatalf("legacy Assistant fallback must not inherit MCP affordances: %+v", legacyAssistant.Affordances)+ }++ custom, ok := ResolveSurfaceAffordanceContract(SurfaceContract{}, "custom_external_agent", "")+ if ok {+ t.Fatal("unknown custom surface fallback must not report a declared surface")+ }+ if custom.SurfaceLabel != "custom_external_agent" || SurfaceAffordancesDeclared(custom.Affordances) {+ t.Fatalf("unknown custom surface fallback = %+v, want id label and empty affordances", custom)+ }+}++func TestManifestSurfaceAffordancesResolvesDeclaredAndDefaultSurfaces(t *testing.T) {+ defaults, ok := ManifestSurfaceAffordances(Manifest{}, SurfaceIDPulseMCP)+ if ok {+ t.Fatal("legacy manifest fallback must report compatibility default, not a declared surface")+ }+ if !defaults.Tools || !defaults.Resources || !defaults.Prompts || !defaults.CapabilityMetadata || defaults.InteractiveQuestions {+ t.Fatalf("Pulse MCP default affordances = %+v", defaults)+ }++ manifest := Manifest{SurfaceContract: SurfaceContract{OperatorSurfaces: []OperatorSurfaceContract{{+ ID: "custom_external_agent",+ Label: "Custom external agent",+ ExternalAdapter: true,+ Affordances: SurfaceAffordanceContract{+ Tools: true,+ Resources: true,+ },+ }}}}+ declared, ok := ManifestSurfaceAffordances(manifest, "custom_external_agent")+ if !ok {+ t.Fatal("declared custom surface was not found")+ }+ if !declared.Tools || !declared.Resources || declared.Prompts || declared.CapabilityMetadata || declared.InteractiveQuestions {+ t.Fatalf("declared custom surface affordances = %+v", declared)+ }++ if unknown, ok := ManifestSurfaceAffordances(Manifest{}, "unknown_surface"); ok || SurfaceAffordancesDeclared(unknown) {+ t.Fatalf("unknown surface affordances = %+v ok=%v, want empty", unknown, ok)+ }+}++func TestSurfaceAffordanceLabelsAreStable(t *testing.T) {+ got := SurfaceAffordanceLabels(SurfaceAffordanceContract{+ Tools: true,+ Resources: true,+ Prompts: true,+ CapabilityMetadata: true,+ InteractiveQuestions: true,+ })+ want := []string{"tools", "resources", "prompts", "capability metadata", "interactive questions"}+ if len(got) != len(want) {+ t.Fatalf("labels = %#v, want %#v", got, want)+ }+ for i := range want {+ if got[i] != want[i] {+ t.Fatalf("labels = %#v, want %#v", got, want)+ }+ }+}++func TestFindOperatorSurfaceContractMatchesIDOrLabel(t *testing.T) {+ contract := CanonicalManifest().SurfaceContract+ if surface, ok := FindOperatorSurfaceContract(contract, SurfaceIDPulseAssistant, ""); !ok || surface.Label != "Pulse Assistant" {+ t.Fatalf("find by id = %+v ok=%v", surface, ok)+ }+ if surface, ok := FindOperatorSurfaceContract(contract, "", "Pulse MCP"); !ok || surface.ID != SurfaceIDPulseMCP {+ t.Fatalf("find by label = %+v ok=%v", surface, ok)+ }+}++func TestSurfaceToolContractNormalizeCollectionsDetachesNames(t *testing.T) {+ source := []string{PulseQueryToolName}+ contract := SurfaceToolContract{ToolNames: source}.NormalizeCollections()+ if len(contract.ToolNames) != 1 || contract.ToolNames[0] != PulseQueryToolName {+ t.Fatalf("normalized names = %#v", contract.ToolNames)+ }+ contract.ToolNames[0] = PulseReadToolName+ if source[0] != PulseQueryToolName {+ t.Fatalf("NormalizeCollections returned aliased tool names: source=%#v normalized=%#v", source, contract.ToolNames)+ }++ empty := SurfaceToolContract{}.NormalizeCollections()+ if empty.ToolNames == nil || len(empty.ToolNames) != 0 {+ t.Fatalf("empty tool names = %#v, want stable empty list", empty.ToolNames)+ }+}++func TestCloneSurfaceToolContractsDetachesNames(t *testing.T) {+ if empty := CloneSurfaceToolContracts(nil); empty == nil || len(empty) != 0 {+ t.Fatalf("empty surface tool contracts = %#v, want stable empty list", empty)+ }++ source := []SurfaceToolContract{{+ SurfaceID: SurfaceIDPulseMCP,+ ToolNames: []string{FleetContextCapabilityName},+ CapabilityNames: []string{FleetContextCapabilityName},+ RegistryToolNames: []string{PulseReadToolName},+ NativeToolNames: []string{PulseQuestionToolName},+ }}++ cloned := CloneSurfaceToolContracts(source)+ source[0].ToolNames[0] = "mutated"+ source[0].CapabilityNames[0] = "mutated"+ source[0].RegistryToolNames[0] = "mutated"+ source[0].NativeToolNames[0] = "mutated"++ if !reflect.DeepEqual(cloned[0].ToolNames, []string{FleetContextCapabilityName}) {+ t.Fatalf("cloned tool names = %#v", cloned[0].ToolNames)+ }+ if !reflect.DeepEqual(cloned[0].CapabilityNames, []string{FleetContextCapabilityName}) {+ t.Fatalf("cloned capability names = %#v", cloned[0].CapabilityNames)+ }+ if !reflect.DeepEqual(cloned[0].RegistryToolNames, []string{PulseReadToolName}) {+ t.Fatalf("cloned registry names = %#v", cloned[0].RegistryToolNames)+ }+ if !reflect.DeepEqual(cloned[0].NativeToolNames, []string{PulseQuestionToolName}) {+ t.Fatalf("cloned native names = %#v", cloned[0].NativeToolNames)+ }+}++func TestProjectPulseAssistantSurfaceToolContractSeparatesRegistryAndNativeTools(t *testing.T) {+ contract, ok := ProjectPulseAssistantSurfaceToolContract(CanonicalManifest().SurfaceContract, []ProviderTool{+ {Name: PulseQueryToolName},+ {Name: PulseControlToolName},+ NewPulseQuestionProviderTool(),+ })+ if !ok {+ t.Fatal("canonical manifest must declare Pulse Assistant surface")+ }+ if contract.SurfaceID != SurfaceIDPulseAssistant || contract.SurfaceLabel != "Pulse Assistant" {+ t.Fatalf("Assistant surface identity = %+v", contract)+ }+ if contract.ToolSource != SurfaceToolSourceAssistantRegistry {+ t.Fatalf("Assistant tool source = %q, want %s", contract.ToolSource, SurfaceToolSourceAssistantRegistry)+ }+ if !reflect.DeepEqual(contract.ToolNames, []string{PulseQueryToolName, PulseControlToolName, PulseQuestionToolName}) {+ t.Fatalf("Assistant tool names = %#v", contract.ToolNames)+ }+ if !reflect.DeepEqual(contract.RegistryToolNames, []string{PulseQueryToolName, PulseControlToolName}) {+ t.Fatalf("Assistant registry names = %#v", contract.RegistryToolNames)+ }+ if !reflect.DeepEqual(contract.NativeToolNames, []string{PulseQuestionToolName}) {+ t.Fatalf("Assistant native names = %#v", contract.NativeToolNames)+ }+ if len(contract.CapabilityNames) != 0 {+ t.Fatalf("Assistant contract must not pretend registry tools are manifest capabilities: %#v", contract.CapabilityNames)+ }+ if !contract.Affordances.Tools || !contract.Affordances.InteractiveQuestions || contract.Affordances.Resources {+ t.Fatalf("Assistant affordances = %+v", contract.Affordances)+ }++ legacy, ok := ProjectPulseAssistantSurfaceToolContract(SurfaceContract{}, []ProviderTool{+ NewPulseQuestionProviderTool(),+ })+ if ok {+ t.Fatal("legacy Assistant surface fallback must not report a declared surface")+ }+ if legacy.SurfaceID != SurfaceIDPulseAssistant || legacy.SurfaceLabel != "Pulse Assistant" {+ t.Fatalf("legacy Assistant surface identity = %+v", legacy)+ }+ if !legacy.Affordances.Tools || !legacy.Affordances.InteractiveQuestions || legacy.Affordances.Resources {+ t.Fatalf("legacy Assistant affordances = %+v", legacy.Affordances)+ }+}++func TestProjectPulseAssistantSurfaceToolContractHonorsSurfaceAffordances(t *testing.T) {+ providerTools := []ProviderTool{+ {Name: PulseQueryToolName},+ NewPulseQuestionProviderTool(),+ }++ toolsDisabled := CanonicalManifest().SurfaceContract+ for i := range toolsDisabled.OperatorSurfaces {+ if toolsDisabled.OperatorSurfaces[i].ID == SurfaceIDPulseAssistant {+ toolsDisabled.OperatorSurfaces[i].Affordances = SurfaceAffordanceContract{InteractiveQuestions: true}+ }+ }+ withoutTools, _ := ProjectPulseAssistantSurfaceToolContract(toolsDisabled, providerTools)+ if len(withoutTools.ToolNames) != 0 || len(withoutTools.RegistryToolNames) != 0 || len(withoutTools.NativeToolNames) != 0 {+ t.Fatalf("tools-disabled Assistant surface contract = %+v, want no published tools", withoutTools)+ }++ questionsDisabled := CanonicalManifest().SurfaceContract+ for i := range questionsDisabled.OperatorSurfaces {+ if questionsDisabled.OperatorSurfaces[i].ID == SurfaceIDPulseAssistant {+ questionsDisabled.OperatorSurfaces[i].Affordances = SurfaceAffordanceContract{Tools: true}+ }+ }+ withoutQuestions, _ := ProjectPulseAssistantSurfaceToolContract(questionsDisabled, providerTools)+ if !reflect.DeepEqual(withoutQuestions.ToolNames, []string{PulseQueryToolName}) {+ t.Fatalf("questions-disabled Assistant tool names = %#v, want registry tool only", withoutQuestions.ToolNames)+ }+ if len(withoutQuestions.NativeToolNames) != 0 {+ t.Fatalf("questions-disabled Assistant native names = %#v, want none", withoutQuestions.NativeToolNames)+ }+ if !reflect.DeepEqual(withoutQuestions.RegistryToolNames, []string{PulseQueryToolName}) {+ t.Fatalf("questions-disabled Assistant registry names = %#v", withoutQuestions.RegistryToolNames)+ }+}++func TestIntersectSurfaceAffordancesCannotEnableDisabledSurfaceAffordance(t *testing.T) {+ allowed := SurfaceAffordanceContract{+ Resources: true,+ Prompts: true,+ CapabilityMetadata: true,+ }+ requested := SurfaceAffordanceContract{+ Tools: true,+ Resources: true,+ Prompts: true,+ CapabilityMetadata: true,+ }++ got := IntersectSurfaceAffordances(allowed, requested)+ if got.Tools {+ t.Fatalf("intersection re-enabled disabled tools affordance: %+v", got)+ }+ if !got.Resources || !got.Prompts || !got.CapabilityMetadata {+ t.Fatalf("intersection dropped allowed requested affordances: %+v", got)+ }+ if got.InteractiveQuestions {+ t.Fatalf("intersection enabled disabled interactive questions affordance: %+v", got)+ }+}++func TestProjectManifestSurfaceToolContractUsesPublishedSurfaceToolContract(t *testing.T) {+ manifest := Manifest{+ SurfaceContract: CanonicalManifest().SurfaceContract,+ SurfaceToolContracts: []SurfaceToolContract{{+ SurfaceID: SurfaceIDPulseMCP,+ ToolSource: SurfaceToolSourceCapabilityManifest,+ ToolNames: []string{+ SetOperatorStateCapabilityName,+ ResourceContextCapabilityName,+ EventSubscriptionCapabilityName,+ "missing_tool",+ SetOperatorStateCapabilityName,+ },+ }},+ Capabilities: []Capability{+ {Name: FleetContextCapabilityName, Description: "Read fleet context."},+ {Name: EventSubscriptionCapabilityName, Description: "Stream events."},+ {Name: ResourceContextCapabilityName, Description: "Read resource context."},+ {Name: SetOperatorStateCapabilityName, Description: "Set operator state."},+ },+ }++ contract, ok := ProjectManifestSurfaceToolContract(manifest, SurfaceIDPulseMCP)+ if !ok {+ t.Fatal("canonical manifest must declare Pulse MCP surface")+ }+ if contract.SurfaceID != SurfaceIDPulseMCP || contract.SurfaceLabel != "Pulse MCP" {+ t.Fatalf("MCP surface identity = %+v", contract)+ }+ if contract.ToolSource != SurfaceToolSourceCapabilityManifest {+ t.Fatalf("MCP tool source = %q, want %s", contract.ToolSource, SurfaceToolSourceCapabilityManifest)+ }+ want := []string{SetOperatorStateCapabilityName, ResourceContextCapabilityName}+ if !reflect.DeepEqual(contract.ToolNames, want) {+ t.Fatalf("MCP tool names = %#v, want %#v", contract.ToolNames, want)+ }+ if !reflect.DeepEqual(contract.CapabilityNames, want) {+ t.Fatalf("MCP capability names = %#v, want %#v", contract.CapabilityNames, want)+ }+ if len(contract.RegistryToolNames) != 0 || len(contract.NativeToolNames) != 0 {+ t.Fatalf("MCP contract must not expose Assistant registry/native tools: %+v", contract)+ }+ if !contract.Affordances.Tools || !contract.Affordances.Resources || !contract.Affordances.Prompts || !contract.Affordances.CapabilityMetadata || contract.Affordances.InteractiveQuestions {+ t.Fatalf("MCP affordances = %+v", contract.Affordances)+ }++}++func TestProjectManifestSurfaceToolContractCannotReenableDisabledSurfaceTools(t *testing.T) {+ surfaceContract := CloneSurfaceContract(CanonicalManifest().SurfaceContract)+ for i := range surfaceContract.OperatorSurfaces {+ if surfaceContract.OperatorSurfaces[i].ID == SurfaceIDPulseMCP {+ surfaceContract.OperatorSurfaces[i].Affordances = SurfaceAffordanceContract{+ Resources: true,+ Prompts: true,+ CapabilityMetadata: true,+ }+ }+ }+ manifest := Manifest{+ SurfaceContract: surfaceContract,+ SurfaceToolContracts: []SurfaceToolContract{{+ SurfaceID: SurfaceIDPulseMCP,+ ToolSource: SurfaceToolSourceCapabilityManifest,+ ToolNames: []string{FleetContextCapabilityName},+ Affordances: DefaultSurfaceAffordancesForID(SurfaceIDPulseMCP),+ }},+ Capabilities: []Capability{+ {Name: FleetContextCapabilityName, Description: "Read fleet context."},+ },+ }++ contract, ok := ProjectManifestSurfaceToolContract(manifest, SurfaceIDPulseMCP)+ if !ok {+ t.Fatal("published Pulse MCP surface tool contract should still resolve")+ }+ if contract.Affordances.Tools {+ t.Fatalf("disabled surface tools affordance was re-enabled: %+v", contract.Affordances)+ }+ if len(contract.ToolNames) != 0 || len(contract.CapabilityNames) != 0 {+ t.Fatalf("tools-disabled external surface exposed tool names: %+v", contract)+ }+ if !contract.Affordances.Resources || !contract.Affordances.Prompts || !contract.Affordances.CapabilityMetadata {+ t.Fatalf("allowed non-tool affordances were lost: %+v", contract.Affordances)+ }+}++func TestProjectManifestSurfaceToolContractRequiresPublishedSurfaceToolContract(t *testing.T) {+ manifest := Manifest{+ SurfaceContract: CanonicalManifest().SurfaceContract,+ Capabilities: []Capability{+ {Name: FleetContextCapabilityName, Description: "Read fleet context."},+ {Name: EventSubscriptionCapabilityName, Description: "Stream events."},+ {Name: ResourceContextCapabilityName, Description: "Read resource context."},+ },+ }++ if contract, ok := ProjectManifestSurfaceToolContract(manifest, SurfaceIDPulseMCP); ok {+ t.Fatalf("missing Pulse MCP surface tool contract must fail closed, got %+v", contract)+ }+ if contracts := ProjectManifestSurfaceToolContracts(manifest); len(contracts) != 0 {+ t.Fatalf("missing external surface tool contract projected tools: %+v", contracts)+ }+}++func TestProjectManifestSurfaceToolContractRejectsNativeOrMissingSurfaces(t *testing.T) {+ manifest := Manifest{+ SurfaceContract: CanonicalManifest().SurfaceContract,+ Capabilities: []Capability{+ {Name: FleetContextCapabilityName, Description: "Read fleet context."},+ },+ }++ if contract, ok := ProjectManifestSurfaceToolContract(manifest, SurfaceIDPulseAssistant); ok {+ t.Fatalf("native Assistant surface must not project static manifest tools: %+v", contract)+ }+ if contract, ok := ProjectManifestSurfaceToolContract(manifest, "missing_surface"); ok {+ t.Fatalf("missing surface must not project static manifest tools: %+v", contract)+ }+}++func TestProjectManifestSurfaceToolContractsReturnsExternalAdaptersInManifestOrder(t *testing.T) {+ surfaceContract := CanonicalManifest().SurfaceContract+ surfaceContract.OperatorSurfaces = append(surfaceContract.OperatorSurfaces, OperatorSurfaceContract{+ ID: "pulse_cli_agent",+ Label: "Pulse CLI Agent",+ ExternalAdapter: true,+ Affordances: SurfaceAffordanceContract{+ Tools: true,+ CapabilityMetadata: true,+ },+ })+ manifest := Manifest{+ SurfaceContract: surfaceContract,+ SurfaceToolContracts: []SurfaceToolContract{+ {+ SurfaceID: SurfaceIDPulseMCP,+ ToolSource: SurfaceToolSourceCapabilityManifest,+ ToolNames: []string{FleetContextCapabilityName},+ },+ {+ SurfaceID: "pulse_cli_agent",+ ToolSource: SurfaceToolSourceCapabilityManifest,+ ToolNames: []string{PlanActionCapabilityName},+ },+ },+ Capabilities: []Capability{+ {Name: FleetContextCapabilityName, Description: "Read fleet context."},+ {Name: EventSubscriptionCapabilityName, Description: "Stream events."},+ {Name: PlanActionCapabilityName, Description: "Plan a governed action."},+ },+ }++ contracts := ProjectManifestSurfaceToolContracts(manifest)+ if len(contracts) != 2 {+ t.Fatalf("manifest surface contracts = %+v, want MCP and custom external adapter", contracts)+ }+ if contracts[0].SurfaceID != SurfaceIDPulseMCP || contracts[1].SurfaceID != "pulse_cli_agent" {+ t.Fatalf("manifest external surface order = %+v", contracts)+ }+ if !reflect.DeepEqual(contracts[0].ToolNames, []string{FleetContextCapabilityName}) {+ t.Fatalf("MCP surface tool names = %#v", contracts[0].ToolNames)+ }+ if !reflect.DeepEqual(contracts[1].ToolNames, []string{PlanActionCapabilityName}) {+ t.Fatalf("custom external surface tool names = %#v", contracts[1].ToolNames)+ }+ for _, contract := range contracts {+ if contract.ToolSource != SurfaceToolSourceCapabilityManifest {+ t.Fatalf("external surface source = %q", contract.ToolSource)+ }+ for _, name := range contract.ToolNames {+ if name == EventSubscriptionCapabilityName {+ t.Fatalf("external surface tool names included streaming capability: %#v", contract.ToolNames)+ }+ }+ }+}++func TestProjectPulseIntelligenceSurfaceToolContractsPreservesManifestSurfaceOrder(t *testing.T) {+ surfaceContract := CanonicalManifest().SurfaceContract+ surfaceContract.OperatorSurfaces = append(surfaceContract.OperatorSurfaces, OperatorSurfaceContract{+ ID: "pulse_cli_agent",+ Label: "Pulse CLI Agent",+ ExternalAdapter: true,+ Affordances: SurfaceAffordanceContract{+ Tools: true,+ },+ })+ manifest := Manifest{+ SurfaceContract: surfaceContract,+ SurfaceToolContracts: []SurfaceToolContract{+ {+ SurfaceID: SurfaceIDPulseMCP,+ ToolSource: SurfaceToolSourceCapabilityManifest,+ ToolNames: []string{FleetContextCapabilityName},+ },+ {+ SurfaceID: "pulse_cli_agent",+ ToolSource: SurfaceToolSourceCapabilityManifest,+ ToolNames: []string{},+ },+ },+ Capabilities: []Capability{+ {Name: FleetContextCapabilityName, Description: "Read fleet context."},+ {Name: PlanActionCapabilityName, Description: "Plan a governed action."},+ {Name: EventSubscriptionCapabilityName, Description: "Stream events."},+ },+ }+ contracts := ProjectPulseIntelligenceSurfaceToolContracts(manifest, []ProviderTool{+ {Name: PulseQueryToolName},+ NewPulseQuestionProviderTool(),+ })++ if len(contracts) != 3 {+ t.Fatalf("surface contracts = %+v, want Assistant, MCP, and custom external adapter", contracts)+ }+ if contracts[0].SurfaceID != SurfaceIDPulseAssistant || contracts[1].SurfaceID != SurfaceIDPulseMCP || contracts[2].SurfaceID != "pulse_cli_agent" {+ t.Fatalf("surface contract order = %+v", contracts)+ }+ if !reflect.DeepEqual(contracts[0].ToolNames, []string{PulseQueryToolName, PulseQuestionToolName}) {+ t.Fatalf("Assistant projected names = %#v", contracts[0].ToolNames)+ }+ if !reflect.DeepEqual(contracts[1].ToolNames, []string{FleetContextCapabilityName}) {+ t.Fatalf("MCP projected names = %#v", contracts[1].ToolNames)+ }+ if !reflect.DeepEqual(contracts[2].ToolNames, []string{}) {+ t.Fatalf("custom external adapter projected names = %#v", contracts[2].ToolNames)+ }+}diff --git a/internal/agentcapabilities/text_tool_invocation.go b/internal/agentcapabilities/text_tool_invocation.gonew file mode 100644index 0000000000..e00c13fe59--- /dev/null+++ b/internal/agentcapabilities/text_tool_invocation.go@@ -0,0 +1,204 @@+package agentcapabilities++import (+ "fmt"+ "strings"+)++const ApprovalArgumentKey = "_approval_id"++const CurrentResourceHandle = "current_resource"++var currentResourceReferenceAliases = map[string]struct{}{+ CurrentResourceHandle: {},+ "attached_resource": {},+ "selected_resource": {},+ "this_resource": {},+ "redacted by policy": {},+}++// IsTextToolInvocation reports whether command looks like Pulse's legacy text+// projection for a tool-call request.+func IsTextToolInvocation(command string) bool {+ return strings.HasPrefix(command, "pulse_") ||+ strings.HasPrefix(command, "default_api:") ||+ strings.Contains(command, PulseControlGuestToolName) ||+ strings.Contains(command, PulseRunCommandToolName) ||+ strings.Contains(command, PulseGetResourceToolName)+}++// ParseTextToolInvocation converts Pulse's legacy text projection for a+// tool-call request into the shared tool-call params shape.+func ParseTextToolInvocation(command string) (ToolCallParams, error) {+ command = strings.TrimPrefix(command, "default_api:")+ openParen := strings.Index(command, "(")+ if openParen == -1 {+ return ToolCallParams{}, fmt.Errorf("no opening parenthesis in tool call")+ }+ toolName := strings.TrimSpace(command[:openParen])+ closeParen := strings.LastIndex(command, ")")+ if closeParen == -1 || closeParen <= openParen {+ return ToolCallParams{}, fmt.Errorf("no closing parenthesis in tool call")+ }+ argsStr := command[openParen+1 : closeParen]+ args := make(map[string]any)+ if strings.TrimSpace(argsStr) != "" {+ for _, pair := range splitTextToolArguments(argsStr) {+ parts := strings.SplitN(pair, "=", 2)+ if len(parts) != 2 {+ continue+ }+ key := strings.TrimSpace(parts[0])+ value := strings.TrimSpace(parts[1])+ value = strings.Trim(value, "'\"")+ args[key] = value+ }+ }+ params := NormalizeToolCallParams(ToolCallParams{Name: toolName, Arguments: args})+ if err := ValidateToolCallParams(params); err != nil {+ return ToolCallParams{}, err+ }+ return params, nil+}++// IsCurrentResourceReference reports whether a tool argument is one of the+// session-scoped placeholders that must resolve through attached resource+// context before execution.+func IsCurrentResourceReference(value string) bool {+ _, ok := currentResourceReferenceAliases[strings.ToLower(strings.TrimSpace(value))]+ return ok+}++// ToolInputContainsCurrentResourceReference recursively scans JSON-like tool+// input values for the shared current_resource handle and its governed legacy+// aliases. Provider streaming, native Assistant execution, and external-agent+// adapters all branch on this shared vocabulary.+func ToolInputContainsCurrentResourceReference(value any) bool {+ switch v := value.(type) {+ case nil:+ return false+ case string:+ return IsCurrentResourceReference(v)+ case map[string]any:+ for _, child := range v {+ if ToolInputContainsCurrentResourceReference(child) {+ return true+ }+ }+ case []any:+ for _, child := range v {+ if ToolInputContainsCurrentResourceReference(child) {+ return true+ }+ }+ case []string:+ for _, child := range v {+ if IsCurrentResourceReference(child) {+ return true+ }+ }+ }+ return false+}++// ApprovalArgument returns the trimmed approval id carried on an approved+// action replay. The key is intentionally internal to the shared Pulse+// Intelligence tool-call contract rather than a user-facing argument.+func ApprovalArgument(args map[string]any) string {+ approvalID, _ := args[ApprovalArgumentKey].(string)+ return strings.TrimSpace(approvalID)+}++// IsInternalToolArgument reports whether an argument is Pulse runtime metadata+// that must not be projected into public manifest-backed HTTP request bodies.+func IsInternalToolArgument(name string) bool {+ return name == ApprovalArgumentKey+}++// CloneToolArguments returns an independent copy of tool-call arguments.+func CloneToolArguments(args map[string]any) map[string]any {+ if args == nil {+ return nil+ }+ cloned := make(map[string]any, len(args))+ for k, v := range args {+ cloned[k] = cloneSchemaValue(v)+ }+ return cloned+}++// PublicToolArguments returns a copy of args without Pulse runtime metadata.+// Nested JSON-like values are detached so public HTTP projection and native+// handler execution cannot mutate caller-owned tool-call state.+func PublicToolArguments(args map[string]any) map[string]any {+ if args == nil {+ return nil+ }+ public := make(map[string]any, len(args))+ for k, v := range args {+ if IsInternalToolArgument(k) {+ continue+ }+ public[k] = cloneSchemaValue(v)+ }+ return public+}++// WithApprovalArgument returns args with approvalID attached when non-empty.+// Callers pass the returned map because a non-empty approval id initializes a+// nil input map and the returned map is independent from the input.+func WithApprovalArgument(args map[string]any, approvalID string) map[string]any {+ args = CloneToolArguments(args)+ approvalID = strings.TrimSpace(approvalID)+ if approvalID == "" {+ return args+ }+ if args == nil {+ args = map[string]any{}+ }+ args[ApprovalArgumentKey] = approvalID+ return args+}++func splitTextToolArguments(argsStr string) []string {+ var result []string+ var current strings.Builder+ var inQuote rune+ var escaped bool+ for _, r := range argsStr {+ if escaped {+ current.WriteRune(r)+ escaped = false+ continue+ }+ if r == '\\' {+ escaped = true+ current.WriteRune(r)+ continue+ }+ if inQuote != 0 {+ current.WriteRune(r)+ if r == inQuote {+ inQuote = 0+ }+ continue+ }+ if r == '\'' || r == '"' {+ inQuote = r+ current.WriteRune(r)+ continue+ }+ if r == ',' {+ if s := strings.TrimSpace(current.String()); s != "" {+ result = append(result, s)+ }+ current.Reset()+ continue+ }+ current.WriteRune(r)+ }+ if s := strings.TrimSpace(current.String()); s != "" {+ result = append(result, s)+ }+ return result+}diff --git a/internal/agentcapabilities/text_tool_invocation_test.go b/internal/agentcapabilities/text_tool_invocation_test.gonew file mode 100644index 0000000000..a4535992b5--- /dev/null+++ b/internal/agentcapabilities/text_tool_invocation_test.go@@ -0,0 +1,200 @@+package agentcapabilities++import (+ "strings"+ "testing"+)++func TestIsTextToolInvocation(t *testing.T) {+ if !IsTextToolInvocation("pulse_control_guest(guest_id='102')") {+ t.Fatalf("expected Pulse tool invocation to be detected")+ }+ if !IsTextToolInvocation("default_api:pulse_get_resource(id='1')") {+ t.Fatalf("expected default_api-prefixed tool invocation to be detected")+ }+ if IsTextToolInvocation("echo hello") {+ t.Fatalf("expected non-tool command to be false")+ }+}++func TestParseTextToolInvocation(t *testing.T) {+ params, err := ParseTextToolInvocation("default_api:pulse_control_guest(guest_id=\"102\", action='start')")+ if err != nil {+ t.Fatalf("ParseTextToolInvocation returned error: %v", err)+ }+ if params.Name != "pulse_control_guest" {+ t.Fatalf("tool name = %q, want pulse_control_guest", params.Name)+ }+ if params.Arguments["guest_id"] != "102" || params.Arguments["action"] != "start" {+ t.Fatalf("unexpected arguments: %#v", params.Arguments)+ }++ params, err = ParseTextToolInvocation(" pulse_run_command ()")+ if err != nil {+ t.Fatalf("ParseTextToolInvocation empty args returned error: %v", err)+ }+ if params.Name != "pulse_run_command" || len(params.Arguments) != 0 {+ t.Fatalf("expected empty args, got %+v", params)+ }++ if _, err = ParseTextToolInvocation("(target='vm:101')"); err == nil || !strings.Contains(err.Error(), "tool name is required") {+ t.Fatalf("expected tool name validation error, got %v", err)+ }+ if _, err = ParseTextToolInvocation("pulse_control_guest"); err == nil {+ t.Fatalf("expected error for missing opening parenthesis")+ }+ if _, err = ParseTextToolInvocation("pulse_control_guest("); err == nil {+ t.Fatalf("expected error for missing closing parenthesis")+ }+}++func TestParseTextToolInvocationPreservesQuotedArgumentBoundaries(t *testing.T) {+ params, err := ParseTextToolInvocation("pulse_run_command(action='start', guest_id=\"102\", note='hello, world', path=\"/tmp/a,b\", escaped=\"\\\"quote\\\"\")")+ if err != nil {+ t.Fatalf("ParseTextToolInvocation returned error: %v", err)+ }++ expected := map[string]string{+ "action": "start",+ "guest_id": "102",+ "note": "hello, world",+ "path": "/tmp/a,b",+ "escaped": "\\\"quote\\",+ }+ for key, want := range expected {+ if got := params.Arguments[key]; got != want {+ t.Fatalf("argument %s = %q, want %q", key, got, want)+ }+ }+}++func TestCurrentResourceReferenceHelpersOwnSharedToolArgumentVocabulary(t *testing.T) {+ for _, value := range []string{+ "current_resource",+ " CURRENT_RESOURCE ",+ "attached_resource",+ "selected_resource",+ "this_resource",+ "redacted by policy",+ } {+ if !IsCurrentResourceReference(value) {+ t.Fatalf("IsCurrentResourceReference(%q) = false, want true", value)+ }+ }+ for _, value := range []string{"", "resource-1", "redacted-by-policy"} {+ if IsCurrentResourceReference(value) {+ t.Fatalf("IsCurrentResourceReference(%q) = true, want false", value)+ }+ }++ input := map[string]any{+ "body": map[string]any{+ "targets": []any{"vm:101", map[string]any{"resource_id": "selected_resource"}},+ },+ }+ if !ToolInputContainsCurrentResourceReference(input) {+ t.Fatalf("expected nested current_resource alias to be detected")+ }+ if ToolInputContainsCurrentResourceReference(map[string]any{+ "body": []any{"vm:101", map[string]any{"resource_id": "resource-2"}},+ }) {+ t.Fatalf("non-placeholder arguments should not be detected as current_resource references")+ }+}++func TestApprovalArgumentHelpers(t *testing.T) {+ args := WithApprovalArgument(nil, " approval-1 ")+ if got := ApprovalArgument(args); got != "approval-1" {+ t.Fatalf("ApprovalArgument = %q, want trimmed approval id", got)+ }+ if got := args[ApprovalArgumentKey]; got != "approval-1" {+ t.Fatalf("shared approval argument key stored %q", got)+ }++ empty := WithApprovalArgument(nil, " ")+ if empty != nil {+ t.Fatalf("empty approval id should not allocate args: %#v", empty)+ }+ if got := ApprovalArgument(map[string]any{ApprovalArgumentKey: 42}); got != "" {+ t.Fatalf("non-string approval argument = %q, want empty", got)+ }++ original := map[string]any{"resourceId": "vm:101"}+ withApproval := WithApprovalArgument(original, "approval-2")+ if _, mutated := original[ApprovalArgumentKey]; mutated {+ t.Fatalf("WithApprovalArgument mutated source args: %#v", original)+ }+ if got := ApprovalArgument(withApproval); got != "approval-2" {+ t.Fatalf("copied approval argument = %q, want approval-2", got)+ }+}++func TestCloneToolArgumentsDeepCopiesNestedValues(t *testing.T) {+ source := map[string]any{+ "body": map[string]any{+ "note": "maintenance",+ "tags": []any{"planned", "storage"},+ },+ "modes": []string{"dry-run", "apply"},+ }++ cloned := CloneToolArguments(source)+ clonedBody := cloned["body"].(map[string]any)+ clonedBody["note"] = "changed"+ clonedBody["tags"].([]any)[0] = "changed"+ cloned["modes"].([]string)[0] = "changed"++ sourceBody := source["body"].(map[string]any)+ if sourceBody["note"] != "maintenance" {+ t.Fatalf("nested map mutation leaked into source: %#v", sourceBody)+ }+ if sourceBody["tags"].([]any)[0] != "planned" {+ t.Fatalf("nested slice mutation leaked into source: %#v", sourceBody["tags"])+ }+ if source["modes"].([]string)[0] != "dry-run" {+ t.Fatalf("string slice mutation leaked into source: %#v", source["modes"])+ }+}++func TestPublicToolArgumentsDropsInternalMetadata(t *testing.T) {+ args := map[string]any{+ "resourceId": "vm:101",+ "body": map[string]any{"note": "maintenance"},+ ApprovalArgumentKey: "approval-1",+ }+ public := PublicToolArguments(args)+ if public["resourceId"] != "vm:101" {+ t.Fatalf("public arguments lost resource id: %#v", public)+ }+ if _, leaked := public[ApprovalArgumentKey]; leaked {+ t.Fatalf("public arguments leaked internal approval id: %#v", public)+ }+ public["resourceId"] = "vm:102"+ if args["resourceId"] != "vm:101" {+ t.Fatalf("PublicToolArguments returned aliased map: source=%#v public=%#v", args, public)+ }+ public["body"].(map[string]any)["note"] = "changed"+ if args["body"].(map[string]any)["note"] != "maintenance" {+ t.Fatalf("PublicToolArguments returned aliased nested body: source=%#v public=%#v", args, public)+ }+}++func TestSplitTextToolArguments(t *testing.T) {+ args := "action='start', guest_id=\"102\", note='hello, world', path=\"/tmp/a,b\", escaped=\"\\\"quote\\\"\""+ parts := splitTextToolArguments(args)+ expected := []string{+ "action='start'",+ "guest_id=\"102\"",+ "note='hello, world'",+ "path=\"/tmp/a,b\"",+ "escaped=\"\\\"quote\\\"\"",+ }+ if len(parts) != len(expected) {+ t.Fatalf("expected %d parts, got %d", len(expected), len(parts))+ }+ for i := range expected {+ if strings.TrimSpace(parts[i]) != expected[i] {+ t.Fatalf("part %d = %q, want %q", i, parts[i], expected[i])+ }+ }+}diff --git a/internal/agentcapabilities/tool_call.go b/internal/agentcapabilities/tool_call.gonew file mode 100644index 0000000000..ad774840e2--- /dev/null+++ b/internal/agentcapabilities/tool_call.go@@ -0,0 +1,230 @@+package agentcapabilities++import (+ "errors"+ "fmt"+ "strings"+)++// ToolCallParams is the shared request/response tool-call parameter shape used+// by native Pulse Assistant execution and external-agent adapters.+type ToolCallParams struct {+ Name string `json:"name"`+ Arguments map[string]any `json:"arguments,omitempty"`+}++// ToolCallKind classifies a Pulse Intelligence tool call for safety gates and+// workflow transitions. Native Assistant currently uses it for FSM decisions,+// while the vocabulary lives in the shared core so external-agent adapters and+// future surfaces do not grow separate read/write heuristics.+type ToolCallKind int++const (+ // ToolCallKindResolve covers discovery/query tools that establish resource+ // context and also count as safe verification reads.+ ToolCallKindResolve ToolCallKind = iota++ // ToolCallKindRead covers read-only tools such as logs, metrics, status,+ // and config inspection.+ ToolCallKindRead++ // ToolCallKindWrite covers tools that can change Pulse state or target-side+ // infrastructure state.+ ToolCallKindWrite++ // ToolCallKindUserInput covers interactive tools that ask the user for+ // missing information and do not advance infrastructure workflow state.+ ToolCallKindUserInput+)++func (k ToolCallKind) String() string {+ switch k {+ case ToolCallKindResolve:+ return "resolve"+ case ToolCallKindRead:+ return "read"+ case ToolCallKindWrite:+ return "write"+ case ToolCallKindUserInput:+ return "user_input"+ default:+ return "unknown"+ }+}++// NormalizeToolCallParams returns the canonical tool-call parameter shape+// shared by native Assistant execution and external-agent adapters.+func NormalizeToolCallParams(params ToolCallParams) ToolCallParams {+ params.Name = strings.TrimSpace(params.Name)+ params.Arguments = CloneToolArguments(params.Arguments)+ if params.Arguments == nil {+ params.Arguments = map[string]any{}+ }+ return params+}++// ValidateToolCallParams checks the normalized tool-call contract before a+// surface attempts capability lookup or execution.+func ValidateToolCallParams(params ToolCallParams) error {+ if strings.TrimSpace(params.Name) == "" {+ return fmt.Errorf("tool name is required")+ }+ return nil+}++// PrepareToolRegistryExecution normalizes and validates the direct in-process+// registry entrypoint used by native Assistant execution. It returns a+// ready-to-return shared error result when the tool-call params contract is+// invalid, so registry surfaces do not duplicate failure text or envelope+// construction.+func PrepareToolRegistryExecution(name string, args map[string]any) (ToolCallParams, ToolResult, bool) {+ params := NormalizeToolCallParams(ToolCallParams{+ Name: name,+ Arguments: args,+ })+ if err := ValidateToolCallParams(params); err != nil {+ return params, NewInvalidToolCallParamsResult(err), false+ }+ return params, ToolResult{}, true+}++// ClassifyToolCall classifies a provider/registry tool call for safety gates+// and workflow state transitions. Unknown tools default to write so newly+// introduced tools cannot bypass governed-action checks accidentally.+func ClassifyToolCall(toolName string, args map[string]interface{}) ToolCallKind {+ action, _ := args["action"].(string)+ actionLower := strings.ToLower(action)+ operation, _ := args["operation"].(string)+ operationLower := strings.ToLower(operation)++ switch strings.TrimSpace(toolName) {+ case PulseQuestionToolName:+ return ToolCallKindUserInput++ case PulseQueryToolName, PulseDiscoveryToolName:+ return ToolCallKindResolve++ case PulseMetricsToolName, PulseStorageToolName, PulsePMGToolName, PulseSummarizeToolName:+ return ToolCallKindRead++ case PulseAlertsToolName:+ switch actionLower {+ case "resolve", "dismiss":+ return ToolCallKindWrite+ default:+ return ToolCallKindRead+ }++ case PulseKubernetesToolName:+ switch actionLower {+ case "scale", "restart", "delete_pod", "exec":+ return ToolCallKindWrite+ default:+ return ToolCallKindRead+ }++ case PulseKnowledgeToolName:+ switch actionLower {+ case "remember", "note", "save":+ return ToolCallKindWrite+ default:+ return ToolCallKindRead+ }++ case PulseReadToolName, LegacyAssistantFetchURLToolName:+ return ToolCallKindRead++ case PulseControlToolName:+ return ToolCallKindWrite++ case PulseDockerToolName:+ switch actionLower {+ case "control", "update", "check_updates", "trigger_update":+ return ToolCallKindWrite+ default:+ return ToolCallKindRead+ }++ case PulseFileEditToolName:+ switch actionLower {+ case "read":+ return ToolCallKindRead+ case "write", "append":+ return ToolCallKindWrite+ default:+ return ToolCallKindRead+ }++ case PulseRunCommandToolName, PulseControlGuestToolName, PulseControlDockerToolName,+ LegacyAssistantRunCommandToolName, LegacyAssistantSetResourceURLToolName:+ return ToolCallKindWrite++ case PulseSearchResourcesToolName, PulseGetResourceToolName, PulseGetTopologyToolName,+ PulseListInfrastructureToolName, PulseGetConnectionHealthToolName:+ return ToolCallKindResolve++ case PulseGetDockerLogsToolName, PulseGetPerformanceMetricsToolName,+ PulseGetTemperaturesToolName, PulseGetBaselinesToolName, PulseGetPatternsToolName:+ return ToolCallKindRead++ case PatrolGetFindingsToolName:+ return ToolCallKindRead+ case PatrolReportFindingToolName, PatrolResolveFindingToolName:+ return ToolCallKindWrite+ }++ if toolCallActionIsWrite(actionLower) || toolCallActionIsWrite(operationLower) {+ return ToolCallKindWrite+ }++ if toolCallActionIsRead(actionLower) || toolCallActionIsRead(operationLower) {+ return ToolCallKindRead+ }++ return ToolCallKindWrite+}++func toolCallActionIsWrite(action string) bool {+ switch action {+ case "start", "stop", "restart", "delete",+ "shutdown", "reboot", "write", "append",+ "update", "trigger", "resolve", "dismiss",+ "control":+ return true+ default:+ return false+ }+}++func toolCallActionIsRead(action string) bool {+ switch action {+ case "get", "list", "search", "query",+ "read", "logs", "status", "health",+ "describe", "inspect", "show":+ return true+ default:+ return false+ }+}++// NewInvalidToolCallParamsResult returns the stable shared error result for a+// registry tool-call request that fails the shared params contract.+func NewInvalidToolCallParamsResult(err error) ToolResult {+ if err == nil {+ err = errors.New("tool call params are invalid")+ }+ return NewToolErrorResult(fmt.Errorf("invalid tools/call params: %w", err))+}++// NewUnknownToolResult returns the stable shared error result for a registry+// tool-call request that names no registered tool.+func NewUnknownToolResult(name string) ToolResult {+ return NewToolErrorResult(fmt.Errorf("unknown tool: %s", strings.TrimSpace(name)))+}++// NewControlToolsDisabledToolResult returns the stable shared text result used+// when a direct registry execution attempts a control tool at read-only control+// level.+func NewControlToolsDisabledToolResult() ToolResult {+ return NewToolTextResult(ControlToolsDisabledMessage)+}diff --git a/internal/agentcapabilities/tool_call_test.go b/internal/agentcapabilities/tool_call_test.gonew file mode 100644index 0000000000..832483be4b--- /dev/null+++ b/internal/agentcapabilities/tool_call_test.go@@ -0,0 +1,136 @@+package agentcapabilities++import "testing"++func TestToolCallKindString(t *testing.T) {+ tests := []struct {+ kind ToolCallKind+ want string+ }{+ {ToolCallKindResolve, "resolve"},+ {ToolCallKindRead, "read"},+ {ToolCallKindWrite, "write"},+ {ToolCallKindUserInput, "user_input"},+ {ToolCallKind(99), "unknown"},+ }++ for _, tt := range tests {+ if got := tt.kind.String(); got != tt.want {+ t.Fatalf("ToolCallKind(%d).String() = %q, want %q", tt.kind, got, tt.want)+ }+ }+}++func TestPulseIntelligenceToolNameConstants(t *testing.T) {+ tests := map[string]string{+ "PulseQueryToolName": PulseQueryToolName,+ "PulseDiscoveryToolName": PulseDiscoveryToolName,+ "PulseMetricsToolName": PulseMetricsToolName,+ "PulseStorageToolName": PulseStorageToolName,+ "PulseDockerToolName": PulseDockerToolName,+ "PulseKubernetesToolName": PulseKubernetesToolName,+ "PulseAlertsToolName": PulseAlertsToolName,+ "PulseReadToolName": PulseReadToolName,+ "PulseControlToolName": PulseControlToolName,+ "PulseFileEditToolName": PulseFileEditToolName,+ "PulseKnowledgeToolName": PulseKnowledgeToolName,+ "PulsePMGToolName": PulsePMGToolName,+ "PulseSummarizeToolName": PulseSummarizeToolName,+ "PulseRunCommandToolName": PulseRunCommandToolName,+ "PulseControlGuestToolName": PulseControlGuestToolName,+ "PulseControlDockerToolName": PulseControlDockerToolName,+ "PulseSearchResourcesToolName": PulseSearchResourcesToolName,+ "PulseGetResourceToolName": PulseGetResourceToolName,+ "PulseGetTopologyToolName": PulseGetTopologyToolName,+ "PulseListInfrastructureToolName": PulseListInfrastructureToolName,+ "PulseGetConnectionHealthToolName": PulseGetConnectionHealthToolName,+ "PulseGetDockerLogsToolName": PulseGetDockerLogsToolName,+ "PulseGetPerformanceMetricsToolName": PulseGetPerformanceMetricsToolName,+ "PulseGetTemperaturesToolName": PulseGetTemperaturesToolName,+ "PulseGetBaselinesToolName": PulseGetBaselinesToolName,+ "PulseGetPatternsToolName": PulseGetPatternsToolName,+ "PatrolGetFindingsToolName": PatrolGetFindingsToolName,+ "PatrolReportFindingToolName": PatrolReportFindingToolName,+ "PatrolResolveFindingToolName": PatrolResolveFindingToolName,+ }+ want := map[string]string{+ "PulseQueryToolName": "pulse_query",+ "PulseDiscoveryToolName": "pulse_discovery",+ "PulseMetricsToolName": "pulse_metrics",+ "PulseStorageToolName": "pulse_storage",+ "PulseDockerToolName": "pulse_docker",+ "PulseKubernetesToolName": "pulse_kubernetes",+ "PulseAlertsToolName": "pulse_alerts",+ "PulseReadToolName": "pulse_read",+ "PulseControlToolName": "pulse_control",+ "PulseFileEditToolName": "pulse_file_edit",+ "PulseKnowledgeToolName": "pulse_knowledge",+ "PulsePMGToolName": "pulse_pmg",+ "PulseSummarizeToolName": "pulse_summarize",+ "PulseRunCommandToolName": "pulse_run_command",+ "PulseControlGuestToolName": "pulse_control_guest",+ "PulseControlDockerToolName": "pulse_control_docker",+ "PulseSearchResourcesToolName": "pulse_search_resources",+ "PulseGetResourceToolName": "pulse_get_resource",+ "PulseGetTopologyToolName": "pulse_get_topology",+ "PulseListInfrastructureToolName": "pulse_list_infrastructure",+ "PulseGetConnectionHealthToolName": "pulse_get_connection_health",+ "PulseGetDockerLogsToolName": "pulse_get_docker_logs",+ "PulseGetPerformanceMetricsToolName": "pulse_get_performance_metrics",+ "PulseGetTemperaturesToolName": "pulse_get_temperatures",+ "PulseGetBaselinesToolName": "pulse_get_baselines",+ "PulseGetPatternsToolName": "pulse_get_patterns",+ "PatrolGetFindingsToolName": "patrol_get_findings",+ "PatrolReportFindingToolName": "patrol_report_finding",+ "PatrolResolveFindingToolName": "patrol_resolve_finding",+ }++ for name, got := range tests {+ if got != want[name] {+ t.Fatalf("%s = %q, want %q", name, got, want[name])+ }+ }+}++func TestClassifyToolCallUsesSharedSafetyClassification(t *testing.T) {+ tests := []struct {+ name string+ toolName string+ args map[string]interface{}+ want ToolCallKind+ }{+ {name: "native question", toolName: PulseQuestionToolName, want: ToolCallKindUserInput},+ {name: "query resolves", toolName: "pulse_query", want: ToolCallKindResolve},+ {name: "discovery resolves", toolName: "pulse_discovery", want: ToolCallKindResolve},+ {name: "metrics reads", toolName: "pulse_metrics", want: ToolCallKindRead},+ {name: "summarize reads", toolName: PulseSummarizeToolName, want: ToolCallKindRead},+ {name: "alert list reads", toolName: "pulse_alerts", args: map[string]interface{}{"action": "list"}, want: ToolCallKindRead},+ {name: "alert resolve writes", toolName: "pulse_alerts", args: map[string]interface{}{"action": "resolve"}, want: ToolCallKindWrite},+ {name: "read exec remains read", toolName: "pulse_read", args: map[string]interface{}{"action": "exec"}, want: ToolCallKindRead},+ {name: "control writes", toolName: "pulse_control", args: map[string]interface{}{"type": "command"}, want: ToolCallKindWrite},+ {name: "docker services reads", toolName: "pulse_docker", args: map[string]interface{}{"action": "services"}, want: ToolCallKindRead},+ {name: "docker update writes", toolName: "pulse_docker", args: map[string]interface{}{"action": "update"}, want: ToolCallKindWrite},+ {name: "kubernetes pods reads", toolName: "pulse_kubernetes", args: map[string]interface{}{"action": "pods"}, want: ToolCallKindRead},+ {name: "kubernetes exec writes", toolName: "pulse_kubernetes", args: map[string]interface{}{"action": "exec"}, want: ToolCallKindWrite},+ {name: "file read reads", toolName: "pulse_file_edit", args: map[string]interface{}{"action": "read"}, want: ToolCallKindRead},+ {name: "file append writes", toolName: "pulse_file_edit", args: map[string]interface{}{"action": "append"}, want: ToolCallKindWrite},+ {name: "knowledge recall reads", toolName: "pulse_knowledge", args: map[string]interface{}{"action": "recall"}, want: ToolCallKindRead},+ {name: "knowledge remember writes", toolName: "pulse_knowledge", args: map[string]interface{}{"action": "remember"}, want: ToolCallKindWrite},+ {name: "legacy command writes", toolName: LegacyAssistantRunCommandToolName, want: ToolCallKindWrite},+ {name: "legacy fetch url reads", toolName: LegacyAssistantFetchURLToolName, want: ToolCallKindRead},+ {name: "legacy set url writes", toolName: LegacyAssistantSetResourceURLToolName, want: ToolCallKindWrite},+ {name: "patrol findings read", toolName: "patrol_get_findings", want: ToolCallKindRead},+ {name: "patrol report writes", toolName: "patrol_report_finding", want: ToolCallKindWrite},+ {name: "unknown defaults write", toolName: "future_tool", want: ToolCallKindWrite},+ {name: "generic action read", toolName: "future_tool", args: map[string]interface{}{"action": "inspect"}, want: ToolCallKindRead},+ {name: "generic operation write", toolName: "future_tool", args: map[string]interface{}{"operation": "delete"}, want: ToolCallKindWrite},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := ClassifyToolCall(tt.toolName, tt.args); got != tt.want {+ t.Fatalf("ClassifyToolCall(%q, %#v) = %s, want %s", tt.toolName, tt.args, got, tt.want)+ }+ })+ }+}diff --git a/internal/agentcapabilities/tool_execution.go b/internal/agentcapabilities/tool_execution.gonew file mode 100644index 0000000000..fcab116b8e--- /dev/null+++ b/internal/agentcapabilities/tool_execution.go@@ -0,0 +1,75 @@+package agentcapabilities++import (+ "context"+ "errors"+ "fmt"+)++// ExecuteCapabilityToolHTTP projects one shared tool-call request onto the+// canonical agent capability manifest and wraps the upstream Pulse response in+// the shared tool result envelope.+func ExecuteCapabilityToolHTTP(ctx context.Context, client HTTPDoer, baseURL, token string, capabilities []Capability, params ToolCallParams) (ToolResult, error) {+ params = NormalizeToolCallParams(params)+ if err := ValidateToolCallParams(params); err != nil {+ return ToolResult{}, err+ }+ resp, err := CallRequestResponseCapabilityHTTPByName(ctx, client, baseURL, token, capabilities, params.Name, params.Arguments)+ if err != nil {+ var lookupErr CapabilityLookupError+ if errors.As(err, &lookupErr) {+ return ToolResult{}, fmt.Errorf("unknown tool: %s", lookupErr.Name)+ }+ return ToolResult{}, fmt.Errorf("call Pulse: %w", err)+ }+ return NewCapabilityHTTPToolResult(resp), nil+}++// DirectToolExecutionOptions names the surface-specific error messages used+// when native Pulse code executes a shared tool result directly instead of+// feeding it back into a model turn.+type DirectToolExecutionOptions struct {+ FailurePrefix string+ ApprovalRequiredMessage string+ PolicyBlockedMessage string+}++// DirectToolExecutionOutcome is the shared direct-execution projection of a+// tool result. OutputText is the text callers should expose as execution+// output; Interpretation keeps the full marker/result view available for+// diagnostics and future policy callers.+type DirectToolExecutionOutcome struct {+ OutputText string+ Interpretation ToolResultInterpretation+}++// InterpretDirectToolExecution maps a shared tool result into the output and+// error contract used by native Assistant direct execution paths.+// This keeps marker detection, isError handling, and direct-execution failure+// messages out of individual chat or adapter surfaces.+func InterpretDirectToolExecution(result ToolResult, opts DirectToolExecutionOptions) (DirectToolExecutionOutcome, error) {+ interpreted := InterpretToolResult(result)+ outcome := DirectToolExecutionOutcome{+ OutputText: interpreted.Text,+ Interpretation: interpreted,+ }++ if interpreted.IsError {+ prefix := firstNonEmptyString(opts.FailurePrefix, "tool execution failed")+ return outcome, fmt.Errorf("%s: %s", prefix, interpreted.Text)+ }++ if interpreted.ApprovalRequired {+ outcome.OutputText = ""+ message := firstNonEmptyString(opts.ApprovalRequiredMessage, "tool requires approval")+ return outcome, errors.New(message)+ }++ if interpreted.PolicyBlocked {+ outcome.OutputText = ""+ message := firstNonEmptyString(opts.PolicyBlockedMessage, "tool blocked by security policy")+ return outcome, errors.New(message)+ }++ return outcome, nil+}diff --git a/internal/agentcapabilities/tool_marker.go b/internal/agentcapabilities/tool_marker.gonew file mode 100644index 0000000000..2cbee06440--- /dev/null+++ b/internal/agentcapabilities/tool_marker.go@@ -0,0 +1,262 @@+package agentcapabilities++import (+ "encoding/json"+ "fmt"+ "strings"+)++const (+ // ToolMarkerApprovalRequiredPrefix is the legacy-compatible marker used+ // when an Assistant tool needs operator approval before execution.+ ToolMarkerApprovalRequiredPrefix = ErrCodeApprovalRequired + ":"++ // ToolMarkerPolicyBlockedPrefix is the legacy-compatible marker used when+ // an Assistant tool is blocked by command policy.+ ToolMarkerPolicyBlockedPrefix = ErrCodePolicyBlocked + ":"++ // ToolMarkerApprovalRequiredType is the stable JSON payload type carried by+ // approval-required tool markers.+ ToolMarkerApprovalRequiredType = "approval_required"++ // ToolMarkerPolicyBlockedType is the stable JSON payload type carried by+ // policy-blocked tool markers.+ ToolMarkerPolicyBlockedType = "policy_blocked"+)++// ApprovalPlanData is the shared user-facing subset of a governed action plan+// carried inside approval-required tool markers.+type ApprovalPlanData struct {+ ActionID string `json:"action_id,omitempty"`+ RequestID string `json:"request_id,omitempty"`+ Summary string `json:"summary,omitempty"`+ RequiresApproval bool `json:"requires_approval"`+ ApprovalPolicy string `json:"approval_policy,omitempty"`+ BlastRadius string `json:"blast_radius,omitempty"`+ RollbackAvailable bool `json:"rollback_available"`+ PlanHash string `json:"plan_hash,omitempty"`+ ExpiresAt string `json:"expires_at,omitempty"`+}++// ApprovalContextConfidenceData describes how strongly a proposed action was+// bound to a concrete target before approval.+type ApprovalContextConfidenceData struct {+ Level string `json:"level,omitempty"`+ Summary string `json:"summary,omitempty"`+ Evidence []string `json:"evidence,omitempty"`+}++// ApprovalPreflightData describes the pre-execution dry-run and verification+// boundary carried inside approval-required tool markers.+type ApprovalPreflightData struct {+ Target string `json:"target,omitempty"`+ CurrentState string `json:"current_state,omitempty"`+ IntendedChange string `json:"intended_change,omitempty"`+ DryRunAvailable bool `json:"dry_run_available"`+ DryRunSummary string `json:"dry_run_summary,omitempty"`+ SafetyChecks []string `json:"safety_checks,omitempty"`+ VerificationSteps []string `json:"verification_steps,omitempty"`+ GeneratedAt string `json:"generated_at,omitempty"`+}++// ApprovalRequiredToolMarkerData is the typed payload carried by+// APPROVAL_REQUIRED markers. It lives beside the marker formatter so native+// Assistant, external-agent adapters, and evaluation tools parse the same+// approval contract instead of each defining a local anonymous shape.+type ApprovalRequiredToolMarkerData struct {+ Type string `json:"type,omitempty"`+ DoNotRetry bool `json:"do_not_retry,omitempty"`+ ApprovalID string `json:"approval_id,omitempty"`+ Command string `json:"command,omitempty"`+ ToolID string `json:"tool_id,omitempty"`+ Risk string `json:"risk,omitempty"`+ Description string `json:"description,omitempty"`+ Reason string `json:"reason,omitempty"`+ HowToApprove string `json:"how_to_approve,omitempty"`+ TargetHost string `json:"target_host,omitempty"`+ Host string `json:"host,omitempty"`+ DockerHost string `json:"docker_host,omitempty"`+ ResourceHost string `json:"resource_host,omitempty"`+ Cluster string `json:"cluster,omitempty"`+ TargetName string `json:"target_name,omitempty"`+ TargetType string `json:"target_type,omitempty"`+ TargetID string `json:"target_id,omitempty"`+ AuditID string `json:"audit_id,omitempty"`+ Plan *ApprovalPlanData `json:"plan,omitempty"`+ ContextConfidence *ApprovalContextConfidenceData `json:"context_confidence,omitempty"`+ Preflight *ApprovalPreflightData `json:"preflight,omitempty"`+}++// TargetHint returns the best human-facing target label carried by an approval+// marker without making chat surfaces duplicate the same field-priority list.+func (d ApprovalRequiredToolMarkerData) TargetHint() string {+ return firstNonEmptyString(+ d.TargetHost,+ d.Host,+ d.DockerHost,+ d.ResourceHost,+ d.Cluster,+ d.TargetName,+ )+}++// DescriptionText returns the best human-facing reason carried by an approval+// marker.+func (d ApprovalRequiredToolMarkerData) DescriptionText() string {+ return firstNonEmptyString(d.Description, d.Reason)+}++// ApprovalRequiredToolMarker builds the common approval-required marker for a+// command-oriented tool. Callers with richer payload fields can use+// FormatApprovalRequiredToolMarker directly.+func ApprovalRequiredToolMarker(command, toolID, reason, approvalID, howToApprove string) string {+ payload := map[string]any{+ "command": command,+ "tool_id": toolID,+ "reason": reason,+ "how_to_approve": howToApprove,+ }+ if approvalID = strings.TrimSpace(approvalID); approvalID != "" {+ payload["approval_id"] = approvalID+ }+ return FormatApprovalRequiredToolMarker(payload)+}++// PolicyBlockedToolMarker builds the common policy-blocked marker for a+// command-oriented tool. Callers with richer payload fields can use+// FormatPolicyBlockedToolMarker directly.+func PolicyBlockedToolMarker(command, reason string) string {+ return FormatPolicyBlockedToolMarker(map[string]any{+ "command": command,+ "reason": reason,+ })+}++// FormatApprovalRequiredToolMarker formats a caller-provided payload with the+// shared approval marker prefix and required machine-readable fields.+func FormatApprovalRequiredToolMarker(payload map[string]any) string {+ return formatToolMarker(ToolMarkerApprovalRequiredPrefix, ToolMarkerApprovalRequiredType, payload, "command", "reason")+}++// FormatPolicyBlockedToolMarker formats a caller-provided payload with the+// shared policy marker prefix and required machine-readable fields.+func FormatPolicyBlockedToolMarker(payload map[string]any) string {+ return formatToolMarker(ToolMarkerPolicyBlockedPrefix, ToolMarkerPolicyBlockedType, payload, "reason", "command")+}++// HasApprovalRequiredToolMarker reports whether content starts with the shared+// approval-required marker prefix. It intentionally accepts both+// "APPROVAL_REQUIRED:{...}" and "APPROVAL_REQUIRED: {...}" legacy forms.+func HasApprovalRequiredToolMarker(content string) bool {+ return strings.HasPrefix(content, ToolMarkerApprovalRequiredPrefix)+}++// HasPolicyBlockedToolMarker reports whether content starts with the shared+// policy-blocked marker prefix.+func HasPolicyBlockedToolMarker(content string) bool {+ return strings.HasPrefix(content, ToolMarkerPolicyBlockedPrefix)+}++// ApprovalRequiredToolMarkerPayloadJSON returns the marker payload bytes when+// content carries the shared approval-required prefix.+func ApprovalRequiredToolMarkerPayloadJSON(content string) ([]byte, bool) {+ return toolMarkerPayloadJSON(content, ToolMarkerApprovalRequiredPrefix)+}++// PolicyBlockedToolMarkerPayloadJSON returns the marker payload bytes when+// content carries the shared policy-blocked prefix.+func PolicyBlockedToolMarkerPayloadJSON(content string) ([]byte, bool) {+ return toolMarkerPayloadJSON(content, ToolMarkerPolicyBlockedPrefix)+}++// ParseApprovalRequiredToolMarkerPayload parses a shared approval-required+// marker into a generic payload map and verifies the stable payload type.+func ParseApprovalRequiredToolMarkerPayload(content string) (map[string]any, bool) {+ return parseToolMarkerPayload(content, ToolMarkerApprovalRequiredPrefix, ToolMarkerApprovalRequiredType)+}++// ParseApprovalRequiredToolMarkerData parses an approval-required marker into+// the shared typed payload contract.+func ParseApprovalRequiredToolMarkerData(content string) (ApprovalRequiredToolMarkerData, bool) {+ raw, ok := ApprovalRequiredToolMarkerPayloadJSON(content)+ if !ok {+ return ApprovalRequiredToolMarkerData{}, false+ }+ var data ApprovalRequiredToolMarkerData+ if err := json.Unmarshal(raw, &data); err != nil {+ return ApprovalRequiredToolMarkerData{}, false+ }+ if data.Type != ToolMarkerApprovalRequiredType {+ return ApprovalRequiredToolMarkerData{}, false+ }+ return data, true+}++// ParsePolicyBlockedToolMarkerPayload parses a shared policy-blocked marker+// into a generic payload map and verifies the stable payload type.+func ParsePolicyBlockedToolMarkerPayload(content string) (map[string]any, bool) {+ return parseToolMarkerPayload(content, ToolMarkerPolicyBlockedPrefix, ToolMarkerPolicyBlockedType)+}++func formatToolMarker(prefix, payloadType string, payload map[string]any, fallbackKeys ...string) string {+ prepared := map[string]any{}+ for k, v := range payload {+ prepared[k] = v+ }+ prepared["type"] = payloadType+ prepared["do_not_retry"] = true++ body, err := json.Marshal(prepared)+ if err != nil {+ fallback := firstStringPayloadValue(prepared, fallbackKeys...)+ if fallback == "" {+ fallback = payloadType+ }+ return fmt.Sprintf("%s %s", prefix, fallback)+ }+ return fmt.Sprintf("%s %s", prefix, body)+}++func toolMarkerPayloadJSON(content, prefix string) ([]byte, bool) {+ if !strings.HasPrefix(content, prefix) {+ return nil, false+ }+ payload := strings.TrimSpace(strings.TrimPrefix(content, prefix))+ if payload == "" {+ return nil, false+ }+ return []byte(payload), true+}++func parseToolMarkerPayload(content, prefix, payloadType string) (map[string]any, bool) {+ raw, ok := toolMarkerPayloadJSON(content, prefix)+ if !ok {+ return nil, false+ }+ var payload map[string]any+ if err := json.Unmarshal(raw, &payload); err != nil {+ return nil, false+ }+ if payload["type"] != payloadType {+ return nil, false+ }+ return payload, true+}++func firstStringPayloadValue(payload map[string]any, keys ...string) string {+ for _, key := range keys {+ if value, ok := payload[key].(string); ok && strings.TrimSpace(value) != "" {+ return strings.TrimSpace(value)+ }+ }+ return ""+}++func firstNonEmptyString(values ...string) string {+ for _, value := range values {+ if trimmed := strings.TrimSpace(value); trimmed != "" {+ return trimmed+ }+ }+ return ""+}diff --git a/internal/agentcapabilities/tool_marker_test.go b/internal/agentcapabilities/tool_marker_test.gonew file mode 100644index 0000000000..f001b37882--- /dev/null+++ b/internal/agentcapabilities/tool_marker_test.go@@ -0,0 +1,168 @@+package agentcapabilities++import (+ "strings"+ "testing"+)++func TestApprovalRequiredToolMarkerFormatsSharedPayload(t *testing.T) {+ marker := ApprovalRequiredToolMarker("qm start 101", "tool-1", "approval required", "approval-1", "Click approve.")+ if !strings.HasPrefix(marker, ToolMarkerApprovalRequiredPrefix+" ") {+ t.Fatalf("marker prefix = %q", marker)+ }+ payload, ok := ParseApprovalRequiredToolMarkerPayload(marker)+ if !ok {+ t.Fatalf("ParseApprovalRequiredToolMarkerPayload failed for %s", marker)+ }+ for key, want := range map[string]any{+ "type": ToolMarkerApprovalRequiredType,+ "command": "qm start 101",+ "tool_id": "tool-1",+ "reason": "approval required",+ "approval_id": "approval-1",+ "how_to_approve": "Click approve.",+ "do_not_retry": true,+ } {+ if got := payload[key]; got != want {+ t.Fatalf("payload[%s] = %#v, want %#v in %#v", key, got, want, payload)+ }+ }+}++func TestFormatApprovalRequiredToolMarkerPreservesCallerFields(t *testing.T) {+ marker := FormatApprovalRequiredToolMarker(map[string]any{+ "approval_id": "approval-2",+ "command": "docker restart web",+ "risk": "high",+ "plan": map[string]any{+ "action_id": "act-1",+ },+ })+ payload, ok := ParseApprovalRequiredToolMarkerPayload(marker)+ if !ok {+ t.Fatalf("ParseApprovalRequiredToolMarkerPayload failed for %s", marker)+ }+ if payload["risk"] != "high" {+ t.Fatalf("risk = %#v, want high", payload["risk"])+ }+ plan, ok := payload["plan"].(map[string]any)+ if !ok || plan["action_id"] != "act-1" {+ t.Fatalf("plan = %#v, want action_id", payload["plan"])+ }+ if payload["type"] != ToolMarkerApprovalRequiredType || payload["do_not_retry"] != true {+ t.Fatalf("shared fields missing: %#v", payload)+ }+}++func TestParseApprovalRequiredToolMarkerDataUsesSharedTypedPayload(t *testing.T) {+ marker := FormatApprovalRequiredToolMarker(map[string]any{+ "approval_id": "approval-3",+ "command": "kubectl rollout restart deployment/api",+ "risk": "medium",+ "reason": "restart requested",+ "cluster": "prod-cluster",+ "target_type": "kubernetes-deployment",+ "target_id": "prod/api",+ "audit_id": "act-1",+ "do_not_retry": false,+ "how_to_approve": "Approve in chat.",+ "plan": map[string]any{+ "action_id": "act-1",+ "request_id": "req-1",+ "summary": "Restart api",+ "requires_approval": true,+ "approval_policy": "operator",+ "blast_radius": "api pods",+ "rollback_available": true,+ "plan_hash": "hash-1",+ "expires_at": "2026-06-18T06:30:00Z",+ },+ "context_confidence": map[string]any{+ "level": "high",+ "summary": "resource explicitly selected",+ "evidence": []string{"@api"},+ },+ "preflight": map[string]any{+ "target": "deployment/api",+ "current_state": "available",+ "intended_change": "restart pods",+ "dry_run_available": true,+ "dry_run_summary": "server-side dry run passed",+ "safety_checks": []string{"within maintenance window"},+ "verification_steps": []string{"watch rollout"},+ "generated_at": "2026-06-18T06:20:00Z",+ },+ })++ payload, ok := ParseApprovalRequiredToolMarkerData(marker)+ if !ok {+ t.Fatalf("ParseApprovalRequiredToolMarkerData failed for %s", marker)+ }+ if payload.Type != ToolMarkerApprovalRequiredType || !payload.DoNotRetry {+ t.Fatalf("shared marker fields = type:%q do_not_retry:%v", payload.Type, payload.DoNotRetry)+ }+ if payload.ApprovalID != "approval-3" || payload.Command != "kubectl rollout restart deployment/api" {+ t.Fatalf("payload identity fields = %+v", payload)+ }+ if payload.TargetHint() != "prod-cluster" {+ t.Fatalf("TargetHint = %q, want prod-cluster", payload.TargetHint())+ }+ if payload.DescriptionText() != "restart requested" {+ t.Fatalf("DescriptionText = %q, want reason fallback", payload.DescriptionText())+ }+ if payload.Plan == nil || payload.Plan.ActionID != "act-1" || !payload.Plan.RollbackAvailable {+ t.Fatalf("plan payload = %+v", payload.Plan)+ }+ if payload.ContextConfidence == nil || payload.ContextConfidence.Level != "high" || len(payload.ContextConfidence.Evidence) != 1 {+ t.Fatalf("context confidence payload = %+v", payload.ContextConfidence)+ }+ if payload.Preflight == nil || payload.Preflight.Target != "deployment/api" || len(payload.Preflight.VerificationSteps) != 1 {+ t.Fatalf("preflight payload = %+v", payload.Preflight)+ }+}++func TestPolicyBlockedToolMarkerFormatsSharedPayload(t *testing.T) {+ marker := PolicyBlockedToolMarker("rm -rf /", "blocked by policy")+ if !HasPolicyBlockedToolMarker(marker) {+ t.Fatalf("HasPolicyBlockedToolMarker(%q) = false", marker)+ }+ payload, ok := ParsePolicyBlockedToolMarkerPayload(marker)+ if !ok {+ t.Fatalf("ParsePolicyBlockedToolMarkerPayload failed for %s", marker)+ }+ for key, want := range map[string]any{+ "type": ToolMarkerPolicyBlockedType,+ "command": "rm -rf /",+ "reason": "blocked by policy",+ "do_not_retry": true,+ } {+ if got := payload[key]; got != want {+ t.Fatalf("payload[%s] = %#v, want %#v in %#v", key, got, want, payload)+ }+ }+}++func TestToolMarkerPayloadJSONAcceptsLegacyNoSpaceForm(t *testing.T) {+ raw, ok := ApprovalRequiredToolMarkerPayloadJSON(`APPROVAL_REQUIRED:{"type":"approval_required","command":"uptime"}`)+ if !ok {+ t.Fatal("ApprovalRequiredToolMarkerPayloadJSON rejected no-space marker")+ }+ if string(raw) != `{"type":"approval_required","command":"uptime"}` {+ t.Fatalf("raw = %s", raw)+ }+}++func TestParseToolMarkerPayloadRejectsWrongShape(t *testing.T) {+ if _, ok := ParseApprovalRequiredToolMarkerPayload("not a marker"); ok {+ t.Fatal("parsed non-marker")+ }+ if _, ok := ParseApprovalRequiredToolMarkerPayload("APPROVAL_REQUIRED: not-json"); ok {+ t.Fatal("parsed non-JSON marker")+ }+ if _, ok := ParseApprovalRequiredToolMarkerPayload(`APPROVAL_REQUIRED: {"type":"policy_blocked"}`); ok {+ t.Fatal("parsed marker with wrong type")+ }+ if _, ok := ParsePolicyBlockedToolMarkerPayload(`APPROVAL_REQUIRED: {"type":"approval_required"}`); ok {+ t.Fatal("parsed wrong marker prefix")+ }+}diff --git a/internal/agentcapabilities/tool_names.go b/internal/agentcapabilities/tool_names.gonew file mode 100644index 0000000000..ea69d2a516--- /dev/null+++ b/internal/agentcapabilities/tool_names.go@@ -0,0 +1,36 @@+package agentcapabilities++const (+ PulseQueryToolName = "pulse_query"+ PulseDiscoveryToolName = "pulse_discovery"+ PulseMetricsToolName = "pulse_metrics"+ PulseStorageToolName = "pulse_storage"+ PulseDockerToolName = "pulse_docker"+ PulseKubernetesToolName = "pulse_kubernetes"+ PulseAlertsToolName = "pulse_alerts"+ PulseReadToolName = "pulse_read"+ PulseControlToolName = "pulse_control"+ PulseFileEditToolName = "pulse_file_edit"+ PulseKnowledgeToolName = "pulse_knowledge"+ PulsePMGToolName = "pulse_pmg"+ PulseSummarizeToolName = "pulse_summarize"++ PulseRunCommandToolName = "pulse_run_command"+ PulseControlGuestToolName = "pulse_control_guest"+ PulseControlDockerToolName = "pulse_control_docker"++ PulseSearchResourcesToolName = "pulse_search_resources"+ PulseGetResourceToolName = "pulse_get_resource"+ PulseGetTopologyToolName = "pulse_get_topology"+ PulseListInfrastructureToolName = "pulse_list_infrastructure"+ PulseGetConnectionHealthToolName = "pulse_get_connection_health"+ PulseGetDockerLogsToolName = "pulse_get_docker_logs"+ PulseGetPerformanceMetricsToolName = "pulse_get_performance_metrics"+ PulseGetTemperaturesToolName = "pulse_get_temperatures"+ PulseGetBaselinesToolName = "pulse_get_baselines"+ PulseGetPatternsToolName = "pulse_get_patterns"++ PatrolGetFindingsToolName = "patrol_get_findings"+ PatrolReportFindingToolName = "patrol_report_finding"+ PatrolResolveFindingToolName = "patrol_resolve_finding"+)diff --git a/internal/agentcapabilities/tool_response.go b/internal/agentcapabilities/tool_response.gonew file mode 100644index 0000000000..d4d6d9170c--- /dev/null+++ b/internal/agentcapabilities/tool_response.go@@ -0,0 +1,131 @@+package agentcapabilities++import (+ "encoding/json"+ "strings"+)++const (+ ErrCodeFSMBlocked = "FSM_BLOCKED"+ ErrCodeStrictResolution = "STRICT_RESOLUTION"+ ErrCodeRoutingMismatch = "ROUTING_MISMATCH"+ ErrCodeExecutionContextUnavailable = "EXECUTION_CONTEXT_UNAVAILABLE"+ ErrCodeNotFound = "NOT_FOUND"+ ErrCodeActionNotAllowed = "ACTION_NOT_ALLOWED"+ ErrCodePolicyBlocked = "POLICY_BLOCKED"+ ErrCodeApprovalRequired = "APPROVAL_REQUIRED"+ ErrCodeInvalidInput = "INVALID_INPUT"+ ErrCodeExecutionFailed = "EXECUTION_FAILED"+ ErrCodeNoAgent = "NO_AGENT"+)++// ToolResponse is the structured tool-result envelope used when a tool needs+// machine-readable success/failure fields inside the shared text result+// wrapper. It is shared so Assistant tools and agent-facing adapters branch on+// the same blocked/failed/retryable vocabulary.+type ToolResponse struct {+ OK bool `json:"ok"`+ Data any `json:"data,omitempty"`+ Error *ToolError `json:"error,omitempty"`+ Meta map[string]any `json:"meta,omitempty"`+}++// ToolError provides the structured failure shape for ToolResponse.+type ToolError struct {+ Code string `json:"code"`+ Message string `json:"message"`+ Blocked bool `json:"blocked,omitempty"`+ Failed bool `json:"failed,omitempty"`+ Retryable bool `json:"retryable,omitempty"`+ Details map[string]any `json:"details,omitempty"`+}++// NewToolBlockedError creates a policy or validation blocked tool response.+func NewToolBlockedError(code, message string, details map[string]any) ToolResponse {+ return ToolResponse{+ OK: false,+ Error: &ToolError{+ Code: code,+ Message: message,+ Blocked: true,+ Details: details,+ },+ }+}++// NewToolResponseResult wraps a structured ToolResponse in the shared tool+// result envelope while preserving failure state through isError.+func NewToolResponseResult(resp ToolResponse) ToolResult {+ return NewToolJSONResultWithIsError(resp, !resp.OK)+}++func toolResultJSONObject(resultText string) (map[string]any, bool) {+ if resultText == "" {+ return nil, false+ }+ jsonStart := strings.Index(resultText, "{")+ if jsonStart == -1 {+ return nil, false+ }++ var obj map[string]any+ if err := json.Unmarshal([]byte(resultText[jsonStart:]), &obj); err != nil {+ return nil, false+ }+ return obj, true+}++// ToolResultErrorCode extracts the shared ToolResponse error code from a tool+// result text. It also accepts the legacy top-level error_code shape so old+// persisted transcripts and compatibility paths branch through the same helper.+func ToolResultErrorCode(resultText string) (string, bool) {+ obj, ok := toolResultJSONObject(resultText)+ if !ok {+ return "", false+ }+ if errorAny, ok := obj["error"]; ok {+ if errorMap, ok := errorAny.(map[string]any); ok {+ if code, ok := errorMap["code"].(string); ok && strings.TrimSpace(code) != "" {+ return code, true+ }+ }+ }+ if code, ok := obj["error_code"].(string); ok && strings.TrimSpace(code) != "" {+ return code, true+ }+ return "", false+}++// ToolResultHasErrorCode reports whether a tool result text carries the given+// shared ToolResponse error code.+func ToolResultHasErrorCode(resultText, code string) bool {+ got, ok := ToolResultErrorCode(resultText)+ return ok && got == code+}++// ToolResultHasVerificationOK checks whether a tool result text includes+// structured verification evidence indicating a mutation was confirmed.+//+// Expected shape, possibly after leading human-readable text:+//+// { "verification": { "ok": true, ... } }+func ToolResultHasVerificationOK(resultText string) bool {+ obj, ok := toolResultJSONObject(resultText)+ if !ok {+ return false+ }+ vAny, ok := obj["verification"]+ if !ok {+ return false+ }+ vMap, ok := vAny.(map[string]any)+ if !ok {+ return false+ }+ okAny, ok := vMap["ok"]+ if !ok {+ return false+ }+ okBool, ok := okAny.(bool)+ return ok && okBool+}diff --git a/internal/agentcapabilities/tool_response_test.go b/internal/agentcapabilities/tool_response_test.gonew file mode 100644index 0000000000..6cb6321ddc--- /dev/null+++ b/internal/agentcapabilities/tool_response_test.go@@ -0,0 +1,174 @@+package agentcapabilities++import (+ "encoding/json"+ "strings"+ "testing"+)++func TestNewToolBlockedErrorBuildsSharedEnvelope(t *testing.T) {+ resp := NewToolBlockedError(ErrCodeStrictResolution, "discover first", map[string]any{+ "resource_id": "vm:101",+ })++ if resp.OK {+ t.Fatal("blocked tool response must set ok=false")+ }+ if resp.Error == nil {+ t.Fatal("blocked tool response must include error")+ }+ if resp.Error.Code != ErrCodeStrictResolution {+ t.Fatalf("error code = %q, want %q", resp.Error.Code, ErrCodeStrictResolution)+ }+ if !resp.Error.Blocked || resp.Error.Failed || resp.Error.Retryable {+ t.Fatalf("unexpected error posture: %+v", resp.Error)+ }++ body, err := json.Marshal(resp)+ if err != nil {+ t.Fatalf("marshal response: %v", err)+ }+ text := string(body)+ for _, want := range []string{+ `"ok":false`,+ `"code":"STRICT_RESOLUTION"`,+ `"blocked":true`,+ `"resource_id":"vm:101"`,+ } {+ if !strings.Contains(text, want) {+ t.Fatalf("tool response missing %s: %s", want, text)+ }+ }+}++func TestToolResponseResultPreservesErrorState(t *testing.T) {+ blocked := NewToolBlockedError(ErrCodeActionNotAllowed, "not available here", nil)+ result := NewToolResponseResult(blocked)+ if !result.IsError {+ t.Fatal("blocked tool response must become isError=true")+ }+ if len(result.Content) != 1 || !strings.Contains(result.Content[0].Text, `"code":"ACTION_NOT_ALLOWED"`) {+ t.Fatalf("blocked response not encoded in tool content: %+v", result)+ }++ ok := NewToolResponseResult(ToolResponse{OK: true, Data: map[string]any{"status": "ok"}})+ if ok.IsError {+ t.Fatal("ok tool response must become isError=false")+ }+ if len(ok.Content) != 1 || !strings.Contains(ok.Content[0].Text, `"status":"ok"`) {+ t.Fatalf("ok response not encoded in tool content: %+v", ok)+ }++}++func TestToolResultHasVerificationOK(t *testing.T) {+ for _, tc := range []struct {+ name string+ text string+ want bool+ }{+ {+ name: "top level verification ok",+ text: `{"success":true,"verification":{"ok":true,"method":"exit_code"}}`,+ want: true,+ },+ {+ name: "leading text before json",+ text: `Action complete: {"verification":{"ok":true}}`,+ want: true,+ },+ {+ name: "verification false",+ text: `{"verification":{"ok":false}}`,+ want: false,+ },+ {+ name: "missing verification",+ text: `{"success":true}`,+ want: false,+ },+ {+ name: "malformed json",+ text: `Action complete: {"verification":{"ok":true}`,+ want: false,+ },+ {+ name: "non boolean ok",+ text: `{"verification":{"ok":"true"}}`,+ want: false,+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ if got := ToolResultHasVerificationOK(tc.text); got != tc.want {+ t.Fatalf("ToolResultHasVerificationOK(%q) = %v, want %v", tc.text, got, tc.want)+ }+ })+ }+}++func TestToolResultErrorCode(t *testing.T) {+ blocked := NewToolResponseResult(NewToolBlockedError(ErrCodeStrictResolution, "discover first", nil))+ blockedText := ToolResultText(blocked)+ fsmBlocked := NewToolResponseResult(NewToolBlockedError(ErrCodeFSMBlocked, "verify before writing again", nil))+ fsmBlockedText := ToolResultText(fsmBlocked)++ for _, tc := range []struct {+ name string+ text string+ wantCode string+ wantOK bool+ }{+ {+ name: "tool response error code",+ text: blockedText,+ wantCode: ErrCodeStrictResolution,+ wantOK: true,+ },+ {+ name: "fsm blocked error code",+ text: fsmBlockedText,+ wantCode: ErrCodeFSMBlocked,+ wantOK: true,+ },+ {+ name: "leading text before json",+ text: `Blocked: {"ok":false,"error":{"code":"ROUTING_MISMATCH","message":"choose child"}}`,+ wantCode: ErrCodeRoutingMismatch,+ wantOK: true,+ },+ {+ name: "legacy top level error code",+ text: `{"error_code":"EXECUTION_CONTEXT_UNAVAILABLE"}`,+ wantCode: ErrCodeExecutionContextUnavailable,+ wantOK: true,+ },+ {+ name: "missing error",+ text: `{"ok":true}`,+ wantOK: false,+ },+ {+ name: "malformed json",+ text: `Blocked: {"error":{"code":"STRICT_RESOLUTION"}`,+ wantOK: false,+ },+ {+ name: "non string code",+ text: `{"error":{"code":42}}`,+ wantOK: false,+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ gotCode, gotOK := ToolResultErrorCode(tc.text)+ if gotCode != tc.wantCode || gotOK != tc.wantOK {+ t.Fatalf("ToolResultErrorCode(%q) = %q, %v; want %q, %v", tc.text, gotCode, gotOK, tc.wantCode, tc.wantOK)+ }+ if gotOK && !ToolResultHasErrorCode(tc.text, tc.wantCode) {+ t.Fatalf("ToolResultHasErrorCode(%q, %q) = false, want true", tc.text, tc.wantCode)+ }+ if ToolResultHasErrorCode(tc.text, ErrCodeNoAgent) {+ t.Fatalf("ToolResultHasErrorCode(%q, %q) = true, want false", tc.text, ErrCodeNoAgent)+ }+ })+ }+}diff --git a/internal/agentcapabilities/tool_result.go b/internal/agentcapabilities/tool_result.gonew file mode 100644index 0000000000..33cff1d97c--- /dev/null+++ b/internal/agentcapabilities/tool_result.go@@ -0,0 +1,206 @@+package agentcapabilities++import (+ "bytes"+ "encoding/json"+ "io"+ "strings"+)++// ToolContent is one content block in a shared tool result.+type ToolContent struct {+ Type string `json:"type"`+ Text string `json:"text,omitempty"`+ MimeType string `json:"mimeType,omitempty"`+ Data string `json:"data,omitempty"`+ URI string `json:"uri,omitempty"`+}++// ToolResult is the shared result envelope used by the in-app Assistant tool+// executor and external-agent adapters.+type ToolResult struct {+ Content []ToolContent `json:"content"`+ StructuredContent map[string]any `json:"structuredContent,omitempty"`+ IsError bool `json:"isError,omitempty"`+}++// EmptyToolResult returns a result with initialized collection fields.+func EmptyToolResult() ToolResult {+ return ToolResult{}.NormalizeCollections()+}++// NormalizeCollections returns an independent tool result with stable empty+// collections.+func (r ToolResult) NormalizeCollections() ToolResult {+ r.Content = append([]ToolContent(nil), r.Content...)+ if r.Content == nil {+ r.Content = []ToolContent{}+ }+ r.StructuredContent = CloneToolStructuredContent(r.StructuredContent)+ return r+}++// NewToolTextContent creates a text content block.+func NewToolTextContent(text string) ToolContent {+ return ToolContent{Type: "text", Text: text}+}++// NewToolTextResult creates a successful text tool result.+func NewToolTextResult(text string) ToolResult {+ return NewToolTextResultWithIsError(text, false)+}++// NewToolTextResultWithIsError creates a text result with explicit error state.+func NewToolTextResultWithIsError(text string, isError bool) ToolResult {+ return ToolResult{+ Content: []ToolContent{NewToolTextContent(text)},+ IsError: isError,+ }.NormalizeCollections()+}++// NewToolErrorResult creates an error tool result from a Go error.+func NewToolErrorResult(err error) ToolResult {+ if err == nil {+ return NewToolTextResultWithIsError("", true)+ }+ return NewToolTextResultWithIsError(err.Error(), true)+}++// NewToolJSONResult creates a successful JSON text result.+func NewToolJSONResult(data any) ToolResult {+ return NewToolJSONResultWithIsError(data, false)+}++// NewToolJSONResultWithIsError creates a JSON text result with explicit error+// state.+func NewToolJSONResultWithIsError(data any, isError bool) ToolResult {+ body, err := json.Marshal(data)+ if err != nil {+ return NewToolErrorResult(err)+ }+ result := NewToolTextResultWithIsError(string(body), isError)+ if structured, ok := ToolStructuredContentFromJSON(body); ok {+ result.StructuredContent = structured+ }+ return result.NormalizeCollections()+}++// NewToolHTTPTextResult wraps an upstream Pulse HTTP response body as the tool+// content result while preserving non-2xx status as isError=true.+func NewToolHTTPTextResult(body []byte, statusCode int) ToolResult {+ return newToolTextResultFromBody(body, statusCode < 200 || statusCode >= 300)+}++// NewCapabilityHTTPToolResult wraps a manifest capability HTTP response as a+// tool result. The full HTTPCallResponse stays in this shared package so+// adapters do not duplicate the status-to-isError interpretation.+func NewCapabilityHTTPToolResult(resp HTTPCallResponse) ToolResult {+ return newToolTextResultFromBody(resp.Body, !resp.OK())+}++func newToolTextResultFromBody(body []byte, isError bool) ToolResult {+ result := NewToolTextResultWithIsError(string(body), isError)+ if structured, ok := ToolStructuredContentFromJSON(body); ok {+ result.StructuredContent = structured+ }+ return result.NormalizeCollections()+}++// ToolStructuredContentFromJSON returns an MCP-compatible structured content+// object for JSON object payloads. JSON array payloads are wrapped as+// {"items":[...],"count":n} because MCP structuredContent is object-shaped,+// while Pulse's list endpoints intentionally keep their raw array text body for+// legacy clients.+func ToolStructuredContentFromJSON(raw []byte) (map[string]any, bool) {+ trimmed := bytes.TrimSpace(raw)+ if len(trimmed) == 0 {+ return nil, false+ }++ dec := json.NewDecoder(bytes.NewReader(trimmed))+ dec.UseNumber()+ switch trimmed[0] {+ case '{':+ var structured map[string]any+ if err := dec.Decode(&structured); err != nil || structured == nil {+ return nil, false+ }+ var trailing any+ if err := dec.Decode(&trailing); err != io.EOF {+ return nil, false+ }+ return CloneToolStructuredContent(structured), true+ case '[':+ var items []any+ if err := dec.Decode(&items); err != nil || items == nil {+ return nil, false+ }+ var trailing any+ if err := dec.Decode(&trailing); err != io.EOF {+ return nil, false+ }+ return CloneToolStructuredContent(map[string]any{+ "items": items,+ "count": len(items),+ }), true+ default:+ return nil, false+ }+}++// CloneToolStructuredContent returns an independent JSON-like object for shared+// tool results crossing Assistant, MCP, and API boundaries.+func CloneToolStructuredContent(content map[string]any) map[string]any {+ if content == nil {+ return nil+ }+ cloned := make(map[string]any, len(content))+ for key, value := range content {+ cloned[key] = cloneSchemaValue(value)+ }+ return cloned+}++// ToolResultText joins text content blocks from a shared tool result for+// provider context and display surfaces. Non-text content blocks stay available+// on the structured envelope but are intentionally not flattened here.+func ToolResultText(result ToolResult) string {+ if len(result.Content) == 0 {+ return ""+ }++ var text strings.Builder+ for _, c := range result.Content {+ if c.Type != "text" || c.Text == "" {+ continue+ }+ if text.Len() > 0 {+ text.WriteByte('\n')+ }+ text.WriteString(c.Text)+ }+ return text.String()+}++// ToolResultInterpretation is the shared flattened view of a tool result used+// by native Assistant execution paths and external-agent adapters that need to+// branch on the legacy-compatible tool marker vocabulary.+type ToolResultInterpretation struct {+ Text string+ IsError bool+ ApprovalRequired bool+ PolicyBlocked bool+}++// InterpretToolResult flattens text content and detects the shared+// approval-required and policy-blocked markers in one place so callers do not+// duplicate marker prefix checks around ToolResultText.+func InterpretToolResult(result ToolResult) ToolResultInterpretation {+ text := ToolResultText(result)+ return ToolResultInterpretation{+ Text: text,+ IsError: result.IsError,+ ApprovalRequired: HasApprovalRequiredToolMarker(text),+ PolicyBlocked: HasPolicyBlockedToolMarker(text),+ }+}diff --git a/internal/agentcapabilities/types.go b/internal/agentcapabilities/types.gonew file mode 100644index 0000000000..4a242202b6--- /dev/null+++ b/internal/agentcapabilities/types.go@@ -0,0 +1,423 @@+package agentcapabilities++import (+ "encoding/json"+ "net/http"+ "strings"+)++// ActionMode tells agents whether a capability or tool reads state, can run a+// non-persistent check/scan, or changes Pulse or target-side state.+type ActionMode string++// ApprovalPolicy tells external agents whether the required scope is sufficient+// or whether the capability participates in Pulse's governed action-plan+// lifecycle.+type ApprovalPolicy string++const (+ ActionModeRead ActionMode = "read"+ ActionModeMixed ActionMode = "mixed"+ ActionModeWrite ActionMode = "write"++ ApprovalPolicyScopeOnly ApprovalPolicy = "scope_only"+ ApprovalPolicyActionPlan ApprovalPolicy = "action_plan"+)++// ControlToolsDisabledMessage is the stable operator guidance returned when a+// caller attempts to run a control-gated Assistant tool while the shared control+// level is read-only or otherwise not allowed to expose control tools.+const ControlToolsDisabledMessage = "Control tools are disabled. Open Assistant & Patrol settings, then set Pulse Assistant Permissions > Control mode to Controlled before using action tools."++// DefaultApprovalPolicyDescription returns a concise operator-facing+// explanation for a shared approval-policy value.+func DefaultApprovalPolicyDescription(policy ApprovalPolicy) string {+ switch policy {+ case ApprovalPolicyScopeOnly:+ return "required scope is sufficient; no action-plan approval is required"+ case ApprovalPolicyActionPlan:+ return "governed action-plan approval is required before execution"+ default:+ return ""+ }+}++// NormalizeToolGovernance fills the shared governance defaults for a tool+// definition. Assistant registry tools and external-agent projections use this+// instead of carrying their own action-mode and approval-policy fallback rules.+func NormalizeToolGovernance(governance ToolGovernance, requireControl bool, description string) ToolGovernance {+ if governance.ActionMode == "" {+ if requireControl {+ governance.ActionMode = ActionModeWrite+ } else {+ governance.ActionMode = ActionModeRead+ }+ }+ if governance.ApprovalPolicy == "" {+ if governance.ActionMode == ActionModeRead {+ governance.ApprovalPolicy = ApprovalPolicyScopeOnly+ } else if requireControl {+ governance.ApprovalPolicy = ApprovalPolicyActionPlan+ } else {+ governance.ApprovalPolicy = ApprovalPolicyScopeOnly+ }+ }+ if governance.ApprovalSummary == "" {+ if governance.ActionMode == ActionModeRead {+ governance.ApprovalSummary = "no approval required"+ } else if requireControl {+ governance.ApprovalSummary = "hidden in read-only mode; approval required in controlled mode"+ } else if desc := DefaultApprovalPolicyDescription(governance.ApprovalPolicy); desc != "" {+ governance.ApprovalSummary = desc+ } else {+ governance.ApprovalSummary = "write subactions require the tool's governed approval path"+ }+ }+ if governance.Summary == "" {+ governance.Summary = description+ }+ return governance+}++// NormalizeCapabilityGovernance fills the shared governance defaults for a+// manifest capability. Capability projections use HTTP method only as a fallback+// when the manifest has not declared an explicit action mode; the manifest-owned+// actionMode and approvalPolicy remain authoritative when present.+func NormalizeCapabilityGovernance(cap Capability) ToolGovernance {+ governance := ToolGovernance{+ ActionMode: CapabilityActionMode(cap),+ ApprovalPolicy: cap.ApprovalPolicy,+ Summary: cap.Description,+ }+ return NormalizeToolGovernance(governance, false, cap.Description)+}++// CapabilityActionMode returns the shared action mode for a manifest+// capability, preserving explicit read/mixed/write values and using method+// posture only as a compatibility fallback for incomplete manifests.+func CapabilityActionMode(cap Capability) ActionMode {+ switch mode := ActionMode(strings.TrimSpace(string(cap.ActionMode))); mode {+ case ActionModeRead, ActionModeMixed, ActionModeWrite:+ return mode+ }+ if strings.EqualFold(cap.Method, http.MethodGet) {+ return ActionModeRead+ }+ return ActionModeWrite+}++// NewToolGovernanceDescriptor builds the shared read-only governance descriptor+// for a registered tool after applying the canonical defaults.+func NewToolGovernanceDescriptor(name, description string, requireControl bool, governance ToolGovernance) ToolGovernanceDescriptor {+ normalized := NormalizeToolGovernance(governance, requireControl, description)+ return ToolGovernanceDescriptor{+ Name: name,+ Description: description,+ RequireControl: requireControl,+ ActionMode: normalized.ActionMode,+ ApprovalPolicy: normalized.ApprovalPolicy,+ ApprovalSummary: normalized.ApprovalSummary,+ Summary: normalized.Summary,+ }+}++// NormalizeToolGovernanceDescriptor applies the shared governance defaults to+// an existing descriptor without changing its identity or control-gating flag.+func NormalizeToolGovernanceDescriptor(descriptor ToolGovernanceDescriptor) ToolGovernanceDescriptor {+ return NewToolGovernanceDescriptor(descriptor.Name, descriptor.Description, descriptor.RequireControl, ToolGovernance{+ ActionMode: descriptor.ActionMode,+ ApprovalPolicy: descriptor.ApprovalPolicy,+ ApprovalSummary: descriptor.ApprovalSummary,+ Summary: descriptor.Summary,+ })+}++// ToolGovernance records the governed posture for a structured tool. Concrete+// surfaces own handlers and availability, while this shared shape keeps+// Assistant prompts and external-agent projections on the same action and+// approval vocabulary.+type ToolGovernance struct {+ ActionMode ActionMode+ ApprovalPolicy ApprovalPolicy+ ApprovalSummary string+ Summary string+}++// ToolGovernanceDescriptor is the read-only tool governance manifest surfaced+// to agents and Assistant prompt builders.+type ToolGovernanceDescriptor struct {+ Name string `json:"name"`+ Description string `json:"description,omitempty"`+ RequireControl bool `json:"requireControl,omitempty"`+ ActionMode ActionMode `json:"actionMode"`+ ApprovalPolicy ApprovalPolicy `json:"approvalPolicy"`+ ApprovalSummary string `json:"approvalSummary,omitempty"`+ Summary string `json:"summary,omitempty"`+}++// Capability declares one agent-consumable Pulse capability: what it does,+// which canonical HTTP route it calls, which scope it needs, how it is governed,+// and which stable error codes agents can branch on. The shape is intentionally+// narrow so MCP, in-app Assistant, and future external-agent adapters can+// project the same manifest without a second local registry.+type Capability struct {+ // Name is the agent-stable snake_case identifier. Renaming breaks+ // integrations and requires a manifest-version decision.+ Name string `json:"name"`++ // Title is the human-readable display name for agent clients. Name remains+ // the programmatic identifier; UI, docs, and MCP tool titles use this field.+ Title string `json:"title,omitempty"`++ // Description is a single-sentence explanation an agent can surface when+ // deciding whether to call this capability.+ Description string `json:"description"`++ // Category groups capabilities for agent UIs. Stable values include+ // "context", "provisioning", "operator-state", "finding", and "action".+ Category string `json:"category"`++ // Method and Path describe the canonical REST surface. Path segments in+ // braces are agent-supplied parameters and must be percent-encoded as+ // single path segments by adapters.+ Method string `json:"method"`+ Path string `json:"path"`++ // Scope names the auth scope required to call this capability.+ Scope string `json:"scope"`++ // ActionMode tells agents whether the capability reads state, can run a+ // non-persistent check/scan, or changes Pulse or target-side state.+ ActionMode ActionMode `json:"actionMode"`++ // ApprovalPolicy tells agents whether the required scope is sufficient or+ // whether the capability participates in the governed action-plan lifecycle.+ ApprovalPolicy ApprovalPolicy `json:"approvalPolicy"`++ // ResponseShape is the agent-stable response type name.+ ResponseShape string `json:"responseShape,omitempty"`++ // OutputSchema is an optional JSON Schema for the structured result object+ // returned by request/response tools. It is raw JSON so the API can serve it+ // verbatim and MCP adapters can forward the exact same schema.+ OutputSchema json.RawMessage `json:"outputSchema,omitempty"`++ // ErrorCodes is the closed set of stable error codes this capability may+ // return on failure. Agents branch on these, not on human messages.+ ErrorCodes []string `json:"errorCodes,omitempty"`++ // RequestBodyShape names the agent-stable request body shape for non-GET+ // capabilities.+ RequestBodyShape string `json:"requestBodyShape,omitempty"`++ // InputSchema is an optional JSON Schema for agent-facing tool arguments.+ // It is raw JSON so the API can serve it verbatim and adapters can forward+ // the exact same schema.+ InputSchema json.RawMessage `json:"inputSchema,omitempty"`+}++// CapabilityCategory describes one manifest-owned capability group for agent+// UIs and generated MCP docs. The category IDs on individual capabilities must+// refer to this vocabulary.+type CapabilityCategory struct {+ ID string `json:"id"`+ Label string `json:"label"`+ Description string `json:"description,omitempty"`+}++// SurfaceContractComponent names one singular part of the shared Pulse+// Intelligence runtime contract, such as the shared core or primary built-in+// operator.+type SurfaceContractComponent struct {+ ID string `json:"id"`+ Label string `json:"label"`+ Description string `json:"description"`+}++// SurfaceAffordanceContract declares which Pulse Intelligence affordances a+// supported operator-facing surface owns. The manifest carries these booleans+// so Assistant, MCP, docs, and settings UI do not hand-maintain separate+// surface capability claims.+type SurfaceAffordanceContract struct {+ Tools bool `json:"tools,omitempty"`+ Resources bool `json:"resources,omitempty"`+ Prompts bool `json:"prompts,omitempty"`+ CapabilityMetadata bool `json:"capabilityMetadata,omitempty"`+ InteractiveQuestions bool `json:"interactiveQuestions,omitempty"`+}++// OperatorSurfaceContract describes one supported access path over the shared+// Pulse Intelligence Core. The JSON name remains operatorSurfaces for v1+// manifest compatibility.+type OperatorSurfaceContract struct {+ ID string `json:"id"`+ Label string `json:"label"`+ Description string `json:"description"`+ Native bool `json:"native"`+ ExternalAdapter bool `json:"externalAdapter"`+ Affordances SurfaceAffordanceContract `json:"affordances,omitempty"`+}++// SurfaceContract pins the runtime relationship between the shared Pulse+// Intelligence Core, the primary built-in Patrol operator, and the supported+// access paths. External agents consume this from the same discovery manifest+// as tool capabilities so Pulse MCP cannot drift into a separate product+// contract.+type SurfaceContract struct {+ Core SurfaceContractComponent `json:"core"`+ ProactiveEngine SurfaceContractComponent `json:"proactiveEngine"`+ OperatorSurfaces []OperatorSurfaceContract `json:"operatorSurfaces"`+}++// MCPAdapterConfigFamily describes one client configuration shape supported by+// the Pulse MCP adapter. Client labels are examples for operator-facing copy;+// Shape is the stable formatter key used by docs and UI projections.+type MCPAdapterConfigFamily struct {+ ID string `json:"id"`+ Label string `json:"label"`+ Shape string `json:"shape"`+ Description string `json:"description,omitempty"`+ FileHints []string `json:"fileHints,omitempty"`+ ClientLabels []string `json:"clientLabels,omitempty"`+}++// MCPAdapterContract pins the runtime facts that every Pulse MCP client setup+// must share. Keeping these values in the manifest prevents the first-party UI,+// README generation, and external adapters from hand-maintaining separate+// command, flag, token, and config-shape copies.+type MCPAdapterContract struct {+ ServerName string `json:"serverName"`+ Command string `json:"command"`+ BaseURLFlag string `json:"baseUrlFlag"`+ DefaultBaseURL string `json:"defaultBaseUrl"`+ TokenEnv string `json:"tokenEnv"`+ ConfigFamilies []MCPAdapterConfigFamily `json:"configFamilies"`+}++// Manifest is the discovery document for Pulse's agent surface. The API serves+// this shape directly, while adapters such as pulse-mcp and agent-probe consume+// the same type rather than maintaining local wire-shape copies.+type Manifest struct {+ Version string `json:"version"`++ // SurfaceContract is the canonical product/runtime relationship for Pulse+ // Intelligence surfaces. It keeps first-party Assistant, external-agent MCP,+ // and proactive Patrol wording coupled to the same discovery contract as the+ // manifest-backed tools.+ SurfaceContract SurfaceContract `json:"surfaceContract"`++ // SurfaceToolContracts is the manifest-owned static tool posture for+ // external-agent adapters. Native Assistant live tool availability is+ // runtime-specific and stays behind the authenticated Assistant endpoint.+ SurfaceToolContracts []SurfaceToolContract `json:"surfaceToolContracts"`++ // MCPAdapter is the canonical setup contract for the Pulse MCP adapter:+ // server name, command, base URL flag/default, token environment variable,+ // and the supported client configuration families.+ MCPAdapter MCPAdapterContract `json:"mcpAdapter"`++ // RequiredScopes is the canonical deduplicated scope set needed to use every+ // currently declared capability.+ RequiredScopes []string `json:"requiredScopes"`++ // Categories is the manifest-owned presentation order and copy for+ // capability groups. First-party UI, MCP docs, and external clients consume+ // this instead of carrying local category tables.+ Categories []CapabilityCategory `json:"categories"`++ // WorkflowPrompts is the manifest-owned reusable workflow starter metadata.+ // Native Assistant surfaces and external MCP clients consume this same list+ // instead of maintaining prompt catalogues per surface.+ WorkflowPrompts []PulseWorkflowPrompt `json:"workflowPrompts"`++ Capabilities []Capability `json:"capabilities"`+}++// CloneCapability returns a detached capability descriptor so callers cannot+// mutate manifest-owned collection fields through a lookup or projection result.+func CloneCapability(cap Capability) Capability {+ if len(cap.ErrorCodes) > 0 {+ cap.ErrorCodes = append([]string(nil), cap.ErrorCodes...)+ }+ cap.InputSchema = CloneRawMessage(cap.InputSchema)+ cap.OutputSchema = CloneRawMessage(cap.OutputSchema)+ return cap+}++// CloneCapabilities returns detached capability descriptors in the original+// order.+func CloneCapabilities(capabilities []Capability) []Capability {+ if capabilities == nil {+ return nil+ }+ cloned := make([]Capability, len(capabilities))+ for i, cap := range capabilities {+ cloned[i] = CloneCapability(cap)+ }+ return cloned+}++// CloneCapabilityCategories returns detached capability-category descriptors in+// the original manifest order.+func CloneCapabilityCategories(categories []CapabilityCategory) []CapabilityCategory {+ if categories == nil {+ return nil+ }+ cloned := make([]CapabilityCategory, len(categories))+ copy(cloned, categories)+ return cloned+}++// ClonePulseWorkflowPrompt returns a detached workflow prompt descriptor.+func ClonePulseWorkflowPrompt(prompt PulseWorkflowPrompt) PulseWorkflowPrompt {+ prompt.Arguments = append([]PulseWorkflowPromptArgument(nil), prompt.Arguments...)+ return prompt.NormalizeCollections()+}++// ClonePulseWorkflowPrompts returns detached workflow prompt descriptors in the+// original projection order.+func ClonePulseWorkflowPrompts(prompts []PulseWorkflowPrompt) []PulseWorkflowPrompt {+ if prompts == nil {+ return nil+ }+ cloned := make([]PulseWorkflowPrompt, len(prompts))+ for i, prompt := range prompts {+ cloned[i] = ClonePulseWorkflowPrompt(prompt)+ }+ return cloned+}++// CloneSurfaceContract returns a detached copy of the manifest surface+// relationship contract.+func CloneSurfaceContract(contract SurfaceContract) SurfaceContract {+ if contract.OperatorSurfaces != nil {+ contract.OperatorSurfaces = append([]OperatorSurfaceContract(nil), contract.OperatorSurfaces...)+ }+ return contract+}++// CloneMCPAdapterConfigFamilies returns detached MCP adapter configuration+// family descriptors.+func CloneMCPAdapterConfigFamilies(families []MCPAdapterConfigFamily) []MCPAdapterConfigFamily {+ if families == nil {+ return nil+ }+ cloned := make([]MCPAdapterConfigFamily, len(families))+ for i, family := range families {+ cloned[i] = family+ if family.FileHints != nil {+ cloned[i].FileHints = append([]string(nil), family.FileHints...)+ }+ if family.ClientLabels != nil {+ cloned[i].ClientLabels = append([]string(nil), family.ClientLabels...)+ }+ }+ return cloned+}++// CloneMCPAdapterContract returns a detached copy of the manifest-owned Pulse+// MCP adapter setup contract.+func CloneMCPAdapterContract(contract MCPAdapterContract) MCPAdapterContract {+ contract.ConfigFamilies = CloneMCPAdapterConfigFamilies(contract.ConfigFamilies)+ return contract+}diff --git a/internal/agentcapabilities/types_test.go b/internal/agentcapabilities/types_test.gonew file mode 100644index 0000000000..0ff1809c9f--- /dev/null+++ b/internal/agentcapabilities/types_test.go@@ -0,0 +1,150 @@+package agentcapabilities++import (+ "net/http"+ "strings"+ "testing"+)++func TestDefaultApprovalPolicyDescriptionUsesSharedPolicyVocabulary(t *testing.T) {+ cases := []struct {+ policy ApprovalPolicy+ want string+ }{+ {ApprovalPolicyScopeOnly, "required scope is sufficient"},+ {ApprovalPolicyActionPlan, "governed action-plan approval is required"},+ {ApprovalPolicy("custom"), ""},+ }++ for _, tc := range cases {+ got := DefaultApprovalPolicyDescription(tc.policy)+ if tc.want == "" {+ if got != "" {+ t.Fatalf("DefaultApprovalPolicyDescription(%q) = %q, want empty", tc.policy, got)+ }+ continue+ }+ if got == "" || !strings.Contains(got, tc.want) {+ t.Fatalf("DefaultApprovalPolicyDescription(%q) = %q, want substring %q", tc.policy, got, tc.want)+ }+ }+}++func TestToolGovernanceDescriptorUsesSharedVocabulary(t *testing.T) {+ descriptor := ToolGovernanceDescriptor{+ Name: "pulse_control",+ Description: "Run governed control actions.",+ RequireControl: true,+ ActionMode: ActionModeWrite,+ ApprovalPolicy: ApprovalPolicyActionPlan,+ ApprovalSummary: "approval required in controlled mode",+ Summary: "Runs shared Pulse control actions.",+ }++ if descriptor.ActionMode != ActionModeWrite {+ t.Fatalf("descriptor action mode = %q, want %q", descriptor.ActionMode, ActionModeWrite)+ }+ if descriptor.ApprovalPolicy != ApprovalPolicyActionPlan {+ t.Fatalf("descriptor approval policy = %q, want %q", descriptor.ApprovalPolicy, ApprovalPolicyActionPlan)+ }+ if !descriptor.RequireControl {+ t.Fatal("descriptor must preserve Assistant control gating")+ }+}++func TestNormalizeToolGovernanceAppliesSharedDefaults(t *testing.T) {+ read := NormalizeToolGovernance(ToolGovernance{}, false, "Read state.")+ if read.ActionMode != ActionModeRead {+ t.Fatalf("read action mode = %q, want %q", read.ActionMode, ActionModeRead)+ }+ if read.ApprovalPolicy != ApprovalPolicyScopeOnly {+ t.Fatalf("read approval policy = %q, want %q", read.ApprovalPolicy, ApprovalPolicyScopeOnly)+ }+ if read.ApprovalSummary != "no approval required" {+ t.Fatalf("read approval summary = %q", read.ApprovalSummary)+ }+ if read.Summary != "Read state." {+ t.Fatalf("read summary = %q", read.Summary)+ }++ control := NormalizeToolGovernance(ToolGovernance{}, true, "Run actions.")+ if control.ActionMode != ActionModeWrite {+ t.Fatalf("control action mode = %q, want %q", control.ActionMode, ActionModeWrite)+ }+ if control.ApprovalPolicy != ApprovalPolicyActionPlan {+ t.Fatalf("control approval policy = %q, want %q", control.ApprovalPolicy, ApprovalPolicyActionPlan)+ }+ if control.ApprovalSummary != "hidden in read-only mode; approval required in controlled mode" {+ t.Fatalf("control approval summary = %q", control.ApprovalSummary)+ }++ mixed := NormalizeToolGovernance(ToolGovernance{ActionMode: ActionModeMixed}, false, "Mixed actions.")+ if mixed.ApprovalPolicy != ApprovalPolicyScopeOnly {+ t.Fatalf("mixed approval policy = %q, want %q", mixed.ApprovalPolicy, ApprovalPolicyScopeOnly)+ }+ if !strings.Contains(mixed.ApprovalSummary, "required scope is sufficient") {+ t.Fatalf("mixed approval summary = %q", mixed.ApprovalSummary)+ }+}++func TestNormalizeCapabilityGovernanceAppliesSharedDefaults(t *testing.T) {+ read := NormalizeCapabilityGovernance(Capability{+ Description: "Read capability.",+ Method: http.MethodGet,+ })+ if read.ActionMode != ActionModeRead {+ t.Fatalf("read capability action mode = %q, want %q", read.ActionMode, ActionModeRead)+ }+ if read.ApprovalPolicy != ApprovalPolicyScopeOnly {+ t.Fatalf("read capability approval policy = %q, want %q", read.ApprovalPolicy, ApprovalPolicyScopeOnly)+ }+ if read.ApprovalSummary != "no approval required" {+ t.Fatalf("read capability approval summary = %q", read.ApprovalSummary)+ }+ if read.Summary != "Read capability." {+ t.Fatalf("read capability summary = %q", read.Summary)+ }++ write := NormalizeCapabilityGovernance(Capability{+ Description: "Write capability.",+ Method: http.MethodPost,+ })+ if write.ActionMode != ActionModeWrite {+ t.Fatalf("write capability action mode = %q, want %q", write.ActionMode, ActionModeWrite)+ }+ if write.ApprovalPolicy != ApprovalPolicyScopeOnly {+ t.Fatalf("write capability approval policy = %q, want %q", write.ApprovalPolicy, ApprovalPolicyScopeOnly)+ }++ planned := NormalizeCapabilityGovernance(Capability{+ Description: "Plan an action.",+ Method: http.MethodPost,+ ActionMode: ActionModeMixed,+ ApprovalPolicy: ApprovalPolicyActionPlan,+ })+ if planned.ActionMode != ActionModeMixed {+ t.Fatalf("explicit capability action mode = %q, want %q", planned.ActionMode, ActionModeMixed)+ }+ if planned.ApprovalPolicy != ApprovalPolicyActionPlan {+ t.Fatalf("explicit capability approval policy = %q, want %q", planned.ApprovalPolicy, ApprovalPolicyActionPlan)+ }+ if !strings.Contains(planned.ApprovalSummary, "governed action-plan approval is required") {+ t.Fatalf("explicit capability approval summary = %q", planned.ApprovalSummary)+ }+}++func TestNewToolGovernanceDescriptorAppliesSharedDefaults(t *testing.T) {+ descriptor := NewToolGovernanceDescriptor("pulse_control", "Run actions.", true, ToolGovernance{})+ if descriptor.Name != "pulse_control" || descriptor.Description != "Run actions." {+ t.Fatalf("descriptor identity = %+v", descriptor)+ }+ if !descriptor.RequireControl {+ t.Fatal("descriptor must preserve control gating")+ }+ if descriptor.ActionMode != ActionModeWrite || descriptor.ApprovalPolicy != ApprovalPolicyActionPlan {+ t.Fatalf("descriptor governance = %+v", descriptor)+ }+ if descriptor.ApprovalSummary != "hidden in read-only mode; approval required in controlled mode" {+ t.Fatalf("descriptor approval summary = %q", descriptor.ApprovalSummary)+ }+}diff --git a/internal/agentcapabilities/workflow_prompt.go b/internal/agentcapabilities/workflow_prompt.gonew file mode 100644index 0000000000..f74e47ecf8--- /dev/null+++ b/internal/agentcapabilities/workflow_prompt.go@@ -0,0 +1,263 @@+package agentcapabilities++import (+ "fmt"+ "strings"+)++const (+ PulseWorkflowPromptTriageFleet = "pulse_triage_fleet"+ PulseWorkflowPromptInvestigateResource = "pulse_investigate_resource"+ PulseWorkflowPromptReviewFinding = "pulse_review_finding"+ PulseWorkflowPromptOperationsLoop = "pulse_operations_loop"++ PulseWorkflowPromptPresentationFleet = "fleet"+ PulseWorkflowPromptPresentationResource = "resource"+ PulseWorkflowPromptPresentationFinding = "finding"+ PulseWorkflowPromptPresentationWorkflow = "workflow"++ // Compatibility aliases for MCP callers that already refer to the prompt+ // names through the protocol projection package.+ MCPPromptTriageFleet = PulseWorkflowPromptTriageFleet+ MCPPromptInvestigateResource = PulseWorkflowPromptInvestigateResource+ MCPPromptReviewFinding = PulseWorkflowPromptReviewFinding+ MCPPromptOperationsLoop = PulseWorkflowPromptOperationsLoop+)++// PulseWorkflowPrompt describes a reusable Pulse Intelligence workflow starter.+// Protocol surfaces such as MCP project this neutral shape into their own wire+// structs instead of owning separate workflow catalogues.+type PulseWorkflowPrompt struct {+ Name string `json:"name"`+ Label string `json:"label,omitempty"`+ PresentationKind string `json:"presentationKind,omitempty"`+ Description string `json:"description,omitempty"`+ Arguments []PulseWorkflowPromptArgument `json:"arguments,omitempty"`+}++// NormalizeCollections returns a prompt with detached argument metadata.+func (p PulseWorkflowPrompt) NormalizeCollections() PulseWorkflowPrompt {+ p.Name = strings.TrimSpace(p.Name)+ p.Label = strings.TrimSpace(p.Label)+ p.PresentationKind = strings.TrimSpace(p.PresentationKind)+ p.Description = strings.TrimSpace(p.Description)+ p.Arguments = append([]PulseWorkflowPromptArgument(nil), p.Arguments...)+ if p.Arguments == nil {+ p.Arguments = []PulseWorkflowPromptArgument{}+ }+ return p+}++// PulseWorkflowPromptArgument describes an argument for a reusable workflow+// starter.+type PulseWorkflowPromptArgument struct {+ Name string `json:"name"`+ Description string `json:"description,omitempty"`+ Required bool `json:"required,omitempty"`+}++// PulseWorkflowPromptParams names one workflow prompt and supplies its+// string-valued arguments.+type PulseWorkflowPromptParams struct {+ Name string+ Arguments map[string]string+}++// NormalizeCollections returns detached workflow prompt params with stable+// argument maps.+func (p PulseWorkflowPromptParams) NormalizeCollections() PulseWorkflowPromptParams {+ p.Name = strings.TrimSpace(p.Name)+ if p.Arguments == nil {+ p.Arguments = map[string]string{}+ return p+ }+ args := make(map[string]string, len(p.Arguments))+ for k, v := range p.Arguments {+ args[k] = v+ }+ p.Arguments = args+ return p+}++// PulseWorkflowPromptResult is a rendered workflow starter before any protocol+// surface wraps it in its own message/content envelope.+type PulseWorkflowPromptResult struct {+ Description string+ Text string+}++// PulseWorkflowPromptRenderOptions lets protocol surfaces add affordance-+// specific access hints while leaving the workflow decision tree in the shared+// Pulse Intelligence contract.+type PulseWorkflowPromptRenderOptions struct {+ ResourceContextInstruction func(resourceID string) string+}++// ManifestPulseWorkflowPrompts returns the manifest-owned workflow prompt+// catalogue. Older manifests that predate workflowPrompts are projected from+// capabilities for compatibility, but present workflowPrompts always win.+func ManifestPulseWorkflowPrompts(manifest Manifest) []PulseWorkflowPrompt {+ if manifest.WorkflowPrompts != nil {+ return ClonePulseWorkflowPrompts(manifest.WorkflowPrompts)+ }+ return ProjectPulseWorkflowPrompts(manifest.Capabilities)+}++// ProjectPulseWorkflowPrompts projects canonical manifest capabilities into+// reusable Pulse Intelligence workflow starters. The prompts contain no separate+// business logic; they guide agents toward the same capability names and+// resource identities already advertised by the manifest.+func ProjectPulseWorkflowPrompts(capabilities []Capability) []PulseWorkflowPrompt {+ prompts := []PulseWorkflowPrompt{}+ if _, ok := FindCapability(capabilities, FleetContextCapabilityName); ok {+ prompts = append(prompts, PulseWorkflowPrompt{+ Name: PulseWorkflowPromptTriageFleet,+ Label: "Triage fleet",+ PresentationKind: PulseWorkflowPromptPresentationFleet,+ Description: "Triage the Pulse fleet using the canonical fleet context capability, then choose where deeper investigation is warranted.",+ })+ }+ if pulseOperationsLoopPromptAvailable(capabilities) {+ prompts = append(prompts, PulseWorkflowPrompt{+ Name: PulseWorkflowPromptOperationsLoop,+ Label: "Ask Patrol to handle an issue",+ PresentationKind: PulseWorkflowPromptPresentationWorkflow,+ Description: "Have Patrol investigate active findings, follow the configured Patrol mode, take approved actions, verify the outcome, and record what happened.",+ })+ }+ if _, ok := FindCapability(capabilities, ResourceContextCapabilityName); ok {+ prompts = append(prompts, PulseWorkflowPrompt{+ Name: PulseWorkflowPromptInvestigateResource,+ Label: "Investigate resource",+ PresentationKind: PulseWorkflowPromptPresentationResource,+ Description: "Investigate one Pulse resource using the canonical resource context capability and resource URI projection.",+ Arguments: []PulseWorkflowPromptArgument{{+ Name: ResourceIDArgumentName,+ Description: "Canonical Pulse resource id, such as vm:101.",+ Required: true,+ }},+ })+ }+ if _, ok := FindCapability(capabilities, ListFindingsCapabilityName); ok {+ prompts = append(prompts, PulseWorkflowPrompt{+ Name: PulseWorkflowPromptReviewFinding,+ Label: "Review finding",+ PresentationKind: PulseWorkflowPromptPresentationFinding,+ Description: "Review one Patrol finding and propose the safest governed next step.",+ Arguments: []PulseWorkflowPromptArgument{{+ Name: FindingIDArgumentName,+ Description: "Patrol finding id returned by " + ListFindingsCapabilityName + ".",+ Required: true,+ }},+ })+ }+ for i := range prompts {+ prompts[i] = prompts[i].NormalizeCollections()+ }+ return prompts+}++// BuildPulseWorkflowPrompt renders one shared workflow prompt from canonical+// manifest capabilities and caller-supplied string arguments. It is the+// compatibility entrypoint for older callers that predate manifest-owned+// workflowPrompts; new surface projections should pass the full manifest to+// BuildPulseWorkflowPromptFromManifest.+func BuildPulseWorkflowPrompt(capabilities []Capability, params PulseWorkflowPromptParams) (PulseWorkflowPromptResult, error) {+ return BuildPulseWorkflowPromptWithOptions(capabilities, params, PulseWorkflowPromptRenderOptions{})+}++// BuildPulseWorkflowPromptWithOptions renders one shared workflow prompt with+// optional surface-specific affordance hints. It keeps older capability-backed+// callers on the legacy fallback projection; manifest-backed surfaces should use+// BuildPulseWorkflowPromptFromManifestWithOptions.+func BuildPulseWorkflowPromptWithOptions(capabilities []Capability, params PulseWorkflowPromptParams, opts PulseWorkflowPromptRenderOptions) (PulseWorkflowPromptResult, error) {+ return BuildPulseWorkflowPromptFromManifestWithOptions(Manifest{Capabilities: capabilities}, params, opts)+}++// BuildPulseWorkflowPromptFromManifest renders one manifest-declared shared+// workflow prompt with caller-supplied string arguments.+func BuildPulseWorkflowPromptFromManifest(manifest Manifest, params PulseWorkflowPromptParams) (PulseWorkflowPromptResult, error) {+ return BuildPulseWorkflowPromptFromManifestWithOptions(manifest, params, PulseWorkflowPromptRenderOptions{})+}++// BuildPulseWorkflowPromptFromManifestWithOptions renders one shared workflow+// prompt after resolving availability from manifest-owned workflowPrompts.+func BuildPulseWorkflowPromptFromManifestWithOptions(manifest Manifest, params PulseWorkflowPromptParams, opts PulseWorkflowPromptRenderOptions) (PulseWorkflowPromptResult, error) {+ params = params.NormalizeCollections()+ if !pulseWorkflowPromptDeclared(ManifestPulseWorkflowPrompts(manifest), params.Name) {+ return PulseWorkflowPromptResult{}, fmt.Errorf("unknown prompt: %s", params.Name)+ }+ return buildPulseWorkflowPrompt(params, opts)+}++func buildPulseWorkflowPrompt(params PulseWorkflowPromptParams, opts PulseWorkflowPromptRenderOptions) (PulseWorkflowPromptResult, error) {+ switch params.Name {+ case PulseWorkflowPromptTriageFleet:+ return PulseWorkflowPromptResult{+ Description: "Pulse fleet triage",+ Text: "Use get_fleet_context to identify resources with active findings, pending approvals, operator-state flags, or stale action history. Then choose the highest-risk resource and read deeper context before recommending any write action. Summarize what needs attention, why it matters, and the safest next governed step.",+ }, nil+ case PulseWorkflowPromptInvestigateResource:+ resourceID, err := RequiredPulseWorkflowPromptArgument(params.Arguments, ResourceIDArgumentName)+ if err != nil {+ return PulseWorkflowPromptResult{}, err+ }+ resourceInstruction := defaultPulseWorkflowResourceContextInstruction(resourceID)+ if opts.ResourceContextInstruction != nil {+ if custom := strings.TrimSpace(opts.ResourceContextInstruction(resourceID)); custom != "" {+ resourceInstruction = custom+ }+ }+ return PulseWorkflowPromptResult{+ Description: "Pulse resource investigation",+ Text: fmt.Sprintf("Investigate Pulse resource %q. %s. Explain current state, active findings, pending approvals, recent actions, and operator-state flags. Do not execute write tools unless the operator explicitly asks for a governed action.", resourceID, resourceInstruction),+ }, nil+ case PulseWorkflowPromptReviewFinding:+ findingID, err := RequiredPulseWorkflowPromptArgument(params.Arguments, FindingIDArgumentName)+ if err != nil {+ return PulseWorkflowPromptResult{}, err+ }+ return PulseWorkflowPromptResult{+ Description: "Pulse finding review",+ Text: fmt.Sprintf("Review Patrol finding %q. Call %s, locate that finding, then read the affected resource context when available. Explain whether to acknowledge, snooze, dismiss, resolve, or plan a governed action, and name the evidence that supports the recommendation.", findingID, ListFindingsCapabilityName),+ }, nil+ case PulseWorkflowPromptOperationsLoop:+ return PulseWorkflowPromptResult{+ Description: "Patrol issue handling",+ Text: fmt.Sprintf("Handle an infrastructure issue with Patrol. Start with %s to understand the current Patrol work status, issue evidence, pending approvals, verified outcomes, and any Assistant or external-agent handoff activity. Use %s to find active findings, pending approvals, and stale action history. Use %s for the relevant finding and %s for the affected resource before recommending any write. Explain the issue, evidence, and risk in operator language. If a governed change is warranted, call %s first and follow the returned approval policy: ask the operator only when policy requires approval, call %s to record an approval or rejection when a decision is required, and call %s only when the plan is approved or allowed without approval. After execution, re-read Patrol status, context, and findings to verify the outcome before calling %s. If the operator or policy rejects the plan, record that decision and propose the next safest follow-up without executing.", OperationsLoopStatusCapabilityName, FleetContextCapabilityName, ListFindingsCapabilityName, ResourceContextCapabilityName, PlanActionCapabilityName, DecideActionCapabilityName, ExecuteActionCapabilityName, ResolveFindingCapabilityName),+ }, nil+ }+ return PulseWorkflowPromptResult{}, fmt.Errorf("unknown prompt: %s", params.Name)+}++// RequiredPulseWorkflowPromptArgument returns a trimmed required prompt argument+// or the stable validation error shared by prompt projections.+func RequiredPulseWorkflowPromptArgument(args map[string]string, name string) (string, error) {+ value := strings.TrimSpace(args[name])+ if value == "" {+ return "", fmt.Errorf("prompt argument %s is required", name)+ }+ return value, nil+}++func pulseWorkflowPromptDeclared(prompts []PulseWorkflowPrompt, name string) bool {+ for _, prompt := range prompts {+ if prompt.Name == name {+ return true+ }+ }+ return false+}++func defaultPulseWorkflowResourceContextInstruction(resourceID string) string {+ return fmt.Sprintf("Call %s with %s %q", ResourceContextCapabilityName, ResourceIDArgumentName, resourceID)+}++func pulseOperationsLoopPromptAvailable(capabilities []Capability) bool {+ for _, name := range OperationsLoopCapabilityNames() {+ if _, ok := FindCapability(capabilities, name); !ok {+ return false+ }+ }+ return true+}diff --git a/internal/agentcapabilities/workflow_prompt_test.go b/internal/agentcapabilities/workflow_prompt_test.gonew file mode 100644index 0000000000..a50ffb75eb--- /dev/null+++ b/internal/agentcapabilities/workflow_prompt_test.go@@ -0,0 +1,219 @@+package agentcapabilities++import (+ "strings"+ "testing"+)++func TestProjectPulseWorkflowPromptsProjectsManifestCapabilities(t *testing.T) {+ got := ProjectPulseWorkflowPrompts([]Capability{+ {Name: OperationsLoopStatusCapabilityName},+ {Name: FleetContextCapabilityName},+ {Name: ResourceContextCapabilityName},+ {Name: ListFindingsCapabilityName},+ {Name: PlanActionCapabilityName},+ {Name: DecideActionCapabilityName},+ {Name: ExecuteActionCapabilityName},+ {Name: ResolveFindingCapabilityName},+ })+ if len(got) != 4 {+ t.Fatalf("workflow prompts = %+v, want four manifest-backed prompts", got)+ }++ names := map[string]PulseWorkflowPrompt{}+ for _, prompt := range got {+ names[prompt.Name] = prompt+ }+ if _, ok := names[PulseWorkflowPromptTriageFleet]; !ok {+ t.Fatalf("workflow prompts missing %s: %+v", PulseWorkflowPromptTriageFleet, got)+ }+ if names[PulseWorkflowPromptTriageFleet].Label != "Triage fleet" {+ t.Fatalf("fleet workflow prompt label = %q", names[PulseWorkflowPromptTriageFleet].Label)+ }+ if names[PulseWorkflowPromptTriageFleet].PresentationKind != PulseWorkflowPromptPresentationFleet {+ t.Fatalf("fleet workflow prompt presentation kind = %q", names[PulseWorkflowPromptTriageFleet].PresentationKind)+ }+ resourcePrompt := names[PulseWorkflowPromptInvestigateResource]+ if resourcePrompt.Label != "Investigate resource" {+ t.Fatalf("resource workflow prompt label = %q", resourcePrompt.Label)+ }+ if resourcePrompt.PresentationKind != PulseWorkflowPromptPresentationResource {+ t.Fatalf("resource workflow prompt presentation kind = %q", resourcePrompt.PresentationKind)+ }+ if len(resourcePrompt.Arguments) != 1 || resourcePrompt.Arguments[0].Name != ResourceIDArgumentName || !resourcePrompt.Arguments[0].Required {+ t.Fatalf("resource prompt arguments = %+v", resourcePrompt.Arguments)+ }+ findingPrompt := names[PulseWorkflowPromptReviewFinding]+ if findingPrompt.Label != "Review finding" {+ t.Fatalf("finding workflow prompt label = %q", findingPrompt.Label)+ }+ if findingPrompt.PresentationKind != PulseWorkflowPromptPresentationFinding {+ t.Fatalf("finding workflow prompt presentation kind = %q", findingPrompt.PresentationKind)+ }+ if len(findingPrompt.Arguments) != 1 || findingPrompt.Arguments[0].Name != FindingIDArgumentName || !findingPrompt.Arguments[0].Required {+ t.Fatalf("finding prompt arguments = %+v", findingPrompt.Arguments)+ }+ loopPrompt := names[PulseWorkflowPromptOperationsLoop]+ if loopPrompt.Label != "Ask Patrol to handle an issue" {+ t.Fatalf("operations-loop workflow prompt label = %q", loopPrompt.Label)+ }+ if loopPrompt.PresentationKind != PulseWorkflowPromptPresentationWorkflow {+ t.Fatalf("operations-loop workflow prompt presentation kind = %q", loopPrompt.PresentationKind)+ }+ if len(loopPrompt.Arguments) != 0 {+ t.Fatalf("operations-loop prompt arguments = %+v, want none", loopPrompt.Arguments)+ }+}++func TestProjectPulseWorkflowPromptsRequiresFullLoopCapabilitiesForOperationsLoop(t *testing.T) {+ partial := ProjectPulseWorkflowPrompts([]Capability{+ {Name: OperationsLoopStatusCapabilityName},+ {Name: FleetContextCapabilityName},+ {Name: ResourceContextCapabilityName},+ {Name: ListFindingsCapabilityName},+ {Name: PlanActionCapabilityName},+ {Name: DecideActionCapabilityName},+ {Name: ExecuteActionCapabilityName},+ })+ for _, prompt := range partial {+ if prompt.Name == PulseWorkflowPromptOperationsLoop {+ t.Fatalf("operations-loop prompt must not appear without resolve_finding: %+v", partial)+ }+ }+}++func TestBuildPulseWorkflowPromptRendersSharedWorkflowText(t *testing.T) {+ got, err := BuildPulseWorkflowPrompt([]Capability{{Name: FleetContextCapabilityName}}, PulseWorkflowPromptParams{Name: PulseWorkflowPromptTriageFleet})+ if err != nil {+ t.Fatalf("BuildPulseWorkflowPrompt: %v", err)+ }+ if got.Description != "Pulse fleet triage" || !strings.Contains(got.Text, "get_fleet_context") || !strings.Contains(got.Text, "safest next governed step") {+ t.Fatalf("fleet workflow prompt = %+v", got)+ }++ resource, err := BuildPulseWorkflowPrompt([]Capability{{Name: ResourceContextCapabilityName}}, PulseWorkflowPromptParams{+ Name: PulseWorkflowPromptInvestigateResource,+ Arguments: map[string]string{ResourceIDArgumentName: " vm:101 "},+ })+ if err != nil {+ t.Fatalf("BuildPulseWorkflowPrompt resource: %v", err)+ }+ for _, want := range []string{`"vm:101"`, ResourceContextCapabilityName, ResourceIDArgumentName, "Do not execute write tools"} {+ if !strings.Contains(resource.Text, want) {+ t.Fatalf("resource workflow prompt missing %q: %q", want, resource.Text)+ }+ }++ loop, err := BuildPulseWorkflowPrompt(+ []Capability{+ {Name: OperationsLoopStatusCapabilityName},+ {Name: FleetContextCapabilityName},+ {Name: ResourceContextCapabilityName},+ {Name: ListFindingsCapabilityName},+ {Name: PlanActionCapabilityName},+ {Name: DecideActionCapabilityName},+ {Name: ExecuteActionCapabilityName},+ {Name: ResolveFindingCapabilityName},+ },+ PulseWorkflowPromptParams{Name: PulseWorkflowPromptOperationsLoop},+ )+ if err != nil {+ t.Fatalf("BuildPulseWorkflowPrompt operations loop: %v", err)+ }+ for _, want := range []string{+ "Patrol issue handling",+ OperationsLoopStatusCapabilityName,+ FleetContextCapabilityName,+ ListFindingsCapabilityName,+ ResourceContextCapabilityName,+ PlanActionCapabilityName,+ "ask the operator only when policy requires approval",+ DecideActionCapabilityName,+ ExecuteActionCapabilityName,+ ResolveFindingCapabilityName,+ "without executing",+ } {+ if !strings.Contains(loop.Text, want) && !strings.Contains(loop.Description, want) {+ t.Fatalf("operations-loop workflow prompt missing %q: description=%q text=%q", want, loop.Description, loop.Text)+ }+ }+}++func TestBuildPulseWorkflowPromptFromManifestHonorsWorkflowPrompts(t *testing.T) {+ got, err := BuildPulseWorkflowPromptFromManifest(Manifest{+ WorkflowPrompts: []PulseWorkflowPrompt{{+ Name: PulseWorkflowPromptTriageFleet,+ }},+ }, PulseWorkflowPromptParams{Name: PulseWorkflowPromptTriageFleet})+ if err != nil {+ t.Fatalf("BuildPulseWorkflowPromptFromManifest declared prompt: %v", err)+ }+ if got.Description != "Pulse fleet triage" || !strings.Contains(got.Text, "get_fleet_context") {+ t.Fatalf("manifest-declared prompt = %+v", got)+ }++ _, err = BuildPulseWorkflowPromptFromManifest(Manifest{+ Capabilities: []Capability{{Name: FleetContextCapabilityName}},+ WorkflowPrompts: []PulseWorkflowPrompt{},+ }, PulseWorkflowPromptParams{Name: PulseWorkflowPromptTriageFleet})+ if err == nil || err.Error() != "unknown prompt: pulse_triage_fleet" {+ t.Fatalf("explicit empty workflowPrompts must suppress capability fallback; err=%v", err)+ }+}++func TestBuildPulseWorkflowPromptSupportsSurfaceResourceInstructions(t *testing.T) {+ got, err := BuildPulseWorkflowPromptWithOptions([]Capability{{Name: ResourceContextCapabilityName}}, PulseWorkflowPromptParams{+ Name: PulseWorkflowPromptInvestigateResource,+ Arguments: map[string]string{ResourceIDArgumentName: "vm:101"},+ }, PulseWorkflowPromptRenderOptions{+ ResourceContextInstruction: func(resourceID string) string {+ return "Use resources/read for " + resourceID+ },+ })+ if err != nil {+ t.Fatalf("BuildPulseWorkflowPromptWithOptions: %v", err)+ }+ if !strings.Contains(got.Text, "Use resources/read for vm:101") {+ t.Fatalf("surface resource instruction missing from prompt: %q", got.Text)+ }+}++func TestBuildPulseWorkflowPromptValidatesAvailabilityAndArguments(t *testing.T) {+ _, err := BuildPulseWorkflowPrompt([]Capability{{Name: ResourceContextCapabilityName}}, PulseWorkflowPromptParams{Name: PulseWorkflowPromptInvestigateResource})+ if err == nil || err.Error() != "prompt argument "+ResourceIDArgumentName+" is required" {+ t.Fatalf("missing resourceId error = %v", err)+ }++ _, err = BuildPulseWorkflowPrompt(nil, PulseWorkflowPromptParams{Name: PulseWorkflowPromptTriageFleet})+ if err == nil || err.Error() != "unknown prompt: pulse_triage_fleet" {+ t.Fatalf("unknown prompt error = %v", err)+ }++ finding, err := BuildPulseWorkflowPrompt([]Capability{{Name: ListFindingsCapabilityName}}, PulseWorkflowPromptParams{+ Name: PulseWorkflowPromptReviewFinding,+ Arguments: map[string]string{FindingIDArgumentName: " finding-1 "},+ })+ if err != nil {+ t.Fatalf("BuildPulseWorkflowPrompt finding: %v", err)+ }+ for _, want := range []string{`"finding-1"`, ListFindingsCapabilityName, "name the evidence"} {+ if !strings.Contains(finding.Text, want) {+ t.Fatalf("finding workflow prompt missing %q: %q", want, finding.Text)+ }+ }+}++func TestPulseWorkflowPromptParamsNormalizeDetachesArguments(t *testing.T) {+ source := map[string]string{ResourceIDArgumentName: "vm:101"}+ params := PulseWorkflowPromptParams{+ Name: " " + PulseWorkflowPromptInvestigateResource + " ",+ Arguments: source,+ }.NormalizeCollections()+ if params.Name != PulseWorkflowPromptInvestigateResource || params.Arguments[ResourceIDArgumentName] != "vm:101" {+ t.Fatalf("normalized prompt params = %+v", params)+ }+ params.Arguments[ResourceIDArgumentName] = "vm:102"+ if source[ResourceIDArgumentName] != "vm:101" {+ t.Fatalf("normalized prompt params aliased source: source=%+v params=%+v", source, params.Arguments)+ }+}diff --git a/internal/ai/adapters/adapters.go b/internal/ai/adapters/adapters.goindex 4e79c2e97f..9bc677ba41 100644--- a/internal/ai/adapters/adapters.go+++ b/internal/ai/adapters/adapters.go@@ -208,8 +208,8 @@ func (e *CommandExecutionDisabledError) Error() string {return "command execution is disabled - commands must be run manually"}-// IncidentRecorderMCPAdapter adapts metrics.IncidentRecorder to tools.IncidentRecorderProvider-type IncidentRecorderMCPAdapter struct {+// IncidentRecorderToolAdapter adapts metrics.IncidentRecorder to tools.IncidentRecorderProvider+type IncidentRecorderToolAdapter struct {recorder IncidentRecorderSource}@@ -250,13 +250,13 @@ type IncidentSummaryData struct {Changes map[string]float64}-// NewIncidentRecorderMCPAdapter creates a new incident recorder adapter-func NewIncidentRecorderMCPAdapter(recorder IncidentRecorderSource) *IncidentRecorderMCPAdapter {- return &IncidentRecorderMCPAdapter{recorder: recorder}+// NewIncidentRecorderToolAdapter creates a new incident recorder adapter+func NewIncidentRecorderToolAdapter(recorder IncidentRecorderSource) *IncidentRecorderToolAdapter {+ return &IncidentRecorderToolAdapter{recorder: recorder}}// GetWindowsForResource returns incident windows for a resource-func (a *IncidentRecorderMCPAdapter) GetWindowsForResource(resourceID string, limit int) []*IncidentWindowData {+func (a *IncidentRecorderToolAdapter) GetWindowsForResource(resourceID string, limit int) []*IncidentWindowData {if a.recorder == nil {return nil}@@ -264,15 +264,15 @@ func (a *IncidentRecorderMCPAdapter) GetWindowsForResource(resourceID string, li}// GetWindow returns a specific incident window-func (a *IncidentRecorderMCPAdapter) GetWindow(windowID string) *IncidentWindowData {+func (a *IncidentRecorderToolAdapter) GetWindow(windowID string) *IncidentWindowData {if a.recorder == nil {return nil}return a.recorder.GetWindow(windowID)}-// EventCorrelatorMCPAdapter adapts proxmox.EventCorrelator to tools.EventCorrelatorProvider-type EventCorrelatorMCPAdapter struct {+// EventCorrelatorToolAdapter adapts proxmox.EventCorrelator to tools.EventCorrelatorProvider+type EventCorrelatorToolAdapter struct {correlator EventCorrelatorSource}@@ -303,13 +303,13 @@ type ProxmoxEventData struct {Status string}-// NewEventCorrelatorMCPAdapter creates a new event correlator adapter-func NewEventCorrelatorMCPAdapter(correlator EventCorrelatorSource) *EventCorrelatorMCPAdapter {- return &EventCorrelatorMCPAdapter{correlator: correlator}+// NewEventCorrelatorToolAdapter creates a new event correlator adapter+func NewEventCorrelatorToolAdapter(correlator EventCorrelatorSource) *EventCorrelatorToolAdapter {+ return &EventCorrelatorToolAdapter{correlator: correlator}}// GetCorrelationsForResource returns correlated events for a resource-func (a *EventCorrelatorMCPAdapter) GetCorrelationsForResource(resourceID string, window time.Duration) []EventCorrelationData {+func (a *EventCorrelatorToolAdapter) GetCorrelationsForResource(resourceID string, window time.Duration) []EventCorrelationData {if a.correlator == nil {return nil}diff --git a/internal/ai/adapters/adapters_additional_test.go b/internal/ai/adapters/adapters_additional_test.goindex 163ae9cde5..b8454ea246 100644--- a/internal/ai/adapters/adapters_additional_test.go+++ b/internal/ai/adapters/adapters_additional_test.go@@ -106,8 +106,8 @@ func TestMetricsAdapter_GetMonitoredResourceIDs(t *testing.T) {}}-func TestIncidentRecorderMCPAdapter(t *testing.T) {- adapter := NewIncidentRecorderMCPAdapter(nil)+func TestIncidentRecorderToolAdapter(t *testing.T) {+ adapter := NewIncidentRecorderToolAdapter(nil)if adapter.GetWindowsForResource("res", 1) != nil {t.Fatalf("expected nil windows for nil recorder")}@@ -119,7 +119,7 @@ func TestIncidentRecorderMCPAdapter(t *testing.T) {windows: []*IncidentWindowData{{ID: "w1"}},window: &IncidentWindowData{ID: "w1"},}- adapter = NewIncidentRecorderMCPAdapter(recorder)+ adapter = NewIncidentRecorderToolAdapter(recorder)if len(adapter.GetWindowsForResource("res", 1)) != 1 {t.Fatalf("expected windows from recorder")}@@ -128,8 +128,8 @@ func TestIncidentRecorderMCPAdapter(t *testing.T) {}}-func TestEventCorrelatorMCPAdapter(t *testing.T) {- adapter := NewEventCorrelatorMCPAdapter(nil)+func TestEventCorrelatorToolAdapter(t *testing.T) {+ adapter := NewEventCorrelatorToolAdapter(nil)if adapter.GetCorrelationsForResource("res", time.Minute) != nil {t.Fatalf("expected nil correlations for nil correlator")}@@ -137,7 +137,7 @@ func TestEventCorrelatorMCPAdapter(t *testing.T) {correlator := &stubEventCorrelator{correlations: []EventCorrelationData{{ID: "c1"}},}- adapter = NewEventCorrelatorMCPAdapter(correlator)+ adapter = NewEventCorrelatorToolAdapter(correlator)if len(adapter.GetCorrelationsForResource("res", time.Minute)) != 1 {t.Fatalf("expected correlations from correlator")}diff --git a/internal/ai/chat/agentic.go b/internal/ai/chat/agentic.goindex 07d079d9ff..400df461fc 100644--- a/internal/ai/chat/agentic.go+++ b/internal/ai/chat/agentic.go@@ -10,6 +10,7 @@ import ("time""github.com/google/uuid"+ "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/ai/tools"@@ -147,46 +148,19 @@ func fallbackProviderStreamErrorMessage(err error) string {}func currentResourceUnavailableToolResult(err error) string {- reason := "current_resource is unavailable because no single attached Pulse resource is selected in this chat turn"+ reason := fmt.Sprintf("%s is unavailable because no single attached Pulse resource is selected in this chat turn", agentcapabilities.CurrentResourceHandle)if err != nil && strings.TrimSpace(err.Error()) != "" {reason = strings.TrimSpace(err.Error())}return fmt.Sprintf(- "CURRENT_RESOURCE_UNAVAILABLE: %s. Ask which host, VM, container, app, or storage resource the user means before calling resource-targeted tools. Do not retry this tool with current_resource until the user provides or opens a specific resource context.",+ "CURRENT_RESOURCE_UNAVAILABLE: %s. Ask which host, VM, container, app, or storage resource the user means before calling resource-targeted tools. Do not retry this tool with %s until the user provides or opens a specific resource context.",reason,+ agentcapabilities.CurrentResourceHandle,)}-func toolInputContainsCurrentResourceReference(value interface{}) bool {- switch v := value.(type) {- case nil:- return false- case string:- return tools.IsCurrentResourceReference(v)- case map[string]interface{}:- for _, child := range v {- if toolInputContainsCurrentResourceReference(child) {- return true- }- }- case []interface{}:- for _, child := range v {- if toolInputContainsCurrentResourceReference(child) {- return true- }- }- case []string:- for _, child := range v {- if tools.IsCurrentResourceReference(child) {- return true- }- }- }- return false-}-func (a *AgenticLoop) currentResourcePlaceholderBlock(tc providers.ToolCall) (string, bool) {- if !toolInputContainsCurrentResourceReference(tc.Input) {+ if !agentcapabilities.ToolInputContainsCurrentResourceReference(tc.Input) {return "", false}if a == nil || a.executor == nil {@@ -331,11 +305,11 @@ func emitToolEndEvent(callback StreamCallback, id, name string, input map[stringfunc toolExecutionProgressMessage(toolName string, input map[string]interface{}, toolKind ToolKind) string {switch strings.TrimSpace(toolName) {- case "pulse_run_command", "run_command":+ case agentcapabilities.PulseRunCommandToolName, agentcapabilities.LegacyAssistantRunCommandToolName:return "Running command."- case "pulse_query":+ case agentcapabilities.PulseQueryToolName:return "Reading inventory."- case "pulse_read", "read":+ case agentcapabilities.PulseReadToolName, "read":return "Reading target."}if isKnownGovernedWriteProgress(toolName, input, toolKind) {@@ -351,19 +325,19 @@ func isKnownGovernedWriteProgress(toolName string, input map[string]interface{},action, _ := input["action"].(string)action = strings.ToLower(strings.TrimSpace(action))switch strings.TrimSpace(toolName) {- case "pulse_control", "pulse_control_guest", "pulse_control_docker":+ case agentcapabilities.PulseControlToolName, agentcapabilities.PulseControlGuestToolName, agentcapabilities.PulseControlDockerToolName:return true- case "pulse_alerts":+ case agentcapabilities.PulseAlertsToolName:return action == "resolve" || action == "dismiss"- case "pulse_docker":+ case agentcapabilities.PulseDockerToolName:return action == "control" || action == "update" || action == "check_updates" || action == "trigger_update"- case "pulse_kubernetes":+ case agentcapabilities.PulseKubernetesToolName:return action == "scale" || action == "restart" || action == "delete_pod" || action == "exec"- case "pulse_file_edit":+ case agentcapabilities.PulseFileEditToolName:return action == "write" || action == "append"- case "pulse_knowledge":+ case agentcapabilities.PulseKnowledgeToolName:return action == "remember" || action == "note" || action == "save"- case "patrol_report_finding", "patrol_resolve_finding":+ case agentcapabilities.PatrolReportFindingToolName, agentcapabilities.PatrolResolveFindingToolName:return truedefault:return false@@ -515,6 +489,7 @@ type AgenticLoop struct {// Token accumulation across all turnstotalInputTokens inttotalOutputTokens int+ totalToolCalls int// State for ongoing executionsmu sync.Mutex@@ -542,10 +517,9 @@ type AgenticLoop struct {// NewAgenticLoop creates a new agentic loopfunc NewAgenticLoop(provider providers.StreamingProvider, executor *tools.PulseToolExecutor, systemPrompt string) *AgenticLoop {- // Convert MCP tools to provider format- mcpTools := executor.ListTools()- providerTools := ConvertMCPToolsToProvider(mcpTools)- providerTools = append(providerTools, userQuestionTool())+ providerTools := executor.AssistantProviderTools(agentcapabilities.AssistantProviderToolOptions{+ IncludeQuestionTool: true,+ })return &AgenticLoop{provider: provider,@@ -561,9 +535,9 @@ func NewAgenticLoop(provider providers.StreamingProvider, executor *tools.PulseT// UpdateTools refreshes the tool list from the executorfunc (a *AgenticLoop) UpdateTools() {- mcpTools := a.executor.ListTools()- tools := ConvertMCPToolsToProvider(mcpTools)- a.tools = append(tools, userQuestionTool())+ a.tools = a.executor.AssistantProviderTools(agentcapabilities.AssistantProviderToolOptions{+ IncludeQuestionTool: true,+ })}// SetRequestSanitizer installs a model-bound request sanitizer. It is called@@ -973,7 +947,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, mecase "done":if data, ok := event.Data.(providers.DoneEvent); ok {attemptSawDone = true- toolCalls = data.ToolCalls+ toolCalls = agentcapabilities.NormalizeProviderToolCallsForExecution(data.ToolCalls)a.totalInputTokens += data.InputTokensa.totalOutputTokens += data.OutputTokenslog.Info().@@ -1093,6 +1067,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meMsg("[AgenticLoop] Model returned tool calls after tools were omitted — stripping them")toolCalls = nil}+ a.totalToolCalls += len(toolCalls)// Check mid-run budget after each turn completesif a.budgetChecker != nil {@@ -1117,12 +1092,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meif len(toolCalls) > 0 {assistantMsg.ToolCalls = make([]ToolCall, len(toolCalls))for i, tc := range toolCalls {- assistantMsg.ToolCalls[i] = ToolCall{- ID: tc.ID,- Name: tc.Name,- Input: tc.Input,- ThoughtSignature: tc.ThoughtSignature,- }+ assistantMsg.ToolCalls[i] = ToolCallFromProvider(tc)}}@@ -1270,13 +1240,10 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meMsg("[AgenticLoop] Blocked invalid current_resource tool call before interactive-set execution")emitCurrentResourceBlock(tc, blockMsg)+ projection := newProviderToolResultContextProjection(tc.ID, blockMsg, true)providerMessages = append(providerMessages, providers.Message{- Role: "user",- ToolResult: &providers.ToolResult{- ToolUseID: tc.ID,- Content: truncateToolResultForModel(blockMsg),- IsError: true,- },+ Role: "user",+ ToolResult: &projection.Model,})continue}@@ -1293,33 +1260,26 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, mefsmBlockedErr, ok := fsmErr.(*FSMBlockedError)if ok && fsmBlockedErr.Recoverable {- fsm.TrackPendingRecovery("FSM_BLOCKED", tc.Name)+ fsm.TrackPendingRecovery(agentcapabilities.ErrCodeFSMBlocked, tc.Name)if metrics := GetAIMetrics(); metrics != nil {- metrics.RecordAutoRecoveryAttempt("FSM_BLOCKED", tc.Name)+ metrics.RecordAutoRecoveryAttempt(agentcapabilities.ErrCodeFSMBlocked, tc.Name)}}emitToolStartIfNeeded(tc)emitToolEndEvent(callback, tc.ID, tc.Name, tc.Input, fsmErr.Error(), false)+ projection := newProviderToolResultContextProjection(tc.ID, fsmErr.Error(), true)toolResultMsg := Message{- ID: uuid.New().String(),- Role: "user",- Timestamp: time.Now(),- ToolResult: &ToolResult{- ToolUseID: tc.ID,- Content: fsmErr.Error(),- IsError: true,- },+ ID: uuid.New().String(),+ Role: "user",+ Timestamp: time.Now(),+ ToolResult: &projection.Transcript,}resultMessages = append(resultMessages, toolResultMsg)providerMessages = append(providerMessages, providers.Message{- Role: "user",- ToolResult: &providers.ToolResult{- ToolUseID: tc.ID,- Content: truncateToolResultForModel(fsmErr.Error()),- IsError: true,- },+ Role: "user",+ ToolResult: &projection.Model,})continue}@@ -1334,24 +1294,17 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meemitToolStartIfNeeded(tc)emitToolEndEvent(callback, tc.ID, tc.Name, tc.Input, loopMsg, false)+ projection := newProviderToolResultContextProjection(tc.ID, loopMsg, true)toolResultMsg := Message{- ID: uuid.New().String(),- Role: "user",- Timestamp: time.Now(),- ToolResult: &ToolResult{- ToolUseID: tc.ID,- Content: loopMsg,- IsError: true,- },+ ID: uuid.New().String(),+ Role: "user",+ Timestamp: time.Now(),+ ToolResult: &projection.Transcript,}resultMessages = append(resultMessages, toolResultMsg)providerMessages = append(providerMessages, providers.Message{- Role: "user",- ToolResult: &providers.ToolResult{- ToolUseID: tc.ID,- Content: truncateToolResultForModel(loopMsg),- IsError: true,- },+ Role: "user",+ ToolResult: &projection.Model,})continue}@@ -1363,24 +1316,17 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meemitToolStartIfNeeded(tc)emitToolEndEvent(callback, tc.ID, tc.Name, tc.Input, skipMsg, false)+ projection := newProviderToolResultContextProjection(tc.ID, skipMsg, true)toolResultMsg := Message{- ID: uuid.New().String(),- Role: "user",- Timestamp: time.Now(),- ToolResult: &ToolResult{- ToolUseID: tc.ID,- Content: skipMsg,- IsError: true,- },+ ID: uuid.New().String(),+ Role: "user",+ Timestamp: time.Now(),+ ToolResult: &projection.Transcript,}resultMessages = append(resultMessages, toolResultMsg)providerMessages = append(providerMessages, providers.Message{- Role: "user",- ToolResult: &providers.ToolResult{- ToolUseID: tc.ID,- Content: truncateToolResultForModel(skipMsg),- IsError: true,- },+ Role: "user",+ ToolResult: &projection.Model,})continue}@@ -1406,25 +1352,18 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, mefsm.OnToolSuccess(toolKind, tc.Name)}+ projection := newProviderToolResultContextProjection(tc.ID, resultText, isError)toolResultMsg := Message{- ID: uuid.New().String(),- Role: "user",- Timestamp: time.Now(),- ToolResult: &ToolResult{- ToolUseID: tc.ID,- Content: resultText,- IsError: isError,- },+ ID: uuid.New().String(),+ Role: "user",+ Timestamp: time.Now(),+ ToolResult: &projection.Transcript,}resultMessages = append(resultMessages, toolResultMsg)providerMessages = append(providerMessages, providers.Message{- Role: "user",- ToolResult: &providers.ToolResult{- ToolUseID: tc.ID,- Content: truncateToolResultForModel(resultText),- IsError: isError,- },+ Role: "user",+ ToolResult: &projection.Model,})}@@ -1451,13 +1390,10 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meMsg("[AgenticLoop] Blocked invalid current_resource tool call before execution")emitCurrentResourceBlock(tc, blockMsg)+ projection := newProviderToolResultContextProjection(tc.ID, blockMsg, true)providerMessages = append(providerMessages, providers.Message{- Role: "user",- ToolResult: &providers.ToolResult{- ToolUseID: tc.ID,- Content: truncateToolResultForModel(blockMsg),- IsError: true,- },+ Role: "user",+ ToolResult: &projection.Model,})continue}@@ -1480,10 +1416,10 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, mefsmBlockedErr, ok := fsmErr.(*FSMBlockedError)if ok && fsmBlockedErr.Recoverable {// Track pending recovery for success correlation- fsm.TrackPendingRecovery("FSM_BLOCKED", tc.Name)+ fsm.TrackPendingRecovery(agentcapabilities.ErrCodeFSMBlocked, tc.Name)// Record that the model received a recoverable policy block.if metrics := GetAIMetrics(); metrics != nil {- metrics.RecordAutoRecoveryAttempt("FSM_BLOCKED", tc.Name)+ metrics.RecordAutoRecoveryAttempt(agentcapabilities.ErrCodeFSMBlocked, tc.Name)}}@@ -1492,26 +1428,19 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meemitToolEndEvent(callback, tc.ID, tc.Name, tc.Input, fsmErr.Error(), false)// Create tool result message with the error+ projection := newProviderToolResultContextProjection(tc.ID, fsmErr.Error(), true)toolResultMsg := Message{- ID: uuid.New().String(),- Role: "user",- Timestamp: time.Now(),- ToolResult: &ToolResult{- ToolUseID: tc.ID,- Content: fsmErr.Error(),- IsError: true,- },+ ID: uuid.New().String(),+ Role: "user",+ Timestamp: time.Now(),+ ToolResult: &projection.Transcript,}resultMessages = append(resultMessages, toolResultMsg)// Add to provider messages for next turnproviderMessages = append(providerMessages, providers.Message{- Role: "user",- ToolResult: &providers.ToolResult{- ToolUseID: tc.ID,- Content: fsmErr.Error(),- IsError: true,- },+ Role: "user",+ ToolResult: &projection.Model,})// Skip execution but continue the loop to process other tool calls@@ -1534,24 +1463,17 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meemitToolStartIfNeeded(tc)emitToolEndEvent(callback, tc.ID, tc.Name, tc.Input, loopMsg, false)+ projection := newProviderToolResultContextProjection(tc.ID, loopMsg, true)toolResultMsg := Message{- ID: uuid.New().String(),- Role: "user",- Timestamp: time.Now(),- ToolResult: &ToolResult{- ToolUseID: tc.ID,- Content: loopMsg,- IsError: true,- },+ ID: uuid.New().String(),+ Role: "user",+ Timestamp: time.Now(),+ ToolResult: &projection.Transcript,}resultMessages = append(resultMessages, toolResultMsg)providerMessages = append(providerMessages, providers.Message{- Role: "user",- ToolResult: &providers.ToolResult{- ToolUseID: tc.ID,- Content: loopMsg,- IsError: true,- },+ Role: "user",+ ToolResult: &projection.Model,})budgetBlockedThisTurn++continue@@ -1629,11 +1551,13 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, mevar isError boolif err != nil {- resultText = fmt.Sprintf("Error: %v", err)- isError = true+ toolResult := agentcapabilities.NewProviderToolErrorResult(tc.ID, fmt.Sprintf("Error: %v", err))+ resultText = toolResult.Content+ isError = toolResult.IsError} else {- resultText = FormatToolResult(result)- isError = result.IsError+ toolResult := agentcapabilities.NewProviderToolResultFromToolResult(tc.ID, result)+ resultText = toolResult.Content+ isError = toolResult.IsError// Extract and accumulate knowledge facts from both success and structured error responsesif a.knowledgeAccumulator != nil {a.knowledgeAccumulator.SetTurn(turn)@@ -1673,45 +1597,23 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me// Track pending recovery for strict resolution blocks// (FSM blocks are tracked above; strict resolution blocks come from the executor)- if isError && fsm != nil && strings.Contains(resultText, "STRICT_RESOLUTION") {- fsm.TrackPendingRecovery("STRICT_RESOLUTION", tc.Name)+ if isError && fsm != nil && agentcapabilities.ToolResultHasErrorCode(resultText, agentcapabilities.ErrCodeStrictResolution) {+ fsm.TrackPendingRecovery(agentcapabilities.ErrCodeStrictResolution, tc.Name)log.Debug().Str("tool", tc.Name).Msg("[AgenticLoop] Tracking pending recovery for strict resolution block")}// Check if this is an approval request- if strings.HasPrefix(resultText, "APPROVAL_REQUIRED:") {- // Parse approval request- approvalJSON := strings.TrimPrefix(resultText, "APPROVAL_REQUIRED:")- approvalJSON = strings.TrimSpace(approvalJSON)-- var approvalData struct {- ApprovalID string `json:"approval_id"`- Command string `json:"command"`- Risk string `json:"risk"`- Description string `json:"description"`- Reason string `json:"reason"`- TargetHost string `json:"target_host"`- Host string `json:"host"`- DockerHost string `json:"docker_host"`- ResourceHost string `json:"resource_host"`- Cluster string `json:"cluster"`- TargetName string `json:"target_name"`- TargetType string `json:"target_type"`- TargetID string `json:"target_id"`- AuditID string `json:"audit_id"`- Plan *ApprovalPlanData `json:"plan"`- ContextConfidence *ApprovalContextConfidenceData `json:"context_confidence"`- Preflight *ApprovalPreflightData `json:"preflight"`- }- if err := json.Unmarshal([]byte(approvalJSON), &approvalData); err != nil {- log.Error().Err(err).Str("data", approvalJSON).Msg("failed to parse approval request")+ if agentcapabilities.HasApprovalRequiredToolMarker(resultText) {+ // Parse approval request through the shared marker payload+ // contract so tool producers and chat consumers stay aligned.+ approvalData, ok := agentcapabilities.ParseApprovalRequiredToolMarkerData(resultText)+ if !ok {+ log.Error().Str("data", resultText).Msg("failed to parse approval request")resultText = "Error: failed to parse approval request"isError = true} else {- targetHost := firstNonEmptyTrimmed(approvalData.TargetHost, approvalData.Host, approvalData.DockerHost, approvalData.ResourceHost, approvalData.Cluster, approvalData.TargetName)- description := firstNonEmptyTrimmed(approvalData.Description, approvalData.Reason)// Send approval_needed eventjsonData, _ := json.Marshal(ApprovalNeededData{ApprovalID: approvalData.ApprovalID,@@ -1719,11 +1621,11 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meToolName: tc.Name,Command: approvalData.Command,RunOnHost: true, // Control commands run on host- TargetHost: targetHost,+ TargetHost: approvalData.TargetHint(),TargetType: approvalData.TargetType,TargetID: approvalData.TargetID,Risk: approvalData.Risk,- Description: description,+ Description: approvalData.DescriptionText(),AuditID: approvalData.AuditID,Plan: approvalData.Plan,ContextConfidence: approvalData.ContextConfidence,@@ -1774,14 +1676,16 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, mefor k, v := range tc.Input {inputWithApproval[k] = v}- inputWithApproval["_approval_id"] = approvalData.ApprovalID+ inputWithApproval = agentcapabilities.WithApprovalArgument(inputWithApproval, approvalData.ApprovalID)result, err = a.executeToolSafely(ctx, tc.Name, inputWithApproval)if err != nil {- resultText = fmt.Sprintf("Error after approval: %v", err)- isError = true+ toolResult := agentcapabilities.NewProviderToolErrorResult(tc.ID, fmt.Sprintf("Error after approval: %v", err))+ resultText = toolResult.Content+ isError = toolResult.IsError} else {- resultText = FormatToolResult(result)- isError = result.IsError+ toolResult := agentcapabilities.NewProviderToolResultFromToolResult(tc.ID, result)+ resultText = toolResult.Content+ isError = toolResult.IsError}} else {if a.executor != nil {@@ -1840,7 +1744,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me//// Verification evidence is a structured field in the tool output:// { "verification": { "ok": true, ... } }- if toolKind == ToolKindWrite && toolResultHasVerificationOK(resultText) {+ if toolKind == ToolKindWrite && agentcapabilities.ToolResultHasVerificationOK(resultText) {fsm.OnToolSuccess(ToolKindRead, "self_verify")if fsm.State == StateVerifying && fsm.ReadAfterWrite {fsm.CompleteVerification()@@ -1873,31 +1777,23 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me}}- // Compute model-facing result text AFTER auto-verify may have appended data.+ // Compute model-facing result AFTER auto-verify may have appended data.// This ensures the model sees the verification result and task-completion signal.- modelResultText := truncateToolResultForModel(resultText)+ projection := newProviderToolResultContextProjection(tc.ID, resultText, isError)// Create tool result messagetoolResultMsg := Message{- ID: uuid.New().String(),- Role: "user", // Tool results are sent as user messages- Timestamp: time.Now(),- ToolResult: &ToolResult{- ToolUseID: tc.ID,- Content: resultText,- IsError: isError,- },+ ID: uuid.New().String(),+ Role: "user", // Tool results are sent as user messages+ Timestamp: time.Now(),+ ToolResult: &projection.Transcript,}resultMessages = append(resultMessages, toolResultMsg)// Add to provider messages for next turnproviderMessages = append(providerMessages, providers.Message{- Role: "user",- ToolResult: &providers.ToolResult{- ToolUseID: tc.ID,- Content: modelResultText,- IsError: isError,- },+ Role: "user",+ ToolResult: &projection.Model,})}diff --git a/internal/ai/chat/agentic_additional_test.go b/internal/ai/chat/agentic_additional_test.goindex 2a9b8bcdcf..261e2b3ae9 100644--- a/internal/ai/chat/agentic_additional_test.go+++ b/internal/ai/chat/agentic_additional_test.go@@ -762,6 +762,87 @@ func TestAgenticLoop_DoesNotAutoRecoverStructuredToolCall(t *testing.T) {}}+func TestAgenticLoop_NormalizesProviderToolCallsThroughSharedProjection(t *testing.T) {+ executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})+ var capturedArgs map[string]interface{}+ executor.RegisterTool(tools.RegisteredTool{+ Definition: tools.Tool{+ Name: "test_tool",+ InputSchema: tools.InputSchema{+ Type: "object",+ Properties: map[string]tools.PropertySchema{+ "value": {Type: "string"},+ },+ },+ },+ Handler: func(ctx context.Context, exec *tools.PulseToolExecutor, args map[string]interface{}) (tools.CallToolResult, error) {+ capturedArgs = args+ return tools.NewTextResult("normalized"), nil+ },+ })++ provider := &stubStreamingProvider{}+ loop := NewAgenticLoop(provider, executor, "prompt")+ callCount := 0+ sourceInput := map[string]interface{}{"value": "ok"}+ provider.chatStream = func(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {+ callCount+++ switch callCount {+ case 1:+ callback(providers.StreamEvent{+ Type: "done",+ Data: providers.DoneEvent{+ ToolCalls: []providers.ToolCall{{+ ID: "call-normalize",+ Name: " test_tool ",+ Input: sourceInput,+ }},+ },+ })+ case 2:+ if len(req.Messages) != 3 {+ t.Fatalf("expected user, normalized assistant call, and tool result, got %d messages", len(req.Messages))+ }+ call := req.Messages[1].ToolCalls[0]+ if call.Name != "test_tool" {+ t.Fatalf("provider continuation must receive normalized tool name, got %+v", call)+ }+ if req.Messages[2].ToolResult == nil || req.Messages[2].ToolResult.Content != "normalized" {+ t.Fatalf("expected normalized tool result, got %+v", req.Messages[2].ToolResult)+ }+ callback(providers.StreamEvent{+ Type: "content",+ Data: providers.ContentEvent{Text: "Done."},+ })+ callback(providers.StreamEvent{+ Type: "done",+ Data: providers.DoneEvent{},+ })+ default:+ t.Fatalf("unexpected provider call %d", callCount)+ }+ return nil+ }++ results, err := loop.Execute(context.Background(), "provider-call-normalize", []Message{{Role: "user", Content: "run it"}}, func(event StreamEvent) {})+ if err != nil {+ t.Fatalf("expected normalized provider tool call to execute, got %v", err)+ }+ if capturedArgs == nil || capturedArgs["value"] != "ok" {+ t.Fatalf("expected normalized args to reach handler, got %#v", capturedArgs)+ }+ capturedArgs["value"] = "changed"+ if sourceInput["value"] != "ok" {+ t.Fatalf("handler args must not alias provider input: source=%#v captured=%#v", sourceInput, capturedArgs)+ }+ if len(results) != 3 {+ t.Fatalf("expected assistant tool call, tool result, and final response, got %+v", results)+ }+ if len(results[0].ToolCalls) != 1 || results[0].ToolCalls[0].Name != "test_tool" {+ t.Fatalf("session-visible assistant call must be normalized, got %+v", results[0].ToolCalls)+ }+}+func TestAgenticLoop_CancelsUnavailableCurrentResourcePendingToolCall(t *testing.T) {executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})provider := &stubStreamingProvider{}diff --git a/internal/ai/chat/agentic_context.go b/internal/ai/chat/agentic_context.goindex e09f27aabc..22d3d9dbf9 100644--- a/internal/ai/chat/agentic_context.go+++ b/internal/ai/chat/agentic_context.go@@ -4,6 +4,7 @@ import ("fmt""strings"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/ai/providers""github.com/rs/zerolog/log")@@ -55,18 +56,33 @@ func pruneMessagesForModel(messages []Message) []Message {}func truncateToolResultForModel(text string) string {- if MaxToolResultCharsLimit <= 0 || len(text) <= MaxToolResultCharsLimit {- return text+ content, truncation := agentcapabilities.ProviderToolResultModelContent(text, providerToolResultContextOptions())+ logProviderToolResultTruncation(truncation)+ return content+}++func providerToolResultContextOptions() agentcapabilities.ProviderToolResultContextOptions {+ return agentcapabilities.ProviderToolResultContextOptions{+ MaxModelContentChars: MaxToolResultCharsLimit,+ }+}++func newProviderToolResultContextProjection(toolUseID, content string, isError bool) agentcapabilities.ProviderToolResultContextProjection {+ projection := agentcapabilities.NewProviderToolResultContextProjection(toolUseID, content, isError, providerToolResultContextOptions())+ logProviderToolResultTruncation(projection.Truncation)+ return projection+}++func logProviderToolResultTruncation(truncation agentcapabilities.ProviderToolResultTruncation) {+ if !truncation.Applied {+ return}- truncated := text[:MaxToolResultCharsLimit]- truncatedChars := len(text) - MaxToolResultCharsLimitlog.Warn().- Int("original_chars", len(text)).- Int("truncated_to", MaxToolResultCharsLimit).- Int("chars_cut", truncatedChars).+ Int("original_chars", truncation.OriginalChars).+ Int("truncated_to", truncation.MaxChars).+ Int("chars_cut", truncation.TruncatedChars).Msg("[AgenticLoop] Truncating oversized tool result")- return fmt.Sprintf("%s\n\n---\n[TRUNCATED: %d characters cut. The result was too large. If you need specific details that may have been cut, make a more targeted query (e.g., filter by specific resource or type).]", truncated, truncatedChars)}// convertToProviderMessages converts our messages to provider format@@ -84,21 +100,13 @@ func convertToProviderMessages(messages []Message) []providers.Message {if len(m.ToolCalls) > 0 {for _, tc := range m.ToolCalls {- pm.ToolCalls = append(pm.ToolCalls, providers.ToolCall{- ID: tc.ID,- Name: tc.Name,- Input: tc.Input,- ThoughtSignature: tc.ThoughtSignature,- })+ pm.ToolCalls = append(pm.ToolCalls, tc.ProviderToolCall())}}if m.ToolResult != nil {- pm.ToolResult = &providers.ToolResult{- ToolUseID: m.ToolResult.ToolUseID,- Content: truncateToolResultForModel(m.ToolResult.Content),- IsError: m.ToolResult.IsError,- }+ projection := newProviderToolResultContextProjection(m.ToolResult.ToolUseID, m.ToolResult.Content, m.ToolResult.IsError)+ pm.ToolResult = &projection.Model}result = append(result, pm)@@ -181,13 +189,10 @@ func repairOrphanToolCalls(messages []providers.Message) []providers.Message {// message.inject := make([]providers.Message, 0, len(missing))for _, id := range missing {+ toolResult := agentcapabilities.NewProviderToolErrorResult(id, orphanToolCallRepairMessage)inject = append(inject, providers.Message{- Role: "user",- ToolResult: &providers.ToolResult{- ToolUseID: id,- Content: orphanToolCallRepairMessage,- IsError: true,- },+ Role: "user",+ ToolResult: &toolResult,})}// Splice the synthetic messages in at position i+1.diff --git a/internal/ai/chat/agentic_control.go b/internal/ai/chat/agentic_control.goindex a72039c3ee..b9b19b6677 100644--- a/internal/ai/chat/agentic_control.go+++ b/internal/ai/chat/agentic_control.go@@ -71,8 +71,14 @@ func (a *AgenticLoop) GetTotalOutputTokens() int {return a.totalOutputTokens}+// GetTotalToolCalls returns the accepted model-selected tool call count across all turns.+func (a *AgenticLoop) GetTotalToolCalls() int {+ return a.totalToolCalls+}+// ResetTokenCounts resets the accumulated token counts (for reuse across executions).func (a *AgenticLoop) ResetTokenCounts() {a.totalInputTokens = 0a.totalOutputTokens = 0+ a.totalToolCalls = 0}diff --git a/internal/ai/chat/agentic_question_tool.go b/internal/ai/chat/agentic_question_tool.goindex 861001ac21..ae0ca1c178 100644--- a/internal/ai/chat/agentic_question_tool.go+++ b/internal/ai/chat/agentic_question_tool.go@@ -1,226 +1,53 @@package chatimport (- "bytes""context""encoding/json""fmt"- "strings""time""github.com/google/uuid"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/ai/providers""github.com/rs/zerolog/log")-func userQuestionTool() providers.Tool {- return providers.Tool{- Name: pulseQuestionToolName,- Description: "Ask the user for missing information using a structured prompt. Use this when you must clarify before proceeding (e.g., choose a target, confirm a risky action, or select among options).",- InputSchema: map[string]interface{}{- "type": "object",- "properties": map[string]interface{}{- "questions": map[string]interface{}{- "type": "array",- "items": map[string]interface{}{- "type": "object",- "properties": map[string]interface{}{- "id": map[string]interface{}{- "type": "string",- "description": "Stable identifier for this question (used in the answer payload).",- },- "type": map[string]interface{}{- "type": "string",- "description": "Question type. Use 'text' for free-form input or 'select' for predefined options.",- "enum": []string{"text", "select"},- },- "header": map[string]interface{}{- "type": "string",- "description": "Optional short context shown above the question.",- },- "question": map[string]interface{}{- "type": "string",- "description": "The question shown to the user.",- },- "options": map[string]interface{}{- "type": "array",- "items": map[string]interface{}{- "type": "object",- "properties": map[string]interface{}{- "label": map[string]interface{}{"type": "string"},- "value": map[string]interface{}{"type": "string"},- "description": map[string]interface{}{- "type": "string",- "description": "Optional detail shown under the label.",- },- },- "required": []string{"label"},- },- },- },- "required": []string{"id", "question"},- },- },- },- "required": []string{"questions"},- },- }-}--const pulseQuestionToolName = "pulse_question"--type questionToolType string--const (- questionToolTypeText questionToolType = "text"- questionToolTypeSelect questionToolType = "select"-)--type questionToolInputPayload struct {- Questions json.RawMessage `json:"questions"`-}--type questionToolInputQuestion struct {- ID string `json:"id"`- Type string `json:"type,omitempty"`- Header string `json:"header,omitempty"`- Question string `json:"question"`- Options json.RawMessage `json:"options,omitempty"`-}--type questionToolInputOption struct {- Label string `json:"label"`- Value string `json:"value,omitempty"`- Description string `json:"description,omitempty"`-}+const pulseQuestionToolName = agentcapabilities.PulseQuestionToolNamefunc parseQuestionToolInput(input map[string]interface{}) ([]Question, error) {- payloadBytes, err := json.Marshal(input)+ parsedQuestions, err := agentcapabilities.ParsePulseQuestionToolInput(input)if err != nil {- return nil, fmt.Errorf("invalid question payload: %w", err)- }-- var payload questionToolInputPayload- if err := json.Unmarshal(payloadBytes, &payload); err != nil {- return nil, fmt.Errorf("invalid question payload: %w", err)- }-- if len(payload.Questions) == 0 {- return nil, fmt.Errorf("missing required field: questions")- }-- var rawQuestions []json.RawMessage- if err := json.Unmarshal(payload.Questions, &rawQuestions); err != nil {- return nil, fmt.Errorf("questions must be an array")- }-- if len(rawQuestions) == 0 {- return nil, fmt.Errorf("questions must not be empty")+ return nil, err}- questions := make([]Question, 0, len(rawQuestions))- for _, rawQuestion := range rawQuestions {- var parsedQuestion questionToolInputQuestion- if err := json.Unmarshal(rawQuestion, &parsedQuestion); err != nil {- return nil, fmt.Errorf("invalid question entry")- }-- id := strings.TrimSpace(parsedQuestion.ID)- questionText := strings.TrimSpace(parsedQuestion.Question)- header := strings.TrimSpace(parsedQuestion.Header)-- if id == "" {- return nil, fmt.Errorf("question.id is required")- }- if questionText == "" {- return nil, fmt.Errorf("question.question is required")- }-- opts, err := parseQuestionToolOptions(parsedQuestion.Options)- if err != nil {- return nil, err- }-- qType, err := normalizeQuestionToolType(parsedQuestion.Type, len(opts) > 0)- if err != nil {- return nil, err+ questions := make([]Question, 0, len(parsedQuestions))+ for _, parsedQuestion := range parsedQuestions {+ options := make([]QuestionOption, 0, len(parsedQuestion.Options))+ for _, parsedOption := range parsedQuestion.Options {+ option := QuestionOption{+ Label: parsedOption.Label,+ Value: parsedOption.Value,+ }+ if parsedOption.Description != "" {+ option.Description = parsedOption.Description+ }+ options = append(options, option)}- q := Question{- ID: id,- Type: string(qType),- Question: questionText,- Options: opts,+ question := Question{+ ID: parsedQuestion.ID,+ Type: string(parsedQuestion.Type),+ Question: parsedQuestion.Question,+ Options: options,}- if header != "" {- q.Header = header+ if parsedQuestion.Header != "" {+ question.Header = parsedQuestion.Header}- questions = append(questions, q)+ questions = append(questions, question)}return questions, nil}-func parseQuestionToolOptions(rawOptions json.RawMessage) ([]QuestionOption, error) {- if len(rawOptions) == 0 {- return nil, nil- }-- trimmed := bytes.TrimSpace(rawOptions)- if bytes.Equal(trimmed, []byte("null")) {- return nil, fmt.Errorf("question.options must be an array")- }-- var decodedOptions []questionToolInputOption- if err := json.Unmarshal(rawOptions, &decodedOptions); err != nil {- return nil, fmt.Errorf("question.options must be an array")- }-- options := make([]QuestionOption, 0, len(decodedOptions))- for _, decodedOption := range decodedOptions {- label := strings.TrimSpace(decodedOption.Label)- value := strings.TrimSpace(decodedOption.Value)- desc := strings.TrimSpace(decodedOption.Description)-- if label == "" {- return nil, fmt.Errorf("option.label is required")- }- if value == "" {- value = label- }-- option := QuestionOption{Label: label, Value: value}- if desc != "" {- option.Description = desc- }- options = append(options, option)- }-- return options, nil-}--func normalizeQuestionToolType(rawType string, hasOptions bool) (questionToolType, error) {- normalizedType := strings.TrimSpace(strings.ToLower(rawType))- if normalizedType == "" {- if hasOptions {- normalizedType = string(questionToolTypeSelect)- } else {- normalizedType = string(questionToolTypeText)- }- }-- switch questionToolType(normalizedType) {- case questionToolTypeText:- return questionToolTypeText, nil- case questionToolTypeSelect:- if !hasOptions {- return "", fmt.Errorf("select questions must include options")- }- return questionToolTypeSelect, nil- default:- return "", fmt.Errorf("question.type must be 'text' or 'select'")- }-}-func (a *AgenticLoop) executeQuestionTool(ctx context.Context, sessionID string, tc providers.ToolCall, callback StreamCallback) (string, bool) {a.mu.Lock()autonomous := a.autonomousModediff --git a/internal/ai/chat/agentic_question_tool_parse_test.go b/internal/ai/chat/agentic_question_tool_parse_test.goindex cc7e7638b5..f484af7f7c 100644--- a/internal/ai/chat/agentic_question_tool_parse_test.go+++ b/internal/ai/chat/agentic_question_tool_parse_test.go@@ -3,11 +3,12 @@ package chatimport ("testing"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")-func TestParseQuestionToolInput_Valid(t *testing.T) {+func TestParseQuestionToolInputMapsSharedQuestionPayloadToChatQuestions(t *testing.T) {input := map[string]interface{}{"questions": []interface{}{map[string]interface{}{@@ -35,148 +36,18 @@ func TestParseQuestionToolInput_Valid(t *testing.T) {require.Len(t, questions, 2)assert.Equal(t, "q1", questions[0].ID)- assert.Equal(t, "select", questions[0].Type)+ assert.Equal(t, string(agentcapabilities.PulseQuestionToolTypeSelect), questions[0].Type)assert.Equal(t, "Pick one", questions[0].Question)require.Len(t, questions[0].Options, 1)- assert.Equal(t, "A", questions[0].Options[0].Label)- assert.Equal(t, "A", questions[0].Options[0].Value)- assert.Equal(t, "Alpha", questions[0].Options[0].Description)+ assert.Equal(t, QuestionOption{Label: "A", Value: "A", Description: "Alpha"}, questions[0].Options[0])assert.Equal(t, "q2", questions[1].ID)- assert.Equal(t, "text", questions[1].Type)+ assert.Equal(t, string(agentcapabilities.PulseQuestionToolTypeText), questions[1].Type)assert.Equal(t, "Why?", questions[1].Question)assert.Equal(t, "Context", questions[1].Header)}-func TestParseQuestionToolInput_Errors(t *testing.T) {- tests := []struct {- name string- input map[string]interface{}- expectedErr string- }{- {- name: "missing questions",- input: map[string]interface{}{},- expectedErr: "missing required field: questions",- },- {- name: "questions must be array",- input: map[string]interface{}{- "questions": map[string]interface{}{},- },- expectedErr: "questions must be an array",- },- {- name: "questions must not be empty",- input: map[string]interface{}{- "questions": []interface{}{},- },- expectedErr: "questions must not be empty",- },- {- name: "invalid question entry",- input: map[string]interface{}{- "questions": []interface{}{"not-an-object"},- },- expectedErr: "invalid question entry",- },- {- name: "missing question id",- input: map[string]interface{}{- "questions": []interface{}{- map[string]interface{}{- "question": "Pick one",- },- },- },- expectedErr: "question.id is required",- },- {- name: "missing question text",- input: map[string]interface{}{- "questions": []interface{}{- map[string]interface{}{- "id": "q1",- },- },- },- expectedErr: "question.question is required",- },- {- name: "invalid question type",- input: map[string]interface{}{- "questions": []interface{}{- map[string]interface{}{- "id": "q1",- "type": "binary",- "question": "Pick one",- },- },- },- expectedErr: "question.type must be 'text' or 'select'",- },- {- name: "select requires options",- input: map[string]interface{}{- "questions": []interface{}{- map[string]interface{}{- "id": "q1",- "type": "select",- "question": "Pick one",- },- },- },- expectedErr: "select questions must include options",- },- {- name: "options must be array",- input: map[string]interface{}{- "questions": []interface{}{- map[string]interface{}{- "id": "q1",- "question": "Pick one",- "options": map[string]interface{}{},- },- },- },- expectedErr: "question.options must be an array",- },- {- name: "null options rejected",- input: map[string]interface{}{- "questions": []interface{}{- map[string]interface{}{- "id": "q1",- "question": "Pick one",- "options": nil,- },- },- },- expectedErr: "question.options must be an array",- },- {- name: "option label required",- input: map[string]interface{}{- "questions": []interface{}{- map[string]interface{}{- "id": "q1",- "question": "Pick one",- "options": []interface{}{- map[string]interface{}{- "label": " ",- },- },- },- },- },- expectedErr: "option.label is required",- },- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- _, err := parseQuestionToolInput(tc.input)- require.EqualError(t, err, tc.expectedErr)- })- }+func TestParseQuestionToolInputReturnsSharedParserErrors(t *testing.T) {+ _, err := parseQuestionToolInput(map[string]interface{}{})+ require.EqualError(t, err, "missing required field: questions")}diff --git a/internal/ai/chat/agentic_sanitize.go b/internal/ai/chat/agentic_sanitize.goindex 3447e5012e..9b0e53f945 100644--- a/internal/ai/chat/agentic_sanitize.go+++ b/internal/ai/chat/agentic_sanitize.go@@ -5,68 +5,14 @@ import ("strings""unicode"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/ai/tools")-// Compiled regexes for structural tool call artifacts from various LLM providers.-// These patterns catch tool call markup that leaks into content when models are-// told not to use tools but still see tool definitions.+// Compiled regexes for Assistant presentation artifacts. Generic provider+// tool-call artifact detection lives in agentcapabilities so native Assistant+// and external adapter boundaries share the same leak guard.var (- dsmlMarkers = []string{- "<|DSML|", // Unicode single pipe (opening)- "</|DSML|", // Unicode single pipe (closing)- "<||DSML||", // Unicode double pipe (opening) — deepseek-v4-flash- "</||DSML||", // Unicode double pipe (closing)- "<||DSML||", // ASCII double pipe (opening)- "</||DSML||", // ASCII double pipe (closing)- "<|DSML|", // ASCII single pipe (opening)- "</|DSML|", // ASCII single pipe (closing)- "<|/DSML|", // Alternative Unicode closing- "<||/DSML||", // Alternative Unicode double-pipe closing- "<|/DSML|", // Alternative ASCII closing- "<||/DSML||", // Alternative ASCII double-pipe closing- }-- // XML-style tool call envelopes: <tool_call>...</tool_call>, <tool_calls>...</tool_calls>,- // <function_call>...</function_call>, <function_calls>...</function_calls>- xmlToolCallRe = regexp.MustCompile(`(?s)</?(?:tool_calls?|function_calls?)>`)-- // Pipe-delimited markers: <|plugin|>, <|interpreter|>, <|tool_call|>, etc.- pipeMarkerRe = regexp.MustCompile(`<\|(?:plugin|interpreter|tool_call)\|>`)-- // MiniMax-style markers: minimax:tool_call followed by JSON-like content- minimaxMarkerRe = regexp.MustCompile(`(?m)^minimax:tool_call\b`)-- // DeepSeek DSML markers with arbitrary pipe-count variants. The- // fast-path string list below covers the single- and double-pipe- // forms we've actually observed in the wild- // (`<|DSML|...>` and `<||DSML||...>` — the latter from- // deepseek-v4-flash). This regex is the catch-all backstop for any- // pipe-count variant the model might emit so the chat orchestrator- // never falls through to showing raw DSML to the user as the- // assistant's "final response."- dsmlRe = regexp.MustCompile(`</?[\||]+/?DSML[\||]*`)-- // Plain-JSON tool-call leak: weak local models (qwen2.5:11b/14b and- // similar small Ollama models) frequently emit Pulse tool invocations- // as JSON inside content instead of through the structured tool_calls- // channel. The leak shape is a JSON object whose first key is "name"- // with a value matching a known Pulse tool, optionally wrapped in a- // markdown code fence. Anchored on (?:^|\n) so prose containing JSON- // fragments inline (e.g. "the field {"name":"x"} in the schema") is- // not stripped. The captured tool name is gated against the canonical- // allowlist in tools.IsKnownToolName so arbitrary JSON the user might- // legitimately share is left untouched.- jsonToolCallRe = regexp.MustCompile(- `(?:^|\n)[ \t]*(?:` + "```" + `[ \t]*(?:json|JSON)?[ \t]*\n?[ \t]*)?\{[ \t\n]*"name"[ \t]*:[ \t]*"([a-zA-Z_][a-zA-Z0-9_]*)"`,- )-- // Plain function-style tool-call leak: some models emit- // pulse_read(target_host="...", command="...") as assistant content- // instead of a structured tool call. Gate on canonical tool names so a- // random prose function call is not stripped.- plainFunctionToolCallRe = regexp.MustCompile(`(?:^|[^a-zA-Z0-9_])([a-zA-Z_][a-zA-Z0-9_]*)[ \t\r\n]*\(`)-// Operational providers often decorate alert/status answers with emoji// badges even when instructed not to. Pulse renders state through typed// tool/progress rows, so these glyphs are treated as presentation artifacts@@ -189,42 +135,7 @@ func containsToolCallMarker(content string) bool {// toolCallArtifactIndex returns the byte offset of the first known tool-call// artifact in content, or -1 if no artifact is present.func toolCallArtifactIndex(content string) int {- if content == "" {- return -1- }-- first := -1- record := func(idx int) {- if idx < 0 {- return- }- if first < 0 || idx < first {- first = idx- }- }-- for _, marker := range dsmlMarkers {- if idx := strings.Index(content, marker); idx >= 0 {- record(idx)- }- }-- if loc := dsmlRe.FindStringIndex(content); loc != nil {- record(loc[0])- }- if loc := xmlToolCallRe.FindStringIndex(content); loc != nil {- record(loc[0])- }- if loc := pipeMarkerRe.FindStringIndex(content); loc != nil {- record(loc[0])- }- if loc := minimaxMarkerRe.FindStringIndex(content); loc != nil {- record(loc[0])- }- record(findJSONToolCallLeak(content))- record(findPlainFunctionToolCallLeak(content))-- return first+ return agentcapabilities.ProviderToolCallArtifactIndex(content, tools.AssistantProviderToolNameCatalog())}func appendVisibleContentBeforeToolLeak(@@ -306,29 +217,7 @@ func appendSanitizedVisibleDelta(builder *strings.Builder, visible string) strin}func splitTrailingPotentialToolNamePrefix(content string) (visible string, held string) {- if content == "" {- return "", ""- }-- start := len(content)- for start > 0 {- ch := content[start-1]- if (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '_' {- start--- continue- }- break- }-- if start == len(content) {- return content, ""- }-- token := content[start:]- if tools.IsKnownToolNamePrefix(token) {- return content[:start], token- }- return content, ""+ return agentcapabilities.SplitTrailingProviderToolNamePrefix(content, tools.AssistantProviderToolNameCatalog())}func isCompactedToolPrelude(content string) bool {@@ -356,43 +245,3 @@ func isCompactedToolPrelude(content string) bool {}return letters >= 48 && whitespace <= 1}--// findJSONToolCallLeak returns the byte offset to strip from when a plain-JSON-// tool-call leak is found, or -1 if none. A match must (a) sit at start of-// content or after a newline, (b) be a JSON object whose first key is "name",-// and (c) reference a tool in tools.IsKnownToolName's allowlist. Returning-// the position of the leading newline (or 0) lets the caller preserve any-// natural-language text before the leak via TrimSpace.-func findJSONToolCallLeak(content string) int {- if content == "" {- return -1- }- matches := jsonToolCallRe.FindAllStringSubmatchIndex(content, -1)- for _, m := range matches {- if len(m) < 4 || m[2] < 0 || m[3] < 0 {- continue- }- name := content[m[2]:m[3]]- if tools.IsKnownToolName(name) {- return m[0]- }- }- return -1-}--func findPlainFunctionToolCallLeak(content string) int {- if content == "" {- return -1- }- matches := plainFunctionToolCallRe.FindAllStringSubmatchIndex(content, -1)- for _, m := range matches {- if len(m) < 4 || m[2] < 0 || m[3] < 0 {- continue- }- name := content[m[2]:m[3]]- if tools.IsKnownToolName(name) {- return m[2]- }- }- return -1-}diff --git a/internal/ai/chat/agentic_sanitize_test.go b/internal/ai/chat/agentic_sanitize_test.goindex f423f4f9c5..62dabf1831 100644--- a/internal/ai/chat/agentic_sanitize_test.go+++ b/internal/ai/chat/agentic_sanitize_test.go@@ -66,6 +66,16 @@ func TestCleanToolCallArtifacts(t *testing.T) {"Let me inspect the device nodes.\npulse_read(target_host=\"current_resource\", command=\"ls /dev | wc -l\")","Let me inspect the device nodes.",},+ {+ "shared native Assistant question leak: JSON",+ "I need to ask a follow-up.\n{\"name\":\"pulse_question\",\"input\":{\"questions\":[{\"id\":\"target\",\"question\":\"Which resource?\"}]}}",+ "I need to ask a follow-up.",+ },+ {+ "shared native Assistant question leak: function",+ "I need to clarify the target.\npulse_question(questions=[{\"id\":\"target\",\"question\":\"Which resource?\"}])",+ "I need to clarify the target.",+ },{"plain function leak inline after prose","I will check that now. pulse_read(target_host=\"current_resource\", command=\"lsblk\")",@@ -159,8 +169,10 @@ func TestContainsToolCallMarker(t *testing.T) {// Plain-JSON tool-call leak detection during streaming.{"json leak pulse_query", "{\"name\": \"pulse_query\", \"parameters\": {}}", true},{"json leak pulse_discovery", "prose\n{\"name\": \"pulse_discovery\", \"parameters\": {}}", true},+ {"json leak pulse_question", "prose\n{\"name\": \"pulse_question\", \"input\": {}}", true},{"json leak with code-fence", "answer\n```json\n{\"name\": \"pulse_query\"}", true},{"plain function leak pulse_read", "pulse_read(target_host=\"current_resource\", command=\"lsblk\")", true},+ {"plain function leak pulse_question", "pulse_question(questions=[])", true},{"plain function leak after prose", "text. pulse_read(target_host=\"current_resource\")", true},{"json non-tool name", "{\"name\": \"frobnicate\", \"parameters\": {}}", false},{"json unrelated object", "{\"foo\": \"bar\"}", false},@@ -205,6 +217,13 @@ func TestAppendVisibleContentBeforeToolLeak(t *testing.T) {}}+func TestSplitTrailingPotentialToolNamePrefixUsesAssistantProviderCatalog(t *testing.T) {+ visible, held := splitTrailingPotentialToolNamePrefix("I need to clarify. pulse_quest")+ if visible != "I need to clarify. " || held != "pulse_quest" {+ t.Fatalf("splitTrailingPotentialToolNamePrefix() = (%q, %q), want Assistant-native pulse_question prefix held", visible, held)+ }+}+func TestAppendVisibleContentBeforeToolLeak_DropsCompactedPrelude(t *testing.T) {var builder strings.Buildervar pending stringdiff --git a/internal/ai/chat/agentic_test.go b/internal/ai/chat/agentic_test.goindex bdb367ce23..943258309a 100644--- a/internal/ai/chat/agentic_test.go+++ b/internal/ai/chat/agentic_test.go@@ -855,6 +855,7 @@ func TestParallelToolExecution(t *testing.T) {assert.Equal(t, "call_a", toolResultIDs[0])assert.Equal(t, "call_b", toolResultIDs[1])assert.Equal(t, "call_c", toolResultIDs[2])+ assert.Equal(t, 3, loop.GetTotalToolCalls())// Verify final responselastMsg := results[len(results)-1]diff --git a/internal/ai/chat/agentic_tool_display.go b/internal/ai/chat/agentic_tool_display.goindex f87759cbd5..2b71a82602 100644--- a/internal/ai/chat/agentic_tool_display.go+++ b/internal/ai/chat/agentic_tool_display.go@@ -3,6 +3,8 @@ package chatimport ("encoding/json""fmt"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")func formatToolInputForFrontend(toolName string, input map[string]interface{}, emptyIfNil bool) (inputStr string, rawInput string) {@@ -18,7 +20,7 @@ func formatToolInputForFrontend(toolName string, input map[string]interface{}, e}// Special handling for command execution tools to avoid showing raw JSON.- if toolName == "pulse_control" || toolName == "pulse_run_command" || toolName == "control" {+ if toolName == agentcapabilities.PulseControlToolName || toolName == agentcapabilities.PulseRunCommandToolName || toolName == "control" {if cmd, ok := input["command"].(string); ok {return fmt.Sprintf("Running: %s", cmd), rawInput}diff --git a/internal/ai/chat/agentic_verification.go b/internal/ai/chat/agentic_verification.goindex 9ff6ed56bb..aa112b9f76 100644--- a/internal/ai/chat/agentic_verification.go+++ b/internal/ai/chat/agentic_verification.go@@ -2,7 +2,6 @@ package chatimport ("encoding/json"- "strings")// truncateForLog truncates a string for logging, adding "..." if truncated.@@ -13,41 +12,6 @@ func truncateForLog(s string, maxLen int) string {return s[:maxLen] + "..."}-// toolResultHasVerificationOK checks whether a tool output includes structured verification-// evidence indicating the mutation was confirmed.-//-// Expected shape (JSON text):-//-// { "verification": { "ok": true, ... } }-func toolResultHasVerificationOK(resultText string) bool {- if resultText == "" {- return false- }- jsonStart := strings.Index(resultText, "{")- if jsonStart == -1 {- return false- }-- var obj map[string]interface{}- if err := json.Unmarshal([]byte(resultText[jsonStart:]), &obj); err != nil {- return false- }- vAny, ok := obj["verification"]- if !ok {- return false- }- vMap, ok := vAny.(map[string]interface{})- if !ok {- return false- }- okAny, ok := vMap["ok"]- if !ok {- return false- }- okBool, ok := okAny.(bool)- return ok && okBool-}-// toolCallKey returns a string key for a tool call (name + serialized input)// used to detect repeated identical calls in the agentic loop.func toolCallKey(name string, input map[string]interface{}) string {diff --git a/internal/ai/chat/cost_recording_test.go b/internal/ai/chat/cost_recording_test.goindex 79bd23fd24..29e56c5a61 100644--- a/internal/ai/chat/cost_recording_test.go+++ b/internal/ai/chat/cost_recording_test.go@@ -24,9 +24,10 @@ func TestRecordChatTurnCost_RecordsWhenStoreConfigured(t *testing.T) {loop := &AgenticLoop{totalInputTokens: 120,totalOutputTokens: 45,+ totalToolCalls: 3,}- svc.recordChatTurnCost(loop, "anthropic:claude-test")+ svc.recordChatTurnCost(loop, "anthropic:claude-test", sessionHandoffKindResourceContext)events := store.ListEvents(1)if len(events) != 1 {@@ -36,6 +37,12 @@ func TestRecordChatTurnCost_RecordsWhenStoreConfigured(t *testing.T) {if ev.UseCase != "chat" {t.Errorf("UseCase = %q, want chat", ev.UseCase)}+ if ev.ContextScope != sessionHandoffKindResourceContext {+ t.Errorf("ContextScope = %q, want %q", ev.ContextScope, sessionHandoffKindResourceContext)+ }+ if ev.ToolCallCount != 3 {+ t.Errorf("ToolCallCount = %d, want 3", ev.ToolCallCount)+ }if ev.InputTokens != 120 || ev.OutputTokens != 45 {t.Errorf("tokens = (%d, %d), want (120, 45)", ev.InputTokens, ev.OutputTokens)}@@ -57,7 +64,7 @@ func TestRecordChatTurnCost_NoopWhenStoreNil(t *testing.T) {totalOutputTokens: 50,}// Must not panic.- svc.recordChatTurnCost(loop, "anthropic:claude-test")+ svc.recordChatTurnCost(loop, "anthropic:claude-test", "")}// TestRecordChatTurnCost_NoopWhenZeroTokens verifies the recorder@@ -71,7 +78,7 @@ func TestRecordChatTurnCost_NoopWhenZeroTokens(t *testing.T) {totalInputTokens: 0,totalOutputTokens: 0,}- svc.recordChatTurnCost(loop, "anthropic:claude-test")+ svc.recordChatTurnCost(loop, "anthropic:claude-test", "")if events := store.ListEvents(1); len(events) != 0 {t.Errorf("expected 0 events for zero-token loop, got %d", len(events))@@ -87,7 +94,7 @@ func TestRecordChatTurnCost_HandlesMalformedModel(t *testing.T) {svc := &Service{costStore: store}loop := &AgenticLoop{totalInputTokens: 10, totalOutputTokens: 5}- svc.recordChatTurnCost(loop, "bare-model-name")+ svc.recordChatTurnCost(loop, "bare-model-name", "")events := store.ListEvents(1)if len(events) != 1 {@@ -100,3 +107,81 @@ func TestRecordChatTurnCost_HandlesMalformedModel(t *testing.T) {t.Errorf("RequestModel should be passed through verbatim, got %q", events[0].RequestModel)}}++func TestAssistantContextScopeForChatTurn_ClassifiesGovernedContext(t *testing.T) {+ tests := []struct {+ name string+ req ExecuteRequest+ findingID string+ context string+ resources []HandoffResource+ actions []HandoffAction+ metadata HandoffMetadata+ mentionsFound bool+ want string+ }{+ {+ name: "finding handoff",+ findingID: "finding-123",+ want: sessionHandoffKindPatrolFinding,+ },+ {+ name: "governed action",+ actions: []HandoffAction{{+ ActionID: "action-123",+ }},+ want: "governed_action",+ },+ {+ name: "patrol run metadata",+ metadata: HandoffMetadata{+ Kind: sessionHandoffKindPatrolRun,+ RunID: "run-123",+ },+ want: sessionHandoffKindPatrolRun,+ },+ {+ name: "resource handoff",+ resources: []HandoffResource{{+ ID: "vm:node:100",+ Type: "vm",+ }},+ want: sessionHandoffKindResourceContext,+ },+ {+ name: "structured mention",+ req: ExecuteRequest{Mentions: []StructuredMention{{+ ID: "vm:node:100",+ Name: "web-01",+ Type: "vm",+ }}},+ want: sessionHandoffKindResourceContext,+ },+ {+ name: "scoped context fallback",+ context: "[Context]\nOperator-selected state",+ want: sessionHandoffKindScopedContext,+ },+ {+ name: "plain chat",+ want: "",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got := assistantContextScopeForChatTurn(+ tt.req,+ tt.findingID,+ tt.context,+ tt.resources,+ tt.actions,+ tt.metadata,+ tt.mentionsFound,+ )+ if got != tt.want {+ t.Fatalf("scope = %q, want %q", got, tt.want)+ }+ })+ }+}diff --git a/internal/ai/chat/fsm.go b/internal/ai/chat/fsm.goindex 59a257315e..edf37250bb 100644--- a/internal/ai/chat/fsm.go+++ b/internal/ai/chat/fsm.go@@ -2,8 +2,9 @@ package chatimport ("fmt"- "strings""time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")// SessionState represents the current state of a chat session's workflow.@@ -25,38 +26,23 @@ const (StateVerifying SessionState = "VERIFYING")-// ToolKind classifies tool calls for FSM state transitions-type ToolKind int+// ToolKind classifies tool calls for FSM state transitions.+type ToolKind = agentcapabilities.ToolCallKindconst (// ToolKindResolve - discovery/query tools that find resources- ToolKindResolve ToolKind = iota+ ToolKindResolve = agentcapabilities.ToolCallKindResolve// ToolKindRead - read-only tools (logs, metrics, status, config)- ToolKindRead+ ToolKindRead = agentcapabilities.ToolCallKindRead// ToolKindWrite - mutating tools (restart, stop, start, delete, file write)- ToolKindWrite+ ToolKindWrite = agentcapabilities.ToolCallKindWrite// ToolKindUserInput - interactive tools that request user input (does not advance FSM state)- ToolKindUserInput+ ToolKindUserInput = agentcapabilities.ToolCallKindUserInput)-func (k ToolKind) String() string {- switch k {- case ToolKindResolve:- return "resolve"- case ToolKindRead:- return "read"- case ToolKindWrite:- return "write"- case ToolKindUserInput:- return "user_input"- default:- return "unknown"- }-}-// SessionFSM tracks the workflow state for a chat session.// This is stored alongside ResolvedContext in the session.type SessionFSM struct {@@ -93,7 +79,7 @@ type SessionFSM struct {// PendingRecovery tracks a blocked operation that may be retried after recoverytype PendingRecovery struct {RecoveryID string `json:"recovery_id"`- ErrorCode string `json:"error_code"` // FSM_BLOCKED, STRICT_RESOLUTION+ ErrorCode string `json:"error_code"` // ErrCodeFSMBlocked, ErrCodeStrictResolutionTool string `json:"tool"` // original tool that was blockedCreatedAt time.Time `json:"created_at"`Attempts int `json:"attempts"` // number of recovery attempts@@ -312,152 +298,10 @@ func (e *FSMBlockedError) Error() string {// Code returns the error code for tool responsesfunc (e *FSMBlockedError) Code() string {- return "FSM_BLOCKED"-}--// classifyToolByName classifies a tool by its name and action parameters.-// This is the centralized classification that new tools must be added to.-func classifyToolByName(toolName string, args map[string]interface{}) ToolKind {- // Get action if present- action, _ := args["action"].(string)- actionLower := strings.ToLower(action)- operation, _ := args["operation"].(string)- operationLower := strings.ToLower(operation)-- switch toolName {- case "pulse_question":- return ToolKindUserInput-- // === Query/Discovery tools (Resolve) ===- case "pulse_query":- // query actions: search, get, config, topology, list, health- return ToolKindResolve-- case "pulse_discovery":- return ToolKindResolve-- // === Read-only tools (Read) ===- case "pulse_metrics":- return ToolKindRead-- case "pulse_alerts":- // Most alert operations are read-only- switch actionLower {- case "resolve", "dismiss":- return ToolKindWrite // These modify alert state- default:- return ToolKindRead- }-- case "pulse_storage":- return ToolKindRead-- case "pulse_kubernetes":- switch actionLower {- case "scale", "restart", "delete_pod", "exec":- return ToolKindWrite- default:- return ToolKindRead- }-- case "pulse_knowledge":- // knowledge operations: remember is write, recall is read- switch actionLower {- case "remember", "note", "save":- return ToolKindWrite- default:- return ToolKindRead- }-- case "pulse_pmg":- return ToolKindRead-- case "pulse_read":- // pulse_read is ALWAYS read-only - enforced at the tool layer- // This tool never triggers VERIFYING state, even when running commands- return ToolKindRead-- // === Control tools (Write) ===- case "pulse_control":- // pulse_control is always a write (guest control, run command)- return ToolKindWrite-- case "pulse_docker":- // Docker operations depend on action- switch actionLower {- case "control":- return ToolKindWrite- case "update", "check_updates", "trigger_update":- return ToolKindWrite- default:- // services, tasks, swarm, list - read operations- return ToolKindRead- }-- case "pulse_file_edit":- // File operations depend on action- switch actionLower {- case "read":- return ToolKindRead- case "write", "append":- return ToolKindWrite- default:- return ToolKindRead- }-- // === Legacy tool names (for backwards compatibility) ===- case "pulse_run_command":- return ToolKindWrite-- case "pulse_control_guest":- return ToolKindWrite-- case "pulse_control_docker":- return ToolKindWrite-- case "pulse_search_resources", "pulse_get_resource", "pulse_get_topology",- "pulse_list_infrastructure", "pulse_get_connection_health":- return ToolKindResolve-- case "pulse_get_docker_logs", "pulse_get_performance_metrics",- "pulse_get_temperatures", "pulse_get_baselines", "pulse_get_patterns":- return ToolKindRead-- // === Patrol tools ===- case "patrol_get_findings":- return ToolKindRead // Reading existing findings doesn't require discovery- case "patrol_report_finding", "patrol_resolve_finding":- return ToolKindWrite- }-- // Check if the action/operation parameter indicates a write- writeActions := map[string]bool{- "start": true, "stop": true, "restart": true, "delete": true,- "shutdown": true, "reboot": true, "write": true, "append": true,- "update": true, "trigger": true, "resolve": true, "dismiss": true,- "control": true,- }- if writeActions[actionLower] || writeActions[operationLower] {- return ToolKindWrite- }-- // Check if the action/operation parameter indicates a read- readActions := map[string]bool{- "get": true, "list": true, "search": true, "query": true,- "read": true, "logs": true, "status": true, "health": true,- "describe": true, "inspect": true, "show": true,- }- if readActions[actionLower] || readActions[operationLower] {- return ToolKindRead- }-- // Default to WRITE for unknown tools (security-safe: requires discovery first,- // verification after). This ensures new tools don't accidentally bypass FSM gates.- return ToolKindWrite+ return agentcapabilities.ErrCodeFSMBlocked}// ClassifyToolCall classifies a tool call for FSM state transitions.-// This is the exported function that the agentic loop should use.func ClassifyToolCall(toolName string, args map[string]interface{}) ToolKind {- return classifyToolByName(toolName, args)+ return agentcapabilities.ClassifyToolCall(toolName, args)}diff --git a/internal/ai/chat/fsm_additional_test.go b/internal/ai/chat/fsm_additional_test.goindex 9c0d181ec6..bfc31e3cd0 100644--- a/internal/ai/chat/fsm_additional_test.go+++ b/internal/ai/chat/fsm_additional_test.go@@ -3,6 +3,8 @@ package chatimport ("strings""testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")func TestFSMBlockedErrorFormatting(t *testing.T) {@@ -16,8 +18,8 @@ func TestFSMBlockedErrorFormatting(t *testing.T) {if !strings.Contains(msg, "pulse_control") {t.Fatalf("expected tool name in error message")}- if err.Code() != "FSM_BLOCKED" {- t.Fatalf("expected FSM_BLOCKED code")+ if err.Code() != agentcapabilities.ErrCodeFSMBlocked {+ t.Fatalf("expected %s code", agentcapabilities.ErrCodeFSMBlocked)}err = &FSMBlockedError{State: StateReading, Reason: "test"}diff --git a/internal/ai/chat/fsm_test.go b/internal/ai/chat/fsm_test.goindex 3adea738a6..471e9c332b 100644--- a/internal/ai/chat/fsm_test.go+++ b/internal/ai/chat/fsm_test.go@@ -3,6 +3,8 @@ package chatimport ("strings""testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")func TestFSM_InitialState(t *testing.T) {@@ -287,7 +289,7 @@ func TestClassifyToolCall(t *testing.T) {{"pulse_search_resources", "pulse_search_resources", nil, ToolKindResolve},// Interactive user input tools- {"pulse_question", "pulse_question", nil, ToolKindUserInput},+ {"pulse_question", agentcapabilities.PulseQuestionToolName, nil, ToolKindUserInput},// Read tools{"pulse_metrics", "pulse_metrics", nil, ToolKindRead},@@ -333,6 +335,11 @@ func TestClassifyToolCall(t *testing.T) {// Unknown tool defaults to write so state-changing safety policy applies.{"unknown_tool", "some_new_tool", nil, ToolKindWrite},+ // Legacy native Assistant compatibility aliases are classified by the shared core.+ {"legacy run_command", agentcapabilities.LegacyAssistantRunCommandToolName, nil, ToolKindWrite},+ {"legacy fetch_url", agentcapabilities.LegacyAssistantFetchURLToolName, nil, ToolKindRead},+ {"legacy set_resource_url", agentcapabilities.LegacyAssistantSetResourceURLToolName, nil, ToolKindWrite},+// Action parameter fallback{"generic restart", "some_tool", map[string]interface{}{"action": "restart"}, ToolKindWrite},{"generic stop", "some_tool", map[string]interface{}{"action": "stop"}, ToolKindWrite},@@ -355,7 +362,7 @@ func TestFSM_UserInputDoesNotAdvanceState(t *testing.T) {t.Fatalf("initial state=%s, want %s", fsm.State, StateResolving)}- fsm.OnToolSuccess(ToolKindUserInput, "pulse_question")+ fsm.OnToolSuccess(ToolKindUserInput, agentcapabilities.PulseQuestionToolName)if fsm.State != StateResolving {t.Fatalf("state after user input=%s, want %s", fsm.State, StateResolving)@@ -394,7 +401,7 @@ func TestFSM_RecoveryTracking(t *testing.T) {fsm := NewSessionFSM()// Track a pending recovery- recoveryID := fsm.TrackPendingRecovery("FSM_BLOCKED", "pulse_control")+ recoveryID := fsm.TrackPendingRecovery(agentcapabilities.ErrCodeFSMBlocked, "pulse_control")if recoveryID == "" {t.Error("TrackPendingRecovery should return a recovery ID")}@@ -415,8 +422,8 @@ func TestFSM_RecoveryTracking(t *testing.T) {if pr == nil {t.Error("CheckRecoverySuccess should return the pending recovery")}- if pr.ErrorCode != "FSM_BLOCKED" {- t.Errorf("ErrorCode = %s, want FSM_BLOCKED", pr.ErrorCode)+ if pr.ErrorCode != agentcapabilities.ErrCodeFSMBlocked {+ t.Errorf("ErrorCode = %s, want %s", pr.ErrorCode, agentcapabilities.ErrCodeFSMBlocked)}if pr.Tool != "pulse_control" {t.Errorf("Tool = %s, want pulse_control", pr.Tool)diff --git a/internal/ai/chat/knowledge_extractor.go b/internal/ai/chat/knowledge_extractor.goindex 233316b941..090408c89d 100644--- a/internal/ai/chat/knowledge_extractor.go+++ b/internal/ai/chat/knowledge_extractor.go@@ -17,7 +17,8 @@ type FactEntry struct {}// ExtractFacts deterministically extracts knowledge facts from a tool result.-// No LLM calls. Parses the JSON text from FormatToolResult() output.+// No LLM calls. Parses the JSON text projected through+// agentcapabilities.ToolResultText.// Returns empty slice on parse errors or unrecognized tools — never panics.//// Tool results use NewJSONResult (direct struct marshaling), NOT ToolResponse wrapper.diff --git a/internal/ai/chat/metrics.go b/internal/ai/chat/metrics.goindex db1f641e0b..7d982ef610 100644--- a/internal/ai/chat/metrics.go+++ b/internal/ai/chat/metrics.go@@ -5,6 +5,7 @@ import ("sync""github.com/prometheus/client_golang/prometheus"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")// maxLabelLen is the maximum length for a metric label value@@ -219,7 +220,7 @@ func (c *AIMetricsTelemetryCallback) RecordStrictResolutionBlock(tool, action stif c.metrics != nil {c.metrics.RecordStrictResolutionBlock(tool, action)// Strict resolution returns policy facts; the model owns any follow-up.- c.metrics.RecordAutoRecoveryAttempt("STRICT_RESOLUTION", tool)+ c.metrics.RecordAutoRecoveryAttempt(agentcapabilities.ErrCodeStrictResolution, tool)}}@@ -242,6 +243,6 @@ func (c *AIMetricsTelemetryCallback) RecordRoutingMismatchBlock(tool, targetKindif c.metrics != nil {c.metrics.RecordRoutingMismatchBlock(tool, targetKind, childKind)// Routing mismatch returns policy facts; the model owns any follow-up.- c.metrics.RecordAutoRecoveryAttempt("ROUTING_MISMATCH", tool)+ c.metrics.RecordAutoRecoveryAttempt(agentcapabilities.ErrCodeRoutingMismatch, tool)}}diff --git a/internal/ai/chat/metrics_additional_test.go b/internal/ai/chat/metrics_additional_test.goindex 22cf3be976..0b1b962fb4 100644--- a/internal/ai/chat/metrics_additional_test.go+++ b/internal/ai/chat/metrics_additional_test.go@@ -1,6 +1,12 @@package chat-import "testing"+import (+ "os"+ "strings"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+)func TestAIMetricsRecording(t *testing.T) {m := GetAIMetrics()@@ -16,8 +22,8 @@ func TestAIMetricsRecording(t *testing.T) {m.RecordStrictResolutionBlock("validateResolvedResource", "restart")m.RecordRoutingMismatchBlock("pulse_control", "node", "vm")m.RecordPhantomDetected("provider", "model")- m.RecordAutoRecoveryAttempt("STRICT_RESOLUTION", "pulse_query")- m.RecordAutoRecoverySuccess("STRICT_RESOLUTION", "pulse_query")+ m.RecordAutoRecoveryAttempt(agentcapabilities.ErrCodeStrictResolution, "pulse_query")+ m.RecordAutoRecoverySuccess(agentcapabilities.ErrCodeStrictResolution, "pulse_query")m.RecordAgenticIteration("provider", "model")cb := NewAIMetricsTelemetryCallback()@@ -26,3 +32,27 @@ func TestAIMetricsRecording(t *testing.T) {cb.RecordAutoRecoverySuccess("ERR", "tool")cb.RecordRoutingMismatchBlock("pulse_control", "node", "vm")}++func TestAIMetricsTelemetryUsesSharedToolResponseErrorCodes(t *testing.T) {+ src, err := os.ReadFile("metrics.go")+ if err != nil {+ t.Fatalf("read metrics.go: %v", err)+ }+ text := string(src)+ for _, fragment := range []string{+ "agentcapabilities.ErrCodeStrictResolution",+ "agentcapabilities.ErrCodeRoutingMismatch",+ } {+ if !strings.Contains(text, fragment) {+ t.Fatalf("metrics telemetry must use shared error-code vocabulary; missing %s", fragment)+ }+ }+ for _, literal := range []string{+ `RecordAutoRecoveryAttempt("STRICT_RESOLUTION"`,+ `RecordAutoRecoveryAttempt("ROUTING_MISMATCH"`,+ } {+ if strings.Contains(text, literal) {+ t.Fatalf("metrics telemetry must not hardcode shared tool-response error codes; found %s", literal)+ }+ }+}diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.goindex 12ccfa9fd9..8192e3aa35 100644--- a/internal/ai/chat/service.go+++ b/internal/ai/chat/service.go@@ -10,6 +10,7 @@ import ("time""github.com/google/uuid"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentcontext""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"@@ -40,28 +41,29 @@ type AgentServer interface {ExecuteCommand(ctx context.Context, agentID string, cmd agentexec.ExecuteCommandPayload) (*agentexec.CommandResultPayload, error)}-// MCP provider type aliases for external use+// Assistant provider type aliases for API wiring. MCP remains the external+// adapter surface; these seams feed the native Pulse Assistant tool registry.type (- MCPAlertProvider = tools.AlertProvider- MCPFindingsProvider = tools.FindingsProvider- MCPBaselineProvider = tools.BaselineProvider- MCPPatternProvider = tools.PatternProvider- MCPMetricsHistoryProvider = tools.MetricsHistoryProvider- MCPBackupProvider = tools.BackupProvider- MCPGuestConfigProvider = tools.GuestConfigProvider- MCPAppContainerConfigProvider = tools.AppContainerConfigProvider- MCPDiskHealthProvider = tools.DiskHealthProvider- MCPUpdatesProvider = tools.UpdatesProvider- MCPAppContainerActionProvider = tools.AppContainerActionProvider- MCPAppContainerReadProvider = tools.AppContainerReadProvider- AgentProfileManager = tools.AgentProfileManager- FindingsManager = tools.FindingsManager- MetadataUpdater = tools.MetadataUpdater- IncidentRecorderProvider = tools.IncidentRecorderProvider- EventCorrelatorProvider = tools.EventCorrelatorProvider- KnowledgeStoreProvider = tools.KnowledgeStoreProvider- MCPDiscoveryProvider = tools.DiscoveryProvider- MCPUnifiedResourceProvider = tools.UnifiedResourceProvider+ AssistantAlertProvider = tools.AlertProvider+ AssistantFindingsProvider = tools.FindingsProvider+ AssistantBaselineProvider = tools.BaselineProvider+ AssistantPatternProvider = tools.PatternProvider+ AssistantMetricsHistoryProvider = tools.MetricsHistoryProvider+ AssistantBackupProvider = tools.BackupProvider+ AssistantGuestConfigProvider = tools.GuestConfigProvider+ AssistantAppContainerConfigProvider = tools.AppContainerConfigProvider+ AssistantDiskHealthProvider = tools.DiskHealthProvider+ AssistantUpdatesProvider = tools.UpdatesProvider+ AssistantAppContainerActionProvider = tools.AppContainerActionProvider+ AssistantAppContainerReadProvider = tools.AppContainerReadProvider+ AgentProfileManager = tools.AgentProfileManager+ FindingsManager = tools.FindingsManager+ MetadataUpdater = tools.MetadataUpdater+ IncidentRecorderProvider = tools.IncidentRecorderProvider+ EventCorrelatorProvider = tools.EventCorrelatorProvider+ KnowledgeStoreProvider = tools.KnowledgeStoreProvider+ AssistantDiscoveryProvider = tools.DiscoveryProvider+ AssistantUnifiedResourceProvider = tools.UnifiedResourceProvider)// Config holds service configuration@@ -264,6 +266,38 @@ func (s *Service) unregisterActiveLoop(sessionID string, loop *AgenticLoop) {}}+func assistantContextScopeForChatTurn(+ req ExecuteRequest,+ handoffFindingID string,+ handoffContext string,+ handoffResources []HandoffResource,+ handoffActions []HandoffAction,+ handoffMetadata HandoffMetadata,+ mentionsFound bool,+) string {+ if strings.TrimSpace(handoffFindingID) != "" || strings.TrimSpace(req.FindingID) != "" {+ return sessionHandoffKindPatrolFinding+ }+ if len(normalizeHandoffActions(handoffActions)) > 0 {+ return "governed_action"+ }+ metadata := NormalizeHandoffMetadata(handoffMetadata)+ switch metadata.Kind {+ case sessionHandoffKindPatrolAssessment,+ sessionHandoffKindPatrolConfigurationFailure,+ sessionHandoffKindPatrolRun,+ sessionHandoffKindResourceContext:+ return metadata.Kind+ }+ if len(normalizeHandoffResources(handoffResources)) > 0 || len(req.Mentions) > 0 || mentionsFound {+ return sessionHandoffKindResourceContext+ }+ if strings.TrimSpace(handoffContext) != "" {+ return sessionHandoffKindScopedContext+ }+ return ""+}+// recordChatTurnCost records a cost.UsageEvent for a completed (or// failed) user-chat agentic turn. Uses the totals accumulated by the// loop's stream callbacks so the recorded numbers match what the@@ -271,7 +305,7 @@ func (s *Service) unregisterActiveLoop(sessionID string, loop *AgenticLoop) {// not configured or when the loop consumed zero tokens (an early// failure before the first turn completed). UseCase is "chat" — the// canonical taxonomy noted on cost.UsageEvent.UseCase.-func (s *Service) recordChatTurnCost(loop *AgenticLoop, requestModel string) {+func (s *Service) recordChatTurnCost(loop *AgenticLoop, requestModel, contextScope string) {if s == nil || loop == nil {return}@@ -293,12 +327,14 @@ func (s *Service) recordChatTurnCost(loop *AgenticLoop, requestModel string) {}}store.Record(cost.UsageEvent{- Timestamp: time.Now(),- Provider: providerName,- RequestModel: requestModel,- UseCase: "chat",- InputTokens: inputTokens,- OutputTokens: outputTokens,+ Timestamp: time.Now(),+ Provider: providerName,+ RequestModel: requestModel,+ UseCase: "chat",+ ContextScope: strings.TrimSpace(contextScope),+ ToolCallCount: loop.GetTotalToolCalls(),+ InputTokens: inputTokens,+ OutputTokens: outputTokens,})}@@ -427,7 +463,7 @@ func (s *Service) Start(ctx context.Context) error {log.Info().Str("model", s.cfg.GetChatModel()).Str("data_dir", dataDir).- Msg("Pulse AI (direct) started")+ Msg("Pulse Assistant service started")return nil}@@ -445,7 +481,7 @@ func (s *Service) Stop(ctx context.Context) error {}s.actionAuditStore = nil}- log.Info().Msg("pulse AI (direct) stopped")+ log.Info().Msg("Pulse Assistant service stopped")return nil}@@ -484,7 +520,7 @@ func (s *Service) Restart(ctx context.Context, newCfg *config.AIConfig) error {log.Info().Str("model", s.cfg.GetChatModel()).- Msg("Pulse AI restarted with new config")+ Msg("Pulse Assistant service restarted with new config")return nil}@@ -792,6 +828,7 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac}}}+ contextScope := assistantContextScopeForChatTurn(req, handoffFindingID, handoffContext, handoffResources, handoffActions, handoffMetadata, mentionsFound)// Run agentic loop. Tool selection is model-owned: the turn always carries// the full governed manifest, and the selected model decides whether to// answer directly, ask, or call tools. The only manifest-boundary@@ -909,7 +946,7 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbacresultMessages, err := loop.ExecuteWithTools(ctx, session.ID, messages, filteredTools, attemptCallback)s.unregisterActiveLoop(session.ID, loop)resultMessages = sanitizeMessagesForHandoffResourcePolicy(resultMessages, handoffResources, handoffResourceProvider)- s.recordChatTurnCost(loop, attempt.Model)+ s.recordChatTurnCost(loop, attempt.Model, contextScope)log.Debug().Str("session_id", session.ID).@@ -1037,7 +1074,7 @@ func (s *Service) assistantInventoryTopologyContextForDirectAnswer(ctx context.Cif err != nil || result.IsError {return assistantInventoryTopologyContext{}, false}- resultText := strings.TrimSpace(FormatToolResult(result))+ resultText := strings.TrimSpace(agentcapabilities.ToolResultText(result))if resultText == "" {return assistantInventoryTopologyContext{}, false}@@ -2962,6 +2999,19 @@ func (s *Service) ListAvailableTools(ctx context.Context, prompt string) []strinreturn names}+// AssistantSurfaceToolContract returns the live native Assistant surface tool+// summary for the current runtime mode. It keeps API/UI consumers on the+// executor-owned projection instead of rebuilding tool buckets from names.+func (s *Service) AssistantSurfaceToolContract(_ context.Context) agentcapabilities.SurfaceToolContract {+ s.mu.RLock()+ executor := s.executor+ s.mu.RUnlock()++ return executor.AssistantSurfaceToolContract(agentcapabilities.AssistantProviderToolOptions{+ IncludeQuestionTool: !s.isAutonomousModeEnabled(),+ })+}+// ListSessions returns all sessions// maxSessionHandoffRefreshPerList bounds how many sessions get their handoff// action status re-checked per list call. The list is newest-first, so this@@ -3301,7 +3351,7 @@ func (s *Service) GetExecutor() *tools.PulseToolExecutor {// Provider setter methods-func (s *Service) SetAlertProvider(provider MCPAlertProvider) {+func (s *Service) SetAlertProvider(provider AssistantAlertProvider) {s.mu.Lock()defer s.mu.Unlock()if s.executor != nil {@@ -3309,7 +3359,7 @@ func (s *Service) SetAlertProvider(provider MCPAlertProvider) {}}-func (s *Service) SetFindingsProvider(provider MCPFindingsProvider) {+func (s *Service) SetFindingsProvider(provider AssistantFindingsProvider) {s.mu.Lock()defer s.mu.Unlock()if s.executor != nil {@@ -3317,7 +3367,7 @@ func (s *Service) SetFindingsProvider(provider MCPFindingsProvider) {}}-func (s *Service) SetBaselineProvider(provider MCPBaselineProvider) {+func (s *Service) SetBaselineProvider(provider AssistantBaselineProvider) {s.mu.Lock()defer s.mu.Unlock()if s.executor != nil {@@ -3325,7 +3375,7 @@ func (s *Service) SetBaselineProvider(provider MCPBaselineProvider) {}}-func (s *Service) SetPatternProvider(provider MCPPatternProvider) {+func (s *Service) SetPatternProvider(provider AssistantPatternProvider) {s.mu.Lock()defer s.mu.Unlock()if s.executor != nil {@@ -3333,7 +3383,7 @@ func (s *Service) SetPatternProvider(provider MCPPatternProvider) {}}-func (s *Service) SetMetricsHistory(provider MCPMetricsHistoryProvider) {+func (s *Service) SetMetricsHistory(provider AssistantMetricsHistoryProvider) {s.mu.Lock()defer s.mu.Unlock()if s.executor != nil {@@ -3341,7 +3391,7 @@ func (s *Service) SetMetricsHistory(provider MCPMetricsHistoryProvider) {}}-func (s *Service) SetBackupProvider(provider MCPBackupProvider) {+func (s *Service) SetBackupProvider(provider AssistantBackupProvider) {s.mu.Lock()defer s.mu.Unlock()if s.executor != nil {@@ -3349,7 +3399,7 @@ func (s *Service) SetBackupProvider(provider MCPBackupProvider) {}}-func (s *Service) SetGuestConfigProvider(provider MCPGuestConfigProvider) {+func (s *Service) SetGuestConfigProvider(provider AssistantGuestConfigProvider) {s.mu.Lock()defer s.mu.Unlock()if s.executor != nil {@@ -3357,7 +3407,7 @@ func (s *Service) SetGuestConfigProvider(provider MCPGuestConfigProvider) {}}-func (s *Service) SetAppContainerConfigProvider(provider MCPAppContainerConfigProvider) {+func (s *Service) SetAppContainerConfigProvider(provider AssistantAppContainerConfigProvider) {s.mu.Lock()defer s.mu.Unlock()if s.executor != nil {@@ -3365,7 +3415,7 @@ func (s *Service) SetAppContainerConfigProvider(provider MCPAppContainerConfigPr}}-func (s *Service) SetDiskHealthProvider(provider MCPDiskHealthProvider) {+func (s *Service) SetDiskHealthProvider(provider AssistantDiskHealthProvider) {s.mu.Lock()defer s.mu.Unlock()if s.executor != nil {@@ -3373,7 +3423,7 @@ func (s *Service) SetDiskHealthProvider(provider MCPDiskHealthProvider) {}}-func (s *Service) SetUpdatesProvider(provider MCPUpdatesProvider) {+func (s *Service) SetUpdatesProvider(provider AssistantUpdatesProvider) {s.mu.Lock()defer s.mu.Unlock()if s.executor != nil {@@ -3429,7 +3479,7 @@ func (s *Service) SetKnowledgeStoreProvider(provider KnowledgeStoreProvider) {}}-func (s *Service) SetUnifiedResourceProvider(provider tools.UnifiedResourceProvider) {+func (s *Service) SetUnifiedResourceProvider(provider AssistantUnifiedResourceProvider) {s.mu.Lock()defer s.mu.Unlock()s.unifiedResourceProvider = provider@@ -3449,7 +3499,7 @@ func (s *Service) SetReadState(readState unifiedresources.ReadState) {}}-func (s *Service) SetAppContainerActionProvider(provider MCPAppContainerActionProvider) {+func (s *Service) SetAppContainerActionProvider(provider AssistantAppContainerActionProvider) {s.mu.Lock()defer s.mu.Unlock()if s.executor != nil {@@ -3457,7 +3507,7 @@ func (s *Service) SetAppContainerActionProvider(provider MCPAppContainerActionPr}}-func (s *Service) SetAppContainerReadProvider(provider MCPAppContainerReadProvider) {+func (s *Service) SetAppContainerReadProvider(provider AssistantAppContainerReadProvider) {s.mu.Lock()defer s.mu.Unlock()if s.executor != nil {@@ -3465,7 +3515,7 @@ func (s *Service) SetAppContainerReadProvider(provider MCPAppContainerReadProvid}}-func (s *Service) SetDiscoveryProvider(provider MCPDiscoveryProvider) {+func (s *Service) SetDiscoveryProvider(provider AssistantDiscoveryProvider) {s.mu.Lock()defer s.mu.Unlock()s.discoveryProvider = provider@@ -3522,15 +3572,7 @@ func (s *Service) SetAutonomousMode(enabled bool) {// ExecuteCommand executes a command directly via the tool executor (bypasses LLM)// This is used for auto-executing fixes in full autonomy modefunc (s *Service) ExecuteCommand(ctx context.Context, command, targetHost string) (output string, exitCode int, err error) {- s.mu.RLock()- executor := s.executor- s.mu.RUnlock()-- if executor == nil {- return "", -1, fmt.Errorf("executor not available")- }-- // Build args for pulse_run_command+ // Build args for the shared command registry tool.args := map[string]interface{}{"command": command,"run_on_host": true,@@ -3539,31 +3581,17 @@ func (s *Service) ExecuteCommand(ctx context.Context, command, targetHost stringargs["target_host"] = targetHost}- // Execute the command- result, toolErr := executor.ExecuteTool(ctx, "pulse_run_command", args)- if toolErr != nil {- return "", -1, toolErr- }-- // Extract text from result content- var resultText string- for _, content := range result.Content {- if content.Type == "text" {- resultText += content.Text+ outcome, executionErr := s.executeAssistantRegistryToolDirect(ctx, agentcapabilities.PulseRunCommandToolName, args, agentcapabilities.DirectToolExecutionOptions{+ FailurePrefix: "command execution failed",+ ApprovalRequiredMessage: "command requires approval (unexpected in autonomous mode)",+ PolicyBlockedMessage: "command blocked by security policy",+ })+ resultText := outcome.OutputText+ if executionErr != nil {+ if outcome.Interpretation.IsError {+ return resultText, 1, executionErr}- }-- // Parse the result- if result.IsError {- return resultText, 1, fmt.Errorf("command execution failed: %s", resultText)- }-- // Check if approval was required (this shouldn't happen in autonomous mode, but just in case)- if strings.HasPrefix(resultText, "APPROVAL_REQUIRED:") {- return "", -1, fmt.Errorf("command requires approval (unexpected in autonomous mode)")- }- if strings.HasPrefix(resultText, "POLICY_BLOCKED:") {- return "", -1, fmt.Errorf("command blocked by security policy")+ return resultText, -1, executionErr}// Check for exit code in result@@ -3635,7 +3663,7 @@ func (s *Service) applyChatContextSettings() {StatelessContext = DefaultStatelessContext}-// buildSystemPrompt builds the base system prompt for the AI.+// buildSystemPrompt builds the base system prompt for Pulse Assistant.// Mode-specific context (autonomous vs controlled) is added dynamically by the AgenticLoop.//// Philosophy: This prompt provides identity, context, and tool policy. Tool@@ -3650,10 +3678,12 @@ func (s *Service) buildSystemPromptForOfferedTools(offeredTools []providers.Tool}func (s *Service) buildSystemPromptWithToolGovernance(toolGovernance string) string {- return `You are Pulse AI, a knowledgeable infrastructure assistant. You pair-program with the user on their homelab and infrastructure tasks.+ return `You are Pulse Assistant, the first-party in-app Pulse Intelligence surface for governed infrastructure operations. You work with the user on their homelab and infrastructure tasks.` + toolGovernance + `+` + agentcapabilities.BuildPulseAssistantOperatingInstructions() + `+## INFRASTRUCTURE TOPOLOGY- Resources are organized hierarchically: nodes → VMs/containers → Docker containers- target_host specifies where commands run (host name, container name, or VM name)@@ -3709,146 +3739,53 @@ func (s *Service) buildToolGovernancePromptSection() string {}func (s *Service) buildToolGovernancePromptSectionForOfferedTools(offeredTools []providers.Tool) string {- offeredNames := make(map[string]bool, len(offeredTools))- orderedOfferedNames := make([]string, 0, len(offeredTools))- for _, tool := range offeredTools {- name := strings.TrimSpace(tool.Name)- if name == "" || offeredNames[name] {- continue- }- offeredNames[name] = true- orderedOfferedNames = append(orderedOfferedNames, name)+ orderedOfferedNames := agentcapabilities.ProviderToolNames(offeredTools)+ if manifest, ok := agentcapabilities.ProviderToolGovernanceDescriptors(offeredTools); ok {+ return agentcapabilities.BuildAssistantToolGovernancePromptSection(manifest, orderedOfferedNames)}return s.buildToolGovernancePromptSectionForOfferedToolNames(orderedOfferedNames)}func (s *Service) buildToolGovernancePromptSectionForOfferedToolNames(orderedOfferedNames []string) string {- offeredFilter := map[string]bool(nil)- if orderedOfferedNames != nil {- offeredFilter = make(map[string]bool, len(orderedOfferedNames))- for _, name := range orderedOfferedNames {- if trimmed := strings.TrimSpace(name); trimmed != "" {- offeredFilter[trimmed] = true- }- }- }-- if offeredFilter != nil && len(offeredFilter) == 0 {- return strings.Join([]string{- "## AVAILABLE TOOL GOVERNANCE",- "No Pulse tools are offered for this turn. Answer directly from the user's message and safe conversation context.",- "Do not claim to inspect infrastructure, run commands, or use Pulse data unless that evidence is already present in the conversation.",- }, "\n")- }-manifest := []tools.ToolGovernanceDescriptor(nil)if s != nil && s.executor != nil {manifest = s.executor.ListToolGovernance()}if len(manifest) == 0 {manifest = fallbackAssistantToolGovernance()- }-- var b strings.Builder- b.WriteString("## AVAILABLE TOOL GOVERNANCE\n")- b.WriteString("This manifest is generated from Pulse's governed tool registry. Use only tools that are actually offered by the provider for the current turn.\n")- emitted := make(map[string]bool, len(manifest))- for _, tool := range manifest {- if offeredFilter != nil && !offeredFilter[tool.Name] {- continue- }- mode := tool.ActionMode- if mode == "" {- mode = tools.ToolActionRead+ if orderedOfferedNames == nil {+ orderedOfferedNames = fallbackAssistantToolGovernanceOfferedNames(manifest)}- policy := strings.TrimSpace(tool.ApprovalPolicy)- if policy == "" {- policy = "no approval required"- }- summary := strings.TrimSpace(tool.Summary)- if summary == "" {- summary = firstPromptLine(tool.Description)- }- if summary != "" {- b.WriteString(fmt.Sprintf("- %s: mode=%s; approval=%s; %s\n", tool.Name, mode, policy, summary))- } else {- b.WriteString(fmt.Sprintf("- %s: mode=%s; approval=%s\n", tool.Name, mode, policy))- }- emitted[tool.Name] = true}- if offeredFilter == nil || offeredFilter[pulseQuestionToolName] {- b.WriteString("- pulse_question: mode=interactive; approval=user answer required; asks the user for missing information using a structured prompt in interactive chat only.\n")- emitted[pulseQuestionToolName] = true- }- if offeredFilter != nil {- for _, name := range orderedOfferedNames {- if emitted[name] {- continue- }- b.WriteString(fmt.Sprintf("- %s: mode=read; approval=no approval required; Offered by Pulse for this turn.\n", name))- emitted[name] = true- }- }- return strings.TrimRight(b.String(), "\n")+ return agentcapabilities.BuildAssistantToolGovernancePromptSection(manifest, orderedOfferedNames)}func fallbackAssistantToolGovernance() []tools.ToolGovernanceDescriptor {- return []tools.ToolGovernanceDescriptor{- {- Name: "pulse_query",- ActionMode: tools.ToolActionRead,- ApprovalPolicy: "no approval required",- Summary: "Resolves canonical infrastructure identity, topology, config, and health without changing state.",- },- {- Name: "pulse_read",- ActionMode: tools.ToolActionRead,- ApprovalPolicy: "no approval required; write-like commands are rejected",- Summary: "Runs read-only infrastructure inspection such as logs, file reads, tails, and safe exec.",- },- {- Name: "pulse_discovery",- ActionMode: tools.ToolActionMixed,- ApprovalPolicy: "no approval required; run uses read-only evidence collection and updates the discovery cache",- Summary: "Reads or refreshes discovered service paths, ports, and bind mounts for known resources.",- },- {- Name: "pulse_control",- ActionMode: tools.ToolActionWrite,- ApprovalPolicy: "hidden in read-only mode; approval required in controlled mode",- Summary: "Runs shared Pulse control actions and can control only resources that explicitly support shared Pulse actions.",- },- {- Name: "pulse_file_edit",- ActionMode: tools.ToolActionWrite,- ApprovalPolicy: "hidden in read-only mode; approval required in controlled mode",- Summary: "Changes files through the governed file-edit path.",- },- {- Name: "pulse_docker",- ActionMode: tools.ToolActionMixed,- ApprovalPolicy: "read/list actions are safe; control and update subactions require approval in controlled mode",- Summary: "Lists Docker state and performs governed Docker control/update subactions.",- },- {- Name: "pulse_kubernetes",- ActionMode: tools.ToolActionMixed,- ApprovalPolicy: "read/list/log actions are safe; scale, restart, delete, and exec subactions require approval in controlled mode",- Summary: "Reads Kubernetes topology and runs governed workload-control subactions.",- },- }+ return tools.CanonicalToolGovernanceForManifestSurface(+ tools.ControlLevelControlled,+ agentcapabilities.CanonicalManifest(),+ agentcapabilities.SurfaceIDPulseAssistant,+ )}-func firstPromptLine(description string) string {- description = strings.TrimSpace(description)- if description == "" {- return ""+func fallbackAssistantToolGovernanceOfferedNames(governance []tools.ToolGovernanceDescriptor) []string {+ affordances, _ := agentcapabilities.ManifestSurfaceAffordances(+ agentcapabilities.CanonicalManifest(),+ agentcapabilities.SurfaceIDPulseAssistant,+ )+ names := make([]string, 0, len(governance)+1)+ if affordances.Tools {+ for _, descriptor := range governance {+ if name := strings.TrimSpace(descriptor.Name); name != "" {+ names = append(names, name)+ }+ }}- if idx := strings.Index(description, "\n"); idx >= 0 {- description = strings.TrimSpace(description[:idx])+ if affordances.InteractiveQuestions {+ names = append(names, agentcapabilities.PulseQuestionToolName)}- return strings.Join(strings.Fields(description), " ")+ return names}func (s *Service) injectRecentSessionContext(sessionID string, messages []Message, sessions *SessionStore) {@@ -4002,8 +3939,10 @@ func firstNonEmptyRecentString(values ...string) string {}func (s *Service) toolsForExecutionMode(autonomousMode bool, patrolMode bool) []providers.Tool {- mcpTools := s.executor.ListTools()- providerTools := ConvertMCPToolsToProvider(mcpTools)+ includeQuestionTool := !autonomousMode && !patrolMode+ providerTools := s.executor.AssistantProviderTools(agentcapabilities.AssistantProviderToolOptions{+ IncludeQuestionTool: includeQuestionTool,+ })// Patrol may be scoped by explicit product configuration, but never by// prompt keyword inference. The selected Patrol model owns tool choice.@@ -4018,10 +3957,6 @@ func (s *Service) toolsForExecutionMode(autonomousMode bool, patrolMode bool) []}filtered := append([]providers.Tool{}, providerTools...)- // pulse_question is interactive; exclude it for autonomous runs (Pulse Patrol).- if !autonomousMode {- filtered = append(filtered, userQuestionTool())- }log.Debug().Int("total_tools", len(providerTools)).Int("tool_manifest_count", len(filtered)).@@ -4327,19 +4262,19 @@ func (s *Service) filterToolsForPatrol(providerTools []providers.Tool) []providefiltered := make([]providers.Tool, 0, len(providerTools))for _, tool := range providerTools {switch tool.Name {- case "pulse_docker":+ case agentcapabilities.PulseDockerToolName:if !includeDocker {continue}- case "pulse_storage":+ case agentcapabilities.PulseStorageToolName:if !includeStorage {continue}- case "pulse_kubernetes":+ case agentcapabilities.PulseKubernetesToolName:if !includeK8s {continue}- case "pulse_pmg":+ case agentcapabilities.PulsePMGToolName:if !includePMG {continue}@@ -4359,50 +4294,42 @@ func (s *Service) isAutonomousModeEnabled() bool {return s.cfg != nil && s.cfg.IsAutonomous()}-// ExecuteMCPTool executes an MCP tool directly by name with arguments-// This is used for executing investigation fixes that are MCP tool calls-func (s *Service) ExecuteMCPTool(ctx context.Context, toolName string, args map[string]interface{}) (string, error) {+// ExecuteAssistantTool executes a native Assistant registry tool directly by+// name with arguments. This is used for replaying approved investigation fixes+// through the same shared tool-result interpretation as model-selected calls.+func (s *Service) ExecuteAssistantTool(ctx context.Context, toolName string, args map[string]interface{}) (string, error) {+ outcome, executionErr := s.executeAssistantRegistryToolDirect(ctx, toolName, args, agentcapabilities.DirectToolExecutionOptions{+ FailurePrefix: "tool execution failed",+ ApprovalRequiredMessage: "tool requires approval (unexpected in fix execution)",+ PolicyBlockedMessage: "tool blocked by security policy",+ })+ if executionErr != nil {+ return outcome.OutputText, executionErr+ }++ return outcome.OutputText, nil+}++func (s *Service) executeAssistantRegistryToolDirect(ctx context.Context, toolName string, args map[string]interface{}, opts agentcapabilities.DirectToolExecutionOptions) (agentcapabilities.DirectToolExecutionOutcome, error) {s.mu.RLock()executor := s.executors.mu.RUnlock()if executor == nil {- return "", fmt.Errorf("executor not available")+ return agentcapabilities.DirectToolExecutionOutcome{}, fmt.Errorf("executor not available")}log.Debug().Str("tool", toolName).Interface("args", args).- Msg("Executing MCP tool directly")+ Msg("Executing Assistant registry tool directly")- // Execute the toolresult, toolErr := executor.ExecuteTool(ctx, toolName, args)if toolErr != nil {- return "", toolErr- }-- // Extract text from result content- var resultText string- for _, content := range result.Content {- if content.Type == "text" {- resultText += content.Text- }- }-- // Check for error- if result.IsError {- return resultText, fmt.Errorf("tool execution failed: %s", resultText)- }-- // Check if approval was required- if strings.HasPrefix(resultText, "APPROVAL_REQUIRED:") {- return "", fmt.Errorf("tool requires approval (unexpected in fix execution)")- }- if strings.HasPrefix(resultText, "POLICY_BLOCKED:") {- return "", fmt.Errorf("tool blocked by security policy")+ return agentcapabilities.DirectToolExecutionOutcome{}, toolErr}- return resultText, nil+ return agentcapabilities.InterpretDirectToolExecution(result, opts)}// Execute provides non-streaming execution (for compatibility)diff --git a/internal/ai/chat/service_patrol_additional_test.go b/internal/ai/chat/service_patrol_additional_test.goindex 4ca64f13e2..1f48cf8a78 100644--- a/internal/ai/chat/service_patrol_additional_test.go+++ b/internal/ai/chat/service_patrol_additional_test.go@@ -639,16 +639,16 @@ func TestService_isAutonomousModeEnabled(t *testing.T) {}}-func TestService_ExecuteMCPTool(t *testing.T) {+func TestService_ExecuteAssistantTool(t *testing.T) {service := &Service{}- if _, err := service.ExecuteMCPTool(context.Background(), "pulse_knowledge", nil); err == nil {+ if _, err := service.ExecuteAssistantTool(context.Background(), "pulse_knowledge", nil); err == nil {t.Fatalf("expected error when executor missing")}executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{KnowledgeStoreProvider: mockKnowledgeStore{}})service.executor = executor- result, err := service.ExecuteMCPTool(context.Background(), "pulse_knowledge", map[string]interface{}{+ result, err := service.ExecuteAssistantTool(context.Background(), "pulse_knowledge", map[string]interface{}{"action": "recall","resource_id": "vm1",})@@ -659,7 +659,7 @@ func TestService_ExecuteMCPTool(t *testing.T) {t.Fatalf("expected result text")}- if _, err := service.ExecuteMCPTool(context.Background(), "pulse_knowledge", map[string]interface{}{+ if _, err := service.ExecuteAssistantTool(context.Background(), "pulse_knowledge", map[string]interface{}{"action": "recall",}); err == nil {t.Fatalf("expected error for missing resource_id")diff --git a/internal/ai/chat/service_tooling_test.go b/internal/ai/chat/service_tooling_test.goindex 850f15256f..43b5bdcc32 100644--- a/internal/ai/chat/service_tooling_test.go+++ b/internal/ai/chat/service_tooling_test.go@@ -4,10 +4,12 @@ import ("context""encoding/json""fmt"+ "os""strings""testing""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/ai/providers""github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"@@ -95,6 +97,15 @@ func toolNameSet(list []providers.Tool) map[string]bool {return set}+func stringSliceContains(values []string, want string) bool {+ for _, value := range values {+ if value == want {+ return true+ }+ }+ return false+}+func TestToolsForExecutionMode_InteractiveExposesGovernedTools(t *testing.T) {exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{StateProvider: fakeStateProvider{},@@ -221,6 +232,49 @@ func TestAssistantPromptQualifiesForLocalInventoryCount(t *testing.T) {}}+func TestAssistantSurfaceToolContractUsesRuntimeAssistantProjection(t *testing.T) {+ exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{+ StateProvider: fakeStateProvider{},+ AgentServer: fakeAgentServer{},+ ReadState: &fakeCanonicalReadState{},+ ControlLevel: tools.ControlLevelControlled,+ })+ svc := &Service{+ executor: exec,+ cfg: &config.AIConfig{ControlLevel: config.ControlLevelControlled},+ }++ interactive := svc.AssistantSurfaceToolContract(context.Background())+ if interactive.SurfaceID != agentcapabilities.SurfaceIDPulseAssistant {+ t.Fatalf("surface id = %q", interactive.SurfaceID)+ }+ if interactive.ToolSource != agentcapabilities.SurfaceToolSourceAssistantRegistry {+ t.Fatalf("tool source = %q", interactive.ToolSource)+ }+ if !stringSliceContains(interactive.ToolNames, agentcapabilities.PulseQueryToolName) {+ t.Fatalf("interactive surface missing registry query tool: %#v", interactive.ToolNames)+ }+ if !stringSliceContains(interactive.RegistryToolNames, agentcapabilities.PulseQueryToolName) {+ t.Fatalf("interactive surface missing registry bucket: %#v", interactive.RegistryToolNames)+ }+ if !stringSliceContains(interactive.NativeToolNames, agentcapabilities.PulseQuestionToolName) {+ t.Fatalf("interactive surface missing native question bucket: %#v", interactive.NativeToolNames)+ }+ if len(interactive.CapabilityNames) != 0 {+ t.Fatalf("Assistant surface must not expose MCP capability names: %#v", interactive.CapabilityNames)+ }++ svc.SetAutonomousMode(true)+ autonomous := svc.AssistantSurfaceToolContract(context.Background())+ if stringSliceContains(autonomous.NativeToolNames, agentcapabilities.PulseQuestionToolName) ||+ stringSliceContains(autonomous.ToolNames, agentcapabilities.PulseQuestionToolName) {+ t.Fatalf("autonomous Assistant surface must not expose interactive question tool: %+v", autonomous)+ }+ if !stringSliceContains(autonomous.RegistryToolNames, agentcapabilities.PulseQueryToolName) {+ t.Fatalf("autonomous surface should retain registry tools: %#v", autonomous.RegistryToolNames)+ }+}+func TestToolsForExecutionMode_AutonomousNonPatrolExposesGovernedTools(t *testing.T) {exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{StateProvider: fakeStateProvider{},@@ -247,6 +301,12 @@ func TestBuildSystemPrompt_DoesNotClaimGenericVMControl(t *testing.T) {prompt := svc.buildSystemPrompt()+ if !strings.Contains(prompt, "You are Pulse Assistant, the first-party in-app Pulse Intelligence surface") {+ t.Fatalf("expected system prompt to name the native Assistant surface, got %q", prompt)+ }+ if strings.Contains(prompt, "You are Pulse AI") {+ t.Fatalf("system prompt must not use legacy Pulse AI surface identity, got %q", prompt)+ }if strings.Contains(prompt, "Run commands on hosts, containers, and VMs") {t.Fatalf("expected system prompt to avoid blanket VM control claim, got %q", prompt)}@@ -309,6 +369,20 @@ func TestBuildSystemPrompt_CurrentResourceRequiresResourceHandoff(t *testing.T)}}+func TestBuildSystemPrompt_IncludesSharedPulseIntelligenceOperatingInstructions(t *testing.T) {+ svc := &Service{}++ prompt := svc.buildSystemPrompt()+ shared := agentcapabilities.BuildPulseAssistantOperatingInstructions()++ if !strings.Contains(prompt, shared) {+ t.Fatalf("expected Assistant system prompt to include shared Pulse Intelligence operating instructions")+ }+ if strings.Contains(prompt, "resources, prompts") || strings.Contains(prompt, "capability metadata as the source of truth") {+ t.Fatalf("Assistant system prompt must not advertise MCP-only operating affordances, got %q", prompt)+ }+}+func TestBuildToolGovernancePromptSection_FallbackDiscoveryMatchesRunContract(t *testing.T) {svc := &Service{}@@ -322,6 +396,120 @@ func TestBuildToolGovernancePromptSection_FallbackDiscoveryMatchesRunContract(t}}+func TestBuildToolGovernancePromptSection_FallbackUsesCanonicalRegistry(t *testing.T) {+ fallback := fallbackAssistantToolGovernance()+ canonical := tools.CanonicalToolGovernanceForManifestSurface(+ tools.ControlLevelControlled,+ agentcapabilities.CanonicalManifest(),+ agentcapabilities.SurfaceIDPulseAssistant,+ )++ if len(fallback) != len(canonical) {+ t.Fatalf("fallback governance length = %d, want canonical registry length %d", len(fallback), len(canonical))+ }+ for i := range canonical {+ if fallback[i] != canonical[i] {+ t.Fatalf("fallback governance[%d] = %#v, want canonical registry descriptor %#v", i, fallback[i], canonical[i])+ }+ }++ prompt := (&Service{}).buildToolGovernancePromptSection()+ for _, tool := range canonical {+ if !strings.Contains(prompt, tool.Name+": mode="+string(tool.ActionMode)) {+ t.Fatalf("expected fallback prompt to include canonical governance for %s, got %q", tool.Name, prompt)+ }+ }+ if strings.Contains(prompt, "patrol_report_finding") ||+ strings.Contains(prompt, "patrol_resolve_finding") ||+ strings.Contains(prompt, "patrol_get_findings") {+ t.Fatalf("expected Assistant fallback prompt to exclude Patrol-only tools, got %q", prompt)+ }+}++func TestBuildToolGovernancePromptSection_FallbackOfferedNamesUseAssistantAffordances(t *testing.T) {+ fallback := fallbackAssistantToolGovernance()+ names := fallbackAssistantToolGovernanceOfferedNames(fallback)++ if len(names) != len(fallback)+1 {+ t.Fatalf("fallback offered names length = %d, want governance names plus question tool", len(names))+ }+ for i, tool := range fallback {+ if names[i] != tool.Name {+ t.Fatalf("fallback offered names[%d] = %q, want %q", i, names[i], tool.Name)+ }+ }+ if names[len(names)-1] != agentcapabilities.PulseQuestionToolName {+ t.Fatalf("fallback offered names must include manifest-enabled question tool last, got %#v", names)+ }+}++func TestBuildToolGovernancePromptSection_OfferedToolsUseCanonicalFallback(t *testing.T) {+ svc := &Service{}++ prompt := svc.buildToolGovernancePromptSectionForOfferedTools([]providers.Tool{{Name: "pulse_discovery"}})++ if !strings.Contains(prompt, "pulse_discovery: mode=mixed; approval=scope_only (no approval required; run uses read-only evidence collection and updates the discovery cache)") {+ t.Fatalf("expected offered fallback prompt to use canonical discovery governance, got %q", prompt)+ }+ if strings.Contains(prompt, "pulse_control:") {+ t.Fatalf("expected offered fallback prompt to exclude non-offered control tools, got %q", prompt)+ }+}++func TestBuildToolGovernancePromptSection_OfferedToolsUseProviderMetadata(t *testing.T) {+ svc := &Service{}++ prompt := svc.buildToolGovernancePromptSectionForOfferedTools([]providers.Tool{+ {+ Name: "pulse_discovery",+ PulseGovernance: &agentcapabilities.ToolGovernanceDescriptor{+ Name: "pulse_discovery",+ Description: "Discover infrastructure.",+ ActionMode: agentcapabilities.ActionModeMixed,+ ApprovalPolicy: agentcapabilities.ApprovalPolicyScopeOnly,+ ApprovalSummary: "metadata-owned approval summary",+ Summary: "metadata-owned discovery summary",+ },+ },+ })++ if !strings.Contains(prompt, "pulse_discovery: mode=mixed; approval=scope_only (metadata-owned approval summary); metadata-owned discovery summary") {+ t.Fatalf("expected offered tool metadata to drive governance prompt, got %q", prompt)+ }+ if strings.Contains(prompt, "run uses read-only evidence collection and updates the discovery cache") {+ t.Fatalf("expected offered metadata to avoid executor fallback governance, got %q", prompt)+ }+}++func TestBuildToolGovernancePromptSection_OfferedQuestionToolStaysInteractive(t *testing.T) {+ svc := &Service{}++ prompt := svc.buildToolGovernancePromptSectionForOfferedTools([]providers.Tool{{Name: pulseQuestionToolName}})++ if !strings.Contains(prompt, agentcapabilities.PulseQuestionToolGovernancePromptLine()) {+ t.Fatalf("expected Assistant question tool to keep interactive governance, got %q", prompt)+ }+ if strings.Contains(prompt, "pulse_question: mode=read") {+ t.Fatalf("expected Assistant question tool not to use generic fallback governance, got %q", prompt)+ }+ if strings.Contains(prompt, "No Pulse tools are offered") {+ t.Fatalf("expected question-only manifest to be described as an offered interactive tool, got %q", prompt)+ }+}++func TestBuildToolGovernancePromptSection_NoOfferedToolsUsesSharedNoToolsGuidance(t *testing.T) {+ svc := &Service{}++ prompt := svc.buildToolGovernancePromptSectionForOfferedTools([]providers.Tool{})++ if !strings.Contains(prompt, "No Pulse tools are offered for this turn") {+ t.Fatalf("expected no-tools guidance, got %q", prompt)+ }+ if strings.Contains(prompt, "pulse_question:") {+ t.Fatalf("expected no Assistant question tool when no tools are offered, got %q", prompt)+ }+}+func TestToolsForExecutionMode_RecoveryOnlyKeepsStorage(t *testing.T) {exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{RecoveryPointsProvider: &fakeRecoveryPointsProvider{points: []recovery.RecoveryPoint{{@@ -374,7 +562,7 @@ func TestToolsForExecutionMode_PatrolScopeUsesConfigNotPrompt(t *testing.T) {func TestExecuteCommand_SuccessAndExitCode(t *testing.T) {exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{})exec.RegisterTool(tools.RegisteredTool{- Definition: tools.Tool{Name: "pulse_run_command"},+ Definition: tools.Tool{Name: agentcapabilities.PulseRunCommandToolName},Handler: func(ctx context.Context, exec *tools.PulseToolExecutor, args map[string]interface{}) (tools.CallToolResult, error) {return tools.NewTextResult("Command failed (exit code 7): boom"), nil},@@ -397,7 +585,7 @@ func TestExecuteCommand_SuccessAndExitCode(t *testing.T) {func TestExecuteCommand_ErrorAndApprovalPaths(t *testing.T) {exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{})exec.RegisterTool(tools.RegisteredTool{- Definition: tools.Tool{Name: "pulse_run_command"},+ Definition: tools.Tool{Name: agentcapabilities.PulseRunCommandToolName},Handler: func(ctx context.Context, exec *tools.PulseToolExecutor, args map[string]interface{}) (tools.CallToolResult, error) {return tools.NewErrorResult(context.Canceled), nil},@@ -411,7 +599,7 @@ func TestExecuteCommand_ErrorAndApprovalPaths(t *testing.T) {}exec.RegisterTool(tools.RegisteredTool{- Definition: tools.Tool{Name: "pulse_run_command"},+ Definition: tools.Tool{Name: agentcapabilities.PulseRunCommandToolName},Handler: func(ctx context.Context, exec *tools.PulseToolExecutor, args map[string]interface{}) (tools.CallToolResult, error) {return tools.NewTextResult("APPROVAL_REQUIRED: requires approval"), nil},@@ -423,7 +611,36 @@ func TestExecuteCommand_ErrorAndApprovalPaths(t *testing.T) {}}-func TestExecuteMCPTool_ErrorsAndSuccess(t *testing.T) {+func TestExecuteCommandUsesSharedResultTextProjection(t *testing.T) {+ exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{})+ exec.RegisterTool(tools.RegisteredTool{+ Definition: tools.Tool{Name: agentcapabilities.PulseRunCommandToolName},+ Handler: func(ctx context.Context, exec *tools.PulseToolExecutor, args map[string]interface{}) (tools.CallToolResult, error) {+ return tools.CallToolResult{+ Content: []tools.Content{+ {Type: "text", Text: "stdout"},+ {Type: "resource", URI: "file://ignored"},+ {Type: "text"},+ {Type: "text", Text: "stderr"},+ },+ }, nil+ },+ })++ svc := &Service{executor: exec}+ output, code, err := svc.ExecuteCommand(context.Background(), "uptime", "")+ if err != nil {+ t.Fatalf("ExecuteCommand: %v", err)+ }+ if code != 0 {+ t.Fatalf("exit code = %d, want 0", code)+ }+ if output != "stdout\nstderr" {+ t.Fatalf("output = %q, want shared result text projection", output)+ }+}++func TestExecuteAssistantTool_ErrorsAndSuccess(t *testing.T) {exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{})exec.RegisterTool(tools.RegisteredTool{Definition: tools.Tool{Name: "test_tool"},@@ -434,7 +651,7 @@ func TestExecuteMCPTool_ErrorsAndSuccess(t *testing.T) {svc := &Service{executor: exec}- _, err := svc.ExecuteMCPTool(context.Background(), "test_tool", map[string]interface{}{})+ _, err := svc.ExecuteAssistantTool(context.Background(), "test_tool", map[string]interface{}{})if err == nil {t.Fatalf("expected tool error")}@@ -445,7 +662,7 @@ func TestExecuteMCPTool_ErrorsAndSuccess(t *testing.T) {return tools.NewTextResult("POLICY_BLOCKED: nope"), nil},})- _, err = svc.ExecuteMCPTool(context.Background(), "test_tool", map[string]interface{}{})+ _, err = svc.ExecuteAssistantTool(context.Background(), "test_tool", map[string]interface{}{})if err == nil {t.Fatalf("expected policy blocked error")}@@ -456,13 +673,189 @@ func TestExecuteMCPTool_ErrorsAndSuccess(t *testing.T) {return tools.NewTextResult("ok"), nil},})- output, err := svc.ExecuteMCPTool(context.Background(), "test_tool", map[string]interface{}{})+ output, err := svc.ExecuteAssistantTool(context.Background(), "test_tool", map[string]interface{}{})if err != nil || output != "ok" {t.Fatalf("expected success, got output=%q err=%v", output, err)}}-func TestExecuteMCPTool_PulseStorageSnapshotsToleratesMalformedRecoveryMetadata(t *testing.T) {+func TestExecuteAssistantToolUsesSharedResultTextProjection(t *testing.T) {+ exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{})+ exec.RegisterTool(tools.RegisteredTool{+ Definition: tools.Tool{Name: "test_tool"},+ Handler: func(ctx context.Context, exec *tools.PulseToolExecutor, args map[string]interface{}) (tools.CallToolResult, error) {+ return tools.CallToolResult{+ Content: []tools.Content{+ {Type: "text", Text: "first"},+ {Type: "resource", URI: "file://ignored"},+ {Type: "text"},+ {Type: "text", Text: "second"},+ },+ }, nil+ },+ })++ svc := &Service{executor: exec}+ output, err := svc.ExecuteAssistantTool(context.Background(), "test_tool", map[string]interface{}{})+ if err != nil {+ t.Fatalf("ExecuteAssistantTool: %v", err)+ }+ if output != "first\nsecond" {+ t.Fatalf("output = %q, want shared result text projection", output)+ }+}++func TestDirectToolExecutionUsesSharedResultExecutionMapping(t *testing.T) {+ src, err := os.ReadFile("service.go")+ if err != nil {+ t.Fatalf("read service.go: %v", err)+ }+ text := string(src)++ if !strings.Contains(text, "agentcapabilities.InterpretDirectToolExecution(result") {+ t.Fatalf("direct tool execution must use shared result execution mapping")+ }+ for _, fragment := range []string{+ "func (s *Service) executeAssistantRegistryToolDirect(",+ `outcome, executionErr := s.executeAssistantRegistryToolDirect(ctx, agentcapabilities.PulseRunCommandToolName, args, agentcapabilities.DirectToolExecutionOptions{`,+ `outcome, executionErr := s.executeAssistantRegistryToolDirect(ctx, toolName, args, agentcapabilities.DirectToolExecutionOptions{`,+ `result, toolErr := executor.ExecuteTool(ctx, toolName, args)`,+ } {+ if !strings.Contains(text, fragment) {+ t.Fatalf("direct Assistant registry execution must use shared service helper; missing %s", fragment)+ }+ }+ if !strings.Contains(text, "strings.TrimSpace(agentcapabilities.ToolResultText(result))") {+ t.Fatalf("direct topology context must use shared result text projection")+ }+ for _, fragment := range []string{+ "agentcapabilities.HasApprovalRequiredToolMarker(resultText)",+ "agentcapabilities.HasPolicyBlockedToolMarker(resultText)",+ "interpreted := agentcapabilities.InterpretToolResult(result)",+ "interpreted := agentcapabilities.InterpretMCPToolResult(result)",+ "if interpreted.IsError",+ "if interpreted.ApprovalRequired",+ "if interpreted.PolicyBlocked",+ "FormatToolResult(result)",+ "agentcapabilities.DirectMCPToolExecutionOptions",+ "agentcapabilities.InterpretDirectMCPToolExecution(result",+ "agentcapabilities.MCPToolResultText(result)",+ } {+ if strings.Contains(text, fragment) {+ t.Fatalf("direct tool execution must not duplicate shared result execution mapping; found %s", fragment)+ }+ }+}++func TestAgenticLoopUsesSharedProviderToolResultConstruction(t *testing.T) {+ src, err := os.ReadFile("agentic.go")+ if err != nil {+ t.Fatalf("read agentic.go: %v", err)+ }+ text := string(src)++ for _, fragment := range []string{+ "agentcapabilities.ParseApprovalRequiredToolMarkerData(resultText)",+ "inputWithApproval = agentcapabilities.WithApprovalArgument(inputWithApproval, approvalData.ApprovalID)",+ "agentcapabilities.NewProviderToolResultFromToolResult(tc.ID, result)",+ "projection := newProviderToolResultContextProjection(tc.ID, resultText, isError)",+ "ToolResult: &projection.Transcript",+ "ToolResult: &projection.Model",+ } {+ if !strings.Contains(text, fragment) {+ t.Fatalf("agentic loop must use shared provider tool-result construction; missing %s", fragment)+ }+ }+ if strings.Contains(text, "resultText = FormatToolResult(result)") {+ t.Fatalf("agentic loop must not flatten tool results into provider context locally")+ }+ if !strings.Contains(text, "toolCalls = agentcapabilities.NormalizeProviderToolCallsForExecution(data.ToolCalls)") {+ t.Fatalf("agentic loop must normalize provider-emitted tool calls through the shared tools/call projection before execution")+ }+ if strings.Contains(text, "toolCalls = data.ToolCalls") {+ t.Fatalf("agentic loop must not execute raw provider tool-call names or inputs")+ }+ for _, forbidden := range []string{+ "agentcapabilities.ApprovalRequiredToolMarkerPayloadJSON(resultText)",+ "var approvalData struct",+ "\n\t\t\t\t\t\t\tagentcapabilities.WithApprovalArgument(inputWithApproval, approvalData.ApprovalID)",+ } {+ if strings.Contains(text, forbidden) {+ t.Fatalf("agentic loop must use shared approval marker/replay helpers correctly; found %s", forbidden)+ }+ }+ for _, forbidden := range []string{+ "ToolResult: &providers.ToolResult{",+ "ToolResult: &ToolResult{",+ "agentcapabilities.NewProviderToolResultFromMCP(tc.ID, result)",+ "modelResultText := truncateToolResultForModel(resultText)",+ } {+ if strings.Contains(text, forbidden) {+ t.Fatalf("agentic loop must not assemble provider tool-result structs locally; found %s", forbidden)+ }+ }+}++func TestAgenticLoopUsesSharedVerificationEvidenceParser(t *testing.T) {+ agenticSrc, err := os.ReadFile("agentic.go")+ if err != nil {+ t.Fatalf("read agentic.go: %v", err)+ }+ if !strings.Contains(string(agenticSrc), "agentcapabilities.ToolResultHasVerificationOK(resultText)") {+ t.Fatalf("agentic loop must use the shared tool-result verification parser for write self-verification")+ }++ verificationSrc, err := os.ReadFile("agentic_verification.go")+ if err != nil {+ t.Fatalf("read agentic_verification.go: %v", err)+ }+ if strings.Contains(string(verificationSrc), "func toolResultHasVerificationOK(") {+ t.Fatalf("chat must not preserve a local verification evidence parser")+ }+}++func TestAgenticLoopUsesSharedToolResultErrorCodeParser(t *testing.T) {+ src, err := os.ReadFile("agentic.go")+ if err != nil {+ t.Fatalf("read agentic.go: %v", err)+ }+ text := string(src)+ if !strings.Contains(text, "agentcapabilities.ToolResultHasErrorCode(resultText, agentcapabilities.ErrCodeStrictResolution)") {+ t.Fatalf("agentic loop must use the shared tool-result error-code parser for strict-resolution recovery")+ }+ if strings.Contains(text, `strings.Contains(resultText, "STRICT_RESOLUTION")`) {+ t.Fatalf("agentic loop must not branch on local strict-resolution string matching")+ }+}++func TestProviderMessageConversionUsesSharedProviderToolResultConstruction(t *testing.T) {+ src, err := os.ReadFile("agentic_context.go")+ if err != nil {+ t.Fatalf("read agentic_context.go: %v", err)+ }+ text := string(src)++ for _, fragment := range []string{+ "projection := newProviderToolResultContextProjection(m.ToolResult.ToolUseID, m.ToolResult.Content, m.ToolResult.IsError)",+ "pm.ToolResult = &projection.Model",+ "agentcapabilities.NewProviderToolErrorResult(",+ } {+ if !strings.Contains(text, fragment) {+ t.Fatalf("provider message conversion must use shared provider tool-result construction; missing %s", fragment)+ }+ }+ for _, forbidden := range []string{+ "func newProviderToolResult(",+ "func newProviderToolErrorResult(",+ "ToolResult: &providers.ToolResult{",+ } {+ if strings.Contains(text, forbidden) {+ t.Fatalf("provider message conversion must not preserve Assistant-local provider-result wrappers or structs; found %s", forbidden)+ }+ }+}++func TestExecuteAssistantTool_PulseStorageSnapshotsToleratesMalformedRecoveryMetadata(t *testing.T) {completedAt := time.Date(2026, 2, 24, 10, 30, 0, 0, time.UTC)svc := &Service{executor: tools.NewPulseToolExecutor(tools.ExecutorConfig{@@ -496,13 +889,13 @@ func TestExecuteMCPTool_PulseStorageSnapshotsToleratesMalformedRecoveryMetadata(}),}- output, err := svc.ExecuteMCPTool(context.Background(), "pulse_storage", map[string]interface{}{+ output, err := svc.ExecuteAssistantTool(context.Background(), "pulse_storage", map[string]interface{}{"type": "snapshots","guest_id": "100","instance": "pve1",})if err != nil {- t.Fatalf("ExecuteMCPTool(pulse_storage snapshots): %v", err)+ t.Fatalf("ExecuteAssistantTool(pulse_storage snapshots): %v", err)}var resp tools.SnapshotsResponse@@ -520,7 +913,7 @@ func TestExecuteMCPTool_PulseStorageSnapshotsToleratesMalformedRecoveryMetadata(}}-func TestExecuteMCPTool_PulseStorageBackupTasksToleratesMalformedRecoveryMetadata(t *testing.T) {+func TestExecuteAssistantTool_PulseStorageBackupTasksToleratesMalformedRecoveryMetadata(t *testing.T) {startedAt := time.Date(2026, 2, 24, 11, 0, 0, 0, time.UTC)completedAt := time.Date(2026, 2, 24, 11, 15, 0, 0, time.UTC)svc := &Service{@@ -556,14 +949,14 @@ func TestExecuteMCPTool_PulseStorageBackupTasksToleratesMalformedRecoveryMetadat}),}- output, err := svc.ExecuteMCPTool(context.Background(), "pulse_storage", map[string]interface{}{+ output, err := svc.ExecuteAssistantTool(context.Background(), "pulse_storage", map[string]interface{}{"type": "backup_tasks","guest_id": "101","instance": "pve1","status": "OK",})if err != nil {- t.Fatalf("ExecuteMCPTool(pulse_storage backup_tasks): %v", err)+ t.Fatalf("ExecuteAssistantTool(pulse_storage backup_tasks): %v", err)}var resp tools.BackupTasksListResponsediff --git a/internal/ai/chat/session_additional_test.go b/internal/ai/chat/session_additional_test.goindex e92eb3ec34..98e42198df 100644--- a/internal/ai/chat/session_additional_test.go+++ b/internal/ai/chat/session_additional_test.go@@ -450,7 +450,7 @@ func TestSessionStore_ListIncludesSafePatrolRunHandoffSummary(t *testing.T) {"[Patrol Run Context]","Source: Pulse Patrol run history","Run ID: run-runtime-error",- "Run Type: Scoped run",+ "Run Type: Targeted check","Status: error","Runtime Failure: Selected model does not support Patrol tools: No endpoints found that support the provided 'tool_choice' value.","Patrol Analysis: Runtime failure prevented analysis.",@@ -461,7 +461,7 @@ func TestSessionStore_ListIncludesSafePatrolRunHandoffSummary(t *testing.T) {}}, nil, HandoffMetadata{Kind: " patrol_run ",RunID: " run-runtime-error ",- RunType: " Scoped run ",+ RunType: " Targeted check ",RunStatus: " error ",RuntimeFailure: true,}); err != nil {@@ -475,7 +475,7 @@ func TestSessionStore_ListIncludesSafePatrolRunHandoffSummary(t *testing.T) {if metadata != (HandoffMetadata{Kind: sessionHandoffKindPatrolRun,RunID: "run-runtime-error",- RunType: "Scoped run",+ RunType: "Targeted check",RunStatus: "error",RuntimeFailure: true,}) {@@ -500,7 +500,7 @@ func TestSessionStore_ListIncludesSafePatrolRunHandoffSummary(t *testing.T) {if summary.FindingID != "" {t.Fatalf("finding ID = %q, want empty Patrol run summary", summary.FindingID)}- if summary.RunID != "run-runtime-error" || summary.RunType != "Scoped run" || summary.RunStatus != "error" || !summary.RuntimeFailure {+ if summary.RunID != "run-runtime-error" || summary.RunType != "Targeted check" || summary.RunStatus != "error" || !summary.RuntimeFailure {t.Fatalf("run summary = %#v, want safe Patrol run identity", summary)}if !summary.HasModelContext {diff --git a/internal/ai/chat/session_test.go b/internal/ai/chat/session_test.goindex e0ae44470c..7a63514335 100644--- a/internal/ai/chat/session_test.go+++ b/internal/ai/chat/session_test.go@@ -9,6 +9,7 @@ import ("testing""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")@@ -629,6 +630,23 @@ func TestMessage_UsesCanonicalEmptyCollections(t *testing.T) {assert.Contains(t, string(payload), `"input":{}`)}+func TestToolResultUsesSharedAgentCapabilitiesShape(t *testing.T) {+ var shared agentcapabilities.ProviderToolResult = ToolResult{+ ToolUseID: "call-1",+ Content: "done",+ IsError: true,+ }+ assert.Equal(t, "call-1", shared.ToolUseID)++ payload, err := json.Marshal(ToolResult{+ ToolUseID: "call-1",+ Content: "done",+ IsError: true,+ })+ require.NoError(t, err)+ assert.JSONEq(t, `{"tool_use_id":"call-1","content":"done","is_error":true}`, string(payload))+}+func TestGenerateTitle(t *testing.T) {tests := []struct {input stringdiff --git a/internal/ai/chat/tools.go b/internal/ai/chat/tools.godeleted file mode 100644index 0854a25128..0000000000--- a/internal/ai/chat/tools.go+++ /dev/null@@ -1,78 +0,0 @@-package chat--import (- "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"- "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"-)--// ConvertMCPToolsToProvider converts MCP tool definitions to provider tool format-func ConvertMCPToolsToProvider(mcpTools []tools.Tool) []providers.Tool {- result := make([]providers.Tool, 0, len(mcpTools))-- for _, t := range mcpTools {- // Build the input schema in the format expected by providers- inputSchema := make(map[string]interface{})- inputSchema["type"] = "object"-- // Convert properties - always include "properties" even if empty- // OpenAI API requires "properties" to be present as an object- props := make(map[string]interface{})- for name, prop := range t.InputSchema.Properties {- propDef := map[string]interface{}{- "type": prop.Type,- }- if prop.Description != "" {- propDef["description"] = prop.Description- }- if len(prop.Enum) > 0 {- propDef["enum"] = prop.Enum- }- if prop.Default != nil {- propDef["default"] = prop.Default- }- props[name] = propDef- }- inputSchema["properties"] = props-- // Add required fields- if len(t.InputSchema.Required) > 0 {- inputSchema["required"] = t.InputSchema.Required- }-- result = append(result, providers.Tool{- Name: t.Name,- Description: t.Description,- InputSchema: inputSchema,- })- }-- return result-}--// ConvertProviderToolCallToMCP converts a provider tool call to MCP format-func ConvertProviderToolCallToMCP(tc providers.ToolCall) tools.CallToolParams {- return tools.CallToolParams{- Name: tc.Name,- Arguments: tc.Input,- }-}--// FormatToolResult formats a tool result for display-func FormatToolResult(result tools.CallToolResult) string {- if len(result.Content) == 0 {- return ""- }-- // Combine all text content- var text string- for _, c := range result.Content {- if c.Type == "text" && c.Text != "" {- if text != "" {- text += "\n"- }- text += c.Text- }- }-- return text-}diff --git a/internal/ai/chat/tools_test.go b/internal/ai/chat/tools_test.godeleted file mode 100644index 7f51592f9c..0000000000--- a/internal/ai/chat/tools_test.go+++ /dev/null@@ -1,76 +0,0 @@-package chat--import (- "testing"-- "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"- "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"- "github.com/stretchr/testify/assert"-)--func TestToolsUtils(t *testing.T) {- t.Run("ConvertMCPToolsToProvider", func(t *testing.T) {- mcpTools := []tools.Tool{- {- Name: "test_tool",- Description: "A test tool",- InputSchema: tools.InputSchema{- Type: "object",- Properties: map[string]tools.PropertySchema{- "arg1": {- Type: "string",- Description: "First argument",- Enum: []string{"a", "b"},- },- "arg2": {- Type: "number",- Default: 10,- },- },- Required: []string{"arg1"},- },- },- }-- converted := ConvertMCPToolsToProvider(mcpTools)- require := assert.New(t)- require.Len(converted, 1)- require.Equal("test_tool", converted[0].Name)- require.Equal("A test tool", converted[0].Description)-- schema := converted[0].InputSchema- require.Equal("object", schema["type"])- props := schema["properties"].(map[string]interface{})- arg1 := props["arg1"].(map[string]interface{})- require.Equal("string", arg1["type"])- require.Equal("First argument", arg1["description"])- require.Equal([]string{"a", "b"}, arg1["enum"])-- required := schema["required"].([]string)- require.Contains(required, "arg1")- })-- t.Run("ConvertProviderToolCallToMCP", func(t *testing.T) {- tc := providers.ToolCall{- ID: "call1",- Name: "test_tool",- Input: map[string]interface{}{"arg1": "val1"},- }- mcpTC := ConvertProviderToolCallToMCP(tc)- assert.Equal(t, "test_tool", mcpTC.Name)- assert.Equal(t, "val1", mcpTC.Arguments["arg1"])- })-- t.Run("FormatToolResult", func(t *testing.T) {- result := tools.CallToolResult{- Content: []tools.Content{- {Type: "text", Text: "part 1"},- {Type: "text", Text: "part 2"},- },- }- formatted := FormatToolResult(result)- assert.Equal(t, "part 1\npart 2", formatted)-- assert.Equal(t, "", FormatToolResult(tools.CallToolResult{}))- })-}diff --git a/internal/ai/chat/types.go b/internal/ai/chat/types.goindex a21c0eb25c..61e7ce5b02 100644--- a/internal/ai/chat/types.go+++ b/internal/ai/chat/types.go@@ -8,6 +8,7 @@ import ("sync""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/ai/tools")@@ -82,9 +83,16 @@ func EmptyMessage() Message {func (m Message) NormalizeCollections() Message {if m.ToolCalls == nil {m.ToolCalls = []ToolCall{}+ } else {+ toolCalls := make([]ToolCall, len(m.ToolCalls))+ for i := range m.ToolCalls {+ toolCalls[i] = m.ToolCalls[i].NormalizeCollections()+ }+ m.ToolCalls = toolCalls}- for i := range m.ToolCalls {- m.ToolCalls[i] = m.ToolCalls[i].NormalizeCollections()+ if m.ToolResult != nil {+ toolResult := *m.ToolResult+ m.ToolResult = &toolResult}return m}@@ -116,18 +124,52 @@ func EmptyToolCall() ToolCall {}func (t ToolCall) NormalizeCollections() ToolCall {- if t.Input == nil {- t.Input = map[string]interface{}{}+ providerCall := agentcapabilities.ProviderToolCall{+ ID: t.ID,+ Name: t.Name,+ Input: t.Input,+ ThoughtSignature: t.ThoughtSignature,+ }.NormalizeCollections()+ t.ID = providerCall.ID+ t.Name = providerCall.Name+ t.Input = providerCall.Input+ t.ThoughtSignature = providerCall.ThoughtSignature+ if t.Success != nil {+ success := *t.Success+ t.Success = &success}return t}-// ToolResult represents the result of a tool execution-type ToolResult struct {- ToolUseID string `json:"tool_use_id"`- Content string `json:"content"`- IsError bool `json:"is_error,omitempty"`-}+// ToolCallFromProvider stores a provider-facing tool call in the richer+// Assistant transcript shape used for in-app history.+func ToolCallFromProvider(tc agentcapabilities.ProviderToolCall) ToolCall {+ tc = tc.NormalizeCollections()+ return ToolCall{+ ID: tc.ID,+ Name: tc.Name,+ Input: tc.Input,+ ThoughtSignature: tc.ThoughtSignature,+ }.NormalizeCollections()+}++// ProviderToolCall projects a stored Assistant transcript call back to the+// shared provider-facing shape, deliberately excluding in-app output/success+// display fields.+func (t ToolCall) ProviderToolCall() agentcapabilities.ProviderToolCall {+ t = t.NormalizeCollections()+ return agentcapabilities.ProviderToolCall{+ ID: t.ID,+ Name: t.Name,+ Input: t.Input,+ ThoughtSignature: t.ThoughtSignature,+ }.NormalizeCollections()+}++// ToolResult represents the result of a tool execution. It aliases the shared+// Pulse Intelligence provider-result shape so stored Assistant transcripts and+// provider turns do not drift on tool result JSON.+type ToolResult = agentcapabilities.ProviderToolResult// StreamEvent represents a streaming event sent to the frontendtype StreamEvent struct {@@ -329,38 +371,17 @@ type ToolEndData struct {Success bool `json:"success"`}-// ApprovalPlanData is the user-facing subset of the governed action plan.-type ApprovalPlanData struct {- ActionID string `json:"action_id,omitempty"`- RequestID string `json:"request_id,omitempty"`- Summary string `json:"summary,omitempty"`- RequiresApproval bool `json:"requires_approval"`- ApprovalPolicy string `json:"approval_policy,omitempty"`- BlastRadius string `json:"blast_radius,omitempty"`- RollbackAvailable bool `json:"rollback_available"`- PlanHash string `json:"plan_hash,omitempty"`- ExpiresAt string `json:"expires_at,omitempty"`-}+// ApprovalPlanData aliases the shared approval-marker plan subset. The+// browser event shape stays in chat, but the marker payload contract lives in+// agentcapabilities so tool producers and chat consumers cannot drift.+type ApprovalPlanData = agentcapabilities.ApprovalPlanData-// ApprovalContextConfidenceData describes how strongly a proposed action was-// bound to a concrete target before approval.-type ApprovalContextConfidenceData struct {- Level string `json:"level,omitempty"`- Summary string `json:"summary,omitempty"`- Evidence []string `json:"evidence,omitempty"`-}+// ApprovalContextConfidenceData aliases the shared approval-marker confidence+// payload.+type ApprovalContextConfidenceData = agentcapabilities.ApprovalContextConfidenceData-// ApprovalPreflightData describes the pre-execution dry-run and verification boundary.-type ApprovalPreflightData struct {- Target string `json:"target,omitempty"`- CurrentState string `json:"current_state,omitempty"`- IntendedChange string `json:"intended_change,omitempty"`- DryRunAvailable bool `json:"dry_run_available"`- DryRunSummary string `json:"dry_run_summary,omitempty"`- SafetyChecks []string `json:"safety_checks,omitempty"`- VerificationSteps []string `json:"verification_steps,omitempty"`- GeneratedAt string `json:"generated_at,omitempty"`-}+// ApprovalPreflightData aliases the shared approval-marker preflight payload.+type ApprovalPreflightData = agentcapabilities.ApprovalPreflightData// ApprovalNeededData is the data for "approval_needed" eventstype ApprovalNeededData struct {@@ -421,9 +442,9 @@ type DoneData struct {// Control level constantsconst (- ControlLevelReadOnly = "read_only"- ControlLevelControlled = "controlled"- ControlLevelAutonomous = "autonomous"+ ControlLevelReadOnly = string(tools.ControlLevelReadOnly)+ ControlLevelControlled = string(tools.ControlLevelControlled)+ ControlLevelAutonomous = string(tools.ControlLevelAutonomous))// ResolvedResource represents a resource that has been authoritatively resolveddiff --git a/internal/ai/chat/types_additional_test.go b/internal/ai/chat/types_additional_test.goindex 5853ce3021..3f377d6a87 100644--- a/internal/ai/chat/types_additional_test.go+++ b/internal/ai/chat/types_additional_test.go@@ -1,9 +1,12 @@package chatimport (+ "encoding/json""strings""testing""time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")func TestResolvedResource_GettersAndAliases(t *testing.T) {@@ -42,6 +45,122 @@ func TestResolvedResource_GettersAndAliases(t *testing.T) {}}+func TestToolCallProviderProjectionUsesSharedAgentCapabilitiesShape(t *testing.T) {+ success := true+ runtimeCall := ToolCall{+ ID: "call-1",+ Name: "diagnose",+ Output: "in-app output",+ Success: &success,+ ThoughtSignature: json.RawMessage(`{"provider":"gemini"}`),+ }++ projected := runtimeCall.ProviderToolCall()+ var shared agentcapabilities.ProviderToolCall = projected+ if shared.ID != "call-1" || shared.Name != "diagnose" {+ t.Fatalf("shared provider call = %+v", shared)+ }+ if shared.Input == nil {+ t.Fatal("shared provider call input must normalize to an empty object")+ }++ payload, err := json.Marshal(projected)+ if err != nil {+ t.Fatalf("marshal provider projection: %v", err)+ }+ text := string(payload)+ if !strings.Contains(text, `"input":{}`) {+ t.Fatalf("provider projection must retain empty input object, got %s", text)+ }+ if !strings.Contains(text, `"thought_signature":{"provider":"gemini"}`) {+ t.Fatalf("provider projection must retain provider continuation signature, got %s", text)+ }+ if strings.Contains(text, `"output"`) || strings.Contains(text, `"success"`) {+ t.Fatalf("provider projection leaked in-app transcript fields: %s", text)+ }++ roundTrip := ToolCallFromProvider(shared)+ if roundTrip.ID != "call-1" || roundTrip.Name != "diagnose" || roundTrip.Input == nil {+ t.Fatalf("stored runtime call from provider shape = %+v", roundTrip)+ }+}++func TestToolCallProviderProjectionDoesNotAliasInputs(t *testing.T) {+ input := map[string]interface{}{"resource_id": "vm/100"}+ runtimeCall := ToolCall{+ ID: "call-1",+ Name: "diagnose",+ Input: input,+ }+ projected := runtimeCall.ProviderToolCall()+ projected.Input["resource_id"] = "vm/101"+ if input["resource_id"] != "vm/100" {+ t.Fatalf("provider projection aliased transcript input: source=%#v projected=%#v", input, projected.Input)+ }++ providerInput := map[string]interface{}{"resource_id": "vm/200"}+ roundTrip := ToolCallFromProvider(agentcapabilities.ProviderToolCall{+ ID: "call-2",+ Name: "diagnose",+ Input: providerInput,+ })+ roundTrip.Input["resource_id"] = "vm/201"+ if providerInput["resource_id"] != "vm/200" {+ t.Fatalf("provider-to-transcript projection aliased provider input: source=%#v roundTrip=%#v", providerInput, roundTrip.Input)+ }+}++func TestMessageNormalizeCollectionsDoesNotAliasToolCallState(t *testing.T) {+ success := true+ sourceInput := map[string]interface{}{+ "body": map[string]interface{}{+ "resource_id": "vm/100",+ },+ "items": []interface{}{+ map[string]interface{}{"name": "alpha"},+ },+ }+ sourceSignature := json.RawMessage(`{"provider":"gemini"}`)+ sourceResult := agentcapabilities.NewProviderToolResult("call-1", "ok", false)+ source := Message{+ ToolCalls: []ToolCall{{+ ID: "call-1",+ Name: "diagnose",+ Input: sourceInput,+ Success: &success,+ ThoughtSignature: sourceSignature,+ }},+ ToolResult: &sourceResult,+ }++ normalized := source.NormalizeCollections()+ normalized.ToolCalls[0].Name = "changed"+ normalized.ToolCalls[0].Input["body"].(map[string]interface{})["resource_id"] = "vm/101"+ normalized.ToolCalls[0].Input["items"].([]interface{})[0].(map[string]interface{})["name"] = "bravo"+ normalized.ToolCalls[0].ThoughtSignature[0] = '['+ *normalized.ToolCalls[0].Success = false+ normalized.ToolResult.Content = "changed"++ if source.ToolCalls[0].Name != "diagnose" {+ t.Fatalf("message normalization aliased tool-call slice: source=%#v normalized=%#v", source.ToolCalls, normalized.ToolCalls)+ }+ if got := sourceInput["body"].(map[string]interface{})["resource_id"]; got != "vm/100" {+ t.Fatalf("message normalization aliased nested tool input: got %v", got)+ }+ if got := sourceInput["items"].([]interface{})[0].(map[string]interface{})["name"]; got != "alpha" {+ t.Fatalf("message normalization aliased nested tool input slice: got %v", got)+ }+ if string(sourceSignature) != `{"provider":"gemini"}` {+ t.Fatalf("message normalization aliased thought signature: %s", sourceSignature)+ }+ if !success {+ t.Fatalf("message normalization aliased success pointer")+ }+ if sourceResult.Content != "ok" {+ t.Fatalf("message normalization aliased tool result pointer: %+v", sourceResult)+ }+}+func TestResolvedResource_GetBestExecutor(t *testing.T) {res := &ResolvedResource{ReachableVia: []ExecutorPath{diff --git a/internal/ai/cost/store.go b/internal/ai/cost/store.goindex f75d813985..91e306515c 100644--- a/internal/ai/cost/store.go+++ b/internal/ai/cost/store.go@@ -17,6 +17,8 @@ type UsageEvent struct {RequestModel string `json:"request_model"`ResponseModel string `json:"response_model,omitempty"`UseCase string `json:"use_case,omitempty"` // "chat" or "patrol"+ ContextScope string `json:"context_scope,omitempty"`+ ToolCallCount int `json:"tool_call_count,omitempty"`InputTokens int `json:"input_tokens,omitempty"`OutputTokens int `json:"output_tokens,omitempty"`TargetType string `json:"target_type,omitempty"`diff --git a/internal/ai/cost_persistence.go b/internal/ai/cost_persistence.goindex 400012174a..d57edcce48 100644--- a/internal/ai/cost_persistence.go+++ b/internal/ai/cost_persistence.go@@ -30,6 +30,8 @@ func (a *CostPersistenceAdapter) SaveUsageHistory(events []cost.UsageEvent) erroRequestModel: e.RequestModel,ResponseModel: e.ResponseModel,UseCase: e.UseCase,+ ContextScope: e.ContextScope,+ ToolCallCount: e.ToolCallCount,InputTokens: e.InputTokens,OutputTokens: e.OutputTokens,TargetType: e.TargetType,@@ -58,6 +60,8 @@ func (a *CostPersistenceAdapter) LoadUsageHistory() ([]cost.UsageEvent, error) {RequestModel: r.RequestModel,ResponseModel: r.ResponseModel,UseCase: r.UseCase,+ ContextScope: r.ContextScope,+ ToolCallCount: r.ToolCallCount,InputTokens: r.InputTokens,OutputTokens: r.OutputTokens,TargetType: r.TargetType,diff --git a/internal/ai/cost_persistence_test.go b/internal/ai/cost_persistence_test.goindex ca26a6675e..3065dcd9af 100644--- a/internal/ai/cost_persistence_test.go+++ b/internal/ai/cost_persistence_test.go@@ -35,6 +35,8 @@ func TestCostPersistenceAdapter_SaveAndLoad(t *testing.T) {RequestModel: "gpt-4",ResponseModel: "gpt-4",UseCase: "patrol",+ ContextScope: "patrol_run",+ ToolCallCount: 4,InputTokens: 100,OutputTokens: 50,TargetType: "vm",@@ -47,6 +49,7 @@ func TestCostPersistenceAdapter_SaveAndLoad(t *testing.T) {RequestModel: "claude-3-sonnet",ResponseModel: "claude-3-sonnet",UseCase: "chat",+ ContextScope: "resource_context",InputTokens: 200,OutputTokens: 100,TargetType: "container",@@ -81,6 +84,12 @@ func TestCostPersistenceAdapter_SaveAndLoad(t *testing.T) {if loaded[0].UseCase != events[0].UseCase {t.Errorf("expected use case %q, got %q", events[0].UseCase, loaded[0].UseCase)}+ if loaded[0].ContextScope != events[0].ContextScope {+ t.Errorf("expected context scope %q, got %q", events[0].ContextScope, loaded[0].ContextScope)+ }+ if loaded[0].ToolCallCount != events[0].ToolCallCount {+ t.Errorf("expected tool call count %d, got %d", events[0].ToolCallCount, loaded[0].ToolCallCount)+ }}func TestCostPersistenceAdapter_LoadEmpty(t *testing.T) {diff --git a/internal/ai/eval/assertions.go b/internal/ai/eval/assertions.goindex 3319424518..3b8ea3b334 100644--- a/internal/ai/eval/assertions.go+++ b/internal/ai/eval/assertions.go@@ -3,6 +3,8 @@ package evalimport ("fmt""strings"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")// === Common Assertions ===@@ -322,10 +324,10 @@ func AssertToolNotBlocked() Assertion {return func(result *StepResult) AssertionResult {for _, tc := range result.ToolCalls {if strings.Contains(tc.Output, `"blocked":true`) ||- strings.Contains(tc.Output, "ROUTING_MISMATCH") ||- strings.Contains(tc.Output, "FSM_BLOCKED") ||+ strings.Contains(tc.Output, agentcapabilities.ErrCodeRoutingMismatch) ||+ strings.Contains(tc.Output, agentcapabilities.ErrCodeFSMBlocked) ||strings.Contains(tc.Output, "READ_ONLY_VIOLATION") ||- strings.Contains(tc.Output, "STRICT_RESOLUTION") {+ strings.Contains(tc.Output, agentcapabilities.ErrCodeStrictResolution) {return AssertionResult{Name: "tool_not_blocked",Passed: false,diff --git a/internal/ai/findings.go b/internal/ai/findings.goindex 4c977d956d..89b2f72f39 100644--- a/internal/ai/findings.go+++ b/internal/ai/findings.go@@ -129,6 +129,7 @@ const (InvestigationOutcomeFixQueued InvestigationOutcome = "fix_queued" // Fix identified, awaiting approvalInvestigationOutcomeFixExecuted InvestigationOutcome = "fix_executed" // Fix command executedInvestigationOutcomeFixFailed InvestigationOutcome = "fix_failed" // Fix command failed+ InvestigationOutcomeFixRejected InvestigationOutcome = "fix_rejected" // Operator rejected the queued fixInvestigationOutcomeFixVerified InvestigationOutcome = "fix_verified" // Fix command verified successfulInvestigationOutcomeFixVerificationFailed InvestigationOutcome = "fix_verification_failed" // Fix ran but issue persistsInvestigationOutcomeFixVerificationUnknown InvestigationOutcome = "fix_verification_unknown" // Fix ran but verification was inconclusive@@ -210,7 +211,7 @@ type Finding struct {// Investigation fields - tracks autonomous AI investigation of findingsInvestigationSessionID string `json:"investigation_session_id,omitempty"` // Chat session ID if being investigatedInvestigationStatus string `json:"investigation_status,omitempty"` // pending, running, completed, failed, needs_attention- InvestigationOutcome string `json:"investigation_outcome,omitempty"` // resolved, fix_queued, fix_executed, fix_failed, fix_verified, fix_verification_failed, needs_attention, cannot_fix+ InvestigationOutcome string `json:"investigation_outcome,omitempty"` // resolved, fix_queued, fix_executed, fix_failed, fix_rejected, fix_verified, fix_verification_failed, needs_attention, cannot_fixLastInvestigatedAt *time.Time `json:"last_investigated_at,omitempty"` // When last investigation completedInvestigationAttempts int `json:"investigation_attempts"` // Number of investigation attemptsInvestigationRecord *aicontracts.InvestigationRecord `json:"investigation_record,omitempty"` // Durable contextual summary for Assistant/unified intelligence@@ -427,7 +428,7 @@ func deriveLoopState(f *Finding) FindingLoopState {return FindingLoopStateRemediatingcase InvestigationOutcomeFixFailed, InvestigationOutcomeFixVerificationFailed:return FindingLoopStateRemediationFailed- case InvestigationOutcomeFixVerificationUnknown, InvestigationOutcomeNeedsAttention, InvestigationOutcomeCannotFix:+ case InvestigationOutcomeFixRejected, InvestigationOutcomeFixVerificationUnknown, InvestigationOutcomeNeedsAttention, InvestigationOutcomeCannotFix:return FindingLoopStateNeedsAttentioncase InvestigationOutcomeTimedOut:return FindingLoopStateTimedOut@@ -475,6 +476,7 @@ func (f *Finding) ShouldInvestigate(autonomyLevel string) bool {// Don't auto-reinvestigate fully terminal outcomes.if InvestigationOutcome(f.InvestigationOutcome) == InvestigationOutcomeFixVerified ||InvestigationOutcome(f.InvestigationOutcome) == InvestigationOutcomeResolved ||+ InvestigationOutcome(f.InvestigationOutcome) == InvestigationOutcomeFixRejected ||InvestigationOutcome(f.InvestigationOutcome) == InvestigationOutcomeCannotFix ||InvestigationOutcome(f.InvestigationOutcome) == InvestigationOutcomeNeedsAttention ||InvestigationOutcome(f.InvestigationOutcome) == InvestigationOutcomeFixVerificationUnknown {@@ -609,6 +611,7 @@ func (f *Finding) CanRetryInvestigation() bool {if InvestigationOutcome(f.InvestigationOutcome) == InvestigationOutcomeFixQueued ||InvestigationOutcome(f.InvestigationOutcome) == InvestigationOutcomeFixVerified ||InvestigationOutcome(f.InvestigationOutcome) == InvestigationOutcomeResolved ||+ InvestigationOutcome(f.InvestigationOutcome) == InvestigationOutcomeFixRejected ||InvestigationOutcome(f.InvestigationOutcome) == InvestigationOutcomeCannotFix ||InvestigationOutcome(f.InvestigationOutcome) == InvestigationOutcomeNeedsAttention ||InvestigationOutcome(f.InvestigationOutcome) == InvestigationOutcomeFixVerificationUnknown {@@ -1308,6 +1311,303 @@ func normalizeLoadedFinding(f *Finding) bool {return false}+func findingSeverityRank(severity FindingSeverity) int {+ switch severity {+ case FindingSeverityCritical:+ return 3+ case FindingSeverityWarning:+ return 2+ case FindingSeverityWatch:+ return 1+ case FindingSeverityInfo:+ return 0+ default:+ return 0+ }+}++func sameFindingResource(a, b *Finding) bool {+ if a == nil || b == nil {+ return false+ }+ candidatesA := []string{+ strings.TrimSpace(a.ResourceID),+ strings.TrimSpace(a.ResourceName),+ }+ candidatesB := []string{+ strings.TrimSpace(b.ResourceID),+ strings.TrimSpace(b.ResourceName),+ }+ for _, left := range candidatesA {+ if left == "" {+ continue+ }+ for _, right := range candidatesB {+ if right != "" && left == right {+ return true+ }+ }+ }+ return false+}++func normalizedStorageFindingIdentity(value string) string {+ value = strings.TrimSpace(strings.ToLower(value))+ if value == "" {+ return ""+ }+ var b strings.Builder+ word := ""+ flush := func() {+ if word == "" {+ return+ }+ switch word {+ case "storage", "pool", "array":+ word = ""+ return+ }+ if b.Len() > 0 {+ b.WriteByte(' ')+ }+ b.WriteString(word)+ word = ""+ }+ for _, r := range value {+ if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') {+ word += string(r)+ continue+ }+ flush()+ }+ flush()+ return b.String()+}++func storageFindingIdentityCandidates(f *Finding) []string {+ if f == nil {+ return nil+ }+ seen := make(map[string]bool)+ raw := []string{f.ResourceID, f.ResourceName}+ candidates := make([]string, 0, len(raw))+ for _, value := range raw {+ normalized := normalizedStorageFindingIdentity(value)+ if normalized == "" || seen[normalized] {+ continue+ }+ seen[normalized] = true+ candidates = append(candidates, normalized)+ }+ return candidates+}++func sameStorageFindingIdentity(a, b *Finding) bool {+ if sameFindingResource(a, b) {+ return true+ }+ aCandidates := storageFindingIdentityCandidates(a)+ bCandidates := storageFindingIdentityCandidates(b)+ for _, left := range aCandidates {+ for _, right := range bCandidates {+ if left == right {+ return true+ }+ }+ }+ return false+}++func findingTextContainsAny(f *Finding, needles ...string) bool {+ if f == nil {+ return false+ }+ text := strings.ToLower(strings.Join([]string{+ f.Key,+ f.ResourceID,+ f.ResourceName,+ f.ResourceType,+ string(f.Category),+ f.Title,+ f.Description,+ f.Impact,+ f.Recommendation,+ f.Evidence,+ }, " "))+ for _, needle := range needles {+ if strings.Contains(text, needle) {+ return true+ }+ }+ return false+}++func storageFindingLooksLikeStorageRisk(f *Finding) bool {+ if f == nil {+ return false+ }+ if canonicalFindingResourceType(f.ResourceType) == "storage" {+ return true+ }+ return findingTextContainsAny(f, "storage", "pool", "array", "unraid", "zfs", "ceph")+}++func storageFindingHasCapacitySignal(f *Finding) bool {+ if f == nil {+ return false+ }+ if f.Category == FindingCategoryCapacity {+ return true+ }+ return findingTextContainsAny(f, "capacity", "usage", "used", "free", "full", "disk", "%", "tb")+}++func equivalentStorageCapacityFinding(existing, incoming *Finding) bool {+ if !sameStorageFindingIdentity(existing, incoming) {+ return false+ }+ if !storageFindingLooksLikeStorageRisk(existing) || !storageFindingLooksLikeStorageRisk(incoming) {+ return false+ }+ if !storageFindingHasCapacitySignal(existing) || !storageFindingHasCapacitySignal(incoming) {+ return false+ }+ return existing.Category == FindingCategoryCapacity || incoming.Category == FindingCategoryCapacity+}++func normalizedFindingTitle(title string) string {+ return normalizeFindingKey(title)+}++func equivalentActiveFinding(existing, incoming *Finding) bool {+ if existing == nil || incoming == nil || existing.ID == incoming.ID {+ return false+ }+ sameResource := sameFindingResource(existing, incoming)+ sameStorageIdentity := !sameResource && sameStorageFindingIdentity(existing, incoming)+ if !existing.IsActive() || (!sameResource && !sameStorageIdentity) {+ return false+ }++ existingTitle := normalizedFindingTitle(existing.Title)+ incomingTitle := normalizedFindingTitle(incoming.Title)+ if existingTitle != "" && existingTitle == incomingTitle {+ return true+ }++ if equivalentStorageCapacityFinding(existing, incoming) {+ return true+ }++ if existing.Category != "" && incoming.Category != "" && existing.Category != incoming.Category {+ return false+ }++ return SemanticSimilarity(existing, incoming) >= 0.78+}++func (s *FindingsStore) findEquivalentActiveFindingLocked(incoming *Finding) *Finding {+ if incoming == nil {+ return nil+ }+ var best *Finding+ bestScore := 0.0+ for _, existing := range s.findings {+ if !equivalentActiveFinding(existing, incoming) {+ continue+ }+ score := SemanticSimilarity(existing, incoming)+ if best == nil || score > bestScore {+ best = existing+ bestScore = score+ }+ }+ return best+}++func findingHasDuplicateMergeEvent(f *Finding, duplicateID string) bool {+ if f == nil || duplicateID == "" {+ return false+ }+ for _, event := range f.Lifecycle {+ if event.Type != "duplicate_merged" {+ continue+ }+ if event.Metadata != nil && event.Metadata["duplicate_id"] == duplicateID {+ return true+ }+ }+ return false+}++func appendFindingResourceIndexUnique(index map[string][]string, resourceID, findingID string) {+ resourceID = strings.TrimSpace(resourceID)+ findingID = strings.TrimSpace(findingID)+ if resourceID == "" || findingID == "" {+ return+ }+ for _, existingID := range index[resourceID] {+ if existingID == findingID {+ return+ }+ }+ index[resourceID] = append(index[resourceID], findingID)+}++func (s *FindingsStore) mergeEquivalentFindingLocked(existing, incoming *Finding) {+ now := time.Now()+ previousSeverity := existing.Severity+ incomingSeverityRank := findingSeverityRank(incoming.Severity)+ existingSeverityRank := findingSeverityRank(existing.Severity)++ existing.LastSeenAt = now+ existing.TimesRaised+++ if incomingSeverityRank >= existingSeverityRank {+ existing.Severity = incoming.Severity+ if incoming.Title != "" {+ existing.Title = incoming.Title+ }+ if incoming.Description != "" {+ existing.Description = incoming.Description+ }+ if incoming.Impact != "" {+ existing.Impact = incoming.Impact+ }+ if incoming.Recommendation != "" {+ existing.Recommendation = incoming.Recommendation+ }+ if incoming.Evidence != "" {+ existing.Evidence = incoming.Evidence+ }+ }+ if existing.Key == "" && incoming.Key != "" {+ existing.Key = incoming.Key+ }+ if existing.AlertIdentifier == "" && incoming.AlertIdentifier != "" {+ existing.AlertIdentifier = incoming.AlertIdentifier+ }+ if existing.Node == "" && incoming.Node != "" {+ existing.Node = incoming.Node+ }+ s.syncLoopStateLocked(existing)+ if incoming.ResourceID != "" && incoming.ResourceID != existing.ResourceID {+ appendFindingResourceIndexUnique(s.byResource, incoming.ResourceID, existing.ID)+ }+ if !findingHasDuplicateMergeEvent(existing, incoming.ID) {+ s.appendLifecycleLocked(existing, "duplicate_merged", "Merged an equivalent active Patrol finding into this issue", existing.LoopState, existing.LoopState, map[string]string{+ "duplicate_id": incoming.ID,+ "duplicate_key": incoming.Key,+ "duplicate_severity": string(incoming.Severity),+ })+ }+ if previousSeverity != existing.Severity && existing.IsActive() {+ if s.activeCounts[previousSeverity] > 0 {+ s.activeCounts[previousSeverity]--+ }+ s.activeCounts[existing.Severity]+++ }+}+// findOperatorStateDismissCause returns the most recent// `operator_state_cause` metadata value from the finding's lifecycle, or// "" if the finding has not been auto-dismissed by operator-state@@ -1574,6 +1874,17 @@ func (s *FindingsStore) Add(f *Finding) bool {return false}+ if equivalent := s.findEquivalentActiveFindingLocked(f); equivalent != nil {+ s.mergeEquivalentFindingLocked(equivalent, f)+ severity := equivalent.Severity+ s.mu.Unlock()+ s.scheduleSave()+ if severity == FindingSeverityWarning || severity == FindingSeverityCritical {+ _ = s.ForceSave()+ }+ return false+ }+// New findingif f.DetectedAt.IsZero() {f.DetectedAt = time.Now()diff --git a/internal/ai/findings_lifecycle_test.go b/internal/ai/findings_lifecycle_test.goindex 58fca82409..81367ed5d6 100644--- a/internal/ai/findings_lifecycle_test.go+++ b/internal/ai/findings_lifecycle_test.go@@ -399,3 +399,264 @@ func TestFindingsStore_KeyCollisionOnResolvedFindingRecordsBothEvents(t *testingt.Fatalf("expected regressed event to remain, lifecycle=%+v", got.Lifecycle)}}++func TestFindingsStore_MergesEquivalentActiveSiblingWithHigherSeverity(t *testing.T) {+ store := NewFindingsStore()+ first := &Finding{+ ID: "provider-warning",+ Key: "provider-connection",+ ResourceID: "patrol-runtime",+ ResourceName: "Patrol runtime",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryReliability,+ Title: "Provider connection issue",+ Description: "The configured provider could not complete Patrol analysis.",+ }+ second := &Finding{+ ID: "provider-critical",+ Key: "openrouter-provider-unavailable",+ ResourceID: "patrol-runtime",+ ResourceName: "Patrol runtime",+ Severity: FindingSeverityCritical,+ Category: FindingCategoryReliability,+ Title: "Provider connection issue",+ Description: "OpenRouter could not complete the selected Patrol model request.",+ }++ if !store.Add(first) {+ t.Fatal("expected first provider finding to be new")+ }+ if store.Add(second) {+ t.Fatal("expected equivalent provider finding to merge into the active issue")+ }++ active := store.GetActive(FindingSeverityWarning)+ if len(active) != 1 {+ t.Fatalf("expected one active finding after equivalent merge, got %d", len(active))+ }+ got := store.Get("provider-warning")+ if got == nil {+ t.Fatal("expected original finding to remain as merged active issue")+ }+ if store.Get("provider-critical") != nil {+ t.Fatal("expected duplicate finding ID not to be stored as a second active issue")+ }+ if got.Severity != FindingSeverityCritical {+ t.Fatalf("expected merged issue to keep highest severity critical, got %s", got.Severity)+ }+ if got.TimesRaised != 2 {+ t.Fatalf("expected merged issue timesRaised=2, got %d", got.TimesRaised)+ }+ events := findLifecycleEvents(got, "duplicate_merged")+ if len(events) != 1 {+ t.Fatalf("expected one duplicate_merged lifecycle event, got %d (lifecycle=%+v)", len(events), got.Lifecycle)+ }+ if events[0].Metadata["duplicate_id"] != "provider-critical" {+ t.Fatalf("expected duplicate_id metadata, got %+v", events[0].Metadata)+ }+}++func TestFindingsStore_DoesNotMergeDistinctSameResourceCategoryIssues(t *testing.T) {+ store := NewFindingsStore()+ if !store.Add(&Finding{+ ID: "cpu-high",+ Key: "cpu-high",+ ResourceID: "vm-100",+ ResourceName: "vm-100",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryPerformance,+ Title: "High CPU usage",+ Description: "CPU saturation is sustained.",+ }) {+ t.Fatal("expected CPU finding to be new")+ }+ if !store.Add(&Finding{+ ID: "memory-high",+ Key: "memory-high",+ ResourceID: "vm-100",+ ResourceName: "vm-100",+ Severity: FindingSeverityCritical,+ Category: FindingCategoryPerformance,+ Title: "High memory usage",+ Description: "Memory pressure is sustained.",+ }) {+ t.Fatal("expected memory finding to remain a separate active issue")+ }++ active := store.GetActive(FindingSeverityWarning)+ if len(active) != 2 {+ t.Fatalf("expected two distinct active findings, got %d", len(active))+ }+}++func TestFindingsStore_MergesRelatedStorageCapacitySibling(t *testing.T) {+ store := NewFindingsStore()+ if !store.Add(&Finding{+ ID: "tower-array-critical",+ Key: "unraid-array-no-parity-capacity-risk",+ ResourceID: "storage/tower-array",+ ResourceName: "Tower Array",+ ResourceType: "storage",+ Severity: FindingSeverityCritical,+ Category: FindingCategoryReliability,+ Title: "Unraid array running without parity protection while at 86% capacity",+ Description: "The Unraid array is at 85.9% capacity while parity is unavailable.",+ }) {+ t.Fatal("expected first storage finding to be new")+ }+ if store.Add(&Finding{+ ID: "tower-array-warning",+ Key: "storage-pool-usage",+ ResourceID: "storage/tower",+ ResourceName: "Tower",+ ResourceType: "storage",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryCapacity,+ Title: "Storage pool Tower Array at 85.9% usage",+ Description: "Usage at 86% exceeds the configured storage warning threshold.",+ }) {+ t.Fatal("expected related storage capacity sibling to merge into the active issue")+ }++ active := store.GetActive(FindingSeverityWarning)+ if len(active) != 1 {+ t.Fatalf("expected one active storage issue after merge, got %d", len(active))+ }+ got := store.Get("tower-array-critical")+ if got == nil {+ t.Fatal("expected original critical issue to remain")+ }+ if got.Severity != FindingSeverityCritical {+ t.Fatalf("expected merged issue to keep critical severity, got %s", got.Severity)+ }+ if got.Title != "Unraid array running without parity protection while at 86% capacity" {+ t.Fatalf("expected broader critical title to remain, got %q", got.Title)+ }+ if store.Get("tower-array-warning") != nil {+ t.Fatal("expected generic storage usage warning not to be stored as a second active issue")+ }+ if got.TimesRaised != 2 {+ t.Fatalf("expected merged issue timesRaised=2, got %d", got.TimesRaised)+ }+ if events := findLifecycleEvents(got, "duplicate_merged"); len(events) != 1 {+ t.Fatalf("expected duplicate_merged event, got %d lifecycle=%+v", len(events), got.Lifecycle)+ }+}++func TestFindingsStore_MergesRelatedStorageCapacitySiblingEscalation(t *testing.T) {+ store := NewFindingsStore()+ if !store.Add(&Finding{+ ID: "tower-array-warning",+ Key: "storage-pool-usage",+ ResourceID: "storage/tower",+ ResourceName: "Tower",+ ResourceType: "storage",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryCapacity,+ Title: "Storage pool Tower Array at 85.9% usage",+ Description: "Usage at 86% exceeds the configured storage warning threshold.",+ }) {+ t.Fatal("expected first storage finding to be new")+ }+ if store.Add(&Finding{+ ID: "tower-array-critical",+ Key: "unraid-array-no-parity-capacity-risk",+ ResourceID: "storage/tower-array",+ ResourceName: "Tower Array",+ ResourceType: "storage",+ Severity: FindingSeverityCritical,+ Category: FindingCategoryReliability,+ Title: "Unraid array running without parity protection while at 86% capacity",+ Description: "The Unraid array is at 85.9% capacity while parity is unavailable.",+ }) {+ t.Fatal("expected broader storage capacity sibling to merge into the active issue")+ }++ active := store.GetActive(FindingSeverityWarning)+ if len(active) != 1 {+ t.Fatalf("expected one active storage issue after merge, got %d", len(active))+ }+ got := store.Get("tower-array-warning")+ if got == nil {+ t.Fatal("expected original warning issue to remain as merged record")+ }+ if got.Severity != FindingSeverityCritical {+ t.Fatalf("expected merged issue to escalate to critical, got %s", got.Severity)+ }+ if got.Title != "Unraid array running without parity protection while at 86% capacity" {+ t.Fatalf("expected merged issue to adopt higher-severity title, got %q", got.Title)+ }+ if store.Get("tower-array-critical") != nil {+ t.Fatal("expected critical sibling not to be stored as a second active issue")+ }+}++func TestFindingsStore_DoesNotMergeStorageCapacityWithDistinctBackupIssue(t *testing.T) {+ store := NewFindingsStore()+ if !store.Add(&Finding{+ ID: "tower-array-usage",+ Key: "storage-pool-usage",+ ResourceID: "storage/tower-array",+ ResourceName: "Tower Array",+ ResourceType: "storage",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryCapacity,+ Title: "Storage pool Tower Array at 85.9% usage",+ Description: "Usage at 86% exceeds the configured storage warning threshold.",+ }) {+ t.Fatal("expected storage capacity finding to be new")+ }+ if !store.Add(&Finding{+ ID: "tower-array-backup",+ Key: "backup-job-failed",+ ResourceID: "storage/tower-array",+ ResourceName: "Tower Array",+ ResourceType: "storage",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryBackup,+ Title: "Backup job failed for Tower Array",+ Description: "The latest backup job failed and no new restore point was created.",+ }) {+ t.Fatal("expected distinct backup finding to remain separate")+ }++ active := store.GetActive(FindingSeverityWarning)+ if len(active) != 2 {+ t.Fatalf("expected two distinct storage findings, got %d", len(active))+ }+}++func TestFindingsStore_DoesNotMergeStoragePoolWithPhysicalDiskChild(t *testing.T) {+ store := NewFindingsStore()+ if !store.Add(&Finding{+ ID: "pool-usage",+ Key: "storage-pool-usage",+ ResourceID: "storage/local-zfs-data",+ ResourceName: "local-zfs (data)",+ ResourceType: "storage",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryCapacity,+ Title: "Storage pool local-zfs (data) at 86% usage",+ Description: "Usage at 86% exceeds the configured storage warning threshold.",+ }) {+ t.Fatal("expected pool finding to be new")+ }+ if !store.Add(&Finding{+ ID: "disk-usage",+ Key: "physical-disk-usage",+ ResourceID: "storage/local-zfs-data-dev-sda4",+ ResourceName: "local-zfs (data, /dev/sda4)",+ ResourceType: "storage",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryCapacity,+ Title: "Storage disk local-zfs (data, /dev/sda4) at 96% usage",+ Description: "Usage at 96% exceeds the configured storage critical threshold.",+ }) {+ t.Fatal("expected physical disk child finding to remain separate")+ }++ active := store.GetActive(FindingSeverityWarning)+ if len(active) != 2 {+ t.Fatalf("expected pool and disk child to remain separate, got %d", len(active))+ }+}diff --git a/internal/ai/findings_tools_adapter.go b/internal/ai/findings_tools_adapter.goindex 4d84f6b546..6e324c9e42 100644--- a/internal/ai/findings_tools_adapter.go+++ b/internal/ai/findings_tools_adapter.go@@ -4,21 +4,22 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/ai/tools")-// FindingsMCPAdapter adapts FindingsStore to MCP FindingsProvider interface-type FindingsMCPAdapter struct {+// FindingsToolAdapter adapts FindingsStore to the native Assistant findings+// provider interface used by the shared Pulse Intelligence tool registry.+type FindingsToolAdapter struct {store *FindingsStore}-// NewFindingsMCPAdapter creates a new adapter for findings store-func NewFindingsMCPAdapter(store *FindingsStore) *FindingsMCPAdapter {+// NewFindingsToolAdapter creates a new adapter for findings store.+func NewFindingsToolAdapter(store *FindingsStore) *FindingsToolAdapter {if store == nil {return nil}- return &FindingsMCPAdapter{store: store}+ return &FindingsToolAdapter{store: store}}// GetActiveFindings implements tools.FindingsProvider-func (a *FindingsMCPAdapter) GetActiveFindings() []tools.Finding {+func (a *FindingsToolAdapter) GetActiveFindings() []tools.Finding {if a.store == nil {return nil}@@ -49,7 +50,7 @@ func (a *FindingsMCPAdapter) GetActiveFindings() []tools.Finding {}// GetDismissedFindings implements tools.FindingsProvider-func (a *FindingsMCPAdapter) GetDismissedFindings() []tools.Finding {+func (a *FindingsToolAdapter) GetDismissedFindings() []tools.Finding {if a.store == nil {return nil}diff --git a/internal/ai/findings_tools_adapter_test.go b/internal/ai/findings_tools_adapter_test.goindex 29f1ae0e5b..0e553644f9 100644--- a/internal/ai/findings_tools_adapter_test.go+++ b/internal/ai/findings_tools_adapter_test.go@@ -2,8 +2,8 @@ package aiimport "testing"-func TestFindingsMCPAdapter(t *testing.T) {- if NewFindingsMCPAdapter(nil) != nil {+func TestFindingsToolAdapter(t *testing.T) {+ if NewFindingsToolAdapter(nil) != nil {t.Fatal("expected nil adapter for nil store")}@@ -20,7 +20,7 @@ func TestFindingsMCPAdapter(t *testing.T) {store.Add(finding)store.Dismiss("f1", "not_an_issue", "ok")- adapter := NewFindingsMCPAdapter(store)+ adapter := NewFindingsToolAdapter(store)active := adapter.GetActiveFindings()if len(active) != 0 {t.Fatalf("expected no active findings, got %d", len(active))@@ -31,7 +31,7 @@ func TestFindingsMCPAdapter(t *testing.T) {t.Fatalf("unexpected dismissed findings: %+v", dismissed)}- adapter = &FindingsMCPAdapter{}+ adapter = &FindingsToolAdapter{}if adapter.GetActiveFindings() != nil || adapter.GetDismissedFindings() != nil {t.Fatal("expected nil results when store missing")}diff --git a/internal/ai/intelligence.go b/internal/ai/intelligence.goindex 988814e592..a6adf6b003 100644--- a/internal/ai/intelligence.go+++ b/internal/ai/intelligence.go@@ -1118,19 +1118,19 @@ func summarizeRecentPatrolCoverage(case !hasSuccessfulFullRun && hasRecentFullRun && recentErrors > 0:return patrolCoverageFactor{name: "Patrol coverage incomplete",- description: "Patrol coverage is incomplete: a recent full patrol ended with errors, so overall health is not fully verified.",+ description: "Patrol needs a clean check: a recent check ended with errors, so current health may be incomplete.",impact: 35,}, truecase !hasSuccessfulFullRun && recentErrors > 0:return patrolCoverageFactor{name: "Patrol coverage incomplete",- description: fmt.Sprintf("Patrol coverage is incomplete: recent activity was limited to %s and ended with errors, so overall health is not fully verified.", limitedActivityLabel),+ description: fmt.Sprintf("Recent Patrol activity only covered %s and ended with errors. Run Patrol to check everything.", limitedActivityLabel),impact: 35,}, truecase !hasSuccessfulFullRun && limitedActivityRuns == len(relevant):return patrolCoverageFactor{name: "Patrol coverage incomplete",- description: fmt.Sprintf("Patrol coverage is incomplete: recent activity was limited to %s, so overall infrastructure health is not fully verified.", limitedActivityLabel),+ description: fmt.Sprintf("Recent Patrol activity only covered %s. Run Patrol to check everything.", limitedActivityLabel),impact: 20,}, truecase recentErrors > 0:@@ -1220,13 +1220,13 @@ func describeLimitedPatrolActivity(runs []PatrolRunRecord) string {switch {case hasScoped && !hasVerification && !hasOther:- return "scoped runs"+ return "targeted checks"case hasVerification && !hasScoped && !hasOther:- return "verification checks"+ return "follow-up checks"case hasScoped && hasVerification && !hasOther:- return "scoped runs and verification checks"+ return "targeted and follow-up checks"default:- return "targeted Patrol activity"+ return "targeted checks"}}diff --git a/internal/ai/intelligence_coverage_test.go b/internal/ai/intelligence_coverage_test.goindex 53fb409514..3abfbe2d7c 100644--- a/internal/ai/intelligence_coverage_test.go+++ b/internal/ai/intelligence_coverage_test.go@@ -277,7 +277,7 @@ func TestIntelligence_GetSummary_DegradesWhenRecentPatrolCoverageIsScopedAndErroif summary.OverallHealth.Grade == HealthGradeA {t.Fatalf("expected non-A grade, got %s", summary.OverallHealth.Grade)}- if !strings.Contains(summary.OverallHealth.Prediction, "not fully verified") {+ if !strings.Contains(summary.OverallHealth.Prediction, "Run Patrol to check everything") {t.Fatalf("expected coverage warning prediction, got %q", summary.OverallHealth.Prediction)}foundCoverageFactor := false@@ -314,7 +314,7 @@ func TestIntelligence_GetSummary_DegradesWhenRecentPatrolCoverageIsVerificationOif summary.OverallHealth.Grade == HealthGradeA {t.Fatalf("expected non-A grade, got %s", summary.OverallHealth.Grade)}- want := "Patrol coverage is incomplete: recent activity was limited to verification checks, so overall infrastructure health is not fully verified."+ want := "Recent Patrol activity only covered follow-up checks. Run Patrol to check everything."if summary.OverallHealth.Prediction != want {t.Fatalf("expected verification-only coverage warning, got %q", summary.OverallHealth.Prediction)}@@ -351,7 +351,7 @@ func TestIntelligence_GetSummary_DegradesWhenRecentFullPatrolErrored(t *testing.if summary.OverallHealth.Grade == HealthGradeA {t.Fatalf("expected non-A grade, got %s", summary.OverallHealth.Grade)}- want := "Patrol coverage is incomplete: a recent full patrol ended with errors, so overall health is not fully verified."+ want := "Patrol needs a clean check: a recent check ended with errors, so current health may be incomplete."if summary.OverallHealth.Prediction != want {t.Fatalf("expected full-patrol coverage warning, got %q", summary.OverallHealth.Prediction)}diff --git a/internal/ai/investigation_records.go b/internal/ai/investigation_records.goindex 80eacdfe0b..27e852b9c1 100644--- a/internal/ai/investigation_records.go+++ b/internal/ai/investigation_records.go@@ -175,6 +175,8 @@ func investigationRecordVerificationNotes(outcome aicontracts.InvestigationOutcoreturn []string{"Patrol could not conclusively verify remediation."}case aicontracts.OutcomeFixFailed:return []string{"Patrol attempted remediation, but the fix did not complete successfully."}+ case aicontracts.OutcomeFixRejected:+ return []string{"The operator rejected the proposed fix before execution."}default:return []string{}}@@ -200,7 +202,7 @@ func deriveInvestigationRecordConfidence(record *aicontracts.InvestigationRecordreturn aicontracts.InvestigationRecordConfidenceHighcase aicontracts.OutcomeFixQueued, aicontracts.OutcomeFixExecuted, aicontracts.OutcomeCannotFix, aicontracts.OutcomeNeedsAttention:return aicontracts.InvestigationRecordConfidenceMedium- case aicontracts.OutcomeFixFailed, aicontracts.OutcomeFixVerificationFailed, aicontracts.OutcomeFixVerificationUnknown, aicontracts.OutcomeTimedOut:+ case aicontracts.OutcomeFixRejected, aicontracts.OutcomeFixFailed, aicontracts.OutcomeFixVerificationFailed, aicontracts.OutcomeFixVerificationUnknown, aicontracts.OutcomeTimedOut:return aicontracts.InvestigationRecordConfidenceLow}if strings.TrimSpace(record.Conclusion) != "" || len(record.Evidence) > 0 {diff --git a/internal/ai/patrol_ai.go b/internal/ai/patrol_ai.goindex ee4c8f56b7..ab89dc5f1c 100644--- a/internal/ai/patrol_ai.go+++ b/internal/ai/patrol_ai.go@@ -21,7 +21,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/ai/cost""github.com/rcourtman/pulse-go-rewrite/internal/ai/memory""github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"- "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"+ "github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources""github.com/rs/zerolog/log"@@ -213,7 +213,7 @@ func CleanThinkingTokens(content string) string {}// runAIAnalysis uses the agentic tool-driven approach to analyze infrastructure.-// The LLM investigates using MCP tools and reports findings via patrol_report_finding.+// The LLM investigates using Assistant tools and reports findings via patrol_report_finding.// An optional scope focuses the patrol on specific resources.func (p *PatrolService) runAIAnalysisState(ctx context.Context, snap patrolRuntimeState, scope *PatrolScope, executionID string) (*AIAnalysisResult, error) {if p.aiService == nil {@@ -688,23 +688,6 @@ func computeTriageMaxTurns(flagCount int, scope *PatrolScope) int {return turns}-func formatToolResult(result tools.CallToolResult) string {- if len(result.Content) == 0 {- return ""- }-- var text string- for _, c := range result.Content {- if c.Type == "text" && c.Text != "" {- if text != "" {- text += "\n"- }- text += c.Text- }- }- return text-}-// runEvaluationPass runs a focused second LLM call to evaluate unmatched signals// that the main patrol pass detected but did not report as findings.func (p *PatrolService) runEvaluationPass(ctx context.Context, adapter *patrolFindingCreatorAdapter, unmatchedSignals []DetectedSignal, executionID string) (*PatrolStreamResponse, error) {@@ -832,13 +815,53 @@ func buildEvalUserPrompt(signals []DetectedSignal) string {return sb.String()}+func patrolAutonomyPrompt(level string) string {+ switch level {+ case config.PatrolAutonomyApproval:+ return `++## Patrol Control Mode: Ask First++Patrol may investigate findings with read-only tools and propose a governed fix. Do not execute remediation commands in this mode. When a fix is appropriate, queue it for operator approval and record the evidence, risk, rollback posture, and verification steps so the operator can approve or reject it.++If a tool or command requires approval, stop at the approval request. Do not treat the request as a failed fix.`+ case config.PatrolAutonomyAssisted:+ return `++## Patrol Control Mode: Safe Auto-Fix++Patrol may investigate findings and execute only low-risk, policy-approved fixes automatically. Queue approval for destructive, high-risk, critical, ambiguous, restricted, or never-auto-remediate actions. After any automatic fix, run verification and record the outcome.++If policy requires approval, stop at the approval request. Do not work around approval by choosing a different command with the same effect.`+ case config.PatrolAutonomyFull:+ return `++## Patrol Control Mode: Autopilot++Patrol may investigate findings and execute policy-approved fixes automatically, including critical fixes, after checking risk and target confidence. Approval boundaries still win: destructive commands, restricted policy, ambiguous targets, full-mode lock, and never-auto-remediate resources must be queued or blocked rather than executed.++After any automatic fix, run verification and record whether the issue was fixed, still failing, or inconclusive.`+ default:+ return `++## Patrol Control Mode: Watch Only++Patrol may inspect infrastructure with read-only evidence and record findings. Do not investigate through remediation flows, queue approvals, or execute any infrastructure-changing action. Report clear recommendations for the operator to handle manually.`+ }+}+// getPatrolSystemPrompt returns the system prompt for AI patrol analysis.// The new agentic prompt instructs the LLM to use investigation tools and// report findings via the patrol_report_finding tool instead of text blocks.func (p *PatrolService) getPatrolSystemPrompt() string {- autoFix := false- if cfg := p.aiService.GetAIConfig(); cfg != nil {- autoFix = cfg.PatrolAutoFix+ autonomyLevel := config.PatrolAutonomyMonitor+ if p != nil && p.aiService != nil {+ autonomyLevel = p.aiService.GetEffectivePatrolAutonomyLevel()+ if cfg := p.aiService.GetConfig(); cfg != nil &&+ autonomyLevel == config.PatrolAutonomyFull &&+ !cfg.PatrolFullModeUnlocked {+ autonomyLevel = config.PatrolAutonomyAssisted+ }}basePrompt := `You are Pulse Patrol, an autonomous infrastructure analysis agent. Your job is to find issues that simple threshold-based alerts CANNOT catch — trends, capacity risks, misconfigurations, reliability gaps, and cross-resource correlations.@@ -948,30 +971,7 @@ One sentence overall health verdict (e.g., "All 3 nodes and 18 guests are operatKeep the summary factual, terse, and scannable. Do NOT repeat your investigation process or thinking. Do NOT use phrases like "Let me check..." or "I'll start by..." — only state results. Maximum 15 lines.`- if autoFix {- return basePrompt + `--## Auto-Fix Mode--Auto-fix is enabled. Governed read and control tools are available for remediation when the model determines they are needed.--Safe operations you can perform autonomously:-- Restart services (systemctl restart)-- Clear caches and temp files-- Rotate/compress logs-- Trigger garbage collection--Always:-1. Run a verification command after any fix to confirm success-2. Report findings for issues you attempted to fix (include fix outcome in evidence)-3. Stop and report if the fix doesn't resolve the issue`- }-- return basePrompt + `--## Observe Only Mode--You are in observation mode. Read-only diagnostic evidence is available, but do not modify anything. Report findings with clear recommendations for the user to review and action manually.`+ return basePrompt + patrolAutonomyPrompt(autonomyLevel)}const triageSystemPreamble = `You are Pulse Patrol, a model-owned infrastructure analysis agent.diff --git a/internal/ai/patrol_ai_eval_additional_test.go b/internal/ai/patrol_ai_eval_additional_test.goindex 509ee772ee..ee36798a9a 100644--- a/internal/ai/patrol_ai_eval_additional_test.go+++ b/internal/ai/patrol_ai_eval_additional_test.go@@ -6,27 +6,9 @@ import ("strings""testing"- "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools""github.com/rcourtman/pulse-go-rewrite/internal/config")-func TestFormatToolResult(t *testing.T) {- result := tools.CallToolResult{- Content: []tools.Content{- {Type: "text", Text: "first"},- {Type: "resource", URI: "file://ignored"},- {Type: "text", Text: "second"},- },- }- if got := formatToolResult(result); got != "first\nsecond" {- t.Fatalf("formatToolResult returned %q", got)- }-- if got := formatToolResult(tools.CallToolResult{}); got != "" {- t.Fatalf("expected empty result for no content, got %q", got)- }-}-func TestEvalPromptBuilders(t *testing.T) {systemPrompt := buildEvalSystemPrompt()if !strings.Contains(systemPrompt, "patrol_report_finding") || !strings.Contains(systemPrompt, "patrol_get_findings") {diff --git a/internal/ai/patrol_ai_more_test.go b/internal/ai/patrol_ai_more_test.goindex 3413bc0063..44d6beb3a5 100644--- a/internal/ai/patrol_ai_more_test.go+++ b/internal/ai/patrol_ai_more_test.go@@ -170,20 +170,101 @@ func TestComputePatrolMaxTurns(t *testing.T) {}func TestGetPatrolSystemPrompt_ModeSwitch(t *testing.T) {- svc := &Service{cfg: &config.AIConfig{PatrolAutoFix: true}}- ps := NewPatrolService(svc, nil)- prompt := ps.getPatrolSystemPrompt()- if !strings.Contains(prompt, "Auto-Fix Mode") || !strings.Contains(prompt, "Governed read and control tools are available") {- t.Fatalf("expected auto-fix prompt, got: %s", prompt)- }- if !strings.Contains(prompt, "pulse_discovery") || !strings.Contains(prompt, "Read or refresh discovered service details") {- t.Fatalf("expected patrol prompt to expose discovery refresh capability, got: %s", prompt)+ tests := []struct {+ name string+ cfg *config.AIConfig+ contains []string+ notContain []string+ }{+ {+ name: "monitor",+ cfg: &config.AIConfig{PatrolAutonomyLevel: config.PatrolAutonomyMonitor},+ contains: []string{+ "Patrol Control Mode: Watch Only",+ "Do not investigate through remediation flows, queue approvals, or execute any infrastructure-changing action.",+ },+ },+ {+ name: "approval",+ cfg: &config.AIConfig{PatrolAutonomyLevel: config.PatrolAutonomyApproval},+ contains: []string{+ "Patrol Control Mode: Ask First",+ "Do not execute remediation commands in this mode.",+ "queue it for operator approval",+ },+ },+ {+ name: "assisted",+ cfg: &config.AIConfig{PatrolAutonomyLevel: config.PatrolAutonomyAssisted},+ contains: []string{+ "Patrol Control Mode: Safe Auto-Fix",+ "execute only low-risk, policy-approved fixes automatically",+ "Queue approval for destructive, high-risk, critical, ambiguous, restricted, or never-auto-remediate actions.",+ },+ },+ {+ name: "full",+ cfg: &config.AIConfig{+ PatrolAutonomyLevel: config.PatrolAutonomyFull,+ PatrolFullModeUnlocked: true,+ },+ contains: []string{+ "Patrol Control Mode: Autopilot",+ "execute policy-approved fixes automatically, including critical fixes",+ "Approval boundaries still win",+ },+ },+ {+ name: "locked full downgrades to assisted",+ cfg: &config.AIConfig{+ PatrolAutonomyLevel: config.PatrolAutonomyFull,+ PatrolFullModeUnlocked: false,+ },+ contains: []string{+ "Patrol Control Mode: Safe Auto-Fix",+ },+ notContain: []string{+ "Patrol Control Mode: Autopilot",+ },+ },+ {+ name: "legacy autofix flag does not overstate autonomy",+ cfg: &config.AIConfig{+ PatrolAutoFix: true,+ },+ contains: []string{+ "Patrol Control Mode: Watch Only",+ },+ notContain: []string{+ "Patrol Control Mode: Autopilot",+ "Auto-Fix Mode",+ },+ },}- svc.cfg = &config.AIConfig{PatrolAutoFix: false}- prompt = ps.getPatrolSystemPrompt()- if !strings.Contains(prompt, "Observe Only Mode") {- t.Fatalf("expected observe-only prompt, got: %s", prompt)+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ svc := &Service{cfg: tt.cfg}+ ps := NewPatrolService(svc, nil)+ prompt := ps.getPatrolSystemPrompt()++ if !strings.Contains(prompt, "pulse_discovery") || !strings.Contains(prompt, "Read or refresh discovered service details") {+ t.Fatalf("expected patrol prompt to expose discovery refresh capability, got: %s", prompt)+ }+ for _, want := range tt.contains {+ if !strings.Contains(prompt, want) {+ t.Fatalf("prompt missing %q:\n%s", want, prompt)+ }+ }+ for _, forbidden := range tt.notContain {+ if strings.Contains(prompt, forbidden) {+ t.Fatalf("prompt contained forbidden %q:\n%s", forbidden, prompt)+ }+ }+ if strings.Contains(prompt, "Observe Only Mode") {+ t.Fatalf("prompt should use Patrol control-mode vocabulary, got legacy observe-only wording:\n%s", prompt)+ }+ })}}diff --git a/internal/ai/patrol_assistant_handoff.go b/internal/ai/patrol_assistant_handoff.goindex fee054e0ca..ae39549ef8 100644--- a/internal/ai/patrol_assistant_handoff.go+++ b/internal/ai/patrol_assistant_handoff.go@@ -141,11 +141,11 @@ func patrolRunRuntimeFailureSummary(run PatrolRunRecord) string {func patrolRunKindLabel(runType string) string {switch strings.ToLower(strings.TrimSpace(runType)) {case "scoped":- return "Scoped run"+ return "Targeted check"case "verification":- return "Verification check"+ return "Follow-up check"case "", "patrol", "full", "scheduled":- return "Full patrol"+ return "Patrol check"default:return "Patrol run"}diff --git a/internal/ai/patrol_assistant_handoff_test.go b/internal/ai/patrol_assistant_handoff_test.goindex c181c2bfc0..cd1f3d48b6 100644--- a/internal/ai/patrol_assistant_handoff_test.go+++ b/internal/ai/patrol_assistant_handoff_test.go@@ -35,7 +35,7 @@ func TestBuildPatrolRunAssistantHandoffUsesBackendSafeRunContext(t *testing.T) {if handoff.Metadata != (chat.HandoffMetadata{Kind: "patrol_run",RunID: "run-runtime-error",- RunType: "Scoped run",+ RunType: "Targeted check",RunStatus: "error",RuntimeFailure: true,}) {@@ -49,7 +49,7 @@ func TestBuildPatrolRunAssistantHandoffUsesBackendSafeRunContext(t *testing.T) {"[Patrol Run Context]","Source: Pulse Patrol run history","Run ID: run-runtime-error",- "Run Type: Scoped run",+ "Run Type: Targeted check","Trigger: Alert fired","Runtime Failure: Selected model does not support Patrol tools","no tool-capable endpoint",diff --git a/internal/ai/patrol_findings.go b/internal/ai/patrol_findings.goindex dc5f6ca5e7..95d9eeaf4e 100644--- a/internal/ai/patrol_findings.go+++ b/internal/ai/patrol_findings.go@@ -12,6 +12,7 @@ import ("sync""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/ai/baseline""github.com/rcourtman/pulse-go-rewrite/internal/ai/safety""github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"@@ -1493,20 +1494,28 @@ func executeToolCall(ctx context.Context, executor *tools.PulseToolExecutor, tooresult, execErr := executor.ExecuteTool(ctx, toolName, args)output := ""success := false+ var interpreted agentcapabilities.ToolResultInterpretationif execErr != nil {output = execErr.Error()} else {- output = formatToolResult(result)- success = !result.IsError+ interpreted = agentcapabilities.InterpretToolResult(result)+ output = interpreted.Text+ success = !interpreted.IsError && !interpreted.ApprovalRequired && !interpreted.PolicyBlocked}end := time.Now().UnixMilli()if execErr != nil {return ToolCallRecord{}, fmt.Errorf("%w: tool execution failed (%s): %v", aicontracts.ErrVerificationUnknown, toolName, execErr)}- if result.IsError {+ if interpreted.IsError {return ToolCallRecord{}, fmt.Errorf("%w: tool returned error (%s): %s", aicontracts.ErrVerificationUnknown, toolName, output)}+ if interpreted.ApprovalRequired {+ return ToolCallRecord{}, fmt.Errorf("%w: tool requires approval (%s): %s", aicontracts.ErrVerificationUnknown, toolName, output)+ }+ if interpreted.PolicyBlocked {+ return ToolCallRecord{}, fmt.Errorf("%w: tool blocked by security policy (%s): %s", aicontracts.ErrVerificationUnknown, toolName, output)+ }// Most verification probes rely on parsing structured JSON outputs. If we receive// non-JSON text, treat verification as inconclusive rather than "resolved".if toolName == "pulse_storage" || toolName == "pulse_metrics" || toolName == "pulse_alerts" {diff --git a/internal/ai/patrol_findings_additional_test.go b/internal/ai/patrol_findings_additional_test.goindex e2ccf82157..6497873363 100644--- a/internal/ai/patrol_findings_additional_test.go+++ b/internal/ai/patrol_findings_additional_test.go@@ -8,6 +8,7 @@ import ("testing""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/ai/tools""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/models"@@ -372,6 +373,51 @@ func TestVerifyFixResolved_WithoutRuntimeStateFailsClosed(t *testing.T) {}}+func TestExecuteToolCallTreatsSharedApprovalAndPolicyMarkersAsInconclusive(t *testing.T) {+ tests := []struct {+ name string+ resultText string+ wantMessage string+ }{+ {+ name: "approval required",+ resultText: agentcapabilities.ApprovalRequiredToolMarker("rm -rf /", "call-1", "needs approval", "approval-1", "approve in Pulse"),+ wantMessage: "tool requires approval",+ },+ {+ name: "policy blocked",+ resultText: agentcapabilities.PolicyBlockedToolMarker("rm -rf /", "blocked"),+ wantMessage: "tool blocked by security policy",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})+ executor.RegisterTool(tools.RegisteredTool{+ Definition: tools.Tool{+ Name: "patrol_marker_probe",+ Description: "test-only marker probe",+ },+ Handler: func(context.Context, *tools.PulseToolExecutor, map[string]interface{}) (tools.CallToolResult, error) {+ return tools.NewTextResult(tt.resultText), nil+ },+ })++ record, err := executeToolCall(context.Background(), executor, "patrol_marker_probe", nil)+ if err == nil {+ t.Fatalf("expected shared marker to fail closed, got record %+v", record)+ }+ if !errors.Is(err, aicontracts.ErrVerificationUnknown) {+ t.Fatalf("expected verification unknown, got %v", err)+ }+ if !strings.Contains(err.Error(), tt.wantMessage) {+ t.Fatalf("expected %q in error, got %v", tt.wantMessage, err)+ }+ })+ }+}+// --- Configurable threshold tests ---func TestActionabilityThreshold_DefaultFallback(t *testing.T) {diff --git a/internal/ai/patrol_preflight.go b/internal/ai/patrol_preflight.goindex 4b91b9eade..c1c73a592c 100644--- a/internal/ai/patrol_preflight.go+++ b/internal/ai/patrol_preflight.go@@ -118,8 +118,8 @@ func (s *Service) RunPatrolToolPreflight(ctx context.Context, providerName, modeif cfg == nil {result.Cause = PatrolFailureCauseSettingsPersistence- result.Title = "Pulse Patrol: Assistant settings unavailable"- result.Summary = "Pulse Assistant settings could not be loaded"+ result.Title = "Pulse Patrol: Assistant & Patrol settings unavailable"+ result.Summary = "Assistant & Patrol settings could not be loaded"result.Recommendation = "Confirm Pulse settings persistence is healthy, then re-run preflight."result.DurationMs = time.Since(started).Milliseconds()s.recordPatrolPreflight(result, time.Now())@@ -216,6 +216,7 @@ func (s *Service) RunPatrolToolPreflight(ctx context.Context, providerName, moderesult.Title = "Pulse Patrol: Preflight succeeded"result.Summary = "Provider accepted the preflight request and the model emitted a tool call."s.recordPatrolPreflight(result, time.Now())+ s.resolvePatrolRuntimeFailureAfterToolPreflight(result)return result}@@ -231,6 +232,17 @@ func (s *Service) RunPatrolToolPreflight(ctx context.Context, providerName, modereturn result}+func (s *Service) resolvePatrolRuntimeFailureAfterToolPreflight(result PatrolPreflightResult) bool {+ if s == nil || !result.Success || !result.ToolCallObserved {+ return false+ }+ patrol := s.GetPatrolService()+ if patrol == nil {+ return false+ }+ return patrol.resolvePatrolRuntimeFailureFinding("patrol_preflight_success")+}+func applyPatrolPreflightDiagnostic(result *PatrolPreflightResult, err error) {failure := patrolRuntimeFailureFromError(err)result.Cause = failure.Causediff --git a/internal/ai/patrol_preflight_test.go b/internal/ai/patrol_preflight_test.goindex ce9268e3b7..381e709454 100644--- a/internal/ai/patrol_preflight_test.go+++ b/internal/ai/patrol_preflight_test.go@@ -3,6 +3,7 @@ package aiimport ("context""encoding/json"+ "errors""net/http""net/http/httptest""strings"@@ -98,6 +99,47 @@ func TestRunPatrolToolPreflight_Success_ToolCallObserved(t *testing.T) {}}+func TestRunPatrolToolPreflight_SuccessResolvesPreviousRuntimeFailure(t *testing.T) {+ h := newPatrolPreflightTestService(t, "openai:gpt-4o-mini", func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{+ "id": "chatcmpl-preflight-ok",+ "model": "gpt-4o-mini",+ "choices": [{+ "finish_reason": "tool_calls",+ "message": {+ "role": "assistant",+ "content": "",+ "tool_calls": [{+ "id": "call_1",+ "type": "function",+ "function": {"name": "verify_pulse_patrol", "arguments": "{\"ok\":true}"}+ }]+ }+ }]+ }`))+ })+ defer h.close()++ patrol := NewPatrolService(h.svc, nil)+ h.svc.patrolService = patrol+ runtimeFinding := newPatrolRuntimeFailureFinding(patrolRuntimeFailureFromError(errors.New("provider connection failed")), time.Now().Add(-time.Hour))+ patrol.recordFinding(runtimeFinding)++ result := h.svc.RunPatrolToolPreflight(context.Background(), "", "")+ if !result.Success || !result.ToolCallObserved {+ t.Fatalf("expected green preflight, got %+v", result)+ }++ finding := patrol.findings.Get(runtimeFinding.ID)+ if finding == nil {+ t.Fatal("expected runtime finding to remain available as resolved history")+ }+ if !finding.IsResolved() {+ t.Fatalf("expected successful preflight to auto-resolve runtime finding, got resolved_at=%v", finding.ResolvedAt)+ }+}+func TestRunPatrolToolPreflight_Success_NoToolCall(t *testing.T) {// Provider accepts the request but the model returned plain text// instead of calling the verify tool. Pulse soft-warns rather than@@ -130,6 +172,39 @@ func TestRunPatrolToolPreflight_Success_NoToolCall(t *testing.T) {}}+func TestRunPatrolToolPreflight_NoToolCallKeepsPreviousRuntimeFailureActive(t *testing.T) {+ h := newPatrolPreflightTestService(t, "openai:gpt-4o-mini", func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{+ "id": "chatcmpl-preflight-no-tool",+ "model": "gpt-4o-mini",+ "choices": [{+ "finish_reason": "stop",+ "message": {"role": "assistant", "content": "ok"}+ }]+ }`))+ })+ defer h.close()++ patrol := NewPatrolService(h.svc, nil)+ h.svc.patrolService = patrol+ runtimeFinding := newPatrolRuntimeFailureFinding(patrolRuntimeFailureFromError(errors.New("provider connection failed")), time.Now().Add(-time.Hour))+ patrol.recordFinding(runtimeFinding)++ result := h.svc.RunPatrolToolPreflight(context.Background(), "", "")+ if !result.Success || result.ToolCallObserved {+ t.Fatalf("expected soft-warning preflight, got %+v", result)+ }++ finding := patrol.findings.Get(runtimeFinding.ID)+ if finding == nil {+ t.Fatal("expected runtime finding to remain available")+ }+ if finding.IsResolved() {+ t.Fatalf("expected no-tool-call preflight to leave runtime finding active, got resolved_at=%v", finding.ResolvedAt)+ }+}+func TestRunPatrolToolPreflight_ToolChoiceRejected(t *testing.T) {// Provider returns the DeepSeek-style 400 that motivated the// classifier split. Preflight must surface the more accurate@@ -191,6 +266,25 @@ func TestRunPatrolToolPreflight_AssistantDisabled(t *testing.T) {}}+func TestRunPatrolToolPreflight_SettingsUnavailableUsesAssistantPatrolCopy(t *testing.T) {+ svc := NewService(config.NewConfigPersistence(t.TempDir()), nil)+ svc.cfg = nil++ result := svc.RunPatrolToolPreflight(context.Background(), "", "")+ if result.Success {+ t.Fatalf("expected failure when settings are unavailable, got %+v", result)+ }+ if result.Cause != PatrolFailureCauseSettingsPersistence {+ t.Fatalf("unexpected cause %q", result.Cause)+ }+ if result.Title != "Pulse Patrol: Assistant & Patrol settings unavailable" {+ t.Fatalf("unexpected title %q", result.Title)+ }+ if result.Summary != "Assistant & Patrol settings could not be loaded" {+ t.Fatalf("unexpected summary %q", result.Summary)+ }+}+func TestRunPatrolToolPreflight_NoModelSelected(t *testing.T) {svc := NewService(config.NewConfigPersistence(t.TempDir()), nil)svc.cfg = &config.AIConfig{Enabled: true, OpenAIAPIKey: "sk-test"}diff --git a/internal/ai/patrol_readiness.go b/internal/ai/patrol_readiness.goindex b8bc078dc8..93e11731cd 100644--- a/internal/ai/patrol_readiness.go+++ b/internal/ai/patrol_readiness.go@@ -48,7 +48,7 @@ type PatrolConfigReadiness struct {func EvaluatePatrolConfigReadiness(cfg *config.AIConfig) PatrolConfigReadiness {if cfg == nil {- return patrolConfigReadiness("", "", PatrolReadinessNotReady, PatrolFailureCauseSettingsPersistence, "Pulse Assistant settings could not be loaded from persistence.")+ return patrolConfigReadiness("", "", PatrolReadinessNotReady, PatrolFailureCauseSettingsPersistence, "Assistant & Patrol settings could not be loaded from persistence.")}if !cfg.Enabled {return patrolConfigReadiness("", "", PatrolReadinessNotReady, PatrolFailureCauseAssistantDisabled, "Pulse Assistant is disabled, so Patrol cannot run model-backed verification.")@@ -140,7 +140,7 @@ func patrolConfigReadiness(provider, model, status string, cause PatrolFailureCafunc (s *Service) PatrolRuntimeReadiness() PatrolConfigReadiness {if s == nil {- return patrolConfigReadiness("", "", PatrolReadinessNotReady, PatrolFailureCauseServiceUnavailable, "Pulse AI runtime service is not available.")+ return patrolConfigReadiness("", "", PatrolReadinessNotReady, PatrolFailureCauseServiceUnavailable, "Pulse Assistant runtime service is not available.")}s.mu.RLock()cfg := s.cfgdiff --git a/internal/ai/patrol_readiness_test.go b/internal/ai/patrol_readiness_test.goindex 72c79c9d68..a9b1ced2be 100644--- a/internal/ai/patrol_readiness_test.go+++ b/internal/ai/patrol_readiness_test.go@@ -138,3 +138,14 @@ func TestEvaluatePatrolConfigReadiness_AssignsStableCause(t *testing.T) {})}}++func TestEvaluatePatrolConfigReadiness_NilConfigUsesAssistantPatrolSettingsCopy(t *testing.T) {+ readiness := EvaluatePatrolConfigReadiness(nil)++ if readiness.Cause != PatrolFailureCauseSettingsPersistence {+ t.Fatalf("cause = %q, want %q", readiness.Cause, PatrolFailureCauseSettingsPersistence)+ }+ if readiness.Summary != "Assistant & Patrol settings could not be loaded from persistence." {+ t.Fatalf("summary = %q", readiness.Summary)+ }+}diff --git a/internal/ai/providers/anthropic.go b/internal/ai/providers/anthropic.goindex 76d439f7b5..28325691a1 100644--- a/internal/ai/providers/anthropic.go+++ b/internal/ai/providers/anthropic.go@@ -11,6 +11,7 @@ import ("strings""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rs/zerolog/log")@@ -550,58 +551,9 @@ type anthropicDelta struct {// ChatStream sends a chat request and streams the response via callbackfunc (c *AnthropicClient) ChatStream(ctx context.Context, req ChatRequest, callback StreamCallback) error {// Convert messages to Anthropic format (same as Chat)- messages := make([]anthropicMessage, 0, len(req.Messages))- for _, m := range req.Messages {- if m.Role == "system" {- continue- }-- if m.ToolResult != nil {- contentJSON, err := json.Marshal(m.ToolResult.Content)- if err != nil {- return fmt.Errorf("failed to marshal tool result content for %s: %w", m.ToolResult.ToolUseID, err)- }- messages = append(messages, anthropicMessage{- Role: "user",- Content: []anthropicContent{- {- Type: "tool_result",- ToolUseID: m.ToolResult.ToolUseID,- Content: contentJSON,- IsError: m.ToolResult.IsError,- },- },- })- continue- }-- if m.Role == "assistant" && len(m.ToolCalls) > 0 {- contentBlocks := make([]anthropicContent, 0)- if m.Content != "" {- contentBlocks = append(contentBlocks, anthropicContent{- Type: "text",- Text: m.Content,- })- }- for _, tc := range m.ToolCalls {- contentBlocks = append(contentBlocks, anthropicContent{- Type: "tool_use",- ID: tc.ID,- Name: tc.Name,- Input: tc.Input,- })- }- messages = append(messages, anthropicMessage{- Role: "assistant",- Content: contentBlocks,- })- continue- }-- messages = append(messages, anthropicMessage{- Role: m.Role,- Content: m.Content,- })+ messages, err := convertMessagesToAnthropic(req.Messages)+ if err != nil {+ return err}model := req.Model@@ -771,7 +723,7 @@ func (c *AnthropicClient) ChatStream(ctx context.Context, req ChatRequest, callbcurrentToolInput.WriteString(event.Delta.PartialJSON)if currentToolName != "" {rawInput := currentToolInput.String()- parsedInput := parseStreamToolInput(rawInput)+ parsedInput, _ := agentcapabilities.ParseProviderToolInput(rawInput)message := "Receiving tool input."if parsedInput != nil {message = "Prepared tool input."@@ -794,10 +746,7 @@ func (c *AnthropicClient) ChatStream(ctx context.Context, req ChatRequest, callbcase "content_block_stop":if currentToolID != "" {// Parse the accumulated tool input- var input map[string]interface{}- if err := json.Unmarshal([]byte(currentToolInput.String()), &input); err != nil {- input = map[string]interface{}{"raw": currentToolInput.String()}- }+ input := agentcapabilities.ProviderToolInputOrRaw(currentToolInput.String())toolCalls = append(toolCalls, ToolCall{ID: currentToolID,Name: currentToolName,diff --git a/internal/ai/providers/anthropic_oauth.go b/internal/ai/providers/anthropic_oauth.godeleted file mode 100644index 395687a3ae..0000000000--- a/internal/ai/providers/anthropic_oauth.go+++ /dev/null@@ -1,661 +0,0 @@-package providers--// anthropic_oauth.go - OAuth client for Claude Pro/Max subscription authentication-//-// STATUS: DISABLED IN UI - Anthropic restricts OAuth to Claude Code only-//-// This implementation follows Claude Code's OAuth flow exactly:-// 1. Get authorization code from claude.ai/oauth/authorize-// 2. Exchange code for tokens at console.anthropic.com/v1/oauth/token-// 3. Try to create API key (works for Team/Enterprise users)-// 4. Use OAuth tokens directly (for Pro/Max users)-//-// However, Anthropic has locked down their OAuth system:-// - OAuth tokens are server-side validated to only work within Claude Code-// - The error "This credential is only authorized for use with Claude Code" is returned-// - Pro/Max users don't have org:create_api_key permission to create API keys-//-// This code is kept intact in case Anthropic opens up OAuth for third-party apps in the future.-// To re-enable, update the frontend AISettings.tsx to un-disable the OAuth button.--import (- "bytes"- "context"- "crypto/rand"- "crypto/sha256"- "encoding/base64"- "encoding/json"- "fmt"- "io"- "net/http"- "net/url"- "time"-- "github.com/rs/zerolog/log"-)--const (- // OAuth endpoints - these are the same endpoints Claude Code uses- // Authorization happens at claude.ai, token exchange at console.anthropic.com- anthropicAuthorizeURL = "https://claude.ai/oauth/authorize"- anthropicTokenURL = "https://console.anthropic.com/v1/oauth/token"- // API key creation endpoint - OAuth tokens create an API key for actual use- anthropicAPIKeyURL = "https://api.anthropic.com/api/oauth/claude_cli/create_api_key"- // Claude Code's client ID - this is what enables subscription-based auth- claudeCodeClientID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e"- // Scopes needed for inference with subscription (matching Claude Code's Oo0 array)- // org:create_api_key, user:profile, user:inference, user:sessions:claude_code- oauthScopes = "org:create_api_key user:profile user:inference user:sessions:claude_code"-)--var (- oauthAuthorizeURL = anthropicAuthorizeURL- oauthTokenURL = anthropicTokenURL- oauthAPIKeyURL = anthropicAPIKeyURL-- // oauthHTTPClient is used for token exchange, refresh, and API key creation.- // It is a package variable to enable deterministic, local unit tests.- oauthHTTPClient = &http.Client{Timeout: 30 * time.Second}-)--// OAuthTokens represents the tokens obtained from OAuth flow-type OAuthTokens struct {- AccessToken string `json:"access_token"`- RefreshToken string `json:"refresh_token"`- TokenType string `json:"token_type"`- ExpiresIn int `json:"expires_in"`- Scope string `json:"scope"`- ExpiresAt time.Time `json:"-"`- // APIKey is created from the access token and used for actual API calls- APIKey string `json:"api_key,omitempty"`-}--// OAuthSession stores the state for an in-progress OAuth flow-type OAuthSession struct {- State string- CodeVerifier string- RedirectURI string- CreatedAt time.Time-}--// GenerateOAuthSession creates a new OAuth session with PKCE parameters-func GenerateOAuthSession(redirectURI string) (*OAuthSession, error) {- // Generate state (for CSRF protection)- stateBytes := make([]byte, 32)- if _, err := rand.Read(stateBytes); err != nil {- return nil, fmt.Errorf("failed to generate state: %w", err)- }- state := base64.RawURLEncoding.EncodeToString(stateBytes)-- // Generate code verifier (PKCE)- verifierBytes := make([]byte, 32)- if _, err := rand.Read(verifierBytes); err != nil {- return nil, fmt.Errorf("failed to generate code verifier: %w", err)- }- codeVerifier := base64.RawURLEncoding.EncodeToString(verifierBytes)-- return &OAuthSession{- State: state,- CodeVerifier: codeVerifier,- RedirectURI: redirectURI,- CreatedAt: time.Now(),- }, nil-}--// GetAuthorizationURL returns the URL to redirect the user to for OAuth authorization-// The user will visit this URL, log in, and get an authorization code to paste back-func GetAuthorizationURL(session *OAuthSession) string {- // Generate code challenge from code verifier (S256)- h := sha256.Sum256([]byte(session.CodeVerifier))- codeChallenge := base64.RawURLEncoding.EncodeToString(h[:])-- params := url.Values{}- // Match Claude Code's exact parameter order and values- params.Set("code", "true") // Claude Code adds this- params.Set("client_id", claudeCodeClientID)- params.Set("response_type", "code")- // Use Anthropic's official callback which displays the code for the user to copy- params.Set("redirect_uri", "https://console.anthropic.com/oauth/code/callback")- params.Set("scope", oauthScopes)- params.Set("code_challenge", codeChallenge)- params.Set("code_challenge_method", "S256")- params.Set("state", session.State)-- return oauthAuthorizeURL + "?" + params.Encode()-}--// ExchangeCodeForTokens exchanges an authorization code for access tokens-func ExchangeCodeForTokens(ctx context.Context, code string, session *OAuthSession) (*OAuthTokens, error) {- // Build JSON body (matching Claude Code's exact implementation)- // Claude Code uses Content-Type: application/json, NOT form-urlencoded- payload := map[string]interface{}{- "grant_type": "authorization_code",- "code": code,- "redirect_uri": "https://console.anthropic.com/oauth/code/callback",- "client_id": claudeCodeClientID,- "code_verifier": session.CodeVerifier,- "state": session.State,- }-- jsonBody, err := json.Marshal(payload)- if err != nil {- return nil, fmt.Errorf("failed to marshal token request: %w", err)- }-- log.Debug().- Str("grant_type", "authorization_code").- Str("client_id", claudeCodeClientID).- Str("code_len", fmt.Sprintf("%d", len(code))).- Str("verifier_len", fmt.Sprintf("%d", len(session.CodeVerifier))).- Str("state_prefix", session.State[:min(8, len(session.State))]).- Str("redirect_uri", "https://console.anthropic.com/oauth/code/callback").- Msg("Sending OAuth token exchange request (JSON)")-- req, err := http.NewRequestWithContext(ctx, "POST", oauthTokenURL, bytes.NewReader(jsonBody))- if err != nil {- return nil, fmt.Errorf("failed to create token request: %w", err)- }-- req.Header.Set("Content-Type", "application/json")-- resp, err := oauthHTTPClient.Do(req)- if err != nil {- return nil, fmt.Errorf("token request failed: %w", err)- }- defer resp.Body.Close()-- body, err := io.ReadAll(resp.Body)- if err != nil {- return nil, fmt.Errorf("failed to read token response: %w", err)- }-- if resp.StatusCode != http.StatusOK {- log.Error().- Int("status", resp.StatusCode).- Str("body", string(body)).- Msg("OAuth token exchange failed")- return nil, fmt.Errorf("token exchange failed with status %d: %s", resp.StatusCode, string(body))- }-- var tokens OAuthTokens- if err := json.Unmarshal(body, &tokens); err != nil {- return nil, fmt.Errorf("failed to parse token response: %w", err)- }-- // Calculate expiration time- if tokens.ExpiresIn > 0 {- tokens.ExpiresAt = time.Now().Add(time.Duration(tokens.ExpiresIn) * time.Second)- }-- log.Info().- Str("token_type", tokens.TokenType).- Int("expires_in", tokens.ExpiresIn).- Str("scope", tokens.Scope).- Msg("Successfully exchanged OAuth code for tokens")-- return &tokens, nil-}--// CreateAPIKeyFromOAuth uses an OAuth access token to create a real API key-// This is how Claude Code uses the OAuth flow - the OAuth token creates an API key-func CreateAPIKeyFromOAuth(ctx context.Context, accessToken string) (string, error) {- req, err := http.NewRequestWithContext(ctx, "POST", oauthAPIKeyURL, nil)- if err != nil {- return "", fmt.Errorf("failed to create API key request: %w", err)- }-- req.Header.Set("Authorization", "Bearer "+accessToken)-- resp, err := oauthHTTPClient.Do(req)- if err != nil {- return "", fmt.Errorf("API key request failed: %w", err)- }- defer resp.Body.Close()-- body, err := io.ReadAll(resp.Body)- if err != nil {- return "", fmt.Errorf("failed to read API key response: %w", err)- }-- if resp.StatusCode != http.StatusOK {- log.Error().- Int("status", resp.StatusCode).- Str("body", string(body)).- Msg("Failed to create API key from OAuth token")- return "", fmt.Errorf("API key creation failed with status %d: %s", resp.StatusCode, string(body))- }-- var result struct {- RawKey string `json:"raw_key"`- }- if err := json.Unmarshal(body, &result); err != nil {- return "", fmt.Errorf("failed to parse API key response: %w", err)- }-- if result.RawKey == "" {- return "", fmt.Errorf("no API key returned from OAuth")- }-- log.Info().Msg("successfully created API key from OAuth token")- return result.RawKey, nil-}--// RefreshAccessToken uses a refresh token to get a new access token-func RefreshAccessToken(ctx context.Context, refreshToken string) (*OAuthTokens, error) {- // Build JSON body (matching Claude Code's implementation)- payload := map[string]interface{}{- "grant_type": "refresh_token",- "refresh_token": refreshToken,- "client_id": claudeCodeClientID,- "scope": oauthScopes,- }-- jsonBody, err := json.Marshal(payload)- if err != nil {- return nil, fmt.Errorf("failed to marshal refresh request: %w", err)- }-- log.Debug().- Str("grant_type", "refresh_token").- Str("client_id", claudeCodeClientID).- Msg("Sending OAuth token refresh request")-- req, err := http.NewRequestWithContext(ctx, "POST", oauthTokenURL, bytes.NewReader(jsonBody))- if err != nil {- return nil, fmt.Errorf("failed to create refresh request: %w", err)- }-- req.Header.Set("Content-Type", "application/json")-- resp, err := oauthHTTPClient.Do(req)- if err != nil {- return nil, fmt.Errorf("refresh request failed: %w", err)- }- defer resp.Body.Close()-- body, err := io.ReadAll(resp.Body)- if err != nil {- return nil, fmt.Errorf("failed to read refresh response: %w", err)- }-- if resp.StatusCode != http.StatusOK {- log.Warn().- Int("status", resp.StatusCode).- Str("body", string(body)).- Msg("OAuth token refresh failed")- return nil, fmt.Errorf("token refresh failed with status %d: %s", resp.StatusCode, string(body))- }-- var tokens OAuthTokens- if err := json.Unmarshal(body, &tokens); err != nil {- return nil, fmt.Errorf("failed to parse refresh response: %w", err)- }-- // Keep the original refresh token if a new one wasn't returned- if tokens.RefreshToken == "" {- tokens.RefreshToken = refreshToken- }-- // Calculate expiration time- if tokens.ExpiresIn > 0 {- tokens.ExpiresAt = time.Now().Add(time.Duration(tokens.ExpiresIn) * time.Second)- }-- log.Info().- Int("expires_in", tokens.ExpiresIn).- Msg("Successfully refreshed OAuth access token")-- return &tokens, nil-}--// AnthropicOAuthClient is a client that uses OAuth tokens instead of API keys-type AnthropicOAuthClient struct {- accessToken string- refreshToken string- expiresAt time.Time- model string- baseURL string- client *http.Client- onTokenRefresh func(tokens *OAuthTokens) // Callback when tokens are refreshed-}--// NewAnthropicOAuthClient creates a new Anthropic client using OAuth tokens-// timeout is optional - pass 0 to use the default 5 minute timeout-func NewAnthropicOAuthClient(accessToken, refreshToken string, expiresAt time.Time, model string, timeout time.Duration) *AnthropicOAuthClient {- return NewAnthropicOAuthClientWithBaseURL(accessToken, refreshToken, expiresAt, model, "https://api.anthropic.com/v1/messages?beta=true", timeout)-}--// NewAnthropicOAuthClientWithBaseURL creates a new Anthropic OAuth client using a custom messages endpoint.-// This is useful for testing and for deployments that route requests through a proxy.-// timeout is optional - pass 0 to use the default 5 minute timeout-func NewAnthropicOAuthClientWithBaseURL(accessToken, refreshToken string, expiresAt time.Time, model, baseURL string, timeout time.Duration) *AnthropicOAuthClient {- if baseURL == "" {- baseURL = "https://api.anthropic.com/v1/messages?beta=true"- }- if timeout <= 0 {- timeout = 300 * time.Second // Default 5 minutes- }- return &AnthropicOAuthClient{- accessToken: accessToken,- refreshToken: refreshToken,- expiresAt: expiresAt,- model: model,- baseURL: baseURL,- client: &http.Client{- Timeout: timeout,- },- }-}--// SetTokenRefreshCallback sets a callback that will be called when tokens are refreshed-func (c *AnthropicOAuthClient) SetTokenRefreshCallback(callback func(tokens *OAuthTokens)) {- c.onTokenRefresh = callback-}--// Name returns the provider name-func (c *AnthropicOAuthClient) Name() string {- return "anthropic-oauth"-}--// ensureValidToken checks if the token is expired and refreshes if needed-func (c *AnthropicOAuthClient) ensureValidToken(ctx context.Context) error {- // Add some buffer (5 minutes) before expiration- if time.Now().Add(5 * time.Minute).Before(c.expiresAt) {- return nil // Token is still valid- }-- return c.forceRefreshToken(ctx)-}--// forceRefreshToken forces a token refresh (used on 401 errors)-func (c *AnthropicOAuthClient) forceRefreshToken(ctx context.Context) error {- if c.refreshToken == "" {- return fmt.Errorf("access token expired and no refresh token available")- }-- log.Info().Msg("OAuth access token expired, refreshing...")-- tokens, err := RefreshAccessToken(ctx, c.refreshToken)- if err != nil {- return fmt.Errorf("failed to refresh token: %w", err)- }-- c.accessToken = tokens.AccessToken- if tokens.RefreshToken != "" {- c.refreshToken = tokens.RefreshToken- }- c.expiresAt = tokens.ExpiresAt-- // Notify callback of new tokens- if c.onTokenRefresh != nil {- c.onTokenRefresh(tokens)- }-- return nil-}--// Chat sends a chat request to the Anthropic API using OAuth bearer token-func (c *AnthropicOAuthClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse, error) {- // Ensure we have a valid token- if err := c.ensureValidToken(ctx); err != nil {- return nil, fmt.Errorf("failed to ensure valid OAuth token: %w", err)- }-- // Convert messages to Anthropic format (same as regular client)- messages, err := convertMessagesToAnthropic(req.Messages)- if err != nil {- return nil, err- }-- model := req.Model- // Strip provider prefix if present - callers may pass the full "provider:model" string- if len(model) > 10 && model[:10] == "anthropic:" {- model = model[10:]- }- if model == "" {- model = c.model- }-- maxTokens := req.MaxTokens- if maxTokens == 0 {- maxTokens = 4096- }-- anthropicReq := anthropicRequest{- Model: model,- Messages: messages,- MaxTokens: maxTokens,- System: req.System,- }-- if req.Temperature > 0 {- anthropicReq.Temperature = req.Temperature- }-- if len(req.Tools) > 0 {- anthropicReq.Tools = make([]anthropicTool, len(req.Tools))- for i, t := range req.Tools {- if t.Type == "web_search_20250305" {- anthropicReq.Tools[i] = anthropicTool{- Type: t.Type,- Name: t.Name,- MaxUses: t.MaxUses,- }- } else {- anthropicReq.Tools[i] = anthropicTool{- Name: t.Name,- Description: t.Description,- InputSchema: t.InputSchema,- }- }- }- }-- body, err := json.Marshal(anthropicReq)- if err != nil {- return nil, fmt.Errorf("failed to marshal request: %w", err)- }-- var respBody []byte- var lastErr error- var skipBackoff bool-- for attempt := 0; attempt <= maxRetries; attempt++ {- if attempt > 0 {- if skipBackoff {- skipBackoff = false- } else {- backoff := initialBackoff * time.Duration(1<<(attempt-1))- log.Warn().- Int("attempt", attempt).- Dur("backoff", backoff).- Str("last_error", lastErr.Error()).- Msg("Retrying Anthropic OAuth API request after transient error")-- backoffTimer := time.NewTimer(backoff)- select {- case <-ctx.Done():- if !backoffTimer.Stop() {- select {- case <-backoffTimer.C:- default:- }- }- return nil, ctx.Err()- case <-backoffTimer.C:- }- }- }-- httpReq, err := http.NewRequestWithContext(ctx, "POST", c.baseURL, bytes.NewReader(body))- if err != nil {- return nil, fmt.Errorf("failed to create request: %w", err)- }-- httpReq.Header.Set("Content-Type", "application/json")- // OAuth uses Authorization: Bearer instead of x-api-key- httpReq.Header.Set("Authorization", "Bearer "+c.accessToken)- httpReq.Header.Set("anthropic-version", anthropicAPIVersion)- // Required for OAuth authentication - enables subscription-based access- httpReq.Header.Set("anthropic-beta", "oauth-2025-04-20")- // Claude Code identification headers- httpReq.Header.Set("x-app", "cli")- httpReq.Header.Set("User-Agent", "claude-code/2.0.60")-- resp, err := c.client.Do(httpReq)- if err != nil {- lastErr = fmt.Errorf("request failed: %w", err)- continue- }-- respBody, err = io.ReadAll(resp.Body)- resp.Body.Close()- if err != nil {- lastErr = fmt.Errorf("failed to read response: %w", err)- continue- }-- // Check for token expiry error (401) - force refresh- if resp.StatusCode == 401 && c.refreshToken != "" {- log.Info().Msg("got 401, forcing token refresh...")- if err := c.forceRefreshToken(ctx); err == nil {- // Token refreshed, retry immediately without backoff- lastErr = fmt.Errorf("token expired, retried with refreshed token")- skipBackoff = true- continue- } else {- log.Error().Err(err).Msg("failed to refresh token after 401")- }- }-- if resp.StatusCode == 429 || resp.StatusCode == 529 || resp.StatusCode >= 500 {- var errResp anthropicError- errMsg := string(respBody)- if err := json.Unmarshal(respBody, &errResp); err == nil && errResp.Error.Message != "" {- errMsg = errResp.Error.Message- }- errMsg = appendRateLimitInfo(errMsg, resp)- lastErr = fmt.Errorf("API error (%d): %s", resp.StatusCode, errMsg)- continue- }-- if resp.StatusCode != http.StatusOK {- var errResp anthropicError- if err := json.Unmarshal(respBody, &errResp); err == nil && errResp.Error.Message != "" {- errMsg := appendRateLimitInfo(errResp.Error.Message, resp)- return nil, fmt.Errorf("API error (%d): %s", resp.StatusCode, errMsg)- }- errMsg := appendRateLimitInfo(string(respBody), resp)- return nil, fmt.Errorf("API error (%d): %s", resp.StatusCode, errMsg)- }-- lastErr = nil- break- }-- if lastErr != nil {- return nil, fmt.Errorf("failed after %d retries: %w", maxRetries, lastErr)- }-- var anthropicResp anthropicResponse- if err := json.Unmarshal(respBody, &anthropicResp); err != nil {- return nil, fmt.Errorf("failed to parse response: %w", err)- }-- var textContent string- var toolCalls []ToolCall- for _, c := range anthropicResp.Content {- switch c.Type {- case "text":- textContent += c.Text- case "tool_use":- toolCalls = append(toolCalls, ToolCall{- ID: c.ID,- Name: c.Name,- Input: c.Input,- })- case "server_tool_use":- log.Debug().- Str("tool_name", c.Name).- Msg("Server tool use detected (handled by Anthropic)")- case "web_search_tool_result":- log.Debug().Msg("web search results received")- }- }-- return &ChatResponse{- Content: textContent,- Model: anthropicResp.Model,- StopReason: anthropicResp.StopReason,- ToolCalls: toolCalls,- InputTokens: anthropicResp.Usage.InputTokens,- OutputTokens: anthropicResp.Usage.OutputTokens,- }, nil-}--// TestConnection validates the OAuth token by listing models-// This avoids dependencies on specific model names which may get deprecated-func (c *AnthropicOAuthClient) TestConnection(ctx context.Context) error {- if _, err := c.ListModels(ctx); err != nil {- return fmt.Errorf("anthropic oauth test connection failed: %w", err)- }- return nil-}--func (c *AnthropicOAuthClient) modelsEndpoint() string {- defaultURL := "https://api.anthropic.com/v1/models"- u, err := url.Parse(c.baseURL)- if err != nil || u.Scheme == "" || u.Host == "" {- return defaultURL- }- return u.Scheme + "://" + u.Host + "/v1/models"-}--// ListModels fetches available models from the Anthropic API using OAuth-func (c *AnthropicOAuthClient) ListModels(ctx context.Context) ([]ModelInfo, error) {- // Ensure we have a valid token- if err := c.ensureValidToken(ctx); err != nil {- return nil, fmt.Errorf("failed to ensure valid OAuth token: %w", err)- }-- req, err := http.NewRequestWithContext(ctx, "GET", c.modelsEndpoint(), nil)- if err != nil {- return nil, fmt.Errorf("failed to create request: %w", err)- }-- req.Header.Set("Authorization", "Bearer "+c.accessToken)- req.Header.Set("anthropic-version", anthropicAPIVersion)-- resp, err := c.client.Do(req)- if err != nil {- return nil, fmt.Errorf("request failed: %w", err)- }- defer resp.Body.Close()-- if resp.StatusCode != http.StatusOK {- body, _ := io.ReadAll(resp.Body)- return nil, fmt.Errorf("API error (%d): %s", resp.StatusCode, string(body))- }-- var result struct {- Data []struct {- ID string `json:"id"`- DisplayName string `json:"display_name"`- CreatedAt string `json:"created_at"`- } `json:"data"`- }-- if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return nil, fmt.Errorf("failed to parse response: %w", err)- }-- models := make([]ModelInfo, 0, len(result.Data))- for _, m := range result.Data {- models = append(models, ModelInfo{- ID: m.ID,- Name: m.DisplayName,- })- }-- return models, nil-}diff --git a/internal/ai/providers/anthropic_oauth_test.go b/internal/ai/providers/anthropic_oauth_test.godeleted file mode 100644index ac807aac7d..0000000000--- a/internal/ai/providers/anthropic_oauth_test.go+++ /dev/null@@ -1,617 +0,0 @@-package providers--import (- "context"- "crypto/sha256"- "encoding/base64"- "encoding/json"- "net/http"- "net/http/httptest"- "net/url"- "strings"- "testing"- "time"-)--func TestGenerateOAuthSession(t *testing.T) {- s, err := GenerateOAuthSession("http://localhost/callback")- if err != nil {- t.Fatalf("GenerateOAuthSession: %v", err)- }- if s.RedirectURI != "http://localhost/callback" {- t.Fatalf("RedirectURI = %q", s.RedirectURI)- }- if s.State == "" || s.CodeVerifier == "" {- t.Fatalf("expected non-empty state and verifier: %+v", s)- }- if strings.Contains(s.State, "=") || strings.Contains(s.CodeVerifier, "=") {- t.Fatalf("expected raw base64url encoding (no '='): %+v", s)- }- if time.Since(s.CreatedAt) > 2*time.Second {- t.Fatalf("CreatedAt too old: %v", s.CreatedAt)- }-}--func TestGetAuthorizationURL_IncludesExpectedParamsAndChallenge(t *testing.T) {- session := &OAuthSession{- State: "state_123",- CodeVerifier: "verifier_456",- }-- u, err := url.Parse(GetAuthorizationURL(session))- if err != nil {- t.Fatalf("parse url: %v", err)- }-- q := u.Query()- if q.Get("code") != "true" {- t.Fatalf("code = %q", q.Get("code"))- }- if q.Get("client_id") != claudeCodeClientID {- t.Fatalf("client_id = %q", q.Get("client_id"))- }- if q.Get("response_type") != "code" {- t.Fatalf("response_type = %q", q.Get("response_type"))- }- if q.Get("redirect_uri") != "https://console.anthropic.com/oauth/code/callback" {- t.Fatalf("redirect_uri = %q", q.Get("redirect_uri"))- }- if q.Get("scope") != oauthScopes {- t.Fatalf("scope = %q", q.Get("scope"))- }- if q.Get("code_challenge_method") != "S256" {- t.Fatalf("code_challenge_method = %q", q.Get("code_challenge_method"))- }- if q.Get("state") != "state_123" {- t.Fatalf("state = %q", q.Get("state"))- }-- h := sha256.Sum256([]byte(session.CodeVerifier))- wantChallenge := base64.RawURLEncoding.EncodeToString(h[:])- if q.Get("code_challenge") != wantChallenge {- t.Fatalf("code_challenge = %q, want %q", q.Get("code_challenge"), wantChallenge)- }-}--func TestExchangeCodeForTokens_Success(t *testing.T) {- oldTokenURL := oauthTokenURL- oldClient := oauthHTTPClient- t.Cleanup(func() {- oauthTokenURL = oldTokenURL- oauthHTTPClient = oldClient- })-- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodPost {- t.Fatalf("method = %s, want POST", r.Method)- }- if r.URL.Path != "/v1/oauth/token" {- t.Fatalf("path = %s", r.URL.Path)- }- if r.Header.Get("Content-Type") != "application/json" {- t.Fatalf("Content-Type = %q", r.Header.Get("Content-Type"))- }-- var payload map[string]any- if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {- t.Fatalf("decode: %v", err)- }- if payload["grant_type"] != "authorization_code" {- t.Fatalf("grant_type = %v", payload["grant_type"])- }- if payload["code"] != "code_abc" {- t.Fatalf("code = %v", payload["code"])- }- if payload["client_id"] != claudeCodeClientID {- t.Fatalf("client_id = %v", payload["client_id"])- }- if payload["code_verifier"] != "verifier" {- t.Fatalf("code_verifier = %v", payload["code_verifier"])- }- if payload["state"] != "state" {- t.Fatalf("state = %v", payload["state"])- }-- _ = json.NewEncoder(w).Encode(OAuthTokens{- AccessToken: "access_1",- RefreshToken: "refresh_1",- TokenType: "bearer",- ExpiresIn: 3600,- Scope: oauthScopes,- })- }))- defer server.Close()-- oauthTokenURL = server.URL + "/v1/oauth/token"- oauthHTTPClient = server.Client()-- now := time.Now()- tokens, err := ExchangeCodeForTokens(context.Background(), "code_abc", &OAuthSession{- State: "state",- CodeVerifier: "verifier",- })- if err != nil {- t.Fatalf("ExchangeCodeForTokens: %v", err)- }- if tokens.AccessToken != "access_1" || tokens.RefreshToken != "refresh_1" {- t.Fatalf("unexpected tokens: %+v", tokens)- }- if tokens.ExpiresAt.Before(now) || tokens.ExpiresAt.After(now.Add(2*time.Hour)) {- t.Fatalf("ExpiresAt = %v, now = %v", tokens.ExpiresAt, now)- }-}--func TestExchangeCodeForTokens_ErrorStatusIncludesBody(t *testing.T) {- oldTokenURL := oauthTokenURL- oldClient := oauthHTTPClient- t.Cleanup(func() {- oauthTokenURL = oldTokenURL- oauthHTTPClient = oldClient- })-- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusBadRequest)- _, _ = w.Write([]byte("bad request"))- }))- defer server.Close()-- oauthTokenURL = server.URL- oauthHTTPClient = server.Client()-- _, err := ExchangeCodeForTokens(context.Background(), "code", &OAuthSession{State: "s", CodeVerifier: "v"})- if err == nil {- t.Fatal("expected error")- }- if !strings.Contains(err.Error(), "status 400") || !strings.Contains(err.Error(), "bad request") {- t.Fatalf("unexpected error: %v", err)- }-}--func TestCreateAPIKeyFromOAuth_SuccessAndEmptyKey(t *testing.T) {- oldAPIKeyURL := oauthAPIKeyURL- oldClient := oauthHTTPClient- t.Cleanup(func() {- oauthAPIKeyURL = oldAPIKeyURL- oauthHTTPClient = oldClient- })-- var call int- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- call++- if r.Header.Get("Authorization") != "Bearer access" {- t.Fatalf("Authorization = %q", r.Header.Get("Authorization"))- }- if call == 1 {- _ = json.NewEncoder(w).Encode(map[string]any{"raw_key": "sk-ant-123"})- return- }- _ = json.NewEncoder(w).Encode(map[string]any{"raw_key": ""})- }))- defer server.Close()-- oauthAPIKeyURL = server.URL- oauthHTTPClient = server.Client()-- key, err := CreateAPIKeyFromOAuth(context.Background(), "access")- if err != nil {- t.Fatalf("CreateAPIKeyFromOAuth: %v", err)- }- if key != "sk-ant-123" {- t.Fatalf("key = %q", key)- }-- _, err = CreateAPIKeyFromOAuth(context.Background(), "access")- if err == nil {- t.Fatal("expected error")- }-}--func TestRefreshAccessToken_KeepsOriginalRefreshTokenWhenOmitted(t *testing.T) {- oldTokenURL := oauthTokenURL- oldClient := oauthHTTPClient- t.Cleanup(func() {- oauthTokenURL = oldTokenURL- oauthHTTPClient = oldClient- })-- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- var payload map[string]any- _ = json.NewDecoder(r.Body).Decode(&payload)- if payload["grant_type"] != "refresh_token" {- t.Fatalf("grant_type = %v", payload["grant_type"])- }- if payload["refresh_token"] != "refresh_old" {- t.Fatalf("refresh_token = %v", payload["refresh_token"])- }- _ = json.NewEncoder(w).Encode(OAuthTokens{- AccessToken: "access_new",- // RefreshToken intentionally omitted- TokenType: "bearer",- ExpiresIn: 3600,- })- }))- defer server.Close()-- oauthTokenURL = server.URL- oauthHTTPClient = server.Client()-- tokens, err := RefreshAccessToken(context.Background(), "refresh_old")- if err != nil {- t.Fatalf("RefreshAccessToken: %v", err)- }- if tokens.AccessToken != "access_new" || tokens.RefreshToken != "refresh_old" {- t.Fatalf("unexpected tokens: %+v", tokens)- }-}--func TestAnthropicOAuthClient_forceRefreshToken_UpdatesAndCallsCallback(t *testing.T) {- oldTokenURL := oauthTokenURL- oldClient := oauthHTTPClient- t.Cleanup(func() {- oauthTokenURL = oldTokenURL- oauthHTTPClient = oldClient- })-- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- _ = json.NewEncoder(w).Encode(OAuthTokens{- AccessToken: "access_new",- RefreshToken: "refresh_new",- TokenType: "bearer",- ExpiresIn: 3600,- })- }))- defer server.Close()-- oauthTokenURL = server.URL- oauthHTTPClient = server.Client()-- client := NewAnthropicOAuthClient("access_old", "refresh_old", time.Now().Add(-time.Minute), "claude-3", 0)-- var cbTokens *OAuthTokens- client.SetTokenRefreshCallback(func(tokens *OAuthTokens) { cbTokens = tokens })-- if err := client.forceRefreshToken(context.Background()); err != nil {- t.Fatalf("forceRefreshToken: %v", err)- }- if client.accessToken != "access_new" || client.refreshToken != "refresh_new" {- t.Fatalf("unexpected client tokens: access=%q refresh=%q", client.accessToken, client.refreshToken)- }- if cbTokens == nil || cbTokens.AccessToken != "access_new" {- t.Fatalf("expected callback with new tokens, got: %+v", cbTokens)- }-}--func TestAnthropicOAuthClient_Chat_RefreshesOn401AndRetriesImmediately(t *testing.T) {- oldTokenURL := oauthTokenURL- oldClient := oauthHTTPClient- t.Cleanup(func() {- oauthTokenURL = oldTokenURL- oauthHTTPClient = oldClient- })-- var messageCalls int- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- switch r.URL.Path {- case "/v1/oauth/token":- _ = json.NewEncoder(w).Encode(OAuthTokens{- AccessToken: "access_new",- RefreshToken: "refresh_new",- TokenType: "bearer",- ExpiresIn: 3600,- })- case "/v1/messages":- if r.URL.Query().Get("beta") != "true" {- t.Fatalf("expected beta=true query, got %q", r.URL.RawQuery)- }- if r.Header.Get("anthropic-version") != anthropicAPIVersion {- t.Fatalf("anthropic-version = %q", r.Header.Get("anthropic-version"))- }- if r.Header.Get("anthropic-beta") != "oauth-2025-04-20" {- t.Fatalf("anthropic-beta = %q", r.Header.Get("anthropic-beta"))- }- if r.Header.Get("x-app") != "cli" {- t.Fatalf("x-app = %q", r.Header.Get("x-app"))- }-- messageCalls++- if messageCalls == 1 {- if r.Header.Get("Authorization") != "Bearer access_old" {- t.Fatalf("Authorization (first) = %q", r.Header.Get("Authorization"))- }- w.WriteHeader(http.StatusUnauthorized)- _, _ = w.Write([]byte(`{"error":{"message":"unauthorized"}}`))- return- }- if r.Header.Get("Authorization") != "Bearer access_new" {- t.Fatalf("Authorization (retry) = %q", r.Header.Get("Authorization"))- }-- var got anthropicRequest- if err := json.NewDecoder(r.Body).Decode(&got); err != nil {- t.Fatalf("decode request: %v", err)- }- if got.Model != "claude-3" {- t.Fatalf("Model = %q", got.Model)- }- if len(got.Messages) != 1 || got.Messages[0].Role != "user" || got.Messages[0].Content != "Hi" {- t.Fatalf("unexpected messages: %+v", got.Messages)- }-- _ = json.NewEncoder(w).Encode(anthropicResponse{- ID: "msg_123",- Type: "message",- Role: "assistant",- Model: "claude-3",- StopReason: "end_turn",- Content: []anthropicContent{{Type: "text", Text: "ok"}},- Usage: anthropicUsage{InputTokens: 1, OutputTokens: 2},- })- default:- t.Fatalf("unexpected path: %s", r.URL.Path)- }- }))- defer server.Close()-- oauthTokenURL = server.URL + "/v1/oauth/token"- oauthHTTPClient = server.Client()-- client := NewAnthropicOAuthClientWithBaseURL(- "access_old",- "refresh_old",- time.Now().Add(10*time.Minute), // valid token, so refresh is driven by 401- "claude-3",- server.URL+"/v1/messages?beta=true",- 0,- )- client.client = server.Client()-- ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)- defer cancel()-- out, err := client.Chat(ctx, ChatRequest{Messages: []Message{{Role: "user", Content: "Hi"}}})- if err != nil {- t.Fatalf("Chat: %v", err)- }- if out.Content != "ok" || out.InputTokens != 1 || out.OutputTokens != 2 {- t.Fatalf("unexpected response: %+v", out)- }- if messageCalls != 2 {- t.Fatalf("messageCalls = %d, want 2", messageCalls)- }-}--func TestAnthropicOAuthClient_ListModels_UsesConfiguredHost(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.URL.Path != "/v1/models" {- t.Fatalf("path = %s, want /v1/models", r.URL.Path)- }- if r.Header.Get("Authorization") != "Bearer access" {- t.Fatalf("Authorization = %q", r.Header.Get("Authorization"))- }- _ = json.NewEncoder(w).Encode(map[string]any{- "data": []map[string]any{- {"id": "claude-3", "display_name": "Claude 3", "created_at": "2024-01-01T00:00:00Z"},- },- })- }))- defer server.Close()-- client := NewAnthropicOAuthClientWithBaseURL(- "access",- "refresh",- time.Now().Add(10*time.Minute),- "claude-3",- server.URL+"/v1/messages?beta=true",- 0,- )- client.client = server.Client()-- models, err := client.ListModels(context.Background())- if err != nil {- t.Fatalf("ListModels: %v", err)- }- if len(models) != 1 || models[0].ID != "claude-3" || models[0].Name != "Claude 3" {- t.Fatalf("unexpected models: %+v", models)- }-}-func TestAnthropicOAuthClient_Name(t *testing.T) {- client := NewAnthropicOAuthClient("access", "refresh", time.Now(), "claude-3", 0)- if client.Name() != "anthropic-oauth" {- t.Errorf("Expected 'anthropic-oauth', got %q", client.Name())- }-}--func TestAnthropicOAuthClient_TestConnection(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- json.NewEncoder(w).Encode(map[string]any{"data": []any{}})- }))- defer server.Close()-- client := NewAnthropicOAuthClientWithBaseURL("access", "refresh", time.Now().Add(time.Hour), "claude-3", server.URL, 0)- client.client = server.Client()-- if err := client.TestConnection(context.Background()); err != nil {- t.Errorf("TestConnection failed: %v", err)- }-}--func TestAnthropicOAuthClient_ListModels_Error(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusInternalServerError)- }))- defer server.Close()-- client := NewAnthropicOAuthClientWithBaseURL("access", "refresh", time.Now().Add(time.Hour), "claude-3", server.URL, 0)- client.client = server.Client()-- if _, err := client.ListModels(context.Background()); err == nil {- t.Error("Expected error for 500 status")- }-}--func TestAnthropicOAuthClient_Chat_SystemAndParams(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- var req anthropicRequest- _ = json.NewDecoder(r.Body).Decode(&req)-- if req.System != "sys" {- t.Errorf("Expected system 'sys', got %q", req.System)- }- if req.Temperature != 0.5 {- t.Errorf("Expected temp 0.5, got %f", req.Temperature)- }- if req.MaxTokens != 100 {- t.Errorf("Expected max tokens 100, got %d", req.MaxTokens)- }- if len(req.Messages) != 1 || req.Messages[0].Content != "hi" {- t.Errorf("Unexpected messages: %+v", req.Messages)- }-- json.NewEncoder(w).Encode(anthropicResponse{- Content: []anthropicContent{{Type: "text", Text: "ok"}},- })- }))- defer server.Close()-- client := NewAnthropicOAuthClientWithBaseURL("access", "refresh", time.Now().Add(time.Hour), "claude-3", server.URL, 0)- client.client = server.Client()-- _, err := client.Chat(context.Background(), ChatRequest{- System: "sys",- Temperature: 0.5,- MaxTokens: 100,- Messages: []Message{{Role: "user", Content: "hi"}},- })- if err != nil {- t.Fatalf("Chat failed: %v", err)- }-}--func TestAnthropicOAuthClient_Chat_NetworkError(t *testing.T) {- client := NewAnthropicOAuthClientWithBaseURL("access", "refresh", time.Now().Add(time.Hour), "claude-3", "http://localhost:99999", 0)-- ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)- defer cancel()-- if _, err := client.Chat(ctx, ChatRequest{Messages: []Message{{Role: "user", Content: "hi"}}}); err == nil {- t.Error("Expected network error")- }-}--func TestAnthropicOAuthClient_Chat_RefreshesOnTimeExpiry(t *testing.T) {- oldTokenURL := oauthTokenURL- oldClient := oauthHTTPClient- t.Cleanup(func() {- oauthTokenURL = oldTokenURL- oauthHTTPClient = oldClient- })-- // Server handles token refresh- tokenServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- _ = json.NewEncoder(w).Encode(OAuthTokens{- AccessToken: "access_new",- RefreshToken: "refresh_new",- TokenType: "bearer",- ExpiresIn: 3600,- })- }))- defer tokenServer.Close()-- oauthTokenURL = tokenServer.URL- oauthHTTPClient = tokenServer.Client()-- // Chat server- chatServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.Header.Get("Authorization") != "Bearer access_new" {- t.Errorf("Expected refreshed token, got %q", r.Header.Get("Authorization"))- }- _ = json.NewEncoder(w).Encode(anthropicResponse{- Content: []anthropicContent{{Type: "text", Text: "ok"}},- })- }))- defer chatServer.Close()-- // Client with expired token- client := NewAnthropicOAuthClientWithBaseURL(- "access_old",- "refresh_old",- time.Now().Add(-time.Hour), // Expired- "claude-3",- chatServer.URL,- 0,- )- client.client = chatServer.Client()-- _, err := client.Chat(context.Background(), ChatRequest{Messages: []Message{{Role: "user", Content: "hi"}}})- if err != nil {- t.Fatalf("Chat failed: %v", err)- }-}--func TestAnthropicOAuthClient_Chat_ContextCanceledDuringRetry(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusTooManyRequests) // Trigger retry- w.Write([]byte(`{"error":{"message":"busy"}}`))- }))- defer server.Close()-- client := NewAnthropicOAuthClientWithBaseURL("access", "refresh", time.Now().Add(time.Hour), "claude-3", server.URL, 0)- client.client = server.Client()-- ctx, cancel := context.WithCancel(context.Background())- // Cancel after short delay, shorter than backoff (2s)- go func() {- time.Sleep(100 * time.Millisecond)- cancel()- }()-- _, err := client.Chat(ctx, ChatRequest{Messages: []Message{{Role: "user", Content: "hi"}}})- if err == nil {- t.Error("Expected error")- }-}--func TestCreateAPIKeyFromOAuth_RequestError(t *testing.T) {- oldURL := oauthAPIKeyURL- defer func() { oauthAPIKeyURL = oldURL }()- oauthAPIKeyURL = "::invalid" // Invalid URL-- _, err := CreateAPIKeyFromOAuth(context.Background(), "token")- if err == nil {- t.Error("Expected error for invalid URL")- }-}--func TestAnthropicOAuthClient_Chat_ToolUsage(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- var req anthropicRequest- _ = json.NewDecoder(r.Body).Decode(&req)-- if len(req.Tools) != 1 || req.Tools[0].Name != "my_tool" {- t.Errorf("Expected tool 'my_tool', got %+v", req.Tools)- }-- json.NewEncoder(w).Encode(anthropicResponse{- Content: []anthropicContent{- {Type: "text", Text: "thinking..."},- {Type: "tool_use", ID: "id1", Name: "my_tool", Input: map[string]any{"arg": 1}},- },- StopReason: "tool_use",- })- }))- defer server.Close()-- client := NewAnthropicOAuthClientWithBaseURL("access", "refresh", time.Now().Add(time.Hour), "claude-3", server.URL, 0)- client.client = server.Client()-- resp, err := client.Chat(context.Background(), ChatRequest{- Messages: []Message{{Role: "user", Content: "hi"}},- Tools: []Tool{{Name: "my_tool", Description: "desc", InputSchema: map[string]any{"type": "object"}}},- })- if err != nil {- t.Fatalf("Chat failed: %v", err)- }- if len(resp.ToolCalls) != 1 || resp.ToolCalls[0].ID != "id1" {- t.Errorf("Expected 1 tool call with ID id1, got %+v", resp.ToolCalls)- }-}diff --git a/internal/ai/providers/anthropic_test.go b/internal/ai/providers/anthropic_test.goindex bf9f9772fd..c611768bb6 100644--- a/internal/ai/providers/anthropic_test.go+++ b/internal/ai/providers/anthropic_test.go@@ -528,6 +528,73 @@ func TestAnthropicClient_ChatStream_ToolUse(t *testing.T) {}}+func TestAnthropicClient_ChatStream_UsesSharedToolResultProjection(t *testing.T) {+ var got map[string]any+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if err := json.NewDecoder(r.Body).Decode(&got); err != nil {+ t.Fatalf("decode request: %v", err)+ }++ stream := []string{+ `{"type":"message_start","message":{"usage":{"input_tokens":2}}}`,+ `{"type":"content_block_delta","delta":{"type":"text_delta","text":"done"}}`,+ `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`,+ `{"type":"message_stop"}`,+ }+ w.Header().Set("Content-Type", "text/event-stream")+ w.WriteHeader(http.StatusOK)+ for _, event := range stream {+ _, _ = w.Write([]byte("data: " + event + "\n\n"))+ w.(http.Flusher).Flush()+ }+ }))+ defer server.Close()++ client := NewAnthropicClientWithBaseURL("test-key", "claude-3-5-sonnet", server.URL, 0)+ err := client.ChatStream(context.Background(), ChatRequest{+ Messages: []Message{+ {Role: "system", Content: "hidden"},+ {+ Role: "user",+ ToolResult: &ToolResult{+ ToolUseID: "tool_1",+ Content: `{"ok":true}`,+ IsError: true,+ },+ },+ },+ }, func(StreamEvent) {})+ if err != nil {+ t.Fatalf("ChatStream: %v", err)+ }++ msgs, ok := got["messages"].([]any)+ if !ok || len(msgs) != 1 {+ t.Fatalf("unexpected messages: %+v", got["messages"])+ }+ first, ok := msgs[0].(map[string]any)+ if !ok {+ t.Fatalf("unexpected message type: %T", msgs[0])+ }+ if first["role"] != "user" {+ t.Fatalf("role = %v, want user", first["role"])+ }+ contentArr, ok := first["content"].([]any)+ if !ok || len(contentArr) != 1 {+ t.Fatalf("unexpected content: %+v", first["content"])+ }+ block, ok := contentArr[0].(map[string]any)+ if !ok {+ t.Fatalf("unexpected content block type: %T", contentArr[0])+ }+ if block["type"] != "tool_result" || block["tool_use_id"] != "tool_1" || block["is_error"] != true {+ t.Fatalf("unexpected tool_result block: %+v", block)+ }+ if _, ok := block["content"].(string); !ok {+ t.Fatalf("expected tool_result content to be a string, got: %+v", block["content"])+ }+}+func TestAnthropicClient_ChatStream_ToolChoiceNone_DropsTools(t *testing.T) {server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {var got map[string]anydiff --git a/internal/ai/providers/factory.go b/internal/ai/providers/factory.goindex 6bbdf5e281..3f4a8cd9f9 100644--- a/internal/ai/providers/factory.go+++ b/internal/ai/providers/factory.go@@ -38,19 +38,11 @@ func NewForProvider(cfg *config.AIConfig, provider, model string) (Provider, errswitch provider {case config.AIProviderAnthropic:- // Check for OAuth first- if cfg.IsUsingOAuth() && cfg.OAuthAccessToken != "" {- return NewAnthropicOAuthClient(- cfg.OAuthAccessToken,- cfg.OAuthRefreshToken,- cfg.OAuthExpiresAt,- model,- timeout,- ), nil- }- // Then check for per-provider API keyapiKey := cfg.GetAPIKeyForProvider(config.AIProviderAnthropic)if apiKey == "" {+ if cfg.AuthMethod == config.AuthMethodOAuth && cfg.OAuthAccessToken != "" {+ return nil, fmt.Errorf("Anthropic OAuth subscription authentication is unsupported; configure an Anthropic API key")+ }return nil, fmt.Errorf("Anthropic API key not configured")}return NewAnthropicClient(apiKey, model, timeout), nildiff --git a/internal/ai/providers/factory_test.go b/internal/ai/providers/factory_test.goindex 0170f40b18..9e23d9e106 100644--- a/internal/ai/providers/factory_test.go+++ b/internal/ai/providers/factory_test.go@@ -1,6 +1,7 @@package providersimport (+ "strings""testing""github.com/rcourtman/pulse-go-rewrite/internal/config"@@ -221,7 +222,7 @@ func TestNewFromConfig_GeminiNoAPIKey(t *testing.T) {}}-func TestNewFromConfig_AnthropicOAuth(t *testing.T) {+func TestNewFromConfig_AnthropicOAuthUnsupported(t *testing.T) {cfg := &config.AIConfig{Enabled: true,Model: "anthropic:claude-3-5-sonnet-20241022",@@ -229,15 +230,12 @@ func TestNewFromConfig_AnthropicOAuth(t *testing.T) {OAuthAccessToken: "test-token",OAuthRefreshToken: "test-refresh",}- provider, err := NewFromConfig(cfg)- if err != nil {- t.Fatalf("Unexpected error: %v", err)- }- if provider == nil {- t.Fatal("Provider should not be nil")+ _, err := NewFromConfig(cfg)+ if err == nil {+ t.Fatal("expected unsupported OAuth error")}- if provider.Name() != "anthropic-oauth" {- t.Errorf("Expected provider name 'anthropic-oauth', got '%s'", provider.Name())+ if !strings.Contains(err.Error(), "OAuth subscription authentication is unsupported") {+ t.Fatalf("expected unsupported OAuth error, got %v", err)}}@@ -393,19 +391,19 @@ func TestNewForProvider_GeminiNoAPIKey(t *testing.T) {}}-func TestNewForProvider_AnthropicOAuth(t *testing.T) {+func TestNewForProvider_AnthropicOAuthUnsupported(t *testing.T) {cfg := &config.AIConfig{Enabled: true,AuthMethod: config.AuthMethodOAuth,OAuthAccessToken: "test-token",OAuthRefreshToken: "test-refresh",}- provider, err := NewForProvider(cfg, config.AIProviderAnthropic, "claude-3")- if err != nil {- t.Fatalf("Unexpected error: %v", err)+ _, err := NewForProvider(cfg, config.AIProviderAnthropic, "claude-3")+ if err == nil {+ t.Fatal("expected unsupported OAuth error")}- if provider.Name() != "anthropic-oauth" {- t.Errorf("Expected provider name 'anthropic-oauth', got '%s'", provider.Name())+ if !strings.Contains(err.Error(), "OAuth subscription authentication is unsupported") {+ t.Fatalf("expected unsupported OAuth error, got %v", err)}}diff --git a/internal/ai/providers/gemini.go b/internal/ai/providers/gemini.goindex 3c31bfe67b..3dc9922602 100644--- a/internal/ai/providers/gemini.go+++ b/internal/ai/providers/gemini.go@@ -267,45 +267,60 @@ func convertToolChoiceToGemini(tc *ToolChoice) string {return ""}-// Chat sends a chat request to the Gemini API-func (c *GeminiClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse, error) {- // Convert messages to Gemini format- contents := make([]geminiContent, 0, len(req.Messages))- for _, m := range req.Messages {- // Skip system messages - they go in systemInstruction+// convertMessagesToGemini converts provider-neutral messages into Gemini's+// content shape used by both non-streaming and streaming requests. Gemini+// requires function responses to reference function names rather than provider+// call ids, and consecutive tool results are grouped into one user content+// block after the model function calls.+func convertMessagesToGemini(reqMessages []Message) []geminiContent {+ contents := make([]geminiContent, 0, len(reqMessages))++ for i := 0; i < len(reqMessages); i++ {+ m := reqMessages[i]if m.Role == "system" {continue}- // Convert role names (Gemini uses "user" and "model")role := m.Roleif role == "assistant" {role = "model"}- // Handle tool resultsif m.ToolResult != nil {+ var assistantMsg *Message+ if i > 0 && reqMessages[i-1].Role == "assistant" {+ assistantMsg = &reqMessages[i-1]+ }+ resolveName := func(id string) string {+ if assistantMsg != nil {+ for _, call := range assistantMsg.ToolCalls {+ if call.ID == id {+ return call.Name+ }+ }+ }+ return id+ }++ parts := []geminiPart{geminiFunctionResponsePart(resolveName(m.ToolResult.ToolUseID), m.ToolResult.Content)}+ for i+1 < len(reqMessages) {+ next := reqMessages[i+1]+ if next.ToolResult == nil {+ break+ }+ parts = append(parts, geminiFunctionResponsePart(resolveName(next.ToolResult.ToolUseID), next.ToolResult.Content))+ i+++ }+contents = append(contents, geminiContent{- Role: "user",- Parts: []geminiPart{- {- FunctionResponse: &geminiFunctionResponse{- Name: m.ToolResult.ToolUseID, // In Gemini, this is the function name- Response: struct {- Content string `json:"content"`- }{- Content: m.ToolResult.Content,- },- },- },- },+ Role: "user",+ Parts: parts,})continue}- // Handle assistant messages with tool callsif m.Role == "assistant" && len(m.ToolCalls) > 0 {- parts := make([]geminiPart, 0)+ parts := make([]geminiPart, 0, len(m.ToolCalls)+1)if m.Content != "" {parts = append(parts, geminiPart{Text: m.Content})}@@ -325,12 +340,10 @@ func (c *GeminiClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponsecontinue}- // Skip messages with empty content - Gemini requires at least one of text, functionCall, or functionResponseif m.Content == "" {continue}- // Simple text messagecontents = append(contents, geminiContent{Role: role,Parts: []geminiPart{@@ -339,8 +352,19 @@ func (c *GeminiClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse})}- // Sanitize message ordering for Gemini's constraints- contents = sanitizeGeminiContents(contents)+ return sanitizeGeminiContents(contents)+}++func geminiFunctionResponsePart(name, content string) geminiPart {+ response := geminiFunctionResponse{Name: name}+ response.Response.Content = content+ return geminiPart{FunctionResponse: &response}+}++// Chat sends a chat request to the Gemini API+func (c *GeminiClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse, error) {+ // Convert messages to Gemini format+ contents := convertMessagesToGemini(req.Messages)// Use provided model or fall back to client defaultmodel := req.Model@@ -623,126 +647,7 @@ type geminiStreamEvent struct {// ChatStream sends a chat request and streams the response via callbackfunc (c *GeminiClient) ChatStream(ctx context.Context, req ChatRequest, callback StreamCallback) error {// Convert messages to Gemini format (same as Chat)- contents := make([]geminiContent, 0, len(req.Messages))-- for i := 0; i < len(req.Messages); i++ {- m := req.Messages[i]- if m.Role == "system" {- continue- }-- // Convert role names (Gemini uses "user" and "model")- role := m.Role- if role == "assistant" {- role = "model"- }-- // Handle tool results - merge consecutive tool results into one content block- if m.ToolResult != nil {- // Find the preceding assistant message to resolve function names- // Gemini requires the 'name' in FunctionResponse to match the function name, not the ID- var assistantMsg *Message- if i > 0 && req.Messages[i-1].Role == "assistant" {- assistantMsg = &req.Messages[i-1]- }-- // Helper to resolve name- resolveName := func(id string) string {- if assistantMsg != nil {- for _, call := range assistantMsg.ToolCalls {- if call.ID == id {- return call.Name- }- }- }- return id- }-- toolName := resolveName(m.ToolResult.ToolUseID)-- parts := []geminiPart{- {- FunctionResponse: &geminiFunctionResponse{- Name: toolName,- Response: struct {- Content string `json:"content"`- }{- Content: m.ToolResult.Content,- },- },- },- }-- // Look ahead for more tool results- for i+1 < len(req.Messages) {- next := req.Messages[i+1]- if next.ToolResult == nil {- break- }-- nextToolName := resolveName(next.ToolResult.ToolUseID)-- // Add next tool result to parts- parts = append(parts, geminiPart{- FunctionResponse: &geminiFunctionResponse{- Name: nextToolName,- Response: struct {- Content string `json:"content"`- }{- Content: next.ToolResult.Content,- },- },- })-- // Advance index- i++- }-- contents = append(contents, geminiContent{- Role: "user",- Parts: parts,- })- continue- }-- // Handle assistant messages with tool calls- if m.Role == "assistant" && len(m.ToolCalls) > 0 {- parts := make([]geminiPart, 0)- if m.Content != "" {- parts = append(parts, geminiPart{Text: m.Content})- }- for _, tc := range m.ToolCalls {- parts = append(parts, geminiPart{- FunctionCall: &geminiFunctionCall{- Name: tc.Name,- Args: tc.Input,- },- ThoughtSignature: tc.ThoughtSignature,- })- }- contents = append(contents, geminiContent{- Role: "model",- Parts: parts,- })- continue- }-- // Skip messages with empty content - Gemini requires at least one of text, functionCall, or functionResponse- if m.Content == "" {- continue- }-- // Simple text message- contents = append(contents, geminiContent{- Role: role,- Parts: []geminiPart{- {Text: m.Content},- },- })- }-- // Sanitize message ordering for Gemini's constraints- contents = sanitizeGeminiContents(contents)+ contents := convertMessagesToGemini(req.Messages)model := req.Modelif strings.HasPrefix(model, "gemini:") {diff --git a/internal/ai/providers/gemini_test.go b/internal/ai/providers/gemini_test.goindex ee7e37fbda..e84fae8857 100644--- a/internal/ai/providers/gemini_test.go+++ b/internal/ai/providers/gemini_test.go@@ -632,6 +632,52 @@ func TestGeminiClient_Chat_ToolResultsAndAssistantToolCalls(t *testing.T) {}}+func TestGeminiClient_Chat_ResolvesAndGroupsToolResults(t *testing.T) {+ var got geminiRequest+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _ = json.NewDecoder(r.Body).Decode(&got)+ _ = json.NewEncoder(w).Encode(geminiResponse{+ Candidates: []geminiCandidate{{Content: geminiContent{Parts: []geminiPart{{Text: "Ok"}}}, FinishReason: "STOP"}},+ })+ }))+ defer server.Close()++ client := NewGeminiClient("test-key", "gemini-pro", server.URL, 0)+ _, err := client.Chat(context.Background(), ChatRequest{+ Messages: []Message{+ {+ Role: "assistant",+ ToolCalls: []ToolCall{+ {ID: "call-time", Name: "get_time", Input: map[string]any{"tz": "UTC"}},+ {ID: "call-weather", Name: "get_weather", Input: map[string]any{"location": "NYC"}},+ },+ },+ {Role: "user", ToolResult: &ToolResult{ToolUseID: "call-time", Content: "{\"time\":\"00:00\"}"}},+ {Role: "user", ToolResult: &ToolResult{ToolUseID: "call-weather", Content: "{\"temp\":72}"}},+ },+ })+ if err != nil {+ t.Fatalf("Chat: %v", err)+ }++ if len(got.Contents) != 2 {+ t.Fatalf("contents length = %d, want grouped assistant call plus tool result response", len(got.Contents))+ }+ if got.Contents[0].Role != "model" || len(got.Contents[0].Parts) != 2 {+ t.Fatalf("expected model content with two function calls, got %+v", got.Contents[0])+ }+ resultParts := got.Contents[1].Parts+ if got.Contents[1].Role != "user" || len(resultParts) != 2 {+ t.Fatalf("expected one grouped user content with two function responses, got %+v", got.Contents[1])+ }+ if resultParts[0].FunctionResponse == nil || resultParts[0].FunctionResponse.Name != "get_time" {+ t.Fatalf("first function response = %+v, want get_time", resultParts[0].FunctionResponse)+ }+ if resultParts[1].FunctionResponse == nil || resultParts[1].FunctionResponse.Name != "get_weather" {+ t.Fatalf("second function response = %+v, want get_weather", resultParts[1].FunctionResponse)+ }+}+func TestGeminiClient_Chat_Retry(t *testing.T) {var count intserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {diff --git a/internal/ai/providers/openai.go b/internal/ai/providers/openai.goindex b224ad0ed4..fa69be1897 100644--- a/internal/ai/providers/openai.go+++ b/internal/ai/providers/openai.go@@ -12,6 +12,7 @@ import ("strings""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rs/zerolog/log")@@ -304,12 +305,12 @@ func convertToolChoiceToOpenAI(tc *ToolChoice) interface{} {return nil}-// Chat sends a chat request to the OpenAI API-func (c *OpenAIClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse, error) {- // Convert messages to OpenAI format+// convertMessagesToOpenAI converts provider-neutral messages into the+// OpenAI-compatible chat message shape used by both non-streaming and streaming+// requests.+func convertMessagesToOpenAI(req ChatRequest, includeReasoningContent bool) ([]openaiMessage, error) {messages := make([]openaiMessage, 0, len(req.Messages)+1)- // Add system message if providedif req.System != "" {messages = append(messages, openaiMessage{Role: "system",@@ -322,15 +323,12 @@ func (c *OpenAIClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponseRole: m.Role,}- // Handle tool calls in assistant messagesif len(m.ToolCalls) > 0 {- msg.Content = nil // Content is null when there are tool calls+ msg.Content = nilif m.Content != "" {msg.Content = m.Content}- // DeepSeek reasoning-backed models require the reasoning_content- // returned with a tool call to be passed back on the next turn.- if c.shouldSendReasoningContent() && m.ReasoningContent != "" {+ if includeReasoningContent && m.ReasoningContent != "" {msg.ReasoningContent = m.ReasoningContent}for _, tc := range m.ToolCalls {@@ -348,14 +346,12 @@ func (c *OpenAIClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse})}} else if m.ToolResult != nil {- // This is a tool result messagemsg.Role = "tool"msg.Content = m.ToolResult.Contentmsg.ToolCallID = m.ToolResult.ToolUseID} else {msg.Content = m.Content- // For assistant messages with reasoning content (DeepSeek)- if c.shouldSendReasoningContent() && m.ReasoningContent != "" {+ if includeReasoningContent && m.ReasoningContent != "" {msg.ReasoningContent = m.ReasoningContent}}@@ -363,6 +359,17 @@ func (c *OpenAIClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponsemessages = append(messages, msg)}+ return messages, nil+}++// Chat sends a chat request to the OpenAI API+func (c *OpenAIClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse, error) {+ // Convert messages to OpenAI format+ messages, err := convertMessagesToOpenAI(req, c.shouldSendReasoningContent())+ if err != nil {+ return nil, err+ }+// Use provided model or fall back to client defaultmodel := req.Model// Strip provider prefix if present - callers may pass the full "provider:model" string@@ -558,14 +565,10 @@ func (c *OpenAIClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponseif len(choice.Message.ToolCalls) > 0 {result.StopReason = "tool_use" // Normalize to match Anthropic's formatfor _, tc := range choice.Message.ToolCalls {- var input map[string]interface{}- if err := json.Unmarshal([]byte(tc.Function.Arguments), &input); err != nil {- input = map[string]interface{}{"raw": tc.Function.Arguments}- }result.ToolCalls = append(result.ToolCalls, ToolCall{ID: tc.ID,Name: tc.Function.Name,- Input: input,+ Input: agentcapabilities.ProviderToolInputOrRaw(tc.Function.Arguments),})}}@@ -754,10 +757,7 @@ func finalizeOpenAIStreamToolCalls(builders map[int]*openaiStreamToolCallBuildercontinue}- var input map[string]interface{}- if err := json.Unmarshal([]byte(builder.args.String()), &input); err != nil {- input = map[string]interface{}{"raw": builder.args.String()}- }+ input := agentcapabilities.ProviderToolInputOrRaw(builder.args.String())toolCalls = append(toolCalls, ToolCall{ID: builder.id,Name: builder.name,@@ -782,54 +782,9 @@ func normalizeOpenAIStreamStopReason(finishReason string, toolCalls []ToolCall)// ChatStream sends a chat request and streams the response via callbackfunc (c *OpenAIClient) ChatStream(ctx context.Context, req ChatRequest, callback StreamCallback) error {// Convert messages to OpenAI format (same as Chat)- messages := make([]openaiMessage, 0, len(req.Messages)+1)-- if req.System != "" {- messages = append(messages, openaiMessage{- Role: "system",- Content: req.System,- })- }-- for _, m := range req.Messages {- msg := openaiMessage{- Role: m.Role,- }-- if len(m.ToolCalls) > 0 {- msg.Content = nil- if m.Content != "" {- msg.Content = m.Content- }- if c.shouldSendReasoningContent() && m.ReasoningContent != "" {- msg.ReasoningContent = m.ReasoningContent- }- for _, tc := range m.ToolCalls {- argsJSON, err := json.Marshal(tc.Input)- if err != nil {- return fmt.Errorf("failed to marshal tool call input for %s: %w", tc.Name, err)- }- msg.ToolCalls = append(msg.ToolCalls, openaiToolCall{- ID: tc.ID,- Type: "function",- Function: openaiToolFunction{- Name: tc.Name,- Arguments: string(argsJSON),- },- })- }- } else if m.ToolResult != nil {- msg.Role = "tool"- msg.Content = m.ToolResult.Content- msg.ToolCallID = m.ToolResult.ToolUseID- } else {- msg.Content = m.Content- if c.shouldSendReasoningContent() && m.ReasoningContent != "" {- msg.ReasoningContent = m.ReasoningContent- }- }-- messages = append(messages, msg)+ messages, err := convertMessagesToOpenAI(req, c.shouldSendReasoningContent())+ if err != nil {+ return err}model := req.Model@@ -1078,7 +1033,7 @@ func (c *OpenAIClient) ChatStream(ctx context.Context, req ChatRequest, callback},})if rawArgs := builder.args.String(); rawArgs != "" {- parsedInput := parseStreamToolInput(rawArgs)+ parsedInput, _ := agentcapabilities.ParseProviderToolInput(rawArgs)callback(StreamEvent{Type: "tool_progress",Data: ToolProgressEvent{@@ -1096,7 +1051,7 @@ func (c *OpenAIClient) ChatStream(ctx context.Context, req ChatRequest, callbackbuilder.args.WriteString(tc.Function.Arguments)if builder.name != "" {rawArgs := builder.args.String()- parsedInput := parseStreamToolInput(rawArgs)+ parsedInput, _ := agentcapabilities.ParseProviderToolInput(rawArgs)message := "Receiving tool input."if parsedInput != nil {message = "Prepared tool input."diff --git a/internal/ai/providers/provider.go b/internal/ai/providers/provider.goindex 40d72f04d6..00ad6426f4 100644--- a/internal/ai/providers/provider.go+++ b/internal/ai/providers/provider.go@@ -3,8 +3,8 @@ package providersimport ("context"- "encoding/json"- "strings"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")// Message represents a chat message@@ -30,50 +30,25 @@ func (m Message) NormalizeCollections() Message {return m}-// ToolCall represents a tool invocation from the AI-type ToolCall struct {- ID string `json:"id"`- Name string `json:"name"`- Input map[string]interface{} `json:"input"`- ThoughtSignature json.RawMessage `json:"thought_signature,omitempty"`-}+// ToolCall represents a tool invocation from the AI. It aliases the shared+// Pulse Intelligence provider-call shape so Assistant execution projects+// model-selected calls through the same boundary as external agent adapters.+type ToolCall = agentcapabilities.ProviderToolCallfunc EmptyToolCall() ToolCall {- return ToolCall{}.NormalizeCollections()+ return agentcapabilities.EmptyProviderToolCall()}-func (t ToolCall) NormalizeCollections() ToolCall {- if t.Input == nil {- t.Input = map[string]interface{}{}- }- return t-}+// ToolResult represents the result of a tool execution.+type ToolResult = agentcapabilities.ProviderToolResult-// ToolResult represents the result of a tool execution-type ToolResult struct {- ToolUseID string `json:"tool_use_id"`- Content string `json:"content"`- IsError bool `json:"is_error,omitempty"`-}--// Tool represents an AI tool definition-type Tool struct {- Type string `json:"type,omitempty"` // "web_search_20250305" for web search, empty for regular tools- Name string `json:"name"`- Description string `json:"description,omitempty"`- InputSchema map[string]interface{} `json:"input_schema"`- MaxUses int `json:"max_uses,omitempty"` // For web search: limit searches per request-}+// Tool represents an AI tool definition. It aliases the shared Pulse+// Intelligence provider tool shape so Assistant provider clients project tools+// through the same schema boundary.+type Tool = agentcapabilities.ProviderToolfunc EmptyTool() Tool {- return Tool{}.NormalizeCollections()-}--func (t Tool) NormalizeCollections() Tool {- if t.InputSchema == nil {- t.InputSchema = map[string]interface{}{}- }- return t+ return agentcapabilities.EmptyProviderTool()}// ToolChoiceType represents how the model should choose tools@@ -213,17 +188,6 @@ func (e ToolProgressEvent) NormalizeCollections() ToolProgressEvent {return e}-func parseStreamToolInput(rawArgs string) map[string]interface{} {- if strings.TrimSpace(rawArgs) == "" {- return nil- }- var input map[string]interface{}- if err := json.Unmarshal([]byte(rawArgs), &input); err != nil {- return nil- }- return input-}-// ToolEndEvent is the data for "tool_end" stream eventstype ToolEndEvent struct {ID string `json:"id"`diff --git a/internal/ai/providers/provider_contract_test.go b/internal/ai/providers/provider_contract_test.goindex dae0bad7a5..54be576042 100644--- a/internal/ai/providers/provider_contract_test.go+++ b/internal/ai/providers/provider_contract_test.go@@ -2,8 +2,11 @@ package providersimport ("encoding/json"+ "os""strings""testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")func TestProviderContracts_UseCanonicalEmptyCollections(t *testing.T) {@@ -78,3 +81,214 @@ func TestProviderContracts_UseCanonicalEmptyCollections(t *testing.T) {t.Fatalf("expected empty provider tool to retain input_schema object, got %s", payload)}}++func TestProviderContracts_StreamToolInputParsingUsesSharedAgentCapabilities(t *testing.T) {+ for _, path := range []string{"openai.go", "anthropic.go"} {+ source, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read %s: %v", path, err)+ }+ text := string(source)+ for _, fragment := range []string{+ "agentcapabilities.ParseProviderToolInput(",+ "agentcapabilities.ProviderToolInputOrRaw(",+ } {+ if !strings.Contains(text, fragment) {+ t.Fatalf("%s must use shared provider tool input parsing; missing %s", path, fragment)+ }+ }+ for _, forbidden := range []string{+ `map[string]interface{}{"raw":`,+ `json.Unmarshal([]byte(currentToolInput.String())`,+ `json.Unmarshal([]byte(builder.args.String())`,+ } {+ if strings.Contains(text, forbidden) {+ t.Fatalf("%s must not own provider tool input fallback parsing; found %s", path, forbidden)+ }+ }+ }++ providerSource, err := os.ReadFile("provider.go")+ if err != nil {+ t.Fatalf("read provider.go: %v", err)+ }+ if strings.Contains(string(providerSource), "func parseStreamToolInput(") {+ t.Fatal("provider package must not keep a local streamed tool-input parser")+ }++ parsed, ok := agentcapabilities.ParseProviderToolInput(`{"host":"nas01"}`)+ if !ok || parsed["host"] != "nas01" {+ t.Fatalf("shared parser returned %#v, %v", parsed, ok)+ }+}++func TestProviderContracts_AnthropicStreamingUsesSharedMessageProjection(t *testing.T) {+ source, err := os.ReadFile("anthropic.go")+ if err != nil {+ t.Fatalf("read anthropic.go: %v", err)+ }+ text := string(source)++ if strings.Count(text, "convertMessagesToAnthropic(req.Messages)") != 2 {+ t.Fatal("Anthropic Chat and ChatStream must both use convertMessagesToAnthropic for provider message projection")+ }++ streamStart := strings.Index(text, "func (c *AnthropicClient) ChatStream(")+ if streamStart < 0 {+ t.Fatal("missing Anthropic ChatStream")+ }+ streamText := text[streamStart:]+ for _, forbidden := range []string{+ `json.Marshal(m.ToolResult.Content)`,+ `Type: "tool_result"`,+ `Type: "tool_use"`,+ `Content: m.Content`,+ } {+ if strings.Contains(streamText, forbidden) {+ t.Fatalf("Anthropic ChatStream must not duplicate provider message projection; found %s", forbidden)+ }+ }+}++func TestProviderContracts_OpenAIStreamingUsesSharedMessageProjection(t *testing.T) {+ source, err := os.ReadFile("openai.go")+ if err != nil {+ t.Fatalf("read openai.go: %v", err)+ }+ text := string(source)++ if strings.Count(text, "convertMessagesToOpenAI(req, c.shouldSendReasoningContent())") != 2 {+ t.Fatal("OpenAI Chat and ChatStream must both use convertMessagesToOpenAI for provider message projection")+ }++ streamStart := strings.Index(text, "func (c *OpenAIClient) ChatStream(")+ if streamStart < 0 {+ t.Fatal("missing OpenAI ChatStream")+ }+ streamText := text[streamStart:]+ modelStart := strings.Index(streamText, "model := req.Model")+ if modelStart < 0 {+ t.Fatal("missing OpenAI ChatStream model setup")+ }+ streamProjectionText := streamText[:modelStart]+ for _, forbidden := range []string{+ `json.Marshal(tc.Input)`,+ `m.ToolResult`,+ `m.ToolCalls`,+ `m.ReasoningContent`,+ `m.Content`,+ } {+ if strings.Contains(streamProjectionText, forbidden) {+ t.Fatalf("OpenAI ChatStream must not duplicate provider message projection; found %s", forbidden)+ }+ }+}++func TestProviderContracts_GeminiStreamingUsesSharedMessageProjection(t *testing.T) {+ source, err := os.ReadFile("gemini.go")+ if err != nil {+ t.Fatalf("read gemini.go: %v", err)+ }+ text := string(source)++ if strings.Count(text, "convertMessagesToGemini(req.Messages)") != 2 {+ t.Fatal("Gemini Chat and ChatStream must both use convertMessagesToGemini for provider message projection")+ }++ streamStart := strings.Index(text, "func (c *GeminiClient) ChatStream(")+ if streamStart < 0 {+ t.Fatal("missing Gemini ChatStream")+ }+ streamText := text[streamStart:]+ modelStart := strings.Index(streamText, "model := req.Model")+ if modelStart < 0 {+ t.Fatal("missing Gemini ChatStream model setup")+ }+ streamProjectionText := streamText[:modelStart]+ for _, forbidden := range []string{+ `m.ToolResult`,+ `m.ToolCalls`,+ `m.Content`,+ `FunctionResponse:`,+ `FunctionCall:`,+ } {+ if strings.Contains(streamProjectionText, forbidden) {+ t.Fatalf("Gemini ChatStream must not duplicate provider message projection; found %s", forbidden)+ }+ }+}++func TestProviderToolUsesSharedAgentCapabilitiesShape(t *testing.T) {+ var shared agentcapabilities.ProviderTool = Tool{+ Name: "diagnose",+ Description: "Diagnose infrastructure",+ InputSchema: map[string]interface{}{+ "type": "object",+ },+ }+ if shared.Name != "diagnose" {+ t.Fatalf("shared provider tool name = %q", shared.Name)+ }++ tool := Tool{Name: "diagnose"}.NormalizeCollections()+ if tool.InputSchema == nil {+ t.Fatal("provider tool alias must retain shared NormalizeCollections behavior")+ }+}++func TestProviderContracts_PulseProviderToolMetadataStaysOutOfUpstreamEncoders(t *testing.T) {+ for _, path := range []string{"openai.go", "anthropic.go", "gemini.go", "ollama.go"} {+ source, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read %s: %v", path, err)+ }+ text := string(source)+ for _, forbidden := range []string{+ "BehaviorHints",+ "PulseGovernance",+ "behavior_hints",+ "pulse_governance",+ } {+ if strings.Contains(text, forbidden) {+ t.Fatalf("%s must not forward Pulse-local provider tool metadata to upstream provider payloads; found %s", path, forbidden)+ }+ }+ }+}++func TestProviderToolCallAndResultUseSharedAgentCapabilitiesShape(t *testing.T) {+ var sharedCall agentcapabilities.ProviderToolCall = ToolCall{+ ID: "call-1",+ Name: "diagnose",+ Input: map[string]interface{}{"resource_id": "vm/100"},+ }+ if sharedCall.Name != "diagnose" {+ t.Fatalf("shared provider tool call name = %q", sharedCall.Name)+ }++ toolCall := ToolCall{Name: "diagnose"}.NormalizeCollections()+ if toolCall.Input == nil {+ t.Fatal("provider tool call alias must retain shared NormalizeCollections behavior")+ }++ input := map[string]interface{}{"resource_id": "vm/100"}+ toolCall = ToolCall{Name: "diagnose", Input: input}.NormalizeCollections()+ toolCall.Input["resource_id"] = "vm/101"+ if input["resource_id"] != "vm/100" {+ t.Fatalf("provider tool call alias must retain shared no-alias input normalization: source=%#v normalized=%#v", input, toolCall.Input)+ }++ emptyToolCall := EmptyToolCall()+ if emptyToolCall.Input == nil {+ t.Fatal("EmptyToolCall must return the shared initialized provider tool-call shape")+ }++ var sharedResult agentcapabilities.ProviderToolResult = ToolResult{+ ToolUseID: "call-1",+ Content: "done",+ IsError: true,+ }+ if sharedResult.ToolUseID != "call-1" {+ t.Fatalf("shared provider tool result id = %q", sharedResult.ToolUseID)+ }+}diff --git a/internal/ai/safety/sensitive_paths.go b/internal/ai/safety/sensitive_paths.goindex e7b022c3db..9054aca4f1 100644--- a/internal/ai/safety/sensitive_paths.go+++ b/internal/ai/safety/sensitive_paths.go@@ -50,9 +50,9 @@ func IsSensitivePath(path string) (bool, string) {}}- // Pulse AI encrypted configuration store.+ // Pulse encrypted AI provider configuration store.if strings.HasSuffix(lower, "/ai.enc") || strings.Contains(lower, "ai.enc") {- return true, "pulse ai encrypted config store"+ return true, "pulse encrypted AI provider config store"}// Common dotfiles that may include tokens.diff --git a/internal/ai/service.go b/internal/ai/service.goindex dd14e83ae9..c87aa047dc 100644--- a/internal/ai/service.go+++ b/internal/ai/service.go@@ -4,7 +4,6 @@ import ("context""crypto/sha256""encoding/hex"- "encoding/json""fmt""io""net"@@ -19,6 +18,7 @@ import ("time""github.com/google/uuid"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/ai/approval""github.com/rcourtman/pulse-go-rewrite/internal/ai/baseline"@@ -56,6 +56,40 @@ const (LicenseStateGracePeriod LicenseState = "grace_period")+const legacyServiceToolResultModelContextChars = 8000++func legacyServiceProviderToolResultContextOptions() agentcapabilities.ProviderToolResultContextOptions {+ return agentcapabilities.ProviderToolResultContextOptions{+ MaxModelContentChars: legacyServiceToolResultModelContextChars,+ }+}++func newLegacyServiceProviderToolResultContextProjection(toolUseID, content string, isError bool) agentcapabilities.ProviderToolResultContextProjection {+ projection := agentcapabilities.NewProviderToolResultContextProjection(toolUseID, content, isError, legacyServiceProviderToolResultContextOptions())+ logLegacyServiceProviderToolResultTruncation(projection.Truncation)+ return projection+}++func legacyAssistantCapabilityInputSchema(name string) map[string]interface{} {+ cap, ok := agentcapabilities.FindCapability(agentcapabilities.CanonicalManifest().Capabilities, name)+ if !ok {+ return agentcapabilities.ProviderInputSchema(agentcapabilities.InputSchema{})+ }+ return agentcapabilities.ProviderInputSchemaFromRaw(agentcapabilities.ToolInputSchema(cap))+}++func logLegacyServiceProviderToolResultTruncation(truncation agentcapabilities.ProviderToolResultTruncation) {+ if !truncation.Applied {+ return+ }++ log.Debug().+ Int("original_chars", truncation.OriginalChars).+ Int("truncated_to", truncation.MaxChars).+ Int("chars_cut", truncation.TruncatedChars).+ Msg("Truncated large tool result")+}+// LicenseChecker provides license feature checking for Pro featurestype LicenseChecker interface {HasFeature(feature string) bool@@ -126,30 +160,19 @@ func (m ChatMessage) NormalizeCollections() ChatMessage {return m}-// ChatToolCall represents a tool invocation in a chat message-type ChatToolCall struct {- ID string `json:"id"`- Name string `json:"name"`- Input map[string]interface{} `json:"input"`-}+// ChatToolCall represents a provider-facing tool invocation in an API-facing+// chat message. It aliases the shared Pulse Intelligence provider-call shape so+// API chat history and provider turns do not drift on tool-call JSON.+type ChatToolCall = agentcapabilities.ProviderToolCallfunc EmptyChatToolCall() ChatToolCall {- return ChatToolCall{}.NormalizeCollections()+ return agentcapabilities.EmptyProviderToolCall()}-func (t ChatToolCall) NormalizeCollections() ChatToolCall {- if t.Input == nil {- t.Input = map[string]interface{}{}- }- return t-}--// ChatToolResult represents the result of a tool invocation-type ChatToolResult struct {- ToolUseID string `json:"tool_use_id"`- Content string `json:"content"`- IsError bool `json:"is_error,omitempty"`-}+// ChatToolResult represents the result of a tool invocation. It aliases the+// shared Pulse Intelligence provider-result shape so API-facing chat messages+// and provider turns do not drift on tool result JSON.+type ChatToolResult = agentcapabilities.ProviderToolResult// PatrolExecuteRequest represents a patrol execution request via the chat servicetype PatrolExecuteRequest struct {@@ -988,7 +1011,7 @@ func (s *Service) patrolConfigFromAIConfig(cfg *config.AIConfig) PatrolConfig {patrolCfg := DefaultPatrolConfig()if cfg == nil {patrolCfg.Enabled = false- patrolCfg.RuntimeBlockedReason = "Pulse Assistant settings could not be loaded from persistence."+ patrolCfg.RuntimeBlockedReason = "Assistant & Patrol settings could not be loaded from persistence."patrolCfg.RuntimeBlockedCause = PatrolFailureCauseSettingsPersistencereturn patrolCfg}@@ -1080,7 +1103,7 @@ func (s *Service) StartPatrol(ctx context.Context) {return}- // Check license for safe remediation workflows (Pro only) - patrol itself is free with BYOK+ // Check license for Patrol fix actions (Pro only) - Patrol itself is free with BYOKif licenseChecker != nil && !licenseChecker.HasFeature(FeatureAIAutoFix) {log.Info().Msg("Patrol safe remediation requires Pulse Pro license - fixes will require manual approval")}@@ -1419,35 +1442,26 @@ func extractVMIDFromCommand(command string) (vmID int, requiresOwnerNode bool, freturn 0, false, false}-// formatApprovalNeededToolResult returns a structured tool result for commands that require approval.-// It is encoded as a marker + JSON so the LLM can reliably detect it.+// formatApprovalNeededToolResult returns a structured tool marker for commands+// that require approval. The shared marker vocabulary lives in+// agentcapabilities so Assistant and external-agent bridges cannot drift.func formatApprovalNeededToolResult(command, toolID, reason, approvalID string) string {- payload := map[string]interface{}{- "type": "approval_required",- "command": command,- "tool_id": toolID,- "reason": reason,- "how_to_approve": "Ask the user to click the approval button shown in the UI.",- "do_not_retry": true,- }- if strings.TrimSpace(approvalID) != "" {- payload["approval_id"] = strings.TrimSpace(approvalID)- }- b, err := json.Marshal(payload)- if err != nil {- // Fallback to a safe plain-text marker.- return fmt.Sprintf("APPROVAL_REQUIRED: %s", command)- }- return "APPROVAL_REQUIRED: " + string(b)+ return agentcapabilities.ApprovalRequiredToolMarker(+ command,+ toolID,+ reason,+ approvalID,+ "Ask the user to click the approval button shown in the UI.",+ )}func resolveRunCommandApprovalTarget(req ExecuteRequest, runOnHost bool, targetHost string) (targetType, targetID, targetName string) {normalizedTargetHost := strings.ToLower(strings.TrimSpace(targetHost))- targetType = strings.ToLower(strings.TrimSpace(req.TargetType))+ targetType = agentcapabilities.NormalizeActionTargetType(req.TargetType)targetID = strings.TrimSpace(req.TargetID)if runOnHost {- targetType = "agent"+ targetType = agentcapabilities.ActionTargetTypeAgentif normalizedTargetHost != "" {targetID = normalizedTargetHosttargetName = normalizedTargetHost@@ -1455,10 +1469,10 @@ func resolveRunCommandApprovalTarget(req ExecuteRequest, runOnHost bool, targetH}if targetType == "" {- targetType = "agent"+ targetType = agentcapabilities.ActionTargetTypeAgent}- if targetType == "agent" && targetID == "" {+ if targetType == agentcapabilities.ActionTargetTypeAgent && targetID == "" {if node, ok := req.Context["node"].(string); ok && node != "" {targetID = strings.ToLower(strings.TrimSpace(node))} else if node, ok := req.Context["hostname"].(string); ok && node != "" {@@ -1503,64 +1517,27 @@ func createRunCommandApprovalRecord(orgID, command, toolID string, req ExecuteRereturn approvalReq.ID}-// formatPolicyBlockedToolResult returns a structured tool result for commands blocked by policy.+// formatPolicyBlockedToolResult returns a structured tool marker for commands+// blocked by policy.func formatPolicyBlockedToolResult(command, reason string) string {- payload := map[string]interface{}{- "type": "policy_blocked",- "command": command,- "reason": reason,- "do_not_retry": true,- }- b, err := json.Marshal(payload)- if err != nil {- return fmt.Sprintf("POLICY_BLOCKED: %s", reason)- }- return "POLICY_BLOCKED: " + string(b)-}--func parseApprovalNeededMarker(content string) (ApprovalNeededData, bool) {- const prefix = "APPROVAL_REQUIRED:"- if !strings.HasPrefix(content, prefix) {- return ApprovalNeededData{}, false- }- trimmed := strings.TrimSpace(strings.TrimPrefix(content, prefix))- if trimmed == "" {- return ApprovalNeededData{}, false- }-- var payload struct {- Type string `json:"type"`- Command string `json:"command"`- ToolID string `json:"tool_id"`- Reason string `json:"reason"`- ApprovalID string `json:"approval_id"`- }- if err := json.Unmarshal([]byte(trimmed), &payload); err != nil {- return ApprovalNeededData{}, false- }- if payload.Type != "approval_required" || payload.Command == "" {- return ApprovalNeededData{}, false- }-- return ApprovalNeededData{- Command: payload.Command,- ToolID: payload.ToolID,- ApprovalID: strings.TrimSpace(payload.ApprovalID),- }, true+ return agentcapabilities.PolicyBlockedToolMarker(command, reason)}func approvalNeededFromToolCall(req ExecuteRequest, tc providers.ToolCall, result string) (ApprovalNeededData, bool) {- if !strings.HasPrefix(result, "APPROVAL_REQUIRED:") {+ if !agentcapabilities.HasApprovalRequiredToolMarker(result) {return ApprovalNeededData{}, false}- if tc.Name != "run_command" {+ if tc.Name != agentcapabilities.LegacyAssistantRunCommandToolName {return ApprovalNeededData{}, false}- parsed, parsedOK := parseApprovalNeededMarker(result)- cmd, _ := tc.Input["command"].(string)- runOnHost, _ := tc.Input["run_on_host"].(bool)- targetHost, _ := tc.Input["target_host"].(string)+ parsed, parsedOK := agentcapabilities.ParseApprovalRequiredToolMarkerData(result)+ if parsedOK && strings.TrimSpace(parsed.Command) == "" {+ parsedOK = false+ }+ cmd, _ := tc.Input[agentcapabilities.LegacyAssistantCommandArgumentName].(string)+ runOnHost, _ := tc.Input[agentcapabilities.LegacyAssistantRunOnHostArgumentName].(bool)+ targetHost, _ := tc.Input[agentcapabilities.LegacyAssistantTargetHostArgumentName].(string)if targetHost == "" {if node, ok := req.Context["node"].(string); ok && node != "" {@@ -1573,10 +1550,8 @@ func approvalNeededFromToolCall(req ExecuteRequest, tc providers.ToolCall, resul}if parsedOK {- if parsed.Command != "" {- cmd = parsed.Command- }- toolID := parsed.ToolID+ cmd = parsed.Command+ toolID := strings.TrimSpace(parsed.ToolID)if toolID == "" {toolID = tc.ID}@@ -1586,7 +1561,7 @@ func approvalNeededFromToolCall(req ExecuteRequest, tc providers.ToolCall, resulToolName: tc.Name,RunOnHost: runOnHost,TargetHost: targetHost,- ApprovalID: parsed.ApprovalID,+ ApprovalID: strings.TrimSpace(parsed.ApprovalID),}, true}@@ -1955,6 +1930,19 @@ type ExecuteRequest struct {RequireCommandApproval bool `json:"require_command_approval,omitempty"` // Force every run_command tool call through operator approval}+func assistantContextScopeForExecuteRequest(req ExecuteRequest) string {+ if strings.TrimSpace(req.FindingID) != "" {+ return "patrol_finding"+ }+ if strings.TrimSpace(req.TargetType) != "" || strings.TrimSpace(req.TargetID) != "" {+ return "resource_context"+ }+ if len(req.Context) > 0 {+ return "operator_context"+ }+ return ""+}+// ExecuteResponse represents the AI's responsetype ExecuteResponse struct {Content string `json:"content"`@@ -2182,6 +2170,7 @@ Always execute the commands rather than telling the user how to do it.`RequestModel: modelString,ResponseModel: resp.Model,UseCase: req.UseCase,+ ContextScope: assistantContextScopeForExecuteRequest(req),InputTokens: resp.InputTokens,OutputTokens: resp.OutputTokens,TargetType: req.TargetType,@@ -2220,13 +2209,10 @@ Always execute the commands rather than telling the user how to do it.`}// Add tool result to messages+ projection := newLegacyServiceProviderToolResultContextProjection(tc.ID, result, !execution.Success)messages = append(messages, providers.Message{- Role: "user",- ToolResult: &providers.ToolResult{- ToolUseID: tc.ID,- Content: result,- IsError: !execution.Success,- },+ Role: "user",+ ToolResult: &projection.Model,})}@@ -2421,6 +2407,7 @@ Always execute the commands rather than telling the user how to do it.`RequestModel: modelString,ResponseModel: resp.Model,UseCase: req.UseCase,+ ContextScope: assistantContextScopeForExecuteRequest(req),InputTokens: resp.InputTokens,OutputTokens: resp.OutputTokens,TargetType: req.TargetType,@@ -2485,10 +2472,10 @@ Always execute the commands rather than telling the user how to do it.`needsApproval := falseapprovalID := ""approvalReason := "Command requires user approval"- if tc.Name == "run_command" {- cmd, _ := tc.Input["command"].(string)- runOnHost, _ := tc.Input["run_on_host"].(bool)- targetHost, _ := tc.Input["target_host"].(string)+ if tc.Name == agentcapabilities.LegacyAssistantRunCommandToolName {+ cmd, _ := tc.Input[agentcapabilities.LegacyAssistantCommandArgumentName].(string)+ runOnHost, _ := tc.Input[agentcapabilities.LegacyAssistantRunOnHostArgumentName].(bool)+ targetHost, _ := tc.Input[agentcapabilities.LegacyAssistantTargetHostArgumentName].(string)s.mu.RLock()approvalOrgID := s.orgIDs.mu.RUnlock()@@ -2534,13 +2521,10 @@ Always execute the commands rather than telling the user how to do it.`Data: ToolEndData{Name: tc.Name, Input: toolInput, Output: result, Success: false},})+ projection := newLegacyServiceProviderToolResultContextProjection(tc.ID, result, true)messages = append(messages, providers.Message{- Role: "user",- ToolResult: &providers.ToolResult{- ToolUseID: tc.ID,- Content: result,- IsError: true,- },+ Role: "user",+ ToolResult: &projection.Model,})continue}@@ -2583,7 +2567,7 @@ Always execute the commands rather than telling the user how to do it.`// We'll break out of the loop after processing all tool calls// Note: We don't add to toolExecutions here because the approval_needed event// already tells the frontend to show the approval UI- cmd, _ := tc.Input["command"].(string)+ cmd, _ := tc.Input[agentcapabilities.LegacyAssistantCommandArgumentName].(string)result = formatApprovalNeededToolResult(cmd, tc.ID, approvalReason, approvalID)execution = ToolExecution{Name: tc.Name,@@ -2609,34 +2593,16 @@ Always execute the commands rather than telling the user how to do it.`// Log to remediation log for operational memory// Only log run_command since that's the main remediation action- if tc.Name == "run_command" {+ if tc.Name == agentcapabilities.LegacyAssistantRunCommandToolName {s.logRemediation(req, toolInput, result, execution.Success)}}- // Truncate large results to prevent context bloat- // Keep first and last parts for context- resultForContext := result- const maxResultSize = 8000 // ~8KB per tool result- if len(result) > maxResultSize {- halfSize := maxResultSize / 2- resultForContext = result[:halfSize] + "\n\n[... output truncated (" +- fmt.Sprintf("%d", len(result)-maxResultSize) + " bytes omitted) ...]\n\n" +- result[len(result)-halfSize:]- log.Debug().- Int("original_size", len(result)).- Int("truncated_size", len(resultForContext)).- Msg("Truncated large tool result")- }-// Add tool result to messages+ projection := newLegacyServiceProviderToolResultContextProjection(tc.ID, result, !execution.Success)messages = append(messages, providers.Message{- Role: "user",- ToolResult: &providers.ToolResult{- ToolUseID: tc.ID,- Content: resultForContext,- IsError: !execution.Success,- },+ Role: "user",+ ToolResult: &projection.Model,})}@@ -2671,18 +2637,18 @@ Always execute the commands rather than telling the user how to do it.`// getToolInputDisplay returns a human-readable display of tool inputfunc (s *Service) getToolInputDisplay(tc providers.ToolCall) string {switch tc.Name {- case "run_command":- cmd, _ := tc.Input["command"].(string)- if runOnHost, ok := tc.Input["run_on_host"].(bool); ok && runOnHost {+ case agentcapabilities.LegacyAssistantRunCommandToolName:+ cmd, _ := tc.Input[agentcapabilities.LegacyAssistantCommandArgumentName].(string)+ if runOnHost, ok := tc.Input[agentcapabilities.LegacyAssistantRunOnHostArgumentName].(bool); ok && runOnHost {return fmt.Sprintf("[host] %s", cmd)}return cmd- case "fetch_url":- fetchURL, _ := tc.Input["url"].(string)+ case agentcapabilities.LegacyAssistantFetchURLToolName:+ fetchURL, _ := tc.Input[agentcapabilities.LegacyAssistantURLArgumentName].(string)return fetchURL- case "set_resource_url":- resourceType, _ := tc.Input["resource_type"].(string)- resourceURL, _ := tc.Input["url"].(string)+ case agentcapabilities.LegacyAssistantSetResourceURLToolName:+ resourceType, _ := tc.Input[agentcapabilities.LegacyAssistantResourceTypeArgumentName].(string)+ resourceURL, _ := tc.Input[agentcapabilities.LegacyAssistantURLArgumentName].(string)return fmt.Sprintf("Set %s URL: %s", resourceType, resourceURL)default:return fmt.Sprintf("%v", tc.Input)@@ -2731,7 +2697,7 @@ func (s *Service) logRemediation(req ExecuteRequest, command, output string, suc}// Generate a meaningful summary from the command that describes what was achieved- // This is what gets displayed in the Pulse AI Impact section+ // This is what gets displayed in the Pulse Intelligence Impact sectionsummary := generateRemediationSummary(command, req.TargetType, req.Context)// Get resource name from context if available@@ -2761,7 +2727,7 @@ func (s *Service) logRemediation(req ExecuteRequest, command, output string, sucOutcome: outcome,Automatic: req.UseCase == "patrol", // Patrol runs are automatic}); err != nil {- log.Warn().Err(err).Str("resource_id", req.TargetID).Msg("Failed to log ACTION to Pulse AI Impact")+ log.Warn().Err(err).Str("resource_id", req.TargetID).Msg("Failed to log ACTION to Pulse Intelligence Impact")}log.Info().@@ -2770,7 +2736,7 @@ func (s *Service) logRemediation(req ExecuteRequest, command, output string, sucStr("command", command).Str("summary", summary).Bool("success", success).- Msg("Logged ACTION to Pulse AI Impact")+ Msg("Logged ACTION to Pulse Intelligence Impact")}// isActionableCommand returns true if the command performs an actual action@@ -2816,7 +2782,7 @@ func isActionableCommand(cmd string) bool {}// generateRemediationSummary creates a human-readable summary of what a command achieved-// This is used to display meaningful descriptions in the Pulse AI Impact section+// This is used to display meaningful descriptions in the Pulse Intelligence Impact sectionfunc generateRemediationSummary(command string, _ string, context map[string]interface{}) string {cmd := strings.TrimSpace(command)@@ -3061,108 +3027,19 @@ func (s *Service) hasAgentForTarget(req ExecuteRequest) bool {// getTools returns the available tools for AIfunc (s *Service) getTools() []providers.Tool {- tools := []providers.Tool{- {- Name: "run_command",- Description: "Execute a shell command. By default runs on the current target (container/VM), but set run_on_host=true for Proxmox host commands. IMPORTANT: For targets on different nodes, specify target_host to route to the correct PVE node.",- InputSchema: map[string]interface{}{- "type": "object",- "properties": map[string]interface{}{- "command": map[string]interface{}{- "type": "string",- "description": "The shell command to execute (e.g., 'ps aux --sort=-%mem | head -20')",- },- "run_on_host": map[string]interface{}{- "type": "boolean",- "description": "If true, run on the Proxmox/Docker host instead of inside the container/VM. Use for pct/qm commands like 'pct resize 101 rootfs +10G'. When true, you should also set target_host.",- },- "target_host": map[string]interface{}{- "type": "string",- "description": "Optional hostname of the specific host/node to run the command on. Use this to explicitly route pct/qm/docker commands to the correct host node or Docker host. Check the 'node' or 'Host Node' field in the target's context.",- },- },- "required": []string{"command"},- },- },- {- Name: "fetch_url",- Description: "Fetch content from a URL. Use this to check if web services are responding, read API endpoints, or fetch documentation. Works with local network URLs and public sites.",- InputSchema: map[string]interface{}{- "type": "object",- "properties": map[string]interface{}{- "url": map[string]interface{}{- "type": "string",- "description": "The URL to fetch (e.g., 'http://192.0.2.50:8080/api/health' or 'https://example.com/docs')",- },- },- "required": []string{"url"},- },- },- {- Name: "set_resource_url",- Description: "Set the web URL for a resource in Pulse after discovering a web service. Use this when you've found a web server running on a VM/container/host and want to save it for quick access. The URL will appear as a clickable link in the Pulse dashboard.",- InputSchema: map[string]interface{}{- "type": "object",- "properties": map[string]interface{}{- "resource_type": map[string]interface{}{- "type": "string",- "description": "Canonical v6 resource type: 'vm', 'system-container', 'oci-container', 'app-container', 'agent', 'node', or 'docker-host'",- "enum": []string{"vm", "system-container", "oci-container", "app-container", "agent", "node", "docker-host"},- },- "resource_id": map[string]interface{}{- "type": "string",- "description": "The resource ID from context. For VMs/LXC, use the canonical resource ID shown by Pulse (for example 'homelab:pve-node:150'). For app containers, use the container resource ID (for example 'hostid:container:containerid').",- },- "url": map[string]interface{}{- "type": "string",- "description": "The discovered URL (e.g., 'http://192.0.2.50:8096' for Jellyfin). Use an empty string to remove the URL.",- },- },- "required": []string{"resource_type", "resource_id"},- },- },- {- Name: "resolve_finding",+ tools := append([]providers.Tool{}, agentcapabilities.LegacyAssistantUtilityProviderTools()...)+ tools = append(tools,+ providers.Tool{+ Name: agentcapabilities.ResolveFindingCapabilityName,Description: "Mark an AI patrol finding as resolved after successfully fixing the issue. Use the finding ID shown in your Patrol Finding Context section. Call this after verifying the fix worked - do NOT ask the user for the finding ID.",- InputSchema: map[string]interface{}{- "type": "object",- "properties": map[string]interface{}{- "finding_id": map[string]interface{}{- "type": "string",- "description": "The finding ID from your context (shown in ## Patrol Finding Context section).",- },- "resolution_note": map[string]interface{}{- "type": "string",- "description": "Brief description of how the issue was resolved (e.g., 'Restarted nginx service', 'Cleaned up disk space').",- },- },- "required": []string{"finding_id", "resolution_note"},- },+ InputSchema: legacyAssistantCapabilityInputSchema(agentcapabilities.ResolveFindingCapabilityName),},- {- Name: "dismiss_finding",- Description: "Dismiss an AI patrol finding when it's not actually an issue or is expected behavior. Use this instead of resolve_finding when the finding is a false positive or the configuration is intentional. This creates a suppression rule to prevent similar findings from being raised again.",- InputSchema: map[string]interface{}{- "type": "object",- "properties": map[string]interface{}{- "finding_id": map[string]interface{}{- "type": "string",- "description": "The finding ID from your context (shown in ## Patrol Finding Context section).",- },- "reason": map[string]interface{}{- "type": "string",- "description": "Why the finding is being dismissed.",- "enum": []string{"not_an_issue", "expected_behavior", "will_fix_later"},- },- "note": map[string]interface{}{- "type": "string",- "description": "Explanation of why this is not an issue or is expected behavior (e.g., 'PBS storage restricted to specific nodes is intentional').",- },- },- "required": []string{"finding_id", "reason", "note"},- },+ providers.Tool{+ Name: agentcapabilities.DismissFindingCapabilityName,+ Description: "Dismiss an AI patrol finding when it's not actually an issue or is expected behavior. Use this instead of " + agentcapabilities.ResolveFindingCapabilityName + " when the finding is a false positive or the configuration is intentional. This creates a suppression rule to prevent similar findings from being raised again.",+ InputSchema: legacyAssistantCapabilityInputSchema(agentcapabilities.DismissFindingCapabilityName),},- }+ )// Add web search tool for Anthropic providerif s.provider != nil && s.provider.Name() == "anthropic" {@@ -3184,10 +3061,10 @@ func (s *Service) executeTool(ctx context.Context, req ExecuteRequest, tc provid}switch tc.Name {- case "run_command":- command, _ := tc.Input["command"].(string)- runOnHost, _ := tc.Input["run_on_host"].(bool)- targetHost, _ := tc.Input["target_host"].(string)+ case agentcapabilities.LegacyAssistantRunCommandToolName:+ command, _ := tc.Input[agentcapabilities.LegacyAssistantCommandArgumentName].(string)+ runOnHost, _ := tc.Input[agentcapabilities.LegacyAssistantRunOnHostArgumentName].(bool)+ targetHost, _ := tc.Input[agentcapabilities.LegacyAssistantTargetHostArgumentName].(string)execution.Input = commandif runOnHost && targetHost != "" {execution.Input = fmt.Sprintf("[%s] %s", targetHost, command)@@ -3315,8 +3192,8 @@ func (s *Service) executeTool(ctx context.Context, req ExecuteRequest, tc providexecution.Success = truereturn result, execution- case "fetch_url":- urlStr, _ := tc.Input["url"].(string)+ case agentcapabilities.LegacyAssistantFetchURLToolName:+ urlStr, _ := tc.Input[agentcapabilities.LegacyAssistantURLArgumentName].(string)execution.Input = urlStrif urlStr == "" {@@ -3335,10 +3212,10 @@ func (s *Service) executeTool(ctx context.Context, req ExecuteRequest, tc providexecution.Success = truereturn result, execution- case "set_resource_url":- resourceType, _ := tc.Input["resource_type"].(string)- resourceID, _ := tc.Input["resource_id"].(string)- resourceURL, _ := tc.Input["url"].(string)+ case agentcapabilities.LegacyAssistantSetResourceURLToolName:+ resourceType, _ := tc.Input[agentcapabilities.LegacyAssistantResourceTypeArgumentName].(string)+ resourceID, _ := tc.Input[agentcapabilities.LegacyAssistantResourceIDArgumentName].(string)+ resourceURL, _ := tc.Input[agentcapabilities.LegacyAssistantURLArgumentName].(string)execution.Input = fmt.Sprintf("%s %s -> %s", resourceType, resourceID, resourceURL)if resourceType == "" {@@ -3371,9 +3248,9 @@ func (s *Service) executeTool(ctx context.Context, req ExecuteRequest, tc providexecution.Success = truereturn execution.Output, execution- case "resolve_finding":- findingID, _ := tc.Input["finding_id"].(string)- resolutionNote, _ := tc.Input["resolution_note"].(string)+ case agentcapabilities.ResolveFindingCapabilityName:+ findingID, _ := tc.Input[agentcapabilities.FindingIDArgumentName].(string)+ resolutionNote, _ := tc.Input[agentcapabilities.ResolutionNoteArgumentName].(string)execution.Input = fmt.Sprintf("finding: %s, note: %s", findingID, resolutionNote)// If no finding ID provided by AI, check the request context@@ -3386,11 +3263,6 @@ func (s *Service) executeTool(ctx context.Context, req ExecuteRequest, tc providreturn execution.Output, execution}- if resolutionNote == "" {- execution.Output = "Error: resolution_note is required. Please describe how the issue was resolved."- return execution.Output, execution- }-// Get the patrol service to resolve the findings.mu.RLock()patrolService := s.patrolService@@ -3408,14 +3280,17 @@ func (s *Service) executeTool(ctx context.Context, req ExecuteRequest, tc providreturn execution.Output, execution}- execution.Output = fmt.Sprintf("Finding resolved! The Patrol finding has been marked as fixed.\nID: %s\nResolution: %s", findingID, resolutionNote)+ execution.Output = fmt.Sprintf("Finding resolved! The Patrol finding has been marked as fixed.\nID: %s", findingID)+ if resolutionNote != "" {+ execution.Output += fmt.Sprintf("\nResolution: %s", resolutionNote)+ }execution.Success = truereturn execution.Output, execution- case "dismiss_finding":- findingID, _ := tc.Input["finding_id"].(string)- reason, _ := tc.Input["reason"].(string)- note, _ := tc.Input["note"].(string)+ case agentcapabilities.DismissFindingCapabilityName:+ findingID, _ := tc.Input[agentcapabilities.FindingIDArgumentName].(string)+ reason, _ := tc.Input[agentcapabilities.ReasonArgumentName].(string)+ note, _ := tc.Input[agentcapabilities.NoteArgumentName].(string)execution.Input = fmt.Sprintf("finding: %s, reason: %s, note: %s", findingID, reason, note)// If no finding ID provided by AI, check the request context@@ -3435,11 +3310,6 @@ func (s *Service) executeTool(ctx context.Context, req ExecuteRequest, tc providreturn execution.Output, execution}- if note == "" {- execution.Output = "Error: note is required. Please explain why this finding is being dismissed."- return execution.Output, execution- }-// Get the patrol service to dismiss the findings.mu.RLock()patrolService := s.patrolService@@ -3826,21 +3696,17 @@ func hasExplicitHostRoutingContext(ctx map[string]interface{}) bool {}func normalizeExecuteTargetType(raw, targetID string, ctx map[string]interface{}) (string, error) {- targetType := strings.ToLower(strings.TrimSpace(raw))+ targetType := agentcapabilities.NormalizeActionTargetType(raw)switch targetType {- case "agent":- return "agent", nil- case "system-container":- return "system-container", nil- case "vm":- return "vm", nil+ case agentcapabilities.ActionTargetTypeAgent, agentcapabilities.ActionTargetTypeSystemContainer, agentcapabilities.ActionTargetTypeVM:+ return targetType, nilcase "":if strings.TrimSpace(targetID) == "" && hasExplicitHostRoutingContext(ctx) {- return "agent", nil+ return agentcapabilities.ActionTargetTypeAgent, nil}return "", fmt.Errorf("target_type is required (agent, system-container, or vm)")default:- return "", fmt.Errorf("unsupported target_type %q (allowed: agent, system-container, vm)", raw)+ return "", fmt.Errorf("unsupported target_type %q (allowed: %s)", raw, agentcapabilities.ActionTargetTypeAllowedDescription())}}@@ -4017,7 +3883,7 @@ func (s *Service) RunCommand(ctx context.Context, req RunCommandRequest) (*RunCo// If running on host, override target typeif req.RunOnHost {- execReq.TargetType = "agent"+ execReq.TargetType = agentcapabilities.ActionTargetTypeAgent// Keep the original target info for routing}@@ -4197,10 +4063,12 @@ Latest version: https://api.github.com/repos/rcourtman/Pulse/releases/latest`, cprompt += fmt.Sprintf("\n\n## Patrol Finding Context\n"+"You are helping with patrol finding **%s**.\n\n"+"Lifecycle tools are available when current evidence supports them:\n"+- "- `resolve_finding` records that the underlying issue has actually been fixed.\n"+- "- `dismiss_finding` records a false positive or expected behavior.\n"++ "- `%s` records that the underlying issue has actually been fixed.\n"++ "- `%s` records a false positive or expected behavior.\n"+"Only call a lifecycle tool when that is the model's conclusion from the current evidence.\n",- req.FindingID)+ req.FindingID,+ agentcapabilities.ResolveFindingCapabilityName,+ agentcapabilities.DismissFindingCapabilityName)}// Add any provided context in a structured waydiff --git a/internal/ai/service_extended_test.go b/internal/ai/service_extended_test.goindex 72c1f3a256..54c1767cb7 100644--- a/internal/ai/service_extended_test.go+++ b/internal/ai/service_extended_test.go@@ -10,6 +10,7 @@ import ("testing""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/ai/cost""github.com/rcourtman/pulse-go-rewrite/internal/ai/knowledge"@@ -46,9 +47,9 @@ func TestService_GetToolInputDisplay(t *testing.T) {{name: "run_command",tc: providers.ToolCall{- Name: "run_command",+ Name: agentcapabilities.LegacyAssistantRunCommandToolName,Input: map[string]interface{}{- "command": "uptime",+ agentcapabilities.LegacyAssistantCommandArgumentName: "uptime",},},expected: "uptime",@@ -56,10 +57,10 @@ func TestService_GetToolInputDisplay(t *testing.T) {{name: "run_command on host",tc: providers.ToolCall{- Name: "run_command",+ Name: agentcapabilities.LegacyAssistantRunCommandToolName,Input: map[string]interface{}{- "command": "uptime",- "run_on_host": true,+ agentcapabilities.LegacyAssistantCommandArgumentName: "uptime",+ agentcapabilities.LegacyAssistantRunOnHostArgumentName: true,},},expected: "[host] uptime",@@ -67,9 +68,9 @@ func TestService_GetToolInputDisplay(t *testing.T) {{name: "fetch_url",tc: providers.ToolCall{- Name: "fetch_url",+ Name: agentcapabilities.LegacyAssistantFetchURLToolName,Input: map[string]interface{}{- "url": "https://google.com",+ agentcapabilities.LegacyAssistantURLArgumentName: "https://google.com",},},expected: "https://google.com",@@ -77,10 +78,10 @@ func TestService_GetToolInputDisplay(t *testing.T) {{name: "set_resource_url",tc: providers.ToolCall{- Name: "set_resource_url",+ Name: agentcapabilities.LegacyAssistantSetResourceURLToolName,Input: map[string]interface{}{- "resource_type": "vm",- "url": "http://1.2.3.4",+ agentcapabilities.LegacyAssistantResourceTypeArgumentName: "vm",+ agentcapabilities.LegacyAssistantURLArgumentName: "http://1.2.3.4",},},expected: "Set vm URL: http://1.2.3.4",@@ -119,7 +120,7 @@ func TestService_GetTools(t *testing.T) {// Verify some common tools are presentfoundRunCommand := falsefor _, tool := range tools {- if tool.Name == "run_command" {+ if tool.Name == agentcapabilities.LegacyAssistantRunCommandToolName {foundRunCommand = truebreak}@@ -129,6 +130,113 @@ func TestService_GetTools(t *testing.T) {}}+func TestService_GetToolsUsesSharedLegacyUtilitySchemas(t *testing.T) {+ svc := NewService(nil, nil)+ tools := svc.getTools()+ byName := map[string]providers.Tool{}+ for _, tool := range tools {+ byName[tool.Name] = tool+ }++ for _, shared := range agentcapabilities.LegacyAssistantUtilityProviderTools() {+ assistantTool, ok := byName[shared.Name]+ if !ok {+ t.Fatalf("legacy Assistant tools missing %s", shared.Name)+ }+ if !providerSchemaRequiredEqual(assistantTool.InputSchema, shared.InputSchema) {+ t.Fatalf("%s Assistant provider schema required = %#v, want shared required %#v",+ shared.Name, assistantTool.InputSchema["required"], shared.InputSchema["required"])+ }+ gotProps, ok := assistantTool.InputSchema["properties"].(map[string]interface{})+ if !ok {+ t.Fatalf("%s Assistant provider schema properties = %T, want map", shared.Name, assistantTool.InputSchema["properties"])+ }+ wantProps, ok := shared.InputSchema["properties"].(map[string]interface{})+ if !ok {+ t.Fatalf("%s shared provider schema properties = %T, want map", shared.Name, shared.InputSchema["properties"])+ }+ for field := range wantProps {+ if _, ok := gotProps[field]; !ok {+ t.Fatalf("%s Assistant provider schema missing shared field %q: %#v", shared.Name, field, gotProps)+ }+ }+ }+}++func TestService_GetToolsUsesManifestFindingLifecycleSchemas(t *testing.T) {+ svc := NewService(nil, nil)+ tools := svc.getTools()+ byName := map[string]providers.Tool{}+ for _, tool := range tools {+ byName[tool.Name] = tool+ }++ for _, name := range []string{+ agentcapabilities.ResolveFindingCapabilityName,+ agentcapabilities.DismissFindingCapabilityName,+ } {+ assistantTool, ok := byName[name]+ if !ok {+ t.Fatalf("legacy Assistant tools missing %s", name)+ }+ capability, ok := agentcapabilities.FindCapability(agentcapabilities.CanonicalManifest().Capabilities, name)+ if !ok {+ t.Fatalf("canonical manifest missing %s", name)+ }+ manifestSchema := agentcapabilities.ProviderInputSchemaFromRaw(agentcapabilities.ToolInputSchema(capability))+ if !providerSchemaRequiredEqual(assistantTool.InputSchema, manifestSchema) {+ t.Fatalf("%s Assistant provider schema required = %#v, want manifest required %#v",+ name, assistantTool.InputSchema["required"], manifestSchema["required"])+ }+ }+ if providerSchemaRequiredContains(byName[agentcapabilities.ResolveFindingCapabilityName].InputSchema, agentcapabilities.ResolutionNoteArgumentName) {+ t.Fatalf("%s must not require optional %s", agentcapabilities.ResolveFindingCapabilityName, agentcapabilities.ResolutionNoteArgumentName)+ }+ if providerSchemaRequiredContains(byName[agentcapabilities.DismissFindingCapabilityName].InputSchema, agentcapabilities.NoteArgumentName) {+ t.Fatalf("%s must not require optional note", agentcapabilities.DismissFindingCapabilityName)+ }+}++func providerSchemaRequiredEqual(got map[string]interface{}, want map[string]interface{}) bool {+ gotRequired := providerSchemaRequiredValues(got)+ wantRequired := providerSchemaRequiredValues(want)+ if len(gotRequired) != len(wantRequired) {+ return false+ }+ for i := range gotRequired {+ if gotRequired[i] != wantRequired[i] {+ return false+ }+ }+ return true+}++func providerSchemaRequiredContains(schema map[string]interface{}, want string) bool {+ for _, value := range providerSchemaRequiredValues(schema) {+ if value == want {+ return true+ }+ }+ return false+}++func providerSchemaRequiredValues(schema map[string]interface{}) []string {+ switch required := schema["required"].(type) {+ case []string:+ return append([]string(nil), required...)+ case []interface{}:+ values := make([]string, 0, len(required))+ for _, value := range required {+ if text, ok := value.(string); ok {+ values = append(values, text)+ }+ }+ return values+ default:+ return nil+ }+}+func TestService_AcquireExecutionSlot_Blocked(t *testing.T) {svc := NewService(nil, nil)@@ -456,7 +564,7 @@ func TestApprovalNeededFromToolCall(t *testing.T) {"command": "uptime",},}- result := "APPROVAL_REQUIRED:{\"command\":\"uptime\",\"tool_id\":\"call-1\"}"+ result := formatApprovalNeededToolResult("uptime", "tool-1", "needs approval", "approval-1")data, needed := approvalNeededFromToolCall(req, tc, result)if !needed {@@ -465,6 +573,12 @@ func TestApprovalNeededFromToolCall(t *testing.T) {if data.Command != "uptime" || data.TargetHost != "node-1" {t.Errorf("Unexpected data: %+v", data)}+ if data.ToolID != "tool-1" {+ t.Errorf("Expected parsed tool id, got %q", data.ToolID)+ }+ if data.ApprovalID != "approval-1" {+ t.Errorf("Expected parsed approval id, got %q", data.ApprovalID)+ }// Not a run_commandtc.Name = "fetch_url"@@ -1035,10 +1149,10 @@ func TestService_ExecuteTool_ResolveFinding(t *testing.T) {// 1. Successful resolutiontc := providers.ToolCall{- Name: "resolve_finding",+ Name: agentcapabilities.ResolveFindingCapabilityName,Input: map[string]interface{}{- "finding_id": "test-finding-1",- "resolution_note": "Restarted the service",+ agentcapabilities.FindingIDArgumentName: "test-finding-1",+ agentcapabilities.ResolutionNoteArgumentName: "Restarted the service",},}@@ -1053,9 +1167,9 @@ func TestService_ExecuteTool_ResolveFinding(t *testing.T) {// 2. Missing finding_id (should use from request context)req2 := ExecuteRequest{FindingID: "test-finding-1"}tc2 := providers.ToolCall{- Name: "resolve_finding",+ Name: agentcapabilities.ResolveFindingCapabilityName,Input: map[string]interface{}{- "resolution_note": "Fixed it",+ agentcapabilities.ResolutionNoteArgumentName: "Fixed it",},}_, exec2 := svc.executeTool(ctx, req2, tc2)@@ -1064,24 +1178,32 @@ func TestService_ExecuteTool_ResolveFinding(t *testing.T) {t.Error("Expected failure for already resolved finding")}- // 3. Missing resolution_note+ // 3. Missing resolution_note is allowed by the shared Pulse Intelligence manifest+ findingWithoutNote := &Finding{+ ID: "new-finding",+ Severity: FindingSeverityWarning,+ ResourceID: "vm-101",+ ResourceName: "test-vm-2",+ Title: "Recovered CPU",+ }+ patrol.GetFindings().Add(findingWithoutNote)tc3 := providers.ToolCall{- Name: "resolve_finding",+ Name: agentcapabilities.ResolveFindingCapabilityName,Input: map[string]interface{}{- "finding_id": "new-finding",+ agentcapabilities.FindingIDArgumentName: "new-finding",},}result3, exec3 := svc.executeTool(ctx, ExecuteRequest{}, tc3)- if exec3.Success {- t.Error("Expected failure for missing resolution_note")+ if !exec3.Success {+ t.Errorf("Expected success without resolution_note, got failure: %s", result3)}- if !strings.Contains(result3, "resolution_note is required") {- t.Errorf("Expected resolution_note error, got: %s", result3)+ if strings.Contains(result3, "resolution_note is required") {+ t.Errorf("Unexpected resolution_note error: %s", result3)}// 4. Missing bothtc4 := providers.ToolCall{- Name: "resolve_finding",+ Name: agentcapabilities.ResolveFindingCapabilityName,Input: map[string]interface{}{},}result4, exec4 := svc.executeTool(ctx, ExecuteRequest{}, tc4)@@ -1508,6 +1630,29 @@ func TestService_ExecuteOnAgent_RejectsLegacyContainerTargetTypeAlias(t *testing}}+func TestService_NormalizeExecuteTargetTypeUsesSharedActionTargetVocabulary(t *testing.T) {+ valid, err := normalizeExecuteTargetType(" SYSTEM-CONTAINER ", "101", nil)+ if err != nil {+ t.Fatalf("normalizeExecuteTargetType returned error: %v", err)+ }+ if valid != agentcapabilities.ActionTargetTypeSystemContainer {+ t.Fatalf("normalizeExecuteTargetType returned %q, want %q", valid, agentcapabilities.ActionTargetTypeSystemContainer)+ }++ hostRouted, err := normalizeExecuteTargetType("", "", map[string]interface{}{"node": "pve-a"})+ if err != nil {+ t.Fatalf("normalizeExecuteTargetType with host routing returned error: %v", err)+ }+ if hostRouted != agentcapabilities.ActionTargetTypeAgent {+ t.Fatalf("normalizeExecuteTargetType host-routed target = %q, want %q", hostRouted, agentcapabilities.ActionTargetTypeAgent)+ }++ _, err = normalizeExecuteTargetType("container", "101", nil)+ if err == nil || !strings.Contains(err.Error(), agentcapabilities.ActionTargetTypeAllowedDescription()) {+ t.Fatalf("expected shared allowed-target description in error, got %v", err)+ }+}+func TestService_ExecuteOnAgent_AcceptsSystemContainerTargetType(t *testing.T) {mockAgent := agentexec.ConnectedAgent{AgentID: "agent-1",@@ -2040,8 +2185,8 @@ func TestService_ExecuteStream_ResultTruncation(t *testing.T) {// Check if the previous tool result was truncated in the request messagesfor _, msg := range req.Messages {if msg.Role == "user" && msg.ToolResult != nil {- // Use a more flexible check as the exact string might vary- if strings.Contains(msg.ToolResult.Content, "omitted") || strings.Contains(msg.ToolResult.Content, "truncated") {+ if strings.Contains(msg.ToolResult.Content, "[TRUNCATED: 4000 characters cut.") &&+ !strings.Contains(msg.ToolResult.Content, "bytes omitted") {return &providers.ChatResponse{Content: "Verified truncation", StopReason: "end_turn"}, nil}}diff --git a/internal/ai/service_test.go b/internal/ai/service_test.goindex 7aaba3d9ed..ac044c2332 100644--- a/internal/ai/service_test.go+++ b/internal/ai/service_test.go@@ -9,6 +9,7 @@ import ("testing""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/ai/providers""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/models"@@ -159,6 +160,24 @@ func TestChatMessage_UsesCanonicalEmptyCollections(t *testing.T) {t.Fatalf("expected empty chat tool call to retain input object, got %s", payload)}+ sharedCall := ChatToolCall{+ ID: "call-1",+ Name: "diagnose",+ ThoughtSignature: json.RawMessage(`{"provider":"gemini"}`),+ }+ var sharedProviderCall agentcapabilities.ProviderToolCall = sharedCall.NormalizeCollections()+ if sharedProviderCall.ID != "call-1" || sharedProviderCall.Input == nil {+ t.Fatalf("shared chat tool call = %+v", sharedProviderCall)+ }++ payload, err = json.Marshal(sharedCall.NormalizeCollections())+ if err != nil {+ t.Fatalf("marshal shared chat tool call: %v", err)+ }+ if string(payload) != `{"id":"call-1","name":"diagnose","input":{},"thought_signature":{"provider":"gemini"}}` {+ t.Fatalf("shared chat tool call JSON = %s", payload)+ }+payload, err = json.Marshal(ChatMessage{ToolCalls: []ChatToolCall{{ID: "call-1",@@ -171,6 +190,27 @@ func TestChatMessage_UsesCanonicalEmptyCollections(t *testing.T) {if !strings.Contains(string(payload), `"input":{}`) {t.Fatalf("expected normalized chat message tool call to retain input object, got %s", payload)}++ var shared agentcapabilities.ProviderToolResult = ChatToolResult{+ ToolUseID: "call-1",+ Content: "done",+ IsError: true,+ }+ if shared.ToolUseID != "call-1" {+ t.Fatalf("shared chat tool result id = %q", shared.ToolUseID)+ }++ payload, err = json.Marshal(ChatToolResult{+ ToolUseID: "call-1",+ Content: "done",+ IsError: true,+ })+ if err != nil {+ t.Fatalf("marshal chat tool result: %v", err)+ }+ if string(payload) != `{"tool_use_id":"call-1","content":"done","is_error":true}` {+ t.Fatalf("chat tool result JSON = %s", payload)+ }}func TestService_SetStateProvider(t *testing.T) {@@ -609,14 +649,19 @@ func TestFormatApprovalNeededToolResult(t *testing.T) {t.Error("Expected non-empty result")}- // Should contain APPROVAL_REQUIRED prefix- if !hasPrefix(result, "APPROVAL_REQUIRED:") {- t.Error("Expected APPROVAL_REQUIRED prefix")+ if !agentcapabilities.HasApprovalRequiredToolMarker(result) {+ t.Error("Expected shared APPROVAL_REQUIRED marker")}- // Should contain the command- if !containsString(result, "rm -rf /") {- t.Error("Expected result to contain command")+ payload, ok := agentcapabilities.ParseApprovalRequiredToolMarkerPayload(result)+ if !ok {+ t.Fatalf("Expected shared approval marker payload, got %s", result)+ }+ if payload["command"] != "rm -rf /" {+ t.Errorf("Expected result to contain command, got %#v", payload)+ }+ if payload["type"] != agentcapabilities.ToolMarkerApprovalRequiredType {+ t.Errorf("Expected shared approval marker type, got %#v", payload["type"])}}@@ -627,45 +672,70 @@ func TestFormatPolicyBlockedToolResult(t *testing.T) {t.Error("Expected non-empty result")}- // Should contain POLICY_BLOCKED prefix- if !hasPrefix(result, "POLICY_BLOCKED:") {- t.Error("Expected POLICY_BLOCKED prefix")+ if !agentcapabilities.HasPolicyBlockedToolMarker(result) {+ t.Error("Expected shared POLICY_BLOCKED marker")}-}-func TestParseApprovalNeededMarker(t *testing.T) {- // Valid approval needed response- validResult := formatApprovalNeededToolResult("rm -rf /", "tool-123", "test", "approval-1")- data, found := parseApprovalNeededMarker(validResult)- if !found {- t.Error("Expected to parse approval needed marker")- }- if data.Command != "rm -rf /" {- t.Errorf("Expected command 'rm -rf /', got '%s'", data.Command)+ payload, ok := agentcapabilities.ParsePolicyBlockedToolMarkerPayload(result)+ if !ok {+ t.Fatalf("Expected shared policy marker payload, got %s", result)}- if data.ToolID != "tool-123" {- t.Errorf("Expected tool ID 'tool-123', got '%s'", data.ToolID)+ if payload["reason"] != "Command not allowed by policy" {+ t.Errorf("Expected result to contain policy reason, got %#v", payload)}- if data.ApprovalID != "approval-1" {- t.Errorf("Expected approval ID 'approval-1', got '%s'", data.ApprovalID)+ if payload["type"] != agentcapabilities.ToolMarkerPolicyBlockedType {+ t.Errorf("Expected shared policy marker type, got %#v", payload["type"])}+}- // Invalid input- _, found = parseApprovalNeededMarker("not an approval marker")- if found {- t.Error("Expected not found for invalid input")+func TestServiceUsesSharedProviderToolResultConstruction(t *testing.T) {+ src, err := os.ReadFile("service.go")+ if err != nil {+ t.Fatalf("read service.go: %v", err)+ }+ text := string(src)++ for _, fragment := range []string{+ "projection := newLegacyServiceProviderToolResultContextProjection(tc.ID, result, !execution.Success)",+ "projection := newLegacyServiceProviderToolResultContextProjection(tc.ID, result, true)",+ "agentcapabilities.NewProviderToolResultContextProjection(toolUseID, content, isError, legacyServiceProviderToolResultContextOptions())",+ "ToolResult: &projection.Model",+ "agentcapabilities.ParseApprovalRequiredToolMarkerData(result)",+ } {+ if !strings.Contains(text, fragment) {+ t.Fatalf("service tool loop must use shared provider tool-result construction; missing %s", fragment)+ }}-- // Empty input- _, found = parseApprovalNeededMarker("")- if found {- t.Error("Expected not found for empty input")+ for _, forbidden := range []string{+ "ToolResult: &providers.ToolResult{",+ "resultForContext",+ "maxResultSize",+ "output truncated (",+ } {+ if strings.Contains(text, forbidden) {+ t.Fatalf("service tool loop must not assemble or truncate provider tool-result context locally; found %s", forbidden)+ }+ }+ if strings.Contains(text, "func parseApprovalNeededMarker(") {+ t.Fatalf("service approval marker handling must call the shared parser directly, not wrap it locally")}+}++func TestLegacyServiceProviderToolResultContextProjectionUsesSharedTruncation(t *testing.T) {+ content := strings.Repeat("x", legacyServiceToolResultModelContextChars+12)+ projection := newLegacyServiceProviderToolResultContextProjection("call-1", content, false)- // Only prefix without JSON- _, found = parseApprovalNeededMarker("APPROVAL_REQUIRED:")- if found {- t.Error("Expected not found for prefix without JSON")+ if projection.Transcript.ToolUseID != "call-1" || projection.Transcript.Content != content || projection.Transcript.IsError {+ t.Fatalf("transcript result = %+v", projection.Transcript)+ }+ if projection.Model.ToolUseID != "call-1" || projection.Model.IsError {+ t.Fatalf("model result metadata = %+v", projection.Model)+ }+ if !strings.HasPrefix(projection.Model.Content, strings.Repeat("x", legacyServiceToolResultModelContextChars)) {+ t.Fatalf("model result did not retain shared prefix truncation")+ }+ if !strings.Contains(projection.Model.Content, "[TRUNCATED: 12 characters cut.") {+ t.Fatalf("model result missing shared truncation notice: %q", projection.Model.Content)}}diff --git a/internal/ai/tools/action_audit.go b/internal/ai/tools/action_audit.goindex 3f9ed55441..cb6a3b8723 100644--- a/internal/ai/tools/action_audit.go+++ b/internal/ai/tools/action_audit.go@@ -10,6 +10,7 @@ import ("time""github.com/google/uuid"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"@@ -624,8 +625,18 @@ func (e *PulseToolExecutor) recordActionLifecycle(actionID string, state unified// RecordApprovalDecision updates the unified action audit for an approval that// reached a terminal or pre-execution decision state.func (e *PulseToolExecutor) RecordApprovalDecision(approvalID string, state unifiedresources.ActionState, actor, message string) {+ var store unifiedresources.ResourceStore+ if e != nil {+ store = e.actionAuditStore+ }+ RecordApprovalDecision(store, approvalID, state, actor, message)+}++// RecordApprovalDecision updates the unified action audit for an approval that+// reached a terminal or pre-execution decision state.+func RecordApprovalDecision(store unifiedresources.ResourceStore, approvalID string, state unifiedresources.ActionState, actor, message string) {req := approvalRequestForID(approvalID)- if e == nil || req == nil || req.Plan == nil {+ if req == nil || req.Plan == nil {return}if strings.TrimSpace(actor) == "" {@@ -636,22 +647,29 @@ func (e *PulseToolExecutor) RecordApprovalDecision(approvalID string, state unif}record := actionAuditRecordFromApproval(req, state, actor)record.Approvals = approvalRecordsForID(req.ID)- if e.recordApprovalDecisionAtomically(req.ID, record, actor) {+ if recordApprovalDecisionAtomically(store, req.ID, record, actor) {return}- e.recordActionAudit(record)- e.recordActionLifecycle(req.Plan.ActionID, state, actor, message)+ recordActionAudit(store, record)+ recordActionLifecycle(store, req.Plan.ActionID, state, actor, message)}func (e *PulseToolExecutor) recordApprovalDecisionAtomically(approvalID string, record unifiedresources.ActionAuditRecord, actor string) bool {- if e == nil || e.actionAuditStore == nil {+ if e == nil {+ return false+ }+ return recordApprovalDecisionAtomically(e.actionAuditStore, approvalID, record, actor)+}++func recordApprovalDecisionAtomically(store unifiedresources.ResourceStore, approvalID string, record unifiedresources.ActionAuditRecord, actor string) bool {+ if store == nil {return false}if record.State != unifiedresources.ActionStateApproved && record.State != unifiedresources.ActionStateRejected {return false}- current, ok, err := e.actionAuditStore.GetActionAudit(record.ID)+ current, ok, err := store.GetActionAudit(record.ID)if err != nil {log.Warn().Err(err).Str("action_id", record.ID).Msg("failed to query action audit before approval decision")return false@@ -681,13 +699,46 @@ func (e *PulseToolExecutor) recordApprovalDecisionAtomically(approvalID string,log.Warn().Err(err).Str("action_id", record.ID).Msg("failed to normalize approval decision")return false}- if err := e.actionAuditStore.RecordActionDecision(updated, event); err != nil {+ if err := store.RecordActionDecision(updated, event); err != nil {log.Warn().Err(err).Str("action_id", record.ID).Msg("failed to persist approval decision")return false}return true}+func recordActionAudit(store unifiedresources.ResourceStore, record unifiedresources.ActionAuditRecord) {+ if store == nil {+ return+ }+ if err := store.RecordActionAudit(record); err != nil {+ log.Warn().+ Err(err).+ Str("action_id", record.ID).+ Str("resource_id", record.Request.ResourceID).+ Msg("failed to persist action audit")+ }+}++func recordActionLifecycle(store unifiedresources.ResourceStore, actionID string, state unifiedresources.ActionState, actor, message string) {+ if store == nil || strings.TrimSpace(actionID) == "" {+ return+ }+ event := unifiedresources.ActionLifecycleEvent{+ ActionID: actionID,+ Timestamp: time.Now().UTC(),+ State: state,+ Actor: actor,+ Message: message,+ }+ if err := store.RecordActionLifecycleEvent(event); err != nil {+ log.Warn().+ Err(err).+ Str("action_id", actionID).+ Str("state", string(state)).+ Msg("failed to persist action lifecycle event")+ }+}+func (e *PulseToolExecutor) recordPendingApprovalAction(req *approval.ApprovalRequest) {if e == nil {return@@ -880,13 +931,13 @@ func approvalDecisionActor(req *approval.ApprovalRequest, fallback string) strinfunc approvalCapabilityForTargetType(targetType string) string {switch strings.ToLower(strings.TrimSpace(targetType)) {case "docker":- return "pulse_docker"+ return agentcapabilities.PulseDockerToolNamecase "file":- return "pulse_file_edit"+ return agentcapabilities.PulseFileEditToolNamecase "kubernetes":- return "pulse_kubernetes"+ return agentcapabilities.PulseKubernetesToolNamedefault:- return "pulse_control"+ return agentcapabilities.PulseControlToolName}}diff --git a/internal/ai/tools/action_audit_execution_test.go b/internal/ai/tools/action_audit_execution_test.goindex 257c62a1eb..2c9c41a7eb 100644--- a/internal/ai/tools/action_audit_execution_test.go+++ b/internal/ai/tools/action_audit_execution_test.go@@ -384,7 +384,7 @@ func TestRecordApprovalDecisionUsesRejectedActionDecisionStoreContract(t *testint.Fatalf("Deny: %v", err)}- executor.RecordApprovalDecision("approval-rejected-decision", unifiedresources.ActionStateRejected, "[email protected]", "outside maintenance")+ RecordApprovalDecision(actionStore, "approval-rejected-decision", unifiedresources.ActionStateRejected, "[email protected]", "outside maintenance")audit, ok, err := actionStore.GetActionAudit("act-rejected-decision-contract")if err != nil {diff --git a/internal/ai/tools/adapters.go b/internal/ai/tools/adapters.goindex 75a5ce6902..b2d7891f97 100644--- a/internal/ai/tools/adapters.go+++ b/internal/ai/tools/adapters.go@@ -13,8 +13,8 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")-// AlertManagerMCPAdapter adapts alerts.Manager to MCP AlertProvider interface-type AlertManagerMCPAdapter struct {+// AlertManagerToolAdapter adapts alerts.Manager to AlertProvider interface+type AlertManagerToolAdapter struct {manager AlertManager}@@ -24,16 +24,16 @@ type AlertManager interface {GetRecentlyResolved() []models.ResolvedAlert}-// NewAlertManagerMCPAdapter creates a new adapter for alert manager-func NewAlertManagerMCPAdapter(manager AlertManager) *AlertManagerMCPAdapter {+// NewAlertManagerToolAdapter creates a new adapter for alert manager+func NewAlertManagerToolAdapter(manager AlertManager) *AlertManagerToolAdapter {if manager == nil {return nil}- return &AlertManagerMCPAdapter{manager: manager}+ return &AlertManagerToolAdapter{manager: manager}}-// GetActiveAlerts implements mcp.AlertProvider-func (a *AlertManagerMCPAdapter) GetActiveAlerts() []ActiveAlert {+// GetActiveAlerts implements AlertProvider+func (a *AlertManagerToolAdapter) GetActiveAlerts() []ActiveAlert {if a.manager == nil {return nil}@@ -58,8 +58,8 @@ func (a *AlertManagerMCPAdapter) GetActiveAlerts() []ActiveAlert {return result}-// GetRecentlyResolved implements mcp.AlertProvider-func (a *AlertManagerMCPAdapter) GetRecentlyResolved(minutes int) []models.ResolvedAlert {+// GetRecentlyResolved implements AlertProvider+func (a *AlertManagerToolAdapter) GetRecentlyResolved(minutes int) []models.ResolvedAlert {if a.manager == nil {return nil}@@ -71,25 +71,25 @@ type GuestConfigSource interface {GetGuestConfig(ctx context.Context, guestType, instance, node string, vmID int) (map[string]interface{}, error)}-// GuestConfigMCPAdapter adapts monitoring config access to MCP GuestConfigProvider interface.-type GuestConfigMCPAdapter struct {+// GuestConfigToolAdapter adapts monitoring config access to GuestConfigProvider interface.+type GuestConfigToolAdapter struct {source GuestConfigSourcetimeout time.Duration}-// NewGuestConfigMCPAdapter creates a new adapter for guest config data.-func NewGuestConfigMCPAdapter(source GuestConfigSource) *GuestConfigMCPAdapter {+// NewGuestConfigToolAdapter creates a new adapter for guest config data.+func NewGuestConfigToolAdapter(source GuestConfigSource) *GuestConfigToolAdapter {if source == nil {return nil}- return &GuestConfigMCPAdapter{+ return &GuestConfigToolAdapter{source: source,timeout: 5 * time.Second,}}-// GetGuestConfig implements mcp.GuestConfigProvider.-func (a *GuestConfigMCPAdapter) GetGuestConfig(guestType, instance, node string, vmID int) (map[string]interface{}, error) {+// GetGuestConfig implements GuestConfigProvider.+func (a *GuestConfigToolAdapter) GetGuestConfig(guestType, instance, node string, vmID int) (map[string]interface{}, error) {if a == nil || a.source == nil {return nil, fmt.Errorf("guest config source not available")}@@ -98,105 +98,105 @@ func (a *GuestConfigMCPAdapter) GetGuestConfig(guestType, instance, node string,return a.source.GetGuestConfig(ctx, guestType, instance, node, vmID)}-// BackupMCPAdapter adapts backup data sources to MCP BackupProvider interface.+// BackupToolAdapter adapts backup data sources to BackupProvider interface.// Uses functional getters so callers can wire ReadState or StateSnapshot sources.-type BackupMCPAdapter struct {+type BackupToolAdapter struct {getBackups func() models.BackupsgetPBSInstances func() []models.PBSInstance}-// NewBackupMCPAdapter creates a new adapter for backup data.+// NewBackupToolAdapter creates a new adapter for backup data.// Both getters must be non-nil; returns nil if either is nil.-func NewBackupMCPAdapter(getBackups func() models.Backups, getPBSInstances func() []models.PBSInstance) *BackupMCPAdapter {+func NewBackupToolAdapter(getBackups func() models.Backups, getPBSInstances func() []models.PBSInstance) *BackupToolAdapter {if getBackups == nil || getPBSInstances == nil {return nil}- return &BackupMCPAdapter{getBackups: getBackups, getPBSInstances: getPBSInstances}+ return &BackupToolAdapter{getBackups: getBackups, getPBSInstances: getPBSInstances}}-// GetBackups implements mcp.BackupProvider-func (a *BackupMCPAdapter) GetBackups() models.Backups {+// GetBackups implements BackupProvider+func (a *BackupToolAdapter) GetBackups() models.Backups {if a.getBackups == nil {return models.Backups{}}return a.getBackups()}-// GetPBSInstances implements mcp.BackupProvider-func (a *BackupMCPAdapter) GetPBSInstances() []models.PBSInstance {+// GetPBSInstances implements BackupProvider+func (a *BackupToolAdapter) GetPBSInstances() []models.PBSInstance {if a.getPBSInstances == nil {return nil}return a.getPBSInstances()}-// ReplicationMCPAdapter adapts replication data sources to MCP ReplicationProvider.+// ReplicationToolAdapter adapts replication data sources to ReplicationProvider.// Uses a functional getter so callers can wire ReadState or StateSnapshot sources.-type ReplicationMCPAdapter struct {+type ReplicationToolAdapter struct {getJobs func() []models.ReplicationJob}-// NewReplicationMCPAdapter creates a new adapter for replication data.-func NewReplicationMCPAdapter(getJobs func() []models.ReplicationJob) *ReplicationMCPAdapter {+// NewReplicationToolAdapter creates a new adapter for replication data.+func NewReplicationToolAdapter(getJobs func() []models.ReplicationJob) *ReplicationToolAdapter {if getJobs == nil {return nil}- return &ReplicationMCPAdapter{getJobs: getJobs}+ return &ReplicationToolAdapter{getJobs: getJobs}}// GetReplicationJobs implements ReplicationProvider.-func (a *ReplicationMCPAdapter) GetReplicationJobs() []models.ReplicationJob {+func (a *ReplicationToolAdapter) GetReplicationJobs() []models.ReplicationJob {if a.getJobs == nil {return nil}return a.getJobs()}-// ConnectionHealthMCPAdapter adapts connection health data sources to MCP ConnectionHealthProvider.+// ConnectionHealthToolAdapter adapts connection health data sources to ConnectionHealthProvider.// Uses a functional getter so callers can wire ReadState or StateSnapshot sources.-type ConnectionHealthMCPAdapter struct {+type ConnectionHealthToolAdapter struct {getHealth func() map[string]bool}-// NewConnectionHealthMCPAdapter creates a new adapter for connection health data.-func NewConnectionHealthMCPAdapter(getHealth func() map[string]bool) *ConnectionHealthMCPAdapter {+// NewConnectionHealthToolAdapter creates a new adapter for connection health data.+func NewConnectionHealthToolAdapter(getHealth func() map[string]bool) *ConnectionHealthToolAdapter {if getHealth == nil {return nil}- return &ConnectionHealthMCPAdapter{getHealth: getHealth}+ return &ConnectionHealthToolAdapter{getHealth: getHealth}}// GetConnectionHealth implements ConnectionHealthProvider.-func (a *ConnectionHealthMCPAdapter) GetConnectionHealth() map[string]bool {+func (a *ConnectionHealthToolAdapter) GetConnectionHealth() map[string]bool {if a.getHealth == nil {return nil}return a.getHealth()}-// RecoveryPointsMCPAdapter provides MCP tools access to persisted recovery points.+// RecoveryPointsToolAdapter provides Assistant tools access to persisted recovery points.// It is org-scoped to avoid leaking cross-tenant data.-type RecoveryPointsMCPAdapter struct {+type RecoveryPointsToolAdapter struct {manager *recoverymanager.ManagerorgID stringtimeout time.Duration}-func NewRecoveryPointsMCPAdapter(manager *recoverymanager.Manager, orgID string) *RecoveryPointsMCPAdapter {+func NewRecoveryPointsToolAdapter(manager *recoverymanager.Manager, orgID string) *RecoveryPointsToolAdapter {if manager == nil {return nil}if orgID == "" {orgID = "default"}- return &RecoveryPointsMCPAdapter{+ return &RecoveryPointsToolAdapter{manager: manager,orgID: orgID,timeout: 5 * time.Second,}}-func (a *RecoveryPointsMCPAdapter) ListPoints(ctx context.Context, opts recovery.ListPointsOptions) ([]recovery.RecoveryPoint, int, error) {+func (a *RecoveryPointsToolAdapter) ListPoints(ctx context.Context, opts recovery.ListPointsOptions) ([]recovery.RecoveryPoint, int, error) {if a == nil || a.manager == nil {return nil, 0, fmt.Errorf("recovery points provider not available")}@@ -210,21 +210,21 @@ func (a *RecoveryPointsMCPAdapter) ListPoints(ctx context.Context, opts recoveryreturn store.ListPoints(ctx, opts)}-// DiskHealthMCPAdapter adapts unified read-state hosts to MCP DiskHealthProvider.-type DiskHealthMCPAdapter struct {+// DiskHealthToolAdapter adapts unified read-state hosts to DiskHealthProvider.+type DiskHealthToolAdapter struct {readState unifiedresources.ReadState}-// NewDiskHealthMCPAdapter creates a new adapter for disk health data-func NewDiskHealthMCPAdapter(readState unifiedresources.ReadState) *DiskHealthMCPAdapter {+// NewDiskHealthToolAdapter creates a new adapter for disk health data+func NewDiskHealthToolAdapter(readState unifiedresources.ReadState) *DiskHealthToolAdapter {if readState == nil {return nil}- return &DiskHealthMCPAdapter{readState: readState}+ return &DiskHealthToolAdapter{readState: readState}}-// GetHosts implements mcp.DiskHealthProvider-func (a *DiskHealthMCPAdapter) GetHosts() []*unifiedresources.HostView {+// GetHosts implements DiskHealthProvider+func (a *DiskHealthToolAdapter) GetHosts() []*unifiedresources.HostView {if a.readState == nil {return nil}@@ -244,26 +244,26 @@ type MetricsSource interface {GetAllGuestMetrics(guestID string, duration time.Duration) map[string][]RawMetricPoint}-// MetricsHistoryMCPAdapter adapts the metrics history to MCP MetricsHistoryProvider interface-type MetricsHistoryMCPAdapter struct {+// MetricsHistoryToolAdapter adapts the metrics history to MetricsHistoryProvider interface+type MetricsHistoryToolAdapter struct {readState unifiedresources.ReadStatemetricsSource MetricsSource}-// NewMetricsHistoryMCPAdapter creates a new adapter for metrics history.+// NewMetricsHistoryToolAdapter creates a new adapter for metrics history.// readState is required for iterating VMs/Containers/Nodes in GetAllMetricsSummary.-func NewMetricsHistoryMCPAdapter(metricsSource MetricsSource, readState unifiedresources.ReadState) *MetricsHistoryMCPAdapter {+func NewMetricsHistoryToolAdapter(metricsSource MetricsSource, readState unifiedresources.ReadState) *MetricsHistoryToolAdapter {if metricsSource == nil || readState == nil {return nil}- return &MetricsHistoryMCPAdapter{+ return &MetricsHistoryToolAdapter{readState: readState,metricsSource: metricsSource,}}-// GetResourceMetrics implements mcp.MetricsHistoryProvider-func (a *MetricsHistoryMCPAdapter) GetResourceMetrics(resourceID string, period time.Duration) ([]MetricPoint, error) {+// GetResourceMetrics implements MetricsHistoryProvider+func (a *MetricsHistoryToolAdapter) GetResourceMetrics(resourceID string, period time.Duration) ([]MetricPoint, error) {if a.metricsSource == nil {return nil, nil}@@ -290,9 +290,9 @@ func (a *MetricsHistoryMCPAdapter) GetResourceMetrics(resourceID string, periodreturn mergeMetricsByTimestamp(allMetrics), nil}-// GetAllMetricsSummary implements mcp.MetricsHistoryProvider.+// GetAllMetricsSummary implements MetricsHistoryProvider.// Uses ReadState to iterate VMs, Containers, and Nodes.-func (a *MetricsHistoryMCPAdapter) GetAllMetricsSummary(period time.Duration) (map[string]ResourceMetricsSummary, error) {+func (a *MetricsHistoryToolAdapter) GetAllMetricsSummary(period time.Duration) (map[string]ResourceMetricsSummary, error) {if a.metricsSource == nil || a.readState == nil {return nil, nil}@@ -325,7 +325,7 @@ func (a *MetricsHistoryMCPAdapter) GetAllMetricsSummary(period time.Duration) (mreturn result, nil}-func (a *MetricsHistoryMCPAdapter) computeSummary(resourceID, resourceName, resourceType string, period time.Duration) *ResourceMetricsSummary {+func (a *MetricsHistoryToolAdapter) computeSummary(resourceID, resourceName, resourceType string, period time.Duration) *ResourceMetricsSummary {var cpuPoints, memPoints []RawMetricPointif resourceType == "node" {@@ -452,21 +452,21 @@ type BaselineData struct {SampleCount int}-// BaselineMCPAdapter adapts baseline.Store to MCP BaselineProvider interface-type BaselineMCPAdapter struct {+// BaselineToolAdapter adapts baseline.Store to BaselineProvider interface+type BaselineToolAdapter struct {source BaselineSource}-// NewBaselineMCPAdapter creates a new adapter for baseline data-func NewBaselineMCPAdapter(source BaselineSource) *BaselineMCPAdapter {+// NewBaselineToolAdapter creates a new adapter for baseline data+func NewBaselineToolAdapter(source BaselineSource) *BaselineToolAdapter {if source == nil {return nil}- return &BaselineMCPAdapter{source: source}+ return &BaselineToolAdapter{source: source}}-// GetBaseline implements mcp.BaselineProvider-func (a *BaselineMCPAdapter) GetBaseline(resourceID, metric string) *MetricBaseline {+// GetBaseline implements BaselineProvider+func (a *BaselineToolAdapter) GetBaseline(resourceID, metric string) *MetricBaseline {if a.source == nil {return nil}@@ -484,8 +484,8 @@ func (a *BaselineMCPAdapter) GetBaseline(resourceID, metric string) *MetricBasel}}-// GetAllBaselines implements mcp.BaselineProvider-func (a *BaselineMCPAdapter) GetAllBaselines() map[string]map[string]*MetricBaseline {+// GetAllBaselines implements BaselineProvider+func (a *BaselineToolAdapter) GetAllBaselines() map[string]map[string]*MetricBaseline {if a.source == nil {return nil}@@ -537,24 +537,24 @@ type PredictionData struct {Recommendation string}-// PatternMCPAdapter adapts patterns.Detector to MCP PatternProvider interface-type PatternMCPAdapter struct {+// PatternToolAdapter adapts patterns.Detector to PatternProvider interface+type PatternToolAdapter struct {source PatternSourcereadState unifiedresources.ReadState}-// NewPatternMCPAdapter creates a new adapter for pattern data.+// NewPatternToolAdapter creates a new adapter for pattern data.// readState is optional: when provided, resource name lookups resolve via// ReadState views; when nil, raw resource IDs are returned as names.-func NewPatternMCPAdapter(source PatternSource, readState unifiedresources.ReadState) *PatternMCPAdapter {+func NewPatternToolAdapter(source PatternSource, readState unifiedresources.ReadState) *PatternToolAdapter {if source == nil {return nil}- return &PatternMCPAdapter{source: source, readState: readState}+ return &PatternToolAdapter{source: source, readState: readState}}-// GetPatterns implements mcp.PatternProvider-func (a *PatternMCPAdapter) GetPatterns() []Pattern {+// GetPatterns implements PatternProvider+func (a *PatternToolAdapter) GetPatterns() []Pattern {if a.source == nil {return nil}@@ -579,8 +579,8 @@ func (a *PatternMCPAdapter) GetPatterns() []Pattern {return result}-// GetPredictions implements mcp.PatternProvider-func (a *PatternMCPAdapter) GetPredictions() []Prediction {+// GetPredictions implements PatternProvider+func (a *PatternToolAdapter) GetPredictions() []Prediction {if a.source == nil {return nil}@@ -605,7 +605,7 @@ func (a *PatternMCPAdapter) GetPredictions() []Prediction {return result}-func (a *PatternMCPAdapter) getResourceName(resourceID string) string {+func (a *PatternToolAdapter) getResourceName(resourceID string) string {if a.readState == nil {return resourceID}@@ -636,29 +636,29 @@ type FindingsManagerSource interface {DismissFinding(findingID, reason, note string) error}-// FindingsManagerMCPAdapter adapts PatrolService to MCP FindingsManager interface-type FindingsManagerMCPAdapter struct {+// FindingsManagerToolAdapter adapts PatrolService to the Assistant findings manager provider.+type FindingsManagerToolAdapter struct {source FindingsManagerSource}-// NewFindingsManagerMCPAdapter creates a new adapter for findings management-func NewFindingsManagerMCPAdapter(source FindingsManagerSource) *FindingsManagerMCPAdapter {+// NewFindingsManagerToolAdapter creates a new adapter for findings management+func NewFindingsManagerToolAdapter(source FindingsManagerSource) *FindingsManagerToolAdapter {if source == nil {return nil}- return &FindingsManagerMCPAdapter{source: source}+ return &FindingsManagerToolAdapter{source: source}}-// ResolveFinding implements mcp.FindingsManager-func (a *FindingsManagerMCPAdapter) ResolveFinding(findingID, note string) error {+// ResolveFinding implements FindingsManager+func (a *FindingsManagerToolAdapter) ResolveFinding(findingID, note string) error {if a.source == nil {return fmt.Errorf("findings manager not available")}return a.source.ResolveFinding(findingID, note)}-// DismissFinding implements mcp.FindingsManager-func (a *FindingsManagerMCPAdapter) DismissFinding(findingID, reason, note string) error {+// DismissFinding implements FindingsManager+func (a *FindingsManagerToolAdapter) DismissFinding(findingID, reason, note string) error {if a.source == nil {return fmt.Errorf("findings manager not available")}@@ -672,21 +672,21 @@ type MetadataUpdaterSource interface {SetResourceURL(resourceType, resourceID, url string) error}-// MetadataUpdaterMCPAdapter adapts ai.Service to MCP MetadataUpdater interface-type MetadataUpdaterMCPAdapter struct {+// MetadataUpdaterToolAdapter adapts ai.Service to the Assistant metadata updater provider.+type MetadataUpdaterToolAdapter struct {source MetadataUpdaterSource}-// NewMetadataUpdaterMCPAdapter creates a new adapter for metadata updates-func NewMetadataUpdaterMCPAdapter(source MetadataUpdaterSource) *MetadataUpdaterMCPAdapter {+// NewMetadataUpdaterToolAdapter creates a new adapter for metadata updates+func NewMetadataUpdaterToolAdapter(source MetadataUpdaterSource) *MetadataUpdaterToolAdapter {if source == nil {return nil}- return &MetadataUpdaterMCPAdapter{source: source}+ return &MetadataUpdaterToolAdapter{source: source}}-// SetResourceURL implements mcp.MetadataUpdater-func (a *MetadataUpdaterMCPAdapter) SetResourceURL(resourceType, resourceID, url string) error {+// SetResourceURL implements MetadataUpdater+func (a *MetadataUpdaterToolAdapter) SetResourceURL(resourceType, resourceID, url string) error {if a.source == nil {return fmt.Errorf("metadata updater not available")}@@ -707,26 +707,26 @@ type UpdatesConfig interface {IsDockerUpdateActionsEnabled() bool}-// UpdatesMCPAdapter adapts Monitor to MCP UpdatesProvider interface.+// UpdatesToolAdapter adapts Monitor to UpdatesProvider interface.// Uses a functional getter for Docker host iteration (decoupled from GetState)// and a command runner for Docker update operations.-type UpdatesMCPAdapter struct {+type UpdatesToolAdapter struct {readState unifiedresources.ReadStatecommands UpdatesCommandRunnerconfig UpdatesConfig}-// NewUpdatesMCPAdapter creates a new adapter for update operations.+// NewUpdatesToolAdapter creates a new adapter for update operations.// readState provides Docker host/container views; commands provides update command execution.-func NewUpdatesMCPAdapter(readState unifiedresources.ReadState, commands UpdatesCommandRunner, config UpdatesConfig) *UpdatesMCPAdapter {+func NewUpdatesToolAdapter(readState unifiedresources.ReadState, commands UpdatesCommandRunner, config UpdatesConfig) *UpdatesToolAdapter {if readState == nil || commands == nil {return nil}- return &UpdatesMCPAdapter{readState: readState, commands: commands, config: config}+ return &UpdatesToolAdapter{readState: readState, commands: commands, config: config}}-// GetPendingUpdates implements mcp.UpdatesProvider-func (a *UpdatesMCPAdapter) GetPendingUpdates(hostID string) []ContainerUpdateInfo {+// GetPendingUpdates implements UpdatesProvider+func (a *UpdatesToolAdapter) GetPendingUpdates(hostID string) []ContainerUpdateInfo {if a.readState == nil {return nil}@@ -811,8 +811,8 @@ func (a *UpdatesMCPAdapter) GetPendingUpdates(hostID string) []ContainerUpdateInreturn updates}-// TriggerUpdateCheck implements mcp.UpdatesProvider-func (a *UpdatesMCPAdapter) TriggerUpdateCheck(hostID string) (DockerCommandStatus, error) {+// TriggerUpdateCheck implements UpdatesProvider+func (a *UpdatesToolAdapter) TriggerUpdateCheck(hostID string) (DockerCommandStatus, error) {if a.commands == nil {return DockerCommandStatus{}, fmt.Errorf("monitor not available")}@@ -830,8 +830,8 @@ func (a *UpdatesMCPAdapter) TriggerUpdateCheck(hostID string) (DockerCommandStat}, nil}-// UpdateContainer implements mcp.UpdatesProvider-func (a *UpdatesMCPAdapter) UpdateContainer(hostID, containerID, containerName string) (DockerCommandStatus, error) {+// UpdateContainer implements UpdatesProvider+func (a *UpdatesToolAdapter) UpdateContainer(hostID, containerID, containerName string) (DockerCommandStatus, error) {if a.commands == nil {return DockerCommandStatus{}, fmt.Errorf("monitor not available")}@@ -849,8 +849,8 @@ func (a *UpdatesMCPAdapter) UpdateContainer(hostID, containerID, containerName s}, nil}-// IsUpdateActionsEnabled implements mcp.UpdatesProvider-func (a *UpdatesMCPAdapter) IsUpdateActionsEnabled() bool {+// IsUpdateActionsEnabled implements UpdatesProvider+func (a *UpdatesToolAdapter) IsUpdateActionsEnabled() bool {if a.config == nil {return true // Default to enabled if no config}@@ -932,21 +932,21 @@ type DiscoverySourceFact struct {Confidence float64 // 0-1 confidence for this fact}-// DiscoveryMCPAdapter adapts servicediscovery.Service to MCP DiscoveryProvider interface-type DiscoveryMCPAdapter struct {+// DiscoveryToolAdapter adapts servicediscovery.Service to DiscoveryProvider interface+type DiscoveryToolAdapter struct {source DiscoverySource}-// NewDiscoveryMCPAdapter creates a new adapter for discovery data-func NewDiscoveryMCPAdapter(source DiscoverySource) *DiscoveryMCPAdapter {+// NewDiscoveryToolAdapter creates a new adapter for discovery data+func NewDiscoveryToolAdapter(source DiscoverySource) *DiscoveryToolAdapter {if source == nil {return nil}- return &DiscoveryMCPAdapter{source: source}+ return &DiscoveryToolAdapter{source: source}}// GetDiscovery implements tools.DiscoveryProvider-func (a *DiscoveryMCPAdapter) GetDiscovery(id string) (*ResourceDiscoveryInfo, error) {+func (a *DiscoveryToolAdapter) GetDiscovery(id string) (*ResourceDiscoveryInfo, error) {if a.source == nil {return nil, fmt.Errorf("discovery source not available")}@@ -960,7 +960,7 @@ func (a *DiscoveryMCPAdapter) GetDiscovery(id string) (*ResourceDiscoveryInfo, e}// GetDiscoveryByResource implements tools.DiscoveryProvider-func (a *DiscoveryMCPAdapter) GetDiscoveryByResource(resourceType, targetID, resourceID string) (*ResourceDiscoveryInfo, error) {+func (a *DiscoveryToolAdapter) GetDiscoveryByResource(resourceType, targetID, resourceID string) (*ResourceDiscoveryInfo, error) {if a.source == nil {return nil, fmt.Errorf("discovery source not available")}@@ -974,7 +974,7 @@ func (a *DiscoveryMCPAdapter) GetDiscoveryByResource(resourceType, targetID, res}// ListDiscoveries implements tools.DiscoveryProvider-func (a *DiscoveryMCPAdapter) ListDiscoveries() ([]*ResourceDiscoveryInfo, error) {+func (a *DiscoveryToolAdapter) ListDiscoveries() ([]*ResourceDiscoveryInfo, error) {if a.source == nil {return nil, fmt.Errorf("discovery source not available")}@@ -988,7 +988,7 @@ func (a *DiscoveryMCPAdapter) ListDiscoveries() ([]*ResourceDiscoveryInfo, error}// ListDiscoveriesByType implements tools.DiscoveryProvider-func (a *DiscoveryMCPAdapter) ListDiscoveriesByType(resourceType string) ([]*ResourceDiscoveryInfo, error) {+func (a *DiscoveryToolAdapter) ListDiscoveriesByType(resourceType string) ([]*ResourceDiscoveryInfo, error) {if a.source == nil {return nil, fmt.Errorf("discovery source not available")}@@ -1002,7 +1002,7 @@ func (a *DiscoveryMCPAdapter) ListDiscoveriesByType(resourceType string) ([]*Res}// ListDiscoveriesByTarget implements tools.DiscoveryProvider-func (a *DiscoveryMCPAdapter) ListDiscoveriesByTarget(targetID string) ([]*ResourceDiscoveryInfo, error) {+func (a *DiscoveryToolAdapter) ListDiscoveriesByTarget(targetID string) ([]*ResourceDiscoveryInfo, error) {if a.source == nil {return nil, fmt.Errorf("discovery source not available")}@@ -1016,7 +1016,7 @@ func (a *DiscoveryMCPAdapter) ListDiscoveriesByTarget(targetID string) ([]*Resou}// FormatForAIContext implements tools.DiscoveryProvider-func (a *DiscoveryMCPAdapter) FormatForAIContext(discoveries []*ResourceDiscoveryInfo) string {+func (a *DiscoveryToolAdapter) FormatForAIContext(discoveries []*ResourceDiscoveryInfo) string {if a.source == nil {return ""}@@ -1086,7 +1086,7 @@ func (a *DiscoveryMCPAdapter) FormatForAIContext(discoveries []*ResourceDiscover}// TriggerDiscovery implements tools.DiscoveryProvider-func (a *DiscoveryMCPAdapter) TriggerDiscovery(ctx context.Context, resourceType, targetID, resourceID string, force bool) (*ResourceDiscoveryInfo, error) {+func (a *DiscoveryToolAdapter) TriggerDiscovery(ctx context.Context, resourceType, targetID, resourceID string, force bool) (*ResourceDiscoveryInfo, error) {if a.source == nil {return nil, fmt.Errorf("discovery source not available")}@@ -1099,7 +1099,7 @@ func (a *DiscoveryMCPAdapter) TriggerDiscovery(ctx context.Context, resourceTypereturn a.convertToInfo(data), nil}-func (a *DiscoveryMCPAdapter) convertToInfo(data DiscoverySourceData) *ResourceDiscoveryInfo {+func (a *DiscoveryToolAdapter) convertToInfo(data DiscoverySourceData) *ResourceDiscoveryInfo {if data.ID == "" {return nil}@@ -1169,7 +1169,7 @@ func (a *DiscoveryMCPAdapter) convertToInfo(data DiscoverySourceData) *ResourceD}}-func (a *DiscoveryMCPAdapter) convertList(dataList []DiscoverySourceData) []*ResourceDiscoveryInfo {+func (a *DiscoveryToolAdapter) convertList(dataList []DiscoverySourceData) []*ResourceDiscoveryInfo {result := make([]*ResourceDiscoveryInfo, 0, len(dataList))for _, data := range dataList {if info := a.convertToInfo(data); info != nil {diff --git a/internal/ai/tools/adapters_readstate_test.go b/internal/ai/tools/adapters_readstate_test.goindex 0c70863c11..e93665df8d 100644--- a/internal/ai/tools/adapters_readstate_test.go+++ b/internal/ai/tools/adapters_readstate_test.go@@ -146,7 +146,7 @@ func TestMetricsSummaryWithReadState(t *testing.T) {nodes: []*ur.NodeView{newNodeView("reg-node-hash", "node-1", "node1")},}- adapter := NewMetricsHistoryMCPAdapter(source, rs)+ adapter := NewMetricsHistoryToolAdapter(source, rs)if adapter == nil {t.Fatal("expected non-nil adapter when readState provided")}@@ -177,7 +177,7 @@ func TestMetricsSummaryReadStateVMsOnly(t *testing.T) {"100": {"cpu": {{Value: 10, Timestamp: now}}},},}- adapter := NewMetricsHistoryMCPAdapter(source, rs)+ adapter := NewMetricsHistoryToolAdapter(source, rs)if adapter == nil {t.Fatal("expected non-nil adapter with readState")}@@ -196,7 +196,7 @@ func TestMetricsSummaryReadStateVMsOnly(t *testing.T) {func TestMetricsSummaryNilMetricsSource(t *testing.T) {// When metricsSource is nil, constructor returns nilrs := &fakeReadState{}- if adapter := NewMetricsHistoryMCPAdapter(nil, rs); adapter != nil {+ if adapter := NewMetricsHistoryToolAdapter(nil, rs); adapter != nil {t.Fatal("expected nil adapter for nil metricsSource")}}@@ -204,7 +204,7 @@ func TestMetricsSummaryNilMetricsSource(t *testing.T) {func TestMetricsSummaryNilReadState(t *testing.T) {// When readState is nil, constructor returns nilsource := &fakeMetricsSource{}- if adapter := NewMetricsHistoryMCPAdapter(source, nil); adapter != nil {+ if adapter := NewMetricsHistoryToolAdapter(source, nil); adapter != nil {t.Fatal("expected nil adapter when readState is nil")}}@@ -226,7 +226,7 @@ func TestPatternAdapterWithReadState(t *testing.T) {},}- adapter := NewPatternMCPAdapter(source, rs)+ adapter := NewPatternToolAdapter(source, rs)patterns := adapter.GetPatterns()if len(patterns) != 2 {t.Fatalf("expected 2 patterns, got %d", len(patterns))@@ -258,7 +258,7 @@ func TestPatternAdapterReadStateFallbackForUnknownID(t *testing.T) {},}- adapter := NewPatternMCPAdapter(source, rs)+ adapter := NewPatternToolAdapter(source, rs)patterns := adapter.GetPatterns()if len(patterns) != 1 {t.Fatalf("expected 1 pattern, got %d", len(patterns))@@ -276,7 +276,7 @@ func TestPatternAdapterNilReadState(t *testing.T) {},}- adapter := NewPatternMCPAdapter(source, nil)+ adapter := NewPatternToolAdapter(source, nil)patterns := adapter.GetPatterns()// nil readState → resource ID returned as nameif patterns[0].ResourceName != "100" {@@ -299,7 +299,7 @@ func TestPatternAdapterReadStateContainerVMIDLookup(t *testing.T) {},}- adapter := NewPatternMCPAdapter(source, rs)+ adapter := NewPatternToolAdapter(source, rs)patterns := adapter.GetPatterns()if patterns[0].ResourceName != "my-container" {t.Fatalf("expected 'my-container', got %q", patterns[0].ResourceName)@@ -323,7 +323,7 @@ func TestMetricsSummaryNodeEmptySourceIDSkipped(t *testing.T) {nodes: []*ur.NodeView{emptySourceNode},}- adapter := NewMetricsHistoryMCPAdapter(source, rs)+ adapter := NewMetricsHistoryToolAdapter(source, rs)summary, err := adapter.GetAllMetricsSummary(time.Hour)if err != nil {t.Fatalf("unexpected error: %v", err)@@ -349,7 +349,7 @@ func TestPatternAdapterNodeEmptySourceIDFallsBackToID(t *testing.T) {},}- adapter := NewPatternMCPAdapter(source, rs)+ adapter := NewPatternToolAdapter(source, rs)patterns := adapter.GetPatterns()// No node matches "some-legacy-id" (the node has empty SourceID),// so the raw resource ID is returned as the name.diff --git a/internal/ai/tools/adapters_test.go b/internal/ai/tools/adapters_test.goindex 850bfec6c7..6a4f0c1ffc 100644--- a/internal/ai/tools/adapters_test.go+++ b/internal/ai/tools/adapters_test.go@@ -134,8 +134,8 @@ func (f *fakeUpdatesConfig) IsDockerUpdateActionsEnabled() bool {return f.enabled}-func TestAlertManagerMCPAdapter(t *testing.T) {- if NewAlertManagerMCPAdapter(nil) != nil {+func TestAlertManagerToolAdapter(t *testing.T) {+ if NewAlertManagerToolAdapter(nil) != nil {t.Fatal("expected nil adapter for nil manager")}@@ -156,7 +156,7 @@ func TestAlertManagerMCPAdapter(t *testing.T) {},}- adapter := NewAlertManagerMCPAdapter(manager)+ adapter := NewAlertManagerToolAdapter(manager)got := adapter.GetActiveAlerts()if len(got) != 1 {t.Fatalf("expected 1 alert, got %d", len(got))@@ -173,17 +173,17 @@ func TestBackupAndDiskAdapters(t *testing.T) {pbsInstances := []models.PBSInstance{{ID: "pbs1"}}repJobs := []models.ReplicationJob{{ID: "rep1"}}- if NewBackupMCPAdapter(nil, nil) != nil {+ if NewBackupToolAdapter(nil, nil) != nil {t.Fatal("expected nil backup adapter for nil getters")}// Partial-nil: one getter nil should also return nil- if NewBackupMCPAdapter(func() models.Backups { return models.Backups{} }, nil) != nil {+ if NewBackupToolAdapter(func() models.Backups { return models.Backups{} }, nil) != nil {t.Fatal("expected nil backup adapter when getPBSInstances is nil")}- if NewBackupMCPAdapter(nil, func() []models.PBSInstance { return nil }) != nil {+ if NewBackupToolAdapter(nil, func() []models.PBSInstance { return nil }) != nil {t.Fatal("expected nil backup adapter when getBackups is nil")}- backupAdapter := NewBackupMCPAdapter(+ backupAdapter := NewBackupToolAdapter(func() models.Backups { return backups },func() []models.PBSInstance { return pbsInstances },)@@ -194,7 +194,7 @@ func TestBackupAndDiskAdapters(t *testing.T) {t.Fatal("expected pbs instances")}- if NewDiskHealthMCPAdapter(nil) != nil {+ if NewDiskHealthToolAdapter(nil) != nil {t.Fatal("expected nil disk health adapter for nil read state")}rs := &fakeReadState{@@ -202,27 +202,27 @@ func TestBackupAndDiskAdapters(t *testing.T) {newHostView("host-resource-1", "Host 1", "host1", "host-1", nil, nil, nil),},}- diskAdapter := NewDiskHealthMCPAdapter(+ diskAdapter := NewDiskHealthToolAdapter(rs,)if len(diskAdapter.GetHosts()) != 1 {t.Fatal("expected hosts")}- if NewReplicationMCPAdapter(nil) != nil {+ if NewReplicationToolAdapter(nil) != nil {t.Fatal("expected nil replication adapter for nil getter")}- replicationAdapter := NewReplicationMCPAdapter(+ replicationAdapter := NewReplicationToolAdapter(func() []models.ReplicationJob { return repJobs },)if len(replicationAdapter.GetReplicationJobs()) != 1 {t.Fatal("expected replication jobs")}- if NewConnectionHealthMCPAdapter(nil) != nil {+ if NewConnectionHealthToolAdapter(nil) != nil {t.Fatal("expected nil connection health adapter for nil getter")}- connectionHealthAdapter := NewConnectionHealthMCPAdapter(+ connectionHealthAdapter := NewConnectionHealthToolAdapter(func() map[string]bool { return nil },)if connectionHealthAdapter.GetConnectionHealth() != nil {@@ -230,7 +230,7 @@ func TestBackupAndDiskAdapters(t *testing.T) {}}-func TestMetricsHistoryMCPAdapter(t *testing.T) {+func TestMetricsHistoryToolAdapter(t *testing.T) {now := time.Now()points := map[string][]RawMetricPoint{"cpu": {{Value: 10, Timestamp: now}},@@ -243,7 +243,7 @@ func TestMetricsHistoryMCPAdapter(t *testing.T) {}rs := &fakeReadState{}- adapter := NewMetricsHistoryMCPAdapter(source, rs)+ adapter := NewMetricsHistoryToolAdapter(source, rs)got, err := adapter.GetResourceMetrics("100", time.Hour)if err != nil {t.Fatalf("unexpected error: %v", err)@@ -262,7 +262,7 @@ func TestMetricsHistoryMCPAdapter(t *testing.T) {},},}- adapter = NewMetricsHistoryMCPAdapter(source, rs)+ adapter = NewMetricsHistoryToolAdapter(source, rs)got, err = adapter.GetResourceMetrics("node1", time.Hour)if err != nil {t.Fatalf("unexpected error: %v", err)@@ -271,7 +271,7 @@ func TestMetricsHistoryMCPAdapter(t *testing.T) {t.Fatalf("unexpected node metrics: %+v", got)}- adapter = &MetricsHistoryMCPAdapter{}+ adapter = &MetricsHistoryToolAdapter{}empty, err := adapter.GetResourceMetrics("missing", time.Hour)if err != nil || empty != nil {t.Fatal("expected nil metrics when source missing")@@ -305,7 +305,7 @@ func TestMetricsSummaryAndHelpers(t *testing.T) {nodes: []*ur.NodeView{newNodeView("reg-node-hash", "node-1", "node1")},}- adapter := NewMetricsHistoryMCPAdapter(source, rs)+ adapter := NewMetricsHistoryToolAdapter(source, rs)summary, err := adapter.GetAllMetricsSummary(time.Hour)if err != nil {t.Fatalf("unexpected error: %v", err)@@ -348,27 +348,27 @@ func TestMetricsSummaryAndHelpers(t *testing.T) {}}-func TestBaselineMCPAdapter(t *testing.T) {- if NewBaselineMCPAdapter(nil) != nil {+func TestBaselineToolAdapter(t *testing.T) {+ if NewBaselineToolAdapter(nil) != nil {t.Fatal("expected nil baseline adapter for nil source")}- adapter := NewBaselineMCPAdapter(&fakeBaselineSource{mean: 10, stddev: 2, ok: true})+ adapter := NewBaselineToolAdapter(&fakeBaselineSource{mean: 10, stddev: 2, ok: true})baseline := adapter.GetBaseline("vm1", "cpu")if baseline == nil || baseline.Min != 6 || baseline.Max != 14 {t.Fatalf("unexpected baseline: %+v", baseline)}- adapter = &BaselineMCPAdapter{}+ adapter = &BaselineToolAdapter{}if adapter.GetBaseline("vm1", "cpu") != nil {t.Fatal("expected nil baseline when source missing")}- adapter = NewBaselineMCPAdapter(&fakeBaselineSource{ok: false})+ adapter = NewBaselineToolAdapter(&fakeBaselineSource{ok: false})if adapter.GetBaseline("vm1", "cpu") != nil {t.Fatal("expected nil baseline when not found")}- adapter = NewBaselineMCPAdapter(&fakeBaselineSource{all: nil})+ adapter = NewBaselineToolAdapter(&fakeBaselineSource{all: nil})if adapter.GetAllBaselines() != nil {t.Fatal("expected nil baselines when source returns nil")}@@ -376,14 +376,14 @@ func TestBaselineMCPAdapter(t *testing.T) {all := map[string]map[string]BaselineData{"100": {"cpu": {Mean: 5, StdDev: 1}},}- adapter = NewBaselineMCPAdapter(&fakeBaselineSource{all: all})+ adapter = NewBaselineToolAdapter(&fakeBaselineSource{all: all})allBaselines := adapter.GetAllBaselines()if allBaselines["100"]["cpu"].Min != 3 || allBaselines["100"]["cpu"].Max != 7 {t.Fatalf("unexpected all baselines: %+v", allBaselines)}}-func TestPatternMCPAdapter(t *testing.T) {+func TestPatternToolAdapter(t *testing.T) {rs := &fakeReadState{vms: []*ur.VMView{newVMView("vm-100", "vm1", 100)},containers: []*ur.ContainerView{newContainerView("ct-200", "ct1", 200)},@@ -399,7 +399,7 @@ func TestPatternMCPAdapter(t *testing.T) {},}- adapter := NewPatternMCPAdapter(source, rs)+ adapter := NewPatternToolAdapter(source, rs)patterns := adapter.GetPatterns()if len(patterns) != 2 || patterns[0].ResourceName != "vm1" || patterns[1].ResourceName != "node-1" {t.Fatalf("unexpected patterns: %+v", patterns)@@ -409,7 +409,7 @@ func TestPatternMCPAdapter(t *testing.T) {t.Fatalf("unexpected predictions: %+v", predictions)}- adapter = NewPatternMCPAdapter(source, nil)+ adapter = NewPatternToolAdapter(source, nil)patterns = adapter.GetPatterns()if patterns[0].ResourceName != "100" {t.Fatal("expected resource ID when readState missing")@@ -418,7 +418,7 @@ func TestPatternMCPAdapter(t *testing.T) {func TestFindingsAndMetadataAdapters(t *testing.T) {manager := &fakeFindingsManager{resolveErr: errors.New("resolve"), dismissErr: errors.New("dismiss")}- adapter := NewFindingsManagerMCPAdapter(manager)+ adapter := NewFindingsManagerToolAdapter(manager)if err := adapter.ResolveFinding("f1", "note"); err == nil {t.Fatal("expected resolve error")}@@ -429,34 +429,34 @@ func TestFindingsAndMetadataAdapters(t *testing.T) {t.Fatal("expected args to be captured")}- adapter = &FindingsManagerMCPAdapter{}+ adapter = &FindingsManagerToolAdapter{}if err := adapter.ResolveFinding("f1", "note"); err == nil {t.Fatal("expected error when manager missing")}updater := &fakeMetadataUpdater{err: errors.New("update")}- meta := NewMetadataUpdaterMCPAdapter(updater)+ meta := NewMetadataUpdaterToolAdapter(updater)if err := meta.SetResourceURL("vm", "1", "http://x"); err == nil {t.Fatal("expected update error")}if len(updater.resourceArgs) != 3 {t.Fatal("expected resource args captured")}- meta = &MetadataUpdaterMCPAdapter{}+ meta = &MetadataUpdaterToolAdapter{}if err := meta.SetResourceURL("vm", "1", "http://x"); err == nil {t.Fatal("expected error when metadata updater missing")}}-func TestUpdatesMCPAdapter(t *testing.T) {- if NewUpdatesMCPAdapter(nil, nil, nil) != nil {+func TestUpdatesToolAdapter(t *testing.T) {+ if NewUpdatesToolAdapter(nil, nil, nil) != nil {t.Fatal("expected nil updates adapter for nil getters")}// Partial-nil: either read state or commands nil should return nil.- if NewUpdatesMCPAdapter(&fakeReadState{}, nil, nil) != nil {+ if NewUpdatesToolAdapter(&fakeReadState{}, nil, nil) != nil {t.Fatal("expected nil updates adapter when commands is nil")}- if NewUpdatesMCPAdapter(nil, &fakeUpdatesCommandRunner{}, nil) != nil {+ if NewUpdatesToolAdapter(nil, &fakeUpdatesCommandRunner{}, nil) != nil {t.Fatal("expected nil updates adapter when readState is nil")}@@ -496,7 +496,7 @@ func TestUpdatesMCPAdapter(t *testing.T) {}runner := &fakeUpdatesCommandRunner{}- adapter := NewUpdatesMCPAdapter(+ adapter := NewUpdatesToolAdapter(rs,runner,&fakeUpdatesConfig{enabled: false},@@ -510,7 +510,7 @@ func TestUpdatesMCPAdapter(t *testing.T) {if adapter.IsUpdateActionsEnabled() {t.Fatal("expected updates disabled")}- if (&UpdatesMCPAdapter{}).IsUpdateActionsEnabled() != true {+ if (&UpdatesToolAdapter{}).IsUpdateActionsEnabled() != true {t.Fatal("expected updates enabled by default")}diff --git a/internal/ai/tools/control_helpers_test.go b/internal/ai/tools/control_helpers_test.goindex 933b74b3e9..c9f16eee39 100644--- a/internal/ai/tools/control_helpers_test.go+++ b/internal/ai/tools/control_helpers_test.go@@ -5,6 +5,7 @@ import ("strings""testing"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/ai/approval""github.com/stretchr/testify/assert"@@ -53,7 +54,7 @@ func TestIsPreApproved(t *testing.T) {defer approval.SetStore(nil)assert.False(t, isPreApproved(map[string]interface{}{}))- assert.False(t, isPreApproved(map[string]interface{}{"_approval_id": "missing"}))+ assert.False(t, isPreApproved(agentcapabilities.WithApprovalArgument(nil, "missing")))req := &approval.ApprovalRequest{ID: "app-1",@@ -61,11 +62,11 @@ func TestIsPreApproved(t *testing.T) {}require.NoError(t, store.CreateApproval(req))- assert.False(t, isPreApproved(map[string]interface{}{"_approval_id": "app-1"}))+ assert.False(t, isPreApproved(agentcapabilities.WithApprovalArgument(nil, "app-1")))_, err = store.Approve("app-1", "tester")require.NoError(t, err)- assert.True(t, isPreApproved(map[string]interface{}{"_approval_id": "app-1"}))+ assert.True(t, isPreApproved(agentcapabilities.WithApprovalArgument(nil, "app-1")))}func TestConsumeApprovalWithValidation_RejectsCrossOrg(t *testing.T) {@@ -88,7 +89,7 @@ func TestConsumeApprovalWithValidation_RejectsCrossOrg(t *testing.T) {_, err = store.Approve("app-1", "tester")require.NoError(t, err)- ok := consumeApprovalWithValidation(map[string]interface{}{"_approval_id": "app-1"}, "org-b", "ls", "agent", "h1")+ ok := consumeApprovalWithValidation(agentcapabilities.WithApprovalArgument(nil, "app-1"), "org-b", "ls", "agent", "h1")assert.False(t, ok)stored, found := store.GetApproval("app-1")@@ -116,7 +117,7 @@ func TestConsumeApprovalWithValidation_AllowsMatchingOrg(t *testing.T) {_, err = store.Approve("app-2", "tester")require.NoError(t, err)- ok := consumeApprovalWithValidation(map[string]interface{}{"_approval_id": "app-2"}, "org-a", "ls", "agent", "h1")+ ok := consumeApprovalWithValidation(agentcapabilities.WithApprovalArgument(nil, "app-2"), "org-a", "ls", "agent", "h1")assert.True(t, ok)stored, found := store.GetApproval("app-2")diff --git a/internal/ai/tools/control_run_command_test.go b/internal/ai/tools/control_run_command_test.goindex 5c54c5d06f..81651cfd68 100644--- a/internal/ai/tools/control_run_command_test.go+++ b/internal/ai/tools/control_run_command_test.go@@ -7,6 +7,7 @@ import ("testing""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/ai/approval""github.com/rcourtman/pulse-go-rewrite/internal/models"@@ -217,11 +218,10 @@ func TestPulseToolExecutor_ExecuteRunCommand(t *testing.T) {})exec.SetContext("host", "different-session-target", false)- result, err := exec.executeRunCommand(ctx, map[string]interface{}{- "command": "uptime",- "target_host": "tower",- "_approval_id": "approval-1",- })+ result, err := exec.executeRunCommand(ctx, agentcapabilities.WithApprovalArgument(map[string]interface{}{+ "command": "uptime",+ "target_host": "tower",+ }, "approval-1"))require.NoError(t, err)resp := mustParseJSONMap(t, result.Content[0].Text)diff --git a/internal/ai/tools/current_resource.go b/internal/ai/tools/current_resource.goindex 194499516c..4311c16765 100644--- a/internal/ai/tools/current_resource.go+++ b/internal/ai/tools/current_resource.go@@ -4,9 +4,11 @@ import ("fmt""strings""time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")-const currentResourceHandle = "current_resource"+const currentResourceHandle = agentcapabilities.CurrentResourceHandleconst currentResourceSelectionWindow = 365 * 24 * time.Hour@@ -14,20 +16,11 @@ type sortedExplicitResourceProvider interface {GetRecentlyAccessedResourcesSorted(window time.Duration, max int) []string}-func isCurrentResourceReference(value string) bool {- switch strings.ToLower(strings.TrimSpace(value)) {- case currentResourceHandle, "attached_resource", "selected_resource", "this_resource", "redacted by policy":- return true- default:- return false- }-}-// IsCurrentResourceReference reports whether a tool argument is one of the// session-scoped placeholders that must resolve through attached resource// context before execution.func IsCurrentResourceReference(value string) bool {- return isCurrentResourceReference(value)+ return agentcapabilities.IsCurrentResourceReference(value)}// ValidateCurrentResourceAvailable checks whether the session currently has a@@ -169,7 +162,7 @@ func (e *PulseToolExecutor) commandTargetForResolvedResource(resource ResolvedRe}func (e *PulseToolExecutor) resolveCurrentResourceCommandTarget(value string) (string, error) {- if !isCurrentResourceReference(value) {+ if !IsCurrentResourceReference(value) {return strings.TrimSpace(value), nil}resource, err := e.resolveCurrentResource()diff --git a/internal/ai/tools/current_resource_test.go b/internal/ai/tools/current_resource_test.gonew file mode 100644index 0000000000..dd992f8ca2--- /dev/null+++ b/internal/ai/tools/current_resource_test.go@@ -0,0 +1,24 @@+package tools++import (+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+)++func TestCurrentResourceReferenceUsesSharedAgentCapabilityVocabulary(t *testing.T) {+ for _, value := range []string{+ agentcapabilities.CurrentResourceHandle,+ "attached_resource",+ "selected_resource",+ "this_resource",+ "redacted by policy",+ } {+ if !IsCurrentResourceReference(value) {+ t.Fatalf("IsCurrentResourceReference(%q) = false, want shared placeholder", value)+ }+ }+ if IsCurrentResourceReference("resource-1") {+ t.Fatalf("ordinary resource id should not be treated as current_resource")+ }+}diff --git a/internal/ai/tools/discovery_adapter_test.go b/internal/ai/tools/discovery_adapter_test.goindex b0ab97990d..2f25acc522 100644--- a/internal/ai/tools/discovery_adapter_test.go+++ b/internal/ai/tools/discovery_adapter_test.go@@ -50,14 +50,14 @@ func (m *MockDiscoverySource) TriggerDiscovery(ctx context.Context, resourceTypereturn args.Get(0).(DiscoverySourceData), args.Error(1)}-func TestNewDiscoveryMCPAdapter(t *testing.T) {- assert.Nil(t, NewDiscoveryMCPAdapter(nil))- assert.NotNil(t, NewDiscoveryMCPAdapter(&MockDiscoverySource{}))+func TestNewDiscoveryToolAdapter(t *testing.T) {+ assert.Nil(t, NewDiscoveryToolAdapter(nil))+ assert.NotNil(t, NewDiscoveryToolAdapter(&MockDiscoverySource{}))}-func TestDiscoveryMCPAdapter_GetDiscovery(t *testing.T) {+func TestDiscoveryToolAdapter_GetDiscovery(t *testing.T) {mockSource := &MockDiscoverySource{}- adapter := NewDiscoveryMCPAdapter(mockSource)+ adapter := NewDiscoveryToolAdapter(mockSource)expectedData := DiscoverySourceData{ID: "test-id",@@ -85,9 +85,9 @@ func TestDiscoveryMCPAdapter_GetDiscovery(t *testing.T) {mockSource.AssertExpectations(t)}-func TestDiscoveryMCPAdapter_GetDiscovery_Error(t *testing.T) {+func TestDiscoveryToolAdapter_GetDiscovery_Error(t *testing.T) {mockSource := &MockDiscoverySource{}- adapter := NewDiscoveryMCPAdapter(mockSource)+ adapter := NewDiscoveryToolAdapter(mockSource)mockSource.On("GetDiscovery", "invalid").Return(DiscoverySourceData{}, errors.New("not found"))@@ -98,9 +98,9 @@ func TestDiscoveryMCPAdapter_GetDiscovery_Error(t *testing.T) {mockSource.AssertExpectations(t)}-func TestDiscoveryMCPAdapter_GetDiscoveryByResource(t *testing.T) {+func TestDiscoveryToolAdapter_GetDiscoveryByResource(t *testing.T) {mockSource := &MockDiscoverySource{}- adapter := NewDiscoveryMCPAdapter(mockSource)+ adapter := NewDiscoveryToolAdapter(mockSource)expectedData := DiscoverySourceData{ID: "res-id",@@ -117,9 +117,9 @@ func TestDiscoveryMCPAdapter_GetDiscoveryByResource(t *testing.T) {mockSource.AssertExpectations(t)}-func TestDiscoveryMCPAdapter_GetDiscovery_UsesTargetID(t *testing.T) {+func TestDiscoveryToolAdapter_GetDiscovery_UsesTargetID(t *testing.T) {mockSource := &MockDiscoverySource{}- adapter := NewDiscoveryMCPAdapter(mockSource)+ adapter := NewDiscoveryToolAdapter(mockSource)expectedData := DiscoverySourceData{ID: "legacy-id",@@ -137,9 +137,9 @@ func TestDiscoveryMCPAdapter_GetDiscovery_UsesTargetID(t *testing.T) {mockSource.AssertExpectations(t)}-func TestDiscoveryMCPAdapter_ListDiscoveries(t *testing.T) {+func TestDiscoveryToolAdapter_ListDiscoveries(t *testing.T) {mockSource := &MockDiscoverySource{}- adapter := NewDiscoveryMCPAdapter(mockSource)+ adapter := NewDiscoveryToolAdapter(mockSource)list := []DiscoverySourceData{{ID: "d1", ServiceName: "s1"},@@ -157,9 +157,9 @@ func TestDiscoveryMCPAdapter_ListDiscoveries(t *testing.T) {mockSource.AssertExpectations(t)}-func TestDiscoveryMCPAdapter_ListDiscoveriesByType(t *testing.T) {+func TestDiscoveryToolAdapter_ListDiscoveriesByType(t *testing.T) {mockSource := &MockDiscoverySource{}- adapter := NewDiscoveryMCPAdapter(mockSource)+ adapter := NewDiscoveryToolAdapter(mockSource)list := []DiscoverySourceData{{ID: "d1", ResourceType: "vm"}}mockSource.On("ListDiscoveriesByType", "vm").Return(list, nil)@@ -171,9 +171,9 @@ func TestDiscoveryMCPAdapter_ListDiscoveriesByType(t *testing.T) {mockSource.AssertExpectations(t)}-func TestDiscoveryMCPAdapter_ListDiscoveriesByTarget(t *testing.T) {+func TestDiscoveryToolAdapter_ListDiscoveriesByTarget(t *testing.T) {mockSource := &MockDiscoverySource{}- adapter := NewDiscoveryMCPAdapter(mockSource)+ adapter := NewDiscoveryToolAdapter(mockSource)list := []DiscoverySourceData{{ID: "d1", TargetID: "h1"}}mockSource.On("ListDiscoveriesByTarget", "h1").Return(list, nil)@@ -185,9 +185,9 @@ func TestDiscoveryMCPAdapter_ListDiscoveriesByTarget(t *testing.T) {mockSource.AssertExpectations(t)}-func TestDiscoveryMCPAdapter_TriggerDiscovery(t *testing.T) {+func TestDiscoveryToolAdapter_TriggerDiscovery(t *testing.T) {mockSource := &MockDiscoverySource{}- adapter := NewDiscoveryMCPAdapter(mockSource)+ adapter := NewDiscoveryToolAdapter(mockSource)ctx := context.Background()expectedData := DiscoverySourceData{ID: "new1"}@@ -200,9 +200,9 @@ func TestDiscoveryMCPAdapter_TriggerDiscovery(t *testing.T) {mockSource.AssertExpectations(t)}-func TestDiscoveryMCPAdapter_FormatForAIContext(t *testing.T) {+func TestDiscoveryToolAdapter_FormatForAIContext(t *testing.T) {mockSource := &MockDiscoverySource{}- adapter := NewDiscoveryMCPAdapter(mockSource)+ adapter := NewDiscoveryToolAdapter(mockSource)inputs := []*ResourceDiscoveryInfo{{diff --git a/internal/ai/tools/executor.go b/internal/ai/tools/executor.goindex 1b76315e0d..3cf6f8d92c 100644--- a/internal/ai/tools/executor.go+++ b/internal/ai/tools/executor.go@@ -6,6 +6,7 @@ import ("sync""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/recovery"@@ -21,7 +22,7 @@ type UnifiedResourceProvider interface {GetByType(t unifiedresources.ResourceType) []unifiedresources.Resource}-// ServerVersion is the version of the MCP tool implementation+// ServerVersion is the version of the shared Assistant tool implementationconst ServerVersion = "1.0.0"// StateProvider is a type alias for models.SnapshotProvider.@@ -200,7 +201,7 @@ type DiskHealthProvider interface {GetHosts() []*unifiedresources.HostView}-// UpdatesProvider provides Docker update operations for MCP tools+// UpdatesProvider provides Docker update operations for Assistant toolstype UpdatesProvider interface {GetPendingUpdates(hostID string) []ContainerUpdateInfoTriggerUpdateCheck(hostID string) (DockerCommandStatus, error)@@ -425,18 +426,6 @@ type DiscoveryFact struct {Confidence float64 `json:"confidence,omitempty"` // 0-1 confidence for this fact}-// ControlLevel represents the AI's permission level for infrastructure control-type ControlLevel string--const (- // ControlLevelReadOnly - AI can only query, no control tools available- ControlLevelReadOnly ControlLevel = "read_only"- // ControlLevelControlled - AI can execute with per-command approval- ControlLevelControlled ControlLevel = "controlled"- // ControlLevelAutonomous - AI executes without approval (requires Pro license)- ControlLevelAutonomous ControlLevel = "autonomous"-)-// ExecutorConfig holds all dependencies for the tool executortype ExecutorConfig struct {// Required providers@@ -657,18 +646,18 @@ func NewPulseToolExecutor(cfg ExecutorConfig) *PulseToolExecutor {if sp := e.stateProvider; sp != nil {getSnapshot := func() models.StateSnapshot { return sp.ReadSnapshot() }if e.backupProvider == nil {- e.backupProvider = NewBackupMCPAdapter(+ e.backupProvider = NewBackupToolAdapter(func() models.Backups { return getSnapshot().Backups },func() []models.PBSInstance { return getSnapshot().PBSInstances },)}if e.replicationProvider == nil {- e.replicationProvider = NewReplicationMCPAdapter(+ e.replicationProvider = NewReplicationToolAdapter(func() []models.ReplicationJob { return getSnapshot().ReplicationJobs },)}if e.connectionHealth == nil {- e.connectionHealth = NewConnectionHealthMCPAdapter(+ e.connectionHealth = NewConnectionHealthToolAdapter(func() map[string]bool { return getSnapshot().ConnectionHealth },)}@@ -1013,31 +1002,33 @@ func (e *PulseToolExecutor) ListToolGovernance() []ToolGovernanceDescriptor {func (e *PulseToolExecutor) isToolAvailable(name string) bool {switch name {// Check tool availability based on primary requirements- case "pulse_query":+ case agentcapabilities.PulseQueryToolName:return e.hasReadState()- case "pulse_metrics":+ case agentcapabilities.PulseMetricsToolName:return e.hasReadState() || e.metricsHistory != nil || e.baselineProvider != nil || e.patternProvider != nil- case "pulse_storage":+ case agentcapabilities.PulseStorageToolName:return e.hasReadState() || e.unifiedResourceProvider != nil || e.backupProvider != nil || e.diskHealthProvider != nil || e.recoveryPointsProvider != nil- case "pulse_docker":+ case agentcapabilities.PulseDockerToolName:return e.hasReadState() || e.updatesProvider != nil- case "pulse_kubernetes":+ case agentcapabilities.PulseKubernetesToolName:return e.hasCanonicalReadState()- case "pulse_alerts":+ case agentcapabilities.PulseAlertsToolName:return e.alertProvider != nil || e.findingsProvider != nil || e.findingsManager != nil || e.hasReadState()- case "pulse_read":+ case agentcapabilities.PulseReadToolName:return e.agentServer != nil || (e.appContainerReadProvider != nil && e.hasReadState())- case "pulse_control":+ case agentcapabilities.PulseControlToolName:return (e.agentServer != nil || e.appContainerActionProvider != nil) && e.hasReadState()- case "pulse_file_edit":+ case agentcapabilities.PulseFileEditToolName:return e.agentServer != nil- case "pulse_discovery":+ case agentcapabilities.PulseDiscoveryToolName:return e.discoveryProvider != nil- case "pulse_knowledge":+ case agentcapabilities.PulseKnowledgeToolName:return e.knowledgeStoreProvider != nil || e.incidentRecorderProvider != nil || e.eventCorrelatorProvider != nil- case "pulse_pmg":+ case agentcapabilities.PulsePMGToolName:+ return e.hasReadState()+ case agentcapabilities.PulseSummarizeToolName:return e.hasReadState()- case "patrol_report_finding", "patrol_resolve_finding", "patrol_get_findings":+ case agentcapabilities.PatrolReportFindingToolName, agentcapabilities.PatrolResolveFindingToolName, agentcapabilities.PatrolGetFindingsToolName:// Always available when registered; handler checks patrolFindingCreator at runtimereturn e.GetPatrolFindingCreator() != nildefault:@@ -1057,7 +1048,7 @@ func (e *PulseToolExecutor) ExecuteTool(ctx context.Context, name string, args m// registerTools registers all available toolsfunc (e *PulseToolExecutor) registerTools() {- // All tools registered below (12 tools total)+ // All registry tools are registered below in provider exposure order.// pulse_query - search, get, config, topology, list, healthe.registerQueryTools()diff --git a/internal/ai/tools/executor_setters_test.go b/internal/ai/tools/executor_setters_test.goindex 9abdb0afe1..519deb31bc 100644--- a/internal/ai/tools/executor_setters_test.go+++ b/internal/ai/tools/executor_setters_test.go@@ -2,8 +2,11 @@ package toolsimport ("context"+ "os"+ "strings""testing"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources""github.com/stretchr/testify/assert"@@ -198,6 +201,10 @@ func TestToolRegistry_ListTools(t *testing.T) {require.Len(t, readOnly, 1)assert.Equal(t, "read", readOnly[0].Name)+ unknown := registry.ListTools(ControlLevel("bad"))+ require.Len(t, unknown, 1)+ assert.Equal(t, "read", unknown[0].Name)+full := registry.ListTools(ControlLevelControlled)require.Len(t, full, 2)assert.Equal(t, "read", full[0].Name)@@ -207,7 +214,88 @@ func TestToolRegistry_ListTools(t *testing.T) {require.Len(t, governance, 2)assert.Equal(t, ToolActionRead, governance[0].ActionMode)assert.Equal(t, ToolActionWrite, governance[1].ActionMode)- assert.Equal(t, "hidden in read-only mode; approval required in controlled mode", governance[1].ApprovalPolicy)+ assert.Equal(t, ToolApprovalActionPlan, governance[1].ApprovalPolicy)+ assert.Equal(t, "hidden in read-only mode; approval required in controlled mode", governance[1].ApprovalSummary)+}++func TestToolRegistry_ListToolsReturnsIndependentDefinitions(t *testing.T) {+ registry := NewToolRegistry()+ required := []string{"mode"}+ enum := []string{"summary", "detail"}+ properties := map[string]PropertySchema{+ "mode": {Type: "string", Enum: enum},+ }+ registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "read",+ InputSchema: InputSchema{+ Properties: properties,+ Required: required,+ },+ },+ })++ required[0] = "source-mutated"+ enum[0] = "source-mutated"+ sourceMode := properties["mode"]+ sourceMode.Enum[1] = "source-mutated"+ properties["mode"] = sourceMode++ first := registry.ListTools(ControlLevelReadOnly)+ require.Len(t, first, 1)+ assert.Equal(t, "object", first[0].InputSchema.Type)+ assert.Equal(t, "mode", first[0].InputSchema.Required[0])+ assert.Equal(t, "summary", first[0].InputSchema.Properties["mode"].Enum[0])+ assert.Equal(t, "detail", first[0].InputSchema.Properties["mode"].Enum[1])++ first[0].InputSchema.Required[0] = "listed-mutated"+ listedMode := first[0].InputSchema.Properties["mode"]+ listedMode.Enum[0] = "listed-mutated"+ first[0].InputSchema.Properties["mode"] = listedMode++ second := registry.ListTools(ControlLevelReadOnly)+ require.Len(t, second, 1)+ assert.Equal(t, "mode", second[0].InputSchema.Required[0])+ assert.Equal(t, "summary", second[0].InputSchema.Properties["mode"].Enum[0])+}++func TestControlLevelUsesSharedAgentCapabilityVocabulary(t *testing.T) {+ assert.Equal(t, agentcapabilities.ControlLevelReadOnly, ControlLevelReadOnly)+ assert.Equal(t, agentcapabilities.ControlLevelControlled, ControlLevelControlled)+ assert.Equal(t, agentcapabilities.ControlLevelAutonomous, ControlLevelAutonomous)+ assert.False(t, agentcapabilities.ControlLevelAllowsControlTools(ControlLevelReadOnly))+ assert.True(t, agentcapabilities.ControlLevelAllowsControlTools(ControlLevelControlled))+}++func TestToolActionModeUsesSharedAgentCapabilityVocabulary(t *testing.T) {+ assert.Equal(t, agentcapabilities.ActionModeRead, ToolActionRead)+ assert.Equal(t, agentcapabilities.ActionModeMixed, ToolActionMixed)+ assert.Equal(t, agentcapabilities.ActionModeWrite, ToolActionWrite)+}++func TestToolApprovalPolicyUsesSharedAgentCapabilityVocabulary(t *testing.T) {+ assert.Equal(t, agentcapabilities.ApprovalPolicyScopeOnly, ToolApprovalScopeOnly)+ assert.Equal(t, agentcapabilities.ApprovalPolicyActionPlan, ToolApprovalActionPlan)+}++func TestToolGovernanceUsesSharedAgentCapabilityShape(t *testing.T) {+ var shared agentcapabilities.ToolGovernance = ToolGovernance{+ ActionMode: ToolActionMixed,+ ApprovalPolicy: ToolApprovalScopeOnly,+ ApprovalSummary: "read/list actions are safe",+ Summary: "Reads and refreshes state.",+ }+ assert.Equal(t, agentcapabilities.ActionModeMixed, shared.ActionMode)+ assert.Equal(t, agentcapabilities.ApprovalPolicyScopeOnly, shared.ApprovalPolicy)++ var descriptor agentcapabilities.ToolGovernanceDescriptor = ToolGovernanceDescriptor{+ Name: "pulse_discovery",+ ActionMode: ToolActionMixed,+ ApprovalPolicy: ToolApprovalScopeOnly,+ ApprovalSummary: "no approval required",+ }+ assert.Equal(t, "pulse_discovery", descriptor.Name)+ assert.Equal(t, agentcapabilities.ActionModeMixed, descriptor.ActionMode)}func TestToolRegistry_ExecuteControlToolReadOnlyUsesAssistantAndPatrolGuidance(t *testing.T) {@@ -228,12 +316,124 @@ func TestToolRegistry_ExecuteControlToolReadOnlyUsesAssistantAndPatrolGuidance(trequire.NoError(t, err)require.Len(t, result.Content, 1)text := result.Content[0].Text- assert.Equal(t, assistantControlToolsDisabledMessage, text)+ assert.Equal(t, agentcapabilities.ControlToolsDisabledMessage, text)assert.Contains(t, text, "Assistant & Patrol settings")assert.Contains(t, text, "Pulse Assistant Permissions > Control mode")assert.NotContains(t, text, "Settings > Pulse Assistant")}+func TestToolRegistryExecuteNormalizesSharedToolCallParams(t *testing.T) {+ registry := NewToolRegistry()+ var gotArgs map[string]interface{}+ var gotArgsLenBeforeMutation int+ registry.Register(RegisteredTool{+ Definition: Tool{Name: "test_tool"},+ Handler: func(ctx context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ gotArgs = args+ gotArgsLenBeforeMutation = len(args)+ args["resource_id"] = "vm/101"+ args["body"].(map[string]interface{})["note"] = "changed"+ return NewTextResult("ok"), nil+ },+ })+ exec := NewPulseToolExecutor(ExecutorConfig{})++ sourceArgs := map[string]interface{}{+ "resource_id": "vm/100",+ "body": map[string]interface{}{"note": "maintenance"},+ }+ result, err := registry.Execute(context.Background(), exec, " test_tool ", sourceArgs)+ require.NoError(t, err)+ assert.Equal(t, "ok", agentcapabilities.ToolResultText(result))+ assert.Equal(t, "vm/100", sourceArgs["resource_id"], "registry execution must not expose the caller's argument map to handlers")+ assert.Equal(t, "maintenance", sourceArgs["body"].(map[string]interface{})["note"], "registry execution must not expose nested caller arguments to handlers")+ require.NotNil(t, gotArgs)+ assert.Equal(t, "vm/101", gotArgs["resource_id"])+ assert.Equal(t, "changed", gotArgs["body"].(map[string]interface{})["note"])++ gotArgs = nil+ result, err = registry.Execute(context.Background(), exec, " ", nil)+ require.NoError(t, err)+ interpreted := agentcapabilities.InterpretToolResult(result)+ assert.True(t, interpreted.IsError)+ assert.Contains(t, interpreted.Text, "invalid tools/call params: tool name is required")++ registry.Register(RegisteredTool{+ Definition: Tool{Name: "empty_args"},+ Handler: func(ctx context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ gotArgs = args+ gotArgsLenBeforeMutation = len(args)+ return NewTextResult("ok"), nil+ },+ })+ result, err = registry.Execute(context.Background(), exec, "empty_args", nil)+ require.NoError(t, err)+ assert.Equal(t, "ok", agentcapabilities.ToolResultText(result))+ require.NotNil(t, gotArgs)+ assert.Equal(t, 0, gotArgsLenBeforeMutation)+}++func TestToolRegistryExecuteNormalizesSharedToolResult(t *testing.T) {+ registry := NewToolRegistry()+ handlerContent := []Content{{Type: "text", Text: "ok"}}+ registry.Register(RegisteredTool{+ Definition: Tool{Name: "read"},+ Handler: func(ctx context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return CallToolResult{Content: handlerContent}, nil+ },+ })+ registry.Register(RegisteredTool{+ Definition: Tool{Name: "empty"},+ Handler: func(ctx context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return CallToolResult{}, nil+ },+ })++ exec := NewPulseToolExecutor(ExecutorConfig{})+ result, err := registry.Execute(context.Background(), exec, "read", nil)+ require.NoError(t, err)+ assert.Equal(t, "ok", agentcapabilities.ToolResultText(result))+ result.Content[0].Text = "changed"+ assert.Equal(t, "ok", handlerContent[0].Text)++ empty, err := registry.Execute(context.Background(), exec, "empty", nil)+ require.NoError(t, err)+ assert.NotNil(t, empty.Content)+ assert.Empty(t, empty.Content)+}++func TestToolRegistryExecuteUsesSharedRegistryExecutionResults(t *testing.T) {+ src, err := os.ReadFile("registry.go")+ require.NoError(t, err)+ text := string(src)++ for _, fragment := range []string{+ "agentcapabilities.PrepareToolRegistryExecution(name, args)",+ "agentcapabilities.NewUnknownToolResult(name)",+ "agentcapabilities.NewControlToolsDisabledToolResult()",+ } {+ assert.Contains(t, text, fragment)+ }+ for _, fragment := range []string{+ "PrepareMCPToolRegistryExecution",+ "NewUnknownMCPToolResult",+ "NewControlToolsDisabledMCPToolResult",+ } {+ if strings.Contains(text, fragment) {+ t.Fatalf("native registry execution must use neutral shared helpers; found %s", fragment)+ }+ }+ for _, fragment := range []string{+ "invalid tools/call params:",+ "unknown tool: %s",+ "agentcapabilities.ControlToolsDisabledMessage",+ } {+ if strings.Contains(text, fragment) {+ t.Fatalf("registry execution must use shared registry result helpers; found %s", fragment)+ }+ }+}+func containsTool(tools []Tool, name string) bool {for _, tool := range tools {if tool.Name == name {diff --git a/internal/ai/tools/governance_manifest.go b/internal/ai/tools/governance_manifest.gonew file mode 100644index 0000000000..7b43a6e3d9--- /dev/null+++ b/internal/ai/tools/governance_manifest.go@@ -0,0 +1,82 @@+package tools++import (+ "strings"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+)++// ToolGovernanceSurface names the Pulse Intelligence surface requesting a+// registry-owned fallback manifest.+type ToolGovernanceSurface string++const (+ ToolGovernanceSurfacePulseIntelligence ToolGovernanceSurface = "pulse_intelligence"+ ToolGovernanceSurfacePulseAssistant ToolGovernanceSurface = "pulse_assistant"+ ToolGovernanceSurfacePulsePatrol ToolGovernanceSurface = "pulse_patrol"+)++// CanonicalToolGovernance returns the complete registry-owned governance+// descriptors available at a control level. Runtime turns should prefer+// PulseToolExecutor.ListToolGovernance so provider availability is still+// honored.+func CanonicalToolGovernance(controlLevel ControlLevel) []ToolGovernanceDescriptor {+ e := NewPulseToolExecutor(ExecutorConfig{})+ return e.registry.ListToolGovernance(controlLevel)+}++// CanonicalToolGovernanceForSurface returns the registry-owned fallback+// manifest projected for one Pulse Intelligence surface. The registry remains+// the source of truth; this helper only removes tools that belong to a+// different first-party runtime surface when no live executor is attached.+func CanonicalToolGovernanceForSurface(controlLevel ControlLevel, surface ToolGovernanceSurface) []ToolGovernanceDescriptor {+ governance := CanonicalToolGovernance(controlLevel)+ if len(governance) == 0 {+ return governance+ }++ projected := make([]ToolGovernanceDescriptor, 0, len(governance))+ for _, tool := range governance {+ if !toolGovernanceSurfaceIncludesTool(surface, tool.Name) {+ continue+ }+ projected = append(projected, tool)+ }+ return projected+}++// CanonicalToolGovernanceForManifestSurface returns registry-owned fallback+// governance for a manifest-declared Pulse Intelligence surface. The registry+// remains the source of tool governance; the shared manifest decides whether+// that operator surface may advertise tools at all.+func CanonicalToolGovernanceForManifestSurface(controlLevel ControlLevel, manifest agentcapabilities.Manifest, surfaceID string) []ToolGovernanceDescriptor {+ affordances, _ := agentcapabilities.ManifestSurfaceAffordances(manifest, surfaceID)+ if !affordances.Tools {+ return []ToolGovernanceDescriptor{}+ }+ return CanonicalToolGovernanceForSurface(controlLevel, toolGovernanceSurfaceForManifestSurfaceID(surfaceID))+}++func toolGovernanceSurfaceForManifestSurfaceID(surfaceID string) ToolGovernanceSurface {+ switch strings.TrimSpace(surfaceID) {+ case agentcapabilities.SurfaceIDPulseAssistant:+ return ToolGovernanceSurfacePulseAssistant+ default:+ return ToolGovernanceSurfacePulseIntelligence+ }+}++func toolGovernanceSurfaceIncludesTool(surface ToolGovernanceSurface, name string) bool {+ switch surface {+ case ToolGovernanceSurfacePulseAssistant:+ return !isPatrolRuntimeTool(name)+ case ToolGovernanceSurfacePulseIntelligence, ToolGovernanceSurfacePulsePatrol, "":+ return true+ default:+ return true+ }+}++func isPatrolRuntimeTool(name string) bool {+ return strings.HasPrefix(strings.TrimSpace(name), "patrol_")+}diff --git a/internal/ai/tools/governance_manifest_test.go b/internal/ai/tools/governance_manifest_test.gonew file mode 100644index 0000000000..d5d5f85185--- /dev/null+++ b/internal/ai/tools/governance_manifest_test.go@@ -0,0 +1,117 @@+package tools++import (+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+)++func TestCanonicalToolGovernanceMirrorsRegisteredRegistry(t *testing.T) {+ exec := NewPulseToolExecutor(ExecutorConfig{})+ registryGovernance := exec.registry.ListToolGovernance(ControlLevelControlled)+ canonical := CanonicalToolGovernance(ControlLevelControlled)++ if len(canonical) != len(registryGovernance) {+ t.Fatalf("canonical governance length = %d, want %d", len(canonical), len(registryGovernance))+ }+ for i := range registryGovernance {+ if canonical[i] != registryGovernance[i] {+ t.Fatalf("canonical governance[%d] = %#v, want registry descriptor %#v", i, canonical[i], registryGovernance[i])+ }+ }+}++func TestCanonicalToolGovernanceForAssistantSurfaceMirrorsRegisteredRegistry(t *testing.T) {+ exec := NewPulseToolExecutor(ExecutorConfig{})+ registryGovernance := exec.registry.ListToolGovernance(ControlLevelControlled)+ canonical := CanonicalToolGovernanceForSurface(ControlLevelControlled, ToolGovernanceSurfacePulseAssistant)++ filtered := make([]ToolGovernanceDescriptor, 0, len(registryGovernance))+ for _, tool := range registryGovernance {+ switch tool.Name {+ case agentcapabilities.PatrolReportFindingToolName, agentcapabilities.PatrolResolveFindingToolName, agentcapabilities.PatrolGetFindingsToolName:+ continue+ default:+ filtered = append(filtered, tool)+ }+ }++ if len(canonical) != len(filtered) {+ t.Fatalf("canonical assistant governance length = %d, want %d", len(canonical), len(filtered))+ }+ for i := range filtered {+ if canonical[i] != filtered[i] {+ t.Fatalf("canonical assistant governance[%d] = %#v, want registry descriptor %#v", i, canonical[i], filtered[i])+ }+ }+}++func TestCanonicalToolGovernanceForManifestSurfaceUsesSurfaceAffordances(t *testing.T) {+ manifest := agentcapabilities.CanonicalManifest()+ assistant := CanonicalToolGovernanceForManifestSurface(+ ControlLevelControlled,+ manifest,+ agentcapabilities.SurfaceIDPulseAssistant,+ )+ canonicalAssistant := CanonicalToolGovernanceForSurface(ControlLevelControlled, ToolGovernanceSurfacePulseAssistant)+ if len(assistant) != len(canonicalAssistant) {+ t.Fatalf("manifest assistant governance length = %d, want %d", len(assistant), len(canonicalAssistant))+ }+ for i := range canonicalAssistant {+ if assistant[i] != canonicalAssistant[i] {+ t.Fatalf("manifest assistant governance[%d] = %#v, want %#v", i, assistant[i], canonicalAssistant[i])+ }+ }++ toolsDisabled := manifest+ for i := range toolsDisabled.SurfaceContract.OperatorSurfaces {+ if toolsDisabled.SurfaceContract.OperatorSurfaces[i].ID == agentcapabilities.SurfaceIDPulseAssistant {+ toolsDisabled.SurfaceContract.OperatorSurfaces[i].Affordances = agentcapabilities.SurfaceAffordanceContract{+ InteractiveQuestions: true,+ }+ }+ }+ if disabled := CanonicalToolGovernanceForManifestSurface(ControlLevelControlled, toolsDisabled, agentcapabilities.SurfaceIDPulseAssistant); len(disabled) != 0 {+ t.Fatalf("tools-disabled manifest assistant governance = %+v, want none", disabled)+ }+}++func TestCanonicalToolGovernanceForSurfaceFiltersAssistantOnlyRuntime(t *testing.T) {+ assistant := CanonicalToolGovernanceForSurface(ControlLevelControlled, ToolGovernanceSurfacePulseAssistant)+ patrol := CanonicalToolGovernanceForSurface(ControlLevelControlled, ToolGovernanceSurfacePulsePatrol)+ core := CanonicalToolGovernanceForSurface(ControlLevelControlled, ToolGovernanceSurfacePulseIntelligence)++ if len(patrol) != len(core) {+ t.Fatalf("patrol fallback governance length = %d, want full core registry length %d", len(patrol), len(core))+ }++ foundPatrolToolInCore := false+ for _, tool := range core {+ switch tool.Name {+ case agentcapabilities.PatrolReportFindingToolName, agentcapabilities.PatrolResolveFindingToolName, agentcapabilities.PatrolGetFindingsToolName:+ foundPatrolToolInCore = true+ }+ }+ if !foundPatrolToolInCore {+ t.Fatal("expected core governance to include Patrol runtime tools")+ }++ for _, tool := range assistant {+ switch tool.Name {+ case agentcapabilities.PatrolReportFindingToolName, agentcapabilities.PatrolResolveFindingToolName, agentcapabilities.PatrolGetFindingsToolName:+ t.Fatalf("Assistant fallback governance exposed Patrol runtime tool %s", tool.Name)+ }+ }+}++func TestCanonicalToolGovernanceForAssistantSurfaceHonorsControlLevel(t *testing.T) {+ governance := CanonicalToolGovernanceForSurface(ControlLevelReadOnly, ToolGovernanceSurfacePulseAssistant)+ for _, tool := range governance {+ if tool.RequireControl {+ t.Fatalf("read-only assistant governance exposed control tool %#v", tool)+ }+ if tool.Name == agentcapabilities.PulseControlToolName || tool.Name == agentcapabilities.PulseFileEditToolName {+ t.Fatalf("read-only assistant governance exposed %s", tool.Name)+ }+ }+}diff --git a/internal/ai/tools/kubernetes_control_test.go b/internal/ai/tools/kubernetes_control_test.goindex 5599f76d6f..b3cc154b74 100644--- a/internal/ai/tools/kubernetes_control_test.go+++ b/internal/ai/tools/kubernetes_control_test.go@@ -4,6 +4,7 @@ import ("context""testing"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/ai/approval""github.com/rcourtman/pulse-go-rewrite/internal/models"@@ -491,12 +492,11 @@ func TestExecuteKubernetesExec(t *testing.T) {cfg.ControlLevel = ControlLevelControlled})- result, err := exec.executeKubernetesExec(ctx, map[string]interface{}{- "cluster": "cluster-1",- "pod": "nginx-pod",- "command": "cat /etc/nginx/nginx.conf",- "_approval_id": "approval-1",- })+ result, err := exec.executeKubernetesExec(ctx, agentcapabilities.WithApprovalArgument(map[string]interface{}{+ "cluster": "cluster-1",+ "pod": "nginx-pod",+ "command": "cat /etc/nginx/nginx.conf",+ }, "approval-1"))require.NoError(t, err)assert.Contains(t, result.Content[0].Text, "APPROVAL_REQUIRED")mockAgent.AssertNotCalled(t, "ExecuteCommand", mock.Anything, mock.Anything, mock.Anything)@@ -542,23 +542,21 @@ func TestExecuteKubernetesExec(t *testing.T) {cfg.ControlLevel = ControlLevelControlled})- result, err := exec.executeKubernetesExec(ctx, map[string]interface{}{- "cluster": "cluster-1",- "pod": "nginx-pod",- "command": "cat /etc/nginx/nginx.conf",- "_approval_id": "approval-2",- })+ result, err := exec.executeKubernetesExec(ctx, agentcapabilities.WithApprovalArgument(map[string]interface{}{+ "cluster": "cluster-1",+ "pod": "nginx-pod",+ "command": "cat /etc/nginx/nginx.conf",+ }, "approval-2"))require.NoError(t, err)assert.NotContains(t, result.Content[0].Text, "APPROVAL_REQUIRED")mockAgent.AssertExpectations(t)// Approval is single-use; second attempt should not bypass.- result, err = exec.executeKubernetesExec(ctx, map[string]interface{}{- "cluster": "cluster-1",- "pod": "nginx-pod",- "command": "cat /etc/nginx/nginx.conf",- "_approval_id": "approval-2",- })+ result, err = exec.executeKubernetesExec(ctx, agentcapabilities.WithApprovalArgument(map[string]interface{}{+ "cluster": "cluster-1",+ "pod": "nginx-pod",+ "command": "cat /etc/nginx/nginx.conf",+ }, "approval-2"))require.NoError(t, err)assert.Contains(t, result.Content[0].Text, "APPROVAL_REQUIRED")})diff --git a/internal/ai/tools/names.go b/internal/ai/tools/names.goindex b59b010e1c..239ed7935c 100644--- a/internal/ai/tools/names.go+++ b/internal/ai/tools/names.go@@ -1,8 +1,9 @@package toolsimport (- "strings""sync"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")// IsKnownToolName reports whether name is one of the canonical Pulse tool@@ -13,9 +14,7 @@ func IsKnownToolName(name string) bool {if name == "" {return false}- initKnownToolNames()- _, ok := knownToolNamesSet[name]- return ok+ return AssistantProviderToolNameCatalog().Has(name)}// IsKnownToolNamePrefix reports whether prefix can still become a canonical@@ -26,29 +25,25 @@ func IsKnownToolNamePrefix(prefix string) bool {if prefix == "" {return false}+ return AssistantProviderToolNameCatalog().HasPrefix(prefix)+}++// AssistantProviderToolNameCatalog returns the registry-backed provider-tool+// name catalog for the native Assistant surface, including native provider+// tools such as pulse_question.+func AssistantProviderToolNameCatalog() agentcapabilities.ProviderToolNameCatalog {initKnownToolNames()- for _, name := range knownToolNamesList {- if strings.HasPrefix(name, prefix) {- return true- }- }- return false+ return knownToolNameCatalog}var (- knownToolNamesOnce sync.Once- knownToolNamesList []string- knownToolNamesSet map[string]struct{}+ knownToolNamesOnce sync.Once+ knownToolNameCatalog agentcapabilities.ProviderToolNameCatalog)func initKnownToolNames() {knownToolNamesOnce.Do(func() {e := NewPulseToolExecutor(ExecutorConfig{})- names := e.registry.allNames()- knownToolNamesList = names- knownToolNamesSet = make(map[string]struct{}, len(names))- for _, n := range names {- knownToolNamesSet[n] = struct{}{}- }+ knownToolNameCatalog = agentcapabilities.NewAssistantProviderToolNameCatalog(e.registry.allNames())})}diff --git a/internal/ai/tools/names_test.go b/internal/ai/tools/names_test.goindex d394381ec5..cb37f1d238 100644--- a/internal/ai/tools/names_test.go+++ b/internal/ai/tools/names_test.go@@ -1,28 +1,34 @@package tools-import "testing"+import (+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+)func TestKnownToolNamesIncludesRegisteredTools(t *testing.T) {// Spot-check a representative subset of canonical names that should// always be registered. Drift here means registerTools() lost a tool- // or KnownToolNames() stopped reading from the canonical registry.+ // or IsKnownToolName() stopped reading from the canonical registry-backed+ // shared provider-tool name catalog.expected := []string{- "pulse_query",- "pulse_discovery",- "pulse_read",- "pulse_summarize",- "pulse_control",- "pulse_metrics",- "pulse_storage",- "pulse_docker",- "pulse_kubernetes",- "pulse_alerts",- "pulse_file_edit",- "pulse_knowledge",- "pulse_pmg",- "patrol_report_finding",- "patrol_resolve_finding",- "patrol_get_findings",+ agentcapabilities.PulseQueryToolName,+ agentcapabilities.PulseDiscoveryToolName,+ agentcapabilities.PulseReadToolName,+ agentcapabilities.PulseSummarizeToolName,+ agentcapabilities.PulseControlToolName,+ agentcapabilities.PulseMetricsToolName,+ agentcapabilities.PulseStorageToolName,+ agentcapabilities.PulseDockerToolName,+ agentcapabilities.PulseKubernetesToolName,+ agentcapabilities.PulseAlertsToolName,+ agentcapabilities.PulseFileEditToolName,+ agentcapabilities.PulseKnowledgeToolName,+ agentcapabilities.PulsePMGToolName,+ agentcapabilities.PulseQuestionToolName,+ agentcapabilities.PatrolReportFindingToolName,+ agentcapabilities.PatrolResolveFindingToolName,+ agentcapabilities.PatrolGetFindingsToolName,}for _, name := range expected {if !IsKnownToolName(name) {@@ -50,6 +56,7 @@ func TestIsKnownToolNamePrefix(t *testing.T) {cases := []string{"p","pulse_",+ "pulse_q","pulse_re","pulse_read","patrol_",diff --git a/internal/ai/tools/protocol.go b/internal/ai/tools/protocol.goindex f6a17f6e15..39a3c3b2d9 100644--- a/internal/ai/tools/protocol.go+++ b/internal/ai/tools/protocol.go@@ -1,318 +1,87 @@package tools-import (- "encoding/json"-)--// JSON-RPC 2.0 types for MCP protocol--// Request represents a JSON-RPC request-type Request struct {- JSONRPC string `json:"jsonrpc"`- ID interface{} `json:"id,omitempty"`- Method string `json:"method"`- Params json.RawMessage `json:"params,omitempty"`-}--// Response represents a JSON-RPC response-type Response struct {- JSONRPC string `json:"jsonrpc"`- ID interface{} `json:"id,omitempty"`- Result json.RawMessage `json:"result,omitempty"`- Error *Error `json:"error,omitempty"`-}--// Error represents a JSON-RPC error-type Error struct {- Code int `json:"code"`- Message string `json:"message"`- Data interface{} `json:"data,omitempty"`-}--// Standard JSON-RPC error codes-const (- ErrParse = -32700- ErrInvalidRequest = -32600- ErrMethodNotFound = -32601- ErrInvalidParams = -32602- ErrInternal = -32603-)--// MCP-specific types--// ServerInfo describes the MCP server-type ServerInfo struct {- Name string `json:"name"`- Version string `json:"version"`- Capabilities Capabilities `json:"capabilities,omitempty"`-}--// Capabilities describes what the server supports-type Capabilities struct {- Tools *ToolsCapability `json:"tools,omitempty"`- Resources *ResourcesCapability `json:"resources,omitempty"`- Prompts *PromptsCapability `json:"prompts,omitempty"`-}--// ToolsCapability describes tool support-type ToolsCapability struct {- ListChanged bool `json:"listChanged,omitempty"`-}--// ResourcesCapability describes resource support-type ResourcesCapability struct {- Subscribe bool `json:"subscribe,omitempty"`- ListChanged bool `json:"listChanged,omitempty"`-}--// PromptsCapability describes prompt support-type PromptsCapability struct {- ListChanged bool `json:"listChanged,omitempty"`-}--// InitializeParams are the params for the initialize method-type InitializeParams struct {- ProtocolVersion string `json:"protocolVersion"`- Capabilities Capabilities `json:"capabilities"`- ClientInfo ClientInfo `json:"clientInfo"`-}--// ClientInfo describes the client-type ClientInfo struct {- Name string `json:"name"`- Version string `json:"version"`-}--// InitializeResult is the result of the initialize method-type InitializeResult struct {- ProtocolVersion string `json:"protocolVersion"`- Capabilities Capabilities `json:"capabilities"`- ServerInfo ServerInfo `json:"serverInfo"`-}--// Tool describes an available tool-type Tool struct {- Name string `json:"name"`- Description string `json:"description,omitempty"`- InputSchema InputSchema `json:"inputSchema"`-}+import "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"-// InputSchema describes the expected input for a tool-type InputSchema struct {- Type string `json:"type"` // Always "object"- Properties map[string]PropertySchema `json:"properties"`- Required []string `json:"required,omitempty"`-}--// PropertySchema describes a property in the input schema-type PropertySchema struct {- Type string `json:"type"`- Description string `json:"description,omitempty"`- Enum []string `json:"enum,omitempty"`- Default interface{} `json:"default,omitempty"`-}--// ListToolsResult is the result of tools/list-type ListToolsResult struct {- Tools []Tool `json:"tools"`-}--// CallToolParams are the params for tools/call-type CallToolParams struct {- Name string `json:"name"`- Arguments map[string]interface{} `json:"arguments,omitempty"`-}--// CallToolResult is the result of tools/call-type CallToolResult struct {- Content []Content `json:"content"`- IsError bool `json:"isError,omitempty"`-}--// Content represents content in a tool result-type Content struct {- Type string `json:"type"` // "text", "image", "resource"- Text string `json:"text,omitempty"`- MimeType string `json:"mimeType,omitempty"`- Data string `json:"data,omitempty"` // base64 for images- URI string `json:"uri,omitempty"` // for resources-}--// Resource describes an available resource-type Resource struct {- URI string `json:"uri"`- Name string `json:"name"`- Description string `json:"description,omitempty"`- MimeType string `json:"mimeType,omitempty"`-}--// ListResourcesResult is the result of resources/list-type ListResourcesResult struct {- Resources []Resource `json:"resources"`-}+// Tool describes an available Assistant registry tool. The shape aliases the+// shared Pulse Intelligence tool schema so provider projection and external+// agent adapters cannot drift.+type Tool = agentcapabilities.Tool-// ReadResourceParams are the params for resources/read-type ReadResourceParams struct {- URI string `json:"uri"`-}--// ReadResourceResult is the result of resources/read-type ReadResourceResult struct {- Contents []ResourceContent `json:"contents"`-}+// InputSchema describes the expected input for a tool.+type InputSchema = agentcapabilities.InputSchema-// ResourceContent is the content of a resource-type ResourceContent struct {- URI string `json:"uri"`- MimeType string `json:"mimeType,omitempty"`- Text string `json:"text,omitempty"`- Blob string `json:"blob,omitempty"` // base64-}+// PropertySchema describes a property in the input schema.+type PropertySchema = agentcapabilities.PropertySchema-// Prompt describes an available prompt template-type Prompt struct {- Name string `json:"name"`- Description string `json:"description,omitempty"`- Arguments []PromptArgument `json:"arguments,omitempty"`-}+// CallToolParams are the shared params for registry tool calls.+type CallToolParams = agentcapabilities.ToolCallParams-// PromptArgument describes an argument for a prompt-type PromptArgument struct {- Name string `json:"name"`- Description string `json:"description,omitempty"`- Required bool `json:"required,omitempty"`-}+// CallToolResult is the shared result envelope returned by Assistant registry+// tools.+type CallToolResult = agentcapabilities.ToolResult-// ListPromptsResult is the result of prompts/list-type ListPromptsResult struct {- Prompts []Prompt `json:"prompts"`-}+// Content represents content in a shared tool result.+type Content = agentcapabilities.ToolContent-// GetPromptParams are the params for prompts/get-type GetPromptParams struct {- Name string `json:"name"`- Arguments map[string]string `json:"arguments,omitempty"`-}+// ToolResponse is the shared structured tool-result envelope used for+// machine-readable blocked/failed Assistant registry tool outcomes.+type ToolResponse = agentcapabilities.ToolResponse-// GetPromptResult is the result of prompts/get-type GetPromptResult struct {- Description string `json:"description,omitempty"`- Messages []PromptMessage `json:"messages"`-}--// PromptMessage is a message in a prompt-type PromptMessage struct {- Role string `json:"role"` // "user" or "assistant"- Content Content `json:"content"`-}--// ToolResponse is a consistent envelope for tool results.-// All tool results should use this structure for predictable parsing.-type ToolResponse struct {- OK bool `json:"ok"` // true if tool succeeded- Data interface{} `json:"data,omitempty"` // result data if ok=true- Error *ToolError `json:"error,omitempty"` // error details if ok=false- Meta map[string]interface{} `json:"meta,omitempty"` // optional metadata-}--// ToolError provides consistent error structure for tool failures.-// Use Blocked=true for policy/validation blocks, Failed=true for runtime errors.-type ToolError struct {- Code string `json:"code"` // Error code (e.g., "STRICT_RESOLUTION", "NOT_FOUND")- Message string `json:"message"` // Human-readable message- Blocked bool `json:"blocked,omitempty"` // True if blocked by policy/validation- Failed bool `json:"failed,omitempty"` // True if runtime failure- Retryable bool `json:"retryable,omitempty"` // True if auto-retry might succeed- Details map[string]interface{} `json:"details,omitempty"` // Additional context-}+// ToolError is the shared structured failure shape for ToolResponse.+type ToolError = agentcapabilities.ToolError// Common error codesconst (- ErrCodeStrictResolution = "STRICT_RESOLUTION"- ErrCodeNotFound = "NOT_FOUND"- ErrCodeActionNotAllowed = "ACTION_NOT_ALLOWED"- ErrCodePolicyBlocked = "POLICY_BLOCKED"- ErrCodeApprovalRequired = "APPROVAL_REQUIRED"- ErrCodeInvalidInput = "INVALID_INPUT"- ErrCodeExecutionFailed = "EXECUTION_FAILED"- ErrCodeNoAgent = "NO_AGENT"+ ErrCodeFSMBlocked = agentcapabilities.ErrCodeFSMBlocked+ ErrCodeStrictResolution = agentcapabilities.ErrCodeStrictResolution+ ErrCodeRoutingMismatch = agentcapabilities.ErrCodeRoutingMismatch+ ErrCodeExecutionContextUnavailable = agentcapabilities.ErrCodeExecutionContextUnavailable+ ErrCodeNotFound = agentcapabilities.ErrCodeNotFound+ ErrCodeActionNotAllowed = agentcapabilities.ErrCodeActionNotAllowed+ ErrCodePolicyBlocked = agentcapabilities.ErrCodePolicyBlocked+ ErrCodeApprovalRequired = agentcapabilities.ErrCodeApprovalRequired+ ErrCodeInvalidInput = agentcapabilities.ErrCodeInvalidInput+ ErrCodeExecutionFailed = agentcapabilities.ErrCodeExecutionFailed+ ErrCodeNoAgent = agentcapabilities.ErrCodeNoAgent)// NewToolBlockedError creates a policy/validation blocked errorfunc NewToolBlockedError(code, message string, details map[string]interface{}) ToolResponse {- return ToolResponse{- OK: false,- Error: &ToolError{- Code: code,- Message: message,- Blocked: true,- Details: details,- },- }+ return agentcapabilities.NewToolBlockedError(code, message, details)}// Helper functions// NewTextContent creates a text content objectfunc NewTextContent(text string) Content {- return Content{- Type: "text",- Text: text,- }+ return agentcapabilities.NewToolTextContent(text)}// NewErrorResult creates an error tool resultfunc NewErrorResult(err error) CallToolResult {- return CallToolResult{- Content: []Content{NewTextContent(err.Error())},- IsError: true,- }+ return agentcapabilities.NewToolErrorResult(err)}// NewTextResult creates a successful text tool resultfunc NewTextResult(text string) CallToolResult {- return CallToolResult{- Content: []Content{NewTextContent(text)},- IsError: false,- }+ return agentcapabilities.NewToolTextResult(text)}// NewJSONResult creates a successful JSON tool result// The data is marshaled to JSON and returned as text contentfunc NewJSONResult(data interface{}) CallToolResult {- b, err := json.Marshal(data)- if err != nil {- return NewErrorResult(err)- }- return CallToolResult{- Content: []Content{NewTextContent(string(b))},- IsError: false,- }+ return agentcapabilities.NewToolJSONResult(data)}// NewJSONResultWithIsError creates a JSON tool result with explicit error state.// Use this when you want to return structured JSON to the model/UI while still// signalling a failure to the agentic loop (IsError=true).func NewJSONResultWithIsError(data interface{}, isError bool) CallToolResult {- b, err := json.Marshal(data)- if err != nil {- return NewErrorResult(err)- }- return CallToolResult{- Content: []Content{NewTextContent(string(b))},- IsError: isError,- }+ return agentcapabilities.NewToolJSONResultWithIsError(data, isError)}// NewToolResponseResult creates a CallToolResult from a ToolResponse-// This provides the consistent envelope while maintaining MCP protocol compatibility+// This provides the consistent shared tool-result envelope.func NewToolResponseResult(resp ToolResponse) CallToolResult {- b, err := json.Marshal(resp)- if err != nil {- return NewErrorResult(err)- }- return CallToolResult{- Content: []Content{NewTextContent(string(b))},- IsError: !resp.OK,- }+ return agentcapabilities.NewToolResponseResult(resp)}diff --git a/internal/ai/tools/protocol_test.go b/internal/ai/tools/protocol_test.gonew file mode 100644index 0000000000..d4d0d0e046--- /dev/null+++ b/internal/ai/tools/protocol_test.go@@ -0,0 +1,80 @@+package tools++import (+ "strings"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+)++func TestAssistantToolResultWrapsSharedEnvelope(t *testing.T) {+ var content agentcapabilities.ToolContent = NewTextContent("ok")+ if content.Type != "text" || content.Text != "ok" {+ t.Fatalf("NewTextContent returned unexpected shared content: %+v", content)+ }++ result := NewJSONResultWithIsError(map[string]string{"error": "policy_blocked"}, true)+ var shared agentcapabilities.ToolResult = result+ if !shared.IsError {+ t.Fatal("Assistant JSON tool result must preserve shared isError=true")+ }+ if len(shared.Content) != 1 || !strings.Contains(shared.Content[0].Text, `"error":"policy_blocked"`) {+ t.Fatalf("Assistant JSON tool result did not use shared content envelope: %+v", shared)+ }+}++func TestAssistantCallToolParamsUseSharedAgentCapabilityTypes(t *testing.T) {+ var params agentcapabilities.ToolCallParams = CallToolParams{+ Name: "pulse_read",+ Arguments: map[string]any{"resource_id": "vm:101"},+ }+ if params.Name != "pulse_read" || params.Arguments["resource_id"] != "vm:101" {+ t.Fatalf("CallToolParams must alias shared call params: %+v", params)+ }+}++func TestAssistantToolResponseUsesSharedAgentCapabilityEnvelope(t *testing.T) {+ var shared agentcapabilities.ToolResponse = ToolResponse{+ OK: false,+ Error: &ToolError{+ Code: ErrCodeRoutingMismatch,+ Message: "choose the child resource",+ Blocked: true,+ },+ }+ if shared.Error == nil || shared.Error.Code != agentcapabilities.ErrCodeRoutingMismatch {+ t.Fatalf("ToolResponse must alias shared agent capability envelope: %+v", shared)+ }+ if ErrCodeFSMBlocked != agentcapabilities.ErrCodeFSMBlocked {+ t.Fatalf("FSM-blocked error code = %q, want shared %q", ErrCodeFSMBlocked, agentcapabilities.ErrCodeFSMBlocked)+ }+ if ErrCodeExecutionContextUnavailable != agentcapabilities.ErrCodeExecutionContextUnavailable {+ t.Fatalf("execution-context error code = %q, want shared %q", ErrCodeExecutionContextUnavailable, agentcapabilities.ErrCodeExecutionContextUnavailable)+ }++ result := NewToolResponseResult(NewToolBlockedError(ErrCodeActionNotAllowed, "not allowed", nil))+ var toolResult agentcapabilities.ToolResult = result+ if !toolResult.IsError {+ t.Fatal("blocked shared ToolResponse must preserve isError=true")+ }+ if len(toolResult.Content) != 1 || !strings.Contains(toolResult.Content[0].Text, `"code":"ACTION_NOT_ALLOWED"`) {+ t.Fatalf("blocked ToolResponse was not encoded through shared result: %+v", toolResult)+ }+}++func TestAssistantToolSchemaUsesSharedAgentCapabilityTypes(t *testing.T) {+ var shared agentcapabilities.Tool = Tool{+ Name: "pulse_read",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ "resourceId": {Type: "string"},+ },+ Required: []string{"resourceId"},+ },+ }++ if shared.InputSchema.Properties["resourceId"].Type != "string" {+ t.Fatalf("Assistant Tool must alias shared agent capability schema: %+v", shared)+ }+}diff --git a/internal/ai/tools/provider_projection.go b/internal/ai/tools/provider_projection.gonew file mode 100644index 0000000000..76d98b3967--- /dev/null+++ b/internal/ai/tools/provider_projection.go@@ -0,0 +1,26 @@+package tools++import "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"++// AssistantProviderTools returns the provider-facing tool declarations for the+// native in-app Assistant surface. It is the executor-owned projection boundary+// that keeps runtime tool availability, registry governance descriptors, and+// Assistant-native interaction tools composed in one place.+func (e *PulseToolExecutor) AssistantProviderTools(opts agentcapabilities.AssistantProviderToolOptions) []agentcapabilities.ProviderTool {+ if e == nil {+ return agentcapabilities.ProjectPulseAssistantProviderTools(agentcapabilities.CanonicalManifest(), nil, nil, opts)+ }+ return agentcapabilities.ProjectPulseAssistantProviderTools(agentcapabilities.CanonicalManifest(), e.ListTools(), e.ListToolGovernance(), opts)+}++// AssistantSurfaceToolContract returns the native Assistant surface summary+// over the shared Pulse Intelligence Core. The executor owns the runtime+// registry and availability rules; agentcapabilities owns the surface projection+// contract shared with MCP and future external-agent adapters.+func (e *PulseToolExecutor) AssistantSurfaceToolContract(opts agentcapabilities.AssistantProviderToolOptions) agentcapabilities.SurfaceToolContract {+ contract, _ := agentcapabilities.ProjectPulseAssistantSurfaceToolContract(+ agentcapabilities.CanonicalManifest().SurfaceContract,+ e.AssistantProviderTools(opts),+ )+ return contract+}diff --git a/internal/ai/tools/provider_projection_test.go b/internal/ai/tools/provider_projection_test.gonew file mode 100644index 0000000000..5178dd4c5d--- /dev/null+++ b/internal/ai/tools/provider_projection_test.go@@ -0,0 +1,170 @@+package tools++import (+ "os"+ "strings"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+)++func providerToolNameSet(list []agentcapabilities.ProviderTool) map[string]bool {+ set := make(map[string]bool, len(list))+ for _, tool := range list {+ set[tool.Name] = true+ }+ return set+}++func providerToolByName(list []agentcapabilities.ProviderTool, name string) (agentcapabilities.ProviderTool, bool) {+ for _, tool := range list {+ if tool.Name == name {+ return tool, true+ }+ }+ return agentcapabilities.ProviderTool{}, false+}++func TestPulseToolExecutorAssistantProviderToolsUsesRuntimeAvailability(t *testing.T) {+ exec := NewPulseToolExecutor(ExecutorConfig{+ ReadState: &fakeReadState{},+ AgentServer: &mockAgentServer{agents: []agentexec.ConnectedAgent{{AgentID: "agent-1", Hostname: "node-1"}}},+ ControlLevel: ControlLevelControlled,+ })++ projected := exec.AssistantProviderTools(agentcapabilities.AssistantProviderToolOptions{IncludeQuestionTool: true})+ names := providerToolNameSet(projected)++ for _, name := range []string{agentcapabilities.PulseQueryToolName, agentcapabilities.PulseReadToolName, agentcapabilities.PulseControlToolName, agentcapabilities.PulseFileEditToolName, agentcapabilities.PulseQuestionToolName} {+ if !names[name] {+ t.Fatalf("AssistantProviderTools did not expose available tool %s; names=%v", name, names)+ }+ }+ for _, name := range []string{agentcapabilities.PulseDiscoveryToolName, agentcapabilities.PatrolReportFindingToolName, agentcapabilities.PatrolResolveFindingToolName, agentcapabilities.PatrolGetFindingsToolName} {+ if names[name] {+ t.Fatalf("AssistantProviderTools exposed unavailable tool %s; names=%v", name, names)+ }+ }++ queryTool, ok := providerToolByName(projected, agentcapabilities.PulseQueryToolName)+ if !ok {+ t.Fatalf("AssistantProviderTools did not expose %s", agentcapabilities.PulseQueryToolName)+ }+ if queryTool.PulseGovernance == nil || queryTool.PulseGovernance.ActionMode != agentcapabilities.ActionModeRead {+ t.Fatalf("%s provider governance = %+v, want read metadata", agentcapabilities.PulseQueryToolName, queryTool.PulseGovernance)+ }+ if queryTool.BehaviorHints == nil || queryTool.BehaviorHints.ReadOnlyHint == nil || !*queryTool.BehaviorHints.ReadOnlyHint {+ t.Fatalf("%s provider behavior hints = %+v, want read-only hint", agentcapabilities.PulseQueryToolName, queryTool.BehaviorHints)+ }++ controlTool, ok := providerToolByName(projected, agentcapabilities.PulseControlToolName)+ if !ok {+ t.Fatalf("AssistantProviderTools did not expose %s", agentcapabilities.PulseControlToolName)+ }+ if controlTool.PulseGovernance == nil || controlTool.PulseGovernance.ApprovalPolicy != agentcapabilities.ApprovalPolicyActionPlan {+ t.Fatalf("%s provider governance = %+v, want action-plan metadata", agentcapabilities.PulseControlToolName, controlTool.PulseGovernance)+ }+ if controlTool.BehaviorHints == nil || controlTool.BehaviorHints.DestructiveHint == nil || !*controlTool.BehaviorHints.DestructiveHint {+ t.Fatalf("%s provider behavior hints = %+v, want destructive hint", agentcapabilities.PulseControlToolName, controlTool.BehaviorHints)+ }+}++func TestPulseToolExecutorAssistantProviderToolsEnterThroughManifestSurfaceAffordances(t *testing.T) {+ source, err := os.ReadFile("provider_projection.go")+ if err != nil {+ t.Fatalf("read provider projection source: %v", err)+ }+ text := string(source)+ for _, required := range []string{+ "agentcapabilities.ProjectPulseAssistantProviderTools(agentcapabilities.CanonicalManifest(), nil, nil, opts)",+ "agentcapabilities.ProjectPulseAssistantProviderTools(agentcapabilities.CanonicalManifest(), e.ListTools(), e.ListToolGovernance(), opts)",+ } {+ if !strings.Contains(text, required) {+ t.Fatalf("Assistant provider tools must enter through manifest surface affordances; missing %s", required)+ }+ }+ for _, forbidden := range []string{+ "agentcapabilities.ProjectAssistantProviderTools(nil, nil, opts)",+ "agentcapabilities.ProjectAssistantProviderTools(e.ListTools(), e.ListToolGovernance(), opts)",+ } {+ if strings.Contains(text, forbidden) {+ t.Fatalf("Assistant provider tools bypass manifest surface affordances: found %s", forbidden)+ }+ }+}++func TestPulseToolExecutorAssistantProviderToolsHonorsInteractionMode(t *testing.T) {+ exec := NewPulseToolExecutor(ExecutorConfig{ReadState: &fakeReadState{}, ControlLevel: ControlLevelControlled})++ interactive := providerToolNameSet(exec.AssistantProviderTools(agentcapabilities.AssistantProviderToolOptions{IncludeQuestionTool: true}))+ if !interactive[agentcapabilities.PulseQuestionToolName] {+ t.Fatal("interactive Assistant provider surface must include the question tool")+ }++ nonInteractive := providerToolNameSet(exec.AssistantProviderTools(agentcapabilities.AssistantProviderToolOptions{}))+ if nonInteractive[agentcapabilities.PulseQuestionToolName] {+ t.Fatal("non-interactive Assistant provider surface must not include the question tool")+ }+}++func TestPulseToolExecutorAssistantProviderToolsHonorsControlLevel(t *testing.T) {+ exec := NewPulseToolExecutor(ExecutorConfig{+ ReadState: &fakeReadState{},+ AgentServer: &mockAgentServer{agents: []agentexec.ConnectedAgent{{AgentID: "agent-1", Hostname: "node-1"}}},+ ControlLevel: ControlLevelReadOnly,+ })++ names := providerToolNameSet(exec.AssistantProviderTools(agentcapabilities.AssistantProviderToolOptions{}))+ if names[agentcapabilities.PulseControlToolName] || names[agentcapabilities.PulseFileEditToolName] {+ t.Fatalf("read-only Assistant provider surface exposed control tools; names=%v", names)+ }+ if !names[agentcapabilities.PulseReadToolName] {+ t.Fatalf("read-only Assistant provider surface should still expose %s; names=%v", agentcapabilities.PulseReadToolName, names)+ }+}++func TestPulseToolExecutorAssistantSurfaceToolContractUsesRuntimeProjection(t *testing.T) {+ exec := NewPulseToolExecutor(ExecutorConfig{+ ReadState: &fakeReadState{},+ AgentServer: &mockAgentServer{agents: []agentexec.ConnectedAgent{{AgentID: "agent-1", Hostname: "node-1"}}},+ ControlLevel: ControlLevelControlled,+ })++ contract := exec.AssistantSurfaceToolContract(agentcapabilities.AssistantProviderToolOptions{IncludeQuestionTool: true})+ names := map[string]bool{}+ for _, name := range contract.ToolNames {+ names[name] = true+ }+ registryNames := map[string]bool{}+ for _, name := range contract.RegistryToolNames {+ registryNames[name] = true+ }+ nativeNames := map[string]bool{}+ for _, name := range contract.NativeToolNames {+ nativeNames[name] = true+ }++ if contract.SurfaceID != agentcapabilities.SurfaceIDPulseAssistant {+ t.Fatalf("Assistant surface id = %q", contract.SurfaceID)+ }+ if contract.ToolSource != agentcapabilities.SurfaceToolSourceAssistantRegistry {+ t.Fatalf("Assistant surface tool source = %q", contract.ToolSource)+ }+ for _, name := range []string{agentcapabilities.PulseQueryToolName, agentcapabilities.PulseReadToolName, agentcapabilities.PulseControlToolName, agentcapabilities.PulseQuestionToolName} {+ if !names[name] {+ t.Fatalf("Assistant surface contract missing %s; names=%v", name, names)+ }+ }+ for _, name := range []string{agentcapabilities.PulseQueryToolName, agentcapabilities.PulseReadToolName, agentcapabilities.PulseControlToolName} {+ if !registryNames[name] {+ t.Fatalf("Assistant registry contract missing %s; names=%v", name, registryNames)+ }+ }+ if !nativeNames[agentcapabilities.PulseQuestionToolName] {+ t.Fatalf("Assistant native contract missing question tool; names=%v", nativeNames)+ }+ if len(contract.CapabilityNames) != 0 {+ t.Fatalf("Assistant surface contract must not duplicate MCP capability names: %+v", contract.CapabilityNames)+ }+}diff --git a/internal/ai/tools/recovery_adapter_resilience_test.go b/internal/ai/tools/recovery_adapter_resilience_test.goindex 807b4097b7..576eee61fa 100644--- a/internal/ai/tools/recovery_adapter_resilience_test.go+++ b/internal/ai/tools/recovery_adapter_resilience_test.go@@ -14,7 +14,7 @@ import (_ "modernc.org/sqlite")-func TestRecoveryPointsMCPAdapter_ListPointsToleratesMalformedPersistedMetadata(t *testing.T) {+func TestRecoveryPointsToolAdapter_ListPointsToleratesMalformedPersistedMetadata(t *testing.T) {baseDir := t.TempDir()mtp := config.NewMultiTenantPersistence(baseDir)manager := recoverymanager.New(mtp)@@ -59,7 +59,7 @@ func TestRecoveryPointsMCPAdapter_ListPointsToleratesMalformedPersistedMetadata("adapter-point-bad-json",)- adapter := NewRecoveryPointsMCPAdapter(manager, "default")+ adapter := NewRecoveryPointsToolAdapter(manager, "default")points, total, err := adapter.ListPoints(context.Background(), recovery.ListPointsOptions{Page: 1,Limit: 50,diff --git a/internal/ai/tools/registry.go b/internal/ai/tools/registry.goindex e33af20bd0..82d0ea2d64 100644--- a/internal/ai/tools/registry.go+++ b/internal/ai/tools/registry.go@@ -2,38 +2,55 @@ package toolsimport ("context"- "fmt""sync"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")// ToolActionMode describes the state-changing capability of a registered tool.-type ToolActionMode string+// It aliases the shared Pulse Intelligence capability action mode so Assistant+// and external-agent manifests cannot drift on the read/mixed/write vocabulary.+type ToolActionMode = agentcapabilities.ActionMode++const (+ ToolActionRead ToolActionMode = agentcapabilities.ActionModeRead+ ToolActionMixed ToolActionMode = agentcapabilities.ActionModeMixed+ ToolActionWrite ToolActionMode = agentcapabilities.ActionModeWrite+)++// ToolApprovalPolicy describes whether a tool can run with its granted scope or+// must participate in Pulse's governed action-plan approval lifecycle. It+// aliases the shared Pulse Intelligence approval vocabulary so Assistant+// prompts and external-agent manifests cannot drift.+type ToolApprovalPolicy = agentcapabilities.ApprovalPolicyconst (- ToolActionRead ToolActionMode = "read"- ToolActionMixed ToolActionMode = "mixed"- ToolActionWrite ToolActionMode = "write"+ ToolApprovalScopeOnly ToolApprovalPolicy = agentcapabilities.ApprovalPolicyScopeOnly+ ToolApprovalActionPlan ToolApprovalPolicy = agentcapabilities.ApprovalPolicyActionPlan)-const assistantControlToolsDisabledMessage = "Control tools are disabled. Open Assistant & Patrol settings, then set Pulse Assistant Permissions > Control mode to Controlled before using action tools."+// ControlLevel represents the Assistant permission level for infrastructure+// control. It aliases the shared Pulse Intelligence control vocabulary so+// Assistant tool availability and external-agent adapters cannot drift.+type ControlLevel = agentcapabilities.ControlLevel++const (+ // ControlLevelReadOnly - AI can only query, no control tools available+ ControlLevelReadOnly ControlLevel = agentcapabilities.ControlLevelReadOnly+ // ControlLevelControlled - AI can execute with per-command approval+ ControlLevelControlled ControlLevel = agentcapabilities.ControlLevelControlled+ // ControlLevelAutonomous - AI executes without approval (requires Pro license)+ ControlLevelAutonomous ControlLevel = agentcapabilities.ControlLevelAutonomous+)// ToolGovernance records the operator-facing governance contract for a tool.-type ToolGovernance struct {- ActionMode ToolActionMode- ApprovalPolicy string- Summary string-}+// It aliases the shared Pulse Intelligence shape so Assistant and+// external-agent governance descriptors cannot drift.+type ToolGovernance = agentcapabilities.ToolGovernance// ToolGovernanceDescriptor is the read-only manifest used by Assistant prompts// and action-governance surfaces.-type ToolGovernanceDescriptor struct {- Name string- Description string- RequireControl bool- ActionMode ToolActionMode- ApprovalPolicy string- Summary string-}+type ToolGovernanceDescriptor = agentcapabilities.ToolGovernanceDescriptor// ToolHandler is a function that handles tool executiontype ToolHandler func(ctx context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error)@@ -66,6 +83,7 @@ func (r *ToolRegistry) Register(tool RegisteredTool) {r.mu.Lock()defer r.mu.Unlock()+ tool.Definition = tool.Definition.NormalizeCollections()name := tool.Definition.Nameif _, exists := r.tools[name]; !exists {r.order = append(r.order, name)@@ -82,10 +100,10 @@ func (r *ToolRegistry) ListTools(controlLevel ControlLevel) []Tool {for _, name := range r.order {tool := r.tools[name]// Skip control tools if in read-only mode- if tool.RequireControl && (controlLevel == ControlLevelReadOnly || controlLevel == "") {+ if tool.RequireControl && !agentcapabilities.ControlLevelAllowsControlTools(controlLevel) {continue}- result = append(result, tool.Definition)+ result = append(result, tool.Definition.NormalizeCollections())}return result}@@ -98,46 +116,19 @@ func (r *ToolRegistry) ListToolGovernance(controlLevel ControlLevel) []ToolGoverresult := make([]ToolGovernanceDescriptor, 0, len(r.tools))for _, name := range r.order {tool := r.tools[name]- if tool.RequireControl && (controlLevel == ControlLevelReadOnly || controlLevel == "") {+ if tool.RequireControl && !agentcapabilities.ControlLevelAllowsControlTools(controlLevel) {continue}- governance := normalizeToolGovernance(tool)- result = append(result, ToolGovernanceDescriptor{- Name: tool.Definition.Name,- Description: tool.Definition.Description,- RequireControl: tool.RequireControl,- ActionMode: governance.ActionMode,- ApprovalPolicy: governance.ApprovalPolicy,- Summary: governance.Summary,- })+ result = append(result, agentcapabilities.NewToolGovernanceDescriptor(+ tool.Definition.Name,+ tool.Definition.Description,+ tool.RequireControl,+ tool.Governance,+ ))}return result}-func normalizeToolGovernance(tool RegisteredTool) ToolGovernance {- governance := tool.Governance- if governance.ActionMode == "" {- if tool.RequireControl {- governance.ActionMode = ToolActionWrite- } else {- governance.ActionMode = ToolActionRead- }- }- if governance.ApprovalPolicy == "" {- if governance.ActionMode == ToolActionRead {- governance.ApprovalPolicy = "no approval required"- } else if tool.RequireControl {- governance.ApprovalPolicy = "hidden in read-only mode; approval required in controlled mode"- } else {- governance.ApprovalPolicy = "write subactions require the tool's governed approval path"- }- }- if governance.Summary == "" {- governance.Summary = tool.Definition.Description- }- return governance-}-// allNames returns the canonical list of registered tool names in// registration order. Internal helper for KnownToolNames.func (r *ToolRegistry) allNames() []string {@@ -150,20 +141,28 @@ func (r *ToolRegistry) allNames() []string {// Execute runs a tool by namefunc (r *ToolRegistry) Execute(ctx context.Context, e *PulseToolExecutor, name string, args map[string]interface{}) (CallToolResult, error) {+ params, invalidResult, ok := agentcapabilities.PrepareToolRegistryExecution(name, args)+ if !ok {+ return invalidResult, nil+ }+ name = params.Name+ args = params.Arguments+r.mu.RLock()tool, exists := r.tools[name]r.mu.RUnlock()if !exists {- return NewErrorResult(fmt.Errorf("unknown tool: %s", name)), nil+ return agentcapabilities.NewUnknownToolResult(name), nil}// Centralized control level checkif tool.RequireControl {- if e.controlLevel == ControlLevelReadOnly || e.controlLevel == "" {- return NewTextResult(assistantControlToolsDisabledMessage), nil+ if !agentcapabilities.ControlLevelAllowsControlTools(e.controlLevel) {+ return agentcapabilities.NewControlToolsDisabledToolResult(), nil}}- return tool.Handler(ctx, e, args)+ result, err := tool.Handler(ctx, e, args)+ return result.NormalizeCollections(), err}diff --git a/internal/ai/tools/tools_alerts.go b/internal/ai/tools/tools_alerts.goindex ec09172e45..6491754d5b 100644--- a/internal/ai/tools/tools_alerts.go+++ b/internal/ai/tools/tools_alerts.go@@ -4,13 +4,15 @@ import ("context""fmt""strings"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")// registerAlertsTools registers the pulse_alerts toolfunc (e *PulseToolExecutor) registerAlertsTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_alerts",+ Name: agentcapabilities.PulseAlertsToolName,Description: `Manage alerts and AI patrol findings.Actions:@@ -47,19 +49,19 @@ Examples:Type: "string",Description: "Filter by resource ID (for findings)",},- "finding_id": {+ agentcapabilities.FindingIDArgumentName: {Type: "string",Description: "Finding ID (for resolve, dismiss)",},- "resolution_note": {+ agentcapabilities.ResolutionNoteArgumentName: {Type: "string",- Description: "Resolution note (for resolve action)",+ Description: "Optional resolution note (for resolve action)",},- "note": {+ agentcapabilities.NoteArgumentName: {Type: "string",- Description: "Explanation note (for dismiss action)",+ Description: "Optional explanation note (for dismiss action)",},- "reason": {+ agentcapabilities.ReasonArgumentName: {Type: "string",Description: "Dismissal reason: not_an_issue, expected_behavior, will_fix_later",Enum: []string{"not_an_issue", "expected_behavior", "will_fix_later"},@@ -92,9 +94,10 @@ Examples:return exec.executeAlerts(ctx, args)},Governance: ToolGovernance{- ActionMode: ToolActionMixed,- ApprovalPolicy: "read/list actions are safe; finding resolution and dismissal require the alerts governance path",- Summary: "Reviews alert and finding state and records governed finding decisions.",+ ActionMode: ToolActionMixed,+ ApprovalPolicy: ToolApprovalActionPlan,+ ApprovalSummary: "read/list actions are safe; finding resolution and dismissal require the alerts governance path",+ Summary: "Reviews alert and finding state and records governed finding decisions.",},})}@@ -285,14 +288,11 @@ func canonicalAlertFindingResourceType(raw string) string {}func (e *PulseToolExecutor) executeResolveFinding(_ context.Context, args map[string]interface{}) (CallToolResult, error) {- findingID, _ := args["finding_id"].(string)- resolutionNote, _ := args["resolution_note"].(string)+ findingID, _ := args[agentcapabilities.FindingIDArgumentName].(string)+ resolutionNote, _ := args[agentcapabilities.ResolutionNoteArgumentName].(string)if findingID == "" {- return NewErrorResult(fmt.Errorf("finding_id is required")), nil- }- if resolutionNote == "" {- return NewErrorResult(fmt.Errorf("resolution_note is required")), nil+ return NewErrorResult(fmt.Errorf("%s is required", agentcapabilities.FindingIDArgumentName)), nil}if e.findingsManager == nil {@@ -304,27 +304,24 @@ func (e *PulseToolExecutor) executeResolveFinding(_ context.Context, args map[st}return NewJSONResult(map[string]interface{}{- "success": true,- "finding_id": findingID,- "action": "resolved",- "resolution_note": resolutionNote,- "verification": map[string]interface{}{"ok": true, "method": "store"},+ "success": true,+ agentcapabilities.FindingIDArgumentName: findingID,+ "action": "resolved",+ agentcapabilities.ResolutionNoteArgumentName: resolutionNote,+ "verification": map[string]interface{}{"ok": true, "method": "store"},}), nil}func (e *PulseToolExecutor) executeDismissFinding(_ context.Context, args map[string]interface{}) (CallToolResult, error) {- findingID, _ := args["finding_id"].(string)- reason, _ := args["reason"].(string)- note, _ := args["note"].(string)+ findingID, _ := args[agentcapabilities.FindingIDArgumentName].(string)+ reason, _ := args[agentcapabilities.ReasonArgumentName].(string)+ note, _ := args[agentcapabilities.NoteArgumentName].(string)if findingID == "" {- return NewErrorResult(fmt.Errorf("finding_id is required")), nil+ return NewErrorResult(fmt.Errorf("%s is required", agentcapabilities.FindingIDArgumentName)), nil}if reason == "" {- return NewErrorResult(fmt.Errorf("reason is required")), nil- }- if note == "" {- return NewErrorResult(fmt.Errorf("note is required")), nil+ return NewErrorResult(fmt.Errorf("%s is required", agentcapabilities.ReasonArgumentName)), nil}if e.findingsManager == nil {@@ -336,12 +333,12 @@ func (e *PulseToolExecutor) executeDismissFinding(_ context.Context, args map[st}return NewJSONResult(map[string]interface{}{- "success": true,- "finding_id": findingID,- "action": "dismissed",- "reason": reason,- "note": note,- "verification": map[string]interface{}{"ok": true, "method": "store"},+ "success": true,+ agentcapabilities.FindingIDArgumentName: findingID,+ "action": "dismissed",+ agentcapabilities.ReasonArgumentName: reason,+ agentcapabilities.NoteArgumentName: note,+ "verification": map[string]interface{}{"ok": true, "method": "store"},}), nil}diff --git a/internal/ai/tools/tools_control.go b/internal/ai/tools/tools_control.goindex 0afd36eede..f61ccee961 100644--- a/internal/ai/tools/tools_control.go+++ b/internal/ai/tools/tools_control.go@@ -2,7 +2,6 @@ package toolsimport ("context"- "encoding/json""errors""fmt""strconv"@@ -10,6 +9,7 @@ import ("time""github.com/google/uuid"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/ai/approval""github.com/rcourtman/pulse-go-rewrite/internal/ai/safety"@@ -22,7 +22,7 @@ import (func (e *PulseToolExecutor) registerControlTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_control",+ Name: agentcapabilities.PulseControlToolName,Description: `WRITE operations: control canonical resources that explicitly advertise shared Pulse actions (for example Proxmox guests and supported app-containers) or execute state-modifying commands. Some canonical resources are read-only and will reject pulse_control even when their type is vm or system-container. Read-only and Docker-only workflows are exposed through their own governed tools.`,InputSchema: InputSchema{Type: "object",@@ -70,9 +70,10 @@ func (e *PulseToolExecutor) registerControlTools() {},RequireControl: true,Governance: ToolGovernance{- ActionMode: ToolActionWrite,- ApprovalPolicy: "hidden in read-only mode; approval required in controlled mode",- Summary: "Runs shared Pulse control actions and state-changing commands only against resources that advertise supported actions.",+ ActionMode: ToolActionWrite,+ ApprovalPolicy: ToolApprovalActionPlan,+ ApprovalSummary: "hidden in read-only mode; approval required in controlled mode",+ Summary: "Runs shared Pulse control actions; control only resources that explicitly support shared Pulse actions.",},})}@@ -97,8 +98,7 @@ func (e *PulseToolExecutor) executeControlResource(ctx context.Context, args mapresourceRef = strings.TrimSpace(resourceRef)action, _ := args["action"].(string)action = strings.TrimSpace(action)- approvalID, _ := args["_approval_id"].(string)- approvalID = strings.TrimSpace(approvalID)+ approvalID := agentcapabilities.ApprovalArgument(args)if resourceRef == "" {return NewErrorResult(fmt.Errorf("resource_id is required")), nil@@ -132,7 +132,7 @@ func (e *PulseToolExecutor) executeControlResource(ctx context.Context, args mapguestArgs["force"] = force}if approvalID != "" {- guestArgs["_approval_id"] = approvalID+ agentcapabilities.WithApprovalArgument(guestArgs, approvalID)}return e.executeControlGuest(ctx, guestArgs)@@ -145,7 +145,7 @@ func (e *PulseToolExecutor) executeControlResource(ctx context.Context, args map"operation": action,}if approvalID != "" {- dockerArgs["_approval_id"] = approvalID+ agentcapabilities.WithApprovalArgument(dockerArgs, approvalID)}return e.executeDockerControl(ctx, dockerArgs)case "truenas":@@ -186,7 +186,7 @@ func (e *PulseToolExecutor) executeNativeAppContainerControl(ctx context.ContextapprovalTargetID = strings.TrimSpace(resource.GetProviderUID())}- preApproved := consumeApprovalWithValidation(map[string]interface{}{"_approval_id": approvalID}, e.orgID, command, approvalTargetType, approvalTargetID)+ preApproved := consumeApprovalWithValidation(agentcapabilities.WithApprovalArgument(nil, approvalID), e.orgID, command, approvalTargetType, approvalTargetID)decision := agentexec.PolicyAllowif e.policy != nil {decision = e.policy.Evaluate(command)@@ -317,8 +317,7 @@ func resolvedResourceDisplayName(resource ResolvedResourceInfo) string {func (e *PulseToolExecutor) executeRunCommand(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {command, _ := args["command"].(string)targetHost, _ := args["target_host"].(string)- approvalID, _ := args["_approval_id"].(string)- approvalID = strings.TrimSpace(approvalID)+ approvalID := agentcapabilities.ApprovalArgument(args)if command == "" {return NewErrorResult(fmt.Errorf("command is required")), nil@@ -510,8 +509,7 @@ func (e *PulseToolExecutor) executeControlGuest(ctx context.Context, args map[stguestID, _ := args["guest_id"].(string)action, _ := args["action"].(string)force, _ := args["force"].(bool)- approvalID, _ := args["_approval_id"].(string)- approvalID = strings.TrimSpace(approvalID)+ approvalID := agentcapabilities.ApprovalArgument(args)if guestID == "" {return NewErrorResult(fmt.Errorf("guest_id is required")), nil@@ -1809,8 +1807,8 @@ func approvalDryRunAvailable(targetType, command string) bool {// This is used when the agentic loop re-executes a tool after user approval.// DEPRECATED: Use consumeApprovalWithValidation instead for replay protection.func isPreApproved(args map[string]interface{}) bool {- approvalID, ok := args["_approval_id"].(string)- if !ok || approvalID == "" {+ approvalID := agentcapabilities.ApprovalArgument(args)+ if approvalID == "" {return false}@@ -1838,8 +1836,8 @@ func isPreApproved(args map[string]interface{}) bool {// It verifies the command hash matches the approval and marks it as consumed (single-use).// Returns true if the approval is valid and was consumed, false otherwise.func consumeApprovalWithValidation(args map[string]interface{}, orgID, command, targetType, targetID string) bool {- approvalID, ok := args["_approval_id"].(string)- if !ok || approvalID == "" {+ approvalID := agentcapabilities.ApprovalArgument(args)+ if approvalID == "" {return false}@@ -1935,27 +1933,21 @@ func enrichApprovalRequiredPayload(payload map[string]interface{}, approvalID stfunc formatApprovalNeeded(command, reason, approvalID string) string {payload := map[string]interface{}{- "type": "approval_required","approval_id": approvalID,"command": command,"reason": reason,"how_to_approve": "Click the approval button in the chat to execute this command.",- "do_not_retry": true,}payload = enrichApprovalRequiredPayload(payload, approvalID)- b, _ := json.Marshal(payload)- return "APPROVAL_REQUIRED: " + string(b)+ return agentcapabilities.FormatApprovalRequiredToolMarker(payload)}func formatPolicyBlocked(command, reason string) string {payload := map[string]interface{}{- "type": "policy_blocked",- "command": command,- "reason": reason,- "do_not_retry": true,+ "command": command,+ "reason": reason,}- b, _ := json.Marshal(payload)- return "POLICY_BLOCKED: " + string(b)+ return agentcapabilities.FormatPolicyBlockedToolMarker(payload)}func collectAgentHostnames(agents []agentexec.ConnectedAgent, max int) (all []string, truncated []string) {@@ -2007,39 +1999,32 @@ func formatAvailableAgentHosts(agents []agentexec.ConnectedAgent) string {func formatControlApprovalNeeded(name string, vmID int, action, command, approvalID string) string {payload := map[string]interface{}{- "type": "approval_required","approval_id": approvalID,"guest_name": name,"guest_vmid": vmID,"action": action,"command": command,"how_to_approve": "Click the approval button in the chat to execute this action.",- "do_not_retry": true,}payload = enrichApprovalRequiredPayload(payload, approvalID)- b, _ := json.Marshal(payload)- return "APPROVAL_REQUIRED: " + string(b)+ return agentcapabilities.FormatApprovalRequiredToolMarker(payload)}func formatDockerApprovalNeeded(name, host, action, command, approvalID string) string {payload := map[string]interface{}{- "type": "approval_required","approval_id": approvalID,"container_name": name,"docker_host": host,"action": action,"command": command,"how_to_approve": "Click the approval button in the chat to execute this action.",- "do_not_retry": true,}payload = enrichApprovalRequiredPayload(payload, approvalID)- b, _ := json.Marshal(payload)- return "APPROVAL_REQUIRED: " + string(b)+ return agentcapabilities.FormatApprovalRequiredToolMarker(payload)}func formatAppContainerApprovalNeeded(name, host, action, command, approvalID string) string {payload := map[string]interface{}{- "type": "approval_required","approval_id": approvalID,"resource_name": name,"resource_host": host,@@ -2047,9 +2032,7 @@ func formatAppContainerApprovalNeeded(name, host, action, command, approvalID st"action": action,"command": command,"how_to_approve": "Click the approval button in the chat to execute this action.",- "do_not_retry": true,}payload = enrichApprovalRequiredPayload(payload, approvalID)- b, _ := json.Marshal(payload)- return "APPROVAL_REQUIRED: " + string(b)+ return agentcapabilities.FormatApprovalRequiredToolMarker(payload)}diff --git a/internal/ai/tools/tools_discovery.go b/internal/ai/tools/tools_discovery.goindex cd8a030b87..92af25cf92 100644--- a/internal/ai/tools/tools_discovery.go+++ b/internal/ai/tools/tools_discovery.go@@ -6,6 +6,7 @@ import ("strconv""strings"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")@@ -13,7 +14,7 @@ import (func (e *PulseToolExecutor) registerDiscoveryTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_discovery",+ Name: agentcapabilities.PulseDiscoveryToolName,Description: `Get or run AI-discovered service details from Pulse-owned resource access. action="get" returns existing discovery and triggers discovery only when missing. action="run" forces a fresh discovery run for a known resource. action="list" searches existing discoveries. Resource details must already be known from the current context or a prior resource lookup.`,InputSchema: InputSchema{Type: "object",@@ -57,9 +58,10 @@ func (e *PulseToolExecutor) registerDiscoveryTools() {return exec.executeDiscovery(ctx, args)},Governance: ToolGovernance{- ActionMode: ToolActionMixed,- ApprovalPolicy: "no approval required; run uses read-only evidence collection and updates the discovery cache",- Summary: "Reads or refreshes discovered service paths, ports, and bind mounts for known resources.",+ ActionMode: ToolActionMixed,+ ApprovalPolicy: ToolApprovalScopeOnly,+ ApprovalSummary: "no approval required; run uses read-only evidence collection and updates the discovery cache",+ Summary: "Reads or refreshes discovered service paths, ports, and bind mounts for known resources.",},})}@@ -245,7 +247,7 @@ func (e *PulseToolExecutor) normalizeDiscoveryResourceRequest(args map[string]inresourceTypeRaw, _ := args["resource_type"].(string)resourceID, _ := args["resource_id"].(string)targetID, _ := args["target_id"].(string)- if isCurrentResourceReference(resourceID) || isCurrentResourceReference(resourceTypeRaw) || isCurrentResourceReference(targetID) {+ if IsCurrentResourceReference(resourceID) || IsCurrentResourceReference(resourceTypeRaw) || IsCurrentResourceReference(targetID) {resource, err := e.resolveCurrentResource()if err != nil {return discoveryResourceRequest{}, NewErrorResult(err), falsediff --git a/internal/ai/tools/tools_docker.go b/internal/ai/tools/tools_docker.goindex fcfa58d69c..ec9bf2df79 100644--- a/internal/ai/tools/tools_docker.go+++ b/internal/ai/tools/tools_docker.go@@ -2,11 +2,11 @@ package toolsimport ("context"- "encoding/json""fmt""strings""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/ai/safety""github.com/rcourtman/pulse-go-rewrite/internal/models"@@ -30,7 +30,7 @@ var dockerUpdateQueueSleepFn = sleepWithContextfunc (e *PulseToolExecutor) registerDockerTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_docker",+ Name: agentcapabilities.PulseDockerToolName,Description: `Manage Docker containers, updates, and Swarm services. Actions: control, updates, check_updates, update, services, tasks, swarm.`,InputSchema: InputSchema{Type: "object",@@ -69,9 +69,10 @@ func (e *PulseToolExecutor) registerDockerTools() {return exec.executeDocker(ctx, args)},Governance: ToolGovernance{- ActionMode: ToolActionMixed,- ApprovalPolicy: "read/list actions are safe; control and update subactions require approval in controlled mode",- Summary: "Lists Docker state and performs governed Docker control/update subactions.",+ ActionMode: ToolActionMixed,+ ApprovalPolicy: ToolApprovalActionPlan,+ ApprovalSummary: "read/list actions are safe; control and update subactions require approval in controlled mode",+ Summary: "Lists Docker state and performs governed Docker control/update subactions.",},})}@@ -104,8 +105,7 @@ func (e *PulseToolExecutor) executeDockerControl(ctx context.Context, args map[scontainerName, _ := args["container"].(string)hostName, _ := args["host"].(string)operation, _ := args["operation"].(string)- approvalID, _ := args["_approval_id"].(string)- approvalID = strings.TrimSpace(approvalID)+ approvalID := agentcapabilities.ApprovalArgument(args)if containerName == "" {return NewErrorResult(fmt.Errorf("container name is required")), nil@@ -585,18 +585,15 @@ func (e *PulseToolExecutor) getDockerHostName(hostID string) string {func formatDockerUpdateApprovalNeeded(containerName, hostName, approvalID string) string {payload := map[string]interface{}{- "type": "approval_required","approval_id": approvalID,"container_name": containerName,"docker_host": hostName,"action": "update","command": fmt.Sprintf("docker update %s (pull latest + recreate)", containerName),"how_to_approve": "Click the approval button in the chat to execute this update.",- "do_not_retry": true,}payload = enrichApprovalRequiredPayload(payload, approvalID)- b, _ := json.Marshal(payload)- return "APPROVAL_REQUIRED: " + string(b)+ return agentcapabilities.FormatApprovalRequiredToolMarker(payload)}func trimLeadingSlash(name string) string {diff --git a/internal/ai/tools/tools_file.go b/internal/ai/tools/tools_file.goindex eef9c4850d..c1df7c7a7c 100644--- a/internal/ai/tools/tools_file.go+++ b/internal/ai/tools/tools_file.go@@ -5,10 +5,10 @@ import ("crypto/sha256""encoding/base64""encoding/hex"- "encoding/json""fmt""strings"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/ai/safety""github.com/rs/zerolog/log"@@ -35,7 +35,7 @@ type ExecutionProvenance struct {func (e *PulseToolExecutor) registerFileTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_file_edit",+ Name: agentcapabilities.PulseFileEditToolName,Description: `Read and edit files on remote hosts, containers, VMs, and Docker containers safely.Actions:@@ -88,9 +88,10 @@ Examples:},RequireControl: true,Governance: ToolGovernance{- ActionMode: ToolActionWrite,- ApprovalPolicy: "hidden in read-only mode; approval required in controlled mode",- Summary: "Reads or changes files through the governed file-edit path; read-only file inspection is exposed through the read-only tool surface.",+ ActionMode: ToolActionWrite,+ ApprovalPolicy: ToolApprovalActionPlan,+ ApprovalSummary: "hidden in read-only mode; approval required in controlled mode",+ Summary: "Reads or changes files through the governed file-edit path; read-only file inspection is exposed through the read-only tool surface.",},})}@@ -276,8 +277,7 @@ func (e *PulseToolExecutor) executeFileMutation(ctx context.Context, path, conteif e.agentServer == nil {return NewErrorResult(fmt.Errorf("no agent server available")), nil}- approvalID, _ := args["_approval_id"].(string)- approvalID = strings.TrimSpace(approvalID)+ approvalID := agentcapabilities.ApprovalArgument(args)if blocked, reason := safety.IsSensitivePath(path); blocked {return NewToolResponseResult(NewToolBlockedError(@@ -512,7 +512,7 @@ func (e *ErrExecutionContextUnavailable) Error() string {}func (e *ErrExecutionContextUnavailable) ToToolResponse() ToolResponse {- return NewToolBlockedError("EXECUTION_CONTEXT_UNAVAILABLE", e.Message, map[string]interface{}{+ return NewToolBlockedError(ErrCodeExecutionContextUnavailable, e.Message, map[string]interface{}{"target_host": e.TargetHost,"resolved_kind": e.ResolvedKind,"resolved_node": e.ResolvedNode,@@ -612,7 +612,6 @@ func shellEscape(s string) string {// formatFileApprovalNeeded formats an approval-required response for file operationsfunc formatFileApprovalNeeded(path, host, action string, size int, approvalID string) string {payload := map[string]interface{}{- "type": "approval_required","approval_id": approvalID,"action": "file_" + action,"path": path,@@ -621,6 +620,5 @@ func formatFileApprovalNeeded(path, host, action string, size int, approvalID st"message": fmt.Sprintf("File %s operation requires approval", action),}payload = enrichApprovalRequiredPayload(payload, approvalID)- b, _ := json.Marshal(payload)- return "APPROVAL_REQUIRED: " + string(b)+ return agentcapabilities.FormatApprovalRequiredToolMarker(payload)}diff --git a/internal/ai/tools/tools_knowledge.go b/internal/ai/tools/tools_knowledge.goindex 6329abd90f..b39bf01e52 100644--- a/internal/ai/tools/tools_knowledge.go+++ b/internal/ai/tools/tools_knowledge.go@@ -4,6 +4,8 @@ import ("context""fmt""time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")// IncidentRecorderProvider provides access to incident recording data@@ -79,7 +81,7 @@ type KnowledgeEntry struct {func (e *PulseToolExecutor) registerKnowledgeTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_knowledge",+ Name: agentcapabilities.PulseKnowledgeToolName,Description: `Manage AI knowledge, notes, and incident analysis.Actions:@@ -137,9 +139,10 @@ Examples:return exec.executeKnowledge(ctx, args)},Governance: ToolGovernance{- ActionMode: ToolActionMixed,- ApprovalPolicy: "recall and analysis are safe; remember records operator-visible knowledge",- Summary: "Reads operational memory and records governed knowledge notes when requested.",+ ActionMode: ToolActionMixed,+ ApprovalPolicy: ToolApprovalScopeOnly,+ ApprovalSummary: "recall and analysis are safe; remember records operator-visible knowledge",+ Summary: "Reads operational memory and records governed knowledge notes when requested.",},})}diff --git a/internal/ai/tools/tools_kubernetes.go b/internal/ai/tools/tools_kubernetes.goindex 207964b489..74915b561e 100644--- a/internal/ai/tools/tools_kubernetes.go+++ b/internal/ai/tools/tools_kubernetes.go@@ -2,10 +2,10 @@ package toolsimport ("context"- "encoding/json""fmt""strings"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")@@ -25,7 +25,7 @@ type kubernetesClusterTarget struct {func (e *PulseToolExecutor) registerKubernetesTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_kubernetes",+ Name: agentcapabilities.PulseKubernetesToolName,Description: `Query and control Kubernetes clusters, nodes, pods, and deployments. Query: clusters, nodes, pods, deployments. Control: scale, restart, delete_pod, exec, logs.`,InputSchema: InputSchema{Type: "object",@@ -87,9 +87,10 @@ func (e *PulseToolExecutor) registerKubernetesTools() {return exec.executeKubernetes(ctx, args)},Governance: ToolGovernance{- ActionMode: ToolActionMixed,- ApprovalPolicy: "read/list/log actions are safe; scale, restart, delete, and exec subactions require approval in controlled mode",- Summary: "Reads Kubernetes topology and runs governed workload-control subactions.",+ ActionMode: ToolActionMixed,+ ApprovalPolicy: ToolApprovalActionPlan,+ ApprovalSummary: "read/list/log actions are safe; scale, restart, delete, and exec subactions require approval in controlled mode",+ Summary: "Reads Kubernetes topology and runs governed workload-control subactions.",},})}@@ -510,8 +511,7 @@ func (e *PulseToolExecutor) executeKubernetesScale(ctx context.Context, args mapnamespace, _ := args["namespace"].(string)deployment, _ := args["deployment"].(string)replicas := intArg(args, "replicas", -1)- approvalID, _ := args["_approval_id"].(string)- approvalID = strings.TrimSpace(approvalID)+ approvalID := agentcapabilities.ApprovalArgument(args)if clusterArg == "" {return NewErrorResult(fmt.Errorf("cluster is required")), nil@@ -653,8 +653,7 @@ func (e *PulseToolExecutor) executeKubernetesResourceAction(ctx context.Context,clusterArg, _ := args["cluster"].(string)namespace, _ := args["namespace"].(string)name, _ := args[spec.argKey].(string)- approvalID, _ := args["_approval_id"].(string)- approvalID = strings.TrimSpace(approvalID)+ approvalID := agentcapabilities.ApprovalArgument(args)if clusterArg == "" {return NewErrorResult(fmt.Errorf("cluster is required")), nil@@ -745,8 +744,7 @@ func (e *PulseToolExecutor) executeKubernetesExec(ctx context.Context, args map[pod, _ := args["pod"].(string)container, _ := args["container"].(string)command, _ := args["command"].(string)- approvalID, _ := args["_approval_id"].(string)- approvalID = strings.TrimSpace(approvalID)+ approvalID := agentcapabilities.ApprovalArgument(args)if clusterArg == "" {return NewErrorResult(fmt.Errorf("cluster is required")), nil@@ -921,7 +919,6 @@ func (e *PulseToolExecutor) executeKubernetesLogs(ctx context.Context, args map[// formatKubernetesApprovalNeeded formats an approval-required response for Kubernetes operationsfunc formatKubernetesApprovalNeeded(action, resource, namespace, cluster, command, approvalID string) string {payload := map[string]interface{}{- "type": "approval_required","approval_id": approvalID,"action": action,"resource": resource,@@ -929,9 +926,7 @@ func formatKubernetesApprovalNeeded(action, resource, namespace, cluster, comman"cluster": cluster,"command": command,"how_to_approve": "Click the approval button in the chat to execute this action.",- "do_not_retry": true,}payload = enrichApprovalRequiredPayload(payload, approvalID)- b, _ := json.Marshal(payload)- return "APPROVAL_REQUIRED: " + string(b)+ return agentcapabilities.FormatApprovalRequiredToolMarker(payload)}diff --git a/internal/ai/tools/tools_metrics.go b/internal/ai/tools/tools_metrics.goindex 0ce0abcfcd..1b20f19926 100644--- a/internal/ai/tools/tools_metrics.go+++ b/internal/ai/tools/tools_metrics.go@@ -8,6 +8,7 @@ import ("strings""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")@@ -15,7 +16,7 @@ import (func (e *PulseToolExecutor) registerMetricsTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_metrics",+ Name: agentcapabilities.PulseMetricsToolName,Description: `Get performance metrics, baselines, and sensor data.Types:@@ -89,9 +90,10 @@ Examples:return exec.executeMetrics(ctx, args)},Governance: ToolGovernance{- ActionMode: ToolActionRead,- ApprovalPolicy: "no approval required",- Summary: "Reads performance, sensor, baseline, pattern, and disk-health data without changing state.",+ ActionMode: ToolActionRead,+ ApprovalPolicy: ToolApprovalScopeOnly,+ ApprovalSummary: "no approval required",+ Summary: "Reads performance, sensor, baseline, pattern, and disk-health data without changing state.",},})}diff --git a/internal/ai/tools/tools_metrics_alerts_test.go b/internal/ai/tools/tools_metrics_alerts_test.goindex fb1cfb06ab..5f5e6aa1bb 100644--- a/internal/ai/tools/tools_metrics_alerts_test.go+++ b/internal/ai/tools/tools_metrics_alerts_test.go@@ -7,6 +7,7 @@ import ("testing""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/stretchr/testify/mock""github.com/stretchr/testify/require"@@ -271,18 +272,30 @@ func TestExecuteResolveAndDismissFinding(t *testing.T) {executor.findingsManager = &stubFindingsManager{resolveErr: errors.New("resolve")}result, _ = executor.executeResolveFinding(context.Background(), map[string]interface{}{- "finding_id": "f1",- "resolution_note": "note",+ agentcapabilities.FindingIDArgumentName: "f1",+ agentcapabilities.ResolutionNoteArgumentName: "note",})if !result.IsError {t.Fatal("expected resolve error")}+ executor.findingsManager = &stubFindingsManager{}+ result, _ = executor.executeResolveFinding(context.Background(), map[string]interface{}{+ agentcapabilities.FindingIDArgumentName: "f1",+ })+ var resolveResp map[string]interface{}+ if err := json.Unmarshal([]byte(result.Content[0].Text), &resolveResp); err != nil {+ t.Fatalf("decode resolve response: %v", err)+ }+ if resolveResp["success"] != true {+ t.Fatalf("unexpected resolve response without note: %+v", resolveResp)+ }+executor.findingsManager = &stubFindingsManager{dismissErr: errors.New("dismiss")}result, _ = executor.executeDismissFinding(context.Background(), map[string]interface{}{- "finding_id": "f1",- "reason": "not_an_issue",- "note": "note",+ agentcapabilities.FindingIDArgumentName: "f1",+ agentcapabilities.ReasonArgumentName: "not_an_issue",+ agentcapabilities.NoteArgumentName: "note",})if !result.IsError {t.Fatal("expected dismiss error")@@ -290,9 +303,21 @@ func TestExecuteResolveAndDismissFinding(t *testing.T) {executor.findingsManager = &stubFindingsManager{}result, _ = executor.executeDismissFinding(context.Background(), map[string]interface{}{- "finding_id": "f1",- "reason": "not_an_issue",- "note": "note",+ agentcapabilities.FindingIDArgumentName: "f1",+ agentcapabilities.ReasonArgumentName: "not_an_issue",+ })+ var dismissWithoutNoteResp map[string]interface{}+ if err := json.Unmarshal([]byte(result.Content[0].Text), &dismissWithoutNoteResp); err != nil {+ t.Fatalf("decode dismiss response without note: %v", err)+ }+ if dismissWithoutNoteResp["success"] != true {+ t.Fatalf("unexpected dismiss response without note: %+v", dismissWithoutNoteResp)+ }++ result, _ = executor.executeDismissFinding(context.Background(), map[string]interface{}{+ agentcapabilities.FindingIDArgumentName: "f1",+ agentcapabilities.ReasonArgumentName: "not_an_issue",+ agentcapabilities.NoteArgumentName: "note",})var okResp map[string]interface{}if err := json.Unmarshal([]byte(result.Content[0].Text), &okResp); err != nil {@@ -303,6 +328,31 @@ func TestExecuteResolveAndDismissFinding(t *testing.T) {}}+func TestAlertsToolUsesSharedFindingLifecycleVocabulary(t *testing.T) {+ executor := NewPulseToolExecutor(ExecutorConfig{StateProvider: &mockStateProvider{}})+ var alerts Tool+ for _, tool := range executor.ListTools() {+ if tool.Name == "pulse_alerts" {+ alerts = tool+ break+ }+ }+ if alerts.Name == "" {+ t.Fatal("pulse_alerts tool not registered")+ }++ for _, field := range []string{+ agentcapabilities.FindingIDArgumentName,+ agentcapabilities.ResolutionNoteArgumentName,+ agentcapabilities.ReasonArgumentName,+ agentcapabilities.NoteArgumentName,+ } {+ if _, ok := alerts.InputSchema.Properties[field]; !ok {+ t.Fatalf("pulse_alerts schema missing shared field %q: %#v", field, alerts.InputSchema.Properties)+ }+ }+}+func TestExecuteGetMetrics_InvalidResourceType(t *testing.T) {executor := NewPulseToolExecutor(ExecutorConfig{})result, _ := executor.executeGetMetrics(context.Background(), map[string]interface{}{diff --git a/internal/ai/tools/tools_patrol.go b/internal/ai/tools/tools_patrol.goindex 3787846fcd..c2adc8fab8 100644--- a/internal/ai/tools/tools_patrol.go+++ b/internal/ai/tools/tools_patrol.go@@ -2,9 +2,10 @@ package toolsimport ("context"- "encoding/json""fmt""strings"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")// registerPatrolTools registers the three patrol-specific tools.@@ -13,7 +14,7 @@ func (e *PulseToolExecutor) registerPatrolTools() {// patrol_report_finding — LLM calls this to create a findinge.registry.Register(RegisteredTool{Definition: Tool{- Name: "patrol_report_finding",+ Name: agentcapabilities.PatrolReportFindingToolName,Description: `Report an infrastructure finding discovered during patrol investigation.Call this tool to create a structured finding after you have gathered sufficient evidence via investigation tools.@@ -76,16 +77,17 @@ Returns: {"ok": true, "finding_id": "...", "is_new": true/false} on success.`,},Handler: handlePatrolReportFinding,Governance: ToolGovernance{- ActionMode: ToolActionWrite,- ApprovalPolicy: "patrol-only; records a governed finding after evidence collection",- Summary: "Creates a structured patrol finding during autonomous investigation.",+ ActionMode: ToolActionWrite,+ ApprovalPolicy: ToolApprovalScopeOnly,+ ApprovalSummary: "patrol-only; records a governed finding after evidence collection",+ Summary: "Creates a structured patrol finding during autonomous investigation.",},})// patrol_resolve_finding — LLM calls this to resolve an active findinge.registry.Register(RegisteredTool{Definition: Tool{- Name: "patrol_resolve_finding",+ Name: agentcapabilities.PatrolResolveFindingToolName,Description: `Resolve an active patrol finding after verifying the issue is no longer present.Call this after investigating an existing finding and confirming the issue has been resolved.@@ -93,30 +95,31 @@ Returns: {"ok": true, "resolved": true} on success.`,InputSchema: InputSchema{Type: "object",Properties: map[string]PropertySchema{- "finding_id": {+ agentcapabilities.FindingIDArgumentName: {Type: "string",Description: "The ID of the finding to resolve",},- "reason": {+ agentcapabilities.ReasonArgumentName: {Type: "string",Description: "Brief explanation of why this finding is being resolved (e.g. 'CPU has returned to 35%, well below threshold')",},},- Required: []string{"finding_id", "reason"},+ Required: []string{agentcapabilities.FindingIDArgumentName, agentcapabilities.ReasonArgumentName},},},Handler: handlePatrolResolveFinding,Governance: ToolGovernance{- ActionMode: ToolActionWrite,- ApprovalPolicy: "patrol-only; resolves a finding after verification",- Summary: "Marks a patrol finding resolved after current evidence supports closure.",+ ActionMode: ToolActionWrite,+ ApprovalPolicy: ToolApprovalScopeOnly,+ ApprovalSummary: "patrol-only; resolves a finding after verification",+ Summary: "Marks a patrol finding resolved after current evidence supports closure.",},})// patrol_get_findings — LLM calls this to check existing active findingse.registry.Register(RegisteredTool{Definition: Tool{- Name: "patrol_get_findings",+ Name: agentcapabilities.PatrolGetFindingsToolName,Description: `Get currently active patrol findings. Use this to check what findings already exist before reporting new ones (avoids duplicates) and to identify findings that may need resolution.Returns a list of active findings with their IDs, severity, resource, and title.`,@@ -137,9 +140,10 @@ Returns a list of active findings with their IDs, severity, resource, and title.},Handler: handlePatrolGetFindings,Governance: ToolGovernance{- ActionMode: ToolActionRead,- ApprovalPolicy: "no approval required",- Summary: "Reads active patrol findings for deduplication and investigation context.",+ ActionMode: ToolActionRead,+ ApprovalPolicy: ToolApprovalScopeOnly,+ ApprovalSummary: "no approval required",+ Summary: "Reads active patrol findings for deduplication and investigation context.",},})}@@ -246,12 +250,11 @@ func handlePatrolReportFinding(_ context.Context, e *PulseToolExecutor, args map}result := map[string]interface{}{- "ok": true,- "finding_id": findingID,- "is_new": isNew,+ "ok": true,+ agentcapabilities.FindingIDArgumentName: findingID,+ "is_new": isNew,}- b, _ := json.Marshal(result)- return NewTextResult(string(b)), nil+ return NewJSONResult(result), nil}func handlePatrolResolveFinding(_ context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {@@ -263,14 +266,14 @@ func handlePatrolResolveFinding(_ context.Context, e *PulseToolExecutor, args mareturn NewErrorResult(fmt.Errorf("call patrol_get_findings before resolving a finding")), nil}- findingID, _ := args["finding_id"].(string)- reason, _ := args["reason"].(string)+ findingID, _ := args[agentcapabilities.FindingIDArgumentName].(string)+ reason, _ := args[agentcapabilities.ReasonArgumentName].(string)if findingID == "" {- return NewErrorResult(fmt.Errorf("missing required field: finding_id")), nil+ return NewErrorResult(fmt.Errorf("missing required field: %s", agentcapabilities.FindingIDArgumentName)), nil}if reason == "" {- return NewErrorResult(fmt.Errorf("missing required field: reason")), nil+ return NewErrorResult(fmt.Errorf("missing required field: %s", agentcapabilities.ReasonArgumentName)), nil}if err := creator.ResolveFinding(findingID, reason); err != nil {@@ -281,8 +284,7 @@ func handlePatrolResolveFinding(_ context.Context, e *PulseToolExecutor, args ma"ok": true,"resolved": true,}- b, _ := json.Marshal(result)- return NewTextResult(string(b)), nil+ return NewJSONResult(result), nil}func handlePatrolGetFindings(_ context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {@@ -301,8 +303,7 @@ func handlePatrolGetFindings(_ context.Context, e *PulseToolExecutor, args map[s"count": len(findings),"findings": findings,}- b, _ := json.Marshal(result)- return NewTextResult(string(b)), nil+ return NewJSONResult(result), nil}func canonicalPatrolResourceType(resourceType string) string {diff --git a/internal/ai/tools/tools_patrol_test.go b/internal/ai/tools/tools_patrol_test.goindex 425080e124..51c36dc881 100644--- a/internal/ai/tools/tools_patrol_test.go+++ b/internal/ai/tools/tools_patrol_test.go@@ -6,6 +6,7 @@ import ("fmt""testing"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")@@ -127,8 +128,10 @@ func TestHandlePatrolReportFinding_ValidInput(t *testing.T) {require.NoError(t, json.Unmarshal([]byte(text), &parsed))assert.Equal(t, true, parsed["ok"])- assert.Equal(t, "finding-123", parsed["finding_id"])+ assert.Equal(t, "finding-123", parsed[agentcapabilities.FindingIDArgumentName])assert.Equal(t, true, parsed["is_new"])+ assert.Equal(t, true, result.StructuredContent["ok"])+ assert.Equal(t, "finding-123", result.StructuredContent[agentcapabilities.FindingIDArgumentName])// Verify the creator was called with correct inputrequire.Len(t, creator.createCalls, 1)@@ -400,8 +403,9 @@ func TestHandlePatrolReportFinding_DuplicateFinding(t *testing.T) {require.NoError(t, json.Unmarshal([]byte(text), &parsed))assert.Equal(t, true, parsed["ok"])- assert.Equal(t, "finding-existing", parsed["finding_id"])+ assert.Equal(t, "finding-existing", parsed[agentcapabilities.FindingIDArgumentName])assert.Equal(t, false, parsed["is_new"])+ assert.Equal(t, "finding-existing", result.StructuredContent[agentcapabilities.FindingIDArgumentName])}func TestHandlePatrolReportFinding_CreatorError(t *testing.T) {@@ -446,8 +450,8 @@ func TestHandlePatrolResolveFinding_NilCreator(t *testing.T) {exec := NewPulseToolExecutor(ExecutorConfig{})result, err := handlePatrolResolveFinding(context.Background(), exec, map[string]interface{}{- "finding_id": "f-123",- "reason": "CPU recovered",+ agentcapabilities.FindingIDArgumentName: "f-123",+ agentcapabilities.ReasonArgumentName: "CPU recovered",})require.NoError(t, err)@@ -460,8 +464,8 @@ func TestHandlePatrolResolveFinding_RequiresGetFindings(t *testing.T) {exec := newPatrolTestExecutor(creator)result, err := handlePatrolResolveFinding(context.Background(), exec, map[string]interface{}{- "finding_id": "f-123",- "reason": "CPU recovered",+ agentcapabilities.FindingIDArgumentName: "f-123",+ agentcapabilities.ReasonArgumentName: "CPU recovered",})require.NoError(t, err)@@ -474,8 +478,8 @@ func TestHandlePatrolResolveFinding_ValidInput(t *testing.T) {exec := newPatrolTestExecutor(creator)result, err := handlePatrolResolveFinding(context.Background(), exec, map[string]interface{}{- "finding_id": "f-123",- "reason": "CPU has returned to 35%",+ agentcapabilities.FindingIDArgumentName: "f-123",+ agentcapabilities.ReasonArgumentName: "CPU has returned to 35%",})require.NoError(t, err)@@ -485,6 +489,8 @@ func TestHandlePatrolResolveFinding_ValidInput(t *testing.T) {assert.Equal(t, true, parsed["ok"])assert.Equal(t, true, parsed["resolved"])+ assert.Equal(t, true, result.StructuredContent["ok"])+ assert.Equal(t, true, result.StructuredContent["resolved"])require.Len(t, creator.resolveCalls, 1)assert.Equal(t, "f-123", creator.resolveCalls[0].FindingID)@@ -496,7 +502,7 @@ func TestHandlePatrolResolveFinding_MissingFindingID(t *testing.T) {exec := newPatrolTestExecutor(creator)result, err := handlePatrolResolveFinding(context.Background(), exec, map[string]interface{}{- "reason": "CPU recovered",+ agentcapabilities.ReasonArgumentName: "CPU recovered",})require.NoError(t, err)@@ -509,7 +515,7 @@ func TestHandlePatrolResolveFinding_MissingReason(t *testing.T) {exec := newPatrolTestExecutor(creator)result, err := handlePatrolResolveFinding(context.Background(), exec, map[string]interface{}{- "finding_id": "f-123",+ agentcapabilities.FindingIDArgumentName: "f-123",})require.NoError(t, err)@@ -527,8 +533,8 @@ func TestHandlePatrolResolveFinding_ResolveError(t *testing.T) {exec := newPatrolTestExecutor(creator)result, err := handlePatrolResolveFinding(context.Background(), exec, map[string]interface{}{- "finding_id": "f-nonexistent",- "reason": "CPU recovered",+ agentcapabilities.FindingIDArgumentName: "f-nonexistent",+ agentcapabilities.ReasonArgumentName: "CPU recovered",})require.NoError(t, err)@@ -562,6 +568,8 @@ func TestHandlePatrolGetFindings_EmptyResult(t *testing.T) {assert.Equal(t, true, parsed["ok"])assert.Equal(t, float64(0), parsed["count"])+ assert.Equal(t, true, result.StructuredContent["ok"])+ assert.Equal(t, "0", fmt.Sprint(result.StructuredContent["count"]))}func TestHandlePatrolGetFindings_WithFindings(t *testing.T) {@@ -604,6 +612,8 @@ func TestHandlePatrolGetFindings_WithFindings(t *testing.T) {assert.Equal(t, true, parsed["ok"])assert.Equal(t, float64(2), parsed["count"])+ assert.Equal(t, true, result.StructuredContent["ok"])+ assert.Equal(t, "2", fmt.Sprint(result.StructuredContent["count"]))findings := parsed["findings"].([]interface{})require.Len(t, findings, 2)@@ -676,15 +686,24 @@ func TestPatrolToolsRegistered(t *testing.T) {// Patrol tools should be registered but availability depends on patrolFindingCreatortools := exec.registry.ListTools(ControlLevelReadOnly)found := map[string]bool{}+ var resolveTool Toolfor _, tool := range tools {if tool.Name == "patrol_report_finding" || tool.Name == "patrol_resolve_finding" || tool.Name == "patrol_get_findings" {found[tool.Name] = true}+ if tool.Name == "patrol_resolve_finding" {+ resolveTool = tool+ }}assert.True(t, found["patrol_report_finding"], "patrol_report_finding should be registered")assert.True(t, found["patrol_resolve_finding"], "patrol_resolve_finding should be registered")assert.True(t, found["patrol_get_findings"], "patrol_get_findings should be registered")+ require.NotEmpty(t, resolveTool.Name)+ assert.Contains(t, resolveTool.InputSchema.Required, agentcapabilities.FindingIDArgumentName)+ assert.Contains(t, resolveTool.InputSchema.Required, agentcapabilities.ReasonArgumentName)+ assert.Contains(t, resolveTool.InputSchema.Properties, agentcapabilities.FindingIDArgumentName)+ assert.Contains(t, resolveTool.InputSchema.Properties, agentcapabilities.ReasonArgumentName)}func TestPatrolToolsAvailability(t *testing.T) {diff --git a/internal/ai/tools/tools_pmg.go b/internal/ai/tools/tools_pmg.goindex ed7dc080b0..121ad4123c 100644--- a/internal/ai/tools/tools_pmg.go+++ b/internal/ai/tools/tools_pmg.go@@ -3,13 +3,15 @@ package toolsimport ("context""fmt"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")// registerPMGTools registers the pulse_pmg toolfunc (e *PulseToolExecutor) registerPMGTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_pmg",+ Name: agentcapabilities.PulsePMGToolName,Description: `Query Proxmox Mail Gateway status and statistics. Types: status, mail_stats, queues, spam.`,InputSchema: InputSchema{Type: "object",@@ -31,9 +33,10 @@ func (e *PulseToolExecutor) registerPMGTools() {return exec.executePMG(ctx, args)},Governance: ToolGovernance{- ActionMode: ToolActionRead,- ApprovalPolicy: "no approval required",- Summary: "Reads Proxmox Mail Gateway status, queue, spam, and mail statistics.",+ ActionMode: ToolActionRead,+ ApprovalPolicy: ToolApprovalScopeOnly,+ ApprovalSummary: "no approval required",+ Summary: "Reads Proxmox Mail Gateway status, queue, spam, and mail statistics.",},})}diff --git a/internal/ai/tools/tools_query.go b/internal/ai/tools/tools_query.goindex 187ad04e5c..f9d760d700 100644--- a/internal/ai/tools/tools_query.go+++ b/internal/ai/tools/tools_query.go@@ -10,6 +10,7 @@ import ("sync""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources""github.com/rs/zerolog/log")@@ -85,7 +86,7 @@ func (e *ErrRoutingMismatch) Error() string {// Code returns the error code for structured responsesfunc (e *ErrRoutingMismatch) Code() string {- return "ROUTING_MISMATCH"+ return ErrCodeRoutingMismatch}// ToToolResponse returns a consistent ToolResponse for routing mismatches.@@ -105,7 +106,7 @@ func (e *ErrRoutingMismatch) ToToolResponse() ToolResponse {}return NewToolBlockedError(- "ROUTING_MISMATCH",+ ErrCodeRoutingMismatch,e.Message,details,)@@ -2149,7 +2150,7 @@ func logRoutingMismatchDebug(targetHost string, childKinds, childIDs []string) {func (e *PulseToolExecutor) registerQueryTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_query",+ Name: agentcapabilities.PulseQueryToolName,Description: `Query and search canonical infrastructure resources. Start here to discover systems, workloads, storage, and disks by name. Actions: search, get, config, topology, list, health.`,InputSchema: InputSchema{Type: "object",@@ -2250,9 +2251,10 @@ func (e *PulseToolExecutor) registerQueryTools() {return exec.executeQuery(ctx, args)},Governance: ToolGovernance{- ActionMode: ToolActionRead,- ApprovalPolicy: "no approval required",- Summary: "Resolves canonical infrastructure identity, topology, config, and health without changing state.",+ ActionMode: ToolActionRead,+ ApprovalPolicy: ToolApprovalScopeOnly,+ ApprovalSummary: "no approval required",+ Summary: "Resolves canonical infrastructure identity, topology, config, and health without changing state.",},})}@@ -4768,7 +4770,7 @@ func (e *PulseToolExecutor) executeGetResource(_ context.Context, args map[strinresourceTypeRaw := strings.TrimSpace(resourceType)resourceType = canonicalQueryResourceType(resourceType)- if isCurrentResourceReference(resourceID) || isCurrentResourceReference(resourceTypeRaw) {+ if IsCurrentResourceReference(resourceID) || IsCurrentResourceReference(resourceTypeRaw) {resource, err := e.resolveCurrentResource()if err != nil {return NewErrorResult(err), nildiff --git a/internal/ai/tools/tools_read.go b/internal/ai/tools/tools_read.goindex c8c439c69e..a140d2f3bd 100644--- a/internal/ai/tools/tools_read.go+++ b/internal/ai/tools/tools_read.go@@ -5,6 +5,7 @@ import ("fmt""strings"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/ai/safety""github.com/rs/zerolog/log"@@ -15,7 +16,7 @@ import (func (e *PulseToolExecutor) registerReadTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_read",+ Name: agentcapabilities.PulseReadToolName,Description: `Execute read-only operations on infrastructure (exec, file, find, tail, logs). Rejects write commands. Use target_host for agent-routed reads, or resource_id for API-backed native resource logs such as supported TrueNAS app-containers. When Pulse has attached resource context, use target_host="current_resource" or resource_id="current_resource" for the attached resource instead of copying redacted identifiers.`,InputSchema: InputSchema{Type: "object",@@ -78,9 +79,10 @@ func (e *PulseToolExecutor) registerReadTools() {return exec.executeRead(ctx, args)},Governance: ToolGovernance{- ActionMode: ToolActionRead,- ApprovalPolicy: "no approval required; write-like commands are rejected",- Summary: "Runs read-only infrastructure inspection such as logs, file reads, tails, and safe exec.",+ ActionMode: ToolActionRead,+ ApprovalPolicy: ToolApprovalScopeOnly,+ ApprovalSummary: "no approval required; write-like commands are rejected",+ Summary: "Runs read-only infrastructure inspection such as logs, file reads, tails, and safe exec.",},// Note: RequireControl is NOT set - this is a read-only tool// It's available at all control levels including read_only@@ -117,7 +119,7 @@ func (e *PulseToolExecutor) executeReadExec(ctx context.Context, args map[stringif command == "" {return NewErrorResult(fmt.Errorf("command is required for exec action")), nil}- if strings.TrimSpace(targetHost) == "" && isCurrentResourceReference(resourceRef) {+ if strings.TrimSpace(targetHost) == "" && IsCurrentResourceReference(resourceRef) {targetHost = resourceRef}if targetHost == "" {@@ -261,7 +263,7 @@ func (e *PulseToolExecutor) executeReadFile(ctx context.Context, args map[stringif path == "" {return NewErrorResult(fmt.Errorf("path is required for file action")), nil}- if strings.TrimSpace(targetHost) == "" && isCurrentResourceReference(resourceRef) {+ if strings.TrimSpace(targetHost) == "" && IsCurrentResourceReference(resourceRef) {targetHost = resourceRef}if targetHost == "" {@@ -296,7 +298,7 @@ func (e *PulseToolExecutor) executeReadFind(ctx context.Context, args map[stringif pattern == "" && path == "" {return NewErrorResult(fmt.Errorf("pattern or path is required for find action")), nil}- if strings.TrimSpace(targetHost) == "" && isCurrentResourceReference(resourceRef) {+ if strings.TrimSpace(targetHost) == "" && IsCurrentResourceReference(resourceRef) {targetHost = resourceRef}if targetHost == "" {@@ -347,7 +349,7 @@ func (e *PulseToolExecutor) executeReadTail(ctx context.Context, args map[stringif path == "" {return NewErrorResult(fmt.Errorf("path is required for tail action")), nil}- if strings.TrimSpace(targetHost) == "" && isCurrentResourceReference(resourceRef) {+ if strings.TrimSpace(targetHost) == "" && IsCurrentResourceReference(resourceRef) {targetHost = resourceRef}if targetHost == "" {@@ -410,7 +412,7 @@ func (e *PulseToolExecutor) executeReadLogs(ctx context.Context, args map[stringlines = 100}- if isCurrentResourceReference(resourceRef) {+ if IsCurrentResourceReference(resourceRef) {resource, err := e.resolveCurrentResource()if err != nil {return NewErrorResult(err), nildiff --git a/internal/ai/tools/tools_storage.go b/internal/ai/tools/tools_storage.goindex c5b108f11f..398ec1bc40 100644--- a/internal/ai/tools/tools_storage.go+++ b/internal/ai/tools/tools_storage.go@@ -8,6 +8,7 @@ import ("strings""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/recovery"proxmoxrecoverymapper "github.com/rcourtman/pulse-go-rewrite/internal/recovery/mapper/proxmox""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"@@ -17,7 +18,7 @@ import (func (e *PulseToolExecutor) registerStorageTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_storage",+ Name: agentcapabilities.PulseStorageToolName,Description: `Query storage pools, backups, snapshots, Ceph, replication, RAID, and disk health. Use the "type" parameter to select what to query.`,InputSchema: InputSchema{Type: "object",@@ -96,9 +97,10 @@ func (e *PulseToolExecutor) registerStorageTools() {return exec.executeStorage(ctx, args)},Governance: ToolGovernance{- ActionMode: ToolActionRead,- ApprovalPolicy: "no approval required",- Summary: "Reads storage, backup, recovery, Ceph, RAID, and disk-health state without changing infrastructure.",+ ActionMode: ToolActionRead,+ ApprovalPolicy: ToolApprovalScopeOnly,+ ApprovalSummary: "no approval required",+ Summary: "Reads storage, backup, recovery, Ceph, RAID, and disk-health state without changing infrastructure.",},})}diff --git a/internal/ai/tools/tools_summarize.go b/internal/ai/tools/tools_summarize.goindex 202642c17a..e4bf96bb51 100644--- a/internal/ai/tools/tools_summarize.go+++ b/internal/ai/tools/tools_summarize.go@@ -6,6 +6,7 @@ import ("strings""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/pkg/reporting""github.com/rs/zerolog/log")@@ -24,7 +25,7 @@ import (func (e *PulseToolExecutor) registerSummarizeTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_summarize",+ Name: agentcapabilities.PulseSummarizeToolName,Description: `Generate a retrospective summary of one resource or a fleet across a time window. Use this when the operator asks questions like "what's been happening with pve1 this week" or "where should I look across my fleet" — answers grounded in metric stats, alerts, storage state, disk health, and Patrol findings within the window.Two modes via the 'action' parameter:@@ -65,9 +66,10 @@ Time window defaults to the last 7 days; supported ranges: 24h, 7d, 30d.`,return exec.executeSummarize(ctx, args)},Governance: ToolGovernance{- ActionMode: ToolActionRead,- ApprovalPolicy: "no approval required; pure read of metrics history and findings store.",- Summary: "Returns a retrospective synthesis (observations, recommendations, outliers, period comparison) for one resource or a fleet within a time window.",+ ActionMode: ToolActionRead,+ ApprovalPolicy: ToolApprovalScopeOnly,+ ApprovalSummary: "no approval required; pure read of metrics history and findings store.",+ Summary: "Returns a retrospective synthesis (observations, recommendations, outliers, period comparison) for one resource or a fleet within a time window.",},})}diff --git a/internal/ai/tools/tools_summarize_test.go b/internal/ai/tools/tools_summarize_test.goindex fc60cabc44..a6fc8f5666 100644--- a/internal/ai/tools/tools_summarize_test.go+++ b/internal/ai/tools/tools_summarize_test.go@@ -7,6 +7,7 @@ import ("testing""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/pkg/metrics""github.com/rcourtman/pulse-go-rewrite/pkg/reporting")@@ -46,19 +47,19 @@ func TestSummarizeTool_RegisteredAndDiscoverable(t *testing.T) {tools := exec.registry.ListTools("")var found boolfor _, tool := range tools {- if tool.Name == "pulse_summarize" {+ if tool.Name == agentcapabilities.PulseSummarizeToolName {found = trueif _, ok := tool.InputSchema.Properties["action"]; !ok {- t.Error("pulse_summarize should declare 'action' property")+ t.Errorf("%s should declare 'action' property", agentcapabilities.PulseSummarizeToolName)}if _, ok := tool.InputSchema.Properties["resource_type"]; !ok {- t.Error("pulse_summarize should declare 'resource_type' property")+ t.Errorf("%s should declare 'resource_type' property", agentcapabilities.PulseSummarizeToolName)}break}}if !found {- t.Fatal("pulse_summarize not registered")+ t.Fatalf("%s not registered", agentcapabilities.PulseSummarizeToolName)}}diff --git a/internal/api/actions.go b/internal/api/actions.goindex 6dd78db41a..1fd4ed94ec 100644--- a/internal/api/actions.go+++ b/internal/api/actions.go@@ -11,6 +11,7 @@ import ("time""github.com/rcourtman/pulse-go-rewrite/internal/actionplanner"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")@@ -63,13 +64,13 @@ func (h *ResourceHandlers) HandlePlanAction(w http.ResponseWriter, r *http.Requedecoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxActionPlanRequestBytes))decoder.DisallowUnknownFields()if err := decoder.Decode(&req); err != nil {- writeJSONErrorWithDetails(w, http.StatusBadRequest, "invalid_action_request", "Invalid action planning request", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeInvalidActionRequest, "Invalid action planning request", map[string]string{"body": "request body must be a valid ActionRequest JSON object",})return}if err := decoder.Decode(&struct{}{}); err != io.EOF {- writeJSONErrorWithDetails(w, http.StatusBadRequest, "invalid_action_request", "Invalid action planning request", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeInvalidActionRequest, "Invalid action planning request", map[string]string{"body": "request body must contain one JSON object",})return@@ -77,7 +78,7 @@ func (h *ResourceHandlers) HandlePlanAction(w http.ResponseWriter, r *http.Requereq.ResourceID = unified.CanonicalResourceID(req.ResourceID)if req.ResourceID == "" {- writeJSONErrorWithDetails(w, http.StatusBadRequest, "invalid_action_request", "Invalid action planning request", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeInvalidActionRequest, "Invalid action planning request", map[string]string{"resourceId": "resource id is required",})return@@ -92,7 +93,7 @@ func (h *ResourceHandlers) HandlePlanAction(w http.ResponseWriter, r *http.Requeresource, ok := registry.Get(req.ResourceID)if !ok || resource == nil {- writeJSONErrorWithDetails(w, http.StatusNotFound, "resource_not_found", "Resource not found", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusNotFound, agentcapabilities.AgentErrCodeResourceNotFound, "Resource not found", map[string]string{"resourceId": req.ResourceID,})return@@ -105,11 +106,11 @@ func (h *ResourceHandlers) HandlePlanAction(w http.ResponseWriter, r *http.Requeif validationErr.Field != "" {details[validationErr.Field] = validationErr.Message}- writeJSONErrorWithDetails(w, http.StatusBadRequest, "invalid_action_request", "Invalid action planning request", details)+ writeJSONErrorWithDetails(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeInvalidActionRequest, "Invalid action planning request", details)return}if errors.Is(err, actionplanner.ErrCapabilityNotFound) {- writeJSONErrorWithDetails(w, http.StatusNotFound, "capability_not_found", "Capability not found on resource", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusNotFound, agentcapabilities.AgentErrCodeCapabilityNotFound, "Capability not found on resource", map[string]string{"resourceId": req.ResourceID,"capabilityName": req.CapabilityName,})@@ -122,7 +123,7 @@ func (h *ResourceHandlers) HandlePlanAction(w http.ResponseWriter, r *http.Requereq = normalizeActionRequestForAudit(req)if checker, ok := h.actionExecutor.(ActionAvailabilityChecker); ok {if readiness := checker.CheckActionAvailable(r.Context(), req, *resource); readiness.Name != "" && !readiness.Available {- writeJSONErrorWithDetails(w, http.StatusConflict, "action_execution_unavailable", "Action execution is unavailable", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusConflict, agentcapabilities.AgentErrCodeActionExecutionUnavailable, "Action execution is unavailable", map[string]string{"resourceId": req.ResourceID,"capabilityName": req.CapabilityName,"reasonCode": readiness.ReasonCode,@@ -222,11 +223,11 @@ func (h *ResourceHandlers) HandleDecideAction(w http.ResponseWriter, r *http.ReqactionID := strings.TrimSpace(r.PathValue("id"))if actionID == "" {- writeJSONError(w, http.StatusBadRequest, "missing_id", "Missing action ID")+ writeJSONError(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeMissingID, "Missing action ID")return}if !validAuditEventID.MatchString(actionID) || len(actionID) > 128 {- writeJSONError(w, http.StatusBadRequest, "invalid_id", "Invalid action ID format")+ writeJSONError(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeInvalidID, "Invalid action ID format")return}@@ -234,13 +235,13 @@ func (h *ResourceHandlers) HandleDecideAction(w http.ResponseWriter, r *http.Reqdecoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxActionDecisionRequestBytes))decoder.DisallowUnknownFields()if err := decoder.Decode(&decision); err != nil {- writeJSONErrorWithDetails(w, http.StatusBadRequest, "invalid_action_decision", "Invalid action decision request", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeInvalidActionDecision, "Invalid action decision request", map[string]string{"body": "request body must be a valid action decision JSON object",})return}if err := decoder.Decode(&struct{}{}); err != io.EOF {- writeJSONErrorWithDetails(w, http.StatusBadRequest, "invalid_action_decision", "Invalid action decision request", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeInvalidActionDecision, "Invalid action decision request", map[string]string{"body": "request body must contain one JSON object",})return@@ -248,7 +249,7 @@ func (h *ResourceHandlers) HandleDecideAction(w http.ResponseWriter, r *http.Reqdecision.Outcome = unified.ApprovalOutcome(strings.TrimSpace(string(decision.Outcome)))decision.Reason = strings.TrimSpace(decision.Reason)if decision.Outcome != unified.OutcomeApproved && decision.Outcome != unified.OutcomeRejected {- writeJSONErrorWithDetails(w, http.StatusBadRequest, "invalid_action_decision", "Invalid action decision request", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeInvalidActionDecision, "Invalid action decision request", map[string]string{"outcome": "outcome must be approved or rejected",})return@@ -266,7 +267,7 @@ func (h *ResourceHandlers) HandleDecideAction(w http.ResponseWriter, r *http.Reqreturn}if !ok {- writeJSONErrorWithDetails(w, http.StatusNotFound, "action_not_found", "Action not found", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusNotFound, agentcapabilities.AgentErrCodeActionNotFound, "Action not found", map[string]string{"actionId": actionID,})return@@ -318,11 +319,11 @@ func (h *ResourceHandlers) HandleExecuteAction(w http.ResponseWriter, r *http.ReactionID := strings.TrimSpace(r.PathValue("id"))if actionID == "" {- writeJSONError(w, http.StatusBadRequest, "missing_id", "Missing action ID")+ writeJSONError(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeMissingID, "Missing action ID")return}if !validAuditEventID.MatchString(actionID) || len(actionID) > 128 {- writeJSONError(w, http.StatusBadRequest, "invalid_id", "Invalid action ID format")+ writeJSONError(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeInvalidID, "Invalid action ID format")return}@@ -331,13 +332,13 @@ func (h *ResourceHandlers) HandleExecuteAction(w http.ResponseWriter, r *http.Redecoder.DisallowUnknownFields()if err := decoder.Decode(&execution); err != nil {if !errors.Is(err, io.EOF) {- writeJSONErrorWithDetails(w, http.StatusBadRequest, "invalid_action_execution", "Invalid action execution request", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeInvalidActionExecution, "Invalid action execution request", map[string]string{"body": "request body must be a valid action execution JSON object",})return}} else if err := decoder.Decode(&struct{}{}); err != io.EOF {- writeJSONErrorWithDetails(w, http.StatusBadRequest, "invalid_action_execution", "Invalid action execution request", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeInvalidActionExecution, "Invalid action execution request", map[string]string{"body": "request body must contain one JSON object",})return@@ -356,7 +357,7 @@ func (h *ResourceHandlers) HandleExecuteAction(w http.ResponseWriter, r *http.Rereturn}if !ok {- writeJSONErrorWithDetails(w, http.StatusNotFound, "action_not_found", "Action not found", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusNotFound, agentcapabilities.AgentErrCodeActionNotFound, "Action not found", map[string]string{"actionId": actionID,})return@@ -377,7 +378,7 @@ func (h *ResourceHandlers) HandleExecuteAction(w http.ResponseWriter, r *http.Rereturn}if h.actionExecutor == nil {- writeJSONError(w, http.StatusNotImplemented, "action_executor_unavailable", "No action executor is configured for this API instance")+ writeJSONError(w, http.StatusNotImplemented, agentcapabilities.AgentErrCodeActionExecutorUnavailable, "No action executor is configured for this API instance")return}if err := h.validateActionPlanFresh(orgID, record); err != nil {@@ -545,13 +546,13 @@ func actionDecisionActor(h *ResourceHandlers, r *http.Request) string {func writeActionDecisionApplyError(w http.ResponseWriter, err error) {switch {case errors.Is(err, unified.ErrInvalidApprovalOutcome):- writeJSONErrorWithDetails(w, http.StatusBadRequest, "invalid_action_decision", "Invalid action decision request", map[string]string{+ writeJSONErrorWithDetails(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeInvalidActionDecision, "Invalid action decision request", map[string]string{"outcome": "outcome must be approved or rejected",})case errors.Is(err, unified.ErrActionNotPending):- writeJSONError(w, http.StatusConflict, "action_not_pending", "Action is not pending approval")+ writeJSONError(w, http.StatusConflict, agentcapabilities.AgentErrCodeActionNotPending, "Action is not pending approval")case errors.Is(err, unified.ErrActionPlanExpired):- writeJSONError(w, http.StatusConflict, "action_plan_expired", "Action plan has expired")+ writeJSONError(w, http.StatusConflict, agentcapabilities.AgentErrCodeActionPlanExpired, "Action plan has expired")default:writeJSONError(w, http.StatusInternalServerError, "action_decision_failed", sanitizeErrorForClient(err, "Action decision failed"))}@@ -560,21 +561,21 @@ func writeActionDecisionApplyError(w http.ResponseWriter, err error) {func writeActionExecutionApplyError(w http.ResponseWriter, err error) {switch {case errors.Is(err, unified.ErrActionNotApproved):- writeJSONError(w, http.StatusConflict, "action_not_approved", "Action is not approved for execution")+ writeJSONError(w, http.StatusConflict, agentcapabilities.AgentErrCodeActionNotApproved, "Action is not approved for execution")case errors.Is(err, unified.ErrActionAlreadyExecuting):- writeJSONError(w, http.StatusConflict, "action_already_executing", "Action is already executing")+ writeJSONError(w, http.StatusConflict, agentcapabilities.AgentErrCodeActionAlreadyExecuting, "Action is already executing")case errors.Is(err, unified.ErrActionExecutionFinal):- writeJSONError(w, http.StatusConflict, "action_execution_final", "Action execution is already final")+ writeJSONError(w, http.StatusConflict, agentcapabilities.AgentErrCodeActionExecutionFinal, "Action execution is already final")case errors.Is(err, unified.ErrActionNotExecuting):writeJSONError(w, http.StatusConflict, "action_not_executing", "Action is not executing")case errors.Is(err, unified.ErrActionPlanExpired):- writeJSONError(w, http.StatusConflict, "action_plan_expired", "Action plan has expired")+ writeJSONError(w, http.StatusConflict, agentcapabilities.AgentErrCodeActionPlanExpired, "Action plan has expired")case errors.Is(err, unified.ErrActionDryRunOnly):- writeJSONError(w, http.StatusConflict, "action_dry_run_only", "Action plan is dry-run only and cannot be executed")+ writeJSONError(w, http.StatusConflict, agentcapabilities.AgentErrCodeActionDryRunOnly, "Action plan is dry-run only and cannot be executed")case errors.Is(err, unified.ErrActionPlanDrift):- writeJSONError(w, http.StatusConflict, "action_plan_drift", "Action plan no longer matches the current resource contract; re-plan before executing")+ writeJSONError(w, http.StatusConflict, agentcapabilities.AgentErrCodeActionPlanDrift, "Action plan no longer matches the current resource contract; re-plan before executing")case errors.Is(err, unified.ErrResourceRemediationLocked):- writeJSONError(w, http.StatusConflict, "resource_remediation_locked", "Resource is operator-locked against automated remediation")+ writeJSONError(w, http.StatusConflict, agentcapabilities.AgentErrCodeResourceRemediationLocked, "Resource is operator-locked against automated remediation")default:writeJSONError(w, http.StatusInternalServerError, "action_execution_failed", sanitizeErrorForClient(err, "Action execution failed"))}diff --git a/internal/api/agent_activity_telemetry.go b/internal/api/agent_activity_telemetry.gonew file mode 100644index 0000000000..8fd6d067fa--- /dev/null+++ b/internal/api/agent_activity_telemetry.go@@ -0,0 +1,242 @@+package api++import (+ "encoding/json"+ "io"+ "net/http"+ "strings"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rs/zerolog/log"+)++func (r *Router) withExternalAgentActivity(activity string, handler http.HandlerFunc) http.HandlerFunc {+ return func(w http.ResponseWriter, req *http.Request) {+ r.recordExternalAgentActivity(req, activity)+ handler(w, req)+ }+}++func (r *Router) withExternalAgentCapabilityActivity(capabilityName string, handler http.HandlerFunc) http.HandlerFunc {+ return func(w http.ResponseWriter, req *http.Request) {+ r.recordExternalAgentCapabilityActivity(req, capabilityName)+ handler(w, req)+ }+}++func (r *Router) recordExternalAgentCapabilityActivity(req *http.Request, capabilityName string) {+ activity, requiredScope, ok := externalAgentCapabilityActivity(capabilityName)+ if !ok {+ return+ }+ r.recordExternalAgentActivity(req, activity, requiredScope)+}++func externalAgentActivityForCapability(capabilityName string) (string, bool) {+ activity, _, ok := externalAgentCapabilityActivity(capabilityName)+ return activity, ok+}++func externalAgentCapabilityActivity(capabilityName string) (string, string, bool) {+ capabilityName = strings.TrimSpace(capabilityName)+ if capabilityName == "" {+ return "", "", false+ }+ capability, ok := agentcapabilities.FindCapability(agentcapabilities.CanonicalManifest().Capabilities, capabilityName)+ if !ok {+ return "", "", false+ }+ var activity string+ switch strings.TrimSpace(capabilityName) {+ case agentcapabilities.ResourceContextCapabilityName:+ activity = config.ExternalAgentActivityResourceContext+ case agentcapabilities.FleetContextCapabilityName:+ activity = config.ExternalAgentActivityFleetContext+ case agentcapabilities.OperationsLoopStatusCapabilityName:+ activity = config.ExternalAgentActivityFleetContext+ case agentcapabilities.EventSubscriptionCapabilityName:+ activity = config.ExternalAgentActivityEventStream+ case agentcapabilities.ListNodesCapabilityName,+ agentcapabilities.AddNodeCapabilityName,+ agentcapabilities.UpdateNodeCapabilityName,+ agentcapabilities.RemoveNodeCapabilityName,+ agentcapabilities.TestNodeCredentialsCapabilityName,+ agentcapabilities.TestNodeConnectionCapabilityName,+ agentcapabilities.RefreshNodeClusterMembershipCapabilityName,+ agentcapabilities.DiscoverLANCapabilityName:+ activity = config.ExternalAgentActivityProvisioning+ case agentcapabilities.GetOperatorStateCapabilityName,+ agentcapabilities.SetOperatorStateCapabilityName,+ agentcapabilities.ClearOperatorStateCapabilityName:+ activity = config.ExternalAgentActivityOperatorState+ case agentcapabilities.ListFindingsCapabilityName:+ activity = config.ExternalAgentActivityFindingList+ case agentcapabilities.AcknowledgeFindingCapabilityName,+ agentcapabilities.SnoozeFindingCapabilityName,+ agentcapabilities.DismissFindingCapabilityName,+ agentcapabilities.ResolveFindingCapabilityName:+ activity = config.ExternalAgentActivityFindingDecision+ case agentcapabilities.PlanActionCapabilityName:+ activity = config.ExternalAgentActivityActionPlan+ case agentcapabilities.DecideActionCapabilityName:+ activity = config.ExternalAgentActivityActionDecision+ case agentcapabilities.ExecuteActionCapabilityName:+ activity = config.ExternalAgentActivityActionExecute+ default:+ return "", "", false+ }+ requiredScope := strings.TrimSpace(capability.Scope)+ if requiredScope == "" {+ return "", "", false+ }+ return activity, requiredScope, true+}++func (r *Router) recordExternalAgentActivity(req *http.Request, activity string, requiredScopes ...string) {+ if r == nil || req == nil || strings.TrimSpace(activity) == "" {+ return+ }+ token := getAPITokenRecordFromRequest(req)+ if !apiTokenCoversExternalAgentSurface(token, time.Now().UTC(), requiredScopes...) {+ return+ }+ persistence := r.persistenceForOrg(req.Context())+ if persistence == nil {+ return+ }+ if err := persistence.RecordExternalAgentActivity(config.ExternalAgentActivityRecord{+ Timestamp: time.Now().UTC(),+ Surface: externalAgentActivitySurface(req),+ Activity: activity,+ }); err != nil {+ log.Debug().Err(err).Str("activity", activity).Msg("Failed to record external agent activity")+ }+}++type agentWorkflowPromptActivityRequest struct {+ Name string `json:"name"`+}++// HandleAgentWorkflowPromptActivity records content-free workflow starter+// usage from agent adapters that render prompts locally, such as pulse-mcp.+func (r *Router) HandleAgentWorkflowPromptActivity(w http.ResponseWriter, req *http.Request) {+ if req.Method != http.MethodPost {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ var payload agentWorkflowPromptActivityRequest+ dec := json.NewDecoder(http.MaxBytesReader(w, req.Body, 4096))+ if err := dec.Decode(&payload); err != nil {+ http.Error(w, "Invalid request", http.StatusBadRequest)+ return+ }+ var discard json.RawMessage+ if err := dec.Decode(&discard); err != io.EOF {+ http.Error(w, "Invalid request", http.StatusBadRequest)+ return+ }++ promptName := strings.TrimSpace(payload.Name)+ if !canonicalWorkflowPromptDeclared(promptName) {+ http.Error(w, "Unknown workflow prompt", http.StatusBadRequest)+ return+ }++ r.recordWorkflowPromptActivity(req, workflowPromptActivitySurface(req), promptName)+ w.WriteHeader(http.StatusNoContent)+}++func canonicalWorkflowPromptDeclared(promptName string) bool {+ promptName = strings.TrimSpace(promptName)+ if promptName == "" {+ return false+ }+ for _, prompt := range agentcapabilities.ManifestPulseWorkflowPrompts(agentcapabilities.CanonicalManifest()) {+ if strings.TrimSpace(prompt.Name) == promptName {+ return true+ }+ }+ return false+}++func (r *Router) recordWorkflowPromptActivity(req *http.Request, surface, promptName string) {+ if r == nil || req == nil || strings.TrimSpace(promptName) == "" {+ return+ }+ token := getAPITokenRecordFromRequest(req)+ if !apiTokenCoversExternalAgentSurface(token, time.Now().UTC(), config.ScopeMonitoringRead) {+ return+ }+ persistence := r.persistenceForOrg(req.Context())+ if persistence == nil {+ return+ }+ if err := persistence.RecordWorkflowPromptActivity(config.WorkflowPromptActivityRecord{+ Timestamp: time.Now().UTC(),+ Surface: surface,+ PromptName: promptName,+ }); err != nil {+ log.Debug().Err(err).Str("prompt_name", promptName).Msg("Failed to record workflow prompt activity")+ }+}++func workflowPromptActivitySurface(req *http.Request) string {+ if req == nil {+ return config.WorkflowPromptActivitySurfaceAgentAPI+ }+ switch strings.TrimSpace(req.Header.Get(agentcapabilities.AgentSurfaceHeader)) {+ case agentcapabilities.AgentSurfacePulseMCP:+ return config.WorkflowPromptActivitySurfacePulseMCP+ default:+ return config.WorkflowPromptActivitySurfaceAgentAPI+ }+}++func externalAgentActivitySurface(req *http.Request) string {+ if req == nil {+ return config.ExternalAgentActivitySurfaceAgentAPI+ }+ switch strings.TrimSpace(req.Header.Get(agentcapabilities.AgentSurfaceHeader)) {+ case agentcapabilities.AgentSurfacePulseMCP:+ return config.ExternalAgentActivitySurfacePulseMCP+ default:+ return config.ExternalAgentActivitySurfaceAgentAPI+ }+}++func apiTokenCoversExternalAgentSurface(token *config.APITokenRecord, now time.Time, requiredScopes ...string) bool {+ if token == nil {+ return false+ }+ if token.ExpiresAt != nil && now.After(token.ExpiresAt.UTC()) {+ return false+ }+ if len(requiredScopes) == 0 {+ requiredScopes = agentcapabilities.CanonicalManifest().RequiredScopes+ }+ if len(requiredScopes) == 0 {+ return false+ }+ token = cloneAPITokenRecord(token)+ for _, scope := range requiredScopes {+ scope = strings.TrimSpace(scope)+ if scope == "" {+ return false+ }+ if !token.HasScope(scope) {+ return false+ }+ }+ return true+}++func cloneAPITokenRecord(token *config.APITokenRecord) *config.APITokenRecord {+ if token == nil {+ return nil+ }+ clone := token.Clone()+ return &clone+}diff --git a/internal/api/agent_activity_telemetry_test.go b/internal/api/agent_activity_telemetry_test.gonew file mode 100644index 0000000000..b6c756a5da--- /dev/null+++ b/internal/api/agent_activity_telemetry_test.go@@ -0,0 +1,218 @@+package api++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+ "github.com/rcourtman/pulse-go-rewrite/internal/config"+)++func TestRecordExternalAgentCapabilityActivityUsesCapabilityScope(t *testing.T) {+ persistence := config.NewConfigPersistence(t.TempDir())+ router := &Router{persistence: persistence}++ readOnlyReq := httptest.NewRequest(http.MethodGet, "/api/agent/fleet-context", nil)+ attachAPITokenRecord(readOnlyReq, &config.APITokenRecord{Scopes: []string{config.ScopeMonitoringRead}})+ router.recordExternalAgentCapabilityActivity(readOnlyReq, agentcapabilities.FleetContextCapabilityName)++ history, err := persistence.LoadExternalAgentActivityHistory()+ if err != nil {+ t.Fatalf("LoadExternalAgentActivityHistory: %v", err)+ }+ if len(history.Events) != 1 {+ t.Fatalf("read-only fleet context should record external-agent activity, got %d: %+v", len(history.Events), history.Events)+ }+ if history.Events[0].Surface != config.ExternalAgentActivitySurfaceAgentAPI ||+ history.Events[0].Activity != config.ExternalAgentActivityFleetContext {+ t.Fatalf("unexpected read-only external-agent activity event: %+v", history.Events[0])+ }++ router.recordExternalAgentCapabilityActivity(readOnlyReq, agentcapabilities.PlanActionCapabilityName)++ history, err = persistence.LoadExternalAgentActivityHistory()+ if err != nil {+ t.Fatalf("LoadExternalAgentActivityHistory: %v", err)+ }+ if len(history.Events) != 1 {+ t.Fatalf("read-only token should not record action capability activity, got %d: %+v", len(history.Events), history.Events)+ }++ actionReq := httptest.NewRequest(http.MethodPost, "/api/actions/plan", nil)+ attachAPITokenRecord(actionReq, &config.APITokenRecord{Scopes: []string{config.ScopeAIExecute}})+ router.recordExternalAgentCapabilityActivity(actionReq, agentcapabilities.PlanActionCapabilityName)++ history, err = persistence.LoadExternalAgentActivityHistory()+ if err != nil {+ t.Fatalf("LoadExternalAgentActivityHistory: %v", err)+ }+ if len(history.Events) != 2 {+ t.Fatalf("expected two external-agent activity events, got %d: %+v", len(history.Events), history.Events)+ }+ if history.Events[1].Activity != config.ExternalAgentActivityActionPlan {+ t.Fatalf("action capability activity = %q, want %q", history.Events[1].Activity, config.ExternalAgentActivityActionPlan)+ }+}++func TestRecordExternalAgentCapabilityActivityPreservesMCPAdapterSurface(t *testing.T) {+ persistence := config.NewConfigPersistence(t.TempDir())+ router := &Router{persistence: persistence}++ mcpReq := httptest.NewRequest(http.MethodGet, "/api/agent/fleet-context", nil)+ mcpReq.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseMCP)+ attachAPITokenRecord(mcpReq, &config.APITokenRecord{Scopes: []string{config.ScopeMonitoringRead}})+ router.recordExternalAgentCapabilityActivity(mcpReq, agentcapabilities.FleetContextCapabilityName)++ plainReq := httptest.NewRequest(http.MethodGet, "/api/agent/fleet-context", nil)+ plainReq.Header.Set(agentcapabilities.AgentSurfaceHeader, "unknown-client")+ attachAPITokenRecord(plainReq, &config.APITokenRecord{Scopes: []string{config.ScopeMonitoringRead}})+ router.recordExternalAgentCapabilityActivity(plainReq, agentcapabilities.FleetContextCapabilityName)++ history, err := persistence.LoadExternalAgentActivityHistory()+ if err != nil {+ t.Fatalf("LoadExternalAgentActivityHistory: %v", err)+ }+ if len(history.Events) != 2 {+ t.Fatalf("expected two external-agent activity events, got %d: %+v", len(history.Events), history.Events)+ }+ if history.Events[0].Surface != config.ExternalAgentActivitySurfacePulseMCP {+ t.Fatalf("MCP adapter event surface = %q, want %q", history.Events[0].Surface, config.ExternalAgentActivitySurfacePulseMCP)+ }+ if history.Events[1].Surface != config.ExternalAgentActivitySurfaceAgentAPI {+ t.Fatalf("unknown adapter event surface = %q, want %q", history.Events[1].Surface, config.ExternalAgentActivitySurfaceAgentAPI)+ }+}++func TestHandleAgentWorkflowPromptActivityRecordsMCPAdapterSurface(t *testing.T) {+ persistence := config.NewConfigPersistence(t.TempDir())+ router := &Router{persistence: persistence}++ body := `{"name":"` + agentcapabilities.PulseWorkflowPromptOperationsLoop + `"}`+ req := httptest.NewRequest(http.MethodPost, agentcapabilities.AgentWorkflowPromptActivityPath, strings.NewReader(body))+ req.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseMCP)+ attachAPITokenRecord(req, &config.APITokenRecord{Scopes: []string{config.ScopeMonitoringRead}})+ rec := httptest.NewRecorder()++ router.HandleAgentWorkflowPromptActivity(rec, req)++ if rec.Code != http.StatusNoContent {+ t.Fatalf("HandleAgentWorkflowPromptActivity status = %d body=%q, want 204", rec.Code, rec.Body.String())+ }+ history, err := persistence.LoadWorkflowPromptActivityHistory()+ if err != nil {+ t.Fatalf("LoadWorkflowPromptActivityHistory: %v", err)+ }+ if len(history.Events) != 1 {+ t.Fatalf("expected one workflow prompt activity event, got %d: %+v", len(history.Events), history.Events)+ }+ if history.Events[0].Surface != config.WorkflowPromptActivitySurfacePulseMCP ||+ history.Events[0].PromptName != agentcapabilities.PulseWorkflowPromptOperationsLoop {+ t.Fatalf("unexpected workflow prompt activity event: %+v", history.Events[0])+ }+}++func TestHandleAgentWorkflowPromptActivityRejectsUnknownPrompt(t *testing.T) {+ persistence := config.NewConfigPersistence(t.TempDir())+ router := &Router{persistence: persistence}++ req := httptest.NewRequest(http.MethodPost, agentcapabilities.AgentWorkflowPromptActivityPath, strings.NewReader(`{"name":"unknown"}`))+ attachAPITokenRecord(req, &config.APITokenRecord{Scopes: []string{config.ScopeMonitoringRead}})+ rec := httptest.NewRecorder()++ router.HandleAgentWorkflowPromptActivity(rec, req)++ if rec.Code != http.StatusBadRequest {+ t.Fatalf("unknown prompt status = %d, want 400", rec.Code)+ }+ history, err := persistence.LoadWorkflowPromptActivityHistory()+ if err != nil {+ t.Fatalf("LoadWorkflowPromptActivityHistory: %v", err)+ }+ if len(history.Events) != 0 {+ t.Fatalf("unknown prompt should not record activity, got %+v", history.Events)+ }+}++func TestAPITokenCoversExternalAgentSurfaceRejectsExpiredToken(t *testing.T) {+ now := time.Date(2026, 6, 20, 9, 30, 0, 0, time.UTC)+ expiredAt := now.Add(-time.Minute)+ token := &config.APITokenRecord{+ Scopes: []string{config.ScopeWildcard},+ ExpiresAt: &expiredAt,+ }++ if apiTokenCoversExternalAgentSurface(token, now, config.ScopeMonitoringRead) {+ t.Fatal("expired token should not cover the external-agent surface")+ }+}++func TestRecordExternalAgentCapabilityActivityKeepsProvisioningScopesRouteSpecific(t *testing.T) {+ persistence := config.NewConfigPersistence(t.TempDir())+ router := &Router{persistence: persistence}++ readReq := httptest.NewRequest(http.MethodGet, "/api/config/nodes", nil)+ attachAPITokenRecord(readReq, &config.APITokenRecord{Scopes: []string{config.ScopeSettingsRead}})+ router.recordExternalAgentCapabilityActivity(readReq, agentcapabilities.ListNodesCapabilityName)+ router.recordExternalAgentCapabilityActivity(readReq, agentcapabilities.AddNodeCapabilityName)++ writeReq := httptest.NewRequest(http.MethodPost, "/api/config/nodes", nil)+ attachAPITokenRecord(writeReq, &config.APITokenRecord{Scopes: []string{config.ScopeSettingsWrite}})+ router.recordExternalAgentCapabilityActivity(writeReq, agentcapabilities.AddNodeCapabilityName)++ history, err := persistence.LoadExternalAgentActivityHistory()+ if err != nil {+ t.Fatalf("LoadExternalAgentActivityHistory: %v", err)+ }+ if len(history.Events) != 2 {+ t.Fatalf("expected read list_nodes and write add_node activity only, got %d: %+v", len(history.Events), history.Events)+ }+ for _, event := range history.Events {+ if event.Activity != config.ExternalAgentActivityProvisioning {+ t.Fatalf("provisioning activity = %q, want %q", event.Activity, config.ExternalAgentActivityProvisioning)+ }+ }+}++func TestExternalAgentActivityForCanonicalPulseMCPSurfaceTools(t *testing.T) {+ manifest := agentcapabilities.CanonicalManifest()+ capabilities := agentcapabilities.ManifestSurfaceToolCapabilities(manifest, agentcapabilities.SurfaceIDPulseMCP)+ if len(capabilities) == 0 {+ t.Fatal("Pulse MCP surface must publish request/response tools")+ }+ for _, capability := range capabilities {+ activity, ok := externalAgentActivityForCapability(capability.Name)+ if !ok {+ t.Fatalf("MCP-published capability %q has no external-agent activity class", capability.Name)+ }+ if activity == "" {+ t.Fatalf("MCP-published capability %q maps to an empty external-agent activity class", capability.Name)+ }+ }+ if activity, ok := externalAgentActivityForCapability(agentcapabilities.EventSubscriptionCapabilityName); !ok || activity != config.ExternalAgentActivityEventStream {+ t.Fatalf("%s activity = %q, %v; want %s", agentcapabilities.EventSubscriptionCapabilityName, activity, ok, config.ExternalAgentActivityEventStream)+ }+}++func TestRecordExternalAgentCapabilityActivityUsesCapabilityClass(t *testing.T) {+ persistence := config.NewConfigPersistence(t.TempDir())+ router := &Router{persistence: persistence}+ req := httptest.NewRequest(http.MethodPut, "/api/resources/vm:101/operator-state", nil)+ attachAPITokenRecord(req, &config.APITokenRecord{Scopes: []string{config.ScopeWildcard}})++ router.recordExternalAgentCapabilityActivity(req, agentcapabilities.SetOperatorStateCapabilityName)+ router.recordExternalAgentCapabilityActivity(req, "unknown_capability")++ history, err := persistence.LoadExternalAgentActivityHistory()+ if err != nil {+ t.Fatalf("LoadExternalAgentActivityHistory: %v", err)+ }+ if len(history.Events) != 1 {+ t.Fatalf("expected one external-agent activity event, got %d: %+v", len(history.Events), history.Events)+ }+ if history.Events[0].Activity != config.ExternalAgentActivityOperatorState {+ t.Fatalf("operator-state capability activity = %q, want %q", history.Events[0].Activity, config.ExternalAgentActivityOperatorState)+ }+}diff --git a/internal/api/agent_capabilities.go b/internal/api/agent_capabilities.goindex a362dd89cb..2c82488b15 100644--- a/internal/api/agent_capabilities.go+++ b/internal/api/agent_capabilities.go@@ -3,477 +3,12 @@ package apiimport ("encoding/json""net/http"-)--// AgentCapability declares one agent-consumable capability Pulse-// exposes — a single point of "here's what you can do and how." The-// shape is intentionally narrow so a future MCP-server slice can-// consume the manifest to register tools, and so external agents-// (Claude Code, custom integrations) can introspect Pulse without-// reading documentation. Each capability names the canonical REST-// path, the method, the scope required, and the stable error-// codes the response may carry — agents branch on those, not on-// human messages.-type AgentCapability struct {- // Name is the agent-stable identifier for this capability.- // snake_case to match the convention agents use for tool names.- // MUST be stable across releases — renaming breaks integrations.- Name string `json:"name"`-- // Description is a single-sentence explanation an agent can- // surface to a user when it's deciding whether to call this- // capability. Phrased imperatively ("Get the situated context for- // a resource") rather than narratively.- Description string `json:"description"`-- // Category groups capabilities for agent UIs. Stable values:- // "context" (read-only situated reads), "provisioning"- // (infrastructure onboarding and source lifecycle),- // "operator-state" (per-resource intent writes), "finding"- // (per-finding lifecycle actions), and "action" (governed- // plan/decision/execute operations). Agents can filter the- // manifest by category.- Category string `json:"category"`-- // Method + Path describe the canonical REST surface. Path- // segments in `{braces}` are agent-supplied parameters; agents- // percent-encode them when they substitute (the canonical IDs- // commonly contain colons).- Method string `json:"method"`- Path string `json:"path"`-- // Scope names the auth scope required to call this capability.- // Agents that lack the scope must ask the operator to widen- // their token rather than retrying.- Scope string `json:"scope"`-- // ResponseShape is the agent-stable name of the response type- // (e.g. "AgentResourceContext", "ResourceOperatorState"). Agents- // branch on this to know what to parse; future MCP integrations- // can map it to tool result schemas.- ResponseShape string `json:"responseShape,omitempty"`-- // ErrorCodes is the closed set of stable error codes this- // capability may return on failure. Agents branch on these- // (e.g. "operator_state_not_set", "operator_state_invalid",- // "resource_remediation_locked", "plan_drift") rather than- // parsing human messages. Empty list = the capability uses only- // generic HTTP-status error responses.- ErrorCodes []string `json:"errorCodes,omitempty"`-- // RequestBodyShape, when non-empty, names the agent-stable- // request body shape for non-GET capabilities so agents can- // validate before sending.- RequestBodyShape string `json:"requestBodyShape,omitempty"`-- // InputSchema is an optional JSON Schema for agent-facing tool- // arguments. It is hand-authored for capabilities where prose- // body hints are not enough for reliable model use.- InputSchema map[string]any `json:"inputSchema,omitempty"`-}--// AgentCapabilitiesManifest is the discovery document for Pulse's-// agent surface. Any agent that wants to integrate with Pulse fetches-// this once at startup, learns what's available, and calls the named-// capabilities. The manifest itself is read-only and unauthenticated-// (the Pulse capabilities it describes have their own auth scopes).-type AgentCapabilitiesManifest struct {- // Version pins the manifest contract. Agents validate they- // understand this version before using the manifest. Bumping- // version is reserved for breaking shape changes; additive- // capabilities ship under the same version.- Version string `json:"version"`-- // Capabilities is the canonical list. Order is stable across- // requests so agents can diff snapshots cheaply.- Capabilities []AgentCapability `json:"capabilities"`-}--func agentObjectInputSchema(required []string, properties map[string]any) map[string]any {- schema := map[string]any{- "type": "object",- "properties": properties,- "additionalProperties": false,- }- if len(required) > 0 {- schema["required"] = required- }- return schema-}--func nodeIDInputSchema() map[string]any {- return agentObjectInputSchema([]string{"nodeId"}, map[string]any{- "nodeId": map[string]any{- "type": "string",- "description": "Configured node id from list_nodes, such as pve:lab or pve-0.",- },- })-}--func discoverLANInputSchema() map[string]any {- return agentObjectInputSchema(nil, map[string]any{- "subnet": map[string]any{- "type": "string",- "description": "CIDR to scan, such as 192.168.1.0/24, or auto to let Pulse choose the local subnet.",- "default": "auto",- },- "use_cache": map[string]any{- "type": "boolean",- "description": "Return cached discovery results when available instead of starting a new scan.",- "default": false,- },- })-}-func addNodeInputSchema() map[string]any {- schema := agentObjectInputSchema([]string{"type", "name", "host"}, nodeConfigInputProperties(false))- schema["oneOf"] = []map[string]any{- {"required": []string{"user", "password"}},- {"required": []string{"tokenName", "tokenValue"}},- }- return schema-}--func testNodeCredentialsInputSchema() map[string]any {- schema := agentObjectInputSchema([]string{"type", "host"}, nodeConfigInputProperties(false))- schema["oneOf"] = []map[string]any{- {"required": []string{"user", "password"}},- {"required": []string{"tokenName", "tokenValue"}},- }- return schema-}--func updateNodeInputSchema() map[string]any {- properties := nodeConfigInputProperties(true)- return agentObjectInputSchema([]string{"nodeId"}, properties)-}--func nodeConfigInputProperties(includeNodeID bool) map[string]any {- properties := map[string]any{- "type": map[string]any{- "type": "string",- "enum": []string{"pve", "pbs", "pmg"},- "description": "Infrastructure source type: pve, pbs, or pmg.",- },- "name": map[string]any{- "type": "string",- "description": "Human-readable source name to show in Pulse.",- },- "host": map[string]any{- "type": "string",- "description": "Source endpoint URL or host, including scheme and port when needed.",- },- "guestURL": map[string]any{- "type": "string",- "description": "Optional guest-accessible URL for navigation.",- },- "user": map[string]any{- "type": "string",- "description": "Username for password authentication, or the token owner when needed by the platform.",- },- "password": map[string]any{- "type": "string",- "description": "Password used only for setup or password-backed monitoring.",- },- "tokenName": map[string]any{- "type": "string",- "description": "API token id or name, such as root@pam!pulse-monitor.",- },- "tokenValue": map[string]any{- "type": "string",- "description": "API token secret value. Pulse stores this as a credential and never returns it from list_nodes.",- },- "fingerprint": map[string]any{- "type": "string",- "description": "Optional TLS certificate fingerprint for pinned self-signed endpoints.",- },- "verifySSL": map[string]any{- "type": "boolean",- "description": "Whether Pulse should require normal TLS certificate validation.",- },- "monitorVMs": platformBool("PVE", "virtual machines"),- "monitorContainers": platformBool("PVE", "containers"),- "monitorStorage": platformBool("PVE", "storage"),- "monitorBackups": platformBool("PVE or PBS", "backups"),- "monitorPhysicalDisks": platformBool("PVE", "physical disks"),- "physicalDiskPollingMinutes": integerOption("PVE physical disk polling interval in minutes. Use 0 or omit for the default."),- "temperatureMonitoringEnabled": platformBool("All source types", "temperature monitoring"),- "monitorDatastores": platformBool("PBS", "datastores"),- "monitorSyncJobs": platformBool("PBS", "sync jobs"),- "monitorVerifyJobs": platformBool("PBS", "verify jobs"),- "monitorPruneJobs": platformBool("PBS", "prune jobs"),- "monitorGarbageJobs": platformBool("PBS", "garbage collection jobs"),- "monitorMailStats": platformBool("PMG", "mail statistics"),- "monitorQueues": platformBool("PMG", "mail queues"),- "monitorQuarantine": platformBool("PMG", "quarantine"),- "monitorDomainStats": platformBool("PMG", "domain statistics"),- "enabled": platformBool("All source types", "collection from this source"),- "excludeDatastores": stringArrayOption("PBS datastore names to exclude from monitoring."),- }- if includeNodeID {- properties["nodeId"] = map[string]any{- "type": "string",- "description": "Configured node id from list_nodes, such as pve:lab or pve-0.",- }- }- return properties-}--func platformBool(platform, subject string) map[string]any {- return map[string]any{- "type": "boolean",- "description": platform + " option for " + subject + ".",- }-}--func integerOption(description string) map[string]any {- return map[string]any{- "type": "integer",- "minimum": 0,- "description": description,- }-}--func stringArrayOption(description string) map[string]any {- return map[string]any{- "type": "array",- "description": description,- "items": map[string]any{- "type": "string",- },- }-}+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+)-// agentCapabilitiesManifest is the v1 declaration of Pulse's-// agent-consumable surface. Hand-authored rather than auto-generated-// because the contract decisions (which capabilities are-// agent-stable, what the stable error codes are, what category each-// belongs to) are product-shaping and must not drift behind code-// changes. Adding a capability here is a deliberate "this is part of-// the agent surface" commitment.-var agentCapabilitiesManifest = AgentCapabilitiesManifest{- Version: "v1",- Capabilities: []AgentCapability{- {- Name: "get_resource_context",- Description: "Return the situated picture of a resource — identity, operator-set state with maintenance-window-active flag, active findings, pending approvals scoped to this resource, recent actions including refused dispatches. Command fields are redacted for monitoring-read API tokens unless the token also has ai:execute.",- Category: "context",- Method: http.MethodGet,- Path: "/api/agent/resource-context/{resourceId}",- Scope: "monitoring:read",- ResponseShape: "AgentResourceContext",- ErrorCodes: []string{"resource_not_found"},- },- {- Name: "get_fleet_context",- Description: "Return a thin per-resource triage rollup across every resource visible to the org — identity, operator flags (intentionallyOffline, neverAutoRemediate, maintenanceWindowActive), per-severity finding counts (total/critical/warning/info), and pending-approval count. One read for 'where do I focus?'; follow up via get_resource_context for depth.",- Category: "context",- Method: http.MethodGet,- Path: "/api/agent/fleet-context",- Scope: "monitoring:read",- ResponseShape: "AgentFleetContext",- },- {- Name: "list_nodes",- Description: "List configured infrastructure sources that Pulse can monitor or manage. Credential secret values are redacted; use the returned id with update_node, remove_node, test_node_connection, or refresh_node_cluster_membership.",- Category: "provisioning",- Method: http.MethodGet,- Path: "/api/config/nodes",- Scope: "settings:read",- ResponseShape: "NodeResponse[]",- },- {- Name: "add_node",- Description: "Add a Proxmox VE, Proxmox Backup Server, or Proxmox Mail Gateway source to Pulse after credentials have been collected, generated, or approved.",- Category: "provisioning",- Method: http.MethodPost,- Path: "/api/config/nodes",- Scope: "settings:write",- RequestBodyShape: "NodeConfigRequest",- ResponseShape: "{ status: \"success\" }",- InputSchema: addNodeInputSchema(),- },- {- Name: "update_node",- Description: "Update a configured infrastructure source. Omitted fields preserve the current value; tokenValue or password only changes when supplied.",- Category: "provisioning",- Method: http.MethodPut,- Path: "/api/config/nodes/{nodeId}",- Scope: "settings:write",- RequestBodyShape: "NodeConfigRequest",- ResponseShape: "{ status: \"success\" }",- InputSchema: updateNodeInputSchema(),- },- {- Name: "remove_node",- Description: "Remove a configured infrastructure source from Pulse by node id.",- Category: "provisioning",- Method: http.MethodDelete,- Path: "/api/config/nodes/{nodeId}",- Scope: "settings:write",- ResponseShape: "{ status: \"success\" }",- InputSchema: nodeIDInputSchema(),- },- {- Name: "test_node_credentials",- Description: "Validate proposed source credentials and connection details without saving them to Pulse.",- Category: "provisioning",- Method: http.MethodPost,- Path: "/api/config/nodes/test-config",- Scope: "settings:write",- RequestBodyShape: "NodeConfigRequest",- ResponseShape: "{ status: \"success\"|\"error\", message: string }",- InputSchema: testNodeCredentialsInputSchema(),- },- {- Name: "test_node_connection",- Description: "Validate the saved connection for an existing configured infrastructure source.",- Category: "provisioning",- Method: http.MethodPost,- Path: "/api/config/nodes/{nodeId}/test",- Scope: "settings:write",- ResponseShape: "{ status: \"success\"|\"error\", message: string }",- InputSchema: nodeIDInputSchema(),- },- {- Name: "refresh_node_cluster_membership",- Description: "Re-detect Proxmox VE cluster membership and endpoint metadata for a configured source.",- Category: "provisioning",- Method: http.MethodPost,- Path: "/api/config/nodes/{nodeId}/refresh-cluster",- Scope: "settings:write",- ResponseShape: "ClusterRefreshResponse",- InputSchema: nodeIDInputSchema(),- },- {- Name: "discover_lan",- Description: "Scan a subnet, or return cached scan results, to find candidate infrastructure hosts before deciding which sources to add to Pulse.",- Category: "provisioning",- Method: http.MethodPost,- Path: "/api/discover",- Scope: "settings:write",- RequestBodyShape: "{ subnet?: string, use_cache?: boolean }",- ResponseShape: "ManualDiscoveryResult",- InputSchema: discoverLANInputSchema(),- },- {- Name: "get_operator_state",- Description: "Read the operator-set state for a resource (intentionally offline, never auto-remediate, maintenance window, criticality).",- Category: "operator-state",- Method: http.MethodGet,- Path: "/api/resources/{resourceId}/operator-state",- Scope: "monitoring:read",- ResponseShape: "ResourceOperatorState",- ErrorCodes: []string{"operator_state_not_set"},- },- {- Name: "set_operator_state",- Description: "Replace the operator-set state for a resource. URL canonicalId wins over body; server populates setAt and setBy from the authenticated identity.",- Category: "operator-state",- Method: http.MethodPut,- Path: "/api/resources/{resourceId}/operator-state",- Scope: "monitoring:write",- RequestBodyShape: "ResourceOperatorStateInput",- ResponseShape: "ResourceOperatorState",- ErrorCodes: []string{"operator_state_invalid"},- },- {- Name: "clear_operator_state",- Description: "Remove any operator-set state for a resource. Idempotent — succeeds whether or not an entry was present.",- Category: "operator-state",- Method: http.MethodDelete,- Path: "/api/resources/{resourceId}/operator-state",- Scope: "monitoring:write",- },- {- Name: "subscribe_events",- Description: "Subscribe to the SSE event stream for real-time notifications: finding.created when a new finding is raised, approval.pending when a remediation request enters StatusPending and waits on operator decision, action.completed when an action audit reaches a terminal state (Completed or Failed, including refused-before-dispatch failures with stable error-token prefixes; carries a verification block with the read-after-write probe outcome so agents close the certainty loop without polling /api/actions/{id}), stream-local heartbeat every 15s. Command fields are redacted for monitoring-read API tokens unless the token also has ai:execute. Long-lived connection; agents listen instead of polling.",- Category: "context",- Method: http.MethodGet,- Path: "/api/agent/events",- Scope: "monitoring:read",- ResponseShape: "text/event-stream of AgentEvent",- },- {- Name: "list_findings",- Description: "List all Patrol findings (active, dismissed, resolved). Filter client-side on returned shape.",- Category: "finding",- Method: http.MethodGet,- Path: "/api/ai/patrol/findings",- Scope: "monitoring:read",- ResponseShape: "Finding[]",- },- {- Name: "acknowledge_finding",- Description: "Mark a finding as seen but keep it visible. Auto-resolves when the underlying condition clears.",- Category: "finding",- Method: http.MethodPost,- Path: "/api/ai/patrol/acknowledge",- Scope: "monitoring:write",- RequestBodyShape: "{ finding_id: string }",- },- {- Name: "snooze_finding",- Description: "Hide a finding for a defined duration in hours.",- Category: "finding",- Method: http.MethodPost,- Path: "/api/ai/patrol/snooze",- Scope: "monitoring:write",- RequestBodyShape: "{ finding_id: string, duration_hours: number }",- },- {- Name: "dismiss_finding",- Description: "Dismiss a finding with a reason: not_an_issue (permanent suppression), expected_behavior (acknowledged forever), or will_fix_later (7-day reminder commitment).",- Category: "finding",- Method: http.MethodPost,- Path: "/api/ai/patrol/dismiss",- Scope: "monitoring:write",- RequestBodyShape: "{ finding_id: string, reason: \"not_an_issue\"|\"expected_behavior\"|\"will_fix_later\", note?: string }",- },- {- Name: "resolve_finding",- Description: "Manually mark a finding as resolved when the underlying issue has been fixed out-of-band.",- Category: "finding",- Method: http.MethodPost,- Path: "/api/ai/patrol/resolve",- Scope: "monitoring:write",- RequestBodyShape: "{ finding_id: string }",- },- {- Name: "plan_action",- Description: "Plan an action against a resource. The planner validates the request, looks up the capability on the resource, checks executor-owned live availability, and returns an ActionPlan with the approval policy, blast radius, plan hash, and preflight summary. The plan is persisted to the audit history at the planned/pending state only after the live availability check passes, so subsequent decide_action and execute_action calls can reference it by id. Plan-and-execute is a two-step flow when the resulting plan requires approval, one-step otherwise.",- Category: "action",- Method: http.MethodPost,- Path: "/api/actions/plan",- Scope: "ai:execute",- RequestBodyShape: "ActionRequest",- ResponseShape: "ActionPlan",- ErrorCodes: []string{"invalid_action_request", "resource_not_found", "capability_not_found", "action_execution_unavailable"},- },- {- Name: "decide_action",- Description: "Record an approval decision (approved or rejected) on a previously planned action. The actor is taken from the authenticated identity; an explicit reason can be passed in the body. Idempotent on the persisted decision: re-deciding a non-pending action surfaces the action_not_pending stable code so agents can branch on the conflict rather than retrying blindly.",- Category: "action",- Method: http.MethodPost,- Path: "/api/actions/{actionId}/decision",- Scope: "ai:execute",- RequestBodyShape: "{ outcome: \"approved\"|\"rejected\", reason?: string }",- ResponseShape: "ActionDecisionResponse",- ErrorCodes: []string{"missing_id", "invalid_id", "invalid_action_decision", "action_not_found", "action_not_pending", "action_plan_expired"},- },- {- Name: "execute_action",- Description: "Execute a previously planned and (when required) approved action. Returns the persisted audit record with the execution result attached. Refuses with stable codes when the action is in the wrong lifecycle state (action_not_approved, action_already_executing, action_execution_final, action_dry_run_only, action_plan_expired), when the approved plan no longer matches the current resource/capability contract (action_plan_drift), when the target is operator-locked against automated remediation (resource_remediation_locked), or when the API instance has no executor wired (action_executor_unavailable). action.completed SSE events fire on every terminal state so agents watching the stream do not need to poll this endpoint after dispatch.",- Category: "action",- Method: http.MethodPost,- Path: "/api/actions/{actionId}/execute",- Scope: "ai:execute",- RequestBodyShape: "{ reason?: string }",- ResponseShape: "ActionExecutionResponse",- ErrorCodes: []string{"missing_id", "invalid_id", "invalid_action_execution", "action_not_found", "action_not_approved", "action_already_executing", "action_execution_final", "action_dry_run_only", "action_plan_expired", "action_plan_drift", "resource_remediation_locked", "action_executor_unavailable"},- },- },-}+type AgentCapability = agentcapabilities.Capability+type AgentCapabilitiesManifest = agentcapabilities.Manifest// HandleAgentCapabilitiesManifest serves// `GET /api/agent/capabilities` — the discovery document for Pulse's@@ -487,5 +22,5 @@ func HandleAgentCapabilitiesManifest(w http.ResponseWriter, r *http.Request) {}w.Header().Set("Content-Type", "application/json")w.Header().Set("Cache-Control", "public, max-age=300")- _ = json.NewEncoder(w).Encode(agentCapabilitiesManifest)+ _ = json.NewEncoder(w).Encode(agentcapabilities.CanonicalManifest())}diff --git a/internal/api/agent_capabilities_test.go b/internal/api/agent_capabilities_test.goindex 0eb287457b..b803279ec4 100644--- a/internal/api/agent_capabilities_test.go+++ b/internal/api/agent_capabilities_test.go@@ -6,6 +6,9 @@ import ("net/http/httptest""strings""testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+ "github.com/rcourtman/pulse-go-rewrite/internal/config")func TestHandleAgentCapabilitiesManifest_ReturnsStableShape(t *testing.T) {@@ -33,9 +36,110 @@ func TestHandleAgentCapabilitiesManifest_ReturnsStableShape(t *testing.T) {if manifest.Version != "v1" {t.Errorf("version pin: got %q want v1", manifest.Version)}+ if manifest.SurfaceContract.Core.Label != "Pulse Intelligence Core" {+ t.Fatalf("manifest must expose Pulse Intelligence Core surface contract, got %+v", manifest.SurfaceContract)+ }+ if len(manifest.SurfaceContract.OperatorSurfaces) != 2 {+ t.Fatalf("manifest access path count = %d, want Assistant and MCP", len(manifest.SurfaceContract.OperatorSurfaces))+ }+ surfaceIDs := map[string]bool{}+ for _, surface := range manifest.SurfaceContract.OperatorSurfaces {+ surfaceIDs[surface.ID] = true+ }+ if !surfaceIDs["pulse_assistant"] || !surfaceIDs["pulse_mcp"] || surfaceIDs["pulse_patrol"] {+ t.Fatalf("manifest compatibility access paths must be Assistant and MCP; Patrol is the primary built-in operator component, got %+v", manifest.SurfaceContract.OperatorSurfaces)+ }+ if len(manifest.SurfaceToolContracts) != 1 {+ t.Fatalf("manifest surfaceToolContracts = %+v, want static Pulse MCP tool posture", manifest.SurfaceToolContracts)+ }+ mcpSurfaceTools := manifest.SurfaceToolContracts[0]+ if mcpSurfaceTools.SurfaceID != agentcapabilities.SurfaceIDPulseMCP || mcpSurfaceTools.ToolSource != agentcapabilities.SurfaceToolSourceCapabilityManifest {+ t.Fatalf("manifest MCP surface tool contract = %+v", mcpSurfaceTools)+ }+ for _, name := range mcpSurfaceTools.ToolNames {+ if name == agentcapabilities.EventSubscriptionCapabilityName || name == agentcapabilities.PulseQuestionToolName {+ t.Fatalf("manifest MCP surface tool names must exclude streaming/native tools, got %#v", mcpSurfaceTools.ToolNames)+ }+ }if len(manifest.Capabilities) == 0 {t.Fatal("manifest must declare at least one capability")}+ if len(manifest.Categories) == 0 {+ t.Fatal("manifest must declare category presentation metadata")+ }+ wantPrompts := agentcapabilities.ProjectPulseWorkflowPrompts(manifest.Capabilities)+ if len(manifest.WorkflowPrompts) == 0 {+ t.Fatal("manifest must declare shared workflow prompts")+ }+ if len(manifest.WorkflowPrompts) != len(wantPrompts) {+ t.Fatalf("manifest workflowPrompts length = %d, want %d", len(manifest.WorkflowPrompts), len(wantPrompts))+ }+ for i := range manifest.WorkflowPrompts {+ if manifest.WorkflowPrompts[i].Name != wantPrompts[i].Name {+ t.Fatalf("manifest workflowPrompts[%d].name = %q, want %q", i, manifest.WorkflowPrompts[i].Name, wantPrompts[i].Name)+ }+ }+ wantScopes := agentcapabilities.RequiredCapabilityScopes(manifest.Capabilities)+ if strings.Join(manifest.RequiredScopes, "\n") != strings.Join(wantScopes, "\n") {+ t.Fatalf("manifest requiredScopes = %v, want %v", manifest.RequiredScopes, wantScopes)+ }+ knownCategories := map[string]bool{}+ for _, category := range manifest.Categories {+ if category.ID == "" || category.Label == "" {+ t.Fatalf("manifest category metadata must declare id and label, got %+v", category)+ }+ knownCategories[category.ID] = true+ }++ foundPlanAction := false+ foundFleetContextOutputSchema := false+ foundListNodesOutputSchema := false+ missingOutputSchemas := []string{}+ for _, cap := range manifest.Capabilities {+ if !knownCategories[cap.Category] {+ t.Errorf("capability %q category %q missing from manifest category metadata", cap.Name, cap.Category)+ }+ if agentcapabilities.IsRequestResponseCapability(cap) && strings.TrimSpace(cap.ResponseShape) != "" && len(cap.OutputSchema) == 0 {+ missingOutputSchemas = append(missingOutputSchemas, cap.Name)+ }+ if len(cap.OutputSchema) > 0 {+ var schema map[string]any+ if err := json.Unmarshal(cap.OutputSchema, &schema); err != nil {+ t.Errorf("capability %q outputSchema must be valid JSON Schema: %v", cap.Name, err)+ }+ if schema["type"] != "object" {+ t.Errorf("capability %q outputSchema type = %v, want object for MCP structuredContent", cap.Name, schema["type"])+ }+ }+ if cap.Name == agentcapabilities.FleetContextCapabilityName && strings.Contains(string(cap.OutputSchema), `"resources"`) {+ foundFleetContextOutputSchema = true+ }+ if cap.Name == "list_nodes" && strings.Contains(string(cap.OutputSchema), `"items"`) && strings.Contains(string(cap.OutputSchema), `"count"`) {+ foundListNodesOutputSchema = true+ }+ if cap.Name != agentcapabilities.PlanActionCapabilityName {+ continue+ }+ foundPlanAction = true+ if cap.ActionMode != agentcapabilities.ActionModeWrite {+ t.Errorf("plan_action actionMode: got %q want %q", cap.ActionMode, agentcapabilities.ActionModeWrite)+ }+ if cap.ApprovalPolicy != agentcapabilities.ApprovalPolicyActionPlan {+ t.Errorf("plan_action approvalPolicy: got %q want %q", cap.ApprovalPolicy, agentcapabilities.ApprovalPolicyActionPlan)+ }+ }+ if !foundPlanAction {+ t.Fatalf("manifest must expose %s capability", agentcapabilities.PlanActionCapabilityName)+ }+ if !foundFleetContextOutputSchema {+ t.Fatalf("manifest must expose %s outputSchema so structured MCP results are typed", agentcapabilities.FleetContextCapabilityName)+ }+ if len(missingOutputSchemas) > 0 {+ t.Fatalf("manifest request/response capabilities with responseShape must expose outputSchema: %v", missingOutputSchemas)+ }+ if !foundListNodesOutputSchema {+ t.Fatal("manifest must expose list_nodes outputSchema for array structuredContent wrapper")+ }}func TestHandleAgentCapabilitiesManifest_RejectsNonGet(t *testing.T) {@@ -53,7 +157,8 @@ func TestAgentCapabilitiesManifest_NamesAreUniqueAndSnakeCase(t *testing.T) {// non-snake_case would break the convention agents use for tool// names. Pin both invariants.seen := map[string]bool{}- for _, cap := range agentCapabilitiesManifest.Capabilities {+ manifest := agentcapabilities.CanonicalManifest()+ for _, cap := range manifest.Capabilities {if seen[cap.Name] {t.Errorf("duplicate capability name %q — names are agent-stable identifiers", cap.Name)}@@ -75,7 +180,8 @@ func TestAgentCapabilitiesManifest_NamesAreUniqueAndSnakeCase(t *testing.T) {func TestAgentCapabilitiesManifest_EveryCapabilityDeclaresMethodPathScope(t *testing.T) {// Without method/path/scope, an agent can't actually call the// capability. These three are the minimum viable contract.- for _, cap := range agentCapabilitiesManifest.Capabilities {+ manifest := agentcapabilities.CanonicalManifest()+ for _, cap := range manifest.Capabilities {if cap.Method == "" {t.Errorf("capability %q missing method", cap.Name)}@@ -94,19 +200,147 @@ func TestAgentCapabilitiesManifest_EveryCapabilityDeclaresMethodPathScope(t *tes}}+func TestAgentCapabilitiesManifest_ScopesMatchAPIAuthConstants(t *testing.T) {+ expected := map[string]string{+ agentcapabilities.ResourceContextCapabilityName: config.ScopeMonitoringRead,+ agentcapabilities.FleetContextCapabilityName: config.ScopeMonitoringRead,+ agentcapabilities.OperationsLoopStatusCapabilityName: config.ScopeMonitoringRead,+ "list_nodes": config.ScopeSettingsRead,+ "add_node": config.ScopeSettingsWrite,+ "update_node": config.ScopeSettingsWrite,+ "remove_node": config.ScopeSettingsWrite,+ "test_node_credentials": config.ScopeSettingsWrite,+ "test_node_connection": config.ScopeSettingsWrite,+ "refresh_node_cluster_membership": config.ScopeSettingsWrite,+ "discover_lan": config.ScopeSettingsWrite,+ agentcapabilities.GetOperatorStateCapabilityName: config.ScopeMonitoringRead,+ agentcapabilities.SetOperatorStateCapabilityName: config.ScopeMonitoringWrite,+ agentcapabilities.ClearOperatorStateCapabilityName: config.ScopeMonitoringWrite,+ agentcapabilities.EventSubscriptionCapabilityName: config.ScopeMonitoringRead,+ agentcapabilities.ListFindingsCapabilityName: config.ScopeAIExecute,+ agentcapabilities.AcknowledgeFindingCapabilityName: config.ScopeAIExecute,+ agentcapabilities.SnoozeFindingCapabilityName: config.ScopeAIExecute,+ agentcapabilities.DismissFindingCapabilityName: config.ScopeAIExecute,+ agentcapabilities.ResolveFindingCapabilityName: config.ScopeAIExecute,+ agentcapabilities.PlanActionCapabilityName: config.ScopeAIExecute,+ agentcapabilities.DecideActionCapabilityName: config.ScopeAIExecute,+ agentcapabilities.ExecuteActionCapabilityName: config.ScopeAIExecute,+ }++ manifest := agentcapabilities.CanonicalManifest()+ if len(manifest.Capabilities) != len(expected) {+ t.Fatalf("expected scope map for every manifest capability: manifest=%d expected=%d", len(manifest.Capabilities), len(expected))+ }++ for _, cap := range manifest.Capabilities {+ want, ok := expected[cap.Name]+ if !ok {+ t.Errorf("capability %q missing from expected API scope map", cap.Name)+ continue+ }+ if cap.Scope != want {+ t.Errorf("capability %q scope = %q, want API auth scope %q", cap.Name, cap.Scope, want)+ }+ }+}++func TestAgentCapabilitiesManifest_PatrolFindingScopesMatchAPIRoutes(t *testing.T) {+ manifest := agentcapabilities.CanonicalManifest()+ byName := map[string]agentcapabilities.Capability{}+ for _, cap := range manifest.Capabilities {+ byName[cap.Name] = cap+ }++ expected := map[string]relayMobileRuntimeRouteID{+ agentcapabilities.ListFindingsCapabilityName: relayMobileRoutePatrolFindingsList,+ agentcapabilities.AcknowledgeFindingCapabilityName: relayMobileRoutePatrolAcknowledge,+ agentcapabilities.SnoozeFindingCapabilityName: relayMobileRoutePatrolSnooze,+ agentcapabilities.DismissFindingCapabilityName: relayMobileRoutePatrolDismiss,+ }+ for capabilityName, routeID := range expected {+ capability, ok := byName[capabilityName]+ if !ok {+ t.Fatalf("manifest missing Patrol finding capability %q", capabilityName)+ }+ route := relayMobileRuntimeRouteSpecFor(routeID)+ if capability.Method != route.method || capability.Path != route.path || capability.Scope != route.requiredScope {+ t.Fatalf("%s manifest route/scope = %s %s => %s, want API route %s %s => %s",+ capabilityName, capability.Method, capability.Path, capability.Scope, route.method, route.path, route.requiredScope)+ }+ }++ resolve, ok := byName[agentcapabilities.ResolveFindingCapabilityName]+ if !ok {+ t.Fatalf("manifest missing Patrol finding capability %q", agentcapabilities.ResolveFindingCapabilityName)+ }+ if resolve.Method != http.MethodPost || resolve.Path != "/api/ai/patrol/resolve" || resolve.Scope != config.ScopeAIExecute {+ t.Fatalf("%s manifest route/scope = %s %s => %s, want API route POST /api/ai/patrol/resolve => %s",+ agentcapabilities.ResolveFindingCapabilityName, resolve.Method, resolve.Path, resolve.Scope, config.ScopeAIExecute)+ }+}++func TestAgentCapabilitiesManifest_EveryCapabilityDeclaresGovernance(t *testing.T) {+ // External agents need to know whether a capability is only a+ // read, a non-persistent check/scan, or a write before choosing+ // a tool. Keep that posture on the manifest instead of letting+ // adapters infer it from HTTP method alone.+ allowedActionModes := map[agentcapabilities.ActionMode]bool{+ agentcapabilities.ActionModeRead: true,+ agentcapabilities.ActionModeMixed: true,+ agentcapabilities.ActionModeWrite: true,+ }+ allowedApprovalPolicies := map[agentcapabilities.ApprovalPolicy]bool{+ agentcapabilities.ApprovalPolicyScopeOnly: true,+ agentcapabilities.ApprovalPolicyActionPlan: true,+ }++ manifest := agentcapabilities.CanonicalManifest()+ for _, cap := range manifest.Capabilities {+ if !allowedActionModes[cap.ActionMode] {+ t.Errorf("capability %q has unknown actionMode %q", cap.Name, cap.ActionMode)+ }+ if !allowedApprovalPolicies[cap.ApprovalPolicy] {+ t.Errorf("capability %q has unknown approvalPolicy %q", cap.Name, cap.ApprovalPolicy)+ }+ if cap.Method == http.MethodGet && cap.ActionMode != agentcapabilities.ActionModeRead {+ t.Errorf("GET capability %q actionMode = %q, want read", cap.Name, cap.ActionMode)+ }+ if cap.Category == "action" && cap.ApprovalPolicy != agentcapabilities.ApprovalPolicyActionPlan {+ t.Errorf("action capability %q approvalPolicy = %q, want action_plan", cap.Name, cap.ApprovalPolicy)+ }+ if cap.Category != "action" && cap.ApprovalPolicy == agentcapabilities.ApprovalPolicyActionPlan {+ t.Errorf("non-action capability %q must not claim action_plan approval policy", cap.Name)+ }+ }+}+func TestAgentCapabilitiesManifest_CategoriesAreClosed(t *testing.T) {// Agents filter the manifest by category. Keep the set closed// so a typo in a future capability doesn't fragment the surface// (e.g. "operator-state" vs "operator_state" would split into// two categories an agent might miss).- allowed := map[string]bool{- "context": true,- "provisioning": true,- "operator-state": true,- "finding": true,- "action": true,- }- for _, cap := range agentCapabilitiesManifest.Capabilities {+ expectedOrder := []string{+ "context",+ "operator-state",+ "finding",+ "action",+ "provisioning",+ }+ manifest := agentcapabilities.CanonicalManifest()+ if len(manifest.Categories) != len(expectedOrder) {+ t.Fatalf("manifest categories = %v, want %v", manifest.Categories, expectedOrder)+ }+ allowed := map[string]bool{}+ for i, category := range manifest.Categories {+ if category.ID != expectedOrder[i] {+ t.Fatalf("manifest category order[%d] = %q, want %q", i, category.ID, expectedOrder[i])+ }+ if category.Label == "" || category.Description == "" {+ t.Fatalf("manifest category %q must include presentation label and description", category.ID)+ }+ allowed[category.ID] = true+ }+ for _, cap := range manifest.Capabilities {if !allowed[cap.Category] {t.Errorf("capability %q has unknown category %q — extend the allowlist deliberately", cap.Name, cap.Category)}@@ -115,7 +349,8 @@ func TestAgentCapabilitiesManifest_CategoriesAreClosed(t *testing.T) {func TestAgentCapabilitiesManifest_DeclaresNodeProvisioningSurface(t *testing.T) {byName := map[string]AgentCapability{}- for _, cap := range agentCapabilitiesManifest.Capabilities {+ manifest := agentcapabilities.CanonicalManifest()+ for _, cap := range manifest.Capabilities {byName[cap.Name] = cap}@@ -185,18 +420,121 @@ func TestAgentCapabilitiesManifest_DeclaresNodeProvisioningSurface(t *testing.T)}}+func TestAgentCapabilitiesManifest_DeclaresTypedFindingAndActionSchemas(t *testing.T) {+ byName := map[string]AgentCapability{}+ manifest := agentcapabilities.CanonicalManifest()+ for _, cap := range manifest.Capabilities {+ byName[cap.Name] = cap+ }++ assertInputSchemaFragments(t, byName, agentcapabilities.SetOperatorStateCapabilityName, []string{+ requiredSchemaFragment(agentcapabilities.ResourceIDArgumentName, "intentionallyOffline", "neverAutoRemediate"),+ `"dependencies":{"maintenanceEndAt":["maintenanceStartAt"],"maintenanceStartAt":["maintenanceEndAt"]}`,+ `"enum":["high","medium","low",""]`,+ })+ assertInputSchemaFragments(t, byName, agentcapabilities.AcknowledgeFindingCapabilityName, []string{+ requiredSchemaFragment(agentcapabilities.FindingIDArgumentName),+ `"additionalProperties":false`,+ })+ assertInputSchemaFragments(t, byName, agentcapabilities.SnoozeFindingCapabilityName, []string{+ requiredSchemaFragment(agentcapabilities.FindingIDArgumentName, "duration_hours"),+ `"minimum":1`,+ `"maximum":168`,+ })+ assertInputSchemaFragments(t, byName, agentcapabilities.DismissFindingCapabilityName, []string{+ requiredSchemaFragment(agentcapabilities.FindingIDArgumentName, agentcapabilities.ReasonArgumentName),+ `"enum":["not_an_issue","expected_behavior","will_fix_later"]`,+ `"` + agentcapabilities.NoteArgumentName + `"`,+ })+ assertInputSchemaFragments(t, byName, agentcapabilities.ResolveFindingCapabilityName, []string{+ requiredSchemaFragment(agentcapabilities.FindingIDArgumentName),+ `"` + agentcapabilities.ResolutionNoteArgumentName + `"`,+ })+ assertInputSchemaFragments(t, byName, agentcapabilities.PlanActionCapabilityName, []string{+ requiredSchemaFragment(+ agentcapabilities.RequestIDArgumentName,+ agentcapabilities.ResourceIDArgumentName,+ agentcapabilities.CapabilityNameArgumentName,+ agentcapabilities.ReasonArgumentName,+ agentcapabilities.RequestedByArgumentName,+ ),+ `"params"`,+ `"additionalProperties":true`,+ })+ assertInputSchemaFragments(t, byName, agentcapabilities.DecideActionCapabilityName, []string{+ requiredSchemaFragment(agentcapabilities.ActionIDArgumentName, agentcapabilities.OutcomeArgumentName),+ `"enum":["approved","rejected"]`,+ `"pattern":"^[a-zA-Z0-9_-]+$"`,+ })+ assertInputSchemaFragments(t, byName, agentcapabilities.ExecuteActionCapabilityName, []string{+ requiredSchemaFragment(agentcapabilities.ActionIDArgumentName),+ `"maxLength":128`,+ })+}++func requiredSchemaFragment(fields ...string) string {+ raw, _ := json.Marshal(fields)+ return `"required":` + string(raw)+}++func assertInputSchemaFragments(t *testing.T, byName map[string]AgentCapability, name string, fragments []string) {+ t.Helper()+ cap, ok := byName[name]+ if !ok {+ t.Fatalf("manifest missing capability %q", name)+ }+ if cap.InputSchema == nil {+ t.Fatalf("%s must publish an inputSchema", name)+ }+ raw, err := json.Marshal(cap.InputSchema)+ if err != nil {+ t.Fatalf("%s inputSchema marshal: %v", name, err)+ }+ text := string(raw)+ for _, fragment := range fragments {+ if !strings.Contains(text, fragment) {+ t.Errorf("%s inputSchema missing %s: %s", name, fragment, text)+ }+ }+}+func TestAgentCapabilitiesManifest_CarriesStableErrorCodes(t *testing.T) {// The error-code surface is the agent-branching contract. The// codes I've shipped this session must appear on the// corresponding capability so agents can branch on them. Pin a// few of the most consequential codes.wantErrorCodes := map[string][]string{- "get_resource_context": {"resource_not_found"},- "get_operator_state": {"operator_state_not_set"},- "set_operator_state": {"operator_state_invalid"},+ agentcapabilities.ResourceContextCapabilityName: {agentcapabilities.AgentErrCodeResourceNotFound},+ agentcapabilities.GetOperatorStateCapabilityName: {agentcapabilities.AgentErrCodeOperatorStateNotSet},+ agentcapabilities.SetOperatorStateCapabilityName: {agentcapabilities.AgentErrCodeOperatorStateInvalid},+ agentcapabilities.AcknowledgeFindingCapabilityName: {+ agentcapabilities.AgentErrCodeInvalidFindingRequest,+ agentcapabilities.AgentErrCodeFindingNotFound,+ agentcapabilities.AgentErrCodeFindingActionNotAllowed,+ agentcapabilities.AgentErrCodePatrolUnavailable,+ },+ agentcapabilities.SnoozeFindingCapabilityName: {+ agentcapabilities.AgentErrCodeInvalidFindingRequest,+ agentcapabilities.AgentErrCodeFindingNotFound,+ agentcapabilities.AgentErrCodeFindingActionNotAllowed,+ agentcapabilities.AgentErrCodePatrolUnavailable,+ },+ agentcapabilities.DismissFindingCapabilityName: {+ agentcapabilities.AgentErrCodeInvalidFindingRequest,+ agentcapabilities.AgentErrCodeFindingNotFound,+ agentcapabilities.AgentErrCodeFindingActionNotAllowed,+ agentcapabilities.AgentErrCodePatrolUnavailable,+ },+ agentcapabilities.ResolveFindingCapabilityName: {+ agentcapabilities.AgentErrCodeInvalidFindingRequest,+ agentcapabilities.AgentErrCodeFindingNotFound,+ agentcapabilities.AgentErrCodeFindingActionNotAllowed,+ agentcapabilities.AgentErrCodePatrolUnavailable,+ },}byName := map[string]AgentCapability{}- for _, cap := range agentCapabilitiesManifest.Capabilities {+ manifest := agentcapabilities.CanonicalManifest()+ for _, cap := range manifest.Capabilities {byName[cap.Name] = cap}for name, expected := range wantErrorCodes {diff --git a/internal/api/agent_events.go b/internal/api/agent_events.goindex a7705a7fee..00189a924e 100644--- a/internal/api/agent_events.go+++ b/internal/api/agent_events.go@@ -8,6 +8,7 @@ import ("sync/atomic""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources""github.com/rs/zerolog/log")@@ -23,7 +24,7 @@ const (// against any resource. Payload carries the finding's canonical// id, resource id, severity, title, and category — enough for an// agent to decide whether to fetch the full situated context.- AgentEventFindingCreated AgentEventKind = "finding.created"+ AgentEventFindingCreated AgentEventKind = AgentEventKind(agentcapabilities.EventKindFindingCreated)// AgentEventApprovalPending fires when a remediation request enters// StatusPending and is waiting on an operator (or operator-acting@@ -33,7 +34,7 @@ const (// action-capable API tokens; monitoring-read subscribers receive// a redacted doorbell and can fetch governed detail through the// approval/action surfaces when authorized.- AgentEventApprovalPending AgentEventKind = "approval.pending"+ AgentEventApprovalPending AgentEventKind = AgentEventKind(agentcapabilities.EventKindApprovalPending)// AgentEventActionCompleted fires when an action audit reaches a// terminal state — Completed (executed and verified) or Failed@@ -44,13 +45,17 @@ const (// error message), who acted, and the completion timestamp —// enough for an agent to close the dispatch loop without polling// the audit endpoint.- AgentEventActionCompleted AgentEventKind = "action.completed"+ AgentEventActionCompleted AgentEventKind = AgentEventKind(agentcapabilities.EventKindActionCompleted)++ // AgentEventStreamConnected is emitted once when an SSE subscriber connects+ // so clients can distinguish a healthy stream from an idle one.+ AgentEventStreamConnected AgentEventKind = AgentEventKind(agentcapabilities.EventKindStreamConnected)// AgentEventHeartbeat is a keepalive that fires at a fixed// interval. Agents that hold an open SSE connection use it to// confirm the stream is healthy without waiting for a real// event.- AgentEventHeartbeat AgentEventKind = "heartbeat"+ AgentEventHeartbeat AgentEventKind = AgentEventKind(agentcapabilities.EventKindHeartbeat))// AgentEvent is the agent-stable event envelope. Carries the kind, a@@ -267,7 +272,7 @@ func (b *AgentEventBroadcaster) HandleAgentEvents(w http.ResponseWriter, r *http// distinct from heartbeat: the connected event fires once at// subscribe time, the heartbeat fires periodically.writeAgentSSEEvent(w, AgentEvent{- Kind: "stream.connected",+ Kind: AgentEventStreamConnected,At: time.Now().UTC(),})flusher.Flush()diff --git a/internal/api/agent_events_test.go b/internal/api/agent_events_test.goindex e08cd21d71..2b33b9f6c5 100644--- a/internal/api/agent_events_test.go+++ b/internal/api/agent_events_test.go@@ -9,6 +9,7 @@ import ("testing""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/config"unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")@@ -217,7 +218,7 @@ func TestHandleAgentEvents_StreamsConnectedAndPublishedEvents(t *testing.T) {select {case payload := <-got:- if !strings.Contains(payload, "stream.connected") {+ if !strings.Contains(payload, string(agentcapabilities.EventKindStreamConnected)) {t.Error("expected stream.connected event before any published events")}if !strings.Contains(payload, "f-stream") {@@ -391,9 +392,9 @@ func TestAgentEventApprovalPendingKindIsStable(t *testing.T) {// Pin the wire-stable kind string. Renaming it breaks every agent// that branches on the event type; the constant is part of the// contract, not an implementation detail.- if AgentEventApprovalPending != "approval.pending" {+ if AgentEventApprovalPending != AgentEventKind(agentcapabilities.EventKindApprovalPending) {t.Fatalf("AgentEventApprovalPending changed: got %q want %q",- AgentEventApprovalPending, "approval.pending")+ AgentEventApprovalPending, agentcapabilities.EventKindApprovalPending)}}@@ -563,9 +564,9 @@ func TestAgentEventBroadcaster_PublishActionCompletedPreservesRefusalToken(t *tefunc TestAgentEventActionCompletedKindIsStable(t *testing.T) {// Pin the wire-stable kind string. Renaming it breaks every// agent that branches on the event type.- if AgentEventActionCompleted != "action.completed" {+ if AgentEventActionCompleted != AgentEventKind(agentcapabilities.EventKindActionCompleted) {t.Fatalf("AgentEventActionCompleted changed: got %q want %q",- AgentEventActionCompleted, "action.completed")+ AgentEventActionCompleted, agentcapabilities.EventKindActionCompleted)}}diff --git a/internal/api/agent_profiles_tools.go b/internal/api/agent_profiles_tools.goindex 615644d722..5c098a6954 100644--- a/internal/api/agent_profiles_tools.go+++ b/internal/api/agent_profiles_tools.go@@ -15,22 +15,22 @@ import (const aiProfileDescription = "Managed by Pulse Patrol"-// MCPAgentProfileManager manages agent profiles for MCP tools.-type MCPAgentProfileManager struct {+// AssistantAgentProfileManager manages agent profiles for Assistant tools.+type AssistantAgentProfileManager struct {persistence *config.ConfigPersistencelicenseService licenseFeatureCheckervalidator *models.ProfileValidator}-func NewMCPAgentProfileManager(persistence *config.ConfigPersistence, licenseService licenseFeatureChecker) *MCPAgentProfileManager {- return &MCPAgentProfileManager{+func NewAssistantAgentProfileManager(persistence *config.ConfigPersistence, licenseService licenseFeatureChecker) *AssistantAgentProfileManager {+ return &AssistantAgentProfileManager{persistence: persistence,licenseService: licenseService,validator: models.NewProfileValidator(),}}-func (m *MCPAgentProfileManager) ApplyAgentScope(_ context.Context, agentID, agentLabel string, settings map[string]interface{}) (string, string, bool, error) {+func (m *AssistantAgentProfileManager) ApplyAgentScope(_ context.Context, agentID, agentLabel string, settings map[string]interface{}) (string, string, bool, error) {if err := m.requireLicense(); err != nil {return "", "", false, err}@@ -116,7 +116,7 @@ func (m *MCPAgentProfileManager) ApplyAgentScope(_ context.Context, agentID, agereturn profile.ID, profile.Name, created, nil}-func (m *MCPAgentProfileManager) AssignProfile(_ context.Context, agentID, profileID string) (string, error) {+func (m *AssistantAgentProfileManager) AssignProfile(_ context.Context, agentID, profileID string) (string, error) {if err := m.requireLicense(); err != nil {return "", err}@@ -154,7 +154,7 @@ func (m *MCPAgentProfileManager) AssignProfile(_ context.Context, agentID, profireturn profile.Name, nil}-func (m *MCPAgentProfileManager) GetAgentScope(_ context.Context, agentID string) (*tools.AgentScope, error) {+func (m *AssistantAgentProfileManager) GetAgentScope(_ context.Context, agentID string) (*tools.AgentScope, error) {if err := m.requireLicense(); err != nil {return nil, err}@@ -202,7 +202,7 @@ func (m *MCPAgentProfileManager) GetAgentScope(_ context.Context, agentID stringreturn nil, nil}-func (m *MCPAgentProfileManager) assignProfile(agentID string, profile models.AgentProfile, username string) error {+func (m *AssistantAgentProfileManager) assignProfile(agentID string, profile models.AgentProfile, username string) error {assignments, err := m.persistence.LoadAgentProfileAssignments()if err != nil {return fmt.Errorf("failed to load assignments: %w", err)@@ -240,7 +240,7 @@ func (m *MCPAgentProfileManager) assignProfile(agentID string, profile models.Agreturn nil}-func (m *MCPAgentProfileManager) validateSettings(settings map[string]interface{}) error {+func (m *AssistantAgentProfileManager) validateSettings(settings map[string]interface{}) error {if m.validator == nil {return nil}@@ -265,7 +265,7 @@ func formatValidationIssues(result models.ValidationResult) string {return strings.Join(parts, "; ")}-func (m *MCPAgentProfileManager) saveVersion(profile models.AgentProfile, note string) error {+func (m *AssistantAgentProfileManager) saveVersion(profile models.AgentProfile, note string) error {versions, err := m.persistence.LoadAgentProfileVersions()if err != nil {return fmt.Errorf("load profile versions: %w", err)@@ -289,13 +289,13 @@ func (m *MCPAgentProfileManager) saveVersion(profile models.AgentProfile, note sreturn nil}-func (m *MCPAgentProfileManager) logChange(entry models.ProfileChangeLog) {+func (m *AssistantAgentProfileManager) logChange(entry models.ProfileChangeLog) {if err := m.persistence.AppendProfileChangeLog(entry); err != nil {log.Warn().Err(err).Msg("Failed to log profile change")}}-func (m *MCPAgentProfileManager) requireLicense() error {+func (m *AssistantAgentProfileManager) requireLicense() error {if m.licenseService == nil {return nil}diff --git a/internal/api/agent_profiles_tools_extra_test.go b/internal/api/agent_profiles_tools_extra_test.goindex 95be7a3cc6..dfbcb7f716 100644--- a/internal/api/agent_profiles_tools_extra_test.go+++ b/internal/api/agent_profiles_tools_extra_test.go@@ -41,7 +41,7 @@ func TestBuildScopeProfileName(t *testing.T) {}}-func TestMCPAgentProfileManager_ValidateSettings(t *testing.T) {+func TestAssistantAgentProfileManager_ValidateSettings(t *testing.T) {manager := newTestProfileManager(t)if err := manager.validateSettings(map[string]interface{}{"unknown_key": true}); err == nil {t.Fatalf("expected validation error for warnings")@@ -51,10 +51,10 @@ func TestMCPAgentProfileManager_ValidateSettings(t *testing.T) {}}-func TestMCPAgentProfileManager_RequireLicense(t *testing.T) {+func TestAssistantAgentProfileManager_RequireLicense(t *testing.T) {persistence := config.NewConfigPersistence(t.TempDir())licenseService := license.NewService()- manager := NewMCPAgentProfileManager(persistence, licenseService)+ manager := NewAssistantAgentProfileManager(persistence, licenseService)_, _, _, err := manager.ApplyAgentScope(context.Background(), "agent-1", "Alpha", map[string]interface{}{"enable_host": true})if err == nil {@@ -62,7 +62,7 @@ func TestMCPAgentProfileManager_RequireLicense(t *testing.T) {}}-func TestMCPAgentProfileManager_SaveVersion(t *testing.T) {+func TestAssistantAgentProfileManager_SaveVersion(t *testing.T) {manager := newTestProfileManager(t)profile := models.AgentProfile{ID: "profile-1",@@ -84,14 +84,14 @@ func TestMCPAgentProfileManager_SaveVersion(t *testing.T) {}}-func TestMCPAgentProfileManager_AssignProfile_NotFound(t *testing.T) {+func TestAssistantAgentProfileManager_AssignProfile_NotFound(t *testing.T) {manager := newTestProfileManager(t)if _, err := manager.AssignProfile(context.Background(), "agent-1", "missing"); err == nil {t.Fatalf("expected error for missing profile")}}-func TestMCPAgentProfileManager_GetScope_EmptyAgent(t *testing.T) {+func TestAssistantAgentProfileManager_GetScope_EmptyAgent(t *testing.T) {manager := newTestProfileManager(t)if _, err := manager.GetAgentScope(context.Background(), ""); err == nil {t.Fatalf("expected error for empty agent ID")diff --git a/internal/api/agent_profiles_tools_test.go b/internal/api/agent_profiles_tools_test.goindex 1caa5daba5..a3c7564a38 100644--- a/internal/api/agent_profiles_tools_test.go+++ b/internal/api/agent_profiles_tools_test.go@@ -8,13 +8,13 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/models")-func newTestProfileManager(t *testing.T) *MCPAgentProfileManager {+func newTestProfileManager(t *testing.T) *AssistantAgentProfileManager {t.Helper()persistence := config.NewConfigPersistence(t.TempDir())- return NewMCPAgentProfileManager(persistence, nil)+ return NewAssistantAgentProfileManager(persistence, nil)}-func TestMCPAgentProfileManagerApplyAndGetScope(t *testing.T) {+func TestAssistantAgentProfileManagerApplyAndGetScope(t *testing.T) {manager := newTestProfileManager(t)ctx := context.Background()@@ -64,7 +64,7 @@ func TestMCPAgentProfileManagerApplyAndGetScope(t *testing.T) {}}-func TestMCPAgentProfileManagerAssignProfile(t *testing.T) {+func TestAssistantAgentProfileManagerAssignProfile(t *testing.T) {manager := newTestProfileManager(t)ctx := context.Background()@@ -99,7 +99,7 @@ func TestMCPAgentProfileManagerAssignProfile(t *testing.T) {}}-func TestMCPAgentProfileManagerGetScopeMissing(t *testing.T) {+func TestAssistantAgentProfileManagerGetScopeMissing(t *testing.T) {manager := newTestProfileManager(t)scope, err := manager.GetAgentScope(context.Background(), "missing")diff --git a/internal/api/agent_resource_context.go b/internal/api/agent_resource_context.goindex 6baaaaf82d..91a6d656e9 100644--- a/internal/api/agent_resource_context.go+++ b/internal/api/agent_resource_context.go@@ -1,14 +1,18 @@package apiimport (+ "context""encoding/json""net/http""reflect""strings""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentcontext""github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"+ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/telemetry"unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")@@ -134,6 +138,72 @@ type AgentFleetContext struct {GeneratedAt time.Time `json:"generatedAt"`}+type AgentOperationsLoopStepStatus string++const (+ agentOperationsLoopActionWindow = 30 * 24 * time.Hour++ AgentOperationsLoopStepComplete AgentOperationsLoopStepStatus = "complete"+ AgentOperationsLoopStepCurrent AgentOperationsLoopStepStatus = "current"+ AgentOperationsLoopStepPending AgentOperationsLoopStepStatus = "pending"+)++// AgentOperationsLoopStep is a content-safe step rollup for the Patrol+// control loop: Patrol issue evidence, Assistant/context explanation,+// governed approve/reject decision, and verified outcome. Counts are aggregate+// only and never carry finding ids, action ids, resource names, commands,+// prompts, or output. External-agent readiness is a separate capability signal,+// not a Patrol operator step.+type AgentOperationsLoopStep struct {+ ID string `json:"id"`+ Label string `json:"label"`+ Status AgentOperationsLoopStepStatus `json:"status"`+ Count int `json:"count,omitempty"`+}++// AgentOperationsLoopStatus is the agent-consumable status projection for the+// same Pulse Intelligence loop shown in the native Patrol control journey. It+// exists so external MCP agents can orient on the operator stage without+// reverse-engineering it from fleet context, finding lists, approvals, and+// action audits. The payload is intentionally count-only. MCP readiness stays+// separate from steps so optional external access does not look like a required+// user journey stage.+type AgentOperationsLoopStatus struct {+ NextAction string `json:"nextAction"`+ ProgressLabel string `json:"progressLabel"`+ Steps []AgentOperationsLoopStep `json:"steps"`+ PatrolEvidenceCount int `json:"patrolEvidenceCount"`+ PatrolIssueEvidenceCount int `json:"patrolIssueEvidenceCount"`+ ActiveFindingCount int `json:"activeFindingCount"`+ PendingApprovalCount int `json:"pendingApprovalCount"`+ GovernedActionCount int `json:"governedActionCount"`+ ApprovedDecisionCount int `json:"approvedDecisionCount"`+ RejectedDecisionCount int `json:"rejectedDecisionCount"`+ VerifiedOutcomeCount int `json:"verifiedOutcomeCount"`+ OperationsLoopStarterCount int `json:"operationsLoopStarterCount"`+ AssistantOperationsLoopStarterCount int `json:"assistantOperationsLoopStarterCount"`+ PatrolOperationsLoopStarterCount int `json:"patrolOperationsLoopStarterCount"`+ PatrolControlLoopStarterCount int `json:"patrolControlOperationsLoopStarterCount"`+ PatrolControlCompletedLoopCount int `json:"patrolControlCompletedOperationsLoopCount"`+ PatrolControlResolvedLoopCount int `json:"patrolControlResolvedOperationsLoopCount"`+ PatrolControlValueState string `json:"patrolControlValueState"`+ PatrolAutonomyLoopStarterCount int `json:"patrolAutonomyOperationsLoopStarterCount"`+ PatrolAutonomyCompletedLoopCount int `json:"patrolAutonomyCompletedOperationsLoopCount"`+ PatrolAutonomyResolvedLoopCount int `json:"patrolAutonomyResolvedOperationsLoopCount"`+ PatrolAutonomyValueState string `json:"patrolAutonomyValueState"`+ ProActivationLoopStarterCount int `json:"proActivationOperationsLoopStarterCount"`+ ProActivationCompletedLoopCount int `json:"proActivationCompletedOperationsLoopCount"`+ ProActivationResolvedLoopCount int `json:"proActivationResolvedOperationsLoopCount"`+ ProActivationValueProofState string `json:"proActivationValueProofState"`+ MCPOperationsLoopStarterCount int `json:"mcpOperationsLoopStarterCount"`+ ExternalAgentReady bool `json:"externalAgentReady"`+ WindowStart time.Time `json:"windowStart"`+ GeneratedAt time.Time `json:"generatedAt"`++ assistantContextCount int+ externalAgentCollaborationCount int+}+// AgentResourceOperatorState mirrors the canonical// `unified.ResourceOperatorState` but with the same JSON shape the// `/api/resources/{id}/operator-state` endpoint already returns. Kept@@ -205,14 +275,37 @@ type AgentResourceContext struct {GeneratedAt time.Time `json:"generatedAt"`}-// AgentFindingsProvider returns the active findings for a resource as-// agent-stable snapshots. The implementation lives outside this-// package (the patrol service holds the canonical findings store);-// this interface keeps the api layer free of an `internal/ai` import.+// AgentFindingsProvider returns active findings as agent-stable snapshots and+// count-only aggregate evidence. The implementation lives outside this package+// (the patrol service holds the canonical findings store); this interface keeps+// the api layer free of an `internal/ai` import.type AgentFindingsProvider interface {ActiveFindingsForResource(resourceID string) []AgentResourceFindingSnapshot}+type AgentAggregateFindingsProvider interface {+ ActiveFindingCount() int+}++type agentFindingsProvider struct {+ activeForResource func(resourceID string) []AgentResourceFindingSnapshot+ activeCount func() int+}++func (p agentFindingsProvider) ActiveFindingsForResource(resourceID string) []AgentResourceFindingSnapshot {+ if p.activeForResource == nil {+ return nil+ }+ return p.activeForResource(resourceID)+}++func (p agentFindingsProvider) ActiveFindingCount() int {+ if p.activeCount == nil {+ return 0+ }+ return p.activeCount()+}+// agentFindingsProviderFunc is a function adapter so wire-up code can// pass a closure without declaring a struct.type agentFindingsProviderFunc func(resourceID string) []AgentResourceFindingSnapshot@@ -261,9 +354,64 @@ func (agentApprovalStoreProvider) PendingApprovalCountsByResource(orgID string)// access (those are the canonical accessors); the// agent-findings adapter is held here.type AgentContextHandler struct {- resources *ResourceHandlers- findingsProvider AgentFindingsProvider- approvalsProvider AgentApprovalsProvider+ resources *ResourceHandlers+ findingsProvider AgentFindingsProvider+ approvalsProvider AgentApprovalsProvider+ workflowPromptActivityProvider AgentWorkflowPromptActivityProvider+ aiUsageProvider AgentAIUsageProvider+ externalAgentActivityProvider AgentExternalAgentActivityProvider+ externalAgentReadinessProvider AgentExternalAgentReadinessProvider+}++// AgentWorkflowPromptActivityProvider loads content-free workflow prompt+// starter activity for the current request context. Implementations are+// responsible for tenant resolution so the agent status projection can stay+// scoped to the authenticated org.+type AgentWorkflowPromptActivityProvider interface {+ WorkflowPromptActivityHistory(ctx context.Context) (*config.WorkflowPromptActivityHistoryData, error)+}++type agentWorkflowPromptActivityProviderFunc func(context.Context) (*config.WorkflowPromptActivityHistoryData, error)++func (fn agentWorkflowPromptActivityProviderFunc) WorkflowPromptActivityHistory(ctx context.Context) (*config.WorkflowPromptActivityHistoryData, error) {+ return fn(ctx)+}++// AgentAIUsageProvider loads content-free AI usage evidence for the operations+// loop status projection.+type AgentAIUsageProvider interface {+ AIUsageHistory(ctx context.Context) (*config.AIUsageHistoryData, error)+}++type agentAIUsageProviderFunc func(context.Context) (*config.AIUsageHistoryData, error)++func (fn agentAIUsageProviderFunc) AIUsageHistory(ctx context.Context) (*config.AIUsageHistoryData, error) {+ return fn(ctx)+}++// AgentExternalAgentActivityProvider loads content-free external-agent+// capability activity for the operations loop status projection.+type AgentExternalAgentActivityProvider interface {+ ExternalAgentActivityHistory(ctx context.Context) (*config.ExternalAgentActivityHistoryData, error)+}++type agentExternalAgentActivityProviderFunc func(context.Context) (*config.ExternalAgentActivityHistoryData, error)++func (fn agentExternalAgentActivityProviderFunc) ExternalAgentActivityHistory(ctx context.Context) (*config.ExternalAgentActivityHistoryData, error) {+ return fn(ctx)+}++// AgentExternalAgentReadinessProvider reports whether the current org has one+// non-expired token that can use the full Pulse MCP operations-loop tool set.+// The status payload exposes only the boolean, never token identity or counts.+type AgentExternalAgentReadinessProvider interface {+ ExternalAgentReady(ctx context.Context, manifest agentcapabilities.Manifest, now time.Time) bool+}++type agentExternalAgentReadinessProviderFunc func(context.Context, agentcapabilities.Manifest, time.Time) bool++func (fn agentExternalAgentReadinessProviderFunc) ExternalAgentReady(ctx context.Context, manifest agentcapabilities.Manifest, now time.Time) bool {+ return fn(ctx, manifest, now)}// NewAgentContextHandler creates a new agent context handler. The@@ -287,6 +435,32 @@ func (h *AgentContextHandler) SetApprovalsProvider(p AgentApprovalsProvider) {h.approvalsProvider = p}+// SetWorkflowPromptActivityProvider wires the content-free workflow starter+// activity source used by the operations-loop status projection. Pass nil to+// omit starter counts without affecting Patrol, governance, or verification+// evidence.+func (h *AgentContextHandler) SetWorkflowPromptActivityProvider(p AgentWorkflowPromptActivityProvider) {+ h.workflowPromptActivityProvider = p+}++// SetAIUsageProvider wires content-free Assistant usage evidence into the+// operations-loop status projection.+func (h *AgentContextHandler) SetAIUsageProvider(p AgentAIUsageProvider) {+ h.aiUsageProvider = p+}++// SetExternalAgentActivityProvider wires content-free external-agent activity+// evidence into the operations-loop status projection.+func (h *AgentContextHandler) SetExternalAgentActivityProvider(p AgentExternalAgentActivityProvider) {+ h.externalAgentActivityProvider = p+}++// SetExternalAgentReadinessProvider wires the token-backed external-agent+// setup signal used by the operations-loop status projection.+func (h *AgentContextHandler) SetExternalAgentReadinessProvider(p AgentExternalAgentReadinessProvider) {+ h.externalAgentReadinessProvider = p+}+// HandleResourceContext serves// `GET /api/agent/resource-context/{id}` — the agent-consumable// situated picture of a resource. Bundle is computed at request time@@ -316,7 +490,7 @@ func (h *AgentContextHandler) HandleResourceContext(w http.ResponseWriter, r *ht}resource, resourceID, ok := presentationResourceByReference(registry, resourceID)if !ok {- writeJSONError(w, http.StatusNotFound, "resource_not_found",+ writeJSONError(w, http.StatusNotFound, agentcapabilities.AgentErrCodeResourceNotFound,"No resource is registered with this canonical id.")return}@@ -513,6 +687,118 @@ func (h *AgentContextHandler) HandleFleetContext(w http.ResponseWriter, r *http._ = json.NewEncoder(w).Encode(out)}+// HandleOperationsLoopStatus serves the content-safe status read for the shared+// Pulse Intelligence Patrol control loop. The canonical route is+// `GET /api/agent/patrol-control/status`; `GET /api/agent/operations-loop/status`+// remains as a compatibility alias. It deliberately summarizes counts and+// stage state instead of exposing finding ids, action ids, commands, prompts,+// output, or resource names.+func (h *AgentContextHandler) HandleOperationsLoopStatus(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }+ if h.resources == nil {+ http.Error(w, "Internal server error", http.StatusInternalServerError)+ return+ }++ orgID := GetOrgID(r.Context())+ registry, err := h.resources.buildRegistry(orgID)+ if err != nil {+ http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)+ return+ }+ store, err := h.resources.getStore(orgID)+ if err != nil {+ http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)+ return+ }++ now := time.Now().UTC()+ windowStart := now.Add(-agentOperationsLoopActionWindow)+ manifest := agentcapabilities.CanonicalManifest()+ status := AgentOperationsLoopStatus{+ Steps: []AgentOperationsLoopStep{},+ ExternalAgentReady: h.agentOperationsLoopExternalAgentReady(r.Context(), manifest, now),+ WindowStart: windowStart,+ GeneratedAt: now,+ }++ pendingByResource := map[string]int{}+ if h.approvalsProvider != nil {+ if counts := h.approvalsProvider.PendingApprovalCountsByResource(orgID); counts != nil {+ pendingByResource = counts+ }+ }++ for _, resource := range registry.List() {+ canonical := unified.CanonicalResourceID(resource.ID)+ if h.findingsProvider != nil {+ status.ActiveFindingCount += len(h.findingsProvider.ActiveFindingsForResource(canonical))+ }+ if pending := pendingByResource[canonical]; pending > 0 {+ status.PendingApprovalCount += pending+ }+ }+ if aggregateProvider, ok := h.findingsProvider.(AgentAggregateFindingsProvider); ok {+ if aggregateActive := aggregateProvider.ActiveFindingCount(); aggregateActive > status.ActiveFindingCount {+ status.ActiveFindingCount = aggregateActive+ }+ }++ if h.workflowPromptActivityProvider != nil {+ if history, err := h.workflowPromptActivityProvider.WorkflowPromptActivityHistory(r.Context()); err == nil {+ starterCounts := agentOperationsLoopWorkflowStarterEvidenceCounts(history, windowStart)+ status.OperationsLoopStarterCount = starterCounts.total+ status.AssistantOperationsLoopStarterCount = starterCounts.assistant+ status.PatrolOperationsLoopStarterCount = starterCounts.patrol+ status.ProActivationLoopStarterCount = starterCounts.proActivation+ status.PatrolControlLoopStarterCount = starterCounts.patrolControl+ status.PatrolAutonomyLoopStarterCount = status.PatrolControlLoopStarterCount+ status.MCPOperationsLoopStarterCount = starterCounts.mcp+ }+ }+ if h.aiUsageProvider != nil {+ if history, err := h.aiUsageProvider.AIUsageHistory(r.Context()); err == nil {+ aiEvidence := telemetry.PulseIntelligenceAIUsageEvidenceFromHistory(history, windowStart)+ status.assistantContextCount = aiEvidence.AssistantContextAICalls + aiEvidence.AssistantToolCalls+ }+ }+ if h.externalAgentActivityProvider != nil {+ if history, err := h.externalAgentActivityProvider.ExternalAgentActivityHistory(r.Context()); err == nil {+ externalEvidence := telemetry.PulseIntelligenceExternalAgentEvidenceFromHistory(history, windowStart)+ status.externalAgentCollaborationCount = externalEvidence.CollaborationCount()+ }+ }++ actionCounts := agentOperationsLoopActionEvidenceCounts(store, windowStart)+ status.GovernedActionCount = actionCounts.governed+ status.ApprovedDecisionCount = actionCounts.approved+ status.RejectedDecisionCount = actionCounts.rejected+ status.VerifiedOutcomeCount = actionCounts.verified+ status.PatrolEvidenceCount = status.ActiveFindingCount + status.PendingApprovalCount + actionCounts.recent+ status.PatrolIssueEvidenceCount = status.ActiveFindingCount + status.PendingApprovalCount + status.GovernedActionCount + status.VerifiedOutcomeCount+ patrolControlProof := agentOperationsLoopPatrolControlProof(status)+ if patrolControlProof.Completed {+ status.PatrolControlCompletedLoopCount = 1+ }+ if patrolControlProof.Resolved {+ status.PatrolControlResolvedLoopCount = 1+ }+ status.PatrolControlValueState = patrolControlProof.ValueProofState+ status.PatrolAutonomyCompletedLoopCount = status.PatrolControlCompletedLoopCount+ status.PatrolAutonomyResolvedLoopCount = status.PatrolControlResolvedLoopCount+ status.PatrolAutonomyValueState = status.PatrolControlValueState+ status.ProActivationCompletedLoopCount = status.PatrolControlCompletedLoopCount+ status.ProActivationResolvedLoopCount = status.PatrolControlResolvedLoopCount+ status.ProActivationValueProofState = status.PatrolControlValueState+ status.NextAction, status.ProgressLabel, status.Steps = agentOperationsLoopProgress(status)++ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(status)+}+// countFleetFindingsBySeverity tallies the per-severity counts an// agent uses to triage. Severity strings outside the canonical set// (`critical`, `warning`, `info`) are counted in `Total` but not in@@ -534,6 +820,342 @@ func countFleetFindingsBySeverity(findings []AgentResourceFindingSnapshot) Agentreturn counts}+type agentOperationsLoopActionCounts struct {+ recent int+ governed int+ approved int+ rejected int+ verified int+}++type agentOperationsLoopWorkflowStarterCounts struct {+ total int+ assistant int+ patrol int+ patrolControl int+ proActivation int+ mcp int+}++func agentOperationsLoopWorkflowStarterEvidenceCounts(history *config.WorkflowPromptActivityHistoryData, since time.Time) agentOperationsLoopWorkflowStarterCounts {+ var counts agentOperationsLoopWorkflowStarterCounts+ if history == nil {+ return counts+ }+ for _, event := range history.Events {+ if strings.TrimSpace(event.PromptName) != agentcapabilities.PulseWorkflowPromptOperationsLoop {+ continue+ }+ if event.Timestamp.Before(since) {+ continue+ }+ counts.total+++ switch strings.TrimSpace(event.Surface) {+ case config.WorkflowPromptActivitySurfacePulseAssistant:+ counts.assistant+++ case config.WorkflowPromptActivitySurfacePulsePatrol:+ counts.patrol+++ counts.patrolControl+++ case config.WorkflowPromptActivitySurfacePatrolControl:+ counts.patrolControl+++ case config.WorkflowPromptActivitySurfacePatrolAutonomy:+ counts.patrolControl+++ case config.WorkflowPromptActivitySurfaceProActivation:+ counts.proActivation+++ counts.patrolControl+++ case config.WorkflowPromptActivitySurfacePulseMCP:+ counts.mcp+++ }+ }+ return counts+}++func agentOperationsLoopActionEvidenceCounts(store unified.ResourceStore, since time.Time) agentOperationsLoopActionCounts {+ var counts agentOperationsLoopActionCounts+ if store == nil {+ return counts+ }+ recentIDs := map[string]struct{}{}+ governedIDs := map[string]struct{}{}+ approvedIDs := map[string]struct{}{}+ rejectedIDs := map[string]struct{}{}+ verifiedIDs := map[string]struct{}{}+ auditsByID := map[string]unified.ActionAuditRecord{}+ cacheAudit := func(audit unified.ActionAuditRecord) {+ actionID := strings.TrimSpace(audit.ID)+ if actionID == "" {+ return+ }+ auditsByID[actionID] = audit+ }+ addAuditEvidence := func(audit unified.ActionAuditRecord) {+ actionID := strings.TrimSpace(audit.ID)+ if actionID == "" {+ return+ }+ recentIDs[actionID] = struct{}{}+ if pulseIntelligenceActionWasApproved(audit) {+ approvedIDs[actionID] = struct{}{}+ }+ if pulseIntelligenceActionWasRejected(audit) {+ rejectedIDs[actionID] = struct{}{}+ }+ if agentOperationsLoopGovernedAction(audit) {+ governedIDs[actionID] = struct{}{}+ }+ if agentOperationsLoopVerifiedAction(audit) {+ verifiedIDs[actionID] = struct{}{}+ }+ }+ auditForID := func(actionID string) (unified.ActionAuditRecord, bool) {+ actionID = strings.TrimSpace(actionID)+ if actionID == "" {+ return unified.ActionAuditRecord{}, false+ }+ if audit, ok := auditsByID[actionID]; ok {+ return audit, true+ }+ audit, ok, err := store.GetActionAudit(actionID)+ if err != nil || !ok {+ return unified.ActionAuditRecord{}, false+ }+ cacheAudit(audit)+ return audit, true+ }++ if audits, err := store.GetActionAudits("", since, 0); err == nil {+ for _, audit := range audits {+ cacheAudit(audit)+ addAuditEvidence(audit)+ }+ }+ if events, err := store.GetActionLifecycleEvents("", since, 0); err == nil {+ for _, event := range events {+ actionID := strings.TrimSpace(event.ActionID)+ if actionID == "" {+ continue+ }+ recentIDs[actionID] = struct{}{}+ audit, ok := auditForID(actionID)+ if !ok {+ continue+ }+ if pulseIntelligenceActionWasApproved(audit) {+ approvedIDs[actionID] = struct{}{}+ }+ if pulseIntelligenceActionWasRejected(audit) {+ rejectedIDs[actionID] = struct{}{}+ }+ if agentOperationsLoopGovernedAction(audit) {+ governedIDs[actionID] = struct{}{}+ }+ if agentOperationsLoopVerifiedAction(audit) {+ verifiedIDs[actionID] = struct{}{}+ }+ }+ }+ counts.recent = len(recentIDs)+ counts.governed = len(governedIDs)+ counts.approved = len(approvedIDs)+ counts.rejected = len(rejectedIDs)+ counts.verified = len(verifiedIDs)+ return counts+}++func agentOperationsLoopGovernedAction(record unified.ActionAuditRecord) bool {+ return pulseIntelligenceActionWasApproved(record) || pulseIntelligenceActionWasRejected(record)+}++func agentOperationsLoopVerifiedAction(record unified.ActionAuditRecord) bool {+ return pulseIntelligenceActionVerifiedOutcome(record)+}++func agentOperationsLoopContextualCollaborationCount(status AgentOperationsLoopStatus) int {+ return status.assistantContextCount + status.externalAgentCollaborationCount+}++func agentOperationsLoopPatrolControlProof(status AgentOperationsLoopStatus) telemetry.PulseIntelligencePatrolControlProof {+ return telemetry.ClassifyPulseIntelligencePatrolControlProof(telemetry.PulseIntelligencePatrolControlProofInput{+ PatrolControlStarterCount: status.PatrolControlLoopStarterCount,+ PatrolIssueEvidenceCount: status.PatrolIssueEvidenceCount,+ ContextualCollaborationCount: agentOperationsLoopContextualCollaborationCount(status),+ ApprovedDecisionCount: status.ApprovedDecisionCount,+ RejectedDecisionCount: status.RejectedDecisionCount,+ VerifiedOutcomeCount: status.VerifiedOutcomeCount,+ })+}++func agentOperationsLoopProgress(status AgentOperationsLoopStatus) (string, string, []AgentOperationsLoopStep) {+ hasIssueEvidence := status.PatrolIssueEvidenceCount > 0+ contextualCollaborationCount := agentOperationsLoopContextualCollaborationCount(status)+ hasContextualCollaboration := contextualCollaborationCount > 0+ hasApprovedDecision := status.ApprovedDecisionCount > 0 || status.VerifiedOutcomeCount > 0+ hasRejectedDecision := status.RejectedDecisionCount > 0+ hasGovernedDecision := hasApprovedDecision || hasRejectedDecision || status.GovernedActionCount > 0+ hasGovernedWork := status.PendingApprovalCount > 0 || hasGovernedDecision+ hasVerifiedOutcome := status.VerifiedOutcomeCount > 0+ hasRejectedTerminalDecision := hasRejectedDecision && !hasApprovedDecision+ hasPatrolControlCompletedLoop := status.PatrolControlCompletedLoopCount > 0+ hasPatrolControlResolvedLoop := status.PatrolControlResolvedLoopCount > 0+ governanceStepCount := status.PendingApprovalCount+ if decisionCount := status.ApprovedDecisionCount + status.RejectedDecisionCount; decisionCount > 0 {+ governanceStepCount = decisionCount+ } else if status.GovernedActionCount > 0 {+ governanceStepCount = status.GovernedActionCount+ }+ verificationStepCount := status.VerifiedOutcomeCount+ if verificationStepCount == 0 && hasRejectedTerminalDecision {+ verificationStepCount = status.RejectedDecisionCount+ }++ steps := []AgentOperationsLoopStep{+ {ID: "patrol", Label: "Patrol", Status: AgentOperationsLoopStepPending, Count: status.PatrolIssueEvidenceCount},+ {ID: "assistant", Label: "Assistant", Status: AgentOperationsLoopStepPending, Count: contextualCollaborationCount},+ {ID: "governance", Label: "Governance", Status: AgentOperationsLoopStepPending, Count: governanceStepCount},+ {ID: "verification", Label: "Verification", Status: AgentOperationsLoopStepPending, Count: verificationStepCount},+ }++ switch {+ case !hasIssueEvidence:+ steps[0].Status = AgentOperationsLoopStepCurrent+ if status.PatrolControlLoopStarterCount > 0 {+ return "run_patrol", "Patrol is ready to check the fleet and investigate the next real infrastructure issue.", steps+ }+ return "run_patrol", "Run Patrol to check for actionable infrastructure issues.", steps+ case !hasContextualCollaboration:+ steps[0].Status = AgentOperationsLoopStepComplete+ steps[1].Status = AgentOperationsLoopStepCurrent+ return "open_assistant", "Open Assistant to explain the Patrol issue and safest next step.", steps+ case !hasGovernedWork:+ steps[0].Status = AgentOperationsLoopStepComplete+ steps[1].Status = AgentOperationsLoopStepCurrent+ return "open_assistant", "Open Assistant to explain the Patrol issue and safest next step.", steps+ case status.PendingApprovalCount > 0 && !hasGovernedDecision:+ steps[0].Status = AgentOperationsLoopStepComplete+ steps[1].Status = AgentOperationsLoopStepComplete+ steps[2].Status = AgentOperationsLoopStepCurrent+ return "review_approvals", "Review the pending governed action approval.", steps+ case status.PendingApprovalCount > 0:+ steps[0].Status = AgentOperationsLoopStepComplete+ steps[1].Status = AgentOperationsLoopStepComplete+ steps[2].Status = AgentOperationsLoopStepCurrent+ return "review_approvals", "Review pending Patrol approvals before treating previous verified work as current.", steps+ case status.ActiveFindingCount > 0 && hasVerifiedOutcome:+ steps[0].Status = AgentOperationsLoopStepComplete+ steps[1].Status = AgentOperationsLoopStepCurrent+ if status.ActiveFindingCount == 1 {+ return "open_assistant", "Open Assistant on the active Patrol finding before treating previous verified work as current.", steps+ }+ return "review_findings", "Review active Patrol findings before treating previous verified work as current.", steps+ case hasRejectedTerminalDecision:+ for i := 0; i < 4; i++ {+ steps[i].Status = AgentOperationsLoopStepComplete+ }+ if hasPatrolControlCompletedLoop {+ return "complete", "Patrol recorded a rejected change decision. Nothing was changed; approve a safer fix before marking the issue resolved.", steps+ }+ return "complete", "Patrol recorded a governed rejection. Nothing was changed.", steps+ case !hasVerifiedOutcome:+ steps[0].Status = AgentOperationsLoopStepComplete+ steps[1].Status = AgentOperationsLoopStepComplete+ steps[2].Status = AgentOperationsLoopStepComplete+ steps[3].Status = AgentOperationsLoopStepCurrent+ if status.PatrolControlLoopStarterCount > 0 {+ return "review_findings", "Verify whether the approved Patrol action fixed the issue.", steps+ }+ return "review_findings", "Verify whether the governed action fixed the issue.", steps+ default:+ for i := 0; i < 4; i++ {+ steps[i].Status = AgentOperationsLoopStepComplete+ }+ if hasPatrolControlResolvedLoop {+ return "complete", "Patrol handled an infrastructure issue, verified the outcome, and recorded what happened.", steps+ }+ return "complete", "Patrol handled an infrastructure issue, verified the outcome, and recorded what happened.", steps+ }+}++func (h *AgentContextHandler) agentOperationsLoopExternalAgentReady(ctx context.Context, manifest agentcapabilities.Manifest, now time.Time) bool {+ if !agentOperationsLoopExternalAgentManifestReady(manifest) {+ return false+ }+ return h != nil &&+ h.externalAgentReadinessProvider != nil &&+ h.externalAgentReadinessProvider.ExternalAgentReady(ctx, manifest, now)+}++func agentOperationsLoopExternalAgentManifestReady(manifest agentcapabilities.Manifest) bool {+ adapter := agentcapabilities.NormalizeMCPAdapterContract(manifest.MCPAdapter)+ if strings.TrimSpace(adapter.Command) == "" ||+ strings.TrimSpace(adapter.ServerName) == "" ||+ strings.TrimSpace(adapter.TokenEnv) == "" ||+ len(adapter.ConfigFamilies) == 0 {+ return false+ }+ if !agentcapabilities.MCPManifestSurfacePromptProjectionSupported(manifest, agentcapabilities.SurfaceIDPulseMCP) {+ return false+ }+ hasOperationsLoopPrompt := false+ for _, prompt := range agentcapabilities.ManifestPulseWorkflowPrompts(manifest) {+ if strings.TrimSpace(prompt.Name) == agentcapabilities.PulseWorkflowPromptOperationsLoop {+ hasOperationsLoopPrompt = true+ break+ }+ }+ if !hasOperationsLoopPrompt {+ return false+ }+ contract, ok := agentcapabilities.ProjectManifestSurfaceToolContract(manifest, agentcapabilities.SurfaceIDPulseMCP)+ if !ok {+ return false+ }+ toolNames := map[string]struct{}{}+ for _, name := range contract.ToolNames {+ name = strings.TrimSpace(name)+ if name != "" {+ toolNames[name] = struct{}{}+ }+ }+ for _, name := range agentcapabilities.OperationsLoopCapabilityNames() {+ if _, ok := toolNames[name]; !ok {+ return false+ }+ }+ return true+}++func agentOperationsLoopExternalAgentTokenReady(manifest agentcapabilities.Manifest, tokens []config.APITokenRecord, now time.Time) bool {+ if !agentOperationsLoopExternalAgentManifestReady(manifest) {+ return false+ }+ surfaceScopes := agentcapabilities.RequiredCapabilityScopes(+ agentcapabilities.ManifestSurfaceToolCapabilities(manifest, agentcapabilities.SurfaceIDPulseMCP),+ )+ if len(surfaceScopes) == 0 {+ return false+ }+ for _, token := range tokens {+ if token.ExpiresAt != nil && now.After(token.ExpiresAt.UTC()) {+ continue+ }+ token = token.Clone()+ coversLoop := true+ for _, scope := range surfaceScopes {+ if strings.TrimSpace(scope) == "" {+ continue+ }+ if !token.HasScope(scope) {+ coversLoop = false+ break+ }+ }+ if coversLoop {+ return true+ }+ }+ return false+}+// projectAgentResourceOperatorState converts the canonical store// shape into the agent-stable wire shape, computing the// maintenance-window-active flag once at the server boundary.diff --git a/internal/api/agent_resource_context_test.go b/internal/api/agent_resource_context_test.goindex 3e13114475..e6f31ca5ca 100644--- a/internal/api/agent_resource_context_test.go+++ b/internal/api/agent_resource_context_test.go@@ -9,6 +9,7 @@ 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/config""github.com/rcourtman/pulse-go-rewrite/internal/models"@@ -19,7 +20,8 @@ import (// — keyed by resource id so each test can stage the snapshot it// expects to see in the bundle.type staticFindingsProvider struct {- byResource map[string][]AgentResourceFindingSnapshot+ byResource map[string][]AgentResourceFindingSnapshot+ activeCount *int}func (s staticFindingsProvider) ActiveFindingsForResource(resourceID string) []AgentResourceFindingSnapshot {@@ -29,6 +31,17 @@ func (s staticFindingsProvider) ActiveFindingsForResource(resourceID string) []Areturn s.byResource[resourceID]}+func (s staticFindingsProvider) ActiveFindingCount() int {+ if s.activeCount != nil {+ return *s.activeCount+ }+ total := 0+ for _, findings := range s.byResource {+ total += len(findings)+ }+ return total+}+// staticApprovalsProvider is a tiny test double for// AgentApprovalsProvider — keyed by (resource id, org id) so each// test can stage the pending approvals it expects to see in the@@ -37,6 +50,33 @@ type staticApprovalsProvider struct {byResource map[string][]AgentResourceApprovalSummary}+type staticWorkflowPromptActivityProvider struct {+ history *config.WorkflowPromptActivityHistoryData+ err error+}++func (s staticWorkflowPromptActivityProvider) WorkflowPromptActivityHistory(_ context.Context) (*config.WorkflowPromptActivityHistoryData, error) {+ return s.history, s.err+}++type staticAIUsageProvider struct {+ history *config.AIUsageHistoryData+ err error+}++func (s staticAIUsageProvider) AIUsageHistory(_ context.Context) (*config.AIUsageHistoryData, error) {+ return s.history, s.err+}++type staticExternalAgentActivityProvider struct {+ history *config.ExternalAgentActivityHistoryData+ err error+}++func (s staticExternalAgentActivityProvider) ExternalAgentActivityHistory(_ context.Context) (*config.ExternalAgentActivityHistoryData, error) {+ return s.history, s.err+}+func (s staticApprovalsProvider) PendingApprovalsForResource(resourceID, _ string) []AgentResourceApprovalSummary {if s.byResource == nil {return nil@@ -1014,6 +1054,9 @@ func fleetFixtureHandlers(t *testing.T, resources []unified.Resource) (*AgentConh := NewAgentContextHandler(rh)h.SetFindingsProvider(findings)h.SetApprovalsProvider(approvals)+ h.SetExternalAgentReadinessProvider(agentExternalAgentReadinessProviderFunc(func(context.Context, agentcapabilities.Manifest, time.Time) bool {+ return true+ }))return h, findings, approvals}@@ -1203,6 +1246,1180 @@ func TestHandleAgentFleetContext_RejectsNonGet(t *testing.T) {}}+func TestHandleAgentOperationsLoopStatus_StartsAtPatrolWithoutIssueEvidence(t *testing.T) {+ h, _, _ := fleetFixtureHandlers(t, []unified.Resource{+ {ID: "vm:101", Type: "vm", Name: "db-01"},+ })++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/agent/operations-loop/status", nil)+ h.HandleOperationsLoopStatus(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("status: got %d, body=%s", rec.Code, rec.Body.String())+ }+ var status AgentOperationsLoopStatus+ if err := json.NewDecoder(rec.Body).Decode(&status); err != nil {+ t.Fatalf("decode: %v", err)+ }+ assertPatrolControlCompatibilityAliases(t, status)+ if status.NextAction != "run_patrol" {+ t.Fatalf("NextAction = %q; want run_patrol", status.NextAction)+ }+ if status.PatrolIssueEvidenceCount != 0 || status.ActiveFindingCount != 0 || status.PendingApprovalCount != 0 {+ t.Fatalf("empty loop should have zero issue counts: %+v", status)+ }+ if status.ProActivationValueProofState != "not_started" {+ t.Fatalf("ProActivationValueProofState = %q; want not_started", status.ProActivationValueProofState)+ }+ steps := agentOperationsLoopStepsByID(status.Steps)+ if got := steps["patrol"].Status; got != AgentOperationsLoopStepCurrent {+ t.Fatalf("patrol step status = %q; want current", got)+ }+ if got := steps["assistant"].Status; got != AgentOperationsLoopStepPending {+ t.Fatalf("assistant step status = %q; want pending", got)+ }+}++func TestAgentOperationsLoopExternalAgentTokenReadyUsesPulseMCPSurfaceScopes(t *testing.T) {+ now := time.Now().UTC()+ expiredAt := now.Add(-time.Minute)+ manifest := agentcapabilities.CanonicalManifest()+ operationLoopScopes := agentcapabilities.RequiredCapabilityScopes(+ agentcapabilities.ManifestSurfaceToolCapabilities(manifest, agentcapabilities.SurfaceIDPulseMCP),+ )+ if len(operationLoopScopes) < 2 {+ t.Fatalf("Pulse MCP operations loop must require multiple scope classes for this readiness test, got %v", operationLoopScopes)+ }++ if agentOperationsLoopExternalAgentTokenReady(manifest, nil, now) {+ t.Fatal("missing token must not satisfy external-agent readiness")+ }+ if agentOperationsLoopExternalAgentTokenReady(manifest, []config.APITokenRecord{+ {Scopes: []string{config.ScopeAIChat}, CreatedAt: now.Add(-time.Hour)},+ }, now) {+ t.Fatal("generic AI chat token must not satisfy external-agent readiness")+ }+ if agentOperationsLoopExternalAgentTokenReady(manifest, []config.APITokenRecord{+ {Scopes: []string{config.ScopeMonitoringRead}, ExpiresAt: &expiredAt, CreatedAt: now.Add(-time.Hour)},+ }, now) {+ t.Fatal("expired MCP-capable token must not satisfy external-agent readiness")+ }+ if agentOperationsLoopExternalAgentTokenReady(manifest, []config.APITokenRecord{+ {Scopes: []string{config.ScopeMonitoringRead}, CreatedAt: now.Add(-time.Hour)},+ }, now) {+ t.Fatal("read-only Pulse MCP token must not satisfy full operations-loop readiness")+ }+ if agentOperationsLoopExternalAgentTokenReady(manifest, []config.APITokenRecord{+ {Scopes: []string{config.ScopeAIExecute}, CreatedAt: now.Add(-time.Hour)},+ }, now) {+ t.Fatal("AI-execute-only Pulse MCP token must not satisfy full operations-loop readiness")+ }+ if agentOperationsLoopExternalAgentTokenReady(manifest, []config.APITokenRecord{+ {Scopes: []string{config.ScopeMonitoringRead}, CreatedAt: now.Add(-time.Hour)},+ {Scopes: []string{config.ScopeAIExecute}, CreatedAt: now.Add(-time.Hour)},+ }, now) {+ t.Fatal("split partial tokens must not satisfy single-token operations-loop readiness")+ }+ if !agentOperationsLoopExternalAgentTokenReady(manifest, []config.APITokenRecord{+ {Scopes: operationLoopScopes, CreatedAt: now.Add(-time.Hour)},+ }, now) {+ t.Fatalf("one token covering all Pulse MCP operations-loop scopes should satisfy external-agent readiness; scopes=%v", operationLoopScopes)+ }+}++func TestHandleAgentOperationsLoopStatus_AggregatesContentSafeLoopCounts(t *testing.T) {+ h, findings, approvals := fleetFixtureHandlers(t, []unified.Resource{+ {ID: "vm:101", Type: "vm", Name: "db-01"},+ })+ findings.byResource["vm:101"] = []AgentResourceFindingSnapshot{+ {ID: "finding-cpu", Title: "CPU pressure", Severity: "warning"},+ {ID: "finding-disk", Title: "Disk pressure", Severity: "critical"},+ }+ approvals.byResource["vm:101"] = []AgentResourceApprovalSummary{{ID: "approval-1"}}++ store, err := h.resources.getStore("default")+ if err != nil {+ t.Fatalf("getStore: %v", err)+ }+ now := time.Now().UTC()+ h.SetAIUsageProvider(staticAIUsageProvider{+ history: &config.AIUsageHistoryData{+ Events: []config.AIUsageEventRecord{{+ Timestamp: now.Add(-7 * time.Minute),+ UseCase: "chat",+ ContextScope: "patrol_finding",+ FindingID: "finding-cpu",+ }},+ },+ })+ if err := store.RecordActionAudit(unified.ActionAuditRecord{+ ID: "act-verified",+ CreatedAt: now.Add(-5 * time.Minute),+ UpdatedAt: now,+ State: unified.ActionStateCompleted,+ Request: unified.ActionRequest{+ RequestID: "req-verified",+ ResourceID: "vm:101",+ CapabilityName: "restart_service",+ Params: map[string]any{"command": "systemctl restart nginx"},+ RequestedBy: "pulse_patrol",+ },+ Plan: unified.ActionPlan{+ ActionID: "act-verified",+ RequestID: "req-verified",+ PlannedAt: now.Add(-6 * time.Minute),+ ExpiresAt: now.Add(time.Hour),+ },+ Approvals: []unified.ActionApprovalRecord{{+ Actor: "[email protected]",+ Method: unified.MethodUI,+ Timestamp: now.Add(-4 * time.Minute),+ Outcome: unified.OutcomeApproved,+ }},+ Result: &unified.ExecutionResult{+ Success: true,+ Output: "service restarted",+ },+ VerificationOutcome: unified.VerificationOutcome{Status: unified.VerificationVerified},+ }); err != nil {+ t.Fatalf("RecordActionAudit: %v", err)+ }++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/agent/operations-loop/status", nil)+ h.HandleOperationsLoopStatus(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("status: got %d, body=%s", rec.Code, rec.Body.String())+ }+ body := rec.Body.String()+ for _, forbidden := range []string{+ "finding-cpu",+ "finding-disk",+ "act-verified",+ "approval-1",+ "vm:101",+ "db-01",+ "systemctl",+ "service restarted",+ "[email protected]",+ } {+ if strings.Contains(body, forbidden) {+ t.Fatalf("operations-loop status leaked %q: %s", forbidden, body)+ }+ }++ var status AgentOperationsLoopStatus+ if err := json.Unmarshal([]byte(body), &status); err != nil {+ t.Fatalf("decode: %v", err)+ }+ assertPatrolControlCompatibilityAliases(t, status)+ if status.NextAction != "review_approvals" {+ t.Fatalf("NextAction = %q; want review_approvals; status=%+v", status.NextAction, status)+ }+ if !status.ExternalAgentReady {+ t.Fatal("canonical manifest should make external-agent readiness true")+ }+ if status.ActiveFindingCount != 2 ||+ status.PendingApprovalCount != 1 ||+ status.GovernedActionCount != 1 ||+ status.ApprovedDecisionCount != 1 ||+ status.RejectedDecisionCount != 0 ||+ status.VerifiedOutcomeCount != 1 {+ t.Fatalf("loop counts wrong: %+v", status)+ }+ if status.PatrolEvidenceCount != 4 || status.PatrolIssueEvidenceCount != 5 {+ t.Fatalf("evidence counts wrong: patrol=%d issue=%d", status.PatrolEvidenceCount, status.PatrolIssueEvidenceCount)+ }+ steps := agentOperationsLoopStepsByID(status.Steps)+ if got := steps["governance"].Count; got != 1 {+ t.Fatalf("governance step count = %d; want approved decision count", got)+ }+ if got := steps["assistant"].Count; got != 1 {+ t.Fatalf("assistant step count = %d; want contextual collaboration count", got)+ }+ if got := steps["verification"].Count; got != 1 {+ t.Fatalf("verification step count = %d; want verified outcome count", got)+ }+ if got := steps["patrol"].Status; got != AgentOperationsLoopStepComplete {+ t.Fatalf("patrol step status = %q; want complete; steps=%+v", got, status.Steps)+ }+ if got := steps["assistant"].Status; got != AgentOperationsLoopStepComplete {+ t.Fatalf("assistant step status = %q; want complete; steps=%+v", got, status.Steps)+ }+ if got := steps["governance"].Status; got != AgentOperationsLoopStepCurrent {+ t.Fatalf("governance step status = %q; want current; steps=%+v", got, status.Steps)+ }+ if got := steps["verification"].Status; got != AgentOperationsLoopStepPending {+ t.Fatalf("verification step status = %q; want pending; steps=%+v", got, status.Steps)+ }+}++func TestHandleAgentOperationsLoopStatus_ActiveAggregateFindingOutranksHistoricalCompletion(t *testing.T) {+ h, findings, _ := fleetFixtureHandlers(t, []unified.Resource{+ {ID: "vm:101", Type: "vm", Name: "db-01"},+ })+ activeCount := 1+ findings.activeCount = &activeCount+ now := time.Now().UTC()+ h.SetWorkflowPromptActivityProvider(staticWorkflowPromptActivityProvider{+ history: &config.WorkflowPromptActivityHistoryData{+ Events: []config.WorkflowPromptActivityRecord{{+ Timestamp: now.Add(-10 * time.Minute),+ Surface: config.WorkflowPromptActivitySurfacePulsePatrol,+ PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop,+ }},+ },+ })+ h.SetAIUsageProvider(staticAIUsageProvider{+ history: &config.AIUsageHistoryData{+ Events: []config.AIUsageEventRecord{{+ Timestamp: now.Add(-7 * time.Minute),+ UseCase: "chat",+ ContextScope: "patrol_finding",+ }},+ },+ })+ store, err := h.resources.getStore("default")+ if err != nil {+ t.Fatalf("getStore: %v", err)+ }+ if err := store.RecordActionAudit(unified.ActionAuditRecord{+ ID: "act-old-verified",+ CreatedAt: now.Add(-5 * time.Minute),+ UpdatedAt: now,+ State: unified.ActionStateCompleted,+ Request: unified.ActionRequest{+ RequestID: "req-old-verified",+ ResourceID: "vm:101",+ CapabilityName: "restart_service",+ RequestedBy: "pulse_patrol",+ },+ Plan: unified.ActionPlan{+ ActionID: "act-old-verified",+ RequestID: "req-old-verified",+ PlannedAt: now.Add(-6 * time.Minute),+ ExpiresAt: now.Add(time.Hour),+ },+ Approvals: []unified.ActionApprovalRecord{{+ Method: unified.MethodUI,+ Timestamp: now.Add(-4 * time.Minute),+ Outcome: unified.OutcomeApproved,+ }},+ Result: &unified.ExecutionResult{Success: true},+ VerificationOutcome: unified.VerificationOutcome{Status: unified.VerificationVerified},+ }); err != nil {+ t.Fatalf("RecordActionAudit: %v", err)+ }++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/agent/operations-loop/status", nil)+ h.HandleOperationsLoopStatus(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("status: got %d, body=%s", rec.Code, rec.Body.String())+ }+ var status AgentOperationsLoopStatus+ if err := json.NewDecoder(rec.Body).Decode(&status); err != nil {+ t.Fatalf("decode: %v", err)+ }+ assertPatrolControlCompatibilityAliases(t, status)+ if status.ActiveFindingCount != 1 {+ t.Fatalf("ActiveFindingCount = %d; want aggregate active finding", status.ActiveFindingCount)+ }+ if status.PatrolEvidenceCount != 2 || status.PatrolIssueEvidenceCount != 3 {+ t.Fatalf("evidence counts wrong: patrol=%d issue=%d status=%+v", status.PatrolEvidenceCount, status.PatrolIssueEvidenceCount, status)+ }+ if status.PatrolControlResolvedLoopCount != 1 || status.PatrolControlValueState != "verified" {+ t.Fatalf("historical resolved proof should remain recorded: %+v", status)+ }+ if status.NextAction != "open_assistant" {+ t.Fatalf("NextAction = %q; want open_assistant for the current active finding; status=%+v", status.NextAction, status)+ }+ if status.ProgressLabel != "Open Assistant on the active Patrol finding before treating previous verified work as current." {+ t.Fatalf("ProgressLabel = %q", status.ProgressLabel)+ }+ steps := agentOperationsLoopStepsByID(status.Steps)+ if steps["patrol"].Status != AgentOperationsLoopStepComplete ||+ steps["assistant"].Status != AgentOperationsLoopStepCurrent ||+ steps["verification"].Status != AgentOperationsLoopStepPending {+ t.Fatalf("steps should point back to the current active finding: %+v", status.Steps)+ }+}++func TestHandleAgentOperationsLoopStatus_AggregatesWorkflowStarterCounts(t *testing.T) {+ h, _, _ := fleetFixtureHandlers(t, []unified.Resource{+ {ID: "vm:101", Type: "vm", Name: "db-01"},+ })+ now := time.Now().UTC()+ h.SetWorkflowPromptActivityProvider(staticWorkflowPromptActivityProvider{+ history: &config.WorkflowPromptActivityHistoryData{+ Events: []config.WorkflowPromptActivityRecord{+ {+ Timestamp: now.Add(-10 * time.Minute),+ Surface: config.WorkflowPromptActivitySurfacePulseAssistant,+ PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop,+ },+ {+ Timestamp: now.Add(-9 * time.Minute),+ Surface: config.WorkflowPromptActivitySurfacePulseAssistant,+ PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop,+ },+ {+ Timestamp: now.Add(-8 * time.Minute),+ Surface: config.WorkflowPromptActivitySurfacePulsePatrol,+ PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop,+ },+ {+ Timestamp: now.Add(-7 * time.Minute),+ Surface: config.WorkflowPromptActivitySurfacePatrolControl,+ PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop,+ },+ {+ Timestamp: now.Add(-6 * time.Minute),+ Surface: config.WorkflowPromptActivitySurfacePatrolAutonomy,+ PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop,+ },+ {+ Timestamp: now.Add(-5 * time.Minute),+ Surface: config.WorkflowPromptActivitySurfaceProActivation,+ PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop,+ },+ {+ Timestamp: now.Add(-4 * time.Minute),+ Surface: config.WorkflowPromptActivitySurfacePulseMCP,+ PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop,+ },+ {+ Timestamp: now.Add(-3 * time.Minute),+ Surface: config.WorkflowPromptActivitySurfaceAgentAPI,+ PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop,+ },+ {+ Timestamp: now.Add(-2 * time.Minute),+ Surface: config.WorkflowPromptActivitySurfacePulseAssistant,+ PromptName: agentcapabilities.PulseWorkflowPromptTriageFleet,+ },+ {+ Timestamp: now.Add(-agentOperationsLoopActionWindow - time.Hour),+ Surface: config.WorkflowPromptActivitySurfacePulseMCP,+ PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop,+ },+ },+ },+ })++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/agent/operations-loop/status", nil)+ h.HandleOperationsLoopStatus(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("status: got %d, body=%s", rec.Code, rec.Body.String())+ }+ body := rec.Body.String()+ for _, forbidden := range []string{+ agentcapabilities.PulseWorkflowPromptOperationsLoop,+ agentcapabilities.PulseWorkflowPromptTriageFleet,+ config.WorkflowPromptActivitySurfacePulseAssistant,+ config.WorkflowPromptActivitySurfacePulsePatrol,+ config.WorkflowPromptActivitySurfacePatrolControl,+ config.WorkflowPromptActivitySurfacePatrolAutonomy,+ config.WorkflowPromptActivitySurfaceProActivation,+ config.WorkflowPromptActivitySurfacePulseMCP,+ config.WorkflowPromptActivitySurfaceAgentAPI,+ } {+ if strings.Contains(body, forbidden) {+ t.Fatalf("operations-loop status leaked workflow activity detail %q: %s", forbidden, body)+ }+ }++ var status AgentOperationsLoopStatus+ if err := json.Unmarshal([]byte(body), &status); err != nil {+ t.Fatalf("decode: %v", err)+ }+ assertPatrolControlCompatibilityAliases(t, status)+ if status.OperationsLoopStarterCount != 8 ||+ status.AssistantOperationsLoopStarterCount != 2 ||+ status.PatrolOperationsLoopStarterCount != 1 ||+ status.PatrolControlLoopStarterCount != 4 ||+ status.PatrolControlResolvedLoopCount != 0 ||+ status.ProActivationLoopStarterCount != 1 ||+ status.ProActivationResolvedLoopCount != 0 ||+ status.MCPOperationsLoopStarterCount != 1 {+ t.Fatalf("workflow starter counts wrong: %+v", status)+ }+ if status.PatrolControlValueState != "in_progress" {+ t.Fatalf("PatrolControlValueState = %q; want in_progress", status.PatrolControlValueState)+ }+ if status.ProActivationValueProofState != "in_progress" {+ t.Fatalf("ProActivationValueProofState = %q; want in_progress", status.ProActivationValueProofState)+ }+ if status.NextAction != "run_patrol" ||+ status.ProgressLabel != "Patrol is ready to check the fleet and investigate the next real infrastructure issue." {+ t.Fatalf("workflow starter progress wrong: %+v", status)+ }+}++func TestHandleAgentOperationsLoopStatus_CountsPulsePatrolStarterAsPatrolControl(t *testing.T) {+ h, _, _ := fleetFixtureHandlers(t, []unified.Resource{+ {ID: "vm:101", Type: "vm", Name: "db-01"},+ })+ now := time.Now().UTC()+ h.SetWorkflowPromptActivityProvider(staticWorkflowPromptActivityProvider{+ history: &config.WorkflowPromptActivityHistoryData{+ Events: []config.WorkflowPromptActivityRecord{{+ Timestamp: now.Add(-10 * time.Minute),+ Surface: config.WorkflowPromptActivitySurfacePulsePatrol,+ PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop,+ }},+ },+ })++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/agent/operations-loop/status", nil)+ h.HandleOperationsLoopStatus(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("status: got %d, body=%s", rec.Code, rec.Body.String())+ }++ var status AgentOperationsLoopStatus+ if err := json.NewDecoder(rec.Body).Decode(&status); err != nil {+ t.Fatalf("decode: %v", err)+ }+ assertPatrolControlCompatibilityAliases(t, status)+ if status.PatrolOperationsLoopStarterCount != 1 ||+ status.PatrolControlLoopStarterCount != 1 ||+ status.ProActivationLoopStarterCount != 0 {+ t.Fatalf("native Patrol starter counts wrong: %+v", status)+ }+ if status.PatrolControlValueState != "in_progress" ||+ status.ProActivationValueProofState != "in_progress" {+ t.Fatalf("native Patrol starter value state wrong: %+v", status)+ }+ if status.NextAction != "run_patrol" ||+ status.ProgressLabel != "Patrol is ready to check the fleet and investigate the next real infrastructure issue." {+ t.Fatalf("native Patrol starter progress wrong: %+v", status)+ }+}++func TestHandleAgentOperationsLoopStatus_CountsPatrolControlStarterWithoutLegacyProActivation(t *testing.T) {+ h, _, _ := fleetFixtureHandlers(t, []unified.Resource{+ {ID: "vm:101", Type: "vm", Name: "db-01"},+ })+ now := time.Now().UTC()+ h.SetWorkflowPromptActivityProvider(staticWorkflowPromptActivityProvider{+ history: &config.WorkflowPromptActivityHistoryData{+ Events: []config.WorkflowPromptActivityRecord{{+ Timestamp: now.Add(-10 * time.Minute),+ Surface: config.WorkflowPromptActivitySurfacePatrolControl,+ PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop,+ }},+ },+ })++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/agent/operations-loop/status", nil)+ h.HandleOperationsLoopStatus(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("status: got %d, body=%s", rec.Code, rec.Body.String())+ }++ var status AgentOperationsLoopStatus+ if err := json.NewDecoder(rec.Body).Decode(&status); err != nil {+ t.Fatalf("decode: %v", err)+ }+ assertPatrolControlCompatibilityAliases(t, status)+ if status.PatrolOperationsLoopStarterCount != 0 ||+ status.PatrolControlLoopStarterCount != 1 ||+ status.ProActivationLoopStarterCount != 0 {+ t.Fatalf("Patrol control starter counts wrong: %+v", status)+ }+ if status.PatrolControlValueState != "in_progress" ||+ status.ProActivationValueProofState != "in_progress" {+ t.Fatalf("Patrol control starter value state wrong: %+v", status)+ }+ if status.NextAction != "run_patrol" ||+ status.ProgressLabel != "Patrol is ready to check the fleet and investigate the next real infrastructure issue." {+ t.Fatalf("Patrol control starter progress wrong: %+v", status)+ }+}++func TestHandleAgentOperationsLoopStatus_ProjectsPatrolControlResolvedLoop(t *testing.T) {+ h, _, _ := fleetFixtureHandlers(t, []unified.Resource{+ {ID: "vm:101", Type: "vm", Name: "db-01"},+ })+ now := time.Now().UTC()+ h.SetAIUsageProvider(staticAIUsageProvider{+ history: &config.AIUsageHistoryData{+ Events: []config.AIUsageEventRecord{{+ Timestamp: now.Add(-9 * time.Minute),+ UseCase: "chat",+ ContextScope: "patrol_finding",+ FindingID: "finding-pro",+ }},+ },+ })+ h.SetWorkflowPromptActivityProvider(staticWorkflowPromptActivityProvider{+ history: &config.WorkflowPromptActivityHistoryData{+ Events: []config.WorkflowPromptActivityRecord{+ {+ Timestamp: now.Add(-10 * time.Minute),+ Surface: config.WorkflowPromptActivitySurfacePulsePatrol,+ PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop,+ },+ },+ },+ })++ store, err := h.resources.getStore("default")+ if err != nil {+ t.Fatalf("getStore: %v", err)+ }+ if err := store.RecordActionAudit(unified.ActionAuditRecord{+ ID: "act-pro-verified",+ CreatedAt: now.Add(-5 * time.Minute),+ UpdatedAt: now,+ State: unified.ActionStateCompleted,+ Request: unified.ActionRequest{+ RequestID: "req-pro-verified",+ ResourceID: "vm:101",+ CapabilityName: "restart_service",+ Params: map[string]any{"command": "systemctl restart nginx"},+ RequestedBy: "pulse_patrol",+ },+ Plan: unified.ActionPlan{+ ActionID: "act-pro-verified",+ RequestID: "req-pro-verified",+ PlannedAt: now.Add(-6 * time.Minute),+ ExpiresAt: now.Add(time.Hour),+ },+ Approvals: []unified.ActionApprovalRecord{{+ Actor: "[email protected]",+ Method: unified.MethodUI,+ Timestamp: now.Add(-4 * time.Minute),+ Outcome: unified.OutcomeApproved,+ }},+ Result: &unified.ExecutionResult{+ Success: true,+ Output: "service restarted",+ },+ VerificationOutcome: unified.VerificationOutcome{Status: unified.VerificationVerified},+ }); err != nil {+ t.Fatalf("RecordActionAudit: %v", err)+ }++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/agent/operations-loop/status", nil)+ h.HandleOperationsLoopStatus(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("status: got %d, body=%s", rec.Code, rec.Body.String())+ }+ body := rec.Body.String()+ for _, forbidden := range []string{+ agentcapabilities.PulseWorkflowPromptOperationsLoop,+ config.WorkflowPromptActivitySurfacePulsePatrol,+ config.WorkflowPromptActivitySurfacePatrolAutonomy,+ config.WorkflowPromptActivitySurfaceProActivation,+ "act-pro-verified",+ "req-pro-verified",+ "vm:101",+ "db-01",+ "systemctl",+ "service restarted",+ "[email protected]",+ } {+ if strings.Contains(body, forbidden) {+ t.Fatalf("operations-loop status leaked %q: %s", forbidden, body)+ }+ }++ var status AgentOperationsLoopStatus+ if err := json.Unmarshal([]byte(body), &status); err != nil {+ t.Fatalf("decode: %v", err)+ }+ assertPatrolControlCompatibilityAliases(t, status)+ if status.PatrolControlLoopStarterCount != 1 ||+ status.PatrolControlCompletedLoopCount != 1 ||+ status.PatrolControlResolvedLoopCount != 1 ||+ status.ProActivationLoopStarterCount != 0 ||+ status.ProActivationCompletedLoopCount != 1 ||+ status.ProActivationResolvedLoopCount != 1 ||+ status.VerifiedOutcomeCount != 1 ||+ status.ApprovedDecisionCount != 1 {+ t.Fatalf("Patrol control resolved-loop counts wrong: %+v", status)+ }+ if status.PatrolControlValueState != "verified" {+ t.Fatalf("PatrolControlValueState = %q; want verified", status.PatrolControlValueState)+ }+ if status.ProActivationValueProofState != "verified" {+ t.Fatalf("ProActivationValueProofState = %q; want verified", status.ProActivationValueProofState)+ }+ if status.NextAction != "complete" ||+ status.ProgressLabel != "Patrol handled an infrastructure issue, verified the outcome, and recorded what happened." {+ t.Fatalf("Patrol control resolved-loop progress wrong: %+v", status)+ }+ steps := agentOperationsLoopStepsByID(status.Steps)+ if got := steps["assistant"].Count; got != 1 {+ t.Fatalf("assistant step count = %d; want contextual collaboration count", got)+ }+ for _, step := range status.Steps {+ if step.Status != AgentOperationsLoopStepComplete {+ t.Fatalf("step %s status = %q; want complete; steps=%+v", step.ID, step.Status, status.Steps)+ }+ }+}++func TestHandleAgentOperationsLoopStatus_ResolvesPatrolControlWithoutExternalAgentReadiness(t *testing.T) {+ h, _, _ := fleetFixtureHandlers(t, []unified.Resource{+ {ID: "vm:101", Type: "vm", Name: "db-01"},+ })+ h.SetExternalAgentReadinessProvider(nil)+ now := time.Now().UTC()+ h.SetAIUsageProvider(staticAIUsageProvider{+ history: &config.AIUsageHistoryData{+ Events: []config.AIUsageEventRecord{{+ Timestamp: now.Add(-9 * time.Minute),+ UseCase: "chat",+ ContextScope: "patrol_finding",+ FindingID: "finding-pro",+ }},+ },+ })+ h.SetWorkflowPromptActivityProvider(staticWorkflowPromptActivityProvider{+ history: &config.WorkflowPromptActivityHistoryData{+ Events: []config.WorkflowPromptActivityRecord{{+ Timestamp: now.Add(-10 * time.Minute),+ Surface: config.WorkflowPromptActivitySurfaceProActivation,+ PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop,+ }},+ },+ })++ store, err := h.resources.getStore("default")+ if err != nil {+ t.Fatalf("getStore: %v", err)+ }+ if err := store.RecordActionAudit(unified.ActionAuditRecord{+ ID: "act-pro-verified",+ CreatedAt: now.Add(-5 * time.Minute),+ UpdatedAt: now,+ State: unified.ActionStateCompleted,+ Request: unified.ActionRequest{+ RequestID: "req-pro-verified",+ ResourceID: "vm:101",+ CapabilityName: "restart_service",+ Params: map[string]any{"command": "systemctl restart nginx"},+ RequestedBy: "pulse_patrol",+ },+ Plan: unified.ActionPlan{+ ActionID: "act-pro-verified",+ RequestID: "req-pro-verified",+ PlannedAt: now.Add(-6 * time.Minute),+ ExpiresAt: now.Add(time.Hour),+ },+ Approvals: []unified.ActionApprovalRecord{{+ Actor: "[email protected]",+ Method: unified.MethodUI,+ Timestamp: now.Add(-4 * time.Minute),+ Outcome: unified.OutcomeApproved,+ }},+ Result: &unified.ExecutionResult{+ Success: true,+ Output: "service restarted",+ },+ VerificationOutcome: unified.VerificationOutcome{Status: unified.VerificationVerified},+ }); err != nil {+ t.Fatalf("RecordActionAudit: %v", err)+ }++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/agent/operations-loop/status", nil)+ h.HandleOperationsLoopStatus(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("status: got %d, body=%s", rec.Code, rec.Body.String())+ }++ var status AgentOperationsLoopStatus+ if err := json.Unmarshal(rec.Body.Bytes(), &status); err != nil {+ t.Fatalf("decode: %v", err)+ }+ assertPatrolControlCompatibilityAliases(t, status)+ if status.ExternalAgentReady ||+ status.PatrolControlCompletedLoopCount != 1 ||+ status.PatrolControlResolvedLoopCount != 1 ||+ status.ProActivationCompletedLoopCount != 1 ||+ status.ProActivationResolvedLoopCount != 1 ||+ status.VerifiedOutcomeCount != 1 ||+ status.ApprovedDecisionCount != 1 {+ t.Fatalf("Patrol control should resolve independently from optional external-agent readiness: %+v", status)+ }+ if status.PatrolControlValueState != "verified" {+ t.Fatalf("PatrolControlValueState = %q; want verified", status.PatrolControlValueState)+ }+ if status.ProActivationValueProofState != "verified" {+ t.Fatalf("ProActivationValueProofState = %q; want verified", status.ProActivationValueProofState)+ }+ if status.NextAction != "complete" ||+ status.ProgressLabel != "Patrol handled an infrastructure issue, verified the outcome, and recorded what happened." {+ t.Fatalf("Patrol control without external-agent readiness progress wrong: %+v", status)+ }+ steps := agentOperationsLoopStepsByID(status.Steps)+ if _, ok := steps["external_agents"]; ok {+ t.Fatalf("external-agent readiness must not render as an operator step: %+v", status.Steps)+ }+ for _, stepID := range []string{"patrol", "assistant", "governance", "verification"} {+ if got := steps[stepID].Status; got != AgentOperationsLoopStepComplete {+ t.Fatalf("%s step status = %q; want complete; steps=%+v", stepID, got, status.Steps)+ }+ }+}++func TestHandleAgentOperationsLoopStatus_DoesNotResolvePatrolControlWithoutContextualCollaboration(t *testing.T) {+ h, _, _ := fleetFixtureHandlers(t, []unified.Resource{+ {ID: "vm:101", Type: "vm", Name: "db-01"},+ })+ now := time.Now().UTC()+ h.SetWorkflowPromptActivityProvider(staticWorkflowPromptActivityProvider{+ history: &config.WorkflowPromptActivityHistoryData{+ Events: []config.WorkflowPromptActivityRecord{+ {+ Timestamp: now.Add(-10 * time.Minute),+ Surface: config.WorkflowPromptActivitySurfacePulsePatrol,+ PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop,+ },+ },+ },+ })++ store, err := h.resources.getStore("default")+ if err != nil {+ t.Fatalf("getStore: %v", err)+ }+ if err := store.RecordActionAudit(unified.ActionAuditRecord{+ ID: "act-pro-verified-no-context",+ CreatedAt: now.Add(-5 * time.Minute),+ UpdatedAt: now,+ State: unified.ActionStateCompleted,+ Request: unified.ActionRequest{+ RequestID: "req-pro-verified-no-context",+ ResourceID: "vm:101",+ CapabilityName: "restart_service",+ RequestedBy: "pulse_patrol",+ },+ Plan: unified.ActionPlan{+ ActionID: "act-pro-verified-no-context",+ RequestID: "req-pro-verified-no-context",+ PlannedAt: now.Add(-6 * time.Minute),+ ExpiresAt: now.Add(time.Hour),+ },+ Approvals: []unified.ActionApprovalRecord{{+ Actor: "[email protected]",+ Method: unified.MethodUI,+ Timestamp: now.Add(-4 * time.Minute),+ Outcome: unified.OutcomeApproved,+ }},+ Result: &unified.ExecutionResult{Success: true},+ VerificationOutcome: unified.VerificationOutcome{Status: unified.VerificationVerified},+ }); err != nil {+ t.Fatalf("RecordActionAudit: %v", err)+ }++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/agent/operations-loop/status", nil)+ h.HandleOperationsLoopStatus(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("status: got %d, body=%s", rec.Code, rec.Body.String())+ }++ var status AgentOperationsLoopStatus+ if err := json.Unmarshal(rec.Body.Bytes(), &status); err != nil {+ t.Fatalf("decode: %v", err)+ }+ assertPatrolControlCompatibilityAliases(t, status)+ if status.ProActivationLoopStarterCount != 0 ||+ status.PatrolControlLoopStarterCount != 1 ||+ status.PatrolControlResolvedLoopCount != 0 ||+ status.ProActivationResolvedLoopCount != 0 ||+ status.ApprovedDecisionCount != 1 ||+ status.VerifiedOutcomeCount != 1 {+ t.Fatalf("Patrol control weak-evidence counts wrong: %+v", status)+ }+ if status.NextAction != "open_assistant" ||+ status.ProgressLabel != "Open Assistant to explain the Patrol issue and safest next step." {+ t.Fatalf("weak Patrol control progress wrong: %+v", status)+ }+ steps := agentOperationsLoopStepsByID(status.Steps)+ if got := steps["assistant"].Status; got != AgentOperationsLoopStepCurrent {+ t.Fatalf("assistant step status = %q; want current; steps=%+v", got, status.Steps)+ }+ if got := steps["verification"].Status; got != AgentOperationsLoopStepPending {+ t.Fatalf("verification step status = %q; want pending until context proof; steps=%+v", got, status.Steps)+ }+}++func TestHandleAgentOperationsLoopStatus_DoesNotTreatUnapprovedExecutionAsGovernedDecision(t *testing.T) {+ h, findings, _ := fleetFixtureHandlers(t, []unified.Resource{+ {ID: "vm:101", Type: "vm", Name: "db-01"},+ })+ findings.byResource["vm:101"] = []AgentResourceFindingSnapshot{+ {ID: "finding-cpu", Title: "CPU pressure", Severity: "warning"},+ }++ store, err := h.resources.getStore("default")+ if err != nil {+ t.Fatalf("getStore: %v", err)+ }+ now := time.Now().UTC()+ if err := store.RecordActionAudit(unified.ActionAuditRecord{+ ID: "act-unapproved",+ CreatedAt: now.Add(-5 * time.Minute),+ UpdatedAt: now,+ State: unified.ActionStateCompleted,+ Request: unified.ActionRequest{+ RequestID: "req-unapproved",+ ResourceID: "vm:101",+ CapabilityName: "restart_service",+ Params: map[string]any{"command": "systemctl restart nginx"},+ RequestedBy: "pulse_patrol",+ },+ Plan: unified.ActionPlan{+ ActionID: "act-unapproved",+ RequestID: "req-unapproved",+ PlannedAt: now.Add(-6 * time.Minute),+ ExpiresAt: now.Add(time.Hour),+ RequiresApproval: false,+ },+ Result: &unified.ExecutionResult{+ Success: true,+ Output: "service restarted",+ },+ VerificationOutcome: unified.VerificationOutcome{Status: unified.VerificationVerified},+ }); err != nil {+ t.Fatalf("RecordActionAudit: %v", err)+ }++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/agent/operations-loop/status", nil)+ h.HandleOperationsLoopStatus(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("status: got %d, body=%s", rec.Code, rec.Body.String())+ }+ var status AgentOperationsLoopStatus+ if err := json.NewDecoder(rec.Body).Decode(&status); err != nil {+ t.Fatalf("decode: %v", err)+ }+ assertPatrolControlCompatibilityAliases(t, status)+ if status.NextAction != "open_assistant" {+ t.Fatalf("NextAction = %q; want open_assistant; status=%+v", status.NextAction, status)+ }+ if status.GovernedActionCount != 0 ||+ status.ApprovedDecisionCount != 0 ||+ status.RejectedDecisionCount != 0 ||+ status.VerifiedOutcomeCount != 0 {+ t.Fatalf("unapproved execution must not satisfy governance or verification: %+v", status)+ }+ steps := agentOperationsLoopStepsByID(status.Steps)+ if got := steps["governance"].Status; got != AgentOperationsLoopStepPending {+ t.Fatalf("governance status = %q; want pending; steps=%+v", got, status.Steps)+ }+ if got := steps["verification"].Status; got != AgentOperationsLoopStepPending {+ t.Fatalf("verification status = %q; want pending; steps=%+v", got, status.Steps)+ }+}++func TestHandleAgentOperationsLoopStatus_UsesDecisionLifecycleEvidenceForOlderPlans(t *testing.T) {+ h, _, _ := fleetFixtureHandlers(t, []unified.Resource{+ {ID: "vm:101", Type: "vm", Name: "db-01"},+ })++ store, err := h.resources.getStore("default")+ if err != nil {+ t.Fatalf("getStore: %v", err)+ }+ now := time.Now().UTC()+ h.SetAIUsageProvider(staticAIUsageProvider{+ history: &config.AIUsageHistoryData{+ Events: []config.AIUsageEventRecord{{+ Timestamp: now.Add(-10 * time.Minute),+ UseCase: "chat",+ ContextScope: "patrol_finding",+ }},+ },+ })+ h.SetWorkflowPromptActivityProvider(staticWorkflowPromptActivityProvider{+ history: &config.WorkflowPromptActivityHistoryData{+ Events: []config.WorkflowPromptActivityRecord{{+ PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop,+ Surface: config.WorkflowPromptActivitySurfaceProActivation,+ Timestamp: now.Add(-9 * time.Minute),+ }},+ },+ })+ old := now.Add(-agentOperationsLoopActionWindow - time.Hour)+ record := unified.ActionAuditRecord{+ ID: "act-rejected",+ CreatedAt: old,+ UpdatedAt: old,+ State: unified.ActionStatePending,+ Request: unified.ActionRequest{+ RequestID: "req-rejected",+ ResourceID: "vm:101",+ CapabilityName: "restart_service",+ Params: map[string]any{"command": "systemctl restart nginx"},+ RequestedBy: "pulse_patrol",+ },+ Plan: unified.ActionPlan{+ ActionID: "act-rejected",+ RequestID: "req-rejected",+ PlannedAt: old,+ ExpiresAt: now.Add(time.Hour),+ RequiresApproval: true,+ },+ }+ if err := store.RecordActionAudit(record); err != nil {+ t.Fatalf("RecordActionAudit: %v", err)+ }+ rejected, event, err := unified.ApplyActionDecision(record, unified.ActionApprovalRecord{+ Actor: "[email protected]",+ Method: unified.MethodUI,+ Outcome: unified.OutcomeRejected,+ }, now)+ if err != nil {+ t.Fatalf("ApplyActionDecision: %v", err)+ }+ if err := store.RecordActionDecision(rejected, event); err != nil {+ t.Fatalf("RecordActionDecision: %v", err)+ }++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/agent/operations-loop/status", nil)+ h.HandleOperationsLoopStatus(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("status: got %d, body=%s", rec.Code, rec.Body.String())+ }+ var status AgentOperationsLoopStatus+ if err := json.NewDecoder(rec.Body).Decode(&status); err != nil {+ t.Fatalf("decode: %v", err)+ }+ assertPatrolControlCompatibilityAliases(t, status)+ if status.GovernedActionCount != 1 || status.RejectedDecisionCount != 1 || status.ApprovedDecisionCount != 0 {+ t.Fatalf("decision counts wrong for rejected action: %+v", status)+ }+ if status.VerifiedOutcomeCount != 0 {+ t.Fatalf("VerifiedOutcomeCount = %d; want 0 for rejected decision", status.VerifiedOutcomeCount)+ }+ if status.PatrolControlCompletedLoopCount != 1 ||+ status.PatrolControlResolvedLoopCount != 0 ||+ status.ProActivationCompletedLoopCount != 1 ||+ status.ProActivationResolvedLoopCount != 0 {+ t.Fatalf("Patrol control terminal counts wrong for rejected action: %+v", status)+ }+ if status.PatrolControlValueState != "governed_decision_recorded" {+ t.Fatalf("PatrolControlValueState = %q; want governed_decision_recorded", status.PatrolControlValueState)+ }+ if status.ProActivationValueProofState != "governed_decision_recorded" {+ t.Fatalf("ProActivationValueProofState = %q; want governed_decision_recorded", status.ProActivationValueProofState)+ }+ if status.NextAction != "complete" {+ t.Fatalf("NextAction = %q; want complete; status=%+v", status.NextAction, status)+ }+ steps := agentOperationsLoopStepsByID(status.Steps)+ if got := steps["governance"].Status; got != AgentOperationsLoopStepComplete {+ t.Fatalf("governance status = %q; want complete; steps=%+v", got, status.Steps)+ }+ if got := steps["governance"].Count; got != 1 {+ t.Fatalf("governance step count = %d; want rejected decision count", got)+ }+ if got := steps["verification"].Status; got != AgentOperationsLoopStepComplete {+ t.Fatalf("verification status = %q; want complete for rejected terminal decision; steps=%+v", got, status.Steps)+ }+ if got := steps["verification"].Count; got != 1 {+ t.Fatalf("verification step count = %d; want terminal rejection count", got)+ }+ if status.ProgressLabel != "Patrol recorded a rejected change decision. Nothing was changed; approve a safer fix before marking the issue resolved." {+ t.Fatalf("ProgressLabel = %q; want Patrol control governed rejection summary", status.ProgressLabel)+ }+}++func TestHandleAgentOperationsLoopStatus_ApprovedDecisionStillNeedsVerifiedOutcome(t *testing.T) {+ h, _, _ := fleetFixtureHandlers(t, []unified.Resource{+ {ID: "vm:101", Type: "vm", Name: "db-01"},+ })++ store, err := h.resources.getStore("default")+ if err != nil {+ t.Fatalf("getStore: %v", err)+ }+ now := time.Now().UTC()+ h.SetAIUsageProvider(staticAIUsageProvider{+ history: &config.AIUsageHistoryData{+ Events: []config.AIUsageEventRecord{{+ Timestamp: now.Add(-10 * time.Minute),+ UseCase: "chat",+ ContextScope: "patrol_finding",+ }},+ },+ })+ record := unified.ActionAuditRecord{+ ID: "act-approved",+ CreatedAt: now.Add(-10 * time.Minute),+ UpdatedAt: now.Add(-10 * time.Minute),+ State: unified.ActionStatePending,+ Request: unified.ActionRequest{+ RequestID: "req-approved",+ ResourceID: "vm:101",+ CapabilityName: "restart_service",+ Params: map[string]any{"command": "systemctl restart nginx"},+ RequestedBy: "pulse_patrol",+ },+ Plan: unified.ActionPlan{+ ActionID: "act-approved",+ RequestID: "req-approved",+ PlannedAt: now.Add(-10 * time.Minute),+ ExpiresAt: now.Add(time.Hour),+ RequiresApproval: true,+ },+ }+ if err := store.RecordActionAudit(record); err != nil {+ t.Fatalf("RecordActionAudit: %v", err)+ }+ approved, event, err := unified.ApplyActionDecision(record, unified.ActionApprovalRecord{+ Actor: "[email protected]",+ Method: unified.MethodUI,+ Outcome: unified.OutcomeApproved,+ }, now)+ if err != nil {+ t.Fatalf("ApplyActionDecision: %v", err)+ }+ if err := store.RecordActionDecision(approved, event); err != nil {+ t.Fatalf("RecordActionDecision: %v", err)+ }++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/agent/operations-loop/status", nil)+ h.HandleOperationsLoopStatus(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("status: got %d, body=%s", rec.Code, rec.Body.String())+ }+ var status AgentOperationsLoopStatus+ if err := json.NewDecoder(rec.Body).Decode(&status); err != nil {+ t.Fatalf("decode: %v", err)+ }+ assertPatrolControlCompatibilityAliases(t, status)+ if status.GovernedActionCount != 1 || status.ApprovedDecisionCount != 1 || status.RejectedDecisionCount != 0 {+ t.Fatalf("decision counts wrong for approved action: %+v", status)+ }+ if status.VerifiedOutcomeCount != 0 {+ t.Fatalf("VerifiedOutcomeCount = %d; want 0 before verification", status.VerifiedOutcomeCount)+ }+ if status.NextAction != "review_findings" {+ t.Fatalf("NextAction = %q; want review_findings; status=%+v", status.NextAction, status)+ }+ steps := agentOperationsLoopStepsByID(status.Steps)+ if got := steps["governance"].Status; got != AgentOperationsLoopStepComplete {+ t.Fatalf("governance status = %q; want complete; steps=%+v", got, status.Steps)+ }+ if got := steps["governance"].Count; got != 1 {+ t.Fatalf("governance step count = %d; want approved decision count", got)+ }+ if got := steps["verification"].Status; got != AgentOperationsLoopStepCurrent {+ t.Fatalf("verification status = %q; want current; steps=%+v", got, status.Steps)+ }+ if got := steps["verification"].Count; got != 0 {+ t.Fatalf("verification step count = %d; want zero before verified outcome", got)+ }+}++func TestHandleAgentOperationsLoopStatus_ReviewApprovalsWhenApprovalPending(t *testing.T) {+ h, findings, approvals := fleetFixtureHandlers(t, []unified.Resource{+ {ID: "vm:101", Type: "vm", Name: "db-01"},+ })+ findings.byResource["vm:101"] = []AgentResourceFindingSnapshot{{ID: "finding-cpu", Severity: "warning"}}+ approvals.byResource["vm:101"] = []AgentResourceApprovalSummary{{ID: "approval-1"}}+ now := time.Now().UTC()+ h.SetAIUsageProvider(staticAIUsageProvider{+ history: &config.AIUsageHistoryData{+ Events: []config.AIUsageEventRecord{{+ Timestamp: now.Add(-10 * time.Minute),+ UseCase: "chat",+ ContextScope: "patrol_finding",+ }},+ },+ })++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/agent/operations-loop/status", nil)+ h.HandleOperationsLoopStatus(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("status: got %d, body=%s", rec.Code, rec.Body.String())+ }+ var status AgentOperationsLoopStatus+ if err := json.NewDecoder(rec.Body).Decode(&status); err != nil {+ t.Fatalf("decode: %v", err)+ }+ assertPatrolControlCompatibilityAliases(t, status)+ if status.NextAction != "review_approvals" {+ t.Fatalf("NextAction = %q; want review_approvals", status.NextAction)+ }+ steps := agentOperationsLoopStepsByID(status.Steps)+ if got := steps["governance"].Status; got != AgentOperationsLoopStepCurrent {+ t.Fatalf("governance status = %q; want current; steps=%+v", got, status.Steps)+ }+ if got := steps["governance"].Count; got != 1 {+ t.Fatalf("governance step count = %d; want pending approval count", got)+ }+ if got := steps["verification"].Status; got != AgentOperationsLoopStepPending {+ t.Fatalf("verification status = %q; want pending; steps=%+v", got, status.Steps)+ }+}++func TestHandleAgentOperationsLoopStatus_RejectsNonGet(t *testing.T) {+ h, _, _ := fleetFixtureHandlers(t, []unified.Resource{})+ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodPost, "/api/agent/operations-loop/status", nil)+ h.HandleOperationsLoopStatus(rec, req)+ if rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("status: got %d, want 405", rec.Code)+ }+}++func agentOperationsLoopStepsByID(steps []AgentOperationsLoopStep) map[string]AgentOperationsLoopStep {+ byID := map[string]AgentOperationsLoopStep{}+ for _, step := range steps {+ byID[step.ID] = step+ }+ return byID+}++func assertPatrolControlCompatibilityAliases(t *testing.T, status AgentOperationsLoopStatus) {+ t.Helper()+ if status.PatrolAutonomyLoopStarterCount != status.PatrolControlLoopStarterCount {+ t.Fatalf("legacy Patrol autonomy starter alias drifted from Patrol control: control=%d legacy=%d",+ status.PatrolControlLoopStarterCount, status.PatrolAutonomyLoopStarterCount)+ }+ if status.PatrolAutonomyCompletedLoopCount != status.PatrolControlCompletedLoopCount ||+ status.PatrolAutonomyResolvedLoopCount != status.PatrolControlResolvedLoopCount ||+ status.PatrolAutonomyValueState != status.PatrolControlValueState {+ t.Fatalf("legacy Patrol autonomy aliases drifted from Patrol control: control=%d/%d/%q legacy=%d/%d/%q",+ status.PatrolControlCompletedLoopCount,+ status.PatrolControlResolvedLoopCount,+ status.PatrolControlValueState,+ status.PatrolAutonomyCompletedLoopCount,+ status.PatrolAutonomyResolvedLoopCount,+ status.PatrolAutonomyValueState,+ )+ }+ if status.ProActivationCompletedLoopCount != status.PatrolControlCompletedLoopCount ||+ status.ProActivationResolvedLoopCount != status.PatrolControlResolvedLoopCount ||+ status.ProActivationValueProofState != status.PatrolControlValueState {+ t.Fatalf("legacy Pro activation aliases drifted from Patrol control: control=%d/%d/%q legacy=%d/%d/%q",+ status.PatrolControlCompletedLoopCount,+ status.PatrolControlResolvedLoopCount,+ status.PatrolControlValueState,+ status.ProActivationCompletedLoopCount,+ status.ProActivationResolvedLoopCount,+ status.ProActivationValueProofState,+ )+ }+}+// pendingApprovalsForResourceFromStore is the named seam the// router-side AgentApprovalsProvider closure delegates to. The// next four tests pin the substrate's tenant- anddiff --git a/internal/api/agent_substrate_e2e_test.go b/internal/api/agent_substrate_e2e_test.goindex c6e76aae3b..18ef1f3072 100644--- a/internal/api/agent_substrate_e2e_test.go+++ b/internal/api/agent_substrate_e2e_test.go@@ -8,6 +8,7 @@ import ("strings""testing"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/monitoring")@@ -74,17 +75,18 @@ func TestAgentSubstrate_DiscoveryToTriageToDepthFlowsThroughHTTPBoundary(t *testbyName[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",+ agentcapabilities.ResourceContextCapabilityName,+ agentcapabilities.FleetContextCapabilityName,+ agentcapabilities.OperationsLoopStatusCapabilityName,+ agentcapabilities.EventSubscriptionCapabilityName,+ agentcapabilities.GetOperatorStateCapabilityName,+ agentcapabilities.SetOperatorStateCapabilityName,+ agentcapabilities.ClearOperatorStateCapabilityName,+ agentcapabilities.ListFindingsCapabilityName,+ agentcapabilities.AcknowledgeFindingCapabilityName,+ agentcapabilities.SnoozeFindingCapabilityName,+ agentcapabilities.DismissFindingCapabilityName,+ agentcapabilities.ResolveFindingCapabilityName,}for _, name := range required {if _, ok := byName[name]; !ok {@@ -95,24 +97,25 @@ func TestAgentSubstrate_DiscoveryToTriageToDepthFlowsThroughHTTPBoundary(t *test// --- 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)+ fleetCap := byName[agentcapabilities.FleetContextCapabilityName]+ if fleetCap.Path != agentcapabilities.FleetContextCapabilityPath {+ t.Fatalf("%s path: got %q, want %q", agentcapabilities.FleetContextCapabilityName, fleetCap.Path, agentcapabilities.FleetContextCapabilityPath)}if fleetCap.Method != http.MethodGet {- t.Fatalf("get_fleet_context method: got %q, want GET", fleetCap.Method)+ t.Fatalf("%s method: got %q, want GET", agentcapabilities.FleetContextCapabilityName, fleetCap.Method)}- if fleetCap.Scope != "monitoring:read" {- t.Fatalf("get_fleet_context scope: got %q, want monitoring:read", fleetCap.Scope)+ if fleetCap.Scope != config.ScopeMonitoringRead {+ t.Fatalf("%s scope: got %q, want %s", agentcapabilities.FleetContextCapabilityName, fleetCap.Scope, config.ScopeMonitoringRead)}if fleetCap.ResponseShape != "AgentFleetContext" {- t.Fatalf("get_fleet_context response shape: got %q, want AgentFleetContext", fleetCap.ResponseShape)+ t.Fatalf("%s response shape: got %q, want AgentFleetContext", agentcapabilities.FleetContextCapabilityName, fleetCap.ResponseShape)}+ fleetPath := projectAgentCapabilityPath(t, fleetCap, nil)// 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)+ req = httptest.NewRequest(http.MethodGet, fleetPath, nil)rec = httptest.NewRecorder()router.Handler().ServeHTTP(rec, req)if rec.Code != http.StatusUnauthorized {@@ -120,7 +123,7 @@ func TestAgentSubstrate_DiscoveryToTriageToDepthFlowsThroughHTTPBoundary(t *test}// Authenticated call must serve the iteration-safe shape.- req = httptest.NewRequest(http.MethodGet, fleetCap.Path, nil)+ req = httptest.NewRequest(http.MethodGet, fleetPath, nil)req.Header.Set("X-API-Token", rawToken)rec = httptest.NewRecorder()router.Handler().ServeHTTP(rec, req)@@ -146,23 +149,55 @@ func TestAgentSubstrate_DiscoveryToTriageToDepthFlowsThroughHTTPBoundary(t *testt.Error("fleet.GeneratedAt must be populated so agents can reason about freshness")}+ statusCap := byName[agentcapabilities.OperationsLoopStatusCapabilityName]+ if statusCap.Path != agentcapabilities.OperationsLoopStatusCapabilityPath {+ t.Fatalf("%s path: got %q, want %q", agentcapabilities.OperationsLoopStatusCapabilityName, statusCap.Path, agentcapabilities.OperationsLoopStatusCapabilityPath)+ }+ if statusCap.Method != http.MethodGet {+ t.Fatalf("%s method: got %q, want GET", agentcapabilities.OperationsLoopStatusCapabilityName, statusCap.Method)+ }+ if statusCap.Scope != config.ScopeMonitoringRead {+ t.Fatalf("%s scope: got %q, want %s", agentcapabilities.OperationsLoopStatusCapabilityName, statusCap.Scope, config.ScopeMonitoringRead)+ }+ if statusCap.ResponseShape != "AgentOperationsLoopStatus" {+ t.Fatalf("%s response shape: got %q, want AgentOperationsLoopStatus", agentcapabilities.OperationsLoopStatusCapabilityName, statusCap.ResponseShape)+ }+ req = httptest.NewRequest(http.MethodGet, projectAgentCapabilityPath(t, statusCap, nil), nil)+ req.Header.Set("X-API-Token", rawToken)+ rec = httptest.NewRecorder()+ router.Handler().ServeHTTP(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("operations-loop status GET auth: status = %d, body = %s", rec.Code, rec.Body.String())+ }+ var loopStatus AgentOperationsLoopStatus+ if err := json.NewDecoder(rec.Body).Decode(&loopStatus); err != nil {+ t.Fatalf("decode operations-loop status: %v", err)+ }+ loopSteps := agentOperationsLoopStepsByID(loopStatus.Steps)+ if loopStatus.NextAction != "run_patrol" || len(loopStatus.Steps) != 4 || loopStatus.GeneratedAt.IsZero() {+ t.Fatalf("operations-loop status shape = %+v", loopStatus)+ }+ if _, ok := loopSteps["external_agents"]; ok {+ t.Fatalf("operations-loop status must keep external-agent readiness out of steps: %+v", loopStatus.Steps)+ }+// --- 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)+ contextCap := byName[agentcapabilities.ResourceContextCapabilityName]+ if contextCap.Path != agentcapabilities.ResourceContextCapabilityPath {+ t.Fatalf("%s path: got %q, want %q", agentcapabilities.ResourceContextCapabilityName, contextCap.Path, agentcapabilities.ResourceContextCapabilityPath)}hasNotFoundCode := falsefor _, code := range contextCap.ErrorCodes {- if code == "resource_not_found" {+ if code == agentcapabilities.AgentErrCodeResourceNotFound {hasNotFoundCode = truebreak}}if !hasNotFoundCode {- t.Fatalf("get_resource_context manifest must declare resource_not_found error code; got %v", contextCap.ErrorCodes)+ t.Fatalf("%s manifest must declare %s error code; got %v", agentcapabilities.ResourceContextCapabilityName, agentcapabilities.AgentErrCodeResourceNotFound, contextCap.ErrorCodes)}// Substitute a deliberately-unknown canonical id so the handler@@ -170,7 +205,9 @@ func TestAgentSubstrate_DiscoveryToTriageToDepthFlowsThroughHTTPBoundary(t *test// 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)+ unknownPath := projectAgentCapabilityPath(t, contextCap, map[string]any{+ agentcapabilities.ResourceIDArgumentName: "vm:e2e-unknown-99",+ })req = httptest.NewRequest(http.MethodGet, unknownPath, nil)req.Header.Set("X-API-Token", rawToken)rec = httptest.NewRecorder()@@ -184,15 +221,15 @@ func TestAgentSubstrate_DiscoveryToTriageToDepthFlowsThroughHTTPBoundary(t *test// 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)+ if !strings.Contains(body, `"error":"`+agentcapabilities.AgentErrCodeResourceNotFound+`"`) {+ t.Errorf("resource-context unknown body must carry stable error code %s under the \"error\" key; body = %s", agentcapabilities.AgentErrCodeResourceNotFound, body)}var errEnvelope map[string]stringif 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 errEnvelope["error"] != agentcapabilities.AgentErrCodeResourceNotFound {+ t.Errorf("error envelope code: got %q, want %s", errEnvelope["error"], agentcapabilities.AgentErrCodeResourceNotFound)}if strings.TrimSpace(errEnvelope["message"]) == "" {t.Error("error envelope must carry a human-readable message alongside the stable code")@@ -203,9 +240,9 @@ func TestAgentSubstrate_DiscoveryToTriageToDepthFlowsThroughHTTPBoundary(t *test// 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)+ streamCap := byName[agentcapabilities.EventSubscriptionCapabilityName]+ if streamCap.Path != agentcapabilities.AgentEventsPath {+ t.Fatalf("%s path: got %q, want %s", agentcapabilities.EventSubscriptionCapabilityName, streamCap.Path, agentcapabilities.AgentEventsPath)}req = httptest.NewRequest(http.MethodGet, streamCap.Path, nil)rec = httptest.NewRecorder()@@ -369,37 +406,42 @@ func TestAgentSubstrate_OperatorStateWriteRoundTripsThroughHTTPBoundary(t *testifor _, c := range manifest.Capabilities {byName[c.Name] = c}- setCap := byName["set_operator_state"]- getCap := byName["get_operator_state"]- clearCap := byName["clear_operator_state"]+ setCap := byName[agentcapabilities.SetOperatorStateCapabilityName]+ getCap := byName[agentcapabilities.GetOperatorStateCapabilityName]+ clearCap := byName[agentcapabilities.ClearOperatorStateCapabilityName]- if setCap.Method != http.MethodPut || setCap.Scope != "monitoring:write" {- t.Fatalf("set_operator_state declared method/scope: got %q/%q, want PUT/monitoring:write",- setCap.Method, setCap.Scope)+ if setCap.Method != http.MethodPut || setCap.Scope != config.ScopeMonitoringWrite {+ t.Fatalf("%s declared method/scope: got %q/%q, want PUT/%s",+ agentcapabilities.SetOperatorStateCapabilityName, setCap.Method, setCap.Scope, config.ScopeMonitoringWrite)}- if !stringSliceContains(setCap.ErrorCodes, "operator_state_invalid") {- t.Fatalf("set_operator_state must declare operator_state_invalid; got %v", setCap.ErrorCodes)+ if !stringSliceContains(setCap.ErrorCodes, agentcapabilities.AgentErrCodeOperatorStateInvalid) {+ t.Fatalf("%s must declare %s; got %v", agentcapabilities.SetOperatorStateCapabilityName, agentcapabilities.AgentErrCodeOperatorStateInvalid, setCap.ErrorCodes)}- if getCap.Method != http.MethodGet || getCap.Scope != "monitoring:read" {- t.Fatalf("get_operator_state declared method/scope: got %q/%q, want GET/monitoring:read",- getCap.Method, getCap.Scope)+ if getCap.Method != http.MethodGet || getCap.Scope != config.ScopeMonitoringRead {+ t.Fatalf("%s declared method/scope: got %q/%q, want GET/%s",+ agentcapabilities.GetOperatorStateCapabilityName, getCap.Method, getCap.Scope, config.ScopeMonitoringRead)}- if !stringSliceContains(getCap.ErrorCodes, "operator_state_not_set") {- t.Fatalf("get_operator_state must declare operator_state_not_set; got %v", getCap.ErrorCodes)+ if !stringSliceContains(getCap.ErrorCodes, agentcapabilities.AgentErrCodeOperatorStateNotSet) {+ t.Fatalf("%s must declare %s; got %v", agentcapabilities.GetOperatorStateCapabilityName, agentcapabilities.AgentErrCodeOperatorStateNotSet, getCap.ErrorCodes)}- if clearCap.Method != http.MethodDelete || clearCap.Scope != "monitoring:write" {- t.Fatalf("clear_operator_state declared method/scope: got %q/%q, want DELETE/monitoring:write",- clearCap.Method, clearCap.Scope)+ if clearCap.Method != http.MethodDelete || clearCap.Scope != config.ScopeMonitoringWrite {+ t.Fatalf("%s declared method/scope: got %q/%q, want DELETE/%s",+ agentcapabilities.ClearOperatorStateCapabilityName, clearCap.Method, clearCap.Scope, config.ScopeMonitoringWrite)}// The capability paths use {resourceId} as the placeholder. Sub// in a colon-bearing canonical id so the test exercises the// URL-routing path most agents will actually hit.resourceID := "vm:e2e-write-101"- resolvedPath := strings.Replace(setCap.Path, "{resourceId}", resourceID, 1)+ pathArgs := map[string]any{+ agentcapabilities.ResourceIDArgumentName: resourceID,+ }+ getPath := projectAgentCapabilityPath(t, getCap, pathArgs)+ setPath := projectAgentCapabilityPath(t, setCap, pathArgs)+ clearPath := projectAgentCapabilityPath(t, clearCap, pathArgs)// --- 1. GET on never-written resource → 404 not_set. ---- req = httptest.NewRequest(http.MethodGet, resolvedPath, nil)+ req = httptest.NewRequest(http.MethodGet, getPath, nil)req.Header.Set("X-API-Token", rawToken)rec = httptest.NewRecorder()router.Handler().ServeHTTP(rec, req)@@ -407,8 +449,8 @@ func TestAgentSubstrate_OperatorStateWriteRoundTripsThroughHTTPBoundary(t *testit.Fatalf("GET unset: status = %d, want 404, body = %s", rec.Code, rec.Body.String())}notSetBody := rec.Body.String()- if !strings.Contains(notSetBody, `"error":"operator_state_not_set"`) {- t.Errorf("GET unset must carry stable error code operator_state_not_set; body = %s", notSetBody)+ if !strings.Contains(notSetBody, `"error":"`+agentcapabilities.AgentErrCodeOperatorStateNotSet+`"`) {+ t.Errorf("GET unset must carry stable error code %s; body = %s", agentcapabilities.AgentErrCodeOperatorStateNotSet, notSetBody)}// --- 2. PUT valid state → 200 with persisted state. ---@@ -417,7 +459,7 @@ func TestAgentSubstrate_OperatorStateWriteRoundTripsThroughHTTPBoundary(t *testi"neverAutoRemediate": true,"note": "decommissioned for hardware refresh"}`)- req = httptest.NewRequest(http.MethodPut, resolvedPath, bytes.NewReader(validBody))+ req = httptest.NewRequest(http.MethodPut, setPath, bytes.NewReader(validBody))req.Header.Set("X-API-Token", rawToken)req.Header.Set("Content-Type", "application/json")rec = httptest.NewRecorder()@@ -450,7 +492,7 @@ func TestAgentSubstrate_OperatorStateWriteRoundTripsThroughHTTPBoundary(t *testi}// --- 3. GET after PUT round-trips. ---- req = httptest.NewRequest(http.MethodGet, resolvedPath, nil)+ req = httptest.NewRequest(http.MethodGet, getPath, nil)req.Header.Set("X-API-Token", rawToken)rec = httptest.NewRecorder()router.Handler().ServeHTTP(rec, req)@@ -475,7 +517,7 @@ func TestAgentSubstrate_OperatorStateWriteRoundTripsThroughHTTPBoundary(t *testi// pin (human text), but the stable code is what agents branch// on.invalidBody := []byte(`{"criticality": "very-high"}`)- req = httptest.NewRequest(http.MethodPut, resolvedPath, bytes.NewReader(invalidBody))+ req = httptest.NewRequest(http.MethodPut, setPath, bytes.NewReader(invalidBody))req.Header.Set("X-API-Token", rawToken)req.Header.Set("Content-Type", "application/json")rec = httptest.NewRecorder()@@ -484,12 +526,12 @@ func TestAgentSubstrate_OperatorStateWriteRoundTripsThroughHTTPBoundary(t *testit.Fatalf("PUT invalid: status = %d, want 400, body = %s", rec.Code, rec.Body.String())}invalidBodyResp := rec.Body.String()- if !strings.Contains(invalidBodyResp, `"error":"operator_state_invalid"`) {- t.Errorf("PUT invalid must carry stable error code operator_state_invalid; body = %s", invalidBodyResp)+ if !strings.Contains(invalidBodyResp, `"error":"`+agentcapabilities.AgentErrCodeOperatorStateInvalid+`"`) {+ t.Errorf("PUT invalid must carry stable error code %s; body = %s", agentcapabilities.AgentErrCodeOperatorStateInvalid, invalidBodyResp)}// --- 5. DELETE → 204 (idempotent). ---- req = httptest.NewRequest(http.MethodDelete, resolvedPath, nil)+ req = httptest.NewRequest(http.MethodDelete, clearPath, nil)req.Header.Set("X-API-Token", rawToken)rec = httptest.NewRecorder()router.Handler().ServeHTTP(rec, req)@@ -498,19 +540,19 @@ func TestAgentSubstrate_OperatorStateWriteRoundTripsThroughHTTPBoundary(t *testi}// --- 6. GET after DELETE → 404 not_set, closing the loop. ---- req = httptest.NewRequest(http.MethodGet, resolvedPath, nil)+ req = httptest.NewRequest(http.MethodGet, getPath, nil)req.Header.Set("X-API-Token", rawToken)rec = httptest.NewRecorder()router.Handler().ServeHTTP(rec, req)if rec.Code != http.StatusNotFound {t.Fatalf("GET after DELETE: status = %d, want 404, body = %s", rec.Code, rec.Body.String())}- if !strings.Contains(rec.Body.String(), `"error":"operator_state_not_set"`) {+ if !strings.Contains(rec.Body.String(), `"error":"`+agentcapabilities.AgentErrCodeOperatorStateNotSet+`"`) {t.Errorf("GET after DELETE must surface operator_state_not_set again; body = %s", rec.Body.String())}// --- 7. DELETE again → still 204 (idempotency contract). ---- req = httptest.NewRequest(http.MethodDelete, resolvedPath, nil)+ req = httptest.NewRequest(http.MethodDelete, clearPath, nil)req.Header.Set("X-API-Token", rawToken)rec = httptest.NewRecorder()router.Handler().ServeHTTP(rec, req)@@ -584,7 +626,11 @@ func TestAgentSubstrate_ActionEndpointsEmitAgentStableEnvelope(t *testing.T) {for _, c := range manifest.Capabilities {byName[c.Name] = c}- for _, want := range []string{"plan_action", "decide_action", "execute_action"} {+ for _, want := range []string{+ agentcapabilities.PlanActionCapabilityName,+ agentcapabilities.DecideActionCapabilityName,+ agentcapabilities.ExecuteActionCapabilityName,+ } {cap, ok := byName[want]if !ok {t.Fatalf("manifest missing %q capability", want)@@ -592,8 +638,8 @@ func TestAgentSubstrate_ActionEndpointsEmitAgentStableEnvelope(t *testing.T) {if cap.Category != "action" {t.Errorf("%s: category = %q, want \"action\"", want, cap.Category)}- if cap.Scope != "ai:execute" {- t.Errorf("%s: scope = %q, want \"ai:execute\"", want, cap.Scope)+ if cap.Scope != config.ScopeAIExecute {+ t.Errorf("%s: scope = %q, want %q", want, cap.Scope, config.ScopeAIExecute)}if len(cap.ErrorCodes) == 0 {t.Errorf("%s: must declare at least one stable errorCode", want)@@ -602,47 +648,74 @@ func TestAgentSubstrate_ActionEndpointsEmitAgentStableEnvelope(t *testing.T) {// --- 1. plan_action: invalid request body lands under the// stable invalid_action_request code with a details map. ---- planCap := byName["plan_action"]- body := strings.NewReader(`{"resourceId": "", "capabilityName": "restart"}`)- req = httptest.NewRequest(http.MethodPost, planCap.Path, body)+ planCap := byName[agentcapabilities.PlanActionCapabilityName]+ body := agentSubstrateJSONBody(t, map[string]string{+ agentcapabilities.ResourceIDArgumentName: "",+ agentcapabilities.CapabilityNameArgumentName: "restart",+ })+ req = httptest.NewRequest(http.MethodPost, projectAgentCapabilityPath(t, planCap, nil), body)req.Header.Set("X-API-Token", rawToken)req.Header.Set("Content-Type", "application/json")rec = httptest.NewRecorder()router.Handler().ServeHTTP(rec, req)if rec.Code != http.StatusBadRequest {- t.Fatalf("plan_action invalid: status = %d, want 400, body = %s", rec.Code, rec.Body.String())+ t.Fatalf("%s invalid: status = %d, want 400, body = %s", agentcapabilities.PlanActionCapabilityName, rec.Code, rec.Body.String())}- assertAgentStableEnvelope(t, "plan_action", rec.Body.String(), "invalid_action_request")- if !stringSliceContains(planCap.ErrorCodes, "invalid_action_request") {- t.Errorf("manifest plan_action.ErrorCodes must declare invalid_action_request; got %v", planCap.ErrorCodes)+ assertAgentStableEnvelope(t, agentcapabilities.PlanActionCapabilityName, rec.Body.String(), agentcapabilities.AgentErrCodeInvalidActionRequest)+ if !stringSliceContains(planCap.ErrorCodes, agentcapabilities.AgentErrCodeInvalidActionRequest) {+ t.Errorf("manifest %s.ErrorCodes must declare %s; got %v", agentcapabilities.PlanActionCapabilityName, agentcapabilities.AgentErrCodeInvalidActionRequest, planCap.ErrorCodes)}// --- 2. decide_action against a non-existent action id. ---- decideCap := byName["decide_action"]- decidePath := strings.Replace(decideCap.Path, "{actionId}", "act_does_not_exist_xyz", 1)- body = strings.NewReader(`{"outcome": "approved"}`)+ decideCap := byName[agentcapabilities.DecideActionCapabilityName]+ decidePath := projectAgentCapabilityPath(t, decideCap, map[string]any{+ agentcapabilities.ActionIDArgumentName: "act_does_not_exist_xyz",+ })+ body = agentSubstrateJSONBody(t, map[string]string{+ agentcapabilities.OutcomeArgumentName: "approved",+ })req = httptest.NewRequest(http.MethodPost, decidePath, body)req.Header.Set("X-API-Token", rawToken)req.Header.Set("Content-Type", "application/json")rec = httptest.NewRecorder()router.Handler().ServeHTTP(rec, req)if rec.Code != http.StatusNotFound {- t.Fatalf("decide_action unknown: status = %d, want 404, body = %s", rec.Code, rec.Body.String())+ t.Fatalf("%s unknown: status = %d, want 404, body = %s", agentcapabilities.DecideActionCapabilityName, rec.Code, rec.Body.String())}- assertAgentStableEnvelope(t, "decide_action", rec.Body.String(), "action_not_found")+ assertAgentStableEnvelope(t, agentcapabilities.DecideActionCapabilityName, rec.Body.String(), agentcapabilities.AgentErrCodeActionNotFound)// --- 3. execute_action against a non-existent action id. ---- executeCap := byName["execute_action"]- executePath := strings.Replace(executeCap.Path, "{actionId}", "act_does_not_exist_xyz", 1)- req = httptest.NewRequest(http.MethodPost, executePath, strings.NewReader(`{}`))+ executeCap := byName[agentcapabilities.ExecuteActionCapabilityName]+ executePath := projectAgentCapabilityPath(t, executeCap, map[string]any{+ agentcapabilities.ActionIDArgumentName: "act_does_not_exist_xyz",+ })+ req = httptest.NewRequest(http.MethodPost, executePath, agentSubstrateJSONBody(t, map[string]any{}))req.Header.Set("X-API-Token", rawToken)req.Header.Set("Content-Type", "application/json")rec = httptest.NewRecorder()router.Handler().ServeHTTP(rec, req)if rec.Code != http.StatusNotFound {- t.Fatalf("execute_action unknown: status = %d, want 404, body = %s", rec.Code, rec.Body.String())+ t.Fatalf("%s unknown: status = %d, want 404, body = %s", agentcapabilities.ExecuteActionCapabilityName, rec.Code, rec.Body.String())+ }+ assertAgentStableEnvelope(t, agentcapabilities.ExecuteActionCapabilityName, rec.Body.String(), agentcapabilities.AgentErrCodeActionNotFound)+}++func projectAgentCapabilityPath(t *testing.T, cap AgentCapability, args map[string]any) string {+ t.Helper()+ projected, err := agentcapabilities.ProjectCapabilityCall(cap, args)+ if err != nil {+ t.Fatalf("%s route projection failed: %v", cap.Name, err)+ }+ return projected.Path+}++func agentSubstrateJSONBody(t *testing.T, payload any) *bytes.Reader {+ t.Helper()+ raw, err := json.Marshal(payload)+ if err != nil {+ t.Fatalf("marshal agent substrate request body: %v", err)}- assertAgentStableEnvelope(t, "execute_action", rec.Body.String(), "action_not_found")+ return bytes.NewReader(raw)}// assertAgentStableEnvelope is the inverse APIError-shape check: itdiff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.goindex 75cff21ae9..e71d89a836 100644--- a/internal/api/ai_handler.go+++ b/internal/api/ai_handler.go@@ -4,6 +4,7 @@ import ("context""crypto/sha256""encoding/json"+ "io""net/http""strconv""strings"@@ -14,6 +15,7 @@ import ("fmt""github.com/google/uuid"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec"airuntime "github.com/rcourtman/pulse-go-rewrite/internal/ai""github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"@@ -59,26 +61,27 @@ type AIService interface {UndoLastTurn(ctx context.Context, sessionID string) (*chat.SessionTurnUndoResult, error)RedoLastTurn(ctx context.Context, sessionID string) (*chat.SessionTurnRedoResult, error)AnswerQuestion(ctx context.Context, questionID string, answers []chat.QuestionAnswer) error- SetAlertProvider(provider chat.MCPAlertProvider)- SetFindingsProvider(provider chat.MCPFindingsProvider)- SetBaselineProvider(provider chat.MCPBaselineProvider)- SetPatternProvider(provider chat.MCPPatternProvider)- SetMetricsHistory(provider chat.MCPMetricsHistoryProvider)+ AssistantSurfaceToolContract(ctx context.Context) agentcapabilities.SurfaceToolContract+ SetAlertProvider(provider chat.AssistantAlertProvider)+ SetFindingsProvider(provider chat.AssistantFindingsProvider)+ SetBaselineProvider(provider chat.AssistantBaselineProvider)+ SetPatternProvider(provider chat.AssistantPatternProvider)+ SetMetricsHistory(provider chat.AssistantMetricsHistoryProvider)SetAgentProfileManager(manager chat.AgentProfileManager)- SetGuestConfigProvider(provider chat.MCPGuestConfigProvider)- SetAppContainerConfigProvider(provider chat.MCPAppContainerConfigProvider)- SetBackupProvider(provider chat.MCPBackupProvider)- SetDiskHealthProvider(provider chat.MCPDiskHealthProvider)- SetUpdatesProvider(provider chat.MCPUpdatesProvider)+ SetGuestConfigProvider(provider chat.AssistantGuestConfigProvider)+ SetAppContainerConfigProvider(provider chat.AssistantAppContainerConfigProvider)+ SetBackupProvider(provider chat.AssistantBackupProvider)+ SetDiskHealthProvider(provider chat.AssistantDiskHealthProvider)+ SetUpdatesProvider(provider chat.AssistantUpdatesProvider)SetFindingsManager(manager chat.FindingsManager)SetMetadataUpdater(updater chat.MetadataUpdater)SetKnowledgeStoreProvider(provider chat.KnowledgeStoreProvider)SetIncidentRecorderProvider(provider chat.IncidentRecorderProvider)SetEventCorrelatorProvider(provider chat.EventCorrelatorProvider)- SetDiscoveryProvider(provider chat.MCPDiscoveryProvider)- SetUnifiedResourceProvider(provider chat.MCPUnifiedResourceProvider)- SetAppContainerActionProvider(provider chat.MCPAppContainerActionProvider)- SetAppContainerReadProvider(provider chat.MCPAppContainerReadProvider)+ SetDiscoveryProvider(provider chat.AssistantDiscoveryProvider)+ SetUnifiedResourceProvider(provider chat.AssistantUnifiedResourceProvider)+ SetAppContainerActionProvider(provider chat.AssistantAppContainerActionProvider)+ SetAppContainerReadProvider(provider chat.AssistantAppContainerReadProvider)UpdateControlSettings(cfg *config.AIConfig)GetBaseURL() string}@@ -616,7 +619,7 @@ func (h *AIHandler) initTenantService(ctx context.Context, orgID string) AIServi},}if recoveryManager != nil {- chatCfg.RecoveryPointsProvider = tools.NewRecoveryPointsMCPAdapter(recoveryManager, orgID)+ chatCfg.RecoveryPointsProvider = tools.NewRecoveryPointsToolAdapter(recoveryManager, orgID)}// Get monitor for state provider@@ -867,7 +870,7 @@ func (h *AIHandler) startWithConfig(ctx context.Context, monitor *monitoring.Mon}_, _, _, _, _, recoveryManager := h.stateRefs()if recoveryManager != nil {- chatCfg.RecoveryPointsProvider = tools.NewRecoveryPointsMCPAdapter(recoveryManager, orgID)+ chatCfg.RecoveryPointsProvider = tools.NewRecoveryPointsToolAdapter(recoveryManager, orgID)}chatCfg.ReportNarrator, chatCfg.ReportFleetNarrator, chatCfg.ReportFindingsProvider = h.resolveReportNarrator(serviceCtx)@@ -885,7 +888,7 @@ func (h *AIHandler) startWithConfig(ctx context.Context, monitor *monitoring.Mon// Initialize approval store for command approval workflow.h.ensureApprovalStore(dataDir)- log.Info().Msg("Pulse AI started (direct integration)")+ log.Info().Msg("Pulse Assistant service started")return nil}@@ -1004,6 +1007,21 @@ type ChatRequest struct {AutonomousMode *bool `json:"autonomous_mode,omitempty"`}+type AssistantWorkflowPromptRenderRequest struct {+ Name string `json:"name"`+ Arguments map[string]string `json:"arguments,omitempty"`+}++type AssistantWorkflowPromptActivityRequest struct {+ Name string `json:"name"`+ Surface string `json:"surface,omitempty"`+}++type AssistantWorkflowPromptRenderResponse struct {+ Description string `json:"description"`+ Text string `json:"text"`+}+type RenameSessionRequest struct {Title string `json:"title"`}@@ -2944,6 +2962,186 @@ func (h *AIHandler) HandleStatus(w http.ResponseWriter, r *http.Request) {json.NewEncoder(w).Encode(status)}+// HandleAssistantSurfaceTools handles GET /api/ai/assistant/surface-tools.+func (h *AIHandler) HandleAssistantSurfaceTools(w http.ResponseWriter, r *http.Request) {+ if cfg := h.getConfig(r.Context()); cfg != nil {+ applyConfiguredCORSHeaders(+ w,+ r.Header.Get("Origin"),+ cfg.AllowedOrigins,+ "GET, OPTIONS",+ "Accept, Cookie",+ )+ }++ if r.Method == http.MethodOptions {+ w.WriteHeader(http.StatusOK)+ return+ }++ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ ctx := r.Context()+ if !h.IsRunning(ctx) {+ http.Error(w, "Pulse Assistant is not running", http.StatusServiceUnavailable)+ return+ }++ svc := h.GetService(ctx)+ if svc == nil {+ http.Error(w, "Pulse Assistant service not available", http.StatusServiceUnavailable)+ return+ }++ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(svc.AssistantSurfaceToolContract(ctx))+}++// HandleRenderWorkflowPrompt handles POST /api/ai/workflow-prompts/render.+func (h *AIHandler) HandleRenderWorkflowPrompt(w http.ResponseWriter, r *http.Request) {+ if cfg := h.getConfig(r.Context()); cfg != nil {+ applyConfiguredCORSHeaders(+ w,+ r.Header.Get("Origin"),+ cfg.AllowedOrigins,+ "POST, OPTIONS",+ "Content-Type, Accept, Cookie",+ )+ }++ if r.Method == http.MethodOptions {+ w.WriteHeader(http.StatusOK)+ return+ }++ if r.Method != http.MethodPost {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ var req AssistantWorkflowPromptRenderRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ http.Error(w, "Invalid request", http.StatusBadRequest)+ return+ }++ manifest := agentcapabilities.CanonicalManifest()+ result, err := agentcapabilities.BuildPulseWorkflowPromptFromManifestWithOptions(+ manifest,+ agentcapabilities.PulseWorkflowPromptParams{+ Name: req.Name,+ Arguments: req.Arguments,+ },+ agentcapabilities.PulseWorkflowPromptRenderOptions{+ ResourceContextInstruction: func(resourceID string) string {+ return fmt.Sprintf("Use the Assistant's current Pulse context for resource %q; if it is not already attached, use the shared resource context capability before making a recommendation", resourceID)+ },+ },+ )+ if err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }+ h.recordAssistantWorkflowPromptActivity(r.Context(), req.Name)++ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(AssistantWorkflowPromptRenderResponse{+ Description: result.Description,+ Text: result.Text,+ })+}++// HandleRecordWorkflowPromptActivity handles POST /api/ai/workflow-prompts/activity.+func (h *AIHandler) HandleRecordWorkflowPromptActivity(w http.ResponseWriter, r *http.Request) {+ if cfg := h.getConfig(r.Context()); cfg != nil {+ applyConfiguredCORSHeaders(+ w,+ r.Header.Get("Origin"),+ cfg.AllowedOrigins,+ "POST, OPTIONS",+ "Content-Type, Accept, Cookie",+ )+ }++ if r.Method == http.MethodOptions {+ w.WriteHeader(http.StatusOK)+ return+ }++ if r.Method != http.MethodPost {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ var req AssistantWorkflowPromptActivityRequest+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096))+ if err := dec.Decode(&req); err != nil {+ http.Error(w, "Invalid request", http.StatusBadRequest)+ return+ }+ var discard json.RawMessage+ if err := dec.Decode(&discard); err != io.EOF {+ http.Error(w, "Invalid request", http.StatusBadRequest)+ return+ }++ promptName := strings.TrimSpace(req.Name)+ if !canonicalWorkflowPromptDeclared(promptName) {+ http.Error(w, "Unknown workflow prompt", http.StatusBadRequest)+ return+ }++ surface := normalizeFirstPartyWorkflowPromptActivitySurface(req.Surface)+ if surface == "" {+ http.Error(w, "Unknown workflow prompt surface", http.StatusBadRequest)+ return+ }++ h.recordFirstPartyWorkflowPromptActivity(r.Context(), surface, promptName)+ w.WriteHeader(http.StatusNoContent)+}++func normalizeFirstPartyWorkflowPromptActivitySurface(surface string) string {+ switch strings.TrimSpace(surface) {+ case "", config.WorkflowPromptActivitySurfacePulseAssistant:+ return config.WorkflowPromptActivitySurfacePulseAssistant+ case config.WorkflowPromptActivitySurfacePulsePatrol:+ return config.WorkflowPromptActivitySurfacePulsePatrol+ case config.WorkflowPromptActivitySurfacePatrolControl:+ return config.WorkflowPromptActivitySurfacePatrolControl+ case config.WorkflowPromptActivitySurfacePatrolAutonomy:+ return config.WorkflowPromptActivitySurfacePatrolAutonomy+ case config.WorkflowPromptActivitySurfaceProActivation:+ return config.WorkflowPromptActivitySurfaceProActivation+ default:+ return ""+ }+}++func (h *AIHandler) recordAssistantWorkflowPromptActivity(ctx context.Context, promptName string) {+ h.recordFirstPartyWorkflowPromptActivity(ctx, config.WorkflowPromptActivitySurfacePulseAssistant, promptName)+}++func (h *AIHandler) recordFirstPartyWorkflowPromptActivity(ctx context.Context, surface, promptName string) {+ if h == nil || strings.TrimSpace(promptName) == "" {+ return+ }+ persistence, ok := h.getPersistence(ctx).(*config.ConfigPersistence)+ if !ok || persistence == nil {+ return+ }+ if err := persistence.RecordWorkflowPromptActivity(config.WorkflowPromptActivityRecord{+ Timestamp: time.Now().UTC(),+ Surface: strings.TrimSpace(surface),+ PromptName: promptName,+ }); err != nil {+ log.Debug().Err(err).Str("prompt_name", strings.TrimSpace(promptName)).Msg("Failed to record first-party workflow prompt activity")+ }+}+// HandleSummarize handles POST /api/ai/sessions/{id}/summarize// Compresses context when nearing model limitsfunc (h *AIHandler) HandleSummarize(w http.ResponseWriter, r *http.Request, sessionID string) {@@ -3119,99 +3317,101 @@ func (h *AIHandler) HandleAnswerQuestion(w http.ResponseWriter, r *http.Request,w.WriteHeader(http.StatusOK)}-// SetAlertProvider sets the alert provider for MCP tools-func (h *AIHandler) SetAlertProvider(provider chat.MCPAlertProvider) {+// SetAlertProvider sets the alert provider for Assistant tools.+func (h *AIHandler) SetAlertProvider(provider chat.AssistantAlertProvider) {if svc := h.getDefaultService(); svc != nil {svc.SetAlertProvider(provider)}}-// SetFindingsProvider sets the findings provider for MCP tools-func (h *AIHandler) SetFindingsProvider(provider chat.MCPFindingsProvider) {+// SetFindingsProvider sets the findings provider for Assistant tools.+func (h *AIHandler) SetFindingsProvider(provider chat.AssistantFindingsProvider) {if svc := h.getDefaultService(); svc != nil {svc.SetFindingsProvider(provider)}}-// SetBaselineProvider sets the baseline provider for MCP tools-func (h *AIHandler) SetBaselineProvider(provider chat.MCPBaselineProvider) {+// SetBaselineProvider sets the baseline provider for Assistant tools.+func (h *AIHandler) SetBaselineProvider(provider chat.AssistantBaselineProvider) {if svc := h.getDefaultService(); svc != nil {svc.SetBaselineProvider(provider)}}-// SetPatternProvider sets the pattern provider for MCP tools-func (h *AIHandler) SetPatternProvider(provider chat.MCPPatternProvider) {+// SetPatternProvider sets the pattern provider for Assistant tools.+func (h *AIHandler) SetPatternProvider(provider chat.AssistantPatternProvider) {if svc := h.getDefaultService(); svc != nil {svc.SetPatternProvider(provider)}}-// SetMetricsHistory sets the metrics history provider for MCP tools-func (h *AIHandler) SetMetricsHistory(provider chat.MCPMetricsHistoryProvider) {+// SetMetricsHistory sets the metrics history provider for Assistant tools.+func (h *AIHandler) SetMetricsHistory(provider chat.AssistantMetricsHistoryProvider) {if svc := h.getDefaultService(); svc != nil {svc.SetMetricsHistory(provider)}}-// SetAgentProfileManager sets the agent profile manager for MCP tools+// SetAgentProfileManager sets the agent profile manager for Assistant tools.func (h *AIHandler) SetAgentProfileManager(manager chat.AgentProfileManager) {if svc := h.getDefaultService(); svc != nil {svc.SetAgentProfileManager(manager)}}-// SetGuestConfigProvider sets the guest config provider for MCP tools-func (h *AIHandler) SetGuestConfigProvider(provider chat.MCPGuestConfigProvider) {+// SetGuestConfigProvider sets the guest config provider for Assistant tools.+func (h *AIHandler) SetGuestConfigProvider(provider chat.AssistantGuestConfigProvider) {if svc := h.getDefaultService(); svc != nil {svc.SetGuestConfigProvider(provider)}}-// SetAppContainerConfigProvider sets the native app-container config provider for MCP tools-func (h *AIHandler) SetAppContainerConfigProvider(provider chat.MCPAppContainerConfigProvider) {+// SetAppContainerConfigProvider sets the native app-container config provider+// for Assistant tools.+func (h *AIHandler) SetAppContainerConfigProvider(provider chat.AssistantAppContainerConfigProvider) {if svc := h.getDefaultService(); svc != nil {svc.SetAppContainerConfigProvider(provider)}}-// SetBackupProvider sets the backup provider for MCP tools-func (h *AIHandler) SetBackupProvider(provider chat.MCPBackupProvider) {+// SetBackupProvider sets the backup provider for Assistant tools.+func (h *AIHandler) SetBackupProvider(provider chat.AssistantBackupProvider) {if svc := h.getDefaultService(); svc != nil {svc.SetBackupProvider(provider)}}-// SetDiskHealthProvider sets the disk health provider for MCP tools-func (h *AIHandler) SetDiskHealthProvider(provider chat.MCPDiskHealthProvider) {+// SetDiskHealthProvider sets the disk health provider for Assistant tools.+func (h *AIHandler) SetDiskHealthProvider(provider chat.AssistantDiskHealthProvider) {if svc := h.getDefaultService(); svc != nil {svc.SetDiskHealthProvider(provider)}}-// SetUpdatesProvider sets the updates provider for MCP tools-func (h *AIHandler) SetUpdatesProvider(provider chat.MCPUpdatesProvider) {+// SetUpdatesProvider sets the updates provider for Assistant tools.+func (h *AIHandler) SetUpdatesProvider(provider chat.AssistantUpdatesProvider) {if svc := h.getDefaultService(); svc != nil {svc.SetUpdatesProvider(provider)}}-// SetFindingsManager sets the findings manager for MCP tools+// SetFindingsManager sets the findings manager for Assistant tools.func (h *AIHandler) SetFindingsManager(manager chat.FindingsManager) {if svc := h.getDefaultService(); svc != nil {svc.SetFindingsManager(manager)}}-// SetMetadataUpdater sets the metadata updater for MCP tools+// SetMetadataUpdater sets the metadata updater for Assistant tools.func (h *AIHandler) SetMetadataUpdater(updater chat.MetadataUpdater) {if svc := h.getDefaultService(); svc != nil {svc.SetMetadataUpdater(updater)}}-// SetUnifiedResourceProvider sets the unified resource provider for MCP tools-func (h *AIHandler) SetUnifiedResourceProvider(provider chat.MCPUnifiedResourceProvider) {+// SetUnifiedResourceProvider sets the unified resource provider for Assistant+// tools.+func (h *AIHandler) SetUnifiedResourceProvider(provider chat.AssistantUnifiedResourceProvider) {if svc := h.getDefaultService(); svc != nil {svc.SetUnifiedResourceProvider(provider)}diff --git a/internal/api/ai_handler_recovery_wiring_test.go b/internal/api/ai_handler_recovery_wiring_test.goindex 2d8bbae33b..9afcb0065d 100644--- a/internal/api/ai_handler_recovery_wiring_test.go+++ b/internal/api/ai_handler_recovery_wiring_test.go@@ -6,6 +6,7 @@ import ("testing""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/ai/chat""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/monitoring"@@ -15,9 +16,9 @@ import (type capturingAIService struct {running bool- appContainerConfigProvider chat.MCPAppContainerConfigProvider- appContainerActionProvider chat.MCPAppContainerActionProvider- appContainerReadProvider chat.MCPAppContainerReadProvider+ appContainerConfigProvider chat.AssistantAppContainerConfigProvider+ appContainerActionProvider chat.AssistantAppContainerActionProvider+ appContainerReadProvider chat.AssistantAppContainerReadProvider}func (s *capturingAIService) Start(ctx context.Context) error { s.running = true; return nil }@@ -71,30 +72,34 @@ func (s *capturingAIService) RedoLastTurn(ctx context.Context, sessionID string)func (s *capturingAIService) AnswerQuestion(ctx context.Context, questionID string, answers []chat.QuestionAnswer) error {return nil}-func (s *capturingAIService) SetAlertProvider(provider chat.MCPAlertProvider) {}-func (s *capturingAIService) SetFindingsProvider(provider chat.MCPFindingsProvider) {}-func (s *capturingAIService) SetBaselineProvider(provider chat.MCPBaselineProvider) {}-func (s *capturingAIService) SetPatternProvider(provider chat.MCPPatternProvider) {}-func (s *capturingAIService) SetMetricsHistory(provider chat.MCPMetricsHistoryProvider) {}-func (s *capturingAIService) SetAgentProfileManager(manager chat.AgentProfileManager) {}-func (s *capturingAIService) SetGuestConfigProvider(provider chat.MCPGuestConfigProvider) {}-func (s *capturingAIService) SetAppContainerConfigProvider(provider chat.MCPAppContainerConfigProvider) {+func (s *capturingAIService) AssistantSurfaceToolContract(ctx context.Context) agentcapabilities.SurfaceToolContract {+ return agentcapabilities.SurfaceToolContract{}+}+func (s *capturingAIService) SetAlertProvider(provider chat.AssistantAlertProvider) {}+func (s *capturingAIService) SetFindingsProvider(provider chat.AssistantFindingsProvider) {}+func (s *capturingAIService) SetBaselineProvider(provider chat.AssistantBaselineProvider) {}+func (s *capturingAIService) SetPatternProvider(provider chat.AssistantPatternProvider) {}+func (s *capturingAIService) SetMetricsHistory(provider chat.AssistantMetricsHistoryProvider) {}+func (s *capturingAIService) SetAgentProfileManager(manager chat.AgentProfileManager) {}+func (s *capturingAIService) SetGuestConfigProvider(provider chat.AssistantGuestConfigProvider) {}+func (s *capturingAIService) SetAppContainerConfigProvider(provider chat.AssistantAppContainerConfigProvider) {s.appContainerConfigProvider = provider}-func (s *capturingAIService) SetBackupProvider(provider chat.MCPBackupProvider) {}-func (s *capturingAIService) SetDiskHealthProvider(provider chat.MCPDiskHealthProvider) {}-func (s *capturingAIService) SetUpdatesProvider(provider chat.MCPUpdatesProvider) {}-func (s *capturingAIService) SetFindingsManager(manager chat.FindingsManager) {}-func (s *capturingAIService) SetMetadataUpdater(updater chat.MetadataUpdater) {}-func (s *capturingAIService) SetKnowledgeStoreProvider(provider chat.KnowledgeStoreProvider) {}-func (s *capturingAIService) SetIncidentRecorderProvider(provider chat.IncidentRecorderProvider) {}-func (s *capturingAIService) SetEventCorrelatorProvider(provider chat.EventCorrelatorProvider) {}-func (s *capturingAIService) SetDiscoveryProvider(provider chat.MCPDiscoveryProvider) {}-func (s *capturingAIService) SetUnifiedResourceProvider(provider chat.MCPUnifiedResourceProvider) {}-func (s *capturingAIService) SetAppContainerActionProvider(provider chat.MCPAppContainerActionProvider) {+func (s *capturingAIService) SetBackupProvider(provider chat.AssistantBackupProvider) {}+func (s *capturingAIService) SetDiskHealthProvider(provider chat.AssistantDiskHealthProvider) {}+func (s *capturingAIService) SetUpdatesProvider(provider chat.AssistantUpdatesProvider) {}+func (s *capturingAIService) SetFindingsManager(manager chat.FindingsManager) {}+func (s *capturingAIService) SetMetadataUpdater(updater chat.MetadataUpdater) {}+func (s *capturingAIService) SetKnowledgeStoreProvider(provider chat.KnowledgeStoreProvider) {}+func (s *capturingAIService) SetIncidentRecorderProvider(provider chat.IncidentRecorderProvider) {}+func (s *capturingAIService) SetEventCorrelatorProvider(provider chat.EventCorrelatorProvider) {}+func (s *capturingAIService) SetDiscoveryProvider(provider chat.AssistantDiscoveryProvider) {}+func (s *capturingAIService) SetUnifiedResourceProvider(provider chat.AssistantUnifiedResourceProvider) {+}+func (s *capturingAIService) SetAppContainerActionProvider(provider chat.AssistantAppContainerActionProvider) {s.appContainerActionProvider = provider}-func (s *capturingAIService) SetAppContainerReadProvider(provider chat.MCPAppContainerReadProvider) {+func (s *capturingAIService) SetAppContainerReadProvider(provider chat.AssistantAppContainerReadProvider) {s.appContainerReadProvider = provider}func (s *capturingAIService) UpdateControlSettings(cfg *config.AIConfig) {}diff --git a/internal/api/ai_handler_test.go b/internal/api/ai_handler_test.goindex 324033bea7..263f76e75c 100644--- a/internal/api/ai_handler_test.go+++ b/internal/api/ai_handler_test.go@@ -6,11 +6,13 @@ import ("fmt""net/http""net/http/httptest"+ "os""path/filepath""strings""testing""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec"airuntime "github.com/rcourtman/pulse-go-rewrite/internal/ai""github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"@@ -23,6 +25,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts""github.com/stretchr/testify/assert""github.com/stretchr/testify/mock"+ "github.com/stretchr/testify/require")type MockAIService struct {@@ -183,24 +186,40 @@ func (m *MockAIService) AnswerQuestion(ctx context.Context, questionID string, areturn args.Error(0)}-func (m *MockAIService) SetAlertProvider(provider chat.MCPAlertProvider) { m.Called(provider) }-func (m *MockAIService) SetFindingsProvider(provider chat.MCPFindingsProvider) { m.Called(provider) }-func (m *MockAIService) SetBaselineProvider(provider chat.MCPBaselineProvider) { m.Called(provider) }-func (m *MockAIService) SetPatternProvider(provider chat.MCPPatternProvider) { m.Called(provider) }-func (m *MockAIService) SetMetricsHistory(provider chat.MCPMetricsHistoryProvider) {+func (m *MockAIService) AssistantSurfaceToolContract(ctx context.Context) agentcapabilities.SurfaceToolContract {+ args := m.Called(ctx)+ if args.Get(0) == nil {+ return agentcapabilities.SurfaceToolContract{}+ }+ return args.Get(0).(agentcapabilities.SurfaceToolContract)+}++func (m *MockAIService) SetAlertProvider(provider chat.AssistantAlertProvider) { m.Called(provider) }+func (m *MockAIService) SetFindingsProvider(provider chat.AssistantFindingsProvider) {+ m.Called(provider)+}+func (m *MockAIService) SetBaselineProvider(provider chat.AssistantBaselineProvider) {m.Called(provider)}-func (m *MockAIService) SetBackupProvider(provider chat.MCPBackupProvider) { m.Called(provider) }-func (m *MockAIService) SetGuestConfigProvider(provider chat.MCPGuestConfigProvider) {+func (m *MockAIService) SetPatternProvider(provider chat.AssistantPatternProvider) {m.Called(provider)}-func (m *MockAIService) SetAppContainerConfigProvider(provider chat.MCPAppContainerConfigProvider) {+func (m *MockAIService) SetMetricsHistory(provider chat.AssistantMetricsHistoryProvider) {m.Called(provider)}-func (m *MockAIService) SetDiskHealthProvider(provider chat.MCPDiskHealthProvider) {+func (m *MockAIService) SetBackupProvider(provider chat.AssistantBackupProvider) { m.Called(provider) }+func (m *MockAIService) SetGuestConfigProvider(provider chat.AssistantGuestConfigProvider) {+ m.Called(provider)+}+func (m *MockAIService) SetAppContainerConfigProvider(provider chat.AssistantAppContainerConfigProvider) {+ m.Called(provider)+}+func (m *MockAIService) SetDiskHealthProvider(provider chat.AssistantDiskHealthProvider) {+ m.Called(provider)+}+func (m *MockAIService) SetUpdatesProvider(provider chat.AssistantUpdatesProvider) {m.Called(provider)}-func (m *MockAIService) SetUpdatesProvider(provider chat.MCPUpdatesProvider) { m.Called(provider) }func (m *MockAIService) SetAgentProfileManager(manager chat.AgentProfileManager) {m.Called(manager)}@@ -215,16 +234,16 @@ func (m *MockAIService) SetIncidentRecorderProvider(provider chat.IncidentRecordfunc (m *MockAIService) SetEventCorrelatorProvider(provider chat.EventCorrelatorProvider) {m.Called(provider)}-func (m *MockAIService) SetDiscoveryProvider(provider chat.MCPDiscoveryProvider) {+func (m *MockAIService) SetDiscoveryProvider(provider chat.AssistantDiscoveryProvider) {m.Called(provider)}-func (m *MockAIService) SetUnifiedResourceProvider(provider chat.MCPUnifiedResourceProvider) {+func (m *MockAIService) SetUnifiedResourceProvider(provider chat.AssistantUnifiedResourceProvider) {m.Called(provider)}-func (m *MockAIService) SetAppContainerActionProvider(provider chat.MCPAppContainerActionProvider) {+func (m *MockAIService) SetAppContainerActionProvider(provider chat.AssistantAppContainerActionProvider) {m.Called(provider)}-func (m *MockAIService) SetAppContainerReadProvider(provider chat.MCPAppContainerReadProvider) {+func (m *MockAIService) SetAppContainerReadProvider(provider chat.AssistantAppContainerReadProvider) {m.Called(provider)}@@ -528,6 +547,74 @@ func TestHandleStatus(t *testing.T) {assert.Equal(t, "direct", resp["engine"])}+func TestHandleAssistantSurfaceTools_UsesRuntimeSurfaceContract(t *testing.T) {+ h := newTestAIHandler(&config.Config{}, nil, nil)+ mockSvc := new(MockAIService)+ h.defaultService = mockSvc++ want := agentcapabilities.SurfaceToolContract{+ SurfaceID: agentcapabilities.SurfaceIDPulseAssistant,+ SurfaceLabel: "Pulse Assistant",+ ToolSource: agentcapabilities.SurfaceToolSourceAssistantRegistry,+ ToolNames: []string{agentcapabilities.PulseQueryToolName, agentcapabilities.PulseQuestionToolName},+ RegistryToolNames: []string{agentcapabilities.PulseQueryToolName},+ NativeToolNames: []string{agentcapabilities.PulseQuestionToolName},+ Affordances: agentcapabilities.SurfaceAffordanceContract{+ Tools: true,+ InteractiveQuestions: true,+ },+ }+ mockSvc.On("IsRunning").Return(true)+ mockSvc.On("AssistantSurfaceToolContract", mock.Anything).Return(want)++ req := httptest.NewRequest(http.MethodGet, "/api/ai/assistant/surface-tools", nil)+ w := httptest.NewRecorder()++ h.HandleAssistantSurfaceTools(w, req)++ assert.Equal(t, http.StatusOK, w.Code)+ assert.Equal(t, "application/json", w.Header().Get("Content-Type"))++ var got agentcapabilities.SurfaceToolContract+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &got))+ assert.Equal(t, want.SurfaceID, got.SurfaceID)+ assert.Equal(t, want.ToolSource, got.ToolSource)+ assert.Equal(t, want.ToolNames, got.ToolNames)+ assert.Equal(t, want.RegistryToolNames, got.RegistryToolNames)+ assert.Equal(t, want.NativeToolNames, got.NativeToolNames)+ assert.Empty(t, got.CapabilityNames)+ assert.True(t, got.Affordances.InteractiveQuestions)+ mockSvc.AssertExpectations(t)+}++func TestHandleAssistantSurfaceTools_RequiresRunningAssistant(t *testing.T) {+ h := newTestAIHandler(&config.Config{}, nil, nil)+ mockSvc := new(MockAIService)+ h.defaultService = mockSvc+ mockSvc.On("IsRunning").Return(false)++ req := httptest.NewRequest(http.MethodGet, "/api/ai/assistant/surface-tools", nil)+ w := httptest.NewRecorder()++ h.HandleAssistantSurfaceTools(w, req)++ assert.Equal(t, http.StatusServiceUnavailable, w.Code)+ assert.Contains(t, w.Body.String(), "Pulse Assistant is not running")+ mockSvc.AssertExpectations(t)+ mockSvc.AssertNotCalled(t, "AssistantSurfaceToolContract", mock.Anything)+}++func TestHandleAssistantSurfaceTools_MethodNotAllowed(t *testing.T) {+ h := newTestAIHandler(&config.Config{}, nil, nil)++ req := httptest.NewRequest(http.MethodPost, "/api/ai/assistant/surface-tools", nil)+ w := httptest.NewRecorder()++ h.HandleAssistantSurfaceTools(w, req)++ assert.Equal(t, http.StatusMethodNotAllowed, w.Code)+}+func TestHandleSessions(t *testing.T) {cfg := &config.Config{}h := newTestAIHandler(cfg, nil, nil)@@ -740,6 +827,160 @@ func TestHandleChat_InvalidJSON(t *testing.T) {assert.Equal(t, http.StatusBadRequest, w.Code)}+func TestHandleRenderWorkflowPrompt_UsesSharedPulseIntelligenceRenderer(t *testing.T) {+ h := newTestAIHandler(&config.Config{}, nil, nil)++ body := fmt.Sprintf(+ `{"name":%q,"arguments":{"resourceId":"vm:101"}}`,+ agentcapabilities.PulseWorkflowPromptInvestigateResource,+ )+ req := httptest.NewRequest(http.MethodPost, "/api/ai/workflow-prompts/render", strings.NewReader(body))+ w := httptest.NewRecorder()++ h.HandleRenderWorkflowPrompt(w, req)++ assert.Equal(t, http.StatusOK, w.Code)+ assert.Equal(t, "application/json", w.Header().Get("Content-Type"))++ var got AssistantWorkflowPromptRenderResponse+ if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {+ t.Fatalf("unmarshal render response: %v", err)+ }+ assert.Equal(t, "Pulse resource investigation", got.Description)+ assert.Contains(t, got.Text, `Investigate Pulse resource "vm:101"`)+ assert.Contains(t, got.Text, "Use the Assistant's current Pulse context")+ assert.Contains(t, got.Text, "shared resource context capability")+}++func TestHandleRenderWorkflowPrompt_RecordsWorkflowPromptActivity(t *testing.T) {+ persistence := config.NewConfigPersistence(t.TempDir())+ h := newTestAIHandler(&config.Config{}, persistence, nil)++ body := fmt.Sprintf(`{"name":%q}`, agentcapabilities.PulseWorkflowPromptOperationsLoop)+ req := httptest.NewRequest(http.MethodPost, "/api/ai/workflow-prompts/render", strings.NewReader(body))+ w := httptest.NewRecorder()++ h.HandleRenderWorkflowPrompt(w, req)++ assert.Equal(t, http.StatusOK, w.Code)+ history, err := persistence.LoadWorkflowPromptActivityHistory()+ require.NoError(t, err)+ require.Len(t, history.Events, 1)+ assert.Equal(t, config.WorkflowPromptActivitySurfacePulseAssistant, history.Events[0].Surface)+ assert.Equal(t, agentcapabilities.PulseWorkflowPromptOperationsLoop, history.Events[0].PromptName)+}++func TestHandleRecordWorkflowPromptActivity_RecordsFirstPartyActivationStarter(t *testing.T) {+ for _, surface := range []string{+ config.WorkflowPromptActivitySurfacePulsePatrol,+ config.WorkflowPromptActivitySurfacePatrolControl,+ config.WorkflowPromptActivitySurfacePatrolAutonomy,+ config.WorkflowPromptActivitySurfaceProActivation,+ } {+ t.Run(surface, func(t *testing.T) {+ persistence := config.NewConfigPersistence(t.TempDir())+ h := newTestAIHandler(&config.Config{}, persistence, nil)++ body := fmt.Sprintf(+ `{"name":%q,"surface":%q}`,+ agentcapabilities.PulseWorkflowPromptOperationsLoop,+ surface,+ )+ req := httptest.NewRequest(http.MethodPost, "/api/ai/workflow-prompts/activity", strings.NewReader(body))+ w := httptest.NewRecorder()++ h.HandleRecordWorkflowPromptActivity(w, req)++ assert.Equal(t, http.StatusNoContent, w.Code)+ history, err := persistence.LoadWorkflowPromptActivityHistory()+ require.NoError(t, err)+ require.Len(t, history.Events, 1)+ assert.Equal(t, surface, history.Events[0].Surface)+ assert.Equal(t, agentcapabilities.PulseWorkflowPromptOperationsLoop, history.Events[0].PromptName)+ })+ }+}++func TestHandleRecordWorkflowPromptActivity_RejectsUnknownPrompt(t *testing.T) {+ h := newTestAIHandler(&config.Config{}, nil, nil)++ req := httptest.NewRequest(+ http.MethodPost,+ "/api/ai/workflow-prompts/activity",+ strings.NewReader(`{"name":"pulse_unknown","surface":"pulse_patrol"}`),+ )+ w := httptest.NewRecorder()++ h.HandleRecordWorkflowPromptActivity(w, req)++ assert.Equal(t, http.StatusBadRequest, w.Code)+ assert.Contains(t, w.Body.String(), "Unknown workflow prompt")+}++func TestHandleRecordWorkflowPromptActivity_RejectsExternalAgentSurfaces(t *testing.T) {+ h := newTestAIHandler(&config.Config{}, nil, nil)++ body := fmt.Sprintf(+ `{"name":%q,"surface":%q}`,+ agentcapabilities.PulseWorkflowPromptOperationsLoop,+ config.WorkflowPromptActivitySurfacePulseMCP,+ )+ req := httptest.NewRequest(http.MethodPost, "/api/ai/workflow-prompts/activity", strings.NewReader(body))+ w := httptest.NewRecorder()++ h.HandleRecordWorkflowPromptActivity(w, req)++ assert.Equal(t, http.StatusBadRequest, w.Code)+ assert.Contains(t, w.Body.String(), "Unknown workflow prompt surface")+}++func TestHandleRenderWorkflowPrompt_UsesManifestWorkflowPromptRenderer(t *testing.T) {+ source, err := os.ReadFile("ai_handler.go")+ require.NoError(t, err)++ text := string(source)+ assert.Contains(t, text, "agentcapabilities.BuildPulseWorkflowPromptFromManifestWithOptions(")+ assert.Contains(t, text, "manifest := agentcapabilities.CanonicalManifest()")+ assert.NotContains(t, text, "agentcapabilities.BuildPulseWorkflowPromptWithOptions(\n\t\tagentcapabilities.CanonicalManifest().Capabilities")+}++func TestHandleRenderWorkflowPrompt_ValidatesSharedPromptArguments(t *testing.T) {+ h := newTestAIHandler(&config.Config{}, nil, nil)++ body := fmt.Sprintf(`{"name":%q}`, agentcapabilities.PulseWorkflowPromptInvestigateResource)+ req := httptest.NewRequest(http.MethodPost, "/api/ai/workflow-prompts/render", strings.NewReader(body))+ w := httptest.NewRecorder()++ h.HandleRenderWorkflowPrompt(w, req)++ assert.Equal(t, http.StatusBadRequest, w.Code)+ assert.Contains(t, w.Body.String(), "prompt argument resourceId is required")+}++func TestHandleRenderWorkflowPrompt_RejectsUnknownSharedPrompt(t *testing.T) {+ h := newTestAIHandler(&config.Config{}, nil, nil)++ req := httptest.NewRequest(http.MethodPost, "/api/ai/workflow-prompts/render", strings.NewReader(`{"name":"pulse_unknown"}`))+ w := httptest.NewRecorder()++ h.HandleRenderWorkflowPrompt(w, req)++ assert.Equal(t, http.StatusBadRequest, w.Code)+ assert.Contains(t, w.Body.String(), "unknown prompt: pulse_unknown")+}++func TestHandleRenderWorkflowPrompt_RejectsInvalidJSON(t *testing.T) {+ h := newTestAIHandler(&config.Config{}, nil, nil)++ req := httptest.NewRequest(http.MethodPost, "/api/ai/workflow-prompts/render", strings.NewReader("invalid"))+ w := httptest.NewRecorder()++ h.HandleRenderWorkflowPrompt(w, req)++ assert.Equal(t, http.StatusBadRequest, w.Code)+ assert.Contains(t, w.Body.String(), "Invalid request")+}+func TestHandleChat_Success(t *testing.T) {cfg := &config.Config{}h := newTestAIHandler(cfg, nil, nil)diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.goindex 041b1510ad..9723e3a31f 100644--- a/internal/api/ai_handlers.go+++ b/internal/api/ai_handlers.go@@ -17,6 +17,7 @@ import ("sync/atomic""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/ai""github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"@@ -154,6 +155,10 @@ func (failClosedLicenseChecker) GetLicenseStateString() (string, bool) {return string(ai.LicenseStateNone), false}+type actionAuditStoreProvider interface {+ GetActionAuditStore() unifiedresources.ResourceStore+}+func (h *AISettingsHandler) providerSnapshot() aiSettingsProviderSnapshot {h.stateMu.RLock()defer h.stateMu.RUnlock()@@ -1749,7 +1754,7 @@ func aiSettingsUpdateTouchesPatrolReadiness(req AISettingsUpdateRequest) bool {}// SetOnControlSettingsChange sets a callback to be invoked when control settings change-// Used by Router to update MCP tool visibility without restarting AI chat+// Used by Router to update Assistant tool visibility without restarting AI chat.func (h *AISettingsHandler) SetOnControlSettingsChange(callback func()) {h.onControlSettingsChange = callback}@@ -2045,18 +2050,11 @@ func (a *orchestratorChatAdapter) GetMessages(ctx context.Context, sessionID strTimestamp: msg.Timestamp,}for _, tc := range msg.ToolCalls {- m.ToolCalls = append(m.ToolCalls, aicontracts.OrchestratorToolCallInfo{- ID: tc.ID,- Name: tc.Name,- Input: tc.Input,- })+ m.ToolCalls = append(m.ToolCalls, aicontracts.OrchestratorToolCallInfoFromProvider(tc.ProviderToolCall()))}if msg.ToolResult != nil {- m.ToolResult = &aicontracts.OrchestratorToolResultInfo{- ToolUseID: msg.ToolResult.ToolUseID,- Content: msg.ToolResult.Content,- IsError: msg.ToolResult.IsError,- }+ toolResult := aicontracts.OrchestratorToolResultInfoFromProvider(*msg.ToolResult)+ m.ToolResult = &toolResult}messages[i] = m.NormalizeCollections()}@@ -2264,9 +2262,9 @@ type AISettingsResponse struct {AutoFixModel string `json:"auto_fix_model,omitempty"` // Model for auto-fix (empty = use patrol model)Configured bool `json:"configured"` // true if AI is ready to useCustomContext string `json:"custom_context"` // user-provided infrastructure context- // OAuth fields for Claude Pro/Max subscription authentication- AuthMethod string `json:"auth_method"` // "api_key" or "oauth"- OAuthConnected bool `json:"oauth_connected"` // true if OAuth tokens are configured+ // Legacy OAuth fields are retained for cleanup/migration only.+ AuthMethod string `json:"auth_method"` // "api_key" or legacy "oauth"+ OAuthConnected bool `json:"oauth_connected"` // true if legacy OAuth tokens are stored// Patrol settings for token efficiencyPatrolIntervalMinutes int `json:"patrol_interval_minutes"` // Patrol interval in minutes (0 = disabled)PatrolEnabled bool `json:"patrol_enabled"` // true if patrol is enabled@@ -2281,7 +2279,7 @@ type AISettingsResponse struct {UseProactiveThresholds bool `json:"use_proactive_thresholds"` // true if patrol warns before thresholds (false = use exact thresholds)AvailableModels []providers.ModelInfo `json:"available_models"` // List of models for current provider// Multi-provider credentials - shows which providers are configured- AnthropicConfigured bool `json:"anthropic_configured"` // true if Anthropic API key or OAuth is set+ AnthropicConfigured bool `json:"anthropic_configured"` // true if Anthropic API key is setOpenAIConfigured bool `json:"openai_configured"` // true if OpenAI API key is setOpenRouterConfigured bool `json:"openrouter_configured"` // true if OpenRouter API key is setDeepSeekConfigured bool `json:"deepseek_configured"` // true if DeepSeek API key is set@@ -2457,8 +2455,8 @@ func (h *AISettingsHandler) HandleGetAISettings(w http.ResponseWriter, r *http.Rctx := r.Context()settings, err := h.loadAIConfig(ctx)if err != nil {- log.Error().Err(err).Msg("Failed to load Pulse Assistant settings")- http.Error(w, "Failed to load Pulse Assistant settings", http.StatusInternalServerError)+ log.Error().Err(err).Msg("Failed to load Assistant & Patrol settings")+ http.Error(w, "Failed to load Assistant & Patrol settings", http.StatusInternalServerError)return}@@ -2608,9 +2606,9 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *htt}if req.PatrolAutoFix != nil {- // Safe remediation requires Pro license with the ai_autofix feature.+ // Patrol fix actions require Pro license with the ai_autofix feature.if *req.PatrolAutoFix && !h.GetAIService(r.Context()).HasLicenseFeature(ai.FeatureAIAutoFix) {- WriteLicenseRequired(w, ai.FeatureAIAutoFix, "Safe remediation workflows require Pulse Pro")+ WriteLicenseRequired(w, ai.FeatureAIAutoFix, "Patrol fix actions require Pulse Pro")return}settings.PatrolAutoFix = *req.PatrolAutoFix@@ -2908,8 +2906,8 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *htth.onModelChange()}- // Update MCP control settings if control level or protected guests changed- // This updates tool visibility without restarting AI chat+ // Update Assistant control settings if control level or protected guests changed.+ // This updates tool visibility without restarting AI chat.if h.onControlSettingsChange != nil && (req.ControlLevel != nil || req.ProtectedGuests != nil) {h.onControlSettingsChange()}@@ -3329,21 +3327,11 @@ type AIExecuteRequest struct {}func normalizeAIExecuteTargetType(raw string) string {- return strings.ToLower(strings.TrimSpace(raw))+ return agentcapabilities.NormalizeActionTargetType(raw)}func normalizeAndValidateAIExecuteTargetType(raw string) (string, error) {- targetType := normalizeAIExecuteTargetType(raw)- if targetType == "" {- return "", nil- }-- switch targetType {- case "agent", "system-container", "vm":- return targetType, nil- default:- return "", fmt.Errorf("invalid target_type")- }+ return agentcapabilities.NormalizeAndValidateOptionalActionTargetType(raw)}// AIExecuteResponse is the response from POST /api/ai/execute@@ -3606,7 +3594,7 @@ func (h *AISettingsHandler) HandleExecute(w http.ResponseWriter, r *http.RequestuseCase := strings.ToLower(strings.TrimSpace(req.UseCase))if useCase == "autofix" || useCase == "remediation" {if !h.GetAIService(r.Context()).HasLicenseFeature(ai.FeatureAIAutoFix) {- WriteLicenseRequired(w, ai.FeatureAIAutoFix, "Safe remediation workflows require Pulse Pro")+ WriteLicenseRequired(w, ai.FeatureAIAutoFix, "Patrol fix actions require Pulse Pro")return}}@@ -3787,7 +3775,7 @@ func (h *AISettingsHandler) HandleExecuteStream(w http.ResponseWriter, r *http.RuseCase := strings.ToLower(strings.TrimSpace(req.UseCase))if useCase == "autofix" || useCase == "remediation" {if !h.GetAIService(r.Context()).HasLicenseFeature(ai.FeatureAIAutoFix) {- WriteLicenseRequired(w, ai.FeatureAIAutoFix, "Safe remediation workflows require Pulse Pro")+ WriteLicenseRequired(w, ai.FeatureAIAutoFix, "Patrol fix actions require Pulse Pro")return}}@@ -4005,10 +3993,10 @@ func (h *AISettingsHandler) HandleRunCommand(w http.ResponseWriter, r *http.Requreturn}- // Gated for safe remediation workflows (Pro feature). Request shape is validated before the+ // Gated for Patrol fix actions (Pro feature). Request shape is validated before the// entitlement check so clients get deterministic 400s for malformed calls.if !h.GetAIService(r.Context()).HasLicenseFeature(ai.FeatureAIAutoFix) {- WriteLicenseRequired(w, ai.FeatureAIAutoFix, "Safe remediation workflows require Pulse Pro")+ WriteLicenseRequired(w, ai.FeatureAIAutoFix, "Patrol fix actions require Pulse Pro")return}@@ -4069,14 +4057,8 @@ func normalizeRunCommandApprovalTarget(req AIRunCommandRequest) (string, string,targetID := strings.TrimSpace(req.TargetID)targetHost := strings.ToLower(strings.TrimSpace(req.TargetHost))- allowedTargetTypes := map[string]struct{}{- "agent": {},- "system-container": {},- "vm": {},- }-if req.RunOnHost {- targetType = "agent"+ targetType = agentcapabilities.ActionTargetTypeAgentif targetHost == "" {return "", "", errors.New("target_host is required when run_on_host is true")}@@ -4084,17 +4066,17 @@ func normalizeRunCommandApprovalTarget(req AIRunCommandRequest) (string, string,}if targetType == "" {- targetType = "agent"+ targetType = agentcapabilities.ActionTargetTypeAgent}- if _, ok := allowedTargetTypes[targetType]; !ok {- return "", "", fmt.Errorf("unsupported target_type %q (allowed: agent, system-container, vm)", targetType)+ if !agentcapabilities.IsActionTargetType(targetType) {+ return "", "", fmt.Errorf("unsupported target_type %q (allowed: %s)", targetType, agentcapabilities.ActionTargetTypeAllowedDescription())}- if (targetType == "system-container" || targetType == "vm") && strings.TrimSpace(req.VMID) != "" {+ if (targetType == agentcapabilities.ActionTargetTypeSystemContainer || targetType == agentcapabilities.ActionTargetTypeVM) && strings.TrimSpace(req.VMID) != "" {targetID = strings.TrimSpace(req.VMID)}- if targetType == "agent" {+ if targetType == agentcapabilities.ActionTargetTypeAgent {if targetID == "" {targetID = targetHost}@@ -4546,19 +4528,7 @@ func (r AIInvestigateAlertRequest) alertIdentifier() string {}func normalizeInvestigateAlertTargetType(raw string) (string, error) {- resourceType := normalizeAITransportResourceType(raw)- switch resourceType {- case "vm":- return "vm", nil- case "system-container", "oci-container":- return "system-container", nil- case "agent", "node", "docker-host", "app-container", "pod", "k8s-node", "k8s-cluster", "k8s-deployment", "k8s-service", "storage", "disk", "pbs", "pmg", "proxmox", "ceph":- return "agent", nil- case "":- return "", errors.New("resource_type is required")- default:- return "", fmt.Errorf("unsupported resource_type %q (allowed: vm, system-container, oci-container, app-container, pod, agent, node, docker-host, k8s-cluster, k8s-node, k8s-deployment, k8s-service, storage, disk, pbs, pmg, proxmox, ceph)", raw)- }+ return agentcapabilities.ActionTargetTypeForResourceType(raw)}// HandleInvestigateAlert investigates an alert using AI (POST /api/ai/investigate-alert)@@ -4774,336 +4744,55 @@ func (h *AISettingsHandler) SetAlertResolver(resolver ai.AlertResolver) {}}-// oauthSessions stores active OAuth sessions (state -> session)-// In production, consider using a more robust session store with expiry-type oauthSessionBinding struct {- session *providers.OAuthSession- orgID string-}--const oauthSessionTTL = 15 * time.Minute--var oauthSessions = make(map[string]*oauthSessionBinding)-var oauthSessionsMu sync.Mutex-var exchangeOAuthCodeForTokens = providers.ExchangeCodeForTokens-var createAPIKeyFromOAuth = providers.CreateAPIKeyFromOAuth--func storeOAuthSession(session *providers.OAuthSession, orgID string) {- oauthSessionsMu.Lock()- defer oauthSessionsMu.Unlock()-- cutoff := time.Now().Add(-oauthSessionTTL)- for state, binding := range oauthSessions {- if binding == nil || binding.session == nil || binding.session.CreatedAt.Before(cutoff) {- delete(oauthSessions, state)- }- }-- oauthSessions[session.State] = &oauthSessionBinding{- session: session,- orgID: orgID,- }-}+const unsupportedAnthropicOAuthMessage = "Anthropic subscription OAuth is not supported by Pulse Assistant. Configure an Anthropic API key or another supported provider."-func consumeOAuthSession(state string) (*oauthSessionBinding, bool) {- oauthSessionsMu.Lock()- binding, ok := oauthSessions[state]- if ok {- delete(oauthSessions, state) // One-time use- }- oauthSessionsMu.Unlock()-- if !ok || binding == nil || binding.session == nil {- return nil, false- }- if time.Since(binding.session.CreatedAt) > oauthSessionTTL {- return nil, false- }- if !isValidOrganizationID(binding.orgID) {- return nil, false+func writeAnthropicOAuthUnsupported(w http.ResponseWriter) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusNotImplemented)+ if err := utils.WriteJSONResponse(w, map[string]interface{}{+ "success": false,+ "error": "unsupported_anthropic_oauth",+ "message": unsupportedAnthropicOAuthMessage,+ }); err != nil {+ log.Error().Err(err).Msg("Failed to write unsupported Anthropic OAuth response")}-- return binding, true}-// HandleOAuthStart initiates the OAuth flow for Claude Pro/Max subscription (POST /api/ai/oauth/start)-// Returns an authorization URL for the user to visit manually+// HandleOAuthStart rejects legacy Anthropic subscription OAuth setup.func (h *AISettingsHandler) HandleOAuthStart(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet && r.Method != http.MethodPost {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return}- // Generate OAuth session (redirect URI is not used since we use Anthropic's callback)- session, err := providers.GenerateOAuthSession("")- if err != nil {- log.Error().Err(err).Msg("Failed to generate OAuth session")- http.Error(w, "Failed to start OAuth flow", http.StatusInternalServerError)- return- }-- orgID := strings.TrimSpace(GetOrgID(r.Context()))- if !isValidOrganizationID(orgID) {- orgID = "default"- }-- // Store session, bound to the tenant context that initiated OAuth.- storeOAuthSession(session, orgID)-- // Get authorization URL- authURL := providers.GetAuthorizationURL(session)-- log.Info().- Str("state", safePrefixForLog(session.State, 8)+"...").- Str("org_id", orgID).- Str("verifier_len", fmt.Sprintf("%d", len(session.CodeVerifier))).- Str("auth_url", authURL).- Msg("Starting Claude OAuth flow - user must visit URL and paste code back")-- // Return the URL for the user to visit- response := map[string]string{- "auth_url": authURL,- "state": session.State,- }-- if err := utils.WriteJSONResponse(w, response); err != nil {- log.Error().Err(err).Msg("Failed to write OAuth start response")- }+ writeAnthropicOAuthUnsupported(w)}-// HandleOAuthExchange exchanges a manually-pasted authorization code for tokens (POST /api/ai/oauth/exchange)+// HandleOAuthExchange rejects legacy Anthropic subscription OAuth setup.func (h *AISettingsHandler) HandleOAuthExchange(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodPost {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return}- // Limit body size — OAuth codes are short strings, 4 KB is plenty.- r.Body = http.MaxBytesReader(w, r.Body, 4*1024)-- // Parse request body- var req struct {- Code string `json:"code"`- State string `json:"state"`- }- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- http.Error(w, "Invalid request body", http.StatusBadRequest)- return- }-- if req.Code == "" || req.State == "" {- http.Error(w, "Missing code or state", http.StatusBadRequest)- return- }-- // Trim any whitespace from the code (user might have copied extra spaces)- code := strings.TrimSpace(req.Code)-- // Anthropic's callback page displays the code as "code#state"- // We need to extract just the code part before the #- if idx := strings.Index(code, "#"); idx > 0 {- code = code[:idx]- }-- log.Debug().- Str("code_len", fmt.Sprintf("%d", len(code))).- Str("code_prefix", code[:min(20, len(code))]).- Str("state_prefix", req.State[:min(8, len(req.State))]).- Msg("Processing OAuth code exchange")-- // Consume one-time OAuth session and enforce TTL.- binding, ok := consumeOAuthSession(req.State)-- if !ok {- log.Error().Str("state", req.State[:min(8, len(req.State))]+"...").Msg("OAuth exchange with unknown state")- http.Error(w, "Invalid or expired session. Please start the OAuth flow again.", http.StatusBadRequest)- return- }- orgID := binding.orgID- oauthCtx := context.WithValue(r.Context(), OrgIDContextKey, orgID)-- // Exchange code for tokens- ctx, cancel := context.WithTimeout(oauthCtx, 30*time.Second)- defer cancel()-- tokens, err := exchangeOAuthCodeForTokens(ctx, code, binding.session)- if err != nil {- log.Error().Err(err).Msg("Failed to exchange OAuth code for tokens")- http.Error(w, "Failed to exchange authorization code", http.StatusBadRequest)- return- }-- // Try to create an API key from the OAuth access token- // Team/Enterprise users get org:create_api_key scope and can create API keys- // Pro/Max users don't have this scope and will use OAuth tokens directly- apiKey, err := createAPIKeyFromOAuth(ctx, tokens.AccessToken)- if err != nil {- // Check if it's a permission error (Pro/Max users)- if strings.Contains(err.Error(), "org:create_api_key") || strings.Contains(err.Error(), "403") {- log.Info().Msg("User doesn't have org:create_api_key permission - will use OAuth tokens directly")- // This is fine for Pro/Max users - they'll use OAuth tokens- } else {- log.Error().Err(err).Msg("Failed to create API key from OAuth token")- http.Error(w, "Failed to create API key", http.StatusBadRequest)- return- }- }-- if apiKey != "" {- log.Info().Msg("Successfully created API key from OAuth - using subscription-based billing")- }-- // Load existing settings- persistence := h.getPersistence(oauthCtx)- if persistence == nil {- http.Error(w, "Tenant persistence unavailable", http.StatusInternalServerError)- return- }- settings, err := h.loadAIConfig(oauthCtx)- if err != nil {- log.Error().Err(err).Msg("Failed to load Pulse Assistant settings for OAuth")- settings = config.NewDefaultAIConfig()- }- if settings == nil {- settings = config.NewDefaultAIConfig()- }-- // Update settings- settings.AuthMethod = config.AuthMethodOAuth- settings.OAuthAccessToken = tokens.AccessToken- settings.OAuthRefreshToken = tokens.RefreshToken- settings.OAuthExpiresAt = tokens.ExpiresAt- settings.Enabled = true-- // If we got an API key, use it; otherwise use OAuth tokens directly- if apiKey != "" {- settings.AnthropicAPIKey = apiKey- } else {- // Pro/Max users: clear any old API key, will use OAuth client- settings.ClearAPIKey()- }-- // Save settings- if err := persistence.SaveAIConfig(*settings); err != nil {- log.Error().Err(err).Msg("Failed to save OAuth tokens")- http.Error(w, "Failed to save OAuth credentials", http.StatusInternalServerError)- return- }-- // Reload the AI service with new settings- if svc := h.GetAIService(oauthCtx); svc != nil {- if err := svc.Reload(); err != nil {- log.Warn().Err(err).Msg("Failed to reload AI service after OAuth setup")- }- }-- log.Info().Msg("Claude OAuth authentication successful")-- response := map[string]interface{}{- "success": true,- "message": "Successfully connected to Claude with your subscription",- }-- if err := utils.WriteJSONResponse(w, response); err != nil {- log.Error().Err(err).Msg("Failed to write OAuth exchange response")- }+ writeAnthropicOAuthUnsupported(w)}-// HandleOAuthCallback handles the OAuth callback (GET /api/ai/oauth/callback)-// This is kept for backwards compatibility but mainly serves as a fallback+// HandleOAuthCallback rejects stale legacy OAuth redirects without saving tokens.func (h *AISettingsHandler) HandleOAuthCallback(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return}- // Get code and state from query params- code := r.URL.Query().Get("code")- state := r.URL.Query().Get("state")errParam := r.URL.Query().Get("error")- errDesc := r.URL.Query().Get("error_description")-- // Check for OAuth errorif errParam != "" {- log.Error().- Str("error", errParam).- Str("description", errDesc).- Msg("OAuth authorization failed")- // Redirect to settings page with error (URL-encode to prevent injection)+ log.Info().Str("error", errParam).Msg("Unsupported Anthropic OAuth callback returned provider error")http.Redirect(w, r, "/settings?ai_oauth_error="+url.QueryEscape(errParam), http.StatusTemporaryRedirect)return}- if code == "" || state == "" {- log.Error().Msg("OAuth callback missing code or state")- http.Redirect(w, r, "/settings?ai_oauth_error=missing_params", http.StatusTemporaryRedirect)- return- }-- // Consume one-time OAuth session and enforce TTL.- binding, ok := consumeOAuthSession(state)-- if !ok {- log.Error().Str("state", state).Msg("OAuth callback with unknown state")- http.Redirect(w, r, "/settings?ai_oauth_error=invalid_state", http.StatusTemporaryRedirect)- return- }- orgID := binding.orgID- oauthCtx := context.WithValue(r.Context(), OrgIDContextKey, orgID)-- // Exchange code for tokens- ctx, cancel := context.WithTimeout(oauthCtx, 30*time.Second)- defer cancel()-- tokens, err := exchangeOAuthCodeForTokens(ctx, code, binding.session)- if err != nil {- log.Error().Err(err).Msg("Failed to exchange OAuth code for tokens")- http.Redirect(w, r, "/settings?ai_oauth_error=token_exchange_failed", http.StatusTemporaryRedirect)- return- }-- // Load existing settings- persistence := h.getPersistence(oauthCtx)- if persistence == nil {- http.Redirect(w, r, "/settings?ai_oauth_error=save_failed", http.StatusTemporaryRedirect)- return- }- settings, err := h.loadAIConfig(oauthCtx)- if err != nil {- log.Error().Err(err).Msg("Failed to load Pulse Assistant settings for OAuth")- settings = config.NewDefaultAIConfig()- }- if settings == nil {- settings = config.NewDefaultAIConfig()- }-- // Update settings with OAuth tokens- settings.AuthMethod = config.AuthMethodOAuth- settings.OAuthAccessToken = tokens.AccessToken- settings.OAuthRefreshToken = tokens.RefreshToken- settings.OAuthExpiresAt = tokens.ExpiresAt- settings.Enabled = true- // Clear API key since we're using OAuth- settings.ClearAPIKey()-- // Save settings- if err := persistence.SaveAIConfig(*settings); err != nil {- log.Error().Err(err).Msg("Failed to save OAuth tokens")- http.Redirect(w, r, "/settings?ai_oauth_error=save_failed", http.StatusTemporaryRedirect)- return- }-- // Reload the AI service with new settings- if svc := h.GetAIService(oauthCtx); svc != nil {- if err := svc.Reload(); err != nil {- log.Warn().Err(err).Msg("Failed to reload AI service after OAuth setup")- }- }-- log.Info().Msg("Claude OAuth authentication successful")-- // Redirect to settings page with success- http.Redirect(w, r, "/settings?ai_oauth_success=true", http.StatusTemporaryRedirect)+ http.Redirect(w, r, "/settings?ai_oauth_error=unsupported", http.StatusTemporaryRedirect)}// HandleOAuthDisconnect disconnects OAuth and clears tokens (POST /api/ai/oauth/disconnect)@@ -5127,7 +4816,7 @@ func (h *AISettingsHandler) HandleOAuthDisconnect(w http.ResponseWriter, r *http}settings, err := h.loadAIConfig(r.Context())if err != nil {- log.Error().Err(err).Msg("Failed to load Pulse Assistant settings for OAuth disconnect")+ log.Error().Err(err).Msg("Failed to load Assistant & Patrol settings for OAuth disconnect")http.Error(w, "Failed to load settings", http.StatusInternalServerError)return}@@ -5153,7 +4842,7 @@ func (h *AISettingsHandler) HandleOAuthDisconnect(w http.ResponseWriter, r *http}}- log.Info().Msg("Claude OAuth disconnected")+ log.Info().Msg("Legacy Anthropic OAuth disconnected")response := map[string]interface{}{"success": true,@@ -5244,7 +4933,7 @@ func (h *AISettingsHandler) buildPatrolReadiness(ctx context.Context, aiService}if aiService == nil {- addCheck("service", patrolReadinessNotReady, ai.PatrolFailureCauseServiceUnavailable, "AI runtime service", "Pulse AI runtime service is not available.", "restart_service")+ addCheck("service", patrolReadinessNotReady, ai.PatrolFailureCauseServiceUnavailable, "Assistant runtime service", "Pulse Assistant runtime service is not available.", "restart_service")return summarizePatrolReadiness("", "", checks)}if !patrolAvailable {@@ -5255,10 +4944,10 @@ func (h *AISettingsHandler) buildPatrolReadiness(ctx context.Context, aiServicecfg, err := h.loadAIConfig(ctx)if err != nil || cfg == nil {- addCheck("settings", patrolReadinessNotReady, ai.PatrolFailureCauseSettingsPersistence, "Settings persistence", "Pulse Assistant settings could not be loaded from persistence.", "open_provider_settings")+ addCheck("settings", patrolReadinessNotReady, ai.PatrolFailureCauseSettingsPersistence, "Settings persistence", "Assistant & Patrol settings could not be loaded from persistence.", "open_provider_settings")return summarizePatrolReadiness("", "", checks)}- addCheck("settings", patrolReadinessReady, ai.PatrolFailureCauseNone, "Settings persistence", "Pulse Assistant and Patrol settings are readable.", "")+ addCheck("settings", patrolReadinessReady, ai.PatrolFailureCauseNone, "Settings persistence", "Assistant & Patrol settings are readable.", "")if !cfg.Enabled {addCheck("enabled", patrolReadinessNotReady, ai.PatrolFailureCauseAssistantDisabled, "Assistant enabled", "Pulse Assistant is disabled, so Patrol cannot run model-backed verification.", "open_provider_settings")@@ -5412,7 +5101,7 @@ func patrolReadinessResponseFromConfigReadiness(readiness ai.PatrolConfigReadineID: "configuration",Status: readiness.Status,Cause: cause,- Label: "Patrol configuration",+ Label: "Patrol control",Message: readiness.Summary,Action: action,},@@ -5436,6 +5125,22 @@ func writePatrolServiceUnavailableResponse(w http.ResponseWriter) {writeErrorResponse(w, http.StatusServiceUnavailable, "service_unavailable", "Pulse Patrol service not available", nil)}+func writePatrolAgentUnavailableResponse(w http.ResponseWriter) {+ writeJSONError(w, http.StatusServiceUnavailable, agentcapabilities.AgentErrCodePatrolUnavailable, "Pulse Patrol service not available")+}++func writeFindingInvalidRequestResponse(w http.ResponseWriter, message string, details map[string]string) {+ writeJSONErrorWithDetails(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeInvalidFindingRequest, message, details)+}++func writeFindingNotFoundResponse(w http.ResponseWriter, message string) {+ writeJSONError(w, http.StatusNotFound, agentcapabilities.AgentErrCodeFindingNotFound, message)+}++func writeFindingActionNotAllowedResponse(w http.ResponseWriter, message string) {+ writeJSONError(w, http.StatusConflict, agentcapabilities.AgentErrCodeFindingActionNotAllowed, message)+}+func writePatrolReadinessNotReadyResponse(w http.ResponseWriter, statusCode int, readiness ai.PatrolConfigReadiness) {details := map[string]string{"status": readiness.Status}if cause := patrolFailureCauseResponse(readiness.Cause); cause != "" {@@ -5984,7 +5689,7 @@ func (h *AISettingsHandler) HandleAcknowledgeFinding(w http.ResponseWriter, r *hpatrol := h.getPatrolService(r.Context())if patrol == nil {- writePatrolServiceUnavailableResponse(w)+ writePatrolAgentUnavailableResponse(w)return}@@ -5992,12 +5697,12 @@ func (h *AISettingsHandler) HandleAcknowledgeFinding(w http.ResponseWriter, r *hFindingID string `json:"finding_id"`}if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- http.Error(w, "Invalid request body", http.StatusBadRequest)+ writeFindingInvalidRequestResponse(w, "Invalid request body", nil)return}if req.FindingID == "" {- http.Error(w, "finding_id is required", http.StatusBadRequest)+ writeFindingInvalidRequestResponse(w, "finding_id is required", map[string]string{"finding_id": "required"})return}@@ -6029,16 +5734,16 @@ func (h *AISettingsHandler) HandleAcknowledgeFinding(w http.ResponseWriter, r *hresourceID = unifiedFinding.ResourceIDfindingKey = unifiedFinding.ID} else {- http.Error(w, "Finding not found", http.StatusNotFound)+ writeFindingNotFoundResponse(w, "Finding not found")return}} else if !foundInPatrol {- http.Error(w, "Finding not found", http.StatusNotFound)+ writeFindingNotFoundResponse(w, "Finding not found")return}if foundInPatrol {if err := patrol.RejectManualActionForRuntimeFinding(req.FindingID, "acknowledged"); err != nil {- http.Error(w, err.Error(), http.StatusConflict)+ writeFindingActionNotAllowedResponse(w, err.Error())return}}@@ -6046,7 +5751,7 @@ func (h *AISettingsHandler) HandleAcknowledgeFinding(w http.ResponseWriter, r *h// Acknowledge in patrol findings if it exists thereif foundInPatrol {if !findings.Acknowledge(req.FindingID) {- http.Error(w, "Finding not found", http.StatusNotFound)+ writeFindingNotFoundResponse(w, "Finding not found")return}}@@ -6098,7 +5803,7 @@ func (h *AISettingsHandler) HandleSnoozeFinding(w http.ResponseWriter, r *http.Rpatrol := h.getPatrolService(r.Context())if patrol == nil {- writePatrolServiceUnavailableResponse(w)+ writePatrolAgentUnavailableResponse(w)return}@@ -6107,17 +5812,17 @@ func (h *AISettingsHandler) HandleSnoozeFinding(w http.ResponseWriter, r *http.RDurationHours int `json:"duration_hours"`}if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- http.Error(w, "Invalid request body", http.StatusBadRequest)+ writeFindingInvalidRequestResponse(w, "Invalid request body", nil)return}if req.FindingID == "" {- http.Error(w, "finding_id is required", http.StatusBadRequest)+ writeFindingInvalidRequestResponse(w, "finding_id is required", map[string]string{"finding_id": "required"})return}if req.DurationHours <= 0 {- http.Error(w, "duration_hours must be positive", http.StatusBadRequest)+ writeFindingInvalidRequestResponse(w, "duration_hours must be positive", map[string]string{"duration_hours": "must be positive"})return}@@ -6155,16 +5860,16 @@ func (h *AISettingsHandler) HandleSnoozeFinding(w http.ResponseWriter, r *http.RresourceID = unifiedFinding.ResourceIDfindingKey = unifiedFinding.ID} else {- http.Error(w, "Finding not found or already resolved", http.StatusNotFound)+ writeFindingNotFoundResponse(w, "Finding not found or already resolved")return}} else if !foundInPatrol {- http.Error(w, "Finding not found or already resolved", http.StatusNotFound)+ writeFindingNotFoundResponse(w, "Finding not found or already resolved")return}if foundInPatrol {if err := patrol.RejectManualActionForRuntimeFinding(req.FindingID, "snoozed"); err != nil {- http.Error(w, err.Error(), http.StatusConflict)+ writeFindingActionNotAllowedResponse(w, err.Error())return}}@@ -6172,7 +5877,7 @@ func (h *AISettingsHandler) HandleSnoozeFinding(w http.ResponseWriter, r *http.R// Snooze in patrol findings if it exists thereif foundInPatrol {if !findings.Snooze(req.FindingID, duration) {- http.Error(w, "Finding not found or already resolved", http.StatusNotFound)+ writeFindingNotFoundResponse(w, "Finding not found or already resolved")return}}@@ -6225,20 +5930,23 @@ func (h *AISettingsHandler) HandleResolveFinding(w http.ResponseWriter, r *http.patrol := h.getPatrolService(r.Context())if patrol == nil {- writePatrolServiceUnavailableResponse(w)+ writePatrolAgentUnavailableResponse(w)return}var req struct {- FindingID string `json:"finding_id"`+ FindingID string `json:"finding_id"`+ ResolutionNote string `json:"resolution_note"`}if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- http.Error(w, "Invalid request body", http.StatusBadRequest)+ writeFindingInvalidRequestResponse(w, "Invalid request body", nil)return}+ req.ResolutionNote = strings.TrimSpace(req.ResolutionNote)+if req.FindingID == "" {- http.Error(w, "finding_id is required", http.StatusBadRequest)+ writeFindingInvalidRequestResponse(w, "finding_id is required", map[string]string{"finding_id": "required"})return}@@ -6247,13 +5955,16 @@ func (h *AISettingsHandler) HandleResolveFinding(w http.ResponseWriter, r *http.// Get finding details before resolving (for learning/analytics)finding := findings.Get(req.FindingID)if finding == nil {- http.Error(w, "Finding not found or already resolved", http.StatusNotFound)+ writeFindingNotFoundResponse(w, "Finding not found or already resolved")return}if err := patrol.RejectManualActionForRuntimeFinding(req.FindingID, "resolved"); err != nil {- http.Error(w, err.Error(), http.StatusConflict)+ writeFindingActionNotAllowedResponse(w, err.Error())return}+ if req.ResolutionNote != "" {+ findings.SetUserNote(req.FindingID, req.ResolutionNote)+ }// Capture details before actiondetectedAt := finding.DetectedAt@@ -6263,7 +5974,7 @@ func (h *AISettingsHandler) HandleResolveFinding(w http.ResponseWriter, r *http.// Mark as manually resolved (auto=false since user did it)if !findings.Resolve(req.FindingID, false) {- http.Error(w, "Finding not found or already resolved", http.StatusNotFound)+ writeFindingNotFoundResponse(w, "Finding not found or already resolved")return}@@ -6282,6 +5993,7 @@ func (h *AISettingsHandler) HandleResolveFinding(w http.ResponseWriter, r *http.Severity: severity,Action: learning.ActionQuickFix, // Manual resolve means user took action to fixTimeToAction: time.Since(detectedAt),+ UserNote: req.ResolutionNote,})}@@ -6369,7 +6081,7 @@ func (h *AISettingsHandler) HandleDismissFinding(w http.ResponseWriter, r *http.patrol := h.getPatrolService(r.Context())if patrol == nil {- writePatrolServiceUnavailableResponse(w)+ writePatrolAgentUnavailableResponse(w)return}@@ -6379,17 +6091,17 @@ func (h *AISettingsHandler) HandleDismissFinding(w http.ResponseWriter, r *http.Note string `json:"note"` // Optional freeform note}if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- http.Error(w, "Invalid request body", http.StatusBadRequest)+ writeFindingInvalidRequestResponse(w, "Invalid request body", nil)return}if req.FindingID == "" {- http.Error(w, "finding_id is required", http.StatusBadRequest)+ writeFindingInvalidRequestResponse(w, "finding_id is required", map[string]string{"finding_id": "required"})return}if req.Reason == "" {- http.Error(w, "reason is required", http.StatusBadRequest)+ writeFindingInvalidRequestResponse(w, "reason is required", map[string]string{"reason": "required"})return}@@ -6400,7 +6112,7 @@ func (h *AISettingsHandler) HandleDismissFinding(w http.ResponseWriter, r *http."will_fix_later": true,}if req.Reason != "" && !validReasons[req.Reason] {- http.Error(w, "Invalid reason. Valid values: not_an_issue, expected_behavior, will_fix_later", http.StatusBadRequest)+ writeFindingInvalidRequestResponse(w, "Invalid reason. Valid values: not_an_issue, expected_behavior, will_fix_later", map[string]string{"reason": "must be one of not_an_issue, expected_behavior, will_fix_later"})return}@@ -6432,16 +6144,16 @@ func (h *AISettingsHandler) HandleDismissFinding(w http.ResponseWriter, r *http.resourceID = unifiedFinding.ResourceIDfindingKey = unifiedFinding.ID // Use ID as key for unified findings} else {- http.Error(w, "Finding not found", http.StatusNotFound)+ writeFindingNotFoundResponse(w, "Finding not found")return}} else if !foundInPatrol {- http.Error(w, "Finding not found", http.StatusNotFound)+ writeFindingNotFoundResponse(w, "Finding not found")return}if foundInPatrol {if err := patrol.RejectManualActionForRuntimeFinding(req.FindingID, "dismissed"); err != nil {- http.Error(w, err.Error(), http.StatusConflict)+ writeFindingActionNotAllowedResponse(w, err.Error())return}}@@ -6449,7 +6161,7 @@ func (h *AISettingsHandler) HandleDismissFinding(w http.ResponseWriter, r *http.// Dismiss in patrol findings if it exists thereif foundInPatrol {if !findings.Dismiss(req.FindingID, req.Reason, req.Note) {- http.Error(w, "Finding not found", http.StatusNotFound)+ writeFindingNotFoundResponse(w, "Finding not found")return}}@@ -7297,7 +7009,7 @@ func (h *AISettingsHandler) HandleApproveCommand(w http.ResponseWriter, r *http.if h.aiAutoFixEndpoints != nil {h.aiAutoFixEndpoints.HandleApproveInvestigationFix(w, r)} else {- WriteLicenseRequired(w, featureAIAutoFixValue, "Safe remediation workflows require Pulse Pro")+ WriteLicenseRequired(w, featureAIAutoFixValue, "Patrol fix actions require Pulse Pro")}return}@@ -7334,9 +7046,8 @@ func (h *AISettingsHandler) HandleApproveCommand(w http.ResponseWriter, r *http.// executeInvestigationFix has been moved to enterprise.-// isMCPToolCall, cleanTargetHost, executeMCPToolFix, parseMCPToolCall,-// splitToolArgs, and findAgentForTarget have been moved to-// router_routes_ai_relay.go as package-level functions used by the+// cleanTargetHost and the agent command/tool executor adapters have been+// moved to router_routes_ai_relay.go as package-level helpers used by the// AIAutoFixHandlerDeps adapters.// updateFindingOutcome updates the investigation outcome on a finding@@ -7368,6 +7079,24 @@ func (h *AISettingsHandler) updateFindingOutcome(ctx context.Context, orgID, finlog.Info().Str("findingID", findingID).Str("outcome", outcome).Msg("Updated finding investigation outcome")}+func (h *AISettingsHandler) actionAuditStoreForApprovalDecision(ctx context.Context) unifiedresources.ResourceStore {+ if h == nil {+ return nil+ }+ h.stateMu.RLock()+ chatHandler := h.chatHandler+ h.stateMu.RUnlock()+ if chatHandler == nil {+ return nil+ }+ service := chatHandler.GetService(ctx)+ provider, ok := service.(actionAuditStoreProvider)+ if !ok {+ return nil+ }+ return provider.GetActionAuditStore()+}+// HandleDenyCommand denies a pending command.func (h *AISettingsHandler) HandleDenyCommand(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodPost {@@ -7420,6 +7149,20 @@ func (h *AISettingsHandler) HandleDenyCommand(w http.ResponseWriter, r *http.ReqwriteErrorResponse(w, http.StatusBadRequest, "denial_failed", err.Error(), nil)return}+ reason := strings.TrimSpace(body.Reason)+ if reason == "" {+ reason = "approval denied"+ }+ tools.RecordApprovalDecision(+ h.actionAuditStoreForApprovalDecision(r.Context()),+ req.ID,+ unifiedresources.ActionStateRejected,+ username,+ reason,+ )+ if req.ToolID == "investigation_fix" && strings.EqualFold(strings.TrimSpace(req.TargetType), "investigation") && strings.TrimSpace(req.TargetID) != "" {+ h.updateFindingOutcome(r.Context(), orgID, strings.TrimSpace(req.TargetID), string(ai.InvestigationOutcomeFixRejected))+ }// Log audit eventLogAuditEvent("ai_command_denied", username, GetClientIP(r), r.URL.Path, true,diff --git a/internal/api/ai_handlers_helpers_test.go b/internal/api/ai_handlers_helpers_test.goindex 0b723435de..0f120731cd 100644--- a/internal/api/ai_handlers_helpers_test.go+++ b/internal/api/ai_handlers_helpers_test.go@@ -2,7 +2,6 @@ package apiimport ("context"- "strings""testing""github.com/rcourtman/pulse-go-rewrite/internal/ai"@@ -31,18 +30,6 @@ func newTestAISettingsHandlerLite() *AISettingsHandler {}}-func TestIsMCPToolCall(t *testing.T) {- if !isMCPToolCall("pulse_control_guest(guest_id='102')") {- t.Fatalf("expected MCP tool call to be detected")- }- if !isMCPToolCall("default_api:pulse_get_resource(id='1')") {- t.Fatalf("expected MCP tool call with default_api prefix")- }- if isMCPToolCall("echo hello") {- t.Fatalf("expected non-tool command to be false")- }-}-func TestCleanTargetHost(t *testing.T) {if got := cleanTargetHost("pve-node (The container's host is 'pve-node')"); got != "pve-node" {t.Fatalf("expected cleaned host, got %q", got)@@ -58,67 +45,19 @@ func TestCleanTargetHost(t *testing.T) {}}-func TestSplitToolArgs(t *testing.T) {- args := "action='start', guest_id=\"102\", note='hello, world', path=\"/tmp/a,b\", escaped=\"\\\"quote\\\"\""- parts := splitToolArgs(args)- expected := []string{- "action='start'",- "guest_id=\"102\"",- "note='hello, world'",- "path=\"/tmp/a,b\"",- "escaped=\"\\\"quote\\\"\"",- }- if len(parts) != len(expected) {- t.Fatalf("expected %d parts, got %d", len(expected), len(parts))- }- for i := range expected {- if strings.TrimSpace(parts[i]) != expected[i] {- t.Fatalf("expected part %q, got %q", expected[i], parts[i])- }- }-}--func TestParseMCPToolCall(t *testing.T) {- tool, args, err := parseMCPToolCall("default_api:pulse_control_guest(guest_id=\"102\", action='start')")- if err != nil {- t.Fatalf("unexpected error: %v", err)- }- if tool != "pulse_control_guest" {- t.Fatalf("expected tool name pulse_control_guest, got %q", tool)- }- if args["guest_id"] != "102" || args["action"] != "start" {- t.Fatalf("unexpected args: %#v", args)- }-- tool, args, err = parseMCPToolCall("pulse_run_command()")- if err != nil {- t.Fatalf("unexpected error for empty args: %v", err)- }- if tool != "pulse_run_command" || len(args) != 0 {- t.Fatalf("expected empty args, got %#v", args)- }-- if _, _, err = parseMCPToolCall("pulse_control_guest"); err == nil {- t.Fatalf("expected error for missing parenthesis")- }- if _, _, err = parseMCPToolCall("pulse_control_guest("); err == nil {- t.Fatalf("expected error for missing closing parenthesis")- }-}--func TestMCPToolAdapter_Errors(t *testing.T) {- adapter := &mcpToolAdapter{handler: &AISettingsHandler{}}- if _, _, err := adapter.ExecuteMCPTool(context.Background(), "pulse_control_guest()", ""); err == nil {+func TestAssistantToolAdapter_Errors(t *testing.T) {+ adapter := &assistantToolAdapter{handler: &AISettingsHandler{}}+ if _, _, err := adapter.ExecuteApprovedAssistantTool(context.Background(), "pulse_control_guest()", ""); err == nil {t.Fatalf("expected error when chat handler is missing")}adapter.handler.chatHandler = &AIHandler{}- if _, _, err := adapter.ExecuteMCPTool(context.Background(), "pulse_control_guest()", ""); err == nil {+ if _, _, err := adapter.ExecuteApprovedAssistantTool(context.Background(), "pulse_control_guest()", ""); err == nil {t.Fatalf("expected error when chat service is missing")}adapter.handler.chatHandler.defaultService = &fakeChatWrapper{}- if _, _, err := adapter.ExecuteMCPTool(context.Background(), "pulse_control_guest()", ""); err == nil {+ if _, _, err := adapter.ExecuteApprovedAssistantTool(context.Background(), "pulse_control_guest()", ""); err == nil {t.Fatalf("expected error for chat service type mismatch")}}diff --git a/internal/api/ai_handlers_investigation_additional_test.go b/internal/api/ai_handlers_investigation_additional_test.goindex 97ec965141..88bbf28abe 100644--- a/internal/api/ai_handlers_investigation_additional_test.go+++ b/internal/api/ai_handlers_investigation_additional_test.go@@ -588,7 +588,7 @@ func TestHandleGetInvestigationMessages(t *testing.T) {}}-// TestHandleReinvestigateFinding, TestExecuteInvestigationFix_MCPTool, and+// TestHandleReinvestigateFinding, TestExecuteInvestigationFix_AssistantTool, and// TestExecuteInvestigationFix_TargetDriftBlocked have been moved to enterprise.func wsURLForHTTP(url string) string {diff --git a/internal/api/ai_handlers_oauth_test.go b/internal/api/ai_handlers_oauth_test.goindex 1475137fb1..c8308430c4 100644--- a/internal/api/ai_handlers_oauth_test.go+++ b/internal/api/ai_handlers_oauth_test.go@@ -1,10 +1,8 @@package apiimport (- "bytes""context""encoding/json"- "errors""net/http""net/http/httptest""net/url"@@ -12,42 +10,26 @@ import ("testing""time"- "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers""github.com/rcourtman/pulse-go-rewrite/internal/config")-func resetOAuthSessions() {- oauthSessionsMu.Lock()- oauthSessions = make(map[string]*oauthSessionBinding)- oauthSessionsMu.Unlock()-}--func TestHandleOAuthStart(t *testing.T) {- resetOAuthSessions()+func TestHandleOAuthStart_Unsupported(t *testing.T) {handler := &AISettingsHandler{}req := httptest.NewRequest(http.MethodGet, "/api/ai/oauth/start", nil)rr := httptest.NewRecorder()handler.HandleOAuthStart(rr, req)- if rr.Code != http.StatusOK {- t.Fatalf("expected 200, got %d", rr.Code)+ if rr.Code != http.StatusNotImplemented {+ t.Fatalf("expected 501, got %d body=%q", rr.Code, rr.Body.String())}-- var resp map[string]string+ var resp map[string]interface{}if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {- t.Fatalf("failed to decode response: %v", err)- }- if resp["auth_url"] == "" || resp["state"] == "" {- t.Fatalf("expected auth_url and state in response")+ t.Fatalf("decode response: %v", err)}- if !strings.Contains(resp["auth_url"], "claude.ai/oauth/authorize") {- t.Fatalf("expected auth_url to contain authorize endpoint")+ if resp["error"] != "unsupported_anthropic_oauth" {+ t.Fatalf("expected unsupported error, got %v", resp["error"])}-- oauthSessionsMu.Lock()- delete(oauthSessions, resp["state"])- oauthSessionsMu.Unlock()}func TestHandleOAuthStart_MethodNotAllowed(t *testing.T) {@@ -61,261 +43,55 @@ func TestHandleOAuthStart_MethodNotAllowed(t *testing.T) {}}-func TestHandleOAuthExchange_MethodNotAllowed(t *testing.T) {- handler := &AISettingsHandler{}- req := httptest.NewRequest(http.MethodGet, "/api/ai/oauth/exchange", nil)- rr := httptest.NewRecorder()-- handler.HandleOAuthExchange(rr, req)- if rr.Code != http.StatusMethodNotAllowed {- t.Fatalf("expected 405, got %d", rr.Code)- }-}--func TestHandleOAuthExchange_InvalidBody(t *testing.T) {- handler := &AISettingsHandler{}- req := httptest.NewRequest(http.MethodPost, "/api/ai/oauth/exchange", strings.NewReader("{"))- rr := httptest.NewRecorder()-- handler.HandleOAuthExchange(rr, req)- if rr.Code != http.StatusBadRequest {- t.Fatalf("expected 400, got %d", rr.Code)- }-}--func TestHandleOAuthExchange_MissingFields(t *testing.T) {- handler := &AISettingsHandler{}- body := []byte(`{"code":"","state":""}`)- req := httptest.NewRequest(http.MethodPost, "/api/ai/oauth/exchange", bytes.NewReader(body))- rr := httptest.NewRecorder()-- handler.HandleOAuthExchange(rr, req)- if rr.Code != http.StatusBadRequest {- t.Fatalf("expected 400, got %d", rr.Code)- }-}--func TestHandleOAuthExchange_UnknownState(t *testing.T) {- resetOAuthSessions()- handler := &AISettingsHandler{}- body := []byte(`{"code":"code123","state":"missing"}`)- req := httptest.NewRequest(http.MethodPost, "/api/ai/oauth/exchange", bytes.NewReader(body))- rr := httptest.NewRecorder()-- handler.HandleOAuthExchange(rr, req)- if rr.Code != http.StatusBadRequest {- t.Fatalf("expected 400, got %d", rr.Code)- }-}--func TestHandleOAuthExchange_BodySizeLimit(t *testing.T) {+func TestHandleOAuthExchange_Unsupported(t *testing.T) {handler := &AISettingsHandler{}- // Build valid JSON that exceeds the 4 KB limit so failure is specifically- // from MaxBytesReader, not from JSON syntax errors.- longCode := strings.Repeat("a", 8*1024)- oversized := []byte(`{"code":"` + longCode + `","state":"s"}`)- req := httptest.NewRequest(http.MethodPost, "/api/ai/oauth/exchange", bytes.NewReader(oversized))+ req := httptest.NewRequest(http.MethodPost, "/api/ai/oauth/exchange", strings.NewReader(`{"code":"code","state":"state"}`))rr := httptest.NewRecorder()handler.HandleOAuthExchange(rr, req)- // MaxBytesReader truncates the stream → json.Decode fails → 400.- if rr.Code != http.StatusBadRequest {- t.Fatalf("expected 400 for oversized body, got %d", rr.Code)- }-}--func TestHandleOAuthExchange_ExpiredSession(t *testing.T) {- resetOAuthSessions()-- oauthSessionsMu.Lock()- oauthSessions["expired-state"] = &oauthSessionBinding{- session: &providers.OAuthSession{- State: "expired-state",- CodeVerifier: "verifier",- CreatedAt: time.Now().Add(-oauthSessionTTL - time.Minute),- },- orgID: "default",- }- oauthSessionsMu.Unlock()-- handler := &AISettingsHandler{}- body := []byte(`{"code":"code123","state":"expired-state"}`)- req := httptest.NewRequest(http.MethodPost, "/api/ai/oauth/exchange", bytes.NewReader(body))- rr := httptest.NewRecorder()-- handler.HandleOAuthExchange(rr, req)- if rr.Code != http.StatusBadRequest {- t.Fatalf("expected 400 for expired session, got %d", rr.Code)- }- if !strings.Contains(rr.Body.String(), "expired") {- t.Fatalf("expected 'expired' in body, got %q", rr.Body.String())- }-}--func TestHandleOAuthExchange_StripsHashFromCode(t *testing.T) {- resetOAuthSessions()-- var capturedCode string- oldExchange := exchangeOAuthCodeForTokens- exchangeOAuthCodeForTokens = func(ctx context.Context, code string, session *providers.OAuthSession) (*providers.OAuthTokens, error) {- capturedCode = code- return &providers.OAuthTokens{- AccessToken: "at",- RefreshToken: "rt",- ExpiresAt: time.Now().Add(time.Hour),- }, nil- }- oldCreateAPIKey := createAPIKeyFromOAuth- createAPIKeyFromOAuth = func(ctx context.Context, accessToken string) (string, error) {- return "", errors.New("403 org:create_api_key")- }- defer func() {- exchangeOAuthCodeForTokens = oldExchange- createAPIKeyFromOAuth = oldCreateAPIKey- }()- baseDir := t.TempDir()- mtp := config.NewMultiTenantPersistence(baseDir)- if _, err := mtp.GetPersistence("default"); err != nil {- t.Fatalf("create default persistence: %v", err)- }- handler := NewAISettingsHandler(mtp, nil, nil)-- oauthSessionsMu.Lock()- oauthSessions["state-hash"] = &oauthSessionBinding{- session: &providers.OAuthSession{- State: "state-hash",- CodeVerifier: "verifier",- CreatedAt: time.Now(),- },- orgID: "default",+ if rr.Code != http.StatusNotImplemented {+ t.Fatalf("expected 501, got %d body=%q", rr.Code, rr.Body.String())}- oauthSessionsMu.Unlock()-- // Anthropic displays code as "code#state" — handler should strip #state.- body := []byte(`{"code":" realcode#extrapart ","state":"state-hash"}`)- req := httptest.NewRequest(http.MethodPost, "/api/ai/oauth/exchange", bytes.NewReader(body))- rr := httptest.NewRecorder()-- handler.HandleOAuthExchange(rr, req)- if rr.Code != http.StatusOK {- t.Fatalf("expected 200, got %d body=%q", rr.Code, rr.Body.String())+ var resp map[string]interface{}+ if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {+ t.Fatalf("decode response: %v", err)}- if capturedCode != "realcode" {- t.Fatalf("expected code='realcode' after hash stripping, got %q", capturedCode)+ if resp["error"] != "unsupported_anthropic_oauth" {+ t.Fatalf("expected unsupported error, got %v", resp["error"])}}-func TestHandleOAuthExchange_TokenExchangeFailure(t *testing.T) {- resetOAuthSessions()-- oldExchange := exchangeOAuthCodeForTokens- exchangeOAuthCodeForTokens = func(ctx context.Context, code string, session *providers.OAuthSession) (*providers.OAuthTokens, error) {- return nil, errors.New("token exchange failed: invalid_grant")- }- defer func() { exchangeOAuthCodeForTokens = oldExchange }()-- oauthSessionsMu.Lock()- oauthSessions["state-fail"] = &oauthSessionBinding{- session: &providers.OAuthSession{- State: "state-fail",- CodeVerifier: "verifier",- CreatedAt: time.Now(),- },- orgID: "default",- }- oauthSessionsMu.Unlock()-+func TestHandleOAuthExchange_MethodNotAllowed(t *testing.T) {handler := &AISettingsHandler{}- body := []byte(`{"code":"badcode","state":"state-fail"}`)- req := httptest.NewRequest(http.MethodPost, "/api/ai/oauth/exchange", bytes.NewReader(body))- rr := httptest.NewRecorder()-- handler.HandleOAuthExchange(rr, req)- if rr.Code != http.StatusBadRequest {- t.Fatalf("expected 400 for token exchange failure, got %d", rr.Code)- }-}--func TestHandleOAuthExchange_APIKeyCreatedSuccessfully(t *testing.T) {- resetOAuthSessions()-- oldExchange := exchangeOAuthCodeForTokens- exchangeOAuthCodeForTokens = func(ctx context.Context, code string, session *providers.OAuthSession) (*providers.OAuthTokens, error) {- return &providers.OAuthTokens{- AccessToken: "access-token",- RefreshToken: "refresh-token",- ExpiresAt: time.Now().Add(time.Hour),- }, nil- }- oldCreateAPIKey := createAPIKeyFromOAuth- createAPIKeyFromOAuth = func(ctx context.Context, accessToken string) (string, error) {- return "sk-ant-generated-key", nil- }- defer func() {- exchangeOAuthCodeForTokens = oldExchange- createAPIKeyFromOAuth = oldCreateAPIKey- }()-- baseDir := t.TempDir()- mtp := config.NewMultiTenantPersistence(baseDir)- if _, err := mtp.GetPersistence("default"); err != nil {- t.Fatalf("create default persistence: %v", err)- }- handler := NewAISettingsHandler(mtp, nil, nil)-- oauthSessionsMu.Lock()- oauthSessions["state-apikey"] = &oauthSessionBinding{- session: &providers.OAuthSession{- State: "state-apikey",- CodeVerifier: "verifier",- CreatedAt: time.Now(),- },- orgID: "default",- }- oauthSessionsMu.Unlock()-- body := []byte(`{"code":"goodcode","state":"state-apikey"}`)- req := httptest.NewRequest(http.MethodPost, "/api/ai/oauth/exchange", bytes.NewReader(body))+ req := httptest.NewRequest(http.MethodGet, "/api/ai/oauth/exchange", nil)rr := httptest.NewRecorder()handler.HandleOAuthExchange(rr, req)- if rr.Code != http.StatusOK {- t.Fatalf("expected 200, got %d body=%q", rr.Code, rr.Body.String())- }-- // Verify the API key was saved.- p, _ := mtp.GetPersistence("default")- cfg, err := p.LoadAIConfig()- if err != nil {- t.Fatalf("load config: %v", err)- }- if cfg.AnthropicAPIKey != "sk-ant-generated-key" {- t.Fatalf("expected API key 'sk-ant-generated-key', got %q", cfg.AnthropicAPIKey)- }- if cfg.AuthMethod != config.AuthMethodOAuth {- t.Fatalf("expected auth method OAuth, got %q", cfg.AuthMethod)+ if rr.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected 405, got %d", rr.Code)}}-func TestHandleOAuthCallback_ErrorParam(t *testing.T) {+func TestHandleOAuthCallback_Unsupported(t *testing.T) {handler := &AISettingsHandler{}- req := httptest.NewRequest(http.MethodGet, "/api/ai/oauth/callback?error=access_denied&error_description=no", nil)+ req := httptest.NewRequest(http.MethodGet, "/api/ai/oauth/callback?code=abc&state=state", nil)rr := httptest.NewRecorder()handler.HandleOAuthCallback(rr, req)+if rr.Code != http.StatusTemporaryRedirect {t.Fatalf("expected 307, got %d", rr.Code)}location := rr.Header().Get("Location")- if !strings.Contains(location, "ai_oauth_error=access_denied") {- t.Fatalf("expected redirect to include error, got %q", location)+ if !strings.Contains(location, "ai_oauth_error=unsupported") {+ t.Fatalf("expected unsupported redirect, got %q", location)}}-func TestHandleOAuthCallback_MissingParams(t *testing.T) {+func TestHandleOAuthCallback_ErrorParamURLEncoded(t *testing.T) {handler := &AISettingsHandler{}- req := httptest.NewRequest(http.MethodGet, "/api/ai/oauth/callback?code=abc", nil)+ req := httptest.NewRequest(http.MethodGet, "/api/ai/oauth/callback?error=bad%26inject%3Dfoo&error_description=test", nil)rr := httptest.NewRecorder()handler.HandleOAuthCallback(rr, req)@@ -323,24 +99,28 @@ func TestHandleOAuthCallback_MissingParams(t *testing.T) {t.Fatalf("expected 307, got %d", rr.Code)}location := rr.Header().Get("Location")- if !strings.Contains(location, "ai_oauth_error=missing_params") {- t.Fatalf("expected missing_params redirect, got %q", location)+ parsed, err := url.Parse(location)+ if err != nil {+ t.Fatalf("failed to parse redirect URL %q: %v", location, err)+ }+ qvals := parsed.Query()+ if len(qvals) != 1 {+ t.Fatalf("expected exactly 1 query key, got %d: %v", len(qvals), qvals)+ }+ got := qvals.Get("ai_oauth_error")+ if got != "bad&inject=foo" {+ t.Fatalf("expected decoded error value %q, got %q", "bad&inject=foo", got)}}-func TestHandleOAuthCallback_InvalidState(t *testing.T) {- resetOAuthSessions()+func TestHandleOAuthCallback_MethodNotAllowed(t *testing.T) {handler := &AISettingsHandler{}- req := httptest.NewRequest(http.MethodGet, "/api/ai/oauth/callback?code=abc&state=missing", nil)+ req := httptest.NewRequest(http.MethodPost, "/api/ai/oauth/callback", nil)rr := httptest.NewRecorder()handler.HandleOAuthCallback(rr, req)- if rr.Code != http.StatusTemporaryRedirect {- t.Fatalf("expected 307, got %d", rr.Code)- }- location := rr.Header().Get("Location")- if !strings.Contains(location, "ai_oauth_error=invalid_state") {- t.Fatalf("expected invalid_state redirect, got %q", location)+ if rr.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected 405, got %d", rr.Code)}}@@ -356,7 +136,6 @@ func TestHandleOAuthDisconnect_MethodNotAllowed(t *testing.T) {}func TestHandleOAuthDisconnect_AuthFailure(t *testing.T) {- // With nil config, CheckAuth returns 503 Service Unavailable.handler := &AISettingsHandler{}req := httptest.NewRequest(http.MethodPost, "/api/ai/oauth/disconnect", nil)req.RemoteAddr = "127.0.0.1:12345"@@ -376,7 +155,6 @@ func TestHandleOAuthDisconnect_Success(t *testing.T) {t.Fatalf("create default persistence: %v", err)}- // Pre-populate with OAuth tokens so we can verify they get cleared.aiCfg := config.NewDefaultAIConfig()aiCfg.AuthMethod = config.AuthMethodOAuthaiCfg.OAuthAccessToken = "access-token-123"@@ -387,7 +165,6 @@ func TestHandleOAuthDisconnect_Success(t *testing.T) {}handler := NewAISettingsHandler(mtp, nil, nil)- // Set a config with no auth credentials so CheckAuth passes as anonymous.handler.SetConfig(&config.Config{})req := httptest.NewRequest(http.MethodPost, "/api/ai/oauth/disconnect", nil)@@ -399,7 +176,6 @@ func TestHandleOAuthDisconnect_Success(t *testing.T) {t.Fatalf("expected 200, got %d body=%q", rr.Code, rr.Body.String())}- // Verify JSON response.var resp map[string]interface{}if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {t.Fatalf("decode response: %v", err)@@ -408,7 +184,6 @@ func TestHandleOAuthDisconnect_Success(t *testing.T) {t.Fatalf("expected success=true, got %v", resp["success"])}- // Verify OAuth tokens were cleared and auth method reverted to API key.saved, err := p.LoadAIConfig()if err != nil {t.Fatalf("load AI config after disconnect: %v", err)@@ -428,7 +203,6 @@ func TestHandleOAuthDisconnect_Success(t *testing.T) {}func TestHandleOAuthDisconnect_NilPersistence(t *testing.T) {- // Handler with nil persistence should return 500 when loading config fails.handler := NewAISettingsHandler(nil, nil, nil)handler.SetConfig(&config.Config{})@@ -446,7 +220,6 @@ func TestHandleOAuthDisconnect_TenantIsolation(t *testing.T) {baseDir := t.TempDir()mtp := config.NewMultiTenantPersistence(baseDir)- // Set up two tenants with OAuth tokens.pA, err := mtp.GetPersistence("tenant-a")if err != nil {t.Fatalf("create tenant-a persistence: %v", err)@@ -472,7 +245,6 @@ func TestHandleOAuthDisconnect_TenantIsolation(t *testing.T) {handler := NewAISettingsHandler(mtp, nil, nil)handler.SetConfig(&config.Config{})- // Disconnect tenant-a's OAuth.req := httptest.NewRequest(http.MethodPost, "/api/ai/oauth/disconnect", nil)req.RemoteAddr = "127.0.0.1:12345"req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "tenant-a"))@@ -483,7 +255,6 @@ func TestHandleOAuthDisconnect_TenantIsolation(t *testing.T) {t.Fatalf("expected 200, got %d body=%q", rr.Code, rr.Body.String())}- // Verify tenant-a tokens are cleared.cfgA, err := pA.LoadAIConfig()if err != nil {t.Fatalf("load tenant-a config: %v", err)@@ -492,7 +263,6 @@ func TestHandleOAuthDisconnect_TenantIsolation(t *testing.T) {t.Fatalf("expected tenant-a OAuth cleared, got auth=%q token=%q refresh=%q", cfgA.AuthMethod, cfgA.OAuthAccessToken, cfgA.OAuthRefreshToken)}- // Verify tenant-b tokens are completely untouched (exact values preserved).cfgB, err := pB.LoadAIConfig()if err != nil {t.Fatalf("load tenant-b config: %v", err)@@ -507,342 +277,3 @@ func TestHandleOAuthDisconnect_TenantIsolation(t *testing.T) {t.Fatalf("expected tenant-b refresh token %q, got %q", "refresh-b", cfgB.OAuthRefreshToken)}}--func TestHandleOAuthStart_BindsSessionToOrgFromContext(t *testing.T) {- resetOAuthSessions()- handler := &AISettingsHandler{}-- req := httptest.NewRequest(http.MethodGet, "/api/ai/oauth/start", nil)- req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "tenant-a"))- rr := httptest.NewRecorder()-- handler.HandleOAuthStart(rr, req)-- if rr.Code != http.StatusOK {- t.Fatalf("expected 200, got %d", rr.Code)- }-- var resp map[string]string- if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {- t.Fatalf("decode response: %v", err)- }- state := strings.TrimSpace(resp["state"])- if state == "" {- t.Fatalf("expected state in response")- }-- oauthSessionsMu.Lock()- binding, ok := oauthSessions[state]- oauthSessionsMu.Unlock()- if !ok || binding == nil {- t.Fatalf("expected OAuth session binding for state %q", state)- }- if binding.orgID != "tenant-a" {- t.Fatalf("expected bound org tenant-a, got %q", binding.orgID)- }-}--func TestConsumeOAuthSession_RejectsExpiredSession(t *testing.T) {- resetOAuthSessions()-- oauthSessionsMu.Lock()- oauthSessions["expired-state"] = &oauthSessionBinding{- session: &providers.OAuthSession{- State: "expired-state",- CodeVerifier: "verifier",- CreatedAt: time.Now().Add(-oauthSessionTTL - time.Minute),- },- orgID: "default",- }- oauthSessionsMu.Unlock()-- if binding, ok := consumeOAuthSession("expired-state"); ok || binding != nil {- t.Fatalf("expected expired session to be rejected")- }-}--func TestHandleOAuthCallback_UsesSessionBoundOrgForSave(t *testing.T) {- resetOAuthSessions()-- oldExchange := exchangeOAuthCodeForTokens- exchangeOAuthCodeForTokens = func(ctx context.Context, code string, session *providers.OAuthSession) (*providers.OAuthTokens, error) {- return &providers.OAuthTokens{- AccessToken: "access-token-a",- RefreshToken: "refresh-token-a",- ExpiresAt: time.Now().Add(time.Hour),- }, nil- }- defer func() { exchangeOAuthCodeForTokens = oldExchange }()-- baseDir := t.TempDir()- mtp := config.NewMultiTenantPersistence(baseDir)- if _, err := mtp.GetPersistence("tenant-a"); err != nil {- t.Fatalf("create tenant-a persistence: %v", err)- }- if _, err := mtp.GetPersistence("tenant-b"); err != nil {- t.Fatalf("create tenant-b persistence: %v", err)- }- handler := NewAISettingsHandler(mtp, nil, nil)-- oauthSessionsMu.Lock()- oauthSessions["state-a"] = &oauthSessionBinding{- session: &providers.OAuthSession{- State: "state-a",- CodeVerifier: "verifier-a",- CreatedAt: time.Now(),- },- orgID: "tenant-a",- }- oauthSessionsMu.Unlock()-- req := httptest.NewRequest(http.MethodGet, "/api/ai/oauth/callback?code=code-a&state=state-a", nil)- req.AddCookie(&http.Cookie{Name: "pulse_org_id", Value: "tenant-b"})- rr := httptest.NewRecorder()-- handler.HandleOAuthCallback(rr, req)-- if rr.Code != http.StatusTemporaryRedirect {- t.Fatalf("expected 307, got %d", rr.Code)- }- if got := rr.Header().Get("Location"); !strings.Contains(got, "ai_oauth_success=true") {- t.Fatalf("expected success redirect, got %q", got)- }-- pA, _ := mtp.GetPersistence("tenant-a")- cfgA, err := pA.LoadAIConfig()- if err != nil {- t.Fatalf("load tenant-a config: %v", err)- }- if cfgA.AuthMethod != config.AuthMethodOAuth || cfgA.OAuthAccessToken != "access-token-a" {- t.Fatalf("expected tenant-a OAuth config to be updated, got auth=%q token=%q", cfgA.AuthMethod, cfgA.OAuthAccessToken)- }-- pB, _ := mtp.GetPersistence("tenant-b")- cfgB, err := pB.LoadAIConfig()- if err != nil {- t.Fatalf("load tenant-b config: %v", err)- }- if cfgB.OAuthAccessToken != "" || cfgB.AuthMethod != config.AuthMethodAPIKey {- t.Fatalf("expected tenant-b OAuth config to remain unchanged, got auth=%q token=%q", cfgB.AuthMethod, cfgB.OAuthAccessToken)- }-}--func TestHandleOAuthCallback_MethodNotAllowed(t *testing.T) {- handler := &AISettingsHandler{}- req := httptest.NewRequest(http.MethodPost, "/api/ai/oauth/callback", nil)- rr := httptest.NewRecorder()-- handler.HandleOAuthCallback(rr, req)- if rr.Code != http.StatusMethodNotAllowed {- t.Fatalf("expected 405, got %d", rr.Code)- }-}--func TestHandleOAuthCallback_ExpiredSession(t *testing.T) {- resetOAuthSessions()-- oauthSessionsMu.Lock()- oauthSessions["expired-cb"] = &oauthSessionBinding{- session: &providers.OAuthSession{- State: "expired-cb",- CodeVerifier: "verifier",- CreatedAt: time.Now().Add(-oauthSessionTTL - time.Minute),- },- orgID: "default",- }- oauthSessionsMu.Unlock()-- handler := &AISettingsHandler{}- req := httptest.NewRequest(http.MethodGet, "/api/ai/oauth/callback?code=abc&state=expired-cb", nil)- rr := httptest.NewRecorder()-- handler.HandleOAuthCallback(rr, req)- if rr.Code != http.StatusTemporaryRedirect {- t.Fatalf("expected 307, got %d", rr.Code)- }- location := rr.Header().Get("Location")- if !strings.Contains(location, "ai_oauth_error=invalid_state") {- t.Fatalf("expected invalid_state redirect for expired session, got %q", location)- }-}--func TestHandleOAuthCallback_TokenExchangeFailure(t *testing.T) {- resetOAuthSessions()-- oldExchange := exchangeOAuthCodeForTokens- exchangeOAuthCodeForTokens = func(ctx context.Context, code string, session *providers.OAuthSession) (*providers.OAuthTokens, error) {- return nil, errors.New("token exchange failed")- }- defer func() { exchangeOAuthCodeForTokens = oldExchange }()-- oauthSessionsMu.Lock()- oauthSessions["state-fail-cb"] = &oauthSessionBinding{- session: &providers.OAuthSession{- State: "state-fail-cb",- CodeVerifier: "verifier",- CreatedAt: time.Now(),- },- orgID: "default",- }- oauthSessionsMu.Unlock()-- handler := &AISettingsHandler{}- req := httptest.NewRequest(http.MethodGet, "/api/ai/oauth/callback?code=badcode&state=state-fail-cb", nil)- rr := httptest.NewRecorder()-- handler.HandleOAuthCallback(rr, req)- if rr.Code != http.StatusTemporaryRedirect {- t.Fatalf("expected 307, got %d", rr.Code)- }- location := rr.Header().Get("Location")- if !strings.Contains(location, "ai_oauth_error=token_exchange_failed") {- t.Fatalf("expected token_exchange_failed redirect, got %q", location)- }-}--func TestHandleOAuthCallback_ErrorParamURLEncoded(t *testing.T) {- handler := &AISettingsHandler{}- // Inject special characters in the error param to verify URL-encoding- req := httptest.NewRequest(http.MethodGet, "/api/ai/oauth/callback?error=bad%26inject%3Dfoo&error_description=test", nil)- rr := httptest.NewRecorder()-- handler.HandleOAuthCallback(rr, req)- if rr.Code != http.StatusTemporaryRedirect {- t.Fatalf("expected 307, got %d", rr.Code)- }- location := rr.Header().Get("Location")- // Parse the redirect URL and verify the error value round-trips correctly.- parsed, err := url.Parse(location)- if err != nil {- t.Fatalf("failed to parse redirect URL %q: %v", location, err)- }- qvals := parsed.Query()- // Only one query key should be present — injection would add extra keys.- if len(qvals) != 1 {- t.Fatalf("expected exactly 1 query key, got %d: %v", len(qvals), qvals)- }- got := qvals.Get("ai_oauth_error")- if got != "bad&inject=foo" {- t.Fatalf("expected decoded error value %q, got %q", "bad&inject=foo", got)- }-}--func TestHandleOAuthCallback_SessionConsumedOnce(t *testing.T) {- resetOAuthSessions()-- oldExchange := exchangeOAuthCodeForTokens- exchangeOAuthCodeForTokens = func(ctx context.Context, code string, session *providers.OAuthSession) (*providers.OAuthTokens, error) {- return &providers.OAuthTokens{- AccessToken: "at",- RefreshToken: "rt",- ExpiresAt: time.Now().Add(time.Hour),- }, nil- }- defer func() { exchangeOAuthCodeForTokens = oldExchange }()-- baseDir := t.TempDir()- mtp := config.NewMultiTenantPersistence(baseDir)- if _, err := mtp.GetPersistence("default"); err != nil {- t.Fatalf("create default persistence: %v", err)- }- handler := NewAISettingsHandler(mtp, nil, nil)-- oauthSessionsMu.Lock()- oauthSessions["state-once"] = &oauthSessionBinding{- session: &providers.OAuthSession{- State: "state-once",- CodeVerifier: "verifier",- CreatedAt: time.Now(),- },- orgID: "default",- }- oauthSessionsMu.Unlock()-- // First call should succeed- req1 := httptest.NewRequest(http.MethodGet, "/api/ai/oauth/callback?code=abc&state=state-once", nil)- rr1 := httptest.NewRecorder()- handler.HandleOAuthCallback(rr1, req1)- if !strings.Contains(rr1.Header().Get("Location"), "ai_oauth_success=true") {- t.Fatalf("first call should succeed, got %q", rr1.Header().Get("Location"))- }-- // Second call with same state should fail (session consumed)- req2 := httptest.NewRequest(http.MethodGet, "/api/ai/oauth/callback?code=abc&state=state-once", nil)- rr2 := httptest.NewRecorder()- handler.HandleOAuthCallback(rr2, req2)- if !strings.Contains(rr2.Header().Get("Location"), "ai_oauth_error=invalid_state") {- t.Fatalf("second call should fail with invalid_state, got %q", rr2.Header().Get("Location"))- }-}--func TestHandleOAuthExchange_UsesSessionBoundOrgForSave(t *testing.T) {- resetOAuthSessions()-- oldExchange := exchangeOAuthCodeForTokens- oldCreateAPIKey := createAPIKeyFromOAuth- exchangeOAuthCodeForTokens = func(ctx context.Context, code string, session *providers.OAuthSession) (*providers.OAuthTokens, error) {- return &providers.OAuthTokens{- AccessToken: "access-token-a",- RefreshToken: "refresh-token-a",- ExpiresAt: time.Now().Add(time.Hour),- }, nil- }- createAPIKeyFromOAuth = func(ctx context.Context, accessToken string) (string, error) {- return "", errors.New("403 org:create_api_key")- }- defer func() {- exchangeOAuthCodeForTokens = oldExchange- createAPIKeyFromOAuth = oldCreateAPIKey- }()-- baseDir := t.TempDir()- mtp := config.NewMultiTenantPersistence(baseDir)- if _, err := mtp.GetPersistence("tenant-a"); err != nil {- t.Fatalf("create tenant-a persistence: %v", err)- }- if _, err := mtp.GetPersistence("tenant-b"); err != nil {- t.Fatalf("create tenant-b persistence: %v", err)- }- handler := NewAISettingsHandler(mtp, nil, nil)-- oauthSessionsMu.Lock()- oauthSessions["state-a"] = &oauthSessionBinding{- session: &providers.OAuthSession{- State: "state-a",- CodeVerifier: "verifier-a",- CreatedAt: time.Now(),- },- orgID: "tenant-a",- }- oauthSessionsMu.Unlock()-- body := []byte(`{"code":"code-a","state":"state-a"}`)- req := httptest.NewRequest(http.MethodPost, "/api/ai/oauth/exchange", bytes.NewReader(body))- req.Header.Set("Content-Type", "application/json")- req.AddCookie(&http.Cookie{Name: "pulse_org_id", Value: "tenant-b"})- rr := httptest.NewRecorder()-- handler.HandleOAuthExchange(rr, req)-- if rr.Code != http.StatusOK {- t.Fatalf("expected 200, got %d body=%q", rr.Code, rr.Body.String())- }-- pA, _ := mtp.GetPersistence("tenant-a")- cfgA, err := pA.LoadAIConfig()- if err != nil {- t.Fatalf("load tenant-a config: %v", err)- }- if cfgA.AuthMethod != config.AuthMethodOAuth || cfgA.OAuthAccessToken != "access-token-a" {- t.Fatalf("expected tenant-a OAuth config to be updated, got auth=%q token=%q", cfgA.AuthMethod, cfgA.OAuthAccessToken)- }-- pB, _ := mtp.GetPersistence("tenant-b")- cfgB, err := pB.LoadAIConfig()- if err != nil {- t.Fatalf("load tenant-b config: %v", err)- }- if cfgB.OAuthAccessToken != "" || cfgB.AuthMethod != config.AuthMethodAPIKey {- t.Fatalf("expected tenant-b OAuth config to remain unchanged, got auth=%q token=%q", cfgB.AuthMethod, cfgB.OAuthAccessToken)- }-}diff --git a/internal/api/ai_handlers_patrol_actions_additional_test.go b/internal/api/ai_handlers_patrol_actions_additional_test.goindex e35bced0ad..8e06a1f915 100644--- a/internal/api/ai_handlers_patrol_actions_additional_test.go+++ b/internal/api/ai_handlers_patrol_actions_additional_test.go@@ -9,6 +9,7 @@ import ("testing""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/ai""github.com/rcourtman/pulse-go-rewrite/internal/ai/learning""github.com/rcourtman/pulse-go-rewrite/internal/ai/unified"@@ -112,6 +113,8 @@ func addUnifiedRuntimeFinding(store *unified.UnifiedStore, id string, detectedAtreturn finding}+type agentStableErrorEnvelope = agentcapabilities.ErrorEnvelope+func TestHandleGetPatrolStatus_DistinguishesLastFullPatrolFromLastActivity(t *testing.T) {handler, patrol, _, _ := setupAIHandlerWithPatrol(t)@@ -224,11 +227,12 @@ func TestPatrolActionHandlers_NoAIService_ReturnStructuredServiceUnavailable(t *handler := newTestAISettingsHandler(cfg, nil, nil)tests := []struct {- name string- method string- path string- body string- handler func(http.ResponseWriter, *http.Request)+ name string+ method string+ path string+ body string+ handler func(http.ResponseWriter, *http.Request)+ agentEnvelope bool}{{name: "force_patrol",@@ -237,25 +241,28 @@ func TestPatrolActionHandlers_NoAIService_ReturnStructuredServiceUnavailable(t *handler: handler.HandleForcePatrol,},{- name: "acknowledge",- method: http.MethodPost,- path: "/api/ai/patrol/acknowledge",- body: `{"finding_id":"finding-1"}`,- handler: handler.HandleAcknowledgeFinding,+ name: "acknowledge",+ method: http.MethodPost,+ path: "/api/ai/patrol/acknowledge",+ body: `{"finding_id":"finding-1"}`,+ handler: handler.HandleAcknowledgeFinding,+ agentEnvelope: true,},{- name: "snooze",- method: http.MethodPost,- path: "/api/ai/patrol/snooze",- body: `{"finding_id":"finding-1","duration_hours":1}`,- handler: handler.HandleSnoozeFinding,+ name: "snooze",+ method: http.MethodPost,+ path: "/api/ai/patrol/snooze",+ body: `{"finding_id":"finding-1","duration_hours":1}`,+ handler: handler.HandleSnoozeFinding,+ agentEnvelope: true,},{- name: "resolve",- method: http.MethodPost,- path: "/api/ai/patrol/resolve",- body: `{"finding_id":"finding-1"}`,- handler: handler.HandleResolveFinding,+ name: "resolve",+ method: http.MethodPost,+ path: "/api/ai/patrol/resolve",+ body: `{"finding_id":"finding-1"}`,+ handler: handler.HandleResolveFinding,+ agentEnvelope: true,},{name: "note",@@ -265,11 +272,12 @@ func TestPatrolActionHandlers_NoAIService_ReturnStructuredServiceUnavailable(t *handler: handler.HandleSetFindingNote,},{- name: "dismiss",- method: http.MethodPost,- path: "/api/ai/patrol/dismiss",- body: `{"finding_id":"finding-1","reason":"expected_behavior"}`,- handler: handler.HandleDismissFinding,+ name: "dismiss",+ method: http.MethodPost,+ path: "/api/ai/patrol/dismiss",+ body: `{"finding_id":"finding-1","reason":"expected_behavior"}`,+ handler: handler.HandleDismissFinding,+ agentEnvelope: true,},{name: "suppress",@@ -310,6 +318,20 @@ func TestPatrolActionHandlers_NoAIService_ReturnStructuredServiceUnavailable(t *t.Fatalf("status = %d, want %d", rec.Code, http.StatusServiceUnavailable)}+ if tc.agentEnvelope {+ var resp agentStableErrorEnvelope+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if resp.Error != "patrol_unavailable" {+ t.Fatalf("error = %q, want patrol_unavailable", resp.Error)+ }+ if resp.Message != "Pulse Patrol service not available" {+ t.Fatalf("message = %q, want Pulse Patrol service not available", resp.Message)+ }+ return+ }+var resp APIErrorif err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {t.Fatalf("decode response: %v", err)@@ -324,6 +346,148 @@ func TestPatrolActionHandlers_NoAIService_ReturnStructuredServiceUnavailable(t *}}+func TestPatrolFindingLifecycleHandlers_ReturnAgentStableValidationErrors(t *testing.T) {+ handler, _, _, _ := setupAIHandlerWithPatrol(t)++ tests := []struct {+ name string+ path string+ body string+ handler func(http.ResponseWriter, *http.Request)+ wantMessage string+ wantDetails map[string]string+ }{+ {+ name: "acknowledge_missing_finding_id",+ path: "/api/ai/patrol/acknowledge",+ body: `{}`,+ handler: handler.HandleAcknowledgeFinding,+ wantMessage: "finding_id is required",+ wantDetails: map[string]string{"finding_id": "required"},+ },+ {+ name: "snooze_invalid_duration",+ path: "/api/ai/patrol/snooze",+ body: `{"finding_id":"finding-1","duration_hours":0}`,+ handler: handler.HandleSnoozeFinding,+ wantMessage: "duration_hours must be positive",+ wantDetails: map[string]string{"duration_hours": "must be positive"},+ },+ {+ name: "dismiss_invalid_reason",+ path: "/api/ai/patrol/dismiss",+ body: `{"finding_id":"finding-1","reason":"invalid_reason"}`,+ handler: handler.HandleDismissFinding,+ wantMessage: "Invalid reason. Valid values: not_an_issue, expected_behavior, will_fix_later",+ wantDetails: map[string]string{"reason": "must be one of not_an_issue, expected_behavior, will_fix_later"},+ },+ {+ name: "resolve_invalid_json",+ path: "/api/ai/patrol/resolve",+ body: `{`,+ handler: handler.HandleResolveFinding,+ wantMessage: "Invalid request body",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ req := newLoopbackRequest(http.MethodPost, tt.path, strings.NewReader(tt.body))+ rec := httptest.NewRecorder()++ tt.handler(rec, req)++ if rec.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusBadRequest, rec.Body.String())+ }++ var resp agentStableErrorEnvelope+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if resp.Error != "invalid_finding_request" {+ t.Fatalf("error = %q, want invalid_finding_request", resp.Error)+ }+ if resp.Message != tt.wantMessage {+ t.Fatalf("message = %q, want %q", resp.Message, tt.wantMessage)+ }+ for key, want := range tt.wantDetails {+ if got := resp.Details[key]; got != want {+ t.Fatalf("details[%q] = %q, want %q; details=%v", key, got, want, resp.Details)+ }+ }+ if len(tt.wantDetails) == 0 && len(resp.Details) != 0 {+ t.Fatalf("details = %v, want empty", resp.Details)+ }+ })+ }+}++func TestPatrolFindingLifecycleHandlers_ReturnAgentStableNotFoundErrors(t *testing.T) {+ handler, _, _, _ := setupAIHandlerWithPatrol(t)++ tests := []struct {+ name string+ path string+ body string+ handler func(http.ResponseWriter, *http.Request)+ wantMessage string+ }{+ {+ name: "acknowledge",+ path: "/api/ai/patrol/acknowledge",+ body: `{"finding_id":"missing"}`,+ handler: handler.HandleAcknowledgeFinding,+ wantMessage: "Finding not found",+ },+ {+ name: "snooze",+ path: "/api/ai/patrol/snooze",+ body: `{"finding_id":"missing","duration_hours":1}`,+ handler: handler.HandleSnoozeFinding,+ wantMessage: "Finding not found or already resolved",+ },+ {+ name: "resolve",+ path: "/api/ai/patrol/resolve",+ body: `{"finding_id":"missing"}`,+ handler: handler.HandleResolveFinding,+ wantMessage: "Finding not found or already resolved",+ },+ {+ name: "dismiss",+ path: "/api/ai/patrol/dismiss",+ body: `{"finding_id":"missing","reason":"expected_behavior"}`,+ handler: handler.HandleDismissFinding,+ wantMessage: "Finding not found",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ req := newLoopbackRequest(http.MethodPost, tt.path, strings.NewReader(tt.body))+ rec := httptest.NewRecorder()++ tt.handler(rec, req)++ if rec.Code != http.StatusNotFound {+ t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusNotFound, rec.Body.String())+ }++ var resp agentStableErrorEnvelope+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if resp.Error != "finding_not_found" {+ t.Fatalf("error = %q, want finding_not_found", resp.Error)+ }+ if resp.Message != tt.wantMessage {+ t.Fatalf("message = %q, want %q", resp.Message, tt.wantMessage)+ }+ })+ }+}+func TestHandleAddSuppressionRuleRejectsImplicitBroadScope(t *testing.T) {handler, patrol, _, _ := setupAIHandlerWithPatrol(t)@@ -482,7 +646,7 @@ func TestHandleResolveFinding_SetsResolved(t *testing.T) {addPatrolFinding(t, patrol, "finding-resolve", detectedAt)addUnifiedFinding(unifiedStore, "finding-resolve", detectedAt)- req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/resolve", strings.NewReader(`{"finding_id":"finding-resolve"}`))+ req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/resolve", strings.NewReader(`{"finding_id":"finding-resolve","resolution_note":"fixed after restarting the worker"}`))rec := httptest.NewRecorder()handler.HandleResolveFinding(rec, req)@@ -495,6 +659,9 @@ func TestHandleResolveFinding_SetsResolved(t *testing.T) {if patrolFinding == nil || patrolFinding.ResolvedAt == nil {t.Fatalf("expected patrol finding to be resolved")}+ if patrolFinding.UserNote != "fixed after restarting the worker" {+ t.Fatalf("patrol finding resolution note = %q", patrolFinding.UserNote)+ }unifiedFinding := unifiedStore.Get("finding-resolve")if unifiedFinding == nil || unifiedFinding.ResolvedAt == nil {@@ -597,39 +764,44 @@ func TestHandlePatrolRuntimeFindingActions_AreRejected(t *testing.T) {addUnifiedRuntimeFinding(unifiedStore, "finding-runtime", detectedAt)tests := []struct {- name string- path string- body string- handler func(http.ResponseWriter, *http.Request)- wantPhrase string+ name string+ path string+ body string+ handler func(http.ResponseWriter, *http.Request)+ wantPhrase string+ wantAgentCode string}{{- name: "acknowledge",- path: "/api/ai/patrol/acknowledge",- body: `{"finding_id":"finding-runtime"}`,- handler: handler.HandleAcknowledgeFinding,- wantPhrase: "cannot be acknowledged manually",+ name: "acknowledge",+ path: "/api/ai/patrol/acknowledge",+ body: `{"finding_id":"finding-runtime"}`,+ handler: handler.HandleAcknowledgeFinding,+ wantPhrase: "cannot be acknowledged manually",+ wantAgentCode: "finding_action_not_allowed",},{- name: "snooze",- path: "/api/ai/patrol/snooze",- body: `{"finding_id":"finding-runtime","duration_hours":24}`,- handler: handler.HandleSnoozeFinding,- wantPhrase: "cannot be snoozed manually",+ name: "snooze",+ path: "/api/ai/patrol/snooze",+ body: `{"finding_id":"finding-runtime","duration_hours":24}`,+ handler: handler.HandleSnoozeFinding,+ wantPhrase: "cannot be snoozed manually",+ wantAgentCode: "finding_action_not_allowed",},{- name: "resolve",- path: "/api/ai/patrol/resolve",- body: `{"finding_id":"finding-runtime"}`,- handler: handler.HandleResolveFinding,- wantPhrase: "cannot be resolved manually",+ name: "resolve",+ path: "/api/ai/patrol/resolve",+ body: `{"finding_id":"finding-runtime"}`,+ handler: handler.HandleResolveFinding,+ wantPhrase: "cannot be resolved manually",+ wantAgentCode: "finding_action_not_allowed",},{- name: "dismiss",- path: "/api/ai/patrol/dismiss",- body: `{"finding_id":"finding-runtime","reason":"expected_behavior","note":"ignore"}`,- handler: handler.HandleDismissFinding,- wantPhrase: "cannot be dismissed manually",+ name: "dismiss",+ path: "/api/ai/patrol/dismiss",+ body: `{"finding_id":"finding-runtime","reason":"expected_behavior","note":"ignore"}`,+ handler: handler.HandleDismissFinding,+ wantPhrase: "cannot be dismissed manually",+ wantAgentCode: "finding_action_not_allowed",},{name: "suppress",@@ -650,6 +822,19 @@ func TestHandlePatrolRuntimeFindingActions_AreRejected(t *testing.T) {if rec.Code != http.StatusConflict {t.Fatalf("status = %d, want 409", rec.Code)}+ if tt.wantAgentCode != "" {+ var resp agentStableErrorEnvelope+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if resp.Error != tt.wantAgentCode {+ t.Fatalf("error = %q, want %q", resp.Error, tt.wantAgentCode)+ }+ if !strings.Contains(resp.Message, tt.wantPhrase) {+ t.Fatalf("expected message to contain %q, got %q", tt.wantPhrase, resp.Message)+ }+ return+ }if !strings.Contains(rec.Body.String(), tt.wantPhrase) {t.Fatalf("expected response to contain %q, got %q", tt.wantPhrase, rec.Body.String())}diff --git a/internal/api/ai_handlers_test.go b/internal/api/ai_handlers_test.goindex 1398348db5..6a857a017d 100644--- a/internal/api/ai_handlers_test.go+++ b/internal/api/ai_handlers_test.go@@ -13,6 +13,7 @@ import ("testing""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/ai""github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"@@ -65,6 +66,131 @@ func TestAIHandlersUseSafeRemediationCommercialCopy(t *testing.T) {}}+func TestAISettingsHandler_AnthropicOAuthSetupFailsClosed(t *testing.T) {+ handler := &AISettingsHandler{}++ tests := []struct {+ name string+ method string+ path string+ body string+ call func(http.ResponseWriter, *http.Request)+ }{+ {+ name: "start",+ method: http.MethodGet,+ path: "/api/ai/oauth/start",+ call: handler.HandleOAuthStart,+ },+ {+ name: "exchange",+ method: http.MethodPost,+ path: "/api/ai/oauth/exchange",+ body: `{"code":"code","state":"state"}`,+ call: handler.HandleOAuthExchange,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ req := newLoopbackRequest(tt.method, tt.path, strings.NewReader(tt.body))+ rec := httptest.NewRecorder()++ tt.call(rec, req)++ require.Equal(t, http.StatusNotImplemented, rec.Code, rec.Body.String())+ var resp struct {+ Success bool `json:"success"`+ Error string `json:"error"`+ Message string `json:"message"`+ }+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))+ require.False(t, resp.Success)+ require.Equal(t, "unsupported_anthropic_oauth", resp.Error)+ require.Contains(t, resp.Message, "Configure an Anthropic API key")+ })+ }+}++func TestAIHandlersDelegateApprovedToolInvocationParsingToSharedCapabilities(t *testing.T) {+ source, err := os.ReadFile("ai_handlers.go")+ require.NoError(t, err)+ aiHandlers := string(source)+ for _, fragment := range []string{+ "isMCPToolCall",+ "parseMCPToolCall",+ "splitToolArgs",+ } {+ require.NotContains(t, aiHandlers, fragment)+ }++ source, err = os.ReadFile("router_routes_ai_relay.go")+ require.NoError(t, err)+ relay := string(source)+ require.Contains(t, relay, "agentcapabilities.ParseTextToolInvocation(command)")+ require.NotContains(t, relay, "func parseMCPToolCall(")+ require.NotContains(t, relay, "func splitToolArgs(")+ require.NotContains(t, relay, "func isMCPToolCall(")+}++func TestAIHandlersUseSharedPatrolFindingAgentErrorCodes(t *testing.T) {+ source, err := os.ReadFile("ai_handlers.go")+ require.NoError(t, err)+ aiHandlers := string(source)++ for _, constant := range []string{+ "agentcapabilities.AgentErrCodePatrolUnavailable",+ "agentcapabilities.AgentErrCodeInvalidFindingRequest",+ "agentcapabilities.AgentErrCodeFindingNotFound",+ "agentcapabilities.AgentErrCodeFindingActionNotAllowed",+ } {+ require.Contains(t, aiHandlers, constant)+ }++ for _, literal := range []string{+ `writeJSONError(w, http.StatusServiceUnavailable, "` + agentcapabilities.AgentErrCodePatrolUnavailable + `"`,+ `writeJSONErrorWithDetails(w, http.StatusBadRequest, "` + agentcapabilities.AgentErrCodeInvalidFindingRequest + `"`,+ `writeJSONError(w, http.StatusNotFound, "` + agentcapabilities.AgentErrCodeFindingNotFound + `"`,+ `writeJSONError(w, http.StatusConflict, "` + agentcapabilities.AgentErrCodeFindingActionNotAllowed + `"`,+ } {+ require.NotContains(t, aiHandlers, literal)+ }+}++func TestAISettingsHandler_PatrolFindingLifecycleUsesAgentStableUnavailableEnvelope(t *testing.T) {+ tmp := t.TempDir()+ cfg := &config.Config{DataPath: tmp}+ handler := newTestAISettingsHandler(cfg, nil, nil)++ req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/acknowledge", strings.NewReader(`{"finding_id":"finding-1"}`))+ rec := httptest.NewRecorder()+ handler.HandleAcknowledgeFinding(rec, req)++ require.Equal(t, http.StatusServiceUnavailable, rec.Code, rec.Body.String())+ var resp agentStableErrorEnvelope+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))+ require.Equal(t, agentcapabilities.AgentErrCodePatrolUnavailable, resp.Error)+ require.Equal(t, "Pulse Patrol service not available", resp.Message)+}++func TestAISettingsHandler_ResolveFindingPersistsResolutionNote(t *testing.T) {+ handler, patrol, unifiedStore, _ := setupAIHandlerWithPatrol(t)+ detectedAt := time.Now().Add(-2 * time.Hour)+ addPatrolFinding(t, patrol, "finding-resolve-note", detectedAt)+ addUnifiedFinding(unifiedStore, "finding-resolve-note", detectedAt)++ req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/resolve", strings.NewReader(`{"finding_id":"finding-resolve-note","resolution_note":" fixed after restarting the worker "}`))+ rec := httptest.NewRecorder()++ handler.HandleResolveFinding(rec, req)++ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())+ patrolFinding := patrol.GetFindings().Get("finding-resolve-note")+ require.NotNil(t, patrolFinding)+ require.NotNil(t, patrolFinding.ResolvedAt)+ require.Equal(t, "fixed after restarting the worker", patrolFinding.UserNote)+}+func TestAISettingsHandler_PatrolAutonomyMonitorOnlyAllowsMonitor(t *testing.T) {tmp := t.TempDir()cfg := &config.Config{DataPath: tmp}@@ -172,6 +298,23 @@ func TestAISettingsHandler_UpdateSettingsPersistsNotReadyPatrolModelWithReadinesrequire.Equal(t, model, persisted.PatrolModel)}+func TestAISettingsHandler_PatrolConfigReadinessUsesControlLabel(t *testing.T) {+ readiness := patrolReadinessResponseFromConfigReadiness(ai.PatrolConfigReadiness{+ Status: ai.PatrolReadinessWarning,+ Ready: true,+ Cause: ai.PatrolFailureCauseModelToolSupportUnverified,+ Summary: "Ollama connectivity alone does not prove tool support.",+ Provider: "ollama",+ Model: "ollama:llama3",+ })++ require.Equal(t, patrolReadinessWarning, readiness.Status)+ require.True(t, readiness.Ready)+ check := requirePatrolReadinessCheck(t, readiness, "configuration")+ require.Equal(t, "Patrol control", check.Label)+ require.NotContains(t, check.Label, "configuration")+}+func TestAISettingsHandler_UpdateSettingsDoesNotLockUnrelatedSavesBehindExistingPatrolReadiness(t *testing.T) {tmp := t.TempDir()cfg := &config.Config{DataPath: tmp}@@ -201,6 +344,56 @@ func TestAISettingsHandler_UpdateSettingsDoesNotLockUnrelatedSavesBehindExistingrequire.Equal(t, model, persisted.PatrolModel)}+func TestAISettingsHandler_UpdateSettingsRefreshesAssistantToolVisibilityForControlChanges(t *testing.T) {+ tmp := t.TempDir()+ cfg := &config.Config{DataPath: tmp}+ persistence := config.NewConfigPersistence(tmp)+ handler := newTestAISettingsHandler(cfg, persistence, nil)++ controlRefreshes := 0+ handler.SetOnControlSettingsChange(func() {+ controlRefreshes+++ })++ unrelatedBody, err := json.Marshal(AISettingsUpdateRequest{+ RequestTimeoutSeconds: ptr(90),+ })+ require.NoError(t, err)+ unrelatedReq := newLoopbackRequest(http.MethodPut, "/api/settings/ai/update", bytes.NewReader(unrelatedBody))+ unrelatedRec := httptest.NewRecorder()+ handler.HandleUpdateAISettings(unrelatedRec, unrelatedReq)++ require.Equal(t, http.StatusOK, unrelatedRec.Code, unrelatedRec.Body.String())+ require.Equal(t, 0, controlRefreshes, "non-control settings must not refresh Assistant tool visibility")++ controlBody, err := json.Marshal(AISettingsUpdateRequest{+ ControlLevel: ptr(config.ControlLevelControlled),+ })+ require.NoError(t, err)+ controlReq := newLoopbackRequest(http.MethodPut, "/api/settings/ai/update", bytes.NewReader(controlBody))+ controlRec := httptest.NewRecorder()+ handler.HandleUpdateAISettings(controlRec, controlReq)++ require.Equal(t, http.StatusOK, controlRec.Code, controlRec.Body.String())+ require.Equal(t, 1, controlRefreshes, "control level changes must refresh Assistant tool visibility")++ protectedBody, err := json.Marshal(AISettingsUpdateRequest{+ ProtectedGuests: []string{"vm-101"},+ })+ require.NoError(t, err)+ protectedReq := newLoopbackRequest(http.MethodPut, "/api/settings/ai/update", bytes.NewReader(protectedBody))+ protectedRec := httptest.NewRecorder()+ handler.HandleUpdateAISettings(protectedRec, protectedReq)++ require.Equal(t, http.StatusOK, protectedRec.Code, protectedRec.Body.String())+ require.Equal(t, 2, controlRefreshes, "protected guest changes must refresh Assistant tool visibility")++ persisted, err := persistence.LoadAIConfig()+ require.NoError(t, err)+ require.Equal(t, config.ControlLevelControlled, persisted.GetControlLevel())+ require.Equal(t, []string{"vm-101"}, persisted.GetProtectedGuests())+}+func TestAISettingsHandler_PatrolReadinessBranches(t *testing.T) {t.Parallel()@@ -364,6 +557,23 @@ func TestAISettingsHandler_PatrolReadinessBranches(t *testing.T) {}}+func TestAISettingsHandler_PatrolReadinessMissingAssistantServiceUsesNativeSurfaceIdentity(t *testing.T) {+ t.Parallel()++ handler := &AISettingsHandler{}+ readiness := handler.buildPatrolReadiness(context.Background(), nil, true)++ require.Equal(t, patrolReadinessNotReady, readiness.Status)+ require.False(t, readiness.Ready)+ require.Equal(t, "Pulse Assistant runtime service is not available.", readiness.Summary)+ require.NotContains(t, readiness.Summary, "Pulse AI")++ check := requirePatrolReadinessCheck(t, readiness, "service")+ require.Equal(t, "Assistant runtime service", check.Label)+ require.Equal(t, "Pulse Assistant runtime service is not available.", check.Message)+ require.NotContains(t, check.Message, "Pulse AI")+}+func TestAISettingsHandler_PatrolReadinessNotReadyTakesPrecedenceOverWarnings(t *testing.T) {readiness := summarizePatrolReadiness("ollama", "ollama:llama3", []PatrolReadinessCheck{{ID: "tools", Status: patrolReadinessWarning, Message: "warning message"},@@ -1124,6 +1334,9 @@ func TestNormalizeAIExecuteTargetType_StrictCanonicalV6(t *testing.T) {if got != tt.want {t.Fatalf("normalizeAIExecuteTargetType(%q) = %q, want %q", tt.in, got, tt.want)}+ if shared := agentcapabilities.NormalizeActionTargetType(tt.in); got != shared {+ t.Fatalf("normalizeAIExecuteTargetType(%q) = %q, shared contract returned %q", tt.in, got, shared)+ }}}@@ -2934,6 +3147,47 @@ func TestAISettingsHandler_Approvals(t *testing.T) {assert.Equal(t, "too dangerous", app.DenyReason)})+ t.Run("HandleDenyCommand_RecordsRejectedInvestigationOutcome", func(t *testing.T) {+ findingID := "finding-denied-fix"+ handler.SetStateProvider(&MockStateProvider{})+ patrol := handler.defaultAIService.GetPatrolService()+ require.NotNil(t, patrol)+ patrol.GetFindings().Add(&ai.Finding{+ ID: findingID,+ ResourceID: "vm:100",+ ResourceName: "web-100",+ ResourceType: "vm",+ Severity: ai.FindingSeverityWarning,+ Category: ai.FindingCategoryPerformance,+ Title: "High CPU",+ Description: "CPU stayed high.",+ InvestigationStatus: string(ai.InvestigationStatusCompleted),+ InvestigationOutcome: string(ai.InvestigationOutcomeFixQueued),+ })+ appIDRejected := "app-investigation-deny"+ _ = approvalStore.CreateApproval(&approval.ApprovalRequest{+ ID: appIDRejected,+ ToolID: "investigation_fix",+ Command: "systemctl restart workload.service",+ TargetType: "investigation",+ TargetID: findingID,+ TargetName: "web-100",+ Context: "Automated fix from patrol investigation: restart workload",+ Status: approval.StatusPending,+ })++ body, _ := json.Marshal(map[string]string{"reason": "outside maintenance"})+ req := newLoopbackRequest(http.MethodPost, "/api/ai/approvals/"+appIDRejected+"/deny", bytes.NewReader(body))+ rec := httptest.NewRecorder()+ handler.HandleDenyCommand(rec, req)++ assert.Equal(t, http.StatusOK, rec.Code)+ updated := patrol.GetFindings().Get(findingID)+ require.NotNil(t, updated)+ assert.Equal(t, string(ai.InvestigationOutcomeFixRejected), updated.InvestigationOutcome)+ assert.Equal(t, string(ai.FindingLoopStateNeedsAttention), updated.LoopState)+ })+t.Run("HandleApproveCommand_AcceptsRelayMobileScope", func(t *testing.T) {appID3 := "app-789"_ = approvalStore.CreateApproval(&approval.ApprovalRequest{@@ -3321,25 +3575,46 @@ func TestAISettingsHandler_PatrolPreflight_RejectsInvalidProviderName(t *testing// GetMessages mirror between orchestratorChatAdapter (ai_handlers.go) and// chatServiceAdapter (chat_service_adapter.go) honest: both convert the same// chat-service messages onto separate output contracts, and a field mapped by-// one must be mapped by the other.+// one must be mapped by the other. chatServiceAdapter routes through+// adaptChatMessage so its API-facing tool calls stay on the shared provider+// shape instead of hand-copying a local duplicate.func TestOrchestratorAndChatAdaptersMapTheSameMessageFields(t *testing.T) {- requiredMappings := []string{- "ID:",- "Role:",- "Content:",- "ReasoningContent:",- "Timestamp:",- "ToolUseID:",- "IsError:",- ".NormalizeCollections()",- }-for _, tc := range []struct {- file string- fn string+ file string+ fn string+ label string+ required []string}{- {"ai_handlers.go", "func (a *orchestratorChatAdapter) GetMessages("},- {"chat_service_adapter.go", "func (a *chatServiceAdapter) GetMessages("},+ {+ file: "ai_handlers.go",+ fn: "func (a *orchestratorChatAdapter) GetMessages(",+ label: "orchestratorChatAdapter.GetMessages",+ required: []string{+ "ID:",+ "Role:",+ "Content:",+ "ReasoningContent:",+ "Timestamp:",+ "aicontracts.OrchestratorToolCallInfoFromProvider(tc.ProviderToolCall())",+ "aicontracts.OrchestratorToolResultInfoFromProvider(*msg.ToolResult)",+ ".NormalizeCollections()",+ },+ },+ {+ file: "chat_service_adapter.go",+ fn: "func adaptChatMessage(",+ label: "adaptChatMessage",+ required: []string{+ "ID:",+ "Role:",+ "Content:",+ "ReasoningContent:",+ "Timestamp:",+ "tc.ProviderToolCall()",+ "toolResult := *m.ToolResult",+ ".NormalizeCollections()",+ },+ },} {source, err := os.ReadFile(tc.file)if err != nil {@@ -3355,10 +3630,18 @@ func TestOrchestratorAndChatAdaptersMapTheSameMessageFields(t *testing.T) {end = len(text) - start}body := text[start : start+end]- for _, required := range requiredMappings {+ for _, required := range tc.required {if !strings.Contains(body, required) {- t.Errorf("%s GetMessages must map %q — keep the adapter mirror in sync", tc.file, required)+ t.Errorf("%s %s must map %q — keep the adapter mirror in sync", tc.file, tc.label, required)}}}++ chatAdapter, err := os.ReadFile("chat_service_adapter.go")+ if err != nil {+ t.Fatalf("read chat_service_adapter.go: %v", err)+ }+ if !strings.Contains(string(chatAdapter), "result[i] = adaptChatMessage(m)") {+ t.Error("chatServiceAdapter.GetMessages must route through adaptChatMessage")+ }}diff --git a/internal/api/ai_patrol_handlers_test.go b/internal/api/ai_patrol_handlers_test.goindex 41dc597820..dfcaa362a2 100644--- a/internal/api/ai_patrol_handlers_test.go+++ b/internal/api/ai_patrol_handlers_test.go@@ -117,7 +117,7 @@ func TestHandleGetPatrolStatus_NoAIService(t *testing.T) {if resp.Readiness.Status != patrolReadinessNotReady {t.Fatalf("readiness status = %q, want %q", resp.Readiness.Status, patrolReadinessNotReady)}- if check := requirePatrolReadinessCheck(t, *resp.Readiness, "service"); check.Message != "Pulse AI runtime service is not available." {+ if check := requirePatrolReadinessCheck(t, *resp.Readiness, "service"); check.Message != "Pulse Assistant runtime service is not available." {t.Fatalf("service readiness message = %q", check.Message)}}diff --git a/internal/api/ai_resource_types.go b/internal/api/ai_resource_types.goindex 48c307cb83..432f0e738d 100644--- a/internal/api/ai_resource_types.go+++ b/internal/api/ai_resource_types.go@@ -1,12 +1,7 @@package api-import "strings"+import "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"func normalizeAITransportResourceType(raw string) string {- switch strings.ToLower(strings.TrimSpace(raw)) {- case "truenas":- return "agent"- default:- return strings.ToLower(strings.TrimSpace(raw))- }+ return agentcapabilities.NormalizeActionResourceType(raw)}diff --git a/internal/api/chat_service_adapter.go b/internal/api/chat_service_adapter.goindex 43fc8fd10a..184705210e 100644--- a/internal/api/chat_service_adapter.go+++ b/internal/api/chat_service_adapter.go@@ -67,32 +67,29 @@ func (a *chatServiceAdapter) GetMessages(ctx context.Context, sessionID string)}result := make([]ai.ChatMessage, len(messages))for i, m := range messages {- msg := ai.ChatMessage{- ID: m.ID,- Role: m.Role,- Content: m.Content,- ReasoningContent: m.ReasoningContent,- Timestamp: m.Timestamp,- }- for _, tc := range m.ToolCalls {- msg.ToolCalls = append(msg.ToolCalls, ai.ChatToolCall{- ID: tc.ID,- Name: tc.Name,- Input: tc.Input,- })- }- if m.ToolResult != nil {- msg.ToolResult = &ai.ChatToolResult{- ToolUseID: m.ToolResult.ToolUseID,- Content: m.ToolResult.Content,- IsError: m.ToolResult.IsError,- }- }- result[i] = msg.NormalizeCollections()+ result[i] = adaptChatMessage(m)}return result, nil}+func adaptChatMessage(m chat.Message) ai.ChatMessage {+ msg := ai.ChatMessage{+ ID: m.ID,+ Role: m.Role,+ Content: m.Content,+ ReasoningContent: m.ReasoningContent,+ Timestamp: m.Timestamp,+ }+ for _, tc := range m.ToolCalls {+ msg.ToolCalls = append(msg.ToolCalls, tc.ProviderToolCall())+ }+ if m.ToolResult != nil {+ toolResult := *m.ToolResult+ msg.ToolResult = &toolResult+ }+ return msg.NormalizeCollections()+}+func (a *chatServiceAdapter) DeleteSession(ctx context.Context, sessionID string) error {return a.svc.DeleteSession(ctx, sessionID)}diff --git a/internal/api/chat_service_adapter_test.go b/internal/api/chat_service_adapter_test.goindex c4504936f0..7effa9df5e 100644--- a/internal/api/chat_service_adapter_test.go+++ b/internal/api/chat_service_adapter_test.go@@ -2,8 +2,12 @@ package apiimport ("context"+ "encoding/json"+ "strings""testing"+ "time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/ai/chat""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/stretchr/testify/assert"@@ -95,6 +99,64 @@ func TestChatServiceAdapter_GetMessages(t *testing.T) {require.NoError(t, err)}+func TestAdaptChatMessageUsesSharedProviderToolCallShape(t *testing.T) {+ success := true+ msg := adaptChatMessage(chat.Message{+ ID: "msg-1",+ Role: "assistant",+ Content: "checking",+ Timestamp: time.Unix(100, 0),+ ToolCalls: []chat.ToolCall{{+ ID: "call-1",+ Name: "diagnose",+ Output: "in-app only",+ Success: &success,+ ThoughtSignature: json.RawMessage(`{"provider":"gemini"}`),+ }},+ ToolResult: &chat.ToolResult{+ ToolUseID: "call-1",+ Content: "done",+ IsError: true,+ },+ })++ require.Len(t, msg.ToolCalls, 1)+ var shared agentcapabilities.ProviderToolCall = msg.ToolCalls[0]+ assert.Equal(t, "call-1", shared.ID)+ assert.Equal(t, "diagnose", shared.Name)+ assert.NotNil(t, shared.Input)++ payload, err := json.Marshal(msg.ToolCalls[0])+ require.NoError(t, err)+ text := string(payload)+ assert.Contains(t, text, `"input":{}`)+ assert.Contains(t, text, `"thought_signature":{"provider":"gemini"}`)+ assert.False(t, strings.Contains(text, `"output"`), text)+ assert.False(t, strings.Contains(text, `"success"`), text)++ require.NotNil(t, msg.ToolResult)+ var sharedResult agentcapabilities.ProviderToolResult = *msg.ToolResult+ assert.Equal(t, "call-1", sharedResult.ToolUseID)+ assert.True(t, sharedResult.IsError)+}++func TestAdaptChatMessageDoesNotAliasToolCallInput(t *testing.T) {+ input := map[string]interface{}{"resource_id": "vm/100"}+ msg := adaptChatMessage(chat.Message{+ ID: "msg-1",+ Role: "assistant",+ ToolCalls: []chat.ToolCall{{+ ID: "call-1",+ Name: "diagnose",+ Input: input,+ }},+ })++ require.Len(t, msg.ToolCalls, 1)+ msg.ToolCalls[0].Input["resource_id"] = "vm/101"+ assert.Equal(t, "vm/100", input["resource_id"])+}+func TestChatServiceAdapter_ReloadConfig(t *testing.T) {cfg := chat.Config{DataDir: t.TempDir(),diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex a345b97efc..43629afdb3 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -23,6 +23,7 @@ import ("github.com/golang-jwt/jwt/v5""github.com/gorilla/websocket""github.com/rcourtman/pulse-go-rewrite/internal/actionplanner"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/ai""github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"@@ -1043,6 +1044,63 @@ func TestContractAISettingsClampsPaidRuntimeControlsToEntitlements(t *testing.T)}}+func TestContractAnthropicOAuthSetupEndpointsFailClosedPayload(t *testing.T) {+ handler := &AISettingsHandler{}++ tests := []struct {+ name string+ method string+ path string+ body string+ call func(http.ResponseWriter, *http.Request)+ }{+ {+ name: "start",+ method: http.MethodGet,+ path: "/api/ai/oauth/start",+ call: handler.HandleOAuthStart,+ },+ {+ name: "exchange",+ method: http.MethodPost,+ path: "/api/ai/oauth/exchange",+ body: `{"code":"code","state":"state"}`,+ call: handler.HandleOAuthExchange,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ req := newLoopbackRequest(tt.method, tt.path, strings.NewReader(tt.body))+ rec := httptest.NewRecorder()++ tt.call(rec, req)++ if rec.Code != http.StatusNotImplemented {+ t.Fatalf("status=%d, want %d: %s", rec.Code, http.StatusNotImplemented, rec.Body.String())+ }++ var resp struct {+ Success bool `json:"success"`+ Error string `json:"error"`+ Message string `json:"message"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if resp.Success {+ t.Fatal("unsupported OAuth response must not report success")+ }+ if resp.Error != "unsupported_anthropic_oauth" {+ t.Fatalf("error=%q, want unsupported_anthropic_oauth", resp.Error)+ }+ if !strings.Contains(resp.Message, "Configure an Anthropic API key") {+ t.Fatalf("message must direct operators to API-key setup, got %q", resp.Message)+ }+ })+ }+}+func sortedVMChartKeys(values map[string]VMChartData) []string {keys := make([]string, 0, len(values))for key := range values {@@ -1190,6 +1248,19 @@ func TestContract_WireAIChatDependencies_WiresTrueNASAppActionProvider(t *testin}}+func TestContract_AITransportResourceTypeUsesSharedActionResourceVocabulary(t *testing.T) {+ for _, input := range []string{"truenas", "SYSTEM-CONTAINER", "app-container", "host"} {+ got := normalizeAITransportResourceType(input)+ want := agentcapabilities.NormalizeActionResourceType(input)+ if got != want {+ t.Fatalf("normalizeAITransportResourceType(%q) = %q, want shared action resource type %q", input, got, want)+ }+ }+ if got := normalizeAITransportResourceType("truenas"); got != agentcapabilities.ActionTargetTypeAgent {+ t.Fatalf("truenas resource type = %q, want %q", got, agentcapabilities.ActionTargetTypeAgent)+ }+}+func TestContract_ChatServiceAdapterPatrolForwardsExecutionID(t *testing.T) {cfg := chat.Config{DataDir: t.TempDir(),@@ -1348,7 +1419,7 @@ func TestContract_AISettingsUpdateProviderResolutionJSONSnapshot(t *testing.T) {"id":"configuration","status":"warning","cause":"model_tool_support_unverified",- "label":"Patrol configuration",+ "label":"Patrol control","message":"Ollama connectivity alone does not prove tool support. Use an Ollama model that returns tool_calls for Patrol verification."}]}@@ -1401,6 +1472,49 @@ func TestContract_PatrolStatusDoesNotSurfaceQuickstartActivation(t *testing.T) {}}+func TestContract_PatrolStatusMissingAssistantServiceUsesNativeSurfaceIdentity(t *testing.T) {+ handler := &AISettingsHandler{}++ req := httptest.NewRequest(http.MethodGet, "/api/ai/patrol/status", nil)+ rec := httptest.NewRecorder()+ handler.HandleGetPatrolStatus(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("status=%d, want %d: %s", rec.Code, http.StatusOK, rec.Body.String())+ }++ var resp PatrolStatusResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode patrol status: %v", err)+ }+ if resp.Readiness == nil {+ t.Fatal("expected readiness payload when Assistant service is missing")+ }+ if resp.Readiness.Summary != "Pulse Assistant runtime service is not available." {+ t.Fatalf("readiness summary = %q", resp.Readiness.Summary)+ }++ var serviceCheck *PatrolReadinessCheck+ for i := range resp.Readiness.Checks {+ if resp.Readiness.Checks[i].ID == "service" {+ serviceCheck = &resp.Readiness.Checks[i]+ break+ }+ }+ if serviceCheck == nil {+ t.Fatalf("service readiness check missing from %+v", resp.Readiness.Checks)+ }+ if serviceCheck.Label != "Assistant runtime service" {+ t.Fatalf("service readiness label = %q", serviceCheck.Label)+ }+ if serviceCheck.Message != "Pulse Assistant runtime service is not available." {+ t.Fatalf("service readiness message = %q", serviceCheck.Message)+ }+ if strings.Contains(rec.Body.String(), "Pulse AI") {+ t.Fatalf("patrol status payload must not expose legacy Pulse AI runtime identity: %s", rec.Body.String())+ }+}+func TestContract_AISettingsDoesNotExposeQuickstartActivation(t *testing.T) {tmp := t.TempDir()cfg := &config.Config{DataPath: tmp}@@ -6624,8 +6738,8 @@ func TestContract_SelfHostedCommunityEntitlementsJSONSnapshot(t *testing.T) {{"key":"push_notifications","reason":"Get Relay so important alerts reach you immediately on mobile instead of waiting for you to reopen Pulse.","action_url":"https://pulserelay.pro/pricing?utm_source=pulse\u0026utm_medium=app\u0026utm_campaign=upgrade\u0026feature=push_notifications"},{"key":"relay","reason":"Get Relay so Pulse stays reachable securely from anywhere instead of only on the local dashboard.","action_url":"https://pulserelay.pro/pricing?utm_source=pulse\u0026utm_medium=app\u0026utm_campaign=upgrade\u0026feature=relay"},{"key":"long_term_metrics","reason":"Get Relay for 14 days of history, or Pro for 90 days, so you can see what changed before and after an incident.","action_url":"https://pulserelay.pro/pricing?utm_source=pulse\u0026utm_medium=app\u0026utm_campaign=upgrade\u0026feature=long_term_metrics"},- {"key":"ai_autofix","reason":"Upgrade to Pro so Pulse can move from finding issues to governed remediation with your approval or autonomy policy.","action_url":"https://pulserelay.pro/pricing?utm_source=pulse\u0026utm_medium=app\u0026utm_campaign=upgrade\u0026feature=ai_autofix"},- {"key":"ai_alerts","reason":"Upgrade to Pro so alerts arrive with root-cause analysis instead of a stack of symptoms.","action_url":"https://pulserelay.pro/pricing?utm_source=pulse\u0026utm_medium=app\u0026utm_campaign=upgrade\u0026feature=ai_alerts"},+ {"key":"ai_autofix","reason":"Upgrade to Pro so Patrol can investigate issues, handle safe fixes within Patrol mode, and verify the outcome.","action_url":"https://pulserelay.pro/pricing?utm_source=pulse\u0026utm_medium=app\u0026utm_campaign=upgrade\u0026feature=ai_autofix"},+ {"key":"ai_alerts","reason":"Upgrade to Pro so Patrol can investigate issues instead of handing you a stack of symptoms.","action_url":"https://pulserelay.pro/pricing?utm_source=pulse\u0026utm_medium=app\u0026utm_campaign=upgrade\u0026feature=ai_alerts"},{"key":"rbac","reason":"Upgrade to Pro when more than one operator needs safe access boundaries around infrastructure changes.","action_url":"https://pulserelay.pro/pricing?utm_source=pulse\u0026utm_medium=app\u0026utm_campaign=upgrade\u0026feature=rbac"},{"key":"agent_profiles","reason":"Upgrade to Pro to standardize agent behavior across systems without reconfiguring every install by hand.","action_url":"https://pulserelay.pro/pricing?utm_source=pulse\u0026utm_medium=app\u0026utm_campaign=upgrade\u0026feature=agent_profiles"},{"key":"audit_logging","reason":"Upgrade to Pro to keep a trustworthy action trail for incident review, accountability, and compliance.","action_url":"https://pulserelay.pro/pricing?utm_source=pulse\u0026utm_medium=app\u0026utm_campaign=upgrade\u0026feature=audit_logging"},@@ -13343,7 +13457,7 @@ func TestContract_APIActionExecutionRevalidatesPlanFreshness(t *testing.T) {"errors.Is(err, unified.ErrActionPlanDrift)","recordRefusedActionExecution(store, record, actor, now, err)","unified.RefuseActionExecution(record, reason, actor, now)",- "writeJSONError(w, http.StatusConflict, \"action_plan_drift\"",+ "writeJSONError(w, http.StatusConflict, agentcapabilities.AgentErrCodeActionPlanDrift",} {if !strings.Contains(src, snippet) {t.Fatalf("actions.go must pin API execute plan freshness guard snippet %q", snippet)@@ -13355,21 +13469,28 @@ func TestContract_APIActionExecutionRevalidatesPlanFreshness(t *testing.T) {}}-func TestContract_ExecuteActionCapabilityDeclaresPlanExpired(t *testing.T) {- source, err := os.ReadFile("agent_capabilities.go")+func readAgentCapabilitiesManifestSource(t *testing.T) string {+ t.Helper()+ source, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "manifest.go"))if err != nil {- t.Fatalf("read agent_capabilities.go: %v", err)+ t.Fatalf("read shared agent capabilities manifest: %v", err)}- src := string(source)- start := strings.Index(src, `Name: "execute_action"`)- if start < 0 {- t.Fatal("agent capabilities manifest must declare execute_action")+ return string(source)+}++func TestContract_ExecuteActionCapabilityDeclaresPlanExpired(t *testing.T) {+ manifest := agentcapabilities.CanonicalManifest()+ var executeAction agentcapabilities.Capability+ for _, cap := range manifest.Capabilities {+ if cap.Name == agentcapabilities.ExecuteActionCapabilityName {+ executeAction = cap+ break+ }}- block := src[start:]- if end := strings.Index(block, "\n\t\t},"); end >= 0 {- block = block[:end]+ if executeAction.Name == "" {+ t.Fatalf("agent capabilities manifest must declare %s", agentcapabilities.ExecuteActionCapabilityName)}- if !strings.Contains(block, `"action_plan_expired"`) {+ if !stringSliceContains(executeAction.ErrorCodes, agentcapabilities.AgentErrCodeActionPlanExpired) {t.Error("execute_action manifest must declare action_plan_expired so agents can branch on permanent expired-plan refusals")}}@@ -14463,13 +14584,12 @@ func TestContract_ApprovalStorePostCreateCallback(t *testing.T) {// breaks every agent that branches on the SSE event-type field; the// constant is part of the contract, not an implementation detail.func TestContract_AgentEventApprovalPendingKindIsStable(t *testing.T) {- source, err := os.ReadFile("agent_events.go")- if err != nil {- t.Fatalf("read agent_events.go: %v", err)+ if AgentEventApprovalPending != AgentEventKind(agentcapabilities.EventKindApprovalPending) {+ t.Errorf("AgentEventApprovalPending = %q, want shared event kind %q",+ AgentEventApprovalPending, agentcapabilities.EventKindApprovalPending)}- src := string(source)- if !strings.Contains(src, `AgentEventApprovalPending AgentEventKind = "approval.pending"`) {- t.Error("AgentEventApprovalPending must remain bound to the wire-stable string \"approval.pending\" — renaming it breaks every agent that branches on the SSE event type")+ if string(AgentEventApprovalPending) != "approval.pending" {+ t.Errorf("AgentEventApprovalPending wire value = %q, want approval.pending", AgentEventApprovalPending)}}@@ -14480,12 +14600,11 @@ func TestContract_AgentEventApprovalPendingKindIsStable(t *testing.T) {// Drift here means external agents miss the event entirely because// they didn't know to listen for it.func TestContract_SubscribeEventsCapabilityListsApprovalPending(t *testing.T) {- source, err := os.ReadFile("agent_capabilities.go")- if err != nil {- t.Fatalf("read agent_capabilities.go: %v", err)+ capability, ok := agentcapabilities.FindCapability(agentcapabilities.CanonicalManifest().Capabilities, agentcapabilities.EventSubscriptionCapabilityName)+ if !ok {+ t.Fatal("canonical manifest must include subscribe_events")}- src := string(source)- if !strings.Contains(src, "approval.pending when a remediation request enters StatusPending") {+ if !strings.Contains(capability.Description, string(agentcapabilities.EventKindApprovalPending)+" when a remediation request enters StatusPending") {t.Error("subscribe_events description must mention approval.pending so agents discover the kind through the manifest")}}@@ -14550,6 +14669,117 @@ func TestContract_AgentEventsStreamPublishesOnActionCompleted(t *testing.T) {}}+// TestContract_ExternalAgentActivityUsesRouteSpecificMarkers pins the+// anonymous usage signal behind Pulse Intelligence external-agent telemetry:+// configured/readiness may come from token capability posture, but recent-use+// must come from authenticated calls into a manifest-backed agent/MCP+// capability route. Generic API-token LastUsedAt is too broad because the same+// token can hit unrelated routes; requiring every manifest scope is too narrow+// because read-only MCP clients are supported.+func TestContract_ExternalAgentActivityUsesRouteSpecificMarkers(t *testing.T) {+ activitySource, err := os.ReadFile("agent_activity_telemetry.go")+ if err != nil {+ t.Fatalf("read agent_activity_telemetry.go: %v", err)+ }+ activitySrc := string(activitySource)+ for _, required := range []string{+ "getAPITokenRecordFromRequest(req)",+ "externalAgentCapabilityActivity(capabilityName)",+ "agentcapabilities.FindCapability(agentcapabilities.CanonicalManifest().Capabilities, capabilityName)",+ "apiTokenCoversExternalAgentSurface(token, time.Now().UTC(), requiredScopes...)",+ "agentcapabilities.CanonicalManifest().RequiredScopes",+ "func externalAgentActivityForCapability(capabilityName string) (string, bool)",+ "persistence.RecordExternalAgentActivity(config.ExternalAgentActivityRecord{",+ } {+ if !strings.Contains(activitySrc, required) {+ t.Errorf("external-agent activity marker must stay token-scoped and manifest-capable; missing %s", required)+ }+ }+ readCapability, ok := agentcapabilities.FindCapability(agentcapabilities.CanonicalManifest().Capabilities, agentcapabilities.FleetContextCapabilityName)+ if !ok {+ t.Fatalf("manifest missing %s", agentcapabilities.FleetContextCapabilityName)+ }+ if _, requiredScope, ok := externalAgentCapabilityActivity(agentcapabilities.FleetContextCapabilityName); !ok || requiredScope != readCapability.Scope {+ t.Fatalf("external-agent activity must use the called capability scope, got scope=%q ok=%v want %q", requiredScope, ok, readCapability.Scope)+ }+ for _, capability := range agentcapabilities.ManifestSurfaceToolCapabilities(agentcapabilities.CanonicalManifest(), agentcapabilities.SurfaceIDPulseMCP) {+ if _, ok := externalAgentActivityForCapability(capability.Name); !ok {+ t.Errorf("MCP-published capability %q must have an external-agent activity class", capability.Name)+ }+ }++ routeFiles := []string{+ "router_routes_monitoring.go",+ "router_routes_registration.go",+ "router_routes_ai_relay.go",+ "router.go",+ }+ var routesBuilder strings.Builder+ for _, file := range routeFiles {+ routesSource, err := os.ReadFile(file)+ if err != nil {+ t.Fatalf("read %s: %v", file, err)+ }+ routesBuilder.Write(routesSource)+ }+ routesSrc := routesBuilder.String()+ for _, required := range []string{+ "agentcapabilities.ResourceContextCapabilityName",+ "agentcapabilities.FleetContextCapabilityName",+ "agentcapabilities.OperationsLoopStatusCapabilityName",+ "agentcapabilities.EventSubscriptionCapabilityName",+ "agentcapabilities.ListNodesCapabilityName",+ "agentcapabilities.AddNodeCapabilityName",+ "agentcapabilities.UpdateNodeCapabilityName",+ "agentcapabilities.RemoveNodeCapabilityName",+ "agentcapabilities.TestNodeCredentialsCapabilityName",+ "agentcapabilities.TestNodeConnectionCapabilityName",+ "agentcapabilities.RefreshNodeClusterMembershipCapabilityName",+ "agentcapabilities.DiscoverLANCapabilityName",+ "agentcapabilities.GetOperatorStateCapabilityName",+ "agentcapabilities.SetOperatorStateCapabilityName",+ "agentcapabilities.ClearOperatorStateCapabilityName",+ "agentcapabilities.ListFindingsCapabilityName",+ "agentcapabilities.AcknowledgeFindingCapabilityName",+ "agentcapabilities.SnoozeFindingCapabilityName",+ "agentcapabilities.DismissFindingCapabilityName",+ "agentcapabilities.ResolveFindingCapabilityName",+ "agentcapabilities.PlanActionCapabilityName",+ "agentcapabilities.DecideActionCapabilityName",+ "agentcapabilities.ExecuteActionCapabilityName",+ } {+ if !strings.Contains(routesSrc, required) {+ t.Errorf("manifest-backed external-agent routes must record capability-specific activity; missing %s", required)+ }+ }++ telemetrySource, err := os.ReadFile(filepath.Join("..", "..", "pkg", "server", "telemetry_pulse_intelligence.go"))+ if err != nil {+ t.Fatalf("read telemetry_pulse_intelligence.go: %v", err)+ }+ telemetrySrc := string(telemetrySource)+ if !strings.Contains(telemetrySrc, "persistence.LoadExternalAgentActivityHistory()") {+ t.Error("Pulse Intelligence external-agent recent-use telemetry must read route activity history")+ }+ for _, required := range []string{+ "pulseIntelligenceExternalAgentSurfaceScopes(agentcapabilities.CanonicalManifest())",+ "agentcapabilities.ManifestSurfaceToolCapabilities(manifest, agentcapabilities.SurfaceIDPulseMCP)",+ "agentcapabilities.RequiredCapabilityScopes(",+ "func pulseIntelligenceExternalAgentToken(token config.APITokenRecord, surfaceScopes []string, now time.Time) bool",+ "if token.HasScope(scope) {\n\t\t\treturn true",+ } {+ if !strings.Contains(telemetrySrc, required) {+ t.Errorf("Pulse Intelligence external-agent readiness telemetry must use MCP-published capability scopes; missing %s", required)+ }+ }+ if strings.Contains(telemetrySrc, "LastUsedAt != nil && !token.LastUsedAt.UTC().Before(since)") {+ t.Error("Pulse Intelligence external-agent recent-use telemetry must not infer usage from generic token LastUsedAt")+ }+ if strings.Contains(telemetrySrc, "requiredScopes := agentcapabilities.CanonicalManifest().RequiredScopes") {+ t.Error("Pulse Intelligence external-agent readiness telemetry must not require every manifest scope")+ }+}+// TestContract_ExecutorPostCompletionCallback pins the seam the SSE// bridge depends on. The executor must expose SetOnActionCompleted// and the action_audit hot path must dispatch the callback for every@@ -14598,13 +14828,12 @@ func TestContract_ExecutorPostCompletionCallback(t *testing.T) {// breaks every agent that branches on the SSE event-type field; the// constant is part of the contract, not an implementation detail.func TestContract_AgentEventActionCompletedKindIsStable(t *testing.T) {- source, err := os.ReadFile("agent_events.go")- if err != nil {- t.Fatalf("read agent_events.go: %v", err)+ if AgentEventActionCompleted != AgentEventKind(agentcapabilities.EventKindActionCompleted) {+ t.Errorf("AgentEventActionCompleted = %q, want shared event kind %q",+ AgentEventActionCompleted, agentcapabilities.EventKindActionCompleted)}- src := string(source)- if !strings.Contains(src, `AgentEventActionCompleted AgentEventKind = "action.completed"`) {- t.Error("AgentEventActionCompleted must remain bound to the wire-stable string \"action.completed\" — renaming it breaks every agent that branches on the SSE event type")+ if string(AgentEventActionCompleted) != "action.completed" {+ t.Errorf("AgentEventActionCompleted wire value = %q, want action.completed", AgentEventActionCompleted)}}@@ -14615,12 +14844,11 @@ func TestContract_AgentEventActionCompletedKindIsStable(t *testing.T) {// Drift here means external agents miss the event entirely because// they didn't know to listen for it.func TestContract_SubscribeEventsCapabilityListsActionCompleted(t *testing.T) {- source, err := os.ReadFile("agent_capabilities.go")- if err != nil {- t.Fatalf("read agent_capabilities.go: %v", err)+ capability, ok := agentcapabilities.FindCapability(agentcapabilities.CanonicalManifest().Capabilities, agentcapabilities.EventSubscriptionCapabilityName)+ if !ok {+ t.Fatal("canonical manifest must include subscribe_events")}- src := string(source)- if !strings.Contains(src, "action.completed when an action audit reaches a terminal state") {+ if !strings.Contains(capability.Description, string(agentcapabilities.EventKindActionCompleted)+" when an action audit reaches a terminal state") {t.Error("subscribe_events description must mention action.completed so agents discover the kind through the manifest")}}@@ -14632,181 +14860,3254 @@ func TestContract_SubscribeEventsCapabilityListsActionCompleted(t *testing.T) {// bumps it shows up as a test failure rather than silently breaking// every external agent that validates compatibility on startup.func TestContract_AgentCapabilitiesManifestVersionIsPinned(t *testing.T) {- source, err := os.ReadFile("agent_capabilities.go")- if err != nil {- t.Fatalf("read agent_capabilities.go: %v", err)- }- src := string(source)+ src := readAgentCapabilitiesManifestSource(t)if !strings.Contains(src, `Version: "v1"`) {t.Error("agent capabilities manifest must pin Version to v1; bumping is a breaking-change decision and should not happen silently")}+ for _, required := range []string{+ `SurfaceContract: SurfaceContract{`,+ `ID: "pulse_intelligence_core"`,+ `Label: "Pulse Intelligence Core"`,+ `ID: "pulse_patrol"`,+ `ID: SurfaceIDPulseAssistant`,+ `ID: SurfaceIDPulseMCP`,+ `InteractiveQuestions: true`,+ `CapabilityMetadata: true`,+ `SurfaceToolContracts: []SurfaceToolContract{`,+ `ToolNames: canonicalPulseMCPSurfaceToolNames(),`,+ `publishedSurfaceToolContracts := CloneSurfaceToolContracts(canonicalManifest.SurfaceToolContracts)`,+ `SurfaceToolContracts: CloneSurfaceToolContracts(surfaceToolContracts)`,+ `WorkflowPrompts:`,+ `ClonePulseWorkflowPrompts(ProjectPulseWorkflowPrompts(capabilities))`,+ } {+ if !strings.Contains(src, required) {+ t.Errorf("agent capabilities manifest must pin the Pulse Intelligence surface contract; missing %s", required)+ }+ }+ if strings.Contains(src, `ID: "pulse_patrol"`) {+ t.Error("Pulse Patrol must stay the primary built-in operator component, not be flattened into the compatibility access-path list")+ }// Capability surface anchors — these names are agent-stable// identifiers and renaming any of them breaks every external// integration. Pin them here so renames must be deliberate.required := []string{- "\"get_resource_context\"",- "\"get_operator_state\"",- "\"set_operator_state\"",- "\"clear_operator_state\"",- "\"list_findings\"",+ agentcapabilities.ResourceContextCapabilityName,+ agentcapabilities.GetOperatorStateCapabilityName,+ agentcapabilities.SetOperatorStateCapabilityName,+ agentcapabilities.ClearOperatorStateCapabilityName,+ agentcapabilities.ListFindingsCapabilityName,}+ manifest := agentcapabilities.CanonicalManifest()for _, name := range required {- if !strings.Contains(src, name) {- t.Errorf("agent capabilities manifest must declare canonical capability %s", name)+ if _, ok := agentcapabilities.FindCapability(manifest.Capabilities, name); !ok {+ t.Errorf("agent capabilities manifest must declare canonical capability %q", name)}}}-// TestContract_AgentCapabilitiesManifestDeclaresProvisioningSurface pins the-// node-lifecycle onboarding surface in the public agent manifest. This is the-// backend API payload proof required when the hand-authored manifest starts-// projecting /api/config/nodes and /api/discover to external agents.-func TestContract_AgentCapabilitiesManifestDeclaresProvisioningSurface(t *testing.T) {- source, err := os.ReadFile("agent_capabilities.go")+func TestContract_PulseIntelligenceSurfaceToolProjectionKeepsAssistantAndMCPDistinct(t *testing.T) {+ surfaceSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "surface_contract.go"))if err != nil {- t.Fatalf("read agent_capabilities.go: %v", err)+ t.Fatalf("read internal/agentcapabilities/surface_contract.go: %v", err)}- src := string(source)-- required := []string{- `"provisioning"`,- `"list_nodes"`,- `Path: "/api/config/nodes"`,- `Scope: "settings:read"`,- `"add_node"`,- `InputSchema: addNodeInputSchema()`,- `"update_node"`,- `InputSchema: updateNodeInputSchema()`,- `"remove_node"`,- `InputSchema: nodeIDInputSchema()`,- `"test_node_credentials"`,- `Path: "/api/config/nodes/test-config"`,- `"test_node_connection"`,- `Path: "/api/config/nodes/{nodeId}/test"`,- `"refresh_node_cluster_membership"`,- `Path: "/api/config/nodes/{nodeId}/refresh-cluster"`,- `"discover_lan"`,- `Path: "/api/discover"`,- `InputSchema: discoverLANInputSchema()`,- `"tokenValue"`,- `"additionalProperties": false`,+ surfaceContract := string(surfaceSource)+ for _, required := range []string{+ `type SurfaceToolContract struct`,+ `SurfaceToolSourceAssistantRegistry = "assistant_registry"`,+ `SurfaceToolSourceCapabilityManifest = "capability_manifest"`,+ `func ProjectPulseAssistantSurfaceToolContract(`,+ `func ProjectManifestSurfaceToolContract(`,+ `func ProjectManifestSurfaceToolContracts(`,+ `func ResolveManifestSurfaceToolContract(`,+ `func ProjectPulseIntelligenceSurfaceToolContracts(`,+ `type ResolvedSurfaceAffordanceContract struct`,+ `func ResolveSurfaceAffordanceContract(`,+ `ResolveSurfaceAffordanceContract(contract, SurfaceIDPulseAssistant, "")`,+ `ResolveSurfaceAffordanceContract(manifest.SurfaceContract, surface.ID, surface.Label)`,+ `func ManifestSurfaceAffordances(`,+ `func IntersectSurfaceAffordances(`,+ `IntersectSurfaceAffordances(resolvedSurface.Affordances, contract.Affordances)`,+ `ProviderToolNames(providerTools)`,+ `AssistantNativeProviderToolNames()`,+ `if !surface.Affordances.Tools`,+ `if !surface.Affordances.InteractiveQuestions`,+ `ToolNames: offeredNames`,+ `!surface.ExternalAdapter`,+ `FindManifestSurfaceToolContract(manifest, surface.ID)`,+ `requestResponseCapabilityNamesForNames(manifest.Capabilities, contract.ToolNames)`,+ `ProjectManifestSurfaceToolContract(manifest, surface.ID)`,+ } {+ if !strings.Contains(surfaceContract, required) {+ t.Errorf("agentcapabilities must own shared Assistant/MCP surface tool projection; missing %s", required)+ }}- for _, fragment := range required {- if !strings.Contains(src, fragment) {- t.Errorf("agent capabilities manifest must declare provisioning contract fragment %s", fragment)+ for _, forbidden := range []string{+ `func ProjectPulseMCPSurfaceToolContract(`,+ `projectManifestSurfaceToolContractFromCapabilities`,+ `requestResponseCapabilityNames(manifest.Capabilities)`,+ `ProjectManifestSurfaceToolContract(manifest, SurfaceIDPulseMCP)`,+ `ProjectTools(manifest.Capabilities)`,+ } {+ if strings.Contains(surfaceContract, forbidden) {+ t.Errorf("agentcapabilities surface resolver must not keep MCP-specific or raw-capability fallback projection; found %s", forbidden)}}-}-// TestContract_AgentResourceContextEndpointSurfacesStableShape pins-// the agent-paradigm substrate contract: the bundled endpoint must-// return arrays (never null) for activeFindings and recentActions so-// agents can iterate without nil-checking, must omit operatorState-// when no entry exists so agents can branch on field presence, and-// must preserve refusal-token prefixes verbatim so agents can branch-// on the stable code without parsing human messages. Without this-// pin, future refactors of the projection helpers could silently-// drift the wire shape and break external agent consumers.-func TestContract_AgentResourceContextEndpointSurfacesStableShape(t *testing.T) {- source, err := os.ReadFile("agent_resource_context.go")+ projectionSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "projection.go"))if err != nil {- t.Fatalf("read agent_resource_context.go: %v", err)- }- src := string(source)- // Always-array initialization for the iteration-safe contract.- if !regexp.MustCompile(`ActiveFindings:\s+\[\]AgentResourceFindingSnapshot\{\},`).MatchString(src) {- t.Error("activeFindings must default to an empty slice, not nil — agents iterate without nil-checks")+ t.Fatalf("read internal/agentcapabilities/projection.go: %v", err)}- if !regexp.MustCompile(`RecentActions:\s+\[\]AgentResourceActionSummary\{\},`).MatchString(src) {- t.Error("recentActions must default to an empty slice, not nil")+ projectionContract := string(projectionSource)+ for _, required := range []string{+ `ResolveManifestSurfaceToolContract(manifest, surfaceID)`,+ `ManifestSurfaceAffordances(manifest, contract.SurfaceID)`,+ `if !affordances.Tools`,+ } {+ if !strings.Contains(projectionContract, required) {+ t.Errorf("agentcapabilities projection must resolve external-surface tools through the normalized surface contract; missing %s", required)+ }}- // Server-computed maintenance-active flag — server pre-computes so- // agents don't re-evaluate timestamps client-side.- if !strings.Contains(src, "MaintenanceWindowActive: state.IsInMaintenanceAt(now)") {- t.Error("MaintenanceWindowActive must be computed server-side via state.IsInMaintenanceAt(now)")++ assistantProjectionSource, err := os.ReadFile(filepath.Join("..", "ai", "tools", "provider_projection.go"))+ if err != nil {+ t.Fatalf("read internal/ai/tools/provider_projection.go: %v", err)}- // Refusal-token preservation: ErrorMessage flows through verbatim- // from the audit record's ExecutionResult, no rewriting.- if !strings.Contains(src, "summary.ErrorMessage = audit.Result.ErrorMessage") {- t.Error("audit ErrorMessage must round-trip verbatim so refusal tokens (resource_remediation_locked:, plan_drift:) reach agents")+ assistantProjection := string(assistantProjectionSource)+ for _, required := range []string{+ `func (e *PulseToolExecutor) AssistantSurfaceToolContract(opts agentcapabilities.AssistantProviderToolOptions) agentcapabilities.SurfaceToolContract`,+ `agentcapabilities.ProjectPulseAssistantSurfaceToolContract(`,+ `agentcapabilities.CanonicalManifest().SurfaceContract`,+ `e.AssistantProviderTools(opts)`,+ } {+ if !strings.Contains(assistantProjection, required) {+ t.Errorf("Assistant executor must expose native surface projection through shared core contract; missing %s", required)+ }}- // pendingApprovals must initialize as an empty slice so agents- // iterate without nil-checking — same iteration-safe contract- // as activeFindings and recentActions.- if !regexp.MustCompile(`PendingApprovals:\s+\[\]AgentResourceApprovalSummary\{\},`).MatchString(src) {- t.Error("pendingApprovals must default to an empty slice, not nil — agents iterate without nil-checks")++ chatServiceSource, err := os.ReadFile(filepath.Join("..", "ai", "chat", "service.go"))+ if err != nil {+ t.Fatalf("read internal/ai/chat/service.go: %v", err)}- if !regexp.MustCompile(`ContextSections:\s+\[\]AgentResourceContextSection\{\},`).MatchString(src) {- t.Error("contextSections must default to an empty slice, not nil — resource-aware agents iterate without nil-checks")+ chatService := string(chatServiceSource)+ for _, required := range []string{+ `func (s *Service) AssistantSurfaceToolContract(_ context.Context) agentcapabilities.SurfaceToolContract`,+ `executor.AssistantSurfaceToolContract(agentcapabilities.AssistantProviderToolOptions{`,+ `IncludeQuestionTool: !s.isAutonomousModeEnabled(),`,+ } {+ if !strings.Contains(chatService, required) {+ t.Errorf("chat service must expose live native Assistant surface tools through the shared core contract; missing %s", required)+ }}- contextType := reflect.TypeOf(AgentResourceContext{})- operatorStateField, ok := contextType.FieldByName("OperatorState")- if !ok {- t.Fatal("AgentResourceContext must carry OperatorState")+ aiHandlerSource, err := os.ReadFile("ai_handler.go")+ if err != nil {+ t.Fatalf("read internal/api/ai_handler.go: %v", err)}- if operatorStateField.Type != reflect.TypeOf((*AgentResourceOperatorState)(nil)) ||- operatorStateField.Tag.Get("json") != "operatorState,omitempty" {- t.Error("operatorState must be an omitempty pointer so absent entries surface as a missing field")+ aiHandler := string(aiHandlerSource)+ for _, required := range []string{+ `AssistantSurfaceToolContract(ctx context.Context) agentcapabilities.SurfaceToolContract`,+ `func (h *AIHandler) HandleAssistantSurfaceTools(w http.ResponseWriter, r *http.Request)`,+ `svc.AssistantSurfaceToolContract(ctx)`,+ `Pulse Assistant is not running`,+ } {+ if !strings.Contains(aiHandler, required) {+ t.Errorf("AI handler must expose authenticated native Assistant surface tool contract from runtime service; missing %s", required)+ }}- discoveryReadinessField, ok := contextType.FieldByName("DiscoveryReadiness")- if !ok {- t.Fatal("AgentResourceContext must carry DiscoveryReadiness")++ aiRelaySource, err := os.ReadFile("router_routes_ai_relay.go")+ if err != nil {+ t.Fatalf("read internal/api/router_routes_ai_relay.go: %v", err)}- if discoveryReadinessField.Type != reflect.TypeOf((*AgentResourceDiscoveryReadiness)(nil)) ||- discoveryReadinessField.Tag.Get("json") != "discoveryReadiness,omitempty" {- t.Error("discoveryReadiness must be an omitempty pointer to the shared resource readiness projection")+ aiRelay := string(aiRelaySource)+ for _, required := range []string{+ `"/api/ai/assistant/surface-tools"`,+ `RequireScope(config.ScopeAIChat, r.aiHandler.HandleAssistantSurfaceTools)`,+ } {+ if !strings.Contains(aiRelay, required) {+ t.Errorf("Assistant surface tools endpoint must stay authenticated behind ai:chat route scope; missing %s", required)+ }}- pendingApprovalsField, ok := contextType.FieldByName("PendingApprovals")- if !ok {- t.Fatal("AgentResourceContext must carry PendingApprovals")++ manifest := agentcapabilities.CanonicalManifest()+ contracts := agentcapabilities.ProjectPulseIntelligenceSurfaceToolContracts(manifest, []agentcapabilities.ProviderTool{+ {Name: agentcapabilities.PulseQueryToolName},+ {Name: agentcapabilities.PulseReadToolName},+ agentcapabilities.NewPulseQuestionProviderTool(),+ })+ if len(contracts) != 2 {+ t.Fatalf("Pulse Intelligence surface tool contracts = %+v, want Assistant and MCP", contracts)}- if pendingApprovalsField.Type != reflect.TypeOf([]AgentResourceApprovalSummary{}) ||- pendingApprovalsField.Tag.Get("json") != "pendingApprovals" {- t.Error("AgentResourceContext must carry PendingApprovals as a stable []AgentResourceApprovalSummary field")++ bySurface := map[string]agentcapabilities.SurfaceToolContract{}+ for _, contract := range contracts {+ bySurface[contract.SurfaceID] = contract}- contextSectionsField, ok := contextType.FieldByName("ContextSections")- if !ok {- t.Fatal("AgentResourceContext must carry ContextSections")+ assistant := bySurface[agentcapabilities.SurfaceIDPulseAssistant]+ if assistant.ToolSource != agentcapabilities.SurfaceToolSourceAssistantRegistry {+ t.Fatalf("Assistant tool source = %q", assistant.ToolSource)}- if contextSectionsField.Type != reflect.TypeOf([]AgentResourceContextSection{}) ||- contextSectionsField.Tag.Get("json") != "contextSections" {- t.Error("AgentResourceContext must carry ContextSections as a stable []AgentResourceContextSection field")+ if !reflect.DeepEqual(assistant.ToolNames, []string{+ agentcapabilities.PulseQueryToolName,+ agentcapabilities.PulseReadToolName,+ agentcapabilities.PulseQuestionToolName,+ }) {+ t.Fatalf("Assistant surface tool names = %#v", assistant.ToolNames)}- if !strings.Contains(src, "type AgentResourceContextRedaction = agentcontext.Redaction") ||- !strings.Contains(src, "type AgentResourceContextFact = agentcontext.Fact") {- t.Error("AgentResourceContext context sections must expose the shared typed fact and redaction metadata")+ if !reflect.DeepEqual(assistant.NativeToolNames, []string{agentcapabilities.PulseQuestionToolName}) {+ t.Fatalf("Assistant native tool names = %#v", assistant.NativeToolNames)+ }+ if len(assistant.CapabilityNames) != 0 {+ t.Fatalf("Assistant surface must not duplicate MCP manifest capabilities: %#v", assistant.CapabilityNames)}-}-// TestContract_AgentResourceContextWiresApprovalsProvider pins the-// startup-time wire-up that lets the bundle endpoint surface pending-// approvals scoped to a resource. Drift here means the field always-// shows up as an empty array even when there ARE pending approvals,-// silently breaking the substrate's "everything an agent needs in-// one read" contract for the governance dimension.-//-// The wire-up has two halves: router.go installs the provider with-// a provider that delegates to named functions in-// agent_resource_context.go, and those functions apply the org and-// resource filters while supporting the fleet endpoint's bulk count-// projection. Both halves are pinned here so a refactor that moves-// the filter logic still passes the test only if the resulting code-// preserves the safety and scale properties.-func TestContract_AgentResourceContextWiresApprovalsProvider(t *testing.T) {- router, err := os.ReadFile("router.go")- if err != nil {- t.Fatalf("read router.go: %v", err)+ mcp := bySurface[agentcapabilities.SurfaceIDPulseMCP]+ if mcp.ToolSource != agentcapabilities.SurfaceToolSourceCapabilityManifest {+ t.Fatalf("MCP tool source = %q", mcp.ToolSource)}- if !strings.Contains(string(router), "r.agentContextHandler.SetApprovalsProvider(agentApprovalStoreProvider{})") {- t.Error("router.go must wire the approvals provider on the agent context handler so the bundle's pendingApprovals section is populated")+ if len(mcp.CapabilityNames) == 0 || len(mcp.ToolNames) != len(mcp.CapabilityNames) {+ t.Fatalf("MCP tools must be manifest request/response capabilities, got tools=%#v capabilities=%#v", mcp.ToolNames, mcp.CapabilityNames)}- if !strings.Contains(string(router), "approval.SetStore") {- t.Error("router.go must keep documenting that the agent approval provider resolves the process-global approval store at request time")+ if !reflect.DeepEqual(mcp.ToolNames, manifest.SurfaceToolContracts[0].ToolNames) {+ t.Fatalf("MCP tools must come from manifest-published surface contract, got tools=%#v published=%#v", mcp.ToolNames, manifest.SurfaceToolContracts[0].ToolNames)}-- bundle, err := os.ReadFile("agent_resource_context.go")- if err != nil {+ for _, forbidden := range []string{+ agentcapabilities.PulseQuestionToolName,+ agentcapabilities.EventSubscriptionCapabilityName,+ } {+ if stringSliceContains(mcp.ToolNames, forbidden) {+ t.Fatalf("MCP tools must not include %s; names=%#v", forbidden, mcp.ToolNames)+ }+ }+ if len(mcp.RegistryToolNames) != 0 || len(mcp.NativeToolNames) != 0 {+ t.Fatalf("MCP surface must not expose Assistant registry/native tool buckets: %+v", mcp)+ }++ disabledManifest := manifest+ disabledManifest.SurfaceContract = agentcapabilities.CloneSurfaceContract(manifest.SurfaceContract)+ for i := range disabledManifest.SurfaceContract.OperatorSurfaces {+ if disabledManifest.SurfaceContract.OperatorSurfaces[i].ID == agentcapabilities.SurfaceIDPulseMCP {+ disabledManifest.SurfaceContract.OperatorSurfaces[i].Affordances = agentcapabilities.SurfaceAffordanceContract{+ Resources: true,+ Prompts: true,+ CapabilityMetadata: true,+ }+ }+ }+ disabledContracts := agentcapabilities.ProjectPulseIntelligenceSurfaceToolContracts(disabledManifest, []agentcapabilities.ProviderTool{+ {Name: agentcapabilities.PulseQueryToolName},+ agentcapabilities.NewPulseQuestionProviderTool(),+ })+ disabledBySurface := map[string]agentcapabilities.SurfaceToolContract{}+ for _, contract := range disabledContracts {+ disabledBySurface[contract.SurfaceID] = contract+ }+ disabledMCP := disabledBySurface[agentcapabilities.SurfaceIDPulseMCP]+ if disabledMCP.Affordances.Tools || len(disabledMCP.ToolNames) != 0 || len(disabledMCP.CapabilityNames) != 0 {+ t.Fatalf("MCP disabled tools affordance must clear static surface tools, got %+v", disabledMCP)+ }+}++func TestContract_AgentCapabilitiesManifestScopesUseAuthConstants(t *testing.T) {+ src := readAgentCapabilitiesManifestSource(t)+ for _, required := range []string{+ `agentCapabilityScopeMonitoringRead = auth.ScopeMonitoringRead`,+ `agentCapabilityScopeMonitoringWrite = auth.ScopeMonitoringWrite`,+ `agentCapabilityScopeSettingsRead = auth.ScopeSettingsRead`,+ `agentCapabilityScopeSettingsWrite = auth.ScopeSettingsWrite`,+ `agentCapabilityScopeAIExecute = auth.ScopeAIExecute`,+ } {+ if !strings.Contains(src, required) {+ t.Errorf("agent capabilities manifest must pin scope vocabulary to pkg/auth; missing %s", required)+ }+ }+ if strings.Contains(src, `Scope: "`) || strings.Contains(src, `Scope: "`) {+ t.Error("agent capabilities manifest must not declare scope values as local string literals")+ }++ known := map[string]bool{}+ for _, scope := range authpkg.AllKnownScopes {+ known[scope] = true+ }+ for _, cap := range agentcapabilities.CanonicalManifest().Capabilities {+ if !known[cap.Scope] {+ t.Errorf("capability %q scope = %q, want auth-owned scope vocabulary", cap.Name, cap.Scope)+ }+ }+}++func TestContract_AgentCapabilitiesFrontendTypesAreGeneratedFromManifest(t *testing.T) {+ generatorSource, err := os.ReadFile(filepath.Join("..", "..", "scripts", "generate-types.go"))+ if err != nil {+ t.Fatalf("read scripts/generate-types.go: %v", err)+ }+ generator := string(generatorSource)+ for _, required := range []string{+ `"github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"`,+ `filepath.Join("frontend-modern", "src", "api", "generated", "agentCapabilities.ts")`,+ `reflect.TypeOf(agentcapabilities.Capability{})`,+ `reflect.TypeOf(agentcapabilities.CapabilityCategory{})`,+ `reflect.TypeOf(agentcapabilities.Manifest{})`,+ `reflect.TypeOf(agentcapabilities.MCPAdapterConfigFamily{})`,+ `reflect.TypeOf(agentcapabilities.MCPAdapterContract{})`,+ `reflect.TypeOf(agentcapabilities.OperatorSurfaceContract{})`,+ `reflect.TypeOf(agentcapabilities.PulseWorkflowPrompt{})`,+ `reflect.TypeOf(agentcapabilities.PulseWorkflowPromptArgument{})`,+ `reflect.TypeOf(agentcapabilities.SurfaceAffordanceContract{})`,+ `reflect.TypeOf(agentcapabilities.SurfaceContract{})`,+ `reflect.TypeOf(agentcapabilities.SurfaceContractComponent{})`,+ `reflect.TypeOf(agentcapabilities.SurfaceToolContract{})`,+ `func agentCapabilitiesAliases() string`,+ `return "AgentCapabilityActionMode"`,+ `return "AgentCapabilityApprovalPolicy"`,+ `return "Record<string, unknown>"`,+ } {+ if !strings.Contains(generator, required) {+ t.Errorf("generate-types.go must derive frontend agent capabilities types from internal/agentcapabilities; missing %s", required)+ }+ }++ generatedSource, err := os.ReadFile(filepath.Join("..", "..", "frontend-modern", "src", "api", "generated", "agentCapabilities.ts"))+ if err != nil {+ t.Fatalf("read generated agent capabilities frontend types: %v", err)+ }+ generated := string(generatedSource)+ for _, required := range []string{+ `// This file is generated from scripts/generate-types.go; DO NOT EDIT.`,+ `// Source: internal/agentcapabilities manifest structs.`,+ `export type AgentCapabilityActionMode = 'read' | 'mixed' | 'write';`,+ `export type AgentCapabilityApprovalPolicy = 'scope_only' | 'action_plan';`,+ `export interface Capability {`,+ `title?: string;`,+ `actionMode: AgentCapabilityActionMode;`,+ `approvalPolicy: AgentCapabilityApprovalPolicy;`,+ `inputSchema?: Record<string, unknown>;`,+ `outputSchema?: Record<string, unknown>;`,+ `export interface CapabilityCategory {`,+ `export interface MCPAdapterConfigFamily {`,+ `clientLabels?: string[];`,+ `export interface MCPAdapterContract {`,+ `serverName: string;`,+ `command: string;`,+ `baseUrlFlag: string;`,+ `defaultBaseUrl: string;`,+ `tokenEnv: string;`,+ `configFamilies: MCPAdapterConfigFamily[];`,+ `export interface Manifest {`,+ `surfaceContract: SurfaceContract;`,+ `surfaceToolContracts: SurfaceToolContract[];`,+ `mcpAdapter: MCPAdapterContract;`,+ `requiredScopes: string[];`,+ `categories: CapabilityCategory[];`,+ `workflowPrompts: PulseWorkflowPrompt[];`,+ `capabilities: Capability[];`,+ `export interface PulseWorkflowPrompt {`,+ `label?: string;`,+ `presentationKind?: string;`,+ `arguments?: PulseWorkflowPromptArgument[];`,+ `export interface PulseWorkflowPromptArgument {`,+ `export interface SurfaceContract {`,+ `core: SurfaceContractComponent;`,+ `proactiveEngine: SurfaceContractComponent;`,+ `operatorSurfaces: OperatorSurfaceContract[];`,+ `export interface OperatorSurfaceContract {`,+ `native: boolean;`,+ `externalAdapter: boolean;`,+ `affordances?: SurfaceAffordanceContract;`,+ `export interface SurfaceAffordanceContract {`,+ `interactiveQuestions?: boolean;`,+ `export interface SurfaceToolContract {`,+ `surfaceId: string;`,+ `toolSource: string;`,+ `toolNames: string[];`,+ `registryToolNames?: string[];`,+ `capabilityNames?: string[];`,+ `nativeToolNames?: string[];`,+ } {+ if !strings.Contains(generated, required) {+ t.Errorf("generated agent capabilities frontend types drifted from manifest contract; missing %s", required)+ }+ }++ clientSource, err := os.ReadFile(filepath.Join("..", "..", "frontend-modern", "src", "api", "agentCapabilities.ts"))+ if err != nil {+ t.Fatalf("read frontend agent capabilities client: %v", err)+ }+ client := string(clientSource)+ for _, required := range []string{+ `from './generated/agentCapabilities'`,+ `export type AgentCapability = Capability;`,+ `export type AgentCapabilityCategory = CapabilityCategory;`,+ `export type AgentCapabilitiesManifest = Manifest;`,+ `export type AgentMCPAdapterConfigFamily = MCPAdapterConfigFamily;`,+ `export type AgentMCPAdapterContract = MCPAdapterContract;`,+ `export type AgentOperatorSurfaceContract = OperatorSurfaceContract;`,+ `export type AgentWorkflowPrompt = PulseWorkflowPrompt;`,+ `export type AgentWorkflowPromptArgument = PulseWorkflowPromptArgument;`,+ `export type AgentSurfaceAffordanceContract = SurfaceAffordanceContract;`,+ `export type AgentSurfaceContractComponent = SurfaceContractComponent;`,+ `export type AgentSurfaceToolContract = SurfaceToolContract;`,+ `export interface AgentSurfaceToolPosturePresentation {`,+ `export interface AgentSurfaceContractEntry {`,+ `normalizeAgentSurfaceToolContract(`,+ `findAgentSurfaceToolContract(`,+ `getAgentManifestSurfaceToolContract(`,+ `getAgentManifestSurfaceToolContracts(`,+ `getAgentSurfaceToolPosturePresentation(`,+ `normalizeAgentMCPAdapter(`,+ `getAgentMCPClientExamples(`,+ `formatAgentOpenCodeMCPConfig(`,+ `formatAgentMCPServersConfig(`,+ `getAgentSurfaceContractEntries(`,+ `getAgentWorkflowPrompts(`,+ `normalizeSurfaceAffordances(`,+ `surfaceAffordanceLabels(`,+ `manifest?.workflowPrompts`,+ `manifest.surfaceContract?.core`,+ `manifest.surfaceContract?.proactiveEngine`,+ `manifest.surfaceContract?.operatorSurfaces`,+ `manifest?.surfaceToolContracts`,+ `manifest?.mcpAdapter`,+ } {+ if !strings.Contains(client, required) {+ t.Errorf("frontend agent capabilities client must consume generated manifest types; missing %s", required)+ }+ }+ for _, forbidden := range []string{+ `export interface AgentCapability {`,+ `export interface AgentCapabilityCategory {`,+ `export interface AgentCapabilitiesManifest {`,+ `export interface AgentMCPAdapterContract {`,+ `AGENT_CAPABILITY_NAME_SUBSCRIBE_EVENTS`,+ `getRequestResponseCapabilityNames(`,+ `isRequestResponseAgentCapability(`,+ `getAgentMCPSurfaceToolContract(`,+ `subscribe_events`,+ } {+ if strings.Contains(client, forbidden) {+ t.Errorf("frontend agent capabilities client must not redeclare manifest types locally; found %s", forbidden)+ }+ }++ panelSource, err := os.ReadFile(filepath.Join("..", "..", "frontend-modern", "src", "components", "Settings", "AgentIntegrationsPanel.tsx"))+ if err != nil {+ t.Fatalf("read AgentIntegrationsPanel.tsx: %v", err)+ }+ panel := string(panelSource)+ for _, required := range []string{+ `getAgentSurfaceContractEntries`,+ `normalizeAgentMCPAdapter`,+ `formatAgentOpenCodeMCPConfig`,+ `formatAgentMCPServersConfig`,+ `AGENT_SURFACE_ID_PULSE_MCP`,+ `getAgentManifestSurfaceToolContract`,+ `getAgentSurfaceToolPosturePresentation`,+ `surfaceContractEntries`,+ `mcpSurfaceToolPosture`,+ `data-testid="agent-mcp-tool-posture"`,+ `External agents expose`,+ } {+ if !strings.Contains(panel, required) {+ t.Errorf("Agent integrations panel must project the manifest surface contract through the shared client; missing %s", required)+ }+ }+ for _, forbidden := range []string{+ `Pulse Intelligence Core`,+ `Pulse Assistant`,+ `Pulse Patrol`,+ `Pulse MCP`,+ } {+ if strings.Contains(panel, forbidden) {+ t.Errorf("Agent integrations panel must not duplicate manifest surface labels locally; found %s", forbidden)+ }+ }+ for _, forbidden := range []string{+ `const MCP_CLIENT_EXAMPLES`,+ `function formatClaudeMcpConfig`,+ `function formatOpenCodeMcpConfig`,+ `command: 'pulse-mcp'`,+ `PULSE_API_TOKEN: '<your-api-token>'`,+ `getAgentMCPClientExamples`,+ `getAgentMCPSurfaceToolContract`,+ `subscribe_events`,+ `capability.name`,+ } {+ if strings.Contains(panel, forbidden) {+ t.Errorf("Agent integrations panel must consume manifest-backed MCP adapter helpers instead of local setup snippets; found %s", forbidden)+ }+ }++ assistantChatSource, err := os.ReadFile(filepath.Join("..", "..", "frontend-modern", "src", "components", "AI", "Chat", "index.tsx"))+ if err != nil {+ t.Fatalf("read AI Chat index.tsx: %v", err)+ }+ assistantChat := string(assistantChatSource)+ for _, required := range []string{+ `getAgentSurfaceToolPosturePresentation`,+ `type AgentSurfaceToolContract`,+ `AIChatAPI.getAssistantSurfaceTools()`,+ `data-testid="assistant-surface-tools-health"`,+ } {+ if !strings.Contains(assistantChat, required) {+ t.Errorf("Assistant chat shell must consume the authenticated runtime surface-tool contract through the shared frontend client; missing %s", required)+ }+ }+ for _, forbidden := range []string{+ `'pulse_query'`,+ `"pulse_query"`,+ `'pulse_read'`,+ `"pulse_read"`,+ `'pulse_question'`,+ `"pulse_question"`,+ } {+ if strings.Contains(assistantChat, forbidden) {+ t.Errorf("Assistant chat shell must not hardcode native Assistant tool names for surface posture; found %s", forbidden)+ }+ }+}++func TestContract_AgentCapabilitiesPatrolFindingScopesMatchAPIAuthorization(t *testing.T) {+ manifest := agentcapabilities.CanonicalManifest()+ byName := map[string]agentcapabilities.Capability{}+ for _, cap := range manifest.Capabilities {+ byName[cap.Name] = cap+ }++ relayBacked := map[string]relayMobileRuntimeRouteID{+ agentcapabilities.ListFindingsCapabilityName: relayMobileRoutePatrolFindingsList,+ agentcapabilities.AcknowledgeFindingCapabilityName: relayMobileRoutePatrolAcknowledge,+ agentcapabilities.SnoozeFindingCapabilityName: relayMobileRoutePatrolSnooze,+ agentcapabilities.DismissFindingCapabilityName: relayMobileRoutePatrolDismiss,+ }+ for capabilityName, routeID := range relayBacked {+ capability, ok := byName[capabilityName]+ if !ok {+ t.Fatalf("agent capabilities manifest missing %s", capabilityName)+ }+ route := relayMobileRuntimeRouteSpecFor(routeID)+ if capability.Method != route.method || capability.Path != route.path || capability.Scope != route.requiredScope {+ t.Fatalf("%s manifest route/scope = %s %s => %s, want API authorization route %s %s => %s",+ capabilityName, capability.Method, capability.Path, capability.Scope, route.method, route.path, route.requiredScope)+ }+ }++ resolve, ok := byName[agentcapabilities.ResolveFindingCapabilityName]+ if !ok {+ t.Fatalf("agent capabilities manifest missing %s", agentcapabilities.ResolveFindingCapabilityName)+ }+ if resolve.Method != http.MethodPost || resolve.Path != "/api/ai/patrol/resolve" || resolve.Scope != config.ScopeAIExecute {+ t.Fatalf("resolve_finding manifest route/scope = %s %s => %s, want API authorization route POST /api/ai/patrol/resolve => %s",+ resolve.Method, resolve.Path, resolve.Scope, config.ScopeAIExecute)+ }+ var resolveSchema struct {+ Properties map[string]json.RawMessage `json:"properties"`+ Required []string `json:"required"`+ }+ if err := json.Unmarshal(resolve.InputSchema, &resolveSchema); err != nil {+ t.Fatalf("decode resolve_finding input schema: %v", err)+ }+ if _, ok := resolveSchema.Properties[agentcapabilities.ResolutionNoteArgumentName]; !ok {+ t.Fatalf("resolve_finding input schema missing optional %s property", agentcapabilities.ResolutionNoteArgumentName)+ }+ for _, required := range resolveSchema.Required {+ if required == agentcapabilities.ResolutionNoteArgumentName {+ t.Fatalf("resolve_finding input schema made optional %s required", agentcapabilities.ResolutionNoteArgumentName)+ }+ }++ dismiss := byName[agentcapabilities.DismissFindingCapabilityName]+ var dismissSchema struct {+ Properties map[string]json.RawMessage `json:"properties"`+ Required []string `json:"required"`+ }+ if err := json.Unmarshal(dismiss.InputSchema, &dismissSchema); err != nil {+ t.Fatalf("decode dismiss_finding input schema: %v", err)+ }+ if _, ok := dismissSchema.Properties[agentcapabilities.NoteArgumentName]; !ok {+ t.Fatalf("dismiss_finding input schema missing optional %s property", agentcapabilities.NoteArgumentName)+ }+ for _, required := range dismissSchema.Required {+ if required == agentcapabilities.NoteArgumentName {+ t.Fatalf("dismiss_finding input schema made optional %s required", agentcapabilities.NoteArgumentName)+ }+ }+}++func TestContract_AgentCapabilitiesManifestRoutesReachRouterWithAdvertisedScope(t *testing.T) {+ rawToken := "agent-route-contract-token.12345678"+ record := newTokenRecord(t, rawToken, []string{config.ScopeAgentReport}, nil)+ cfg := newTestConfigWithTokens(t, record)+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")++ args := map[string]any{+ "actionId": "act_contract",+ "capabilityName": "restart",+ "duration_hours": 1,+ agentcapabilities.FindingIDArgumentName: "finding-contract",+ "host": "https://pve-contract.example.com:8006",+ "intentionallyOffline": false,+ "name": "contract-node",+ "neverAutoRemediate": false,+ "nodeId": "pve-contract",+ "outcome": "approved",+ "params": map[string]any{},+ "password": "not-a-real-secret",+ agentcapabilities.ReasonArgumentName: "contract proof",+ "requestedBy": "agent:contract",+ "requestId": "req-contract",+ "resourceId": "vm101",+ "subnet": "auto",+ "type": "pve",+ "use_cache": true,+ "user": "root@pam",+ "verifySSL": false,+ "monitorVMs": true,+ "monitorContainers": true,+ "monitorStorage": true,+ "monitorBackups": true,+ "monitorPhysicalDisks": true,+ "temperatureMonitoringEnabled": true,+ }++ for _, capability := range agentcapabilities.CanonicalManifest().Capabilities {+ capability := capability+ t.Run(capability.Name, func(t *testing.T) {+ projected, err := agentcapabilities.ProjectCapabilityCall(capability, args)+ if err != nil {+ t.Fatalf("project manifest route %s %s: %v", capability.Method, capability.Path, err)+ }++ body := bytes.NewReader(nil)+ if projected.HasBody {+ body = bytes.NewReader(projected.Body)+ }+ req := httptest.NewRequest(capability.Method, projected.Path, body)+ req.Header.Set(agentcapabilities.AgentAPITokenHeader, rawToken)+ if projected.HasBody {+ req.Header.Set("Content-Type", "application/json")+ }++ rec := httptest.NewRecorder()+ router.Handler().ServeHTTP(rec, req)++ if rec.Code != http.StatusForbidden {+ t.Fatalf("%s projected to %s %s, got HTTP %d body=%s, want missing-scope 403 for %s",+ capability.Name, capability.Method, projected.Path, rec.Code, rec.Body.String(), capability.Scope)+ }+ if !strings.Contains(rec.Body.String(), capability.Scope) {+ t.Fatalf("%s projected to %s %s, missing-scope body %q does not mention advertised scope %q",+ capability.Name, capability.Method, projected.Path, rec.Body.String(), capability.Scope)+ }+ })+ }+}++func TestContract_AgentCapabilitiesRequiredScopeSummaryUsesManifestScopes(t *testing.T) {+ scopesSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "scopes.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/scopes.go: %v", err)+ }+ src := string(scopesSource)+ for _, required := range []string{+ `func NormalizeRequiredScopes(scopes []string) []string`,+ `func RequiredCapabilityScopes(capabilities []Capability) []string`,+ `for _, scope := range auth.AllKnownScopes`,+ `func RequiredScopeList(scopes []string) string`,+ `func RequiredCapabilityScopeList(capabilities []Capability) string`,+ `func ManifestRequiredScopeList(manifest *Manifest) string`,+ } {+ if !strings.Contains(src, required) {+ t.Errorf("agent capabilities scope summary must stay in the shared manifest contract; missing %s", required)+ }+ }++ got := agentcapabilities.RequiredCapabilityScopes(agentcapabilities.CanonicalManifest().Capabilities)+ want := []string{+ authpkg.ScopeMonitoringRead,+ authpkg.ScopeMonitoringWrite,+ authpkg.ScopeSettingsRead,+ authpkg.ScopeSettingsWrite,+ authpkg.ScopeAIExecute,+ }+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("canonical agent capability scopes = %v, want %v", got, want)+ }+ manifest := agentcapabilities.CanonicalManifest()+ if !reflect.DeepEqual(manifest.RequiredScopes, want) {+ t.Fatalf("canonical agent capability manifest requiredScopes = %v, want %v", manifest.RequiredScopes, want)+ }++ mcpSource, err := os.ReadFile(filepath.Join("..", "..", "cmd", "pulse-mcp", "main.go"))+ if err != nil {+ t.Fatalf("read cmd/pulse-mcp/main.go: %v", err)+ }+ mcp := string(mcpSource)+ if !strings.Contains(mcp, `agentcapabilities.ManifestRequiredScopeList(manifest)`) {+ t.Error("pulse-mcp token guidance must consume the manifest-owned requiredScopes summary")+ }+ if strings.Contains(mcp, `RequiredCapabilityScopeList(capabilities)`) {+ t.Error("pulse-mcp token guidance must not recompute current manifest scopes from capability rows")+ }+ if strings.Contains(mcp, `monitoring:read scope (and monitoring:write`) {+ t.Error("pulse-mcp startup guidance must not carry a hand-maintained partial scope list")+ }+}++func TestContract_PulseMCPReadmeManifestProjectionStaysGenerated(t *testing.T) {+ readmeBytes, err := os.ReadFile(filepath.Join("..", "..", "cmd", "pulse-mcp", "README.md"))+ if err != nil {+ t.Fatalf("read cmd/pulse-mcp/README.md: %v", err)+ }+ readme := string(readmeBytes)+ manifest := agentcapabilities.CanonicalManifest()+ generatorSource, err := os.ReadFile(filepath.Join("..", "..", "scripts", "generate-pulse-intelligence-docs.go"))+ if err != nil {+ t.Fatalf("read scripts/generate-pulse-intelligence-docs.go: %v", err)+ }+ generator := string(generatorSource)+ for _, required := range []string{+ "regeneratePulseIntelligenceDocs",+ "regeneratePulseMCPReadme",+ "regeneratePublicPulseIntelligenceOverview",+ "agentcapabilities.MCPSurfaceContractMarkdown(manifest.SurfaceContract)",+ "agentcapabilities.PulseIntelligenceOverviewMarkdown(manifest.SurfaceContract)",+ "agentcapabilities.MCPClientConfigMarkdown(manifest.MCPAdapter)",+ "agentcapabilities.MCPToolCapabilityInventoryMarkdown(manifest)",+ "agentcapabilities.MCPPromptInventoryMarkdown(manifest)",+ "agentcapabilities.MCPErrorCodeInventoryMarkdown(manifest)",+ "agentcapabilities.PulseIntelligenceOverviewStartMarker",+ "agentcapabilities.MCPReadmeSurfaceContractStartMarker",+ "agentcapabilities.MCPReadmeClientConfigStartMarker",+ } {+ if !strings.Contains(generator, required) {+ t.Errorf("Pulse Intelligence docs generator must own manifest-backed docs projection; missing %q", required)+ }+ }+ markdownSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "markdown.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/markdown.go: %v", err)+ }+ markdown := string(markdownSource)+ for _, required := range []string{+ "func MCPPromptInventoryMarkdown(manifest Manifest) string",+ "MCPManifestSurfacePromptProjectionSupported(manifest, SurfaceIDPulseMCP)",+ "ProjectMCPWorkflowPrompts(ManifestPulseWorkflowPrompts(manifest))",+ } {+ if !strings.Contains(markdown, required) {+ t.Errorf("MCP prompt inventory docs must use the shared surface prompt projection; missing %q", required)+ }+ }+ if strings.Contains(markdown, "prompts := ManifestPulseWorkflowPrompts(manifest)") {+ t.Fatal("MCP prompt inventory docs must not project raw workflow prompts without the MCP surface affordance gate")+ }++ surfaceBlock, err := markedContractBlock(readme, agentcapabilities.MCPReadmeSurfaceContractStartMarker, agentcapabilities.MCPReadmeSurfaceContractEndMarker)+ if err != nil {+ t.Fatal(err)+ }+ wantSurfaceBlock := agentcapabilities.MCPSurfaceContractMarkdown(manifest.SurfaceContract)+ if surfaceBlock != wantSurfaceBlock {+ t.Fatalf("pulse-mcp README surface-contract block drifted from canonical manifest; run `go run ./scripts/generate-pulse-intelligence-docs.go`\n%s\nwant:\n%s", surfaceBlock, wantSurfaceBlock)+ }++ scopeBlock, err := markedContractBlock(readme, agentcapabilities.MCPReadmeScopeListStartMarker, agentcapabilities.MCPReadmeScopeListEndMarker)+ if err != nil {+ t.Fatal(err)+ }+ wantScopeBlock := agentcapabilities.ManifestRequiredScopeMarkdownList(manifest)+ if scopeBlock != wantScopeBlock {+ t.Fatalf("pulse-mcp README scope block drifted from canonical manifest:\n%s\nwant:\n%s", scopeBlock, wantScopeBlock)+ }++ clientConfigBlock, err := markedContractBlock(readme, agentcapabilities.MCPReadmeClientConfigStartMarker, agentcapabilities.MCPReadmeClientConfigEndMarker)+ if err != nil {+ t.Fatal(err)+ }+ wantClientConfigBlock := agentcapabilities.MCPClientConfigMarkdown(manifest.MCPAdapter)+ if clientConfigBlock != wantClientConfigBlock {+ t.Fatalf("pulse-mcp README client config block drifted from canonical manifest; run `go run ./scripts/generate-pulse-intelligence-docs.go`\n%s\nwant:\n%s", clientConfigBlock, wantClientConfigBlock)+ }++ toolBlock, err := markedContractBlock(readme, agentcapabilities.MCPReadmeToolInventoryStartMarker, agentcapabilities.MCPReadmeToolInventoryEndMarker)+ if err != nil {+ t.Fatal(err)+ }+ wantToolBlock := agentcapabilities.MCPToolCapabilityInventoryMarkdown(manifest)+ if toolBlock != wantToolBlock {+ t.Fatalf("pulse-mcp README tool block drifted from canonical manifest; run `go run ./scripts/generate-pulse-intelligence-docs.go`\n%s\nwant:\n%s", toolBlock, wantToolBlock)+ }++ promptBlock, err := markedContractBlock(readme, agentcapabilities.MCPReadmePromptInventoryStartMarker, agentcapabilities.MCPReadmePromptInventoryEndMarker)+ if err != nil {+ t.Fatal(err)+ }+ wantPromptBlock := agentcapabilities.MCPPromptInventoryMarkdown(manifest)+ if promptBlock != wantPromptBlock {+ t.Fatalf("pulse-mcp README prompt block drifted from canonical manifest; run `go run ./scripts/generate-pulse-intelligence-docs.go`\n%s\nwant:\n%s", promptBlock, wantPromptBlock)+ }++ errorBlock, err := markedContractBlock(readme, agentcapabilities.MCPReadmeErrorInventoryStartMarker, agentcapabilities.MCPReadmeErrorInventoryEndMarker)+ if err != nil {+ t.Fatal(err)+ }+ wantErrorBlock := agentcapabilities.MCPErrorCodeInventoryMarkdown(manifest)+ if errorBlock != wantErrorBlock {+ t.Fatalf("pulse-mcp README error-code block drifted from canonical manifest; run `go run ./scripts/generate-pulse-intelligence-docs.go`\n%s\nwant:\n%s", errorBlock, wantErrorBlock)+ }+ if strings.Contains(readme, "As of this writing") {+ t.Fatal("pulse-mcp README must not frame the manifest-derived tool inventory as a hand-maintained snapshot")+ }+}++func TestContract_AgentSubstrateDocReflectsCurrentMCPOnboarding(t *testing.T) {+ source, err := os.ReadFile(filepath.Join("..", "..", "docs", "AGENT_SUBSTRATE.md"))+ if err != nil {+ t.Fatalf("read docs/AGENT_SUBSTRATE.md: %v", err)+ }+ doc := string(source)+ for _, required := range []string{+ "Settings -> API Access -> Agent integrations",+ "client-ready `pulse-mcp` config snippets",+ "manifest-owned MCP adapter setup contract",+ "surface contract and affordance badges",+ "server name, command",+ "supported client config families",+ "OpenCode's native `opencode.json` / `mcp` shape",+ "common `mcpServers` shape for Claude-style clients",+ "from the same adapter contract",+ "shows both",+ "OpenCode's native `opencode.json` shape",+ "common `mcpServers`",+ "`pulse-mcp` also has a published distribution path",+ "`install-mcp.sh` and `install-mcp.ps1`",+ "release installers",+ "frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx",+ } {+ if !strings.Contains(doc, required) {+ t.Errorf("docs/AGENT_SUBSTRATE.md must reflect current MCP onboarding; missing %q", required)+ }+ }+ for _, forbidden := range []string{+ "no Settings panel listing the declared capabilities",+ "no \"generate MCP config snippet\" button",+ "no token template that says \"create token for agent integration\"",+ "A distribution path for `pulse-mcp`. Today an integrator must",+ "clone the repo and `go build`",+ "generates the reusable `pulse-mcp` server block",+ } {+ if strings.Contains(doc, forbidden) {+ t.Errorf("docs/AGENT_SUBSTRATE.md must not preserve stale pre-onboarding gap copy; found %q", forbidden)+ }+ }+}++func TestContract_PulseIntelligenceOverviewPinsPatrolPrimaryCore(t *testing.T) {+ source, err := os.ReadFile(filepath.Join("..", "..", "docs", "AI.md"))+ if err != nil {+ t.Fatalf("read docs/AI.md: %v", err)+ }+ doc := string(source)+ manifest := agentcapabilities.CanonicalManifest()+ overviewBlock, err := markedContractBlock(doc, agentcapabilities.PulseIntelligenceOverviewStartMarker, agentcapabilities.PulseIntelligenceOverviewEndMarker)+ if err != nil {+ t.Fatal(err)+ }+ wantOverviewBlock := agentcapabilities.PulseIntelligenceOverviewMarkdown(manifest.SurfaceContract)+ if overviewBlock != wantOverviewBlock {+ t.Fatalf("docs/AI.md Pulse Intelligence overview block drifted from canonical manifest:\n%s\nwant:\n%s", overviewBlock, wantOverviewBlock)+ }++ normalized := strings.Join(strings.Fields(doc), " ")+ for _, required := range []string{+ "Pulse Intelligence Core",+ "Canonical context, governed actions, safety gates, approval state, action audit, and verification",+ "Patrol as the primary built-in operator",+ "Assistant plus MCP as access paths",+ "Patrol is the first-party operations surface: it watches, investigates, acts within the chosen Patrol mode, verifies outcomes, and records what happened",+ "Pulse Assistant",+ "Pulse MCP",+ "contextual explanation, approval, and handoff surface for Patrol findings",+ "Pulse Assistant and `pulse-mcp` are sibling surfaces over Pulse Intelligence, not competing implementations, and neither replaces the other",+ "Assistant remains the in-app Pro surface",+ "New operational capabilities should be added to the canonical API manifest first",+ "MCP-only actions and Assistant-only copies of the same business logic are drift",+ } {+ if !strings.Contains(normalized, required) {+ t.Errorf("docs/AI.md must pin Pulse Intelligence Core Patrol-primary product framing; missing %q", required)+ }+ }+ for _, forbidden := range []string{+ "three supported operator-facing ways",+ "three supported surfaces",+ "two supported operator-facing surfaces",+ "proactive detection and investigation engine running on the shared Pulse Intelligence Core",+ "Pulse Assistant should be replaced by",+ "MCP replaces Pulse Assistant",+ "Assistant can be removed",+ "hand-maintained Assistant tool table",+ } {+ if strings.Contains(normalized, forbidden) {+ t.Errorf("docs/AI.md must not drift away from the shared-core/Patrol-primary strategy; found %q", forbidden)+ }+ }+}++func TestContract_AgentParadigmDocReflectsGenericMCPOnboarding(t *testing.T) {+ source, err := os.ReadFile(filepath.Join("..", "..", "docs", "releases", "AGENT_PARADIGM.md"))+ if err != nil {+ t.Fatalf("read docs/releases/AGENT_PARADIGM.md: %v", err)+ }+ doc := string(source)+ for _, required := range []string{+ "Claude Desktop, Claude Code, OpenCode, other MCP clients",+ "client-ready MCP config snippets",+ "OpenCode's native\n `opencode.json` / `mcp` shape",+ "Drivable from MCP clients in one command",+ "Wire it into any MCP-speaking client",+ "OpenCode-native `mcp` block",+ "common\n `mcpServers` block",+ "manifest `requiredScopes`",+ "read-only subset",+ } {+ if !strings.Contains(doc, required) {+ t.Errorf("docs/releases/AGENT_PARADIGM.md must reflect generic MCP onboarding; missing %q", required)+ }+ }+ for _, forbidden := range []string{+ "Claude Desktop / Claude Code",+ "Drivable from Claude in one command",+ "Wire it into Claude Desktop or Claude Code",+ "adapter for Claude Desktop and Claude Code",+ "clients that accept\n `mcpServers`",+ "`monitoring:read` (and",+ } {+ if strings.Contains(doc, forbidden) {+ t.Errorf("docs/releases/AGENT_PARADIGM.md must not preserve stale Claude-only or partial-scope copy; found %q", forbidden)+ }+ }+}++func markedContractBlock(content, startMarker, endMarker string) (string, error) {+ start := strings.Index(content, startMarker)+ if start < 0 {+ return "", fmt.Errorf("missing marker %s", startMarker)+ }+ bodyStart := start + len(startMarker)+ end := strings.Index(content[bodyStart:], endMarker)+ if end < 0 {+ return "", fmt.Errorf("missing marker %s", endMarker)+ }+ return strings.TrimSpace(content[bodyStart : bodyStart+end]), nil+}++func TestContract_AssistantProviderSeamsDoNotUseMCPTerminology(t *testing.T) {+ chatServiceSource, err := os.ReadFile(filepath.Join("..", "ai", "chat", "service.go"))+ if err != nil {+ t.Fatalf("read internal/ai/chat/service.go: %v", err)+ }+ chatService := string(chatServiceSource)+ for _, fragment := range []string{+ `AssistantAlertProvider = tools.AlertProvider`,+ `AssistantFindingsProvider = tools.FindingsProvider`,+ `AssistantDiscoveryProvider = tools.DiscoveryProvider`,+ `AssistantUnifiedResourceProvider = tools.UnifiedResourceProvider`,+ `func (s *Service) ExecuteAssistantTool(ctx context.Context, toolName string, args map[string]interface{}) (string, error)`,+ `Msg("Executing Assistant registry tool directly")`,+ } {+ if !strings.Contains(chatService, fragment) {+ t.Errorf("native Assistant provider seam must be Assistant-owned, missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `MCPAlertProvider`,+ `MCPFindingsProvider`,+ `MCPDiscoveryProvider`,+ `MCPUnifiedResourceProvider`,+ `func (s *Service) ExecuteMCPTool(`,+ `MCP provider type aliases`,+ `Msg("Executing MCP tool directly")`,+ } {+ if strings.Contains(chatService, fragment) {+ t.Errorf("native Assistant provider seam must not be named as the MCP adapter surface; found %s", fragment)+ }+ }++ apiHandlerSource, err := os.ReadFile("ai_handler.go")+ if err != nil {+ t.Fatalf("read internal/api/ai_handler.go: %v", err)+ }+ apiHandler := string(apiHandlerSource)+ for _, fragment := range []string{+ `SetAlertProvider(provider chat.AssistantAlertProvider)`,+ `SetFindingsProvider(provider chat.AssistantFindingsProvider)`,+ `SetDiscoveryProvider(provider chat.AssistantDiscoveryProvider)`,+ `SetUnifiedResourceProvider(provider chat.AssistantUnifiedResourceProvider)`,+ } {+ if !strings.Contains(apiHandler, fragment) {+ t.Errorf("API chat service interface must expose Assistant provider seams; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `chat.MCPAlertProvider`,+ `chat.MCPFindingsProvider`,+ `chat.MCPDiscoveryProvider`,+ `chat.MCPUnifiedResourceProvider`,+ `for MCP tools`,+ } {+ if strings.Contains(apiHandler, fragment) {+ t.Errorf("API chat service interface must not describe native Assistant providers as MCP tools; found %s", fragment)+ }+ }++ settingsHandlerSource, err := os.ReadFile("ai_handlers.go")+ if err != nil {+ t.Fatalf("read internal/api/ai_handlers.go: %v", err)+ }+ settingsHandler := string(settingsHandlerSource)+ for _, fragment := range []string{+ `Used by Router to update Assistant tool visibility without restarting AI chat.`,+ `Update Assistant control settings if control level or protected guests changed.`,+ `This updates tool visibility without restarting AI chat.`,+ } {+ if !strings.Contains(settingsHandler, fragment) {+ t.Errorf("AI settings handler must describe control refresh as native Assistant tool visibility; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `Update MCP control settings`,+ `MCP control settings`,+ `MCP tool visibility`,+ } {+ if strings.Contains(settingsHandler, fragment) {+ t.Errorf("AI settings handler must not describe native Assistant control refresh as MCP wiring; found %s", fragment)+ }+ }++ routerSource, err := os.ReadFile("router.go")+ if err != nil {+ t.Fatalf("read internal/api/router.go: %v", err)+ }+ router := string(routerSource)+ for _, fragment := range []string{+ `ai.NewFindingsToolAdapter(findingsStore)`,+ `tools.NewAlertManagerToolAdapter(alertManager)`,+ `tools.NewDiscoveryToolAdapter(adapter)`,+ `NewAssistantAgentProfileManager(persistence, licenseSvc)`,+ `AI chat Assistant tool providers wired`,+ `Wire control settings change callback to update Assistant tool visibility`,+ } {+ if !strings.Contains(router, fragment) {+ t.Errorf("router must wire native Assistant providers without MCP terminology; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `ai.NewFindingsMCPAdapter(findingsStore)`,+ `tools.NewAlertManagerMCPAdapter(alertManager)`,+ `tools.NewDiscoveryMCPAdapter(adapter)`,+ `NewMCPAgentProfileManager(persistence, licenseSvc)`,+ `AI chat MCP tool providers wired`,+ `org-scoped MCP tool providers`,+ } {+ if strings.Contains(router, fragment) {+ t.Errorf("router must not describe native Assistant provider wiring as MCP adapter wiring; found %s", fragment)+ }+ }++ relaySource, err := os.ReadFile("router_routes_ai_relay.go")+ if err != nil {+ t.Fatalf("read internal/api/router_routes_ai_relay.go: %v", err)+ }+ relay := string(relaySource)+ for _, fragment := range []string{+ `toolAdapter := &assistantToolAdapter{handler: h}`,+ `AssistantToolExecutor: toolAdapter`,+ `type assistantToolAdapter struct`,+ `var _ aicontracts.ApprovedAssistantToolExecutor = (*assistantToolAdapter)(nil)`,+ `func (m *assistantToolAdapter) ExecuteApprovedAssistantTool(ctx context.Context, command, approvalID string) (string, int, error)`,+ } {+ if !strings.Contains(relay, fragment) {+ t.Errorf("approved Assistant tool adapter must expose native Assistant execution from the current runtime; missing %s", fragment)+ }+ }+ if !strings.Contains(relay, `chatService.ExecuteAssistantTool(ctx, params.Name, params.Arguments)`) {+ t.Error("approved Assistant tool adapter must delegate to the native Assistant tool executor")+ }+ if strings.Contains(relay, `type mcpToolAdapter struct`) || strings.Contains(relay, `&mcpToolAdapter{`) {+ t.Error("approved Assistant tool adapter must not be named as the MCP adapter surface")+ }+ for _, fragment := range []string{+ `MCPExecutor: toolAdapter`,+ `MCPExecutor: toolAdapter`,+ `var _ aicontracts.MCPToolExecutor = (*assistantToolAdapter)(nil)`,+ `func (m *assistantToolAdapter) ExecuteMCPTool(ctx context.Context, command, approvalID string) (string, int, error)`,+ `chatService.ExecuteMCPTool(`,+ } {+ if strings.Contains(relay, fragment) {+ t.Errorf("current runtime must not expose native Assistant execution through the legacy MCP executor seam; found %s", fragment)+ }+ }++ contractSource, err := os.ReadFile(filepath.Join("..", "..", "pkg", "aicontracts", "fix_execution.go"))+ if err != nil {+ t.Fatalf("read pkg/aicontracts/fix_execution.go: %v", err)+ }+ contracts := string(contractSource)+ for _, fragment := range []string{+ `type ApprovedAssistantToolExecutor interface`,+ `ExecuteApprovedAssistantTool(ctx context.Context, command, approvalID string) (output string, exitCode int, err error)`,+ } {+ if !strings.Contains(contracts, fragment) {+ t.Errorf("cross-repo approved tool contract must expose native Assistant executor only; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `type MCPToolExecutor interface`,+ `ExecuteMCPTool(ctx context.Context, command, approvalID string) (output string, exitCode int, err error)`,+ `Prefer ApprovedAssistantToolExecutor for new integrations`,+ } {+ if strings.Contains(contracts, fragment) {+ t.Errorf("cross-repo approved tool contract must not preserve legacy MCP executor compatibility; found %s", fragment)+ }+ }++ extensionSource, err := os.ReadFile(filepath.Join("..", "..", "pkg", "extensions", "ai_autofix.go"))+ if err != nil {+ t.Fatalf("read pkg/extensions/ai_autofix.go: %v", err)+ }+ extensionsSrc := string(extensionSource)+ for _, fragment := range []string{+ `AssistantToolExecutor aicontracts.ApprovedAssistantToolExecutor`,+ `func (d AIAutoFixHandlerDeps) ResolveApprovedAssistantToolExecutor() aicontracts.ApprovedAssistantToolExecutor`,+ `return d.AssistantToolExecutor`,+ } {+ if !strings.Contains(extensionsSrc, fragment) {+ t.Errorf("auto-fix extension deps must expose native Assistant tool execution without MCP compatibility; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `MCPExecutor`,+ `MCPToolExecutor`,+ `legacyMCPApprovedAssistantToolExecutor`,+ `ExecuteMCPTool`,+ `compatibility fallback for enterprise binders`,+ } {+ if strings.Contains(extensionsSrc, fragment) {+ t.Errorf("auto-fix extension deps must not expose legacy MCP executor compatibility; found %s", fragment)+ }+ }++ findingsAdapterSource, err := os.ReadFile(filepath.Join("..", "ai", "findings_tools_adapter.go"))+ if err != nil {+ t.Fatalf("read internal/ai/findings_tools_adapter.go: %v", err)+ }+ findingsAdapter := string(findingsAdapterSource)+ if !strings.Contains(findingsAdapter, `type FindingsToolAdapter struct`) ||+ !strings.Contains(findingsAdapter, `func NewFindingsToolAdapter(store *FindingsStore) *FindingsToolAdapter`) {+ t.Error("findings store adapter must be named for the native tool registry")+ }+ if strings.Contains(findingsAdapter, `FindingsMCPAdapter`) || strings.Contains(findingsAdapter, `NewFindingsMCPAdapter`) {+ t.Error("findings store adapter must not be named as an MCP adapter")+ }++ toolAdaptersSource, err := os.ReadFile(filepath.Join("..", "ai", "tools", "adapters.go"))+ if err != nil {+ t.Fatalf("read internal/ai/tools/adapters.go: %v", err)+ }+ toolAdapters := string(toolAdaptersSource)+ for _, fragment := range []string{+ `type AlertManagerToolAdapter struct`,+ `func NewAlertManagerToolAdapter(manager AlertManager) *AlertManagerToolAdapter`,+ `type RecoveryPointsToolAdapter struct`,+ `func NewRecoveryPointsToolAdapter(manager *recoverymanager.Manager, orgID string) *RecoveryPointsToolAdapter`,+ `type DiscoveryToolAdapter struct`,+ `func NewDiscoveryToolAdapter(source DiscoverySource) *DiscoveryToolAdapter`,+ } {+ if !strings.Contains(toolAdapters, fragment) {+ t.Errorf("Assistant runtime adapters must be named for the native tool registry; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `MCPAdapter`,+ `NewAlertManagerMCPAdapter`,+ `NewRecoveryPointsMCPAdapter`,+ `NewDiscoveryMCPAdapter`,+ `MCP tools`,+ `mcp.`,+ } {+ if strings.Contains(toolAdapters, fragment) {+ t.Errorf("Assistant runtime adapters must not be named as MCP adapters; found %s", fragment)+ }+ }++ intelligenceAdaptersSource, err := os.ReadFile(filepath.Join("..", "ai", "adapters", "adapters.go"))+ if err != nil {+ t.Fatalf("read internal/ai/adapters/adapters.go: %v", err)+ }+ intelligenceAdapters := string(intelligenceAdaptersSource)+ for _, fragment := range []string{+ `type IncidentRecorderToolAdapter struct`,+ `func NewIncidentRecorderToolAdapter(recorder IncidentRecorderSource) *IncidentRecorderToolAdapter`,+ `type EventCorrelatorToolAdapter struct`,+ `func NewEventCorrelatorToolAdapter(correlator EventCorrelatorSource) *EventCorrelatorToolAdapter`,+ } {+ if !strings.Contains(intelligenceAdapters, fragment) {+ t.Errorf("Assistant intelligence adapters must be named for the native tool registry; missing %s", fragment)+ }+ }+ if strings.Contains(intelligenceAdapters, `MCPAdapter`) || strings.Contains(intelligenceAdapters, `NewIncidentRecorderMCPAdapter`) || strings.Contains(intelligenceAdapters, `NewEventCorrelatorMCPAdapter`) {+ t.Error("Assistant intelligence adapters must not be named as MCP adapters")+ }++ agentProfilesSource, err := os.ReadFile("agent_profiles_tools.go")+ if err != nil {+ t.Fatalf("read internal/api/agent_profiles_tools.go: %v", err)+ }+ agentProfiles := string(agentProfilesSource)+ if !strings.Contains(agentProfiles, `type AssistantAgentProfileManager struct`) ||+ !strings.Contains(agentProfiles, `func NewAssistantAgentProfileManager(persistence *config.ConfigPersistence, licenseService licenseFeatureChecker) *AssistantAgentProfileManager`) {+ t.Error("agent profile manager must be named for the native Assistant tool registry")+ }+ if strings.Contains(agentProfiles, `MCPAgentProfileManager`) || strings.Contains(agentProfiles, `NewMCPAgentProfileManager`) || strings.Contains(agentProfiles, `MCP tools`) {+ t.Error("agent profile manager must not be named as an MCP adapter")+ }+}++// TestContract_PulseMCPAdapterProjectsAgentCapabilitiesManifest pins the+// external-agent adapter boundary: pulse-mcp must stay a projection of the+// canonical capabilities manifest, not a second action registry.+func TestContract_PulseMCPAdapterProjectsAgentCapabilitiesManifest(t *testing.T) {+ source, err := os.ReadFile(filepath.Join("..", "..", "cmd", "pulse-mcp", "main.go"))+ if err != nil {+ t.Fatalf("read cmd/pulse-mcp/main.go: %v", err)+ }+ src := string(source)+ required := []string{+ `internal/agentcapabilities`,+ `type agentCapability = agentcapabilities.Capability`,+ `type agentCapabilitiesManifest = agentcapabilities.Manifest`,+ `type jsonRPCRequest = agentcapabilities.JSONRPCRequest`,+ `agentcapabilities.ServeJSONRPCLines(`,+ `agentcapabilities.WriteJSONRPCMessage(out, v)`,+ `agentcapabilities.DispatchMCPToolServerRequest(ctx, *req, s.manifestToolServer().Handlers(func()`,+ `agentcapabilities.MCPManifestToolServer{`,+ `ServerName: pulseMCPServerName`,+ `SurfaceID: agentcapabilities.SurfaceIDPulseMCP`,+ `Manifest: manifest`,+ `agentcapabilities.FetchManifest(context.Background(), manifestClient, *baseURL)`,+ `agentcapabilities.StreamMCPEventNotifications(ctx, pulseMCPAgentSurfaceHTTPDoer{}, s.baseURL, path, s.token, func(notification agentcapabilities.JSONRPCRequest) error`,+ }+ for _, fragment := range required {+ if !strings.Contains(src, fragment) {+ t.Errorf("pulse-mcp must project the canonical agent capabilities manifest; missing %s", fragment)+ }+ }+ forbidden := []string{+ `type jsonRPCRequest struct`,+ `type jsonRPCResponse struct`,+ `type jsonRPCError struct`,+ `type jsonRPCResponse = agentcapabilities.JSONRPCResponse`,+ `type jsonRPCError = agentcapabilities.JSONRPCError`,+ `bufio.NewScanner(in)`,+ `scanner.Scan()`,+ `agentcapabilities.DecodeJSONRPCRequest(`,+ `agentcapabilities.NewJSONRPCParseErrorResponse(`,+ `agentcapabilities.JSONRPCRequestExpectsResponse(`,+ `json.Unmarshal([]byte(line)`,+ `agentcapabilities.JSONRPCErrorParse`,+ `len(req.ID) == 0`,+ `string(req.ID) == "null"`,+ `switch req.Method`,+ `agentcapabilities.NewJSONRPCResponse(req.ID, nil)`,+ `agentcapabilities.JSONRPCErrorInternal`,+ `agentcapabilities.JSONRPCErrorMethodNotFound`,+ `agentcapabilities.MCPToolServerHandlers{`,+ `agentcapabilities.MCPMethodToolsList`,+ `agentcapabilities.MCPMethodToolsCall`,+ `agentcapabilities.MCPMethodResourcesList`,+ `agentcapabilities.MCPMethodResourcesRead`,+ `agentcapabilities.MCPMethodPromptsList`,+ `agentcapabilities.MCPMethodPromptsGet`,+ `agentcapabilities.MCPMethodPing`,+ `func (s *mcpServer) handleInitialize(`,+ `func (s *mcpServer) handleToolsList(`,+ `func (s *mcpServer) handleToolsCall(`,+ `func (s *mcpServer) handleResourcesList(`,+ `func (s *mcpServer) handleResourcesRead(`,+ `func (s *mcpServer) handlePromptsList(`,+ `func (s *mcpServer) handlePromptsGet(`,+ `agentcapabilities.NewMCPToolServerInitializeResult(pulseMCPServerName`,+ `agentcapabilities.ProjectTools(s.manifest.Capabilities)`,+ `agentcapabilities.ProjectMCPPrompts(s.manifest.Capabilities)`,+ `agentcapabilities.GetMCPPrompt(s.manifest.Capabilities`,+ `agentcapabilities.BuildMCPPrompt(s.manifest.Capabilities`,+ `agentcapabilities.ExecuteMCPToolHTTP(`,+ `agentcapabilities.ExecuteMCPManifestSurfaceToolHTTP(ctx, s.http, s.baseURL, s.token, s.manifest, agentcapabilities.SurfaceIDPulseMCP, raw)`,+ `"protocolVersion": "2024-11-05"`,+ `"protocolVersion": "2025-06-18"`,+ `"isError": isError`,+ `NewMCPHTTPTextResult(resp.Body, resp.StatusCode)`,+ `agentcapabilities.MCPCapabilities{`,+ `agentcapabilities.MCPToolsCapability{}`,+ `agentcapabilities.MCPPulseNotificationsCapability{`,+ `json.Unmarshal(raw, ¶ms)`,+ `fmt.Errorf("unknown tool: %s", params.Name)`,+ `agentcapabilities.FindCapability(s.manifest.Capabilities, params.Name)`,+ `agentcapabilities.CallCapabilityHTTP(ctx, s.http, s.baseURL, s.token, cap, params.Arguments)`,+ `agentcapabilities.NewMCPCapabilityHTTPResult(resp)`,+ `http.NewRequestWithContext(ctx, cap.Method`,+ `httpReq.Header.Set("X-API-Token"`,+ `baseURL+"/api/agent/capabilities"`,+ `req.Header.Set("Accept", "text/event-stream")`,+ `http.DefaultClient.Do(req)`,+ `scanner := bufio.NewScanner(resp.Body)`,+ `strings.HasPrefix(line, "event: ")`,+ `strings.HasPrefix(line, "data: ")`,+ `agentcapabilities.StreamAgentSSERecords(ctx, nil, s.baseURL, path, s.token`,+ `agentcapabilities.IsTransportEventKind(event)`,+ `agentcapabilities.NewMCPEventNotification(event, []byte(data))`,+ `agentcapabilities.NewJSONRPCNotification(agentcapabilities.MCPNotificationMethod(event), params)`,+ }+ for _, fragment := range forbidden {+ if strings.Contains(src, fragment) {+ t.Errorf("pulse-mcp must not preserve local MCP wire/result envelope logic; found %s", fragment)+ }+ }++ projectionSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "projection.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/projection.go: %v", err)+ }+ projection := string(projectionSource)+ sharedRequired := []string{+ `type ProjectedTool struct`,+ `Title string`,+ `OutputSchema json.RawMessage`,+ `Annotations *ToolBehaviorHints`,+ `Meta map[string]any`,+ `type ToolBehaviorHints struct`,+ `ToolMetaPulseCapabilityKey = "pulse.capability"`,+ `ReadOnlyHint`,+ `DestructiveHint`,+ `IdempotentHint`,+ `OpenWorldHint`,+ `func ProjectTools(capabilities []Capability) []ProjectedTool`,+ `func ProjectManifestSurfaceTools(manifest Manifest, surfaceID string) []ProjectedTool`,+ `func ManifestSurfaceToolCapabilities(manifest Manifest, surfaceID string) []Capability`,+ `func FindManifestSurfaceToolContract(manifest Manifest, surfaceID string) (SurfaceToolContract, bool)`,+ `func ProjectTool(cap Capability) (ProjectedTool, bool)`,+ `func CapabilityTitle(cap Capability) string`,+ `func ToolAnnotations(cap Capability) *ToolBehaviorHints`,+ `func ToolGovernanceBehaviorHints(governance ToolGovernanceDescriptor) *ToolBehaviorHints`,+ `func CloneToolBehaviorHints(hints *ToolBehaviorHints) *ToolBehaviorHints`,+ `func ToolMeta(cap Capability) map[string]any`,+ `NormalizeCapabilityGovernance(cap)`,+ `func FindCapability(capabilities []Capability, name string) (Capability, bool)`,+ `type CapabilityLookupError struct`,+ `func ResolveCapability(capabilities []Capability, name string) (Capability, error)`,+ `func ResolveRequestResponseCapability(capabilities []Capability, name string) (Capability, error)`,+ `return CloneCapability(cap), true`,+ `IsRequestResponseCapability(cap)`,+ `ResolutionNoteArgumentName = "resolution_note"`,+ `NoteArgumentName = "note"`,+ `Title: CapabilityTitle(cap)`,+ `Description: ToolDescription(cap)`,+ `InputSchema: ToolInputSchema(cap)`,+ `OutputSchema: ToolOutputSchema(cap)`,+ `Annotations: ToolAnnotations(cap)`,+ `Meta: ToolMeta(cap)`,+ `ToolMetaPulseCapabilityKey: capability`,+ `return CloneRawMessage(cap.InputSchema)`,+ `return CloneRawMessage(cap.OutputSchema)`,+ }+ for _, fragment := range sharedRequired {+ if !strings.Contains(projection, fragment) {+ t.Errorf("agentcapabilities must own the external-agent tool projection; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `Annotations *MCPToolAnnotations`,+ `type MCPToolAnnotations struct`,+ `func ToolAnnotations(cap Capability) *MCPToolAnnotations`,+ } {+ if strings.Contains(projection, fragment) {+ t.Errorf("external-agent tool projection must not make MCP the owner of shared behavior hints; found %s", fragment)+ }+ }++ mcpAliasSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "mcp.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/mcp.go: %v", err)+ }+ mcp := string(mcpAliasSource)+ if !strings.Contains(mcp, `type MCPToolAnnotations = ToolBehaviorHints`) {+ t.Error("MCP adapter edge must keep the protocol-facing tool annotations alias over shared behavior hints")+ }++ schemaSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "schema.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/schema.go: %v", err)+ }+ schema := string(schemaSource)+ for _, fragment := range []string{+ `type ProviderTool struct`,+ `type ProviderToolCall struct`,+ `type ProviderToolResult struct`,+ `func (t Tool) NormalizeCollections() Tool`,+ `func (s InputSchema) NormalizeCollections() InputSchema`,+ `func ClonePropertySchemas(properties map[string]PropertySchema) map[string]PropertySchema`,+ `func CloneProviderInputSchema(schema map[string]interface{}) map[string]interface{}`,+ `func CloneRawMessage(raw json.RawMessage) json.RawMessage`,+ `func EmptyProviderTool() ProviderTool`,+ `func (t ProviderTool) NormalizeCollections() ProviderTool`,+ `t.InputSchema = CloneProviderInputSchema(t.InputSchema)`,+ `t.BehaviorHints = CloneToolBehaviorHints(t.BehaviorHints)`,+ `BehaviorHints *ToolBehaviorHints`,+ `PulseGovernance *ToolGovernanceDescriptor`,+ `func EmptyProviderToolCall() ProviderToolCall`,+ `func (t ProviderToolCall) NormalizeCollections() ProviderToolCall`,+ `t.Input = CloneToolArguments(t.Input)`,+ `t.ThoughtSignature = CloneRawMessage(t.ThoughtSignature)`,+ `type ProviderToolResultContextOptions struct`,+ `type ProviderToolResultTruncation struct`,+ `type ProviderToolResultContextProjection struct`,+ `func NewProviderToolResult(toolUseID, content string, isError bool) ProviderToolResult`,+ `func NewProviderToolErrorResult(toolUseID, content string) ProviderToolResult`,+ `func NewProviderToolResultFromToolResult(toolUseID string, result ToolResult) ProviderToolResult`,+ `func NewProviderToolResultContextProjection(toolUseID, content string, isError bool, opts ProviderToolResultContextOptions) ProviderToolResultContextProjection`,+ `func NewProviderToolResultContextProjectionFromToolResult(toolUseID string, result ToolResult, opts ProviderToolResultContextOptions) ProviderToolResultContextProjection`,+ `func ProviderToolResultModelContent(content string, opts ProviderToolResultContextOptions) (string, ProviderToolResultTruncation)`,+ `func ProviderInputSchemaFromRaw(raw json.RawMessage) map[string]interface{}`,+ `func ProjectProviderTool(tool Tool) ProviderTool`,+ `func ProjectProviderToolWithGovernance(tool Tool, governance ToolGovernanceDescriptor) ProviderTool`,+ `func ProjectProviderTools(tools []Tool) []ProviderTool`,+ `func ProjectProviderToolsWithGovernance(tools []Tool, governance []ToolGovernanceDescriptor) []ProviderTool`,+ `type AssistantProviderToolOptions struct`,+ `func ProjectAssistantProviderTools(tools []Tool, governance []ToolGovernanceDescriptor, opts AssistantProviderToolOptions) []ProviderTool`,+ `func ProjectPulseAssistantProviderTools(manifest Manifest, tools []Tool, governance []ToolGovernanceDescriptor, opts AssistantProviderToolOptions) []ProviderTool`,+ `func ProviderToolGovernanceDescriptors(tools []ProviderTool) ([]ToolGovernanceDescriptor, bool)`,+ `func AssistantNativeProviderTools() []ProviderTool`,+ `func AssistantNativeProviderToolNames() []string`,+ `func LegacyAssistantUtilityProviderTools() []ProviderTool`,+ `LegacyAssistantRunCommandToolName = "run_command"`,+ `LegacyAssistantFetchURLToolName = "fetch_url"`,+ `LegacyAssistantSetResourceURLToolName = "set_resource_url"`,+ `func ProviderToolNames(tools []ProviderTool) []string`,+ `type ProviderToolNameCatalog struct`,+ `func NewProviderToolNameCatalog(nameGroups ...[]string) ProviderToolNameCatalog`,+ `func NewAssistantProviderToolNameCatalog(registryToolNames []string) ProviderToolNameCatalog`,+ `func (c ProviderToolNameCatalog) Names() []string`,+ `func (c ProviderToolNameCatalog) Has(name string) bool`,+ `func (c ProviderToolNameCatalog) HasPrefix(prefix string) bool`,+ `func ProviderToolDescriptionWithGovernance(description string, governance ToolGovernanceDescriptor) string`,+ `func ProjectProviderToolCallToToolCall(tc ProviderToolCall) ToolCallParams`,+ `func NormalizeProviderToolCallForExecution(tc ProviderToolCall) ProviderToolCall`,+ `func NormalizeProviderToolCallsForExecution(calls []ProviderToolCall) []ProviderToolCall`,+ `func NewPulseQuestionProviderTool() ProviderTool`,+ `func PulseQuestionProviderInputSchema() map[string]interface{}`,+ `func ParseProviderToolInput(raw string) (map[string]interface{}, bool)`,+ `func ProviderToolInputOrRaw(raw string) map[string]interface{}`,+ `schema = schema.NormalizeCollections()`,+ `projected := CloneProviderInputSchema(schema)`,+ `property = property.NormalizeCollections()`,+ `tool = tool.NormalizeCollections()`,+ `InputSchema: ProviderInputSchema(tool.InputSchema)`,+ `ToolGovernancePromptDescription(governance)`,+ `Pulse governance: `,+ `projected.BehaviorHints = ToolGovernanceBehaviorHints(governance)`,+ `projected.PulseGovernance = &governance`,+ `return NewProviderToolResult(toolUseID, interpreted.Text, interpreted.IsError)`,+ `ProviderToolResultModelContent(content, opts)`,+ `return NormalizeToolCallParams(ToolCallParams{`,+ `Arguments: tc.Input,`,+ `params := ProjectProviderToolCallToToolCall(tc)`,+ `normalized.Name = params.Name`,+ `normalized.Input = params.Arguments`,+ `projected = append(projected, AssistantNativeProviderTools()...)`,+ `ManifestSurfaceAffordances(manifest, SurfaceIDPulseAssistant)`,+ `if !affordances.Tools`,+ `if !affordances.InteractiveQuestions`,+ `return ProviderToolNames(AssistantNativeProviderTools())`,+ `Name: PulseQuestionToolName`,+ `InputSchema: PulseQuestionProviderInputSchema(),`,+ `Name: LegacyAssistantRunCommandToolName`,+ `Name: LegacyAssistantFetchURLToolName`,+ `Name: LegacyAssistantSetResourceURLToolName`,+ `type PulseQuestionToolType string`,+ `PulseQuestionToolTypeText PulseQuestionToolType = "text"`,+ `PulseQuestionToolTypeSelect PulseQuestionToolType = "select"`,+ `func PulseQuestionToolTypeValues() []string`,+ `func NormalizePulseQuestionToolType(rawType string, hasOptions bool) (PulseQuestionToolType, error)`,+ `type PulseQuestionToolQuestion struct`,+ `type PulseQuestionToolOption struct`,+ `func ParsePulseQuestionToolInput(input map[string]interface{}) ([]PulseQuestionToolQuestion, error)`,+ `func parsePulseQuestionToolOptions(rawOptions json.RawMessage) ([]PulseQuestionToolOption, error)`,+ `"enum": PulseQuestionToolTypeValues(),`,+ `return map[string]interface{}{"raw": raw}`,+ } {+ if !strings.Contains(schema, fragment) {+ t.Errorf("agentcapabilities must own the Assistant provider tool projection; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `func ProjectProviderToolCallToMCP(tc ProviderToolCall) MCPCallToolParams`,+ } {+ if strings.Contains(schema, fragment) {+ t.Errorf("neutral provider schema must not own MCP compatibility aliases; found %s", fragment)+ }+ }++ providerArtifactSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "provider_tool_artifacts.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/provider_tool_artifacts.go: %v", err)+ }+ providerArtifacts := string(providerArtifactSource)+ for _, fragment := range []string{+ `func ProviderToolCallArtifactIndex(content string, catalog ProviderToolNameCatalog) int`,+ `func SplitTrailingProviderToolNamePrefix(content string, catalog ProviderToolNameCatalog) (visible string, held string)`,+ `providerJSONToolCallLeakIndex(content, catalog)`,+ `providerPlainFunctionToolCallLeakIndex(content, catalog)`,+ `catalog.Has(name)`,+ `catalog.HasPrefix(token)`,+ } {+ if !strings.Contains(providerArtifacts, fragment) {+ t.Errorf("agentcapabilities must own provider tool-call artifact detection; missing %s", fragment)+ }+ }++ mcpSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "mcp.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/mcp.go: %v", err)+ }+ mcpWire := string(mcpSource)+ toolCallSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "tool_call.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/tool_call.go: %v", err)+ }+ toolNameSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "tool_names.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/tool_names.go: %v", err)+ }+ toolResultSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "tool_result.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/tool_result.go: %v", err)+ }+ toolExecutionSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "tool_execution.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/tool_execution.go: %v", err)+ }+ toolCore := string(toolNameSource) + "\n" + string(toolCallSource) + "\n" + string(toolResultSource) + "\n" + string(toolExecutionSource) + "\n" + projection+ mcpWireContract := mcpWire + "\n" + toolCore+ toolCallSrc := string(toolCallSource)+ toolNameSrc := string(toolNameSource)+ for _, pair := range []struct {+ name string+ value string+ }{+ {`PulseQueryToolName`, `"pulse_query"`},+ {`PulseControlToolName`, `"pulse_control"`},+ {`PulseReadToolName`, `"pulse_read"`},+ {`PulseSummarizeToolName`, `"pulse_summarize"`},+ {`PulseRunCommandToolName`, `"pulse_run_command"`},+ {`PatrolGetFindingsToolName`, `"patrol_get_findings"`},+ {`PatrolReportFindingToolName`, `"patrol_report_finding"`},+ {`PatrolResolveFindingToolName`, `"patrol_resolve_finding"`},+ } {+ if !strings.Contains(toolNameSrc, pair.name) || !strings.Contains(toolNameSrc, pair.value) {+ t.Errorf("agentcapabilities must own stable Pulse Intelligence tool identity %s=%s", pair.name, pair.value)+ }+ }+ for _, fragment := range []string{+ `type ToolCallKind int`,+ `ToolCallKindResolve`,+ `ToolCallKindRead`,+ `ToolCallKindWrite`,+ `ToolCallKindUserInput`,+ `func (k ToolCallKind) String() string`,+ `func ClassifyToolCall(toolName string, args map[string]interface{}) ToolCallKind`,+ `case PulseQuestionToolName:`,+ `case PulseQueryToolName, PulseDiscoveryToolName:`,+ `case PulseControlToolName:`,+ `case PulseReadToolName, LegacyAssistantFetchURLToolName:`,+ `LegacyAssistantRunCommandToolName, LegacyAssistantSetResourceURLToolName`,+ `return ToolCallKindWrite`,+ } {+ if !strings.Contains(toolCallSrc, fragment) {+ t.Errorf("agentcapabilities must own shared tool-call safety classification; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `type JSONRPCRequest struct`,+ `type JSONRPCResponse struct`,+ `type JSONRPCError struct`,+ `type MCPInitializeResult struct`,+ `type ToolCallParams struct`,+ `type MCPCallToolParams = ToolCallParams`,+ `func NormalizeToolCallParams(params ToolCallParams) ToolCallParams`,+ `func ValidateToolCallParams(params ToolCallParams) error`,+ `type MCPProjectedToolsResult struct`,+ `type MCPResource struct`,+ `type MCPListResourcesResult struct`,+ `type MCPReadResourceParams struct`,+ `type MCPReadResourceResult struct`,+ `type MCPResourceContent struct`,+ `type MCPPrompt struct`,+ `Title string`,+ `type MCPPromptArgument struct`,+ `type MCPListPromptsResult struct`,+ `type MCPGetPromptParams struct`,+ `type MCPGetPromptResult struct`,+ `type MCPPromptMessage struct`,+ `type MCPCapabilities struct`,+ `Instructions string`,+ `Resources *MCPResourcesCapability`,+ `Prompts *MCPPromptsCapability`,+ `type MCPResourcesCapability struct`,+ `type MCPPromptsCapability struct`,+ `type ProjectedTool struct`,+ `OutputSchema json.RawMessage`,+ `Meta map[string]any`,+ `type ToolResult struct`,+ `StructuredContent map[string]any`,+ `type MCPToolResult = ToolResult`,+ `type ToolContent struct`,+ `type MCPContent = ToolContent`,+ `func (r MCPListResourcesResult) NormalizeCollections() MCPListResourcesResult`,+ `func (r MCPReadResourceResult) NormalizeCollections() MCPReadResourceResult`,+ `func (r MCPListPromptsResult) NormalizeCollections() MCPListPromptsResult`,+ `func (r MCPGetPromptResult) NormalizeCollections() MCPGetPromptResult`,+ `func EmptyToolResult() ToolResult`,+ `func (r ToolResult) NormalizeCollections() ToolResult`,+ `MCPPulseNotificationsExperimentalKey = "pulseNotifications"`,+ `func NewMCPToolServerInitializeResult(`,+ `func NewMCPManifestToolServerInitializeResult(`,+ `func NewMCPManifestSurfaceToolServerInitializeResult(`,+ `ManifestSurfaceAffordances(manifest, surfaceID)`,+ `ResolveManifestSurfaceToolContract(manifest, surfaceID)`,+ `affordances.Tools && hasSurfaceToolContract`,+ `MCPManifestSurfacePromptProjectionSupported(manifest, surfaceID)`,+ `Instructions: BuildPulseMCPOperatingInstructions(PulseMCPOperatingInstructionOptions{`,+ `SupportsTools: exposeTools`,+ `func MCPManifestResourceProjectionSupported(manifest Manifest, surfaceID string) bool`,+ `func ManifestSurfaceResourceCapabilities(manifest Manifest, surfaceID string) []Capability`,+ `func MCPManifestPromptProjectionSupported(manifest Manifest) bool`,+ `func MCPManifestSurfacePromptProjectionSupported(manifest Manifest, surfaceID string) bool`,+ `func ProjectMCPWorkflowPrompts(workflowPrompts []PulseWorkflowPrompt) []MCPPrompt`,+ `func DecodeMCPGetPromptParams(raw json.RawMessage) (MCPGetPromptParams, error)`,+ `func GetMCPPromptFromManifest(manifest Manifest, raw json.RawMessage) (MCPGetPromptResult, error)`,+ `func GetMCPPromptFromManifestSurface(manifest Manifest, surfaceID string, raw json.RawMessage) (MCPGetPromptResult, error)`,+ `func BuildMCPPromptFromManifest(manifest Manifest, params MCPGetPromptParams) (MCPGetPromptResult, error)`,+ `ManifestPulseWorkflowPrompts(manifest)`,+ `func MCPResourceURI(resourceID string) string`,+ `func ResourceIDFromMCPResourceURI(rawURI string) (string, error)`,+ `func DecodeMCPReadResourceParams(raw json.RawMessage) (MCPReadResourceParams, error)`,+ `func ListMCPManifestSurfaceResourcesHTTP(`,+ `func ReadMCPManifestSurfaceResourceHTTP(`,+ `func resolveMCPManifestSurfaceResourceCapabilities(`,+ `CallRequestResponseCapabilityHTTPBodyByName(ctx, client, baseURL, token, capabilities, FleetContextCapabilityName, map[string]any{})`,+ `CallRequestResponseCapabilityHTTPBodyByName(ctx, client, baseURL, token, capabilities, ResourceContextCapabilityName, map[string]any{`,+ `ResourceIDArgumentName: resourceID`,+ `caps.Tools = &MCPToolsCapability{}`,+ `MCPPulseNotificationsExperimentalKey: MCPPulseNotificationsCapability`,+ `type MCPToolServerHandlers struct`,+ `func DecodeJSONRPCRequest(`,+ `fmt.Errorf("malformed JSON-RPC request: %w", err)`,+ `func NewJSONRPCParseErrorResponse(`,+ `func JSONRPCRequestExpectsResponse(`,+ `type JSONRPCLineDispatcher func(context.Context, JSONRPCRequest) JSONRPCResponse`,+ `type JSONRPCResponseWriter func(JSONRPCResponse) error`,+ `func ServeJSONRPCLines(`,+ `scanner.Buffer(make([]byte, 64*1024), 1<<22)`,+ `DecodeJSONRPCRequest([]byte(line))`,+ `NewJSONRPCParseErrorResponse(err)`,+ `JSONRPCRequestExpectsResponse(req)`,+ `func WriteJSONRPCMessage(`,+ `enc.SetEscapeHTML(false)`,+ `type MCPManifestToolServer struct`,+ `SurfaceID string`,+ `func (s MCPManifestToolServer) Handlers(`,+ `func (s MCPManifestToolServer) Initialize() MCPInitializeResult`,+ `func (s MCPManifestToolServer) ToolsList() MCPProjectedToolsResult`,+ `func (s MCPManifestToolServer) ToolsCall(ctx context.Context, raw json.RawMessage) (MCPToolResult, error)`,+ `func (s MCPManifestToolServer) ResourcesList(ctx context.Context) (MCPListResourcesResult, error)`,+ `func (s MCPManifestToolServer) ResourcesRead(ctx context.Context, raw json.RawMessage) (MCPReadResourceResult, error)`,+ `func (s MCPManifestToolServer) PromptsList() MCPListPromptsResult`,+ `func (s MCPManifestToolServer) PromptsGet(ctx context.Context, raw json.RawMessage) (MCPGetPromptResult, error)`,+ `return NewMCPManifestSurfaceToolServerInitializeResult(s.ServerName, s.ServerVersion, s.EmitPulseNotifications, s.Manifest, s.surfaceID())`,+ `if !s.surfaceAffordances().Tools`,+ `return MCPProjectedToolsResult{Tools: ProjectManifestSurfaceTools(s.Manifest, s.surfaceID())}`,+ `return ExecuteMCPManifestSurfaceToolHTTP(ctx, s.Client, s.BaseURL, s.Token, s.Manifest, s.surfaceID(), raw)`,+ `return ListMCPManifestSurfaceResourcesHTTP(ctx, s.Client, s.BaseURL, s.Token, s.Manifest, s.surfaceID())`,+ `return ReadMCPManifestSurfaceResourceHTTP(ctx, s.Client, s.BaseURL, s.Token, s.Manifest, s.surfaceID(), raw)`,+ `if !affordances.Resources`,+ `fmt.Errorf("MCP resources are not enabled for surface %s", surfaceID)`,+ `return (MCPListPromptsResult{Prompts: ProjectMCPWorkflowPrompts(ManifestPulseWorkflowPrompts(s.Manifest))}).NormalizeCollections()`,+ `result, err := GetMCPPromptFromManifestSurface(s.Manifest, s.surfaceID(), raw)`,+ `func (s MCPManifestToolServer) surfaceAffordances() SurfaceAffordanceContract`,+ `func (s MCPManifestToolServer) surfaceID() string`,+ `func normalizeMCPManifestSurfaceID(surfaceID string) string`,+ `func DispatchMCPToolServerRequest(`,+ `case MCPMethodInitialize:`,+ `case MCPMethodToolsList:`,+ `case MCPMethodToolsCall:`,+ `case MCPMethodResourcesList:`,+ `case MCPMethodResourcesRead:`,+ `case MCPMethodPromptsList:`,+ `case MCPMethodPromptsGet:`,+ `return NewJSONRPCResponse(req.ID, result.NormalizeCollections())`,+ `NewJSONRPCErrorResponse(req.ID, JSONRPCErrorInternal, err.Error(), nil)`,+ `NewJSONRPCErrorResponse(req.ID, JSONRPCErrorMethodNotFound, fmt.Sprintf("method not found: %s", req.Method), nil)`,+ `func DecodeMCPCallToolParams(`,+ `params = NormalizeToolCallParams(params)`,+ `ValidateToolCallParams(params)`,+ `func PrepareToolRegistryExecution(name string, args map[string]any) (ToolCallParams, ToolResult, bool)`,+ `func NewInvalidToolCallParamsResult(err error) ToolResult`,+ `func NewUnknownToolResult(name string) ToolResult`,+ `func NewControlToolsDisabledToolResult() ToolResult`,+ `func ExecuteMCPManifestSurfaceToolHTTP(`,+ `DecodeMCPCallToolParams(raw)`,+ `ManifestSurfaceAffordances(manifest, surfaceID)`,+ `ManifestSurfaceToolCapabilities(manifest, surfaceID)`,+ `return ExecuteCapabilityToolHTTP(ctx, client, baseURL, token, ManifestSurfaceToolCapabilities(manifest, surfaceID), params)`,+ `OutputSchema: ToolOutputSchema(cap)`,+ `func ToolOutputSchema(cap Capability) json.RawMessage`,+ `func ExecuteCapabilityToolHTTP(`,+ `params = NormalizeToolCallParams(params)`,+ `ValidateToolCallParams(params)`,+ `CallRequestResponseCapabilityHTTPByName(ctx, client, baseURL, token, capabilities, params.Name, params.Arguments)`,+ `var lookupErr CapabilityLookupError`,+ `errors.As(err, &lookupErr)`,+ `return NewCapabilityHTTPToolResult(resp), nil`,+ `func NewToolTextContent(text string) ToolContent`,+ `func NewToolTextResult(text string) ToolResult`,+ `func NewToolErrorResult(err error) ToolResult`,+ `func NewToolJSONResult(data any) ToolResult`,+ `func NewToolJSONResultWithIsError(data any, isError bool) ToolResult`,+ `func NewToolHTTPTextResult(`,+ `func NewCapabilityHTTPToolResult(`,+ `func ToolStructuredContentFromJSON(`,+ `func CloneToolStructuredContent(`,+ `func ToolResultText(result ToolResult) string`,+ `type ToolResultInterpretation struct`,+ `func InterpretToolResult(result ToolResult) ToolResultInterpretation`,+ `ApprovalRequired: HasApprovalRequiredToolMarker(text)`,+ `PolicyBlocked: HasPolicyBlockedToolMarker(text)`,+ `type DirectToolExecutionOptions struct`,+ `type DirectToolExecutionOutcome struct`,+ `func InterpretDirectToolExecution(result ToolResult, opts DirectToolExecutionOptions) (DirectToolExecutionOutcome, error)`,+ `resp.OK()`,+ `func NewJSONRPCNotification(`,+ `func NewMCPEventNotification(`,+ `const (`,+ `MCPProtocolVersion = "2025-06-18"`,+ `MCPMethodResourcesList = "resources/list"`,+ `MCPMethodResourcesRead = "resources/read"`,+ `MCPMethodPromptsList = "prompts/list"`,+ `MCPMethodPromptsGet = "prompts/get"`,+ `MCPResourceContextURIHost = "resource"`,+ `MCPResourceContextMIMEType = "application/json"`,+ } {+ if !strings.Contains(mcpWireContract, fragment) {+ t.Errorf("agentcapabilities must own the shared MCP wire/result envelope; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `func MCPResourceProjectionSupported(capabilities []Capability) bool`,+ `func ListMCPResourcesHTTP(ctx context.Context, client HTTPDoer, baseURL, token string, capabilities []Capability)`,+ `func ReadMCPResourceHTTP(ctx context.Context, client HTTPDoer, baseURL, token string, capabilities []Capability`,+ `return ListMCPResourcesHTTP(ctx, s.Client, s.BaseURL, s.Token, s.Manifest.Capabilities)`,+ `return ReadMCPResourceHTTP(ctx, s.Client, s.BaseURL, s.Token, s.Manifest.Capabilities, raw)`,+ } {+ if strings.Contains(mcpWireContract, fragment) {+ t.Errorf("shared MCP resource projection must be manifest-surface-owned, not raw-capability-owned; found %s", fragment)+ }+ }+ for _, fragment := range []string{+ `func MCPPromptProjectionSupported(capabilities []Capability) bool`,+ `func ProjectMCPPrompts(capabilities []Capability) []MCPPrompt`,+ `func GetMCPPrompt(capabilities []Capability, raw json.RawMessage)`,+ `func BuildMCPPrompt(capabilities []Capability, params MCPGetPromptParams)`,+ `return GetMCPPromptFromManifest(s.Manifest, raw)`,+ } {+ if strings.Contains(mcpWireContract, fragment) {+ t.Errorf("shared MCP prompt projection must be manifest-owned, not raw-capability-owned; found %s", fragment)+ }+ }+ for _, fragment := range []string{+ `type ToolCallParams struct`,+ `func NormalizeToolCallParams(params ToolCallParams) ToolCallParams`,+ `func ValidateToolCallParams(params ToolCallParams) error`,+ `func PrepareToolRegistryExecution(name string, args map[string]any) (ToolCallParams, ToolResult, bool)`,+ `func NewInvalidToolCallParamsResult(err error) ToolResult`,+ `func NewUnknownToolResult(name string) ToolResult`,+ `func NewControlToolsDisabledToolResult() ToolResult`,+ `type ProjectedTool struct`,+ `OutputSchema json.RawMessage`,+ `Meta map[string]any`,+ `type ToolContent struct`,+ `type ToolResult struct`,+ `StructuredContent map[string]any`,+ `func EmptyToolResult() ToolResult`,+ `func (r ToolResult) NormalizeCollections() ToolResult`,+ `func NewToolTextContent(text string) ToolContent`,+ `func NewToolTextResult(text string) ToolResult`,+ `func NewToolErrorResult(err error) ToolResult`,+ `func NewToolJSONResult(data any) ToolResult`,+ `func NewToolHTTPTextResult(`,+ `func NewCapabilityHTTPToolResult(`,+ `func ToolOutputSchema(cap Capability) json.RawMessage`,+ `func ToolStructuredContentFromJSON(`,+ `func CloneToolStructuredContent(`,+ `func ToolResultText(result ToolResult) string`,+ `type ToolResultInterpretation struct`,+ `func InterpretToolResult(result ToolResult) ToolResultInterpretation`,+ `func ExecuteCapabilityToolHTTP(`,+ `type DirectToolExecutionOptions struct`,+ `type DirectToolExecutionOutcome struct`,+ `func InterpretDirectToolExecution(result ToolResult, opts DirectToolExecutionOptions) (DirectToolExecutionOutcome, error)`,+ } {+ if strings.Contains(mcpWire, fragment) {+ t.Errorf("neutral Pulse Intelligence tool primitive must not be implemented in mcp.go; found %s", fragment)+ }+ if !strings.Contains(toolCore, fragment) {+ t.Errorf("neutral Pulse Intelligence tool primitive must live outside mcp.go; missing %s", fragment)+ }+ }++ workflowPromptSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "workflow_prompt.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/workflow_prompt.go: %v", err)+ }+ workflowPromptCore := string(workflowPromptSource)+ for _, fragment := range []string{+ `PulseWorkflowPromptTriageFleet = "pulse_triage_fleet"`,+ `PulseWorkflowPromptOperationsLoop`,+ `MCPPromptTriageFleet = PulseWorkflowPromptTriageFleet`,+ `MCPPromptOperationsLoop`,+ `type PulseWorkflowPrompt struct`,+ `type PulseWorkflowPromptArgument struct`,+ `type PulseWorkflowPromptParams struct`,+ `type PulseWorkflowPromptResult struct`,+ `type PulseWorkflowPromptRenderOptions struct`,+ `func ManifestPulseWorkflowPrompts(manifest Manifest) []PulseWorkflowPrompt`,+ `func ProjectPulseWorkflowPrompts(capabilities []Capability) []PulseWorkflowPrompt`,+ `func BuildPulseWorkflowPrompt(capabilities []Capability, params PulseWorkflowPromptParams) (PulseWorkflowPromptResult, error)`,+ `func BuildPulseWorkflowPromptWithOptions(capabilities []Capability, params PulseWorkflowPromptParams, opts PulseWorkflowPromptRenderOptions) (PulseWorkflowPromptResult, error)`,+ `func BuildPulseWorkflowPromptFromManifest(manifest Manifest, params PulseWorkflowPromptParams) (PulseWorkflowPromptResult, error)`,+ `func BuildPulseWorkflowPromptFromManifestWithOptions(manifest Manifest, params PulseWorkflowPromptParams, opts PulseWorkflowPromptRenderOptions) (PulseWorkflowPromptResult, error)`,+ `func RequiredPulseWorkflowPromptArgument(args map[string]string, name string) (string, error)`,+ `Name: ResourceIDArgumentName`,+ `RequiredPulseWorkflowPromptArgument(params.Arguments, ResourceIDArgumentName)`,+ `ResourceIDArgumentName, resourceID`,+ `Name: FindingIDArgumentName`,+ `FindCapability(capabilities, ListFindingsCapabilityName)`,+ `RequiredPulseWorkflowPromptArgument(params.Arguments, FindingIDArgumentName)`,+ `ListFindingsCapabilityName`,+ `PlanActionCapabilityName`,+ `DecideActionCapabilityName`,+ `ExecuteActionCapabilityName`,+ `ResolveFindingCapabilityName`,+ `Triage the Pulse fleet using the canonical fleet context capability`,+ `Review one Patrol finding and propose the safest governed next step`,+ `Patrol issue handling`,+ `Do not execute write tools unless the operator explicitly asks for a governed action`,+ } {+ if !strings.Contains(workflowPromptCore, fragment) {+ t.Errorf("neutral Pulse Intelligence workflow prompt contract must live outside mcp.go; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `func PulseWorkflowPromptProjectionSupported(capabilities []Capability) bool`,+ } {+ if strings.Contains(workflowPromptCore, fragment) {+ t.Errorf("shared workflow prompt projection must be manifest-owned, not raw-capability-owned; found %s", fragment)+ }+ }+ for _, fragment := range []string{+ `Pulse fleet triage`,+ `Triage the Pulse fleet using the canonical fleet context capability`,+ `Review one Patrol finding and propose the safest governed next step`,+ `prompt argument %s is required`,+ `func RequiredPulseWorkflowPromptArgument`,+ } {+ if strings.Contains(mcpWire, fragment) {+ t.Errorf("MCP edge must not own neutral Pulse Intelligence workflow prompt behavior; found %s", fragment)+ }+ }+ for _, fragment := range []string{+ `func NormalizeMCPCallToolParams(`,+ `func ValidateMCPCallToolParams(`,+ `func ProjectProviderToolCallToMCP(`,+ `func PrepareMCPToolRegistryExecution(`,+ `func NewInvalidMCPToolCallParamsResult(`,+ `func NewUnknownMCPToolResult(`,+ `func NewControlToolsDisabledMCPToolResult(`,+ `func EmptyMCPToolResult(`,+ `func NewMCPTextContent(`,+ `func NewMCPTextResult(`,+ `func NewMCPErrorResult(`,+ `func NewProviderToolResultFromMCP(`,+ `func NewMCPToolResponseResult(`,+ `func NewMCPJSONResult(`,+ `func NewMCPJSONResultWithIsError(`,+ `func NewMCPHTTPTextResult(`,+ `func NewMCPCapabilityHTTPResult(`,+ `func MCPToolResultText(`,+ `type MCPToolResultInterpretation`,+ `func InterpretMCPToolResult(`,+ `type DirectMCPToolExecutionOptions`,+ `type DirectMCPToolExecutionOutcome`,+ `func InterpretDirectMCPToolExecution(`,+ } {+ if strings.Contains(mcpWire, fragment) {+ t.Errorf("MCP edge must not preserve compatibility wrappers around neutral tool helpers; found %s", fragment)+ }+ }++ sseSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "sse.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/sse.go: %v", err)+ }+ sse := string(sseSource)+ for _, fragment := range []string{+ `type SSERecord struct`,+ `const AgentSSEAccept = "text/event-stream"`,+ `func ScanSSERecords(`,+ `scanner.Buffer(make([]byte, 64*1024), 1<<22)`,+ `case "event":`,+ `case "data":`,+ `strings.Join(dataLines, "\n")`,+ `func StreamAgentSSERecords(`,+ `NewAgentHTTPRequest(ctx, http.MethodGet, baseURL, path, token, nil)`,+ `req.Header.Set("Accept", AgentSSEAccept)`,+ `httpClient(client).Do(req)`,+ `ScanSSERecords(resp.Body, handle)`,+ `func IsActionableSSERecord(`,+ `func StreamAgentActionableSSERecords(`,+ `type MCPEventNotificationWriter func(JSONRPCRequest) error`,+ `func StreamMCPEventNotifications(`,+ `StreamAgentActionableSSERecords(ctx, client, baseURL, path, token, func(record SSERecord) bool`,+ `NewMCPEventNotification(record.Event, []byte(record.Data))`,+ } {+ if !strings.Contains(sse, fragment) {+ t.Errorf("agentcapabilities must own the shared agent SSE parser, subscription transport, and MCP notification bridge; missing %s", fragment)+ }+ }++ textInvocationSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "text_tool_invocation.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/text_tool_invocation.go: %v", err)+ }+ textInvocation := string(textInvocationSource)+ for _, fragment := range []string{+ `func IsTextToolInvocation(command string) bool`,+ `func ParseTextToolInvocation(command string) (ToolCallParams, error)`,+ `const ApprovalArgumentKey = "_approval_id"`,+ `func ApprovalArgument(args map[string]any) string`,+ `func IsInternalToolArgument(name string) bool`,+ `func CloneToolArguments(args map[string]any) map[string]any`,+ `func PublicToolArguments(args map[string]any) map[string]any`,+ `func WithApprovalArgument(args map[string]any, approvalID string) map[string]any`,+ `cloned[k] = cloneSchemaValue(v)`,+ `public[k] = cloneSchemaValue(v)`,+ `strings.TrimPrefix(command, "default_api:")`,+ `args := make(map[string]any)`,+ `ToolCallParams{Name: toolName, Arguments: args}`,+ `ValidateToolCallParams(params)`,+ `func splitTextToolArguments(argsStr string) []string`,+ } {+ if !strings.Contains(textInvocation, fragment) {+ t.Errorf("agentcapabilities must own the shared text tool invocation parser; missing %s", fragment)+ }+ }++ aiRelaySource, err := os.ReadFile("router_routes_ai_relay.go")+ if err != nil {+ t.Fatalf("read internal/api/router_routes_ai_relay.go: %v", err)+ }+ aiRelay := string(aiRelaySource)+ for _, fragment := range []string{+ `agentcapabilities.ParseTextToolInvocation(command)`,+ `params.Arguments = agentcapabilities.WithApprovalArgument(params.Arguments, approvalID)`,+ `chatService.ExecuteAssistantTool(ctx, params.Name, params.Arguments)`,+ } {+ if !strings.Contains(aiRelay, fragment) {+ t.Errorf("AI relay MCP executor must consume the shared text tool invocation parser; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `func parseMCPToolCall(`,+ `func splitToolArgs(`,+ `func isMCPToolCall(`,+ `params.Arguments["_approval_id"]`,+ } {+ if strings.Contains(aiRelay, fragment) {+ t.Errorf("AI relay must not preserve local text tool invocation parsing; found %s", fragment)+ }+ }++ assistantToolFiles := []string{+ filepath.Join("..", "ai", "chat", "agentic.go"),+ filepath.Join("..", "ai", "tools", "tools_control.go"),+ filepath.Join("..", "ai", "tools", "tools_docker.go"),+ filepath.Join("..", "ai", "tools", "tools_file.go"),+ filepath.Join("..", "ai", "tools", "tools_kubernetes.go"),+ }+ for _, path := range assistantToolFiles {+ source, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read %s: %v", path, err)+ }+ if strings.Contains(string(source), `["_approval_id"]`) {+ t.Errorf("%s must consume shared approved-action argument helpers instead of local key indexing", path)+ }+ }++ httpSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "http.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/http.go: %v", err)+ }+ agentHTTP := string(httpSource)+ for _, fragment := range []string{+ `const (`,+ `AgentCapabilitiesPath = "/api/agent/capabilities"`,+ `AgentAPITokenHeader = "X-API-Token"`,+ `type HTTPCallResponse struct`,+ `func NewAgentHTTPRequest(`,+ `func FetchManifest(`,+ `func BuildCapabilityHTTPRequest(`,+ `func CallCapabilityHTTP(`,+ `func CallCapabilityHTTPByName(`,+ `func CallRequestResponseCapabilityHTTPByName(`,+ `func (r HTTPCallResponse) FailureError() error`,+ `ProjectCapabilityCall(cap, args)`,+ `ResolveRequestResponseCapability(capabilities, name)`,+ `ResolveCapability(capabilities, name)`,+ `DecodeErrorEnvelope(r.Body)`,+ } {+ if !strings.Contains(agentHTTP, fragment) {+ t.Errorf("agentcapabilities must own the shared agent HTTP substrate; missing %s", fragment)+ }+ }+ if !strings.Contains(projection, `for k, v := range PublicToolArguments(args)`) {+ t.Error("manifest-backed HTTP projection must strip internal tool-call arguments before building public request bodies")+ }++ toolResponseSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "tool_response.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/tool_response.go: %v", err)+ }+ toolResponse := string(toolResponseSource)+ for _, fragment := range []string{+ `type ToolResponse struct`,+ `type ToolError struct`,+ `ErrCodeFSMBlocked`,+ `ErrCodeStrictResolution`,+ `ErrCodeRoutingMismatch`,+ `ErrCodeExecutionContextUnavailable`,+ `func NewToolBlockedError(`,+ `func NewToolResponseResult(resp ToolResponse) ToolResult`,+ `func ToolResultErrorCode(resultText string) (string, bool)`,+ `func ToolResultHasErrorCode(resultText, code string) bool`,+ `func ToolResultHasVerificationOK(resultText string) bool`,+ } {+ if !strings.Contains(toolResponse, fragment) {+ t.Errorf("agentcapabilities must own the shared tool response envelope; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `func NewMCPToolResponseResult(`,+ } {+ if strings.Contains(toolResponse, fragment) {+ t.Errorf("neutral tool response envelope must not own MCP compatibility wrappers; found %s", fragment)+ }+ }++ agenticVerificationSource, err := os.ReadFile(filepath.Join("..", "ai", "chat", "agentic_verification.go"))+ if err != nil {+ t.Fatalf("read internal/ai/chat/agentic_verification.go: %v", err)+ }+ if strings.Contains(string(agenticVerificationSource), `func toolResultHasVerificationOK(`) {+ t.Error("chat FSM verification evidence parsing must live in shared agentcapabilities, not a chat-local helper")+ }+ agenticSource, err := os.ReadFile(filepath.Join("..", "ai", "chat", "agentic.go"))+ if err != nil {+ t.Fatalf("read internal/ai/chat/agentic.go: %v", err)+ }+ if !strings.Contains(string(agenticSource), `agentcapabilities.ToolResultHasVerificationOK(resultText)`) {+ t.Error("chat FSM self-verification must consume the shared tool-result verification parser")+ }+ if !strings.Contains(string(agenticSource), `agentcapabilities.ToolResultHasErrorCode(resultText, agentcapabilities.ErrCodeStrictResolution)`) {+ t.Error("chat strict-resolution recovery must consume the shared tool-result error-code parser")+ }+ if strings.Contains(string(agenticSource), `strings.Contains(resultText, "STRICT_RESOLUTION")`) {+ t.Error("chat strict-resolution recovery must not use local string matching")+ }+ if !strings.Contains(string(agenticSource), `agentcapabilities.ErrCodeFSMBlocked`) {+ t.Error("chat FSM recovery tracking must consume the shared FSM-blocked error code")+ }+ if strings.Contains(string(agenticSource), `"FSM_BLOCKED"`) {+ t.Error("chat FSM recovery tracking must not hard-code the FSM-blocked error code")+ }++ toolMarkerSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "tool_marker.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/tool_marker.go: %v", err)+ }+ toolMarker := string(toolMarkerSource)+ for _, fragment := range []string{+ `ToolMarkerApprovalRequiredPrefix = ErrCodeApprovalRequired + ":"`,+ `ToolMarkerPolicyBlockedPrefix = ErrCodePolicyBlocked + ":"`,+ `ToolMarkerApprovalRequiredType = "approval_required"`,+ `ToolMarkerPolicyBlockedType = "policy_blocked"`,+ `type ApprovalRequiredToolMarkerData struct`,+ `func (d ApprovalRequiredToolMarkerData) TargetHint() string`,+ `func (d ApprovalRequiredToolMarkerData) DescriptionText() string`,+ `func ApprovalRequiredToolMarker(`,+ `func PolicyBlockedToolMarker(`,+ `func FormatApprovalRequiredToolMarker(`,+ `func FormatPolicyBlockedToolMarker(`,+ `func HasApprovalRequiredToolMarker(`,+ `func HasPolicyBlockedToolMarker(`,+ `func ApprovalRequiredToolMarkerPayloadJSON(`,+ `func ParseApprovalRequiredToolMarkerPayload(`,+ `func ParseApprovalRequiredToolMarkerData(`,+ } {+ if !strings.Contains(toolMarker, fragment) {+ t.Errorf("agentcapabilities must own the shared Assistant tool marker vocabulary; missing %s", fragment)+ }+ }++ controlLevelSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "control_level.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/control_level.go: %v", err)+ }+ controlLevel := string(controlLevelSource)+ for _, fragment := range []string{+ `type ControlLevel string`,+ `ControlLevelReadOnly`,+ `ControlLevelControlled`,+ `ControlLevelAutonomous`,+ `func NormalizeControlLevel(`,+ `func IsValidControlLevel(`,+ `func ControlLevelAllowsControlTools(`,+ } {+ if !strings.Contains(controlLevel, fragment) {+ t.Errorf("agentcapabilities must own the shared control-level contract; missing %s", fragment)+ }+ }++ typesSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "types.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/types.go: %v", err)+ }+ typesSrc := string(typesSource)+ for _, fragment := range []string{+ `const ControlToolsDisabledMessage = "Control tools are disabled.`,+ `func NormalizeToolGovernance(`,+ `func NormalizeCapabilityGovernance(cap Capability) ToolGovernance`,+ `func CapabilityActionMode(cap Capability) ActionMode`,+ `func NewToolGovernanceDescriptor(`,+ `func NormalizeToolGovernanceDescriptor(descriptor ToolGovernanceDescriptor) ToolGovernanceDescriptor`,+ `governance.ActionMode = ActionModeWrite`,+ `CapabilityActionMode(cap)`,+ `governance.ApprovalPolicy = ApprovalPolicyActionPlan`,+ `DefaultApprovalPolicyDescription(governance.ApprovalPolicy)`,+ `ToolGovernanceDescriptor{`,+ } {+ if !strings.Contains(typesSrc, fragment) {+ t.Errorf("agentcapabilities must own shared tool-governance defaults; missing %s", fragment)+ }+ }+ governancePromptSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "governance_prompt.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/governance_prompt.go: %v", err)+ }+ governancePromptSrc := string(governancePromptSource)+ for _, fragment := range []string{+ `type ToolGovernancePromptOptions struct`,+ `type PulseIntelligenceOperatingInstructionOptions struct`,+ `func BuildToolGovernancePromptSection(`,+ `func BuildAssistantToolGovernancePromptSection(`,+ `func BuildPulseIntelligenceOperatingInstructions() string`,+ `func BuildPulseAssistantOperatingInstructions() string`,+ `type PulseMCPOperatingInstructionOptions struct`,+ `func BuildPulseMCPOperatingInstructions(`,+ `func BuildPulseIntelligenceOperatingInstructionsForSurface(`,+ `ResolveSurfaceAffordanceContract(`,+ `func ToolGovernancePromptLine(`,+ `func ToolGovernancePromptDescription(`,+ `func AssistantGovernanceOfferedToolNames(`,+ `AdditionalToolGovernanceLines []string`,+ `const PulseQuestionToolName = "pulse_question"`,+ `func PulseQuestionToolGovernancePromptLine() string`,+ `SupportsInteractiveQuestions bool`,+ `SurfaceAffordanceLabels(surfaceAffordancesFromOptions(opts))`,+ `## PULSE INTELLIGENCE OPERATING MODEL`,+ `No Pulse tools are offered for this turn.`,+ `This manifest is generated from Pulse's governed tool registry.`,+ `ApprovalPolicyScopeOnly`,+ `ActionModeRead`,+ } {+ if !strings.Contains(governancePromptSrc, fragment) {+ t.Errorf("agentcapabilities must own shared tool-governance prompt projection; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `func CloneCapability(cap Capability) Capability`,+ `func CloneCapabilities(capabilities []Capability) []Capability`,+ `cap.InputSchema = CloneRawMessage(cap.InputSchema)`,+ } {+ if !strings.Contains(typesSrc, fragment) {+ t.Errorf("agentcapabilities must own detached capability projection helpers; missing %s", fragment)+ }+ }++ textToolInvocationSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "text_tool_invocation.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/text_tool_invocation.go: %v", err)+ }+ textToolInvocation := string(textToolInvocationSource)+ for _, fragment := range []string{+ `const CurrentResourceHandle = "current_resource"`,+ `func IsCurrentResourceReference(value string) bool`,+ `func ToolInputContainsCurrentResourceReference(value any) bool`,+ `currentResourceReferenceAliases`,+ `"redacted by policy"`,+ } {+ if !strings.Contains(textToolInvocation, fragment) {+ t.Errorf("agentcapabilities must own shared current_resource tool-argument semantics; missing %s", fragment)+ }+ }++ configSource, err := os.ReadFile(filepath.Join("..", "config", "ai.go"))+ if err != nil {+ t.Fatalf("read internal/config/ai.go: %v", err)+ }+ configAI := string(configSource)+ for _, fragment := range []string{+ `ControlLevelReadOnly = string(agentcapabilities.ControlLevelReadOnly)`,+ `ControlLevelControlled = string(agentcapabilities.ControlLevelControlled)`,+ `ControlLevelAutonomous = string(agentcapabilities.ControlLevelAutonomous)`,+ `return string(agentcapabilities.NormalizeControlLevel(c.ControlLevel))`,+ `return agentcapabilities.ControlLevelAllowsControlTools(agentcapabilities.ControlLevel(c.GetControlLevel()))`,+ `return agentcapabilities.IsValidControlLevel(level)`,+ } {+ if !strings.Contains(configAI, fragment) {+ t.Errorf("AI config must alias shared control-level vocabulary; missing %s", fragment)+ }+ }++ assistantProtocol, err := os.ReadFile(filepath.Join("..", "ai", "tools", "protocol.go"))+ if err != nil {+ t.Fatalf("read internal/ai/tools/protocol.go: %v", err)+ }+ assistantSrc := string(assistantProtocol)+ for _, fragment := range []string{+ `type Tool = agentcapabilities.Tool`,+ `type CallToolResult = agentcapabilities.ToolResult`,+ `type Content = agentcapabilities.ToolContent`,+ `type CallToolParams = agentcapabilities.ToolCallParams`,+ `type ToolResponse = agentcapabilities.ToolResponse`,+ `type ToolError = agentcapabilities.ToolError`,+ `ErrCodeStrictResolution`,+ `agentcapabilities.ErrCodeStrictResolution`,+ `ErrCodeRoutingMismatch`,+ `agentcapabilities.ErrCodeRoutingMismatch`,+ `return agentcapabilities.NewToolTextResult(text)`,+ `return agentcapabilities.NewToolJSONResultWithIsError(data, isError)`,+ `return agentcapabilities.NewToolResponseResult(resp)`,+ } {+ if !strings.Contains(assistantSrc, fragment) {+ t.Errorf("Assistant tool protocol must wrap the shared tool result envelope; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `type Request = agentcapabilities.JSONRPCRequest`,+ `type Response = agentcapabilities.JSONRPCResponse`,+ `type Error = agentcapabilities.JSONRPCError`,+ `type InitializeResult = agentcapabilities.MCPInitializeResult`,+ `type ServerInfo = agentcapabilities.MCPServerInfo`,+ `type ListToolsResult = agentcapabilities.MCPListToolsResult`,+ `type Resource = agentcapabilities.MCPResource`,+ `type Prompt = agentcapabilities.MCPPrompt`,+ } {+ if strings.Contains(assistantSrc, fragment) {+ t.Errorf("native Assistant tool protocol must not expose MCP/JSON-RPC wire aliases; found %s", fragment)+ }+ }++ providerSource, err := os.ReadFile(filepath.Join("..", "ai", "providers", "provider.go"))+ if err != nil {+ t.Fatalf("read internal/ai/providers/provider.go: %v", err)+ }+ providerSrc := string(providerSource)+ for _, fragment := range []string{+ `type Tool = agentcapabilities.ProviderTool`,+ `type ToolCall = agentcapabilities.ProviderToolCall`,+ `type ToolResult = agentcapabilities.ProviderToolResult`,+ `return agentcapabilities.EmptyProviderTool()`,+ `return agentcapabilities.EmptyProviderToolCall()`,+ } {+ if !strings.Contains(providerSrc, fragment) {+ t.Errorf("Assistant providers must alias the shared provider tool shape; missing %s", fragment)+ }+ }++ for _, path := range []string{+ filepath.Join("..", "ai", "chat", "tools.go"),+ filepath.Join("..", "ai", "tools", "schema_projection.go"),+ } {+ if _, err := os.Stat(path); err == nil {+ t.Errorf("%s must not keep provider projection compatibility wrappers; use internal/agentcapabilities directly", path)+ } else if !os.IsNotExist(err) {+ t.Fatalf("stat %s: %v", path, err)+ }+ }++ assistantQuestionToolSource, err := os.ReadFile(filepath.Join("..", "ai", "chat", "agentic_question_tool.go"))+ if err != nil {+ t.Fatalf("read internal/ai/chat/agentic_question_tool.go: %v", err)+ }+ assistantQuestionToolSrc := string(assistantQuestionToolSource)+ for _, fragment := range []string{+ `const pulseQuestionToolName = agentcapabilities.PulseQuestionToolName`,+ `agentcapabilities.ParsePulseQuestionToolInput(input)`,+ } {+ if !strings.Contains(assistantQuestionToolSrc, fragment) {+ t.Errorf("Assistant question tool must use shared provider declaration; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `InputSchema: map[string]interface{}{`,+ `Name: pulseQuestionToolName`,+ `Description: "Ask the user for missing information using a structured prompt.`,+ `func userQuestionTool()`,+ `type questionToolInputPayload struct`,+ `type questionToolInputQuestion struct`,+ `type questionToolInputOption struct`,+ `func parseQuestionToolOptions(`,+ `type questionToolType string`,+ `questionToolTypeText`,+ `questionToolTypeSelect`,+ `func normalizeQuestionToolType(`,+ `agentcapabilities.NormalizePulseQuestionToolType(parsedQuestion.Type, len(opts) > 0)`,+ } {+ if strings.Contains(assistantQuestionToolSrc, fragment) {+ t.Errorf("Assistant question tool must not keep a chat-local provider declaration; found %s", fragment)+ }+ }++ assistantFSMSource, err := os.ReadFile(filepath.Join("..", "ai", "chat", "fsm.go"))+ if err != nil {+ t.Fatalf("read internal/ai/chat/fsm.go: %v", err)+ }+ assistantFSMSrc := string(assistantFSMSource)+ for _, fragment := range []string{+ `type ToolKind = agentcapabilities.ToolCallKind`,+ `ToolKindResolve = agentcapabilities.ToolCallKindResolve`,+ `ToolKindRead = agentcapabilities.ToolCallKindRead`,+ `ToolKindWrite = agentcapabilities.ToolCallKindWrite`,+ `ToolKindUserInput = agentcapabilities.ToolCallKindUserInput`,+ `return agentcapabilities.ClassifyToolCall(toolName, args)`,+ } {+ if !strings.Contains(assistantFSMSrc, fragment) {+ t.Errorf("Assistant FSM must consume shared tool-call safety classification; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `case agentcapabilities.PulseQuestionToolName:`,+ `case "pulse_question":`,+ `case "pulse_control":`,+ `case "pulse_read":`,+ `writeActions := map[string]bool`,+ `readActions := map[string]bool`,+ `actionLower := strings.ToLower(action)`,+ } {+ if strings.Contains(assistantFSMSrc, fragment) {+ t.Errorf("Assistant FSM must not keep local tool-call safety classification; found %s", fragment)+ }+ }++ chatTypesSource, err := os.ReadFile(filepath.Join("..", "ai", "chat", "types.go"))+ if err != nil {+ t.Fatalf("read internal/ai/chat/types.go: %v", err)+ }+ chatTypesSrc := string(chatTypesSource)+ for _, fragment := range []string{+ `func ToolCallFromProvider(tc agentcapabilities.ProviderToolCall) ToolCall`,+ `func (t ToolCall) ProviderToolCall() agentcapabilities.ProviderToolCall`,+ `type ToolResult = agentcapabilities.ProviderToolResult`,+ } {+ if !strings.Contains(chatTypesSrc, fragment) {+ t.Errorf("Assistant chat transcript must project through shared provider tool shapes; missing %s", fragment)+ }+ }++ aiServiceSource, err := os.ReadFile(filepath.Join("..", "ai", "service.go"))+ if err != nil {+ t.Fatalf("read internal/ai/service.go: %v", err)+ }+ aiServiceSrc := string(aiServiceSource)+ for _, fragment := range []string{+ `type ChatToolCall = agentcapabilities.ProviderToolCall`,+ `return agentcapabilities.EmptyProviderToolCall()`,+ `type ChatToolResult = agentcapabilities.ProviderToolResult`,+ `return agentcapabilities.ApprovalRequiredToolMarker(`,+ `return agentcapabilities.PolicyBlockedToolMarker(command, reason)`,+ `agentcapabilities.ParseApprovalRequiredToolMarkerData(result)`,+ `agentcapabilities.HasApprovalRequiredToolMarker(result)`,+ `agentcapabilities.LegacyAssistantUtilityProviderTools()`,+ `agentcapabilities.LegacyAssistantRunCommandToolName`,+ `agentcapabilities.LegacyAssistantCommandArgumentName`,+ `agentcapabilities.LegacyAssistantURLArgumentName`,+ `agentcapabilities.LegacyAssistantResourceTypeArgumentName`,+ `agentcapabilities.LegacyAssistantResourceIDArgumentName`,+ `projection := newLegacyServiceProviderToolResultContextProjection(tc.ID, result, !execution.Success)`,+ `projection := newLegacyServiceProviderToolResultContextProjection(tc.ID, result, true)`,+ `agentcapabilities.NewProviderToolResultContextProjection(toolUseID, content, isError, legacyServiceProviderToolResultContextOptions())`,+ `ToolResult: &projection.Model`,+ } {+ if !strings.Contains(aiServiceSrc, fragment) {+ t.Errorf("AI service chat messages and tool markers must use shared provider/tool shapes; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `ToolResult: &providers.ToolResult{`,+ `resultForContext`,+ `maxResultSize`,+ `output truncated (`,+ } {+ if strings.Contains(aiServiceSrc, fragment) {+ t.Errorf("AI service must not preserve local provider-result context shaping; found %s", fragment)+ }+ }+ for _, fragment := range []string{+ `Name: "run_command"`,+ `Name: "fetch_url"`,+ `Name: "set_resource_url"`,+ `case "run_command":`,+ `case "fetch_url":`,+ `case "set_resource_url":`,+ `tc.Input["command"]`,+ `tc.Input["run_on_host"]`,+ `tc.Input["target_host"]`,+ `tc.Input["url"]`,+ `tc.Input["resource_type"]`,+ `tc.Input["resource_id"]`,+ } {+ if strings.Contains(aiServiceSrc, fragment) {+ t.Errorf("legacy Assistant utility tool schemas and input keys must stay in agentcapabilities; AI service found %s", fragment)+ }+ }+ if strings.Contains(aiServiceSrc, `func parseApprovalNeededMarker(`) {+ t.Error("AI service approval marker handling must call the shared marker parser directly")+ }++ assistantChatAgentic, err := os.ReadFile(filepath.Join("..", "ai", "chat", "agentic.go"))+ if err != nil {+ t.Fatalf("read internal/ai/chat/agentic.go: %v", err)+ }+ agenticSrc := string(assistantChatAgentic)+ for _, fragment := range []string{+ `providerTools := executor.AssistantProviderTools(agentcapabilities.AssistantProviderToolOptions{`,+ `a.tools = a.executor.AssistantProviderTools(agentcapabilities.AssistantProviderToolOptions{`,+ `IncludeQuestionTool: true`,+ `agentcapabilities.HasApprovalRequiredToolMarker(resultText)`,+ `agentcapabilities.ParseApprovalRequiredToolMarkerData(resultText)`,+ `inputWithApproval = agentcapabilities.WithApprovalArgument(inputWithApproval, approvalData.ApprovalID)`,+ `agentcapabilities.NewProviderToolResultFromToolResult(tc.ID, result)`,+ `projection := newProviderToolResultContextProjection(tc.ID, resultText, isError)`,+ `ToolResult: &projection.Transcript`,+ `ToolResult: &projection.Model`,+ `toolCalls = agentcapabilities.NormalizeProviderToolCallsForExecution(data.ToolCalls)`,+ `agentcapabilities.ToolInputContainsCurrentResourceReference(tc.Input)`,+ } {+ if !strings.Contains(agenticSrc, fragment) {+ t.Errorf("Assistant agentic loop must use shared provider-result and marker vocabulary; missing %s", fragment)+ }+ }+ if strings.Contains(agenticSrc, `ProjectAssistantProviderTools(`) || strings.Contains(agenticSrc, `ListToolGovernance()`) {+ t.Error("Assistant agentic loop must request provider-tool projection from the shared executor entrypoint")+ }+ if strings.Contains(agenticSrc, `resultText = FormatToolResult(result)`) {+ t.Error("Assistant agentic loop must project MCP tool results through shared provider-result construction, not local result text assignment")+ }+ for _, fragment := range []string{+ `agentcapabilities.ApprovalRequiredToolMarkerPayloadJSON(resultText)`,+ `var approvalData struct`,+ "\n\t\t\t\t\t\t\tagentcapabilities.WithApprovalArgument(inputWithApproval, approvalData.ApprovalID)",+ `ToolResult: &providers.ToolResult{`,+ `ToolResult: &ToolResult{`,+ `modelResultText := truncateToolResultForModel(resultText)`,+ `func toolInputContainsCurrentResourceReference`,+ `append(providerTools, userQuestionTool())`,+ `userQuestionTool()`,+ `toolCalls = NormalizeProviderToolCallsForExecution(data.ToolCalls)`,+ `func ConvertPulseToolsToProvider`,+ `func ConvertPulseToolsToProviderWithGovernance`,+ `func ConvertProviderToolCallToMCP`,+ `func NormalizeProviderToolCallForExecution`,+ `func NormalizeProviderToolCallsForExecution`,+ } {+ if strings.Contains(agenticSrc, fragment) {+ t.Errorf("Assistant agentic loop must not assemble provider tool-result structs locally; found %s", fragment)+ }+ }++ currentResourceSource, err := os.ReadFile(filepath.Join("..", "ai", "tools", "current_resource.go"))+ if err != nil {+ t.Fatalf("read internal/ai/tools/current_resource.go: %v", err)+ }+ currentResourceSrc := string(currentResourceSource)+ for _, fragment := range []string{+ `const currentResourceHandle = agentcapabilities.CurrentResourceHandle`,+ `return agentcapabilities.IsCurrentResourceReference(value)`,+ } {+ if !strings.Contains(currentResourceSrc, fragment) {+ t.Errorf("Assistant current_resource executor must use shared handle semantics; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `"attached_resource"`,+ `"selected_resource"`,+ `"this_resource"`,+ `"redacted by policy"`,+ } {+ if strings.Contains(currentResourceSrc, fragment) {+ t.Errorf("Assistant current_resource executor must not keep local handle aliases; found %s", fragment)+ }+ }++ assistantChatContext, err := os.ReadFile(filepath.Join("..", "ai", "chat", "agentic_context.go"))+ if err != nil {+ t.Fatalf("read internal/ai/chat/agentic_context.go: %v", err)+ }+ agenticContextSrc := string(assistantChatContext)+ for _, fragment := range []string{+ `agentcapabilities.ProviderToolResultModelContent(text, providerToolResultContextOptions())`,+ `agentcapabilities.NewProviderToolResultContextProjection(toolUseID, content, isError, providerToolResultContextOptions())`,+ `pm.ToolResult = &projection.Model`,+ `agentcapabilities.NewProviderToolErrorResult(`,+ } {+ if !strings.Contains(agenticContextSrc, fragment) {+ t.Errorf("Assistant provider message conversion must use shared provider-result construction; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `func newProviderToolResult(`,+ `func newProviderToolErrorResult(`,+ `ToolResult: &providers.ToolResult{`,+ } {+ if strings.Contains(agenticContextSrc, fragment) {+ t.Errorf("Assistant provider message conversion must not preserve local provider-result wrappers or structs; found %s", fragment)+ }+ }++ assistantChatService, err := os.ReadFile(filepath.Join("..", "ai", "chat", "service.go"))+ if err != nil {+ t.Fatalf("read internal/ai/chat/service.go: %v", err)+ }+ chatServiceSrc := string(assistantChatService)+ for _, fragment := range []string{+ `manifest = s.executor.ListToolGovernance()`,+ `agentcapabilities.ProviderToolNames(offeredTools)`,+ `agentcapabilities.ProviderToolGovernanceDescriptors(offeredTools)`,+ `agentcapabilities.BuildAssistantToolGovernancePromptSection(manifest, orderedOfferedNames)`,+ `tools.CanonicalToolGovernanceForManifestSurface(`,+ `agentcapabilities.SurfaceIDPulseAssistant`,+ `fallbackAssistantToolGovernanceOfferedNames(manifest)`,+ `agentcapabilities.ManifestSurfaceAffordances(`,+ `providerTools := s.executor.AssistantProviderTools(agentcapabilities.AssistantProviderToolOptions{`,+ `IncludeQuestionTool: includeQuestionTool`,+ `agentcapabilities.BuildPulseAssistantOperatingInstructions()`,+ `func (s *Service) executeAssistantRegistryToolDirect(ctx context.Context, toolName string, args map[string]interface{}, opts agentcapabilities.DirectToolExecutionOptions) (agentcapabilities.DirectToolExecutionOutcome, error)`,+ `outcome, executionErr := s.executeAssistantRegistryToolDirect(ctx, agentcapabilities.PulseRunCommandToolName, args, agentcapabilities.DirectToolExecutionOptions{`,+ `outcome, executionErr := s.executeAssistantRegistryToolDirect(ctx, toolName, args, agentcapabilities.DirectToolExecutionOptions{`,+ `result, toolErr := executor.ExecuteTool(ctx, toolName, args)`,+ `agentcapabilities.InterpretDirectToolExecution(result`,+ `FailurePrefix: "command execution failed"`,+ `ApprovalRequiredMessage: "command requires approval (unexpected in autonomous mode)"`,+ `PolicyBlockedMessage: "command blocked by security policy"`,+ `FailurePrefix: "tool execution failed"`,+ `ApprovalRequiredMessage: "tool requires approval (unexpected in fix execution)"`,+ `PolicyBlockedMessage: "tool blocked by security policy"`,+ } {+ if !strings.Contains(chatServiceSrc, fragment) {+ t.Errorf("Assistant chat service must use shared direct result execution mapping; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `agentcapabilities.DirectMCPToolExecutionOptions`,+ `agentcapabilities.DirectMCPToolExecutionOutcome`,+ `agentcapabilities.InterpretDirectMCPToolExecution`,+ } {+ if strings.Contains(chatServiceSrc, fragment) {+ t.Errorf("Assistant chat service must use neutral direct tool execution helpers, found %s", fragment)+ }+ }+ if strings.Contains(chatServiceSrc, `ProjectAssistantProviderTools(`) {+ t.Error("Assistant chat service must request provider-tool projection from the shared executor entrypoint")+ }+ if strings.Contains(chatServiceSrc, `tools.CanonicalToolGovernanceForSurface(`) ||+ strings.Contains(chatServiceSrc, `tools.ToolGovernanceSurfacePulseAssistant`) {+ t.Error("Assistant chat service fallback governance must enter through manifest surface affordances")+ }+ for _, fragment := range []string{+ `b.WriteString("## AVAILABLE TOOL GOVERNANCE`,+ `agentcapabilities.ToolGovernancePromptOptions{`,+ `agentcapabilities.PulseQuestionToolGovernancePromptLine()`,+ `assistantGovernanceOfferedToolNames`,+ `userQuestionTool()`,+ `mode := tool.ActionMode`,+ `approvalSummary := strings.TrimSpace(tool.ApprovalSummary)`,+ `fmt.Sprintf("- %s: mode=%s; approval=%s`,+ `for _, content := range result.Content`,+ `resultText += content.Text`,+ `agentcapabilities.HasApprovalRequiredToolMarker(resultText)`,+ `agentcapabilities.HasPolicyBlockedToolMarker(resultText)`,+ `interpreted := agentcapabilities.InterpretToolResult(result)`,+ `if interpreted.IsError`,+ `if interpreted.ApprovalRequired`,+ `if interpreted.PolicyBlocked`,+ `func assistantQuestionToolGovernancePromptLine() string`,+ } {+ if strings.Contains(chatServiceSrc, fragment) {+ t.Errorf("Assistant chat service must not flatten or interpret direct MCP result outcomes locally; found %s", fragment)+ }+ }++ chatServiceAdapterSource, err := os.ReadFile(filepath.Join("..", "api", "chat_service_adapter.go"))+ if err != nil {+ t.Fatalf("read internal/api/chat_service_adapter.go: %v", err)+ }+ chatServiceAdapterSrc := string(chatServiceAdapterSource)+ for _, fragment := range []string{+ `func adaptChatMessage(m chat.Message) ai.ChatMessage`,+ `msg.ToolCalls = append(msg.ToolCalls, tc.ProviderToolCall())`,+ `toolResult := *m.ToolResult`,+ } {+ if !strings.Contains(chatServiceAdapterSrc, fragment) {+ t.Errorf("chat service adapter must bridge messages through shared provider tool shapes; missing %s", fragment)+ }+ }++ orchestratorDepsSource, err := os.ReadFile(filepath.Join("..", "..", "pkg", "aicontracts", "orchestrator_deps.go"))+ if err != nil {+ t.Fatalf("read pkg/aicontracts/orchestrator_deps.go: %v", err)+ }+ orchestratorDepsSrc := string(orchestratorDepsSource)+ for _, fragment := range []string{+ `func OrchestratorToolCallInfoFromProvider(tc agentcapabilities.ProviderToolCall) OrchestratorToolCallInfo`,+ `func (t OrchestratorToolCallInfo) ProviderToolCall() agentcapabilities.ProviderToolCall`,+ `func OrchestratorToolResultInfoFromProvider(result agentcapabilities.ProviderToolResult) OrchestratorToolResultInfo`,+ `func (r OrchestratorToolResultInfo) ProviderToolResult() agentcapabilities.ProviderToolResult`,+ `return agentcapabilities.NewProviderToolResult(r.ToolUseID, r.Content, r.IsError)`,+ } {+ if !strings.Contains(orchestratorDepsSrc, fragment) {+ t.Errorf("orchestrator dependency contract must bridge messages through shared provider tool shapes; missing %s", fragment)+ }+ }++ aiHandlersSource, err := os.ReadFile(filepath.Join("..", "api", "ai_handlers.go"))+ if err != nil {+ t.Fatalf("read internal/api/ai_handlers.go: %v", err)+ }+ aiHandlersSrc := string(aiHandlersSource)+ for _, fragment := range []string{+ `aicontracts.OrchestratorToolCallInfoFromProvider(tc.ProviderToolCall())`,+ `toolResult := aicontracts.OrchestratorToolResultInfoFromProvider(*msg.ToolResult)`,+ } {+ if !strings.Contains(aiHandlersSrc, fragment) {+ t.Errorf("orchestrator chat adapter must bridge messages through shared provider tool shapes; missing %s", fragment)+ }+ }++ patrolRuntime, err := os.ReadFile(filepath.Join("..", "ai", "patrol_ai.go"))+ if err != nil {+ t.Fatalf("read internal/ai/patrol_ai.go: %v", err)+ }+ patrolSrc := string(patrolRuntime)+ if strings.Contains(patrolSrc, "func formatToolResult(") {+ t.Error("Patrol runtime must not keep a local result-text wrapper; call agentcapabilities.ToolResultText at the execution site")+ }++ patrolFindings, err := os.ReadFile(filepath.Join("..", "ai", "patrol_findings.go"))+ if err != nil {+ t.Fatalf("read internal/ai/patrol_findings.go: %v", err)+ }+ patrolFindingsSrc := string(patrolFindings)+ for _, fragment := range []string{+ `agentcapabilities.InterpretToolResult(result)`,+ `if interpreted.IsError`,+ `if interpreted.ApprovalRequired`,+ `if interpreted.PolicyBlocked`,+ } {+ if !strings.Contains(patrolFindingsSrc, fragment) {+ t.Errorf("Patrol tool-call records must use shared tool result interpretation; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `output = agentcapabilities.MCPToolResultText(result)`,+ `agentcapabilities.InterpretMCPToolResult(result)`,+ `agentcapabilities.MCPToolResultInterpretation`,+ `success = !result.IsError`,+ `if result.IsError`,+ `formatToolResult(result)`,+ } {+ if strings.Contains(patrolFindingsSrc, fragment) {+ t.Errorf("Patrol tool-call records must not duplicate shared result interpretation locally; found %s", fragment)+ }+ }++ assistantRegistry, err := os.ReadFile(filepath.Join("..", "ai", "tools", "registry.go"))+ if err != nil {+ t.Fatalf("read internal/ai/tools/registry.go: %v", err)+ }+ registrySrc := string(assistantRegistry)+ for _, fragment := range []string{+ `type ControlLevel = agentcapabilities.ControlLevel`,+ `ControlLevelReadOnly ControlLevel = agentcapabilities.ControlLevelReadOnly`,+ `ControlLevelControlled ControlLevel = agentcapabilities.ControlLevelControlled`,+ `ControlLevelAutonomous ControlLevel = agentcapabilities.ControlLevelAutonomous`,+ `!agentcapabilities.ControlLevelAllowsControlTools(controlLevel)`,+ `!agentcapabilities.ControlLevelAllowsControlTools(e.controlLevel)`,+ `agentcapabilities.NewToolGovernanceDescriptor(`,+ `tool.Definition = tool.Definition.NormalizeCollections()`,+ `result = append(result, tool.Definition.NormalizeCollections())`,+ `params, invalidResult, ok := agentcapabilities.PrepareToolRegistryExecution(name, args)`,+ `agentcapabilities.NewUnknownToolResult(name)`,+ `agentcapabilities.NewControlToolsDisabledToolResult()`,+ `return result.NormalizeCollections(), err`,+ } {+ if !strings.Contains(registrySrc, fragment) {+ t.Errorf("Assistant tool registry must use shared agentcapabilities contracts; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `assistantControlToolsDisabledMessage`,+ `func normalizeToolGovernance(`,+ `DefaultApprovalPolicyDescription(governance.ApprovalPolicy)`,+ `governance.ActionMode = ToolActionWrite`,+ `governance.ApprovalPolicy = ToolApprovalActionPlan`,+ `invalid tools/call params:`,+ `unknown tool: %s`,+ `agentcapabilities.ControlToolsDisabledMessage`,+ } {+ if strings.Contains(registrySrc, fragment) {+ t.Errorf("Assistant tool registry must not preserve local governance defaults; found %s", fragment)+ }+ }++ assistantRegistryToolFiles := []string{+ filepath.Join("..", "ai", "tools", "tools_alerts.go"),+ filepath.Join("..", "ai", "tools", "tools_control.go"),+ filepath.Join("..", "ai", "tools", "tools_discovery.go"),+ filepath.Join("..", "ai", "tools", "tools_docker.go"),+ filepath.Join("..", "ai", "tools", "tools_file.go"),+ filepath.Join("..", "ai", "tools", "tools_kubernetes.go"),+ filepath.Join("..", "ai", "tools", "tools_knowledge.go"),+ filepath.Join("..", "ai", "tools", "tools_metrics.go"),+ filepath.Join("..", "ai", "tools", "tools_patrol.go"),+ filepath.Join("..", "ai", "tools", "tools_pmg.go"),+ filepath.Join("..", "ai", "tools", "tools_query.go"),+ filepath.Join("..", "ai", "tools", "tools_read.go"),+ filepath.Join("..", "ai", "tools", "tools_storage.go"),+ filepath.Join("..", "ai", "tools", "tools_summarize.go"),+ }+ assistantRegistryToolSrc := strings.Builder{}+ for _, path := range assistantRegistryToolFiles {+ source, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read %s: %v", path, err)+ }+ assistantRegistryToolSrc.Write(source)+ assistantRegistryToolSrc.WriteString("\n")+ }+ registryToolDeclarations := assistantRegistryToolSrc.String()+ for _, fragment := range []string{+ `Name: agentcapabilities.PulseAlertsToolName`,+ `Name: agentcapabilities.PulseControlToolName`,+ `Name: agentcapabilities.PulseDiscoveryToolName`,+ `Name: agentcapabilities.PulseDockerToolName`,+ `Name: agentcapabilities.PulseFileEditToolName`,+ `Name: agentcapabilities.PulseKubernetesToolName`,+ `Name: agentcapabilities.PulseKnowledgeToolName`,+ `Name: agentcapabilities.PulseMetricsToolName`,+ `Name: agentcapabilities.PatrolReportFindingToolName`,+ `Name: agentcapabilities.PatrolResolveFindingToolName`,+ `Name: agentcapabilities.PatrolGetFindingsToolName`,+ `Name: agentcapabilities.PulsePMGToolName`,+ `Name: agentcapabilities.PulseQueryToolName`,+ `Name: agentcapabilities.PulseReadToolName`,+ `Name: agentcapabilities.PulseStorageToolName`,+ `Name: agentcapabilities.PulseSummarizeToolName`,+ } {+ if !strings.Contains(registryToolDeclarations, fragment) {+ t.Errorf("Assistant registry tool declarations must use shared tool identities; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `Name: "pulse_`,+ `Name: "pulse_`,+ `Name: "patrol_`,+ `Name: "patrol_`,+ } {+ if strings.Contains(registryToolDeclarations, fragment) {+ t.Errorf("Assistant registry tool declarations must not own local Pulse tool-name strings; found %s", fragment)+ }+ }++ assistantPatrolTools, err := os.ReadFile(filepath.Join("..", "ai", "tools", "tools_patrol.go"))+ if err != nil {+ t.Fatalf("read internal/ai/tools/tools_patrol.go: %v", err)+ }+ assistantPatrolToolsSrc := string(assistantPatrolTools)+ for _, fragment := range []string{+ `agentcapabilities.FindingIDArgumentName`,+ `agentcapabilities.ReasonArgumentName`,+ `return NewJSONResult(result), nil`,+ } {+ if !strings.Contains(assistantPatrolToolsSrc, fragment) {+ t.Errorf("Assistant Patrol tools must use shared finding vocabulary and JSON result envelope; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `json.Marshal(result)`,+ `NewTextResult(string(b))`,+ } {+ if strings.Contains(assistantPatrolToolsSrc, fragment) {+ t.Errorf("Assistant Patrol tools must not manually marshal JSON text results; found %s", fragment)+ }+ }++ assistantProjection, err := os.ReadFile(filepath.Join("..", "ai", "tools", "provider_projection.go"))+ if err != nil {+ t.Fatalf("read internal/ai/tools/provider_projection.go: %v", err)+ }+ assistantProjectionSrc := string(assistantProjection)+ for _, fragment := range []string{+ `func (e *PulseToolExecutor) AssistantProviderTools(opts agentcapabilities.AssistantProviderToolOptions) []agentcapabilities.ProviderTool`,+ `return agentcapabilities.ProjectPulseAssistantProviderTools(agentcapabilities.CanonicalManifest(), e.ListTools(), e.ListToolGovernance(), opts)`,+ `return agentcapabilities.ProjectPulseAssistantProviderTools(agentcapabilities.CanonicalManifest(), nil, nil, opts)`,+ } {+ if !strings.Contains(assistantProjectionSrc, fragment) {+ t.Errorf("Assistant provider-tool projection must stay centralized on the shared executor; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `return agentcapabilities.ProjectAssistantProviderTools(e.ListTools(), e.ListToolGovernance(), opts)`,+ `return agentcapabilities.ProjectAssistantProviderTools(nil, nil, opts)`,+ } {+ if strings.Contains(assistantProjectionSrc, fragment) {+ t.Errorf("Assistant provider-tool projection must enter through manifest surface affordances; found %s", fragment)+ }+ }++ assistantToolNames, err := os.ReadFile(filepath.Join("..", "ai", "tools", "names.go"))+ if err != nil {+ t.Fatalf("read internal/ai/tools/names.go: %v", err)+ }+ assistantToolNamesSrc := string(assistantToolNames)+ for _, fragment := range []string{+ `agentcapabilities.ProviderToolNameCatalog`,+ `func AssistantProviderToolNameCatalog() agentcapabilities.ProviderToolNameCatalog`,+ `return AssistantProviderToolNameCatalog().Has(name)`,+ `return AssistantProviderToolNameCatalog().HasPrefix(prefix)`,+ `return knownToolNameCatalog`,+ `agentcapabilities.NewAssistantProviderToolNameCatalog(e.registry.allNames())`,+ } {+ if !strings.Contains(assistantToolNamesSrc, fragment) {+ t.Errorf("Assistant tool-name allowlist must adapt the shared provider-tool catalog; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `agentcapabilities.AssistantNativeProviderToolNames()`,+ `knownToolNamesList`,+ `knownToolNamesSet`,+ `strings.HasPrefix(name, prefix)`,+ } {+ if strings.Contains(assistantToolNamesSrc, fragment) {+ t.Errorf("Assistant tool-name allowlist must not keep local provider-tool catalog logic; found %s", fragment)+ }+ }+ if strings.Contains(assistantToolNamesSrc, `"pulse_question"`) {+ t.Error("Assistant tool-name allowlist must not hard-code native Assistant provider tool names")+ }++ assistantSanitize, err := os.ReadFile(filepath.Join("..", "ai", "chat", "agentic_sanitize.go"))+ if err != nil {+ t.Fatalf("read internal/ai/chat/agentic_sanitize.go: %v", err)+ }+ assistantSanitizeSrc := string(assistantSanitize)+ for _, fragment := range []string{+ `agentcapabilities.ProviderToolCallArtifactIndex(content, tools.AssistantProviderToolNameCatalog())`,+ `agentcapabilities.SplitTrailingProviderToolNamePrefix(content, tools.AssistantProviderToolNameCatalog())`,+ } {+ if !strings.Contains(assistantSanitizeSrc, fragment) {+ t.Errorf("Assistant chat sanitizer must use shared provider tool-call artifact detection; missing %s", fragment)+ }+ }+ for _, fragment := range []string{+ `dsmlMarkers`,+ `xmlToolCallRe`,+ `pipeMarkerRe`,+ `minimaxMarkerRe`,+ `jsonToolCallRe`,+ `plainFunctionToolCallRe`,+ `findJSONToolCallLeak`,+ `findPlainFunctionToolCallLeak`,+ } {+ if strings.Contains(assistantSanitizeSrc, fragment) {+ t.Errorf("Assistant chat sanitizer must not preserve local provider artifact detection; found %s", fragment)+ }+ }+}++// TestContract_AgentProbeUsesSharedAgentCapabilityProjection pins the reference+// client boundary: the probe may demonstrate transport mechanics, but manifest+// lookup and route projection must use the same shared helpers as MCP.+func TestContract_AgentProbeUsesSharedAgentCapabilityProjection(t *testing.T) {+ source, err := os.ReadFile(filepath.Join("..", "..", "cmd", "agent-probe", "main.go"))+ if err != nil {+ t.Fatalf("read cmd/agent-probe/main.go: %v", err)+ }+ src := string(source)+ required := []string{+ `internal/agentcapabilities`,+ `agentcapabilities.FleetContextCapabilityName`,+ `agentcapabilities.ResourceContextCapabilityName`,+ `agentcapabilities.FindCapability(manifest.Capabilities, agentcapabilities.EventSubscriptionCapabilityName)`,+ `agentcapabilities.FetchManifest(context.Background(), client, *baseURL)`,+ `agentcapabilities.CallRequestResponseCapabilityHTTPBodyByName(`,+ `agentcapabilities.StreamAgentActionableSSERecords(ctx, nil, baseURL, path, token, func(record agentcapabilities.SSERecord) bool`,+ }+ for _, fragment := range required {+ if !strings.Contains(src, fragment) {+ t.Errorf("agent-probe must use the shared agent capability projection helpers; missing %s", fragment)+ }+ }+ forbidden := []string{+ `agentcapabilities.FindCapability(manifest.Capabilities, "get_fleet_context")`,+ `agentcapabilities.FindCapability(manifest.Capabilities, "get_resource_context")`,+ `agentcapabilities.CallCapabilityHTTPByName(`,+ `agentcapabilities.CallCapabilityHTTP(ctx, client, baseURL, token, cap, args)`,+ `resp.FailureError()`,+ `strings.Replace(contextCap.Path`,+ `byName := map[string]agentCapability`,+ `type errorEnvelope struct`,+ `baseURL + "/api/agent/capabilities"`,+ `req.Header.Set("X-API-Token", token)`,+ `agentcapabilities.DecodeErrorEnvelope(body)`,+ `req.Header.Set("Accept", "text/event-stream")`,+ `http.DefaultClient.Do(req)`,+ `scanner := bufio.NewScanner(resp.Body)`,+ `strings.HasPrefix(line, "event: ")`,+ `strings.HasPrefix(line, "data: ")`,+ `agentcapabilities.StreamAgentSSERecords(ctx, nil, baseURL, path, token`,+ `agentcapabilities.IsTransportEventKind(record.Event)`,+ }+ for _, fragment := range forbidden {+ if strings.Contains(src, fragment) {+ t.Errorf("agent-probe must not preserve local manifest projection logic; found %s", fragment)+ }+ }+}++// TestContract_AgentSurfaceErrorEnvelopeUsesSharedAgentCapabilitiesType pins+// the stable agent error envelope as part of the shared agent capabilities+// contract instead of an API-local map or probe-local struct.+func TestContract_AgentSurfaceErrorEnvelopeUsesSharedAgentCapabilitiesType(t *testing.T) {+ source, err := os.ReadFile("middleware_tenant.go")+ if err != nil {+ t.Fatalf("read middleware_tenant.go: %v", err)+ }+ if !strings.Contains(string(source), "agentcapabilities.NewErrorEnvelope(code, message, details)") {+ t.Error("writeJSONErrorWithDetails must emit the shared agentcapabilities.ErrorEnvelope shape")+ }++ agentCapabilitiesSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "errors.go"))+ if err != nil {+ t.Fatalf("read internal/agentcapabilities/errors.go: %v", err)+ }+ for _, fragment := range []string{+ "type ErrorEnvelope struct",+ "Error string",+ "Message string",+ "Details map[string]string",+ `AgentErrCodeResourceNotFound = "resource_not_found"`,+ `AgentErrCodeOperatorStateNotSet = "operator_state_not_set"`,+ `AgentErrCodeInvalidActionRequest = "invalid_action_request"`,+ `AgentErrCodeActionExecutionUnavailable = "action_execution_unavailable"`,+ "func NewErrorEnvelope(",+ "func DecodeErrorEnvelope(",+ } {+ if !strings.Contains(string(agentCapabilitiesSource), fragment) {+ t.Errorf("agentcapabilities must own the shared agent error envelope; missing %s", fragment)+ }+ }+}++// TestContract_AgentCapabilitiesManifestDeclaresProvisioningSurface pins the+// node-lifecycle onboarding surface in the public agent manifest. This is the+// backend API payload proof required when the hand-authored manifest starts+// projecting /api/config/nodes and /api/discover to external agents.+func TestContract_AgentCapabilitiesManifestDeclaresProvisioningSurface(t *testing.T) {+ src := readAgentCapabilitiesManifestSource(t)++ required := []string{+ `"provisioning"`,+ `ActionMode:`,+ `ApprovalPolicy:`,+ `StrictObjectInputSchema`,+ `agentCapabilityActionModeRead`,+ `agentCapabilityActionModeMixed`,+ `agentCapabilityActionModeWrite`,+ `agentCapabilityApprovalPolicyScopeOnly`,+ `agentCapabilityApprovalPolicyActionPlan`,+ `ListNodesCapabilityName`,+ `Path: "/api/config/nodes"`,+ `Scope: agentCapabilityScopeSettingsRead`,+ `AddNodeCapabilityName`,+ `InputSchema: addNodeInputSchema()`,+ `UpdateNodeCapabilityName`,+ `InputSchema: updateNodeInputSchema()`,+ `RemoveNodeCapabilityName`,+ `InputSchema: nodeIDInputSchema()`,+ `TestNodeCredentialsCapabilityName`,+ `Path: "/api/config/nodes/test-config"`,+ `TestNodeConnectionCapabilityName`,+ `Path: "/api/config/nodes/{nodeId}/test"`,+ `RefreshNodeClusterMembershipCapabilityName`,+ `Path: "/api/config/nodes/{nodeId}/refresh-cluster"`,+ `DiscoverLANCapabilityName`,+ `Path: "/api/discover"`,+ `InputSchema: discoverLANInputSchema()`,+ `"tokenValue"`,+ `StrictObjectInputSchema`,+ }+ for _, fragment := range required {+ if !strings.Contains(src, fragment) {+ t.Errorf("agent capabilities manifest must declare provisioning contract fragment %s", fragment)+ }+ }++ manifest := agentcapabilities.CanonicalManifest()+ mcp, ok := agentcapabilities.FindManifestSurfaceToolContract(manifest, agentcapabilities.SurfaceIDPulseMCP)+ if !ok {+ t.Fatal("agent capabilities manifest must publish Pulse MCP surface tool contract")+ }+ for _, name := range []string{+ agentcapabilities.ListNodesCapabilityName,+ agentcapabilities.AddNodeCapabilityName,+ agentcapabilities.UpdateNodeCapabilityName,+ agentcapabilities.RemoveNodeCapabilityName,+ agentcapabilities.TestNodeCredentialsCapabilityName,+ agentcapabilities.TestNodeConnectionCapabilityName,+ agentcapabilities.RefreshNodeClusterMembershipCapabilityName,+ agentcapabilities.DiscoverLANCapabilityName,+ } {+ if _, ok := agentcapabilities.FindCapability(manifest.Capabilities, name); !ok {+ t.Errorf("agent capabilities manifest must declare provisioning capability %q", name)+ }+ if !stringSliceContains(mcp.ToolNames, name) {+ t.Errorf("Pulse MCP surface contract must explicitly allow provisioning capability %q", name)+ }+ }+}++// TestContract_AgentCapabilitiesManifestDeclaresTypedActionAndFindingSchemas+// pins that high-risk external-agent tools expose exact manifest-owned+// argument schemas instead of adapter-local free-form body conventions.+func TestContract_AgentCapabilitiesManifestDeclaresTypedActionAndFindingSchemas(t *testing.T) {+ src := readAgentCapabilitiesManifestSource(t)+ required := []string{+ `operatorStateInputSchema()`,+ `findingIDInputSchema(`,+ `snoozeFindingInputSchema()`,+ `dismissFindingInputSchema()`,+ `actionPlanInputSchema()`,+ `actionDecisionInputSchema()`,+ `actionExecutionInputSchema()`,+ `FindingIDArgumentName: stringOption(description)`,+ `FindingIDArgumentName, "duration_hours"`,+ `FindingIDArgumentName, ReasonArgumentName`,+ `NoteArgumentName: stringOption("Optional operator note explaining the dismissal.")`,+ `ResourceIDArgumentName, "intentionallyOffline", "neverAutoRemediate"`,+ `"maintenanceStartAt": {"maintenanceEndAt"}`,+ `"not_an_issue", "expected_behavior", "will_fix_later"`,+ `"approved", "rejected"`,+ `RequestIDArgumentName, ResourceIDArgumentName, CapabilityNameArgumentName, ReasonArgumentName, RequestedByArgumentName`,+ `ActionIDArgumentName, OutcomeArgumentName`,+ }+ for _, fragment := range required {+ if !strings.Contains(src, fragment) {+ t.Errorf("agent capabilities manifest must declare typed action/finding input schema fragment %s", fragment)+ }+ }+}++// TestContract_AgentCapabilitiesManifestDeclaresStructuredOutputSchemas pins+// that MCP structuredContent validation metadata is owned by the canonical+// capabilities manifest rather than a local adapter table.+func TestContract_AgentCapabilitiesManifestDeclaresStructuredOutputSchemas(t *testing.T) {+ src := readAgentCapabilitiesManifestSource(t)+ required := []string{+ `fleetContextOutputSchema()`,+ `operationsLoopStatusOutputSchema()`,+ `resourceContextOutputSchema()`,+ `operatorStateOutputSchema()`,+ `toolArrayOutputSchema("Configured infrastructure source records visible to the agent.")`,+ `nodeConnectionTestOutputSchema()`,+ `clusterRefreshOutputSchema()`,+ `discoveryOutputSchema()`,+ `findingActionOutputSchema()`,+ `actionPlanOutputSchema()`,+ `actionDecisionOutputSchema()`,+ `actionExecutionOutputSchema()`,+ `OutputSchema: fleetContextOutputSchema()`,+ `OutputSchema: operationsLoopStatusOutputSchema()`,+ `OutputSchema: resourceContextOutputSchema()`,+ `OutputSchema: operatorStateOutputSchema()`,+ `OutputSchema: toolArrayOutputSchema("Patrol finding records returned by the lifecycle endpoint.")`,+ `OutputSchema: actionPlanOutputSchema()`,+ `"resources", "generatedAt"`,+ `"nextAction", "progressLabel", "steps", "patrolEvidenceCount", "patrolIssueEvidenceCount", "activeFindingCount", "pendingApprovalCount", "governedActionCount", "approvedDecisionCount", "rejectedDecisionCount", "verifiedOutcomeCount", "operationsLoopStarterCount", "assistantOperationsLoopStarterCount", "patrolOperationsLoopStarterCount", "patrolControlOperationsLoopStarterCount", "patrolControlCompletedOperationsLoopCount", "patrolControlResolvedOperationsLoopCount", "patrolControlValueState", "patrolAutonomyOperationsLoopStarterCount", "patrolAutonomyCompletedOperationsLoopCount", "patrolAutonomyResolvedOperationsLoopCount", "patrolAutonomyValueState", "proActivationOperationsLoopStarterCount", "proActivationCompletedOperationsLoopCount", "proActivationResolvedOperationsLoopCount", "proActivationValueProofState", "mcpOperationsLoopStarterCount", "externalAgentReady", "windowStart", "generatedAt"`,+ `"Count of recent decision-backed governed actions without action ids or command content."`,+ `"Count of recent approved governed-action decisions without action ids or command content."`,+ `"Count of recent rejected governed-action decisions without action ids or command content."`,+ `"Count of recent approved governed actions with a verified post-action outcome."`,+ `"Count of content-free Patrol work prompt starter events in the evidence window."`,+ `"Count of Patrol work prompt starters rendered by Pulse Assistant in the evidence window."`,+ `"Count of Patrol work prompt starters launched from Pulse Patrol in the evidence window."`,+ `"Count of Patrol work prompt starters launched from the first-party Patrol control journey in the evidence window."`,+ `"Count-only evidence that the Patrol control journey reached a terminal Patrol work result in the evidence window: Patrol issue evidence, contextual Assistant or external-agent collaboration, and either a rejected governed decision or an approved governed decision with a verified outcome."`,+ `"Count-only evidence that the Patrol control journey reached a verified Patrol work result in the evidence window: Patrol issue evidence, contextual Assistant or external-agent collaboration, approved governed decision, and verified outcome."`,+ `"Content-safe Patrol control value state. Only verified means Patrol completed a verified work outcome; governed_decision_recorded means a safe terminal decision exists without verified outcome evidence."`,+ `"Compatibility field retained for older external-agent clients; primary clients should use patrolControlOperationsLoopStarterCount."`,+ `"Compatibility alias for patrolControlCompletedOperationsLoopCount."`,+ `"Compatibility alias for patrolControlResolvedOperationsLoopCount."`,+ `"Compatibility alias for patrolControlValueState."`,+ `"Count of Patrol work prompt starters rendered by the Pulse MCP surface in the evidence window."`,+ `"canonicalId", "resourceType", "resourceName", "activeFindings", "pendingApprovals", "recentActions", "contextSections", "generatedAt"`,+ `"canonicalId", "intentionallyOffline", "neverAutoRemediate", "setAt"`,+ `ActionIDArgumentName, RequestIDArgumentName, "allowed", "requiresApproval", "approvalPolicy", "rollbackAvailable", "plannedAt", "expiresAt", "resourceVersion", "policyVersion", "planHash"`,+ }+ for _, fragment := range required {+ if !strings.Contains(src, fragment) {+ t.Errorf("agent capabilities manifest must declare structured output schema fragment %s", fragment)+ }+ }+}++// TestContract_AgentResourceContextEndpointSurfacesStableShape pins+// the agent-paradigm substrate contract: the bundled endpoint must+// return arrays (never null) for activeFindings and recentActions so+// agents can iterate without nil-checking, must omit operatorState+// when no entry exists so agents can branch on field presence, and+// must preserve refusal-token prefixes verbatim so agents can branch+// on the stable code without parsing human messages. Without this+// pin, future refactors of the projection helpers could silently+// drift the wire shape and break external agent consumers.+func TestContract_AgentResourceContextEndpointSurfacesStableShape(t *testing.T) {+ source, err := os.ReadFile("agent_resource_context.go")+ if err != nil {+ t.Fatalf("read agent_resource_context.go: %v", err)+ }+ src := string(source)+ // Always-array initialization for the iteration-safe contract.+ if !regexp.MustCompile(`ActiveFindings:\s+\[\]AgentResourceFindingSnapshot\{\},`).MatchString(src) {+ t.Error("activeFindings must default to an empty slice, not nil — agents iterate without nil-checks")+ }+ if !regexp.MustCompile(`RecentActions:\s+\[\]AgentResourceActionSummary\{\},`).MatchString(src) {+ t.Error("recentActions must default to an empty slice, not nil")+ }+ // Server-computed maintenance-active flag — server pre-computes so+ // agents don't re-evaluate timestamps client-side.+ if !strings.Contains(src, "MaintenanceWindowActive: state.IsInMaintenanceAt(now)") {+ t.Error("MaintenanceWindowActive must be computed server-side via state.IsInMaintenanceAt(now)")+ }+ // Refusal-token preservation: ErrorMessage flows through verbatim+ // from the audit record's ExecutionResult, no rewriting.+ if !strings.Contains(src, "summary.ErrorMessage = audit.Result.ErrorMessage") {+ t.Error("audit ErrorMessage must round-trip verbatim so refusal tokens (resource_remediation_locked:, plan_drift:) reach agents")+ }+ // pendingApprovals must initialize as an empty slice so agents+ // iterate without nil-checking — same iteration-safe contract+ // as activeFindings and recentActions.+ if !regexp.MustCompile(`PendingApprovals:\s+\[\]AgentResourceApprovalSummary\{\},`).MatchString(src) {+ t.Error("pendingApprovals must default to an empty slice, not nil — agents iterate without nil-checks")+ }+ if !regexp.MustCompile(`ContextSections:\s+\[\]AgentResourceContextSection\{\},`).MatchString(src) {+ t.Error("contextSections must default to an empty slice, not nil — resource-aware agents iterate without nil-checks")+ }++ contextType := reflect.TypeOf(AgentResourceContext{})+ operatorStateField, ok := contextType.FieldByName("OperatorState")+ if !ok {+ t.Fatal("AgentResourceContext must carry OperatorState")+ }+ if operatorStateField.Type != reflect.TypeOf((*AgentResourceOperatorState)(nil)) ||+ operatorStateField.Tag.Get("json") != "operatorState,omitempty" {+ t.Error("operatorState must be an omitempty pointer so absent entries surface as a missing field")+ }+ discoveryReadinessField, ok := contextType.FieldByName("DiscoveryReadiness")+ if !ok {+ t.Fatal("AgentResourceContext must carry DiscoveryReadiness")+ }+ if discoveryReadinessField.Type != reflect.TypeOf((*AgentResourceDiscoveryReadiness)(nil)) ||+ discoveryReadinessField.Tag.Get("json") != "discoveryReadiness,omitempty" {+ t.Error("discoveryReadiness must be an omitempty pointer to the shared resource readiness projection")+ }+ pendingApprovalsField, ok := contextType.FieldByName("PendingApprovals")+ if !ok {+ t.Fatal("AgentResourceContext must carry PendingApprovals")+ }+ if pendingApprovalsField.Type != reflect.TypeOf([]AgentResourceApprovalSummary{}) ||+ pendingApprovalsField.Tag.Get("json") != "pendingApprovals" {+ t.Error("AgentResourceContext must carry PendingApprovals as a stable []AgentResourceApprovalSummary field")+ }+ contextSectionsField, ok := contextType.FieldByName("ContextSections")+ if !ok {+ t.Fatal("AgentResourceContext must carry ContextSections")+ }+ if contextSectionsField.Type != reflect.TypeOf([]AgentResourceContextSection{}) ||+ contextSectionsField.Tag.Get("json") != "contextSections" {+ t.Error("AgentResourceContext must carry ContextSections as a stable []AgentResourceContextSection field")+ }+ if !strings.Contains(src, "type AgentResourceContextRedaction = agentcontext.Redaction") ||+ !strings.Contains(src, "type AgentResourceContextFact = agentcontext.Fact") {+ t.Error("AgentResourceContext context sections must expose the shared typed fact and redaction metadata")+ }+}++// TestContract_AgentResourceContextWiresApprovalsProvider pins the+// startup-time wire-up that lets the bundle endpoint surface pending+// approvals scoped to a resource. Drift here means the field always+// shows up as an empty array even when there ARE pending approvals,+// silently breaking the substrate's "everything an agent needs in+// one read" contract for the governance dimension.+//+// The wire-up has two halves: router.go installs the provider with+// a provider that delegates to named functions in+// agent_resource_context.go, and those functions apply the org and+// resource filters while supporting the fleet endpoint's bulk count+// projection. Both halves are pinned here so a refactor that moves+// the filter logic still passes the test only if the resulting code+// preserves the safety and scale properties.+func TestContract_AgentResourceContextWiresApprovalsProvider(t *testing.T) {+ router, err := os.ReadFile("router.go")+ if err != nil {+ t.Fatalf("read router.go: %v", err)+ }+ if !strings.Contains(string(router), "r.agentContextHandler.SetApprovalsProvider(agentApprovalStoreProvider{})") {+ t.Error("router.go must wire the approvals provider on the agent context handler so the bundle's pendingApprovals section is populated")+ }+ if !strings.Contains(string(router), "approval.SetStore") {+ t.Error("router.go must keep documenting that the agent approval provider resolves the process-global approval store at request time")+ }++ bundle, err := os.ReadFile("agent_resource_context.go")+ if err != nil {t.Fatalf("read agent_resource_context.go: %v", err)}if !strings.Contains(string(bundle), "type agentApprovalStoreProvider struct{}") {@@ -14842,11 +18143,7 @@ func TestContract_AgentResourceContextWiresApprovalsProvider(t *testing.T) {// dimension. Drift here means external agents still expect the// pre-slice-45 shape.func TestContract_GetResourceContextCapabilityListsPendingApprovals(t *testing.T) {- source, err := os.ReadFile("agent_capabilities.go")- if err != nil {- t.Fatalf("read agent_capabilities.go: %v", err)- }- src := string(source)+ src := readAgentCapabilitiesManifestSource(t)if !strings.Contains(src, "pending approvals scoped to this resource") {t.Error("get_resource_context description must mention pending approvals so agents discover the bundle's new governance section through the manifest")}@@ -14909,6 +18206,95 @@ func TestContract_AgentFleetContextEndpointSurfacesStableShape(t *testing.T) {}}+// TestContract_AgentOperationsLoopStatusEndpointSurfacesStableShape pins the+// content-safe loop-status wire shape external agents use before choosing+// fleet, resource, finding, or action tools.+func TestContract_AgentOperationsLoopStatusEndpointSurfacesStableShape(t *testing.T) {+ source, err := os.ReadFile("agent_resource_context.go")+ if err != nil {+ t.Fatalf("read agent_resource_context.go: %v", err)+ }+ src := string(source)+ required := []string{+ "Steps: []AgentOperationsLoopStep{}",+ "NextAction string `json:\"nextAction\"`",+ "ProgressLabel string `json:\"progressLabel\"`",+ "Steps []AgentOperationsLoopStep `json:\"steps\"`",+ "PatrolEvidenceCount int `json:\"patrolEvidenceCount\"`",+ "PatrolIssueEvidenceCount int `json:\"patrolIssueEvidenceCount\"`",+ "ActiveFindingCount int `json:\"activeFindingCount\"`",+ "PendingApprovalCount int `json:\"pendingApprovalCount\"`",+ "GovernedActionCount int `json:\"governedActionCount\"`",+ "ApprovedDecisionCount int `json:\"approvedDecisionCount\"`",+ "RejectedDecisionCount int `json:\"rejectedDecisionCount\"`",+ "VerifiedOutcomeCount int `json:\"verifiedOutcomeCount\"`",+ "OperationsLoopStarterCount int `json:\"operationsLoopStarterCount\"`",+ "AssistantOperationsLoopStarterCount int `json:\"assistantOperationsLoopStarterCount\"`",+ "PatrolOperationsLoopStarterCount int `json:\"patrolOperationsLoopStarterCount\"`",+ "PatrolControlLoopStarterCount int `json:\"patrolControlOperationsLoopStarterCount\"`",+ "PatrolControlCompletedLoopCount int `json:\"patrolControlCompletedOperationsLoopCount\"`",+ "PatrolControlResolvedLoopCount int `json:\"patrolControlResolvedOperationsLoopCount\"`",+ "PatrolControlValueState string `json:\"patrolControlValueState\"`",+ "PatrolAutonomyLoopStarterCount int `json:\"patrolAutonomyOperationsLoopStarterCount\"`",+ "PatrolAutonomyCompletedLoopCount int `json:\"patrolAutonomyCompletedOperationsLoopCount\"`",+ "PatrolAutonomyResolvedLoopCount int `json:\"patrolAutonomyResolvedOperationsLoopCount\"`",+ "PatrolAutonomyValueState string `json:\"patrolAutonomyValueState\"`",+ "ProActivationLoopStarterCount int `json:\"proActivationOperationsLoopStarterCount\"`",+ "ProActivationCompletedLoopCount int `json:\"proActivationCompletedOperationsLoopCount\"`",+ "ProActivationResolvedLoopCount int `json:\"proActivationResolvedOperationsLoopCount\"`",+ "ProActivationValueProofState string `json:\"proActivationValueProofState\"`",+ "MCPOperationsLoopStarterCount int `json:\"mcpOperationsLoopStarterCount\"`",+ "ExternalAgentReady bool `json:\"externalAgentReady\"`",+ "WindowStart time.Time `json:\"windowStart\"`",+ "GeneratedAt time.Time `json:\"generatedAt\"`",+ "External-agent readiness is a separate capability signal,",+ "manifest := agentcapabilities.CanonicalManifest()",+ "ExternalAgentReady: h.agentOperationsLoopExternalAgentReady(r.Context(), manifest, now)",+ "func agentOperationsLoopExternalAgentTokenReady(manifest agentcapabilities.Manifest, tokens []config.APITokenRecord, now time.Time) bool",+ "agentcapabilities.RequiredCapabilityScopes(",+ "coversLoop := true",+ "if !token.HasScope(scope) {",+ `store.GetActionLifecycleEvents("", since, 0)`,+ "return pulseIntelligenceActionWasApproved(record) || pulseIntelligenceActionWasRejected(record)",+ "return pulseIntelligenceActionVerifiedOutcome(record)",+ "governanceStepCount := status.PendingApprovalCount",+ "decisionCount := status.ApprovedDecisionCount + status.RejectedDecisionCount",+ "verificationStepCount := status.VerifiedOutcomeCount",+ "verificationStepCount = status.RejectedDecisionCount",+ "patrolControlProof := agentOperationsLoopPatrolControlProof(status)",+ "status.PatrolControlLoopStarterCount = starterCounts.patrolControl",+ "status.PatrolAutonomyLoopStarterCount = status.PatrolControlLoopStarterCount",+ "status.PatrolControlValueState = patrolControlProof.ValueProofState",+ "status.PatrolAutonomyValueState = status.PatrolControlValueState",+ "status.ProActivationValueProofState = status.PatrolControlValueState",+ "case config.WorkflowPromptActivitySurfacePatrolControl:",+ "case config.WorkflowPromptActivitySurfacePatrolAutonomy:",+ "counts.patrolControl++",+ "return telemetry.ClassifyPulseIntelligencePatrolControlProof(telemetry.PulseIntelligencePatrolControlProofInput{",+ "ContextualCollaborationCount: agentOperationsLoopContextualCollaborationCount(status)",+ "type AgentAggregateFindingsProvider interface {",+ "ActiveFindingCount() int",+ "if aggregateProvider, ok := h.findingsProvider.(AgentAggregateFindingsProvider); ok {",+ "aggregateProvider.ActiveFindingCount()",+ "case status.PendingApprovalCount > 0:",+ "Review pending Patrol approvals before treating previous verified work as current.",+ "case status.ActiveFindingCount > 0 && hasVerifiedOutcome:",+ "Open Assistant on the active Patrol finding before treating previous verified work as current.",+ "Review active Patrol findings before treating previous verified work as current.",+ }+ for _, fragment := range required {+ if !strings.Contains(src, fragment) {+ t.Errorf("AgentOperationsLoopStatus contract missing %s", fragment)+ }+ }+ if strings.Contains(src, "ExternalAgentReady: status.ExternalAgentReady") {+ t.Error("AgentOperationsLoopStatus must not pass MCP readiness into Patrol control proof classification")+ }+ if strings.Contains(src, `ID: "external_agents"`) {+ t.Error("AgentOperationsLoopStatus steps must not make optional MCP readiness a Patrol operator step")+ }+}+// TestContract_ActionCompletedPayloadCarriesVerification pins that// the action.completed SSE payload exposes the verification block// — the agent-stable projection of the post-execution probe so@@ -14972,6 +18358,114 @@ func TestContract_AgentResourceActionSummaryCarriesVerification(t *testing.T) {}}+// TestContract_PulseIntelligenceApprovedExecutionTelemetryUsesActionLifecycle+// pins that the paid-value approved execution counter is sourced from+// action lifecycle evidence and only then resolved back to the action audit+// approval state. Drift here would let generic planning, approval, or token+// use masquerade as a completed operations loop.+func TestContract_PulseIntelligenceApprovedExecutionTelemetryUsesActionLifecycle(t *testing.T) {+ source, err := os.ReadFile("telemetry_pulse_intelligence.go")+ if err != nil {+ t.Fatalf("read telemetry_pulse_intelligence.go: %v", err)+ }+ src := string(source)+ for _, fragment := range []string{+ `store.GetActionLifecycleEvents("", since, 0)`,+ `store.GetActionAudit(actionID)`,+ `pulseIntelligenceActionWasApproved(record)`,+ `pulseIntelligenceApprovedActionSuccess(record)`,+ `case unifiedresources.ActionStateExecuting, unifiedresources.ActionStateCompleted, unifiedresources.ActionStateFailed:`,+ `snapshot.ApprovedActionAttempts30d += len(approvedAttemptIDs)`,+ `snapshot.ApprovedActionSuccesses30d += len(approvedSuccessIDs)`,+ } {+ if !strings.Contains(src, fragment) {+ t.Errorf("Pulse Intelligence approved execution telemetry must stay lifecycle-backed and audit-approved; missing %s", fragment)+ }+ }+}++// TestContract_PulseIntelligenceApprovedDecisionTelemetryUsesActionDecisionEvidence+// pins that approved governed-action decisions are counted separately from+// approved execution attempts, so completed operations-loop proof can mean an+// approve/reject decision without pretending every approval executed.+func TestContract_PulseIntelligenceApprovedDecisionTelemetryUsesActionDecisionEvidence(t *testing.T) {+ source, err := os.ReadFile("telemetry_pulse_intelligence.go")+ if err != nil {+ t.Fatalf("read telemetry_pulse_intelligence.go: %v", err)+ }+ src := string(source)+ for _, fragment := range []string{+ `approvedDecisionIDs := pulseIntelligenceApprovedActionDecisionIDs(store, orgID, since)`,+ `if event.State != unifiedresources.ActionStateApproved`,+ `pulseIntelligenceActionWasApprovedSince(record, since)`,+ `if approval.Outcome != unifiedresources.OutcomeApproved`,+ `snapshot.ApprovedActionDecisions30d += len(approvedDecisionIDs)`,+ } {+ if !strings.Contains(src, fragment) {+ t.Errorf("Pulse Intelligence approved decision telemetry must stay decision-backed and separate from execution attempts; missing %s", fragment)+ }+ }+}++// TestContract_PulseIntelligenceApprovedSuccessTelemetryRequiresVerifiedOutcome+// pins that outbound Pulse Intelligence approved-success telemetry and the+// operations-loop status route share the same verified-outcome predicate.+// A completed action result alone is execution evidence, not post-action proof+// for Patrol control resolved-loop reporting.+func TestContract_PulseIntelligenceApprovedSuccessTelemetryRequiresVerifiedOutcome(t *testing.T) {+ telemetrySource, err := os.ReadFile("telemetry_pulse_intelligence.go")+ if err != nil {+ t.Fatalf("read telemetry_pulse_intelligence.go: %v", err)+ }+ telemetrySrc := string(telemetrySource)+ for _, fragment := range []string{+ `if record.State != unifiedresources.ActionStateCompleted`,+ `return pulseIntelligenceActionVerifiedOutcome(record)`,+ `func pulseIntelligenceActionVerifiedOutcome(record unifiedresources.ActionAuditRecord) bool`,+ `outcome := unifiedresources.NormalizeVerificationOutcome(record.VerificationOutcome)`,+ `outcome.Status == unifiedresources.VerificationVerified`,+ `verification := unifiedresources.CanonicalActionVerification(record)`,+ `return verification != nil && verification.Ran && verification.Success`,+ } {+ if !strings.Contains(telemetrySrc, fragment) {+ t.Errorf("Pulse Intelligence approved-success telemetry must require verified outcome proof; missing %s", fragment)+ }+ }+ if strings.Contains(telemetrySrc, `return record.Result == nil || record.Result.Success`) {+ t.Error("Pulse Intelligence approved-success telemetry must not treat a bare successful execution result as verified outcome proof")+ }++ statusSource, err := os.ReadFile("agent_resource_context.go")+ if err != nil {+ t.Fatalf("read agent_resource_context.go: %v", err)+ }+ if !strings.Contains(string(statusSource), `return pulseIntelligenceActionVerifiedOutcome(record)`) {+ t.Error("operations-loop status verified outcome count must use the shared Pulse Intelligence verified-outcome predicate")+ }+}++// TestContract_PulseIntelligenceRejectedDecisionTelemetryUsesActionLifecycle+// pins that rejected governed-action decisions are counted from decision+// lifecycle evidence and remain separate from approved execution proof.+func TestContract_PulseIntelligenceRejectedDecisionTelemetryUsesActionLifecycle(t *testing.T) {+ source, err := os.ReadFile("telemetry_pulse_intelligence.go")+ if err != nil {+ t.Fatalf("read telemetry_pulse_intelligence.go: %v", err)+ }+ src := string(source)+ for _, fragment := range []string{+ `rejectedDecisionIDs := pulseIntelligenceRejectedActionDecisionIDs(store, orgID, since)`,+ `if event.State != unifiedresources.ActionStateRejected`,+ `store.GetActionAudit(actionID)`,+ `pulseIntelligenceActionWasRejected(record)`,+ `snapshot.RejectedActionDecisions30d += len(rejectedDecisionIDs)`,+ } {+ if !strings.Contains(src, fragment) {+ t.Errorf("Pulse Intelligence rejected decision telemetry must stay lifecycle-backed and audit-rejected; missing %s", fragment)+ }+ }+}+// TestContract_OperatorStateWriteServerPopulatesAttribution pins the// audit-honesty contract for the agent surface's only write loop:// the PUT handler must populate SetAt and SetBy from the server,@@ -15007,10 +18501,10 @@ func TestContract_OperatorStateWriteEmitsStableErrorTokens(t *testing.T) {t.Fatalf("read resources_operator_state.go: %v", err)}src := string(source)- if !strings.Contains(src, `"operator_state_not_set"`) {+ if !strings.Contains(src, "agentcapabilities.AgentErrCodeOperatorStateNotSet") {t.Error("GET handler must emit operator_state_not_set when no entry exists — manifest declares this code")}- if !strings.Contains(src, `"operator_state_invalid"`) {+ if !strings.Contains(src, "agentcapabilities.AgentErrCodeOperatorStateInvalid") {t.Error("PUT handler must emit operator_state_invalid on validation failure — manifest declares this code")}if !strings.Contains(src, "errors.Is(err, unified.ErrResourceOperatorStateInvalid)") {@@ -15047,6 +18541,7 @@ func TestContract_AgentSurfaceErrorCodesMatchManifestDeclarations(t *testing.T)"agent_resource_context.go","resources_operator_state.go","actions.go",+ "ai_handlers.go",}// Codes the action handlers emit that are deliberately NOT in@@ -15074,49 +18569,73 @@ func TestContract_AgentSurfaceErrorCodesMatchManifestDeclarations(t *testing.T)"resource_registry_unavailable": true,}- // Extract every emitted code from writeJSONError /- // writeJSONErrorWithDetails calls. The regex tolerates- // whitespace/newlines that gofmt may insert between the call's- // arguments and matches both function names since they share- // the same envelope contract.+ agentErrorConstantValues := map[string]string{+ "AgentErrCodeResourceNotFound": agentcapabilities.AgentErrCodeResourceNotFound,+ "AgentErrCodeOperatorStateNotSet": agentcapabilities.AgentErrCodeOperatorStateNotSet,+ "AgentErrCodeOperatorStateInvalid": agentcapabilities.AgentErrCodeOperatorStateInvalid,+ "AgentErrCodeInvalidFindingRequest": agentcapabilities.AgentErrCodeInvalidFindingRequest,+ "AgentErrCodeFindingNotFound": agentcapabilities.AgentErrCodeFindingNotFound,+ "AgentErrCodeFindingActionNotAllowed": agentcapabilities.AgentErrCodeFindingActionNotAllowed,+ "AgentErrCodePatrolUnavailable": agentcapabilities.AgentErrCodePatrolUnavailable,+ "AgentErrCodeInvalidActionRequest": agentcapabilities.AgentErrCodeInvalidActionRequest,+ "AgentErrCodeCapabilityNotFound": agentcapabilities.AgentErrCodeCapabilityNotFound,+ "AgentErrCodeActionExecutionUnavailable": agentcapabilities.AgentErrCodeActionExecutionUnavailable,+ "AgentErrCodeMissingID": agentcapabilities.AgentErrCodeMissingID,+ "AgentErrCodeInvalidID": agentcapabilities.AgentErrCodeInvalidID,+ "AgentErrCodeInvalidActionDecision": agentcapabilities.AgentErrCodeInvalidActionDecision,+ "AgentErrCodeActionNotFound": agentcapabilities.AgentErrCodeActionNotFound,+ "AgentErrCodeActionNotPending": agentcapabilities.AgentErrCodeActionNotPending,+ "AgentErrCodeActionPlanExpired": agentcapabilities.AgentErrCodeActionPlanExpired,+ "AgentErrCodeInvalidActionExecution": agentcapabilities.AgentErrCodeInvalidActionExecution,+ "AgentErrCodeActionNotApproved": agentcapabilities.AgentErrCodeActionNotApproved,+ "AgentErrCodeActionAlreadyExecuting": agentcapabilities.AgentErrCodeActionAlreadyExecuting,+ "AgentErrCodeActionExecutionFinal": agentcapabilities.AgentErrCodeActionExecutionFinal,+ "AgentErrCodeActionDryRunOnly": agentcapabilities.AgentErrCodeActionDryRunOnly,+ "AgentErrCodeActionPlanDrift": agentcapabilities.AgentErrCodeActionPlanDrift,+ "AgentErrCodeResourceRemediationLocked": agentcapabilities.AgentErrCodeResourceRemediationLocked,+ "AgentErrCodeActionExecutorUnavailable": agentcapabilities.AgentErrCodeActionExecutorUnavailable,+ }++ // Extract every emitted shared code from writeJSONError /+ // writeJSONErrorWithDetails calls. Agent-surface codes must flow+ // through agentcapabilities.AgentErrCode* constants so the manifest and+ // handlers cannot drift by editing duplicate literals.emitted := map[string]bool{}for _, file := range handlerFiles {body, err := os.ReadFile(file)if err != nil {t.Fatalf("read %s: %v", file, err)}- // Match the second string literal (the code) on- // writeJSONError(w, status, "code", ...) or- // writeJSONErrorWithDetails(w, status, "code", ...). The- // first arg `w` is an identifier, then a status int or- // http.StatusXxx selector, so the regex skips past those.- looseRE := regexp.MustCompile(`writeJSONError(?:WithDetails)?\([^)]*?"([a-z_][a-z_0-9]+)"`)- for _, m := range looseRE.FindAllSubmatch(body, -1) {- code := string(m[1])- if internalOnlyCodes[code] {+ constantRE := regexp.MustCompile(`(?s)writeJSONError(?:WithDetails)?\(\s*w\s*,\s*[^,]+,\s*agentcapabilities\.(AgentErrCode[A-Za-z0-9]+)`)+ for _, m := range constantRE.FindAllSubmatch(body, -1) {+ constantName := string(m[1])+ code, ok := agentErrorConstantValues[constantName]+ if !ok {+ t.Errorf("%s emits unknown shared agent error constant %s", file, constantName)continue}emitted[code] = true}++ literalRE := regexp.MustCompile(`(?s)writeJSONError(?:WithDetails)?\(\s*w\s*,\s*[^,]+,\s*"([a-z_][a-z_0-9]+)"`)+ for _, m := range literalRE.FindAllSubmatch(body, -1) {+ code := string(m[1])+ if internalOnlyCodes[code] || crossCutting[code] {+ continue+ }+ t.Errorf("%s emits agent-surface error code %q as a local literal; use an agentcapabilities.AgentErrCode* constant", file, code)+ }}if len(emitted) == 0 {- t.Fatal("no writeJSONError emissions found in agent-surface handler files; the audit regex must be wrong")+ t.Fatal("no shared writeJSONError emissions found in agent-surface handler files; the audit regex or handler constants 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)- }+ // Pull declared codes from the runtime manifest so the test follows+ // constant-backed manifest edits without source scraping.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+ for _, cap := range agentcapabilities.CanonicalManifest().Capabilities {+ for _, code := range cap.ErrorCodes {+ declared[code] = true}}@@ -15140,15 +18659,18 @@ func TestContract_AgentSurfaceErrorCodesMatchManifestDeclarations(t *testing.T)}func TestContract_PlanActionDeclaresExecutionUnavailable(t *testing.T) {- source, err := os.ReadFile("agent_capabilities.go")- if err != nil {- t.Fatalf("read agent_capabilities.go: %v", err)+ manifest := agentcapabilities.CanonicalManifest()+ var planAction agentcapabilities.Capability+ for _, cap := range manifest.Capabilities {+ if cap.Name == agentcapabilities.PlanActionCapabilityName {+ planAction = cap+ break+ }}- src := string(source)- if !strings.Contains(src, `Name: "plan_action"`) {- t.Fatal("agent capabilities manifest must declare plan_action")+ if planAction.Name == "" {+ t.Fatalf("agent capabilities manifest must declare %s", agentcapabilities.PlanActionCapabilityName)}- if !strings.Contains(src, `"action_execution_unavailable"`) {+ if !stringSliceContains(planAction.ErrorCodes, agentcapabilities.AgentErrCodeActionExecutionUnavailable) {t.Error("plan_action must declare action_execution_unavailable so agents can branch on executor-owned live-readiness refusal")}}@@ -15285,19 +18807,22 @@ func TestContract_AgentCapabilitiesManifestIsPublic(t *testing.T) {// what its response shape is. Drift here means external agents// still expect to walk every resource id one-by-one.func TestContract_GetFleetContextCapabilityListed(t *testing.T) {- source, err := os.ReadFile("agent_capabilities.go")- if err != nil {- t.Fatalf("read agent_capabilities.go: %v", err)+ var cap *AgentCapability+ manifest := agentcapabilities.CanonicalManifest()+ for i := range manifest.Capabilities {+ if manifest.Capabilities[i].Name == "get_fleet_context" {+ cap = &manifest.Capabilities[i]+ break+ }}- src := string(source)- if !strings.Contains(src, `Name: "get_fleet_context"`) {- t.Error("agent capabilities manifest must declare get_fleet_context — the substrate's triage entry point")+ if cap == nil {+ t.Fatal("agent capabilities manifest must declare get_fleet_context — the substrate's triage entry point")}- if !strings.Contains(src, `Path: "/api/agent/fleet-context"`) {- t.Error("get_fleet_context must point at /api/agent/fleet-context")+ if cap.Path != agentcapabilities.FleetContextCapabilityPath {+ t.Errorf("get_fleet_context path = %q, want %s", cap.Path, agentcapabilities.FleetContextCapabilityPath)}- if !strings.Contains(src, `ResponseShape: "AgentFleetContext"`) {- t.Error("get_fleet_context response shape must be AgentFleetContext so agents know what to parse")+ if cap.ResponseShape != "AgentFleetContext" {+ t.Errorf("get_fleet_context response shape = %q, want AgentFleetContext so agents know what to parse", cap.ResponseShape)}}diff --git a/internal/api/diagnostics.go b/internal/api/diagnostics.goindex 055efe797a..21e3934e36 100644--- a/internal/api/diagnostics.go+++ b/internal/api/diagnostics.go@@ -704,17 +704,16 @@ func (d AlertsDiagnostic) NormalizeCollections() AlertsDiagnostic {return d}-// AIChatDiagnostic reports on the AI chat service status.+// AIChatDiagnostic reports on the native Pulse Assistant runtime status.type AIChatDiagnostic struct {- Enabled bool `json:"enabled"`- Running bool `json:"running"`- Healthy bool `json:"healthy"`- Port int `json:"port,omitempty"`- URL string `json:"url,omitempty"`- Model string `json:"model,omitempty"`- MCPConnected bool `json:"mcpConnected"`- MCPToolCount int `json:"mcpToolCount,omitempty"`- Notes []string `json:"notes"`+ Enabled bool `json:"enabled"`+ Running bool `json:"running"`+ Healthy bool `json:"healthy"`+ Port int `json:"port,omitempty"`+ URL string `json:"url,omitempty"`+ Model string `json:"model,omitempty"`+ AssistantRuntimeConnected bool `json:"assistantRuntimeConnected"`+ Notes []string `json:"notes"`}func (d AIChatDiagnostic) NormalizeCollections() AIChatDiagnostic {@@ -1959,8 +1958,8 @@ func buildAIChatDiagnostic(cfg *config.Config, aiHandler *AIHandler) *AIChatDiag}}- // Check MCP connection (if we had access to check it)- diag.MCPConnected = diag.Running // Assume connected if running for now+ // Native Assistant diagnostics report runtime availability, not MCP transport.+ diag.AssistantRuntimeConnected = diag.Runningif !diag.Running && diag.Enabled {diag.Notes = append(diag.Notes, "Pulse Assistant service is enabled but not running")diff --git a/internal/api/diagnostics_additional_test.go b/internal/api/diagnostics_additional_test.goindex eeb7f03b26..cfc682e2c7 100644--- a/internal/api/diagnostics_additional_test.go+++ b/internal/api/diagnostics_additional_test.go@@ -136,6 +136,31 @@ func TestHandleDiagnostics_CacheHit(t *testing.T) {}}+func TestAIChatDiagnosticUsesNativeAssistantRuntimeField(t *testing.T) {+ payload := DiagnosticsInfo{+ AIChat: &AIChatDiagnostic{+ Enabled: true,+ Running: true,+ Healthy: true,+ AssistantRuntimeConnected: true,+ },+ }.NormalizeCollections()++ body, err := json.Marshal(payload)+ if err != nil {+ t.Fatalf("marshal diagnostics: %v", err)+ }+ text := string(body)+ if !strings.Contains(text, `"assistantRuntimeConnected":true`) {+ t.Fatalf("diagnostics payload must expose native Assistant runtime connectivity: %s", text)+ }+ for _, forbidden := range []string{"mcpConnected", "mcpToolCount"} {+ if strings.Contains(text, forbidden) {+ t.Fatalf("diagnostics payload must not expose legacy MCP field %q: %s", forbidden, text)+ }+ }+}+func TestHandleDiagnostics_CacheIsScopedByOrg(t *testing.T) {cfg := &config.Config{DataPath: t.TempDir()}monitor := newMonitorForDiagnostics(t, cfg)diff --git a/internal/api/diagnostics_contract_test.go b/internal/api/diagnostics_contract_test.goindex be7a45124a..2fd0b9d56b 100644--- a/internal/api/diagnostics_contract_test.go+++ b/internal/api/diagnostics_contract_test.go@@ -25,3 +25,32 @@ func TestContract_DiagnosticsInfoExcludesInternalAnalytics(t *testing.T) {}}}++func TestContract_AssistantDiagnosticsUseNativeRuntimeVocabulary(t *testing.T) {+ payload := EmptyDiagnosticsInfo()+ payload.AIChat = &AIChatDiagnostic{+ Enabled: true,+ Running: true,+ Healthy: true,+ Model: "ollama:llama3",+ AssistantRuntimeConnected: true,+ }++ got, err := json.Marshal(payload.NormalizeCollections())+ if err != nil {+ t.Fatalf("marshal diagnostics info: %v", err)+ }+ body := string(got)++ if !strings.Contains(body, `"assistantRuntimeConnected":true`) {+ t.Fatalf("diagnostics payload must expose native Assistant runtime connectivity: %s", body)+ }+ for _, forbidden := range []string{+ "mcpConnected",+ "mcpToolCount",+ } {+ if strings.Contains(body, forbidden) {+ t.Fatalf("diagnostics payload must not expose legacy MCP diagnostic field %q: %s", forbidden, body)+ }+ }+}diff --git a/internal/api/middleware_tenant.go b/internal/api/middleware_tenant.goindex 9c6118a849..9486928a36 100644--- a/internal/api/middleware_tenant.go+++ b/internal/api/middleware_tenant.go@@ -7,6 +7,7 @@ import ("strings""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/pkg/auth"@@ -236,13 +237,7 @@ func writeJSONError(w http.ResponseWriter, status int, code, message string) {func writeJSONErrorWithDetails(w http.ResponseWriter, status int, code, message string, details map[string]string) {w.Header().Set("Content-Type", "application/json")w.WriteHeader(status)- body := map[string]any{- "error": code,- "message": message,- }- if len(details) > 0 {- body["details"] = details- }+ body := agentcapabilities.NewErrorEnvelope(code, message, details)_ = json.NewEncoder(w).Encode(body)}diff --git a/internal/api/middleware_tenant_additional_test.go b/internal/api/middleware_tenant_additional_test.goindex 8b69e7d51d..0fc679d4f2 100644--- a/internal/api/middleware_tenant_additional_test.go+++ b/internal/api/middleware_tenant_additional_test.go@@ -8,6 +8,7 @@ import ("testing""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/config"pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing")@@ -51,11 +52,11 @@ func TestWriteJSONError(t *testing.T) {t.Fatalf("expected 400, got %d", rec.Code)}- var payload map[string]string+ var payload agentcapabilities.ErrorEnvelopeif err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {t.Fatalf("decode response: %v", err)}- if payload["error"] != "bad" || payload["message"] != "message" {+ if payload.Error != "bad" || payload.Message != "message" {t.Fatalf("unexpected payload: %+v", payload)}}diff --git a/internal/api/profile_suggestions.go b/internal/api/profile_suggestions.goindex 234be45da0..4740ecdaf1 100644--- a/internal/api/profile_suggestions.go+++ b/internal/api/profile_suggestions.go@@ -14,7 +14,7 @@ import ("github.com/rs/zerolog/log")-// ProfileSuggestionHandler handles AI-assisted profile suggestions+// ProfileSuggestionHandler handles Pulse Intelligence-assisted profile suggestionstype ProfileSuggestionHandler struct {mtPersistence *config.MultiTenantPersistenceaiHandler *AIHandler@@ -33,7 +33,7 @@ type SuggestionRequest struct {Prompt string `json:"prompt"`}-// ProfileSuggestion is the AI-generated profile suggestion+// ProfileSuggestion is the Pulse Intelligence-generated profile suggestiontype ProfileSuggestion struct {Name string `json:"name"`Description string `json:"description"`@@ -50,7 +50,7 @@ func (h *ProfileSuggestionHandler) HandleSuggestProfile(w http.ResponseWriter, r// Check if AI is runningif h.aiHandler == nil || !h.aiHandler.IsRunning(r.Context()) {- http.Error(w, "Pulse Assistant service is not available", http.StatusServiceUnavailable)+ http.Error(w, "Pulse Intelligence is not available", http.StatusServiceUnavailable)return}diff --git a/internal/api/profile_suggestions_handlers_test.go b/internal/api/profile_suggestions_handlers_test.goindex 4970aac31a..eae973e495 100644--- a/internal/api/profile_suggestions_handlers_test.go+++ b/internal/api/profile_suggestions_handlers_test.go@@ -46,6 +46,9 @@ func TestProfileSuggestionHandler_ServiceUnavailable(t *testing.T) {if rr.Code != http.StatusServiceUnavailable {t.Fatalf("expected status %d, got %d", http.StatusServiceUnavailable, rr.Code)}+ if rr.Body.String() != "Pulse Intelligence is not available\n" {+ t.Fatalf("unexpected service-unavailable body: %q", rr.Body.String())+ }}func TestProfileSuggestionHandler_InvalidRequest(t *testing.T) {diff --git a/internal/api/resources_operator_state.go b/internal/api/resources_operator_state.goindex 1a624158c0..e49699c7d5 100644--- a/internal/api/resources_operator_state.go+++ b/internal/api/resources_operator_state.go@@ -7,6 +7,7 @@ import ("strings""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")@@ -84,7 +85,7 @@ func (h *ResourceHandlers) HandleResourceOperatorState(w http.ResponseWriter, rreturn}if !found {- writeJSONError(w, http.StatusNotFound, "operator_state_not_set",+ writeJSONError(w, http.StatusNotFound, agentcapabilities.AgentErrCodeOperatorStateNotSet,"No operator-set state recorded for this resource.")return}@@ -115,7 +116,7 @@ func (h *ResourceHandlers) HandleResourceOperatorState(w http.ResponseWriter, rpersisted, err := unified.SetResourceOperatorStateWithMaintenanceLifecycle(store, state)if err != nil {if errors.Is(err, unified.ErrResourceOperatorStateInvalid) {- writeJSONError(w, http.StatusBadRequest, "operator_state_invalid", err.Error())+ writeJSONError(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeOperatorStateInvalid, err.Error())return}http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.goindex e72191e33f..a228bb117e 100644--- a/internal/api/route_inventory_test.go+++ b/internal/api/route_inventory_test.go@@ -421,6 +421,8 @@ var allRouteAllowlist = []string{"POST /api/maintenance-verifications/{reportId}/review","/api/agent/resource-context/{id}","/api/agent/fleet-context",+ "/api/agent/patrol-control/status",+ "/api/agent/operations-loop/status","/api/agent/capabilities","/api/agent/events","POST /api/actions/plan",@@ -645,6 +647,9 @@ var allRouteAllowlist = []string{"/api/ai/incidents","/api/ai/incidents/","/api/ai/status",+ "/api/ai/assistant/surface-tools",+ "/api/ai/workflow-prompts/render",+ "/api/ai/workflow-prompts/activity","/api/ai/chat","/api/ai/sessions","/api/ai/sessions/",@@ -660,6 +665,7 @@ var allRouteAllowlist = []string{"/api/discovery/agent/","/api/discovery/","/api/agent/ws",+ "POST /api/agent/workflow-prompt-activity","/api/agents/agent/enroll","/api/agents/host/enroll","/api/clusters/",diff --git a/internal/api/router.go b/internal/api/router.goindex 6949c5efea..79c26c1d8b 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -24,6 +24,7 @@ import ("sync""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/ai""github.com/rcourtman/pulse-go-rewrite/internal/ai/adapters"@@ -484,6 +485,37 @@ func (r *Router) setupRoutes() {r.maintenanceSentinel.Start(r.lifecycleCtx)}r.agentContextHandler = NewAgentContextHandler(r.resourceHandlers)+ r.agentContextHandler.SetWorkflowPromptActivityProvider(agentWorkflowPromptActivityProviderFunc(func(ctx context.Context) (*config.WorkflowPromptActivityHistoryData, error) {+ persistence := r.persistenceForOrg(ctx)+ if persistence == nil {+ return nil, nil+ }+ return persistence.LoadWorkflowPromptActivityHistory()+ }))+ r.agentContextHandler.SetAIUsageProvider(agentAIUsageProviderFunc(func(ctx context.Context) (*config.AIUsageHistoryData, error) {+ persistence := r.persistenceForOrg(ctx)+ if persistence == nil {+ return nil, nil+ }+ return persistence.LoadAIUsageHistory()+ }))+ r.agentContextHandler.SetExternalAgentActivityProvider(agentExternalAgentActivityProviderFunc(func(ctx context.Context) (*config.ExternalAgentActivityHistoryData, error) {+ persistence := r.persistenceForOrg(ctx)+ if persistence == nil {+ return nil, nil+ }+ return persistence.LoadExternalAgentActivityHistory()+ }))+ r.agentContextHandler.SetExternalAgentReadinessProvider(agentExternalAgentReadinessProviderFunc(func(_ context.Context, manifest agentcapabilities.Manifest, now time.Time) bool {+ if r.config == nil {+ return false+ }+ config.Mu.Lock()+ tokens := make([]config.APITokenRecord, len(r.config.APITokens))+ copy(tokens, r.config.APITokens)+ config.Mu.Unlock()+ return agentOperationsLoopExternalAgentTokenReady(manifest, tokens, now)+ }))// Wire pending-approvals into the bundle. The provider resolves// the approval store at request time so multi-tenant rebuilds// (which install a new global store via approval.SetStore) stay@@ -725,7 +757,7 @@ func (r *Router) setupRoutes() {r.aiSettingsHandler.SetOnModelChange(func() {r.RestartAIChat(context.Background())})- // Wire control settings change callback to update MCP tool visibility+ // Wire control settings change callback to update Assistant tool visibility.r.aiSettingsHandler.SetOnControlSettingsChange(func() {if r.aiHandler != nil {ctx := context.Background()@@ -953,6 +985,7 @@ func (r *Router) routeAIPatrolFindings(w http.ResponseWriter, req *http.Request)if !ensureRelayMobileRuntimeRoute(w, req, relayMobileRoutePatrolFindingsList) {return}+ r.recordExternalAgentCapabilityActivity(req, agentcapabilities.ListFindingsCapabilityName)r.aiSettingsHandler.HandleGetPatrolFindings(w, req)case http.MethodDelete:if !ensureScope(w, req, config.ScopeAIExecute) {@@ -1959,44 +1992,56 @@ func (r *Router) startPatrolForContext(ctx context.Context, orgID string) bool {// picture without any internal type leakage.if r.agentContextHandler != nil {r.agentContextHandler.SetFindingsProvider(- agentFindingsProviderFunc(func(resourceID string) []AgentResourceFindingSnapshot {- if patrol == nil {- return nil- }- findings := patrol.GetFindings()- if findings == nil {- return nil- }- active := findings.GetByResource(resourceID)- if len(active) == 0 {- return []AgentResourceFindingSnapshot{}- }- out := make([]AgentResourceFindingSnapshot, 0, len(active))- for _, f := range active {- snapshot := AgentResourceFindingSnapshot{- ID: f.ID,- Title: f.Title,- Severity: string(f.Severity),- Category: string(f.Category),- Description: f.Description,- Impact: f.Impact,- Recommendation: f.Recommendation,- RegressionCount: f.RegressionCount,- PreviousResolvedFixSummary: f.PreviousResolvedFixSummary,+ agentFindingsProvider{+ activeForResource: func(resourceID string) []AgentResourceFindingSnapshot {+ if patrol == nil {+ return nil}- if !f.DetectedAt.IsZero() {- snapshot.DetectedAt = f.DetectedAt.Format(time.RFC3339)+ findings := patrol.GetFindings()+ if findings == nil {+ return nil}- if !f.LastSeenAt.IsZero() {- snapshot.LastSeenAt = f.LastSeenAt.Format(time.RFC3339)+ active := findings.GetByResource(resourceID)+ if len(active) == 0 {+ return []AgentResourceFindingSnapshot{}}- if f.InvestigationRecord != nil && f.InvestigationRecord.Confidence != "" {- snapshot.Confidence = string(f.InvestigationRecord.Confidence)+ out := make([]AgentResourceFindingSnapshot, 0, len(active))+ for _, f := range active {+ snapshot := AgentResourceFindingSnapshot{+ ID: f.ID,+ Title: f.Title,+ Severity: string(f.Severity),+ Category: string(f.Category),+ Description: f.Description,+ Impact: f.Impact,+ Recommendation: f.Recommendation,+ RegressionCount: f.RegressionCount,+ PreviousResolvedFixSummary: f.PreviousResolvedFixSummary,+ }+ if !f.DetectedAt.IsZero() {+ snapshot.DetectedAt = f.DetectedAt.Format(time.RFC3339)+ }+ if !f.LastSeenAt.IsZero() {+ snapshot.LastSeenAt = f.LastSeenAt.Format(time.RFC3339)+ }+ if f.InvestigationRecord != nil && f.InvestigationRecord.Confidence != "" {+ snapshot.Confidence = string(f.InvestigationRecord.Confidence)+ }+ out = append(out, snapshot)}- out = append(out, snapshot)- }- return out- }),+ return out+ },+ activeCount: func() int {+ if patrol == nil {+ return 0+ }+ findings := patrol.GetFindings()+ if findings == nil {+ return 0+ }+ return len(findings.GetActive(ai.FindingSeverityWarning))+ },+ },)}// Wire per-resource operator-state into the findings runtime so@@ -2597,7 +2642,7 @@ func (r *Router) persistenceForOrg(ctx context.Context) *config.ConfigPersistencreturn nil}-// wireAIChatDependenciesForService wires org-scoped MCP tool providers and chat-service+// wireAIChatDependenciesForService wires org-scoped Assistant tool providers and chat-service// integration for a specific chat service instance.func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service AIService) {if r == nil || service == nil {@@ -2661,7 +2706,7 @@ func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service A// Wire alert providerif monitor != nil {if alertManager := monitor.GetAlertManager(); alertManager != nil {- alertAdapter := tools.NewAlertManagerMCPAdapter(alertManager)+ alertAdapter := tools.NewAlertManagerToolAdapter(alertManager)if alertAdapter != nil {service.SetAlertProvider(alertAdapter)log.Debug().Msg("AI chat: Alert provider wired")@@ -2678,7 +2723,7 @@ func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service A}}if findingsStore := patrolSvc.GetFindings(); findingsStore != nil {- findingsAdapter := ai.NewFindingsMCPAdapter(findingsStore)+ findingsAdapter := ai.NewFindingsToolAdapter(findingsStore)if findingsAdapter != nil {service.SetFindingsProvider(findingsAdapter)log.Debug().Msg("AI chat: Findings provider wired")@@ -2692,14 +2737,14 @@ func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service Aif r.licenseHandlers != nil {licenseSvc = r.licenseHandlers.Service(ctx)}- manager := NewMCPAgentProfileManager(persistence, licenseSvc)+ manager := NewAssistantAgentProfileManager(persistence, licenseSvc)service.SetAgentProfileManager(manager)log.Debug().Msg("AI chat: Agent profile manager wired")}// Wire guest config provider (storage provider wiring removed)if monitor != nil {- guestConfigAdapter := tools.NewGuestConfigMCPAdapter(monitor)+ guestConfigAdapter := tools.NewGuestConfigToolAdapter(monitor)if guestConfigAdapter != nil {service.SetGuestConfigProvider(guestConfigAdapter)log.Debug().Msg("AI chat: Guest config provider wired")@@ -2709,7 +2754,7 @@ func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service A// Wire backup providerif monitor != nil {m := monitor- backupAdapter := tools.NewBackupMCPAdapter(+ backupAdapter := tools.NewBackupToolAdapter(func() models.Backups { return m.BackupsSnapshot() },func() []models.PBSInstance { return m.PBSInstancesSnapshot() },)@@ -2721,7 +2766,7 @@ func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service A// Wire disk health providerif monitor != nil {- diskHealthAdapter := tools.NewDiskHealthMCPAdapter(monitor.GetUnifiedReadState())+ diskHealthAdapter := tools.NewDiskHealthToolAdapter(monitor.GetUnifiedReadState())if diskHealthAdapter != nil {service.SetDiskHealthProvider(diskHealthAdapter)log.Debug().Msg("AI chat: Disk health provider wired")@@ -2734,7 +2779,7 @@ func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service Aif monitorCfg := monitor.GetConfig(); monitorCfg != nil {cfg = monitorCfg}- updatesAdapter := tools.NewUpdatesMCPAdapter(+ updatesAdapter := tools.NewUpdatesToolAdapter(monitor.GetUnifiedReadState(),monitor,&updatesConfigWrapper{cfg: cfg},@@ -2748,7 +2793,7 @@ func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service A// Wire metrics history providerif monitor != nil {if metricsHistory := monitor.GetMetricsHistory(); metricsHistory != nil {- metricsAdapter := tools.NewMetricsHistoryMCPAdapter(+ metricsAdapter := tools.NewMetricsHistoryToolAdapter(&metricsSourceWrapper{history: metricsHistory},monitor.GetUnifiedReadState(),)@@ -2763,7 +2808,7 @@ func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service Aif aiService != nil {if patrolSvc := aiService.GetPatrolService(); patrolSvc != nil {if baselineStore := patrolSvc.GetBaselineStore(); baselineStore != nil {- baselineAdapter := tools.NewBaselineMCPAdapter(&baselineSourceWrapper{store: baselineStore})+ baselineAdapter := tools.NewBaselineToolAdapter(&baselineSourceWrapper{store: baselineStore})if baselineAdapter != nil {service.SetBaselineProvider(baselineAdapter)log.Debug().Msg("AI chat: Baseline provider wired")@@ -2776,7 +2821,7 @@ func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service Aif aiService != nil {if patrolSvc := aiService.GetPatrolService(); patrolSvc != nil {if patternDetector := patrolSvc.GetPatternDetector(); patternDetector != nil {- patternAdapter := tools.NewPatternMCPAdapter(+ patternAdapter := tools.NewPatternToolAdapter(&patternSourceWrapper{detector: patternDetector},monitor.GetUnifiedReadState(),)@@ -2791,7 +2836,7 @@ func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service A// Wire findings manager.if aiService != nil {if patrolSvc := aiService.GetPatrolService(); patrolSvc != nil {- findingsManagerAdapter := tools.NewFindingsManagerMCPAdapter(patrolSvc)+ findingsManagerAdapter := tools.NewFindingsManagerToolAdapter(patrolSvc)if findingsManagerAdapter != nil {service.SetFindingsManager(findingsManagerAdapter)log.Debug().Msg("AI chat: Findings manager wired")@@ -2801,14 +2846,14 @@ func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service A// Wire metadata updater.if aiService != nil {- metadataAdapter := tools.NewMetadataUpdaterMCPAdapter(aiService)+ metadataAdapter := tools.NewMetadataUpdaterToolAdapter(aiService)if metadataAdapter != nil {service.SetMetadataUpdater(metadataAdapter)log.Debug().Msg("AI chat: Metadata updater wired")}}- // Wire intelligence providers for MCP tools+ // Wire intelligence providers for Assistant tools.// - IncidentRecorderProvider: high-frequency incident data (pulse_get_incident_window)// - EventCorrelatorProvider: Proxmox events (pulse_correlate_events)// - KnowledgeStoreProvider: notes (pulse_remember, pulse_recall)@@ -2844,7 +2889,7 @@ func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service Aif discoverySvc := aiService.GetDiscoveryService(); discoverySvc != nil {adapter := servicediscovery.NewToolsAdapter(discoverySvc)if adapter != nil {- service.SetDiscoveryProvider(tools.NewDiscoveryMCPAdapter(adapter))+ service.SetDiscoveryProvider(tools.NewDiscoveryToolAdapter(adapter))log.Debug().Msg("AI chat: Discovery provider wired")}}@@ -2875,7 +2920,7 @@ func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service Alog.Debug().Msg("AI chat: App-container config provider wired")}- log.Info().Str("org_id", orgID).Msg("AI chat MCP tool providers wired")+ log.Info().Str("org_id", orgID).Msg("AI chat Assistant tool providers wired")}// forecastResourceIterator wraps ReadState to implement forecast.ResourceIterator.diff --git a/internal/api/router_routes_ai_relay.go b/internal/api/router_routes_ai_relay.goindex 2f5f75d652..84f2b77e46 100644--- a/internal/api/router_routes_ai_relay.go+++ b/internal/api/router_routes_ai_relay.go@@ -7,6 +7,7 @@ import ("strings""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/agentexec""github.com/rcourtman/pulse-go-rewrite/internal/ai""github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"@@ -70,11 +71,11 @@ func (r *Router) registerAIRelayRoutesGroup() {})))r.mux.HandleFunc("/api/ai/cost/reset", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandleResetAICostHistory)))r.mux.HandleFunc("/api/ai/cost/export", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.aiSettingsHandler.HandleExportAICostHistory)))- // OAuth endpoints for Claude Pro/Max subscription authentication- // Require settings:write scope to prevent low-privilege tokens from modifying OAuth credentials+ // Legacy OAuth cleanup endpoints. Setup/exchange fail closed; disconnect+ // requires settings:write so low-privilege tokens cannot modify credentials.r.mux.HandleFunc("/api/ai/oauth/start", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandleOAuthStart)))- r.mux.HandleFunc("/api/ai/oauth/exchange", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandleOAuthExchange))) // Manual code input- r.mux.HandleFunc("/api/ai/oauth/callback", r.aiSettingsHandler.HandleOAuthCallback) // Public - receives redirect from Anthropic+ r.mux.HandleFunc("/api/ai/oauth/exchange", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandleOAuthExchange)))+ r.mux.HandleFunc("/api/ai/oauth/callback", r.aiSettingsHandler.HandleOAuthCallback)r.mux.HandleFunc("/api/ai/oauth/disconnect", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandleOAuthDisconnect)))// Relay routes for mobile remote access@@ -117,14 +118,35 @@ func (r *Router) registerAIRelayRoutesGroup() {r.mux.HandleFunc("/api/ai/patrol/preflight", RequirePermission(r.config, r.authorizer, auth.ActionWrite, auth.ResourceSettings, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandlePatrolPreflight)))// SECURITY: AI Patrol mutation endpoints - require ai:execute scope to prevent low-privilege tokens from// dismissing, suppressing, or otherwise hiding findings. This prevents attackers from blinding AI Patrol.- r.mux.HandleFunc("/api/ai/patrol/acknowledge", RequireAuth(r.config, requireRelayMobileRuntimeRoute(relayMobileRoutePatrolAcknowledge, r.aiSettingsHandler.HandleAcknowledgeFinding)))+ r.mux.HandleFunc("/api/ai/patrol/acknowledge", RequireAuth(r.config, requireRelayMobileRuntimeRoute(+ relayMobileRoutePatrolAcknowledge,+ r.withExternalAgentCapabilityActivity(+ agentcapabilities.AcknowledgeFindingCapabilityName,+ r.aiSettingsHandler.HandleAcknowledgeFinding,+ ),+ )))// Dismiss and resolve don't require Pro license - users should be able to clear findings they can see// This is especially important for users who accumulated findings before fixing the patrol-without-AI bug- r.mux.HandleFunc("/api/ai/patrol/dismiss", RequireAuth(r.config, requireRelayMobileRuntimeRoute(relayMobileRoutePatrolDismiss, r.aiSettingsHandler.HandleDismissFinding)))+ r.mux.HandleFunc("/api/ai/patrol/dismiss", RequireAuth(r.config, requireRelayMobileRuntimeRoute(+ relayMobileRoutePatrolDismiss,+ r.withExternalAgentCapabilityActivity(+ agentcapabilities.DismissFindingCapabilityName,+ r.aiSettingsHandler.HandleDismissFinding,+ ),+ )))r.mux.HandleFunc("/api/ai/patrol/findings/note", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleSetFindingNote)))r.mux.HandleFunc("/api/ai/patrol/suppress", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleSuppressFinding)))- r.mux.HandleFunc("/api/ai/patrol/snooze", RequireAuth(r.config, requireRelayMobileRuntimeRoute(relayMobileRoutePatrolSnooze, r.aiSettingsHandler.HandleSnoozeFinding)))- r.mux.HandleFunc("/api/ai/patrol/resolve", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleResolveFinding)))+ r.mux.HandleFunc("/api/ai/patrol/snooze", RequireAuth(r.config, requireRelayMobileRuntimeRoute(+ relayMobileRoutePatrolSnooze,+ r.withExternalAgentCapabilityActivity(+ agentcapabilities.SnoozeFindingCapabilityName,+ r.aiSettingsHandler.HandleSnoozeFinding,+ ),+ )))+ r.mux.HandleFunc("/api/ai/patrol/resolve", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.withExternalAgentCapabilityActivity(+ agentcapabilities.ResolveFindingCapabilityName,+ r.aiSettingsHandler.HandleResolveFinding,+ ))))r.mux.HandleFunc("/api/ai/patrol/runs", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleGetPatrolRunHistory)))r.mux.HandleFunc("/api/ai/patrol/runs/", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleGetPatrolRun)))// Suppression rules management - require scope to prevent low-privilege tokens from creating suppression rules@@ -203,6 +225,9 @@ func (r *Router) registerAIRelayRoutesGroup() {// AI chat endpoints// SECURITY: Status endpoint is part of chat UX and should require ai:chat scope for token clients.r.mux.HandleFunc("/api/ai/status", RequireAuth(r.config, RequireScope(config.ScopeAIChat, r.aiHandler.HandleStatus)))+ r.mux.HandleFunc("/api/ai/assistant/surface-tools", RequireAuth(r.config, RequireScope(config.ScopeAIChat, r.aiHandler.HandleAssistantSurfaceTools)))+ r.mux.HandleFunc("/api/ai/workflow-prompts/render", RequireAuth(r.config, RequireScope(config.ScopeAIChat, r.aiHandler.HandleRenderWorkflowPrompt)))+ r.mux.HandleFunc("/api/ai/workflow-prompts/activity", RequireAuth(r.config, RequireScope(config.ScopeAIChat, r.aiHandler.HandleRecordWorkflowPromptActivity)))r.mux.HandleFunc("/api/ai/chat", RequireAuth(r.config, requireRelayMobileRuntimeRoute(relayMobileRouteChatSend, r.aiHandler.HandleChat)))r.mux.HandleFunc("/api/ai/sessions", RequireAuth(r.config, r.routeAISessionsCollection))r.mux.HandleFunc("/api/ai/sessions/", RequireAuth(r.config, r.routeAISessions))@@ -219,7 +244,7 @@ func (r *Router) registerAIRelayRoutesGroup() {r.aiSettingsHandler.SetAIAutoFixEndpoints(r.aiAutoFixEndpoints)}-// --- Safe remediation free-tier adapter ---+// --- Patrol fix-action free-tier adapter ---// All methods return 402 "requires Pulse Pro". Enterprise binders replace this// with real handler implementations.@@ -266,7 +291,7 @@ func (aiAutoFixFreeAdapter) HandleRollbackRemediationPlan(w http.ResponseWriter,}func (aiAutoFixFreeAdapter) HandleApproveInvestigationFix(w http.ResponseWriter, _ *http.Request) {- WriteLicenseRequired(w, featureAIAutoFixKey, "Safe remediation workflows require Pulse Pro")+ WriteLicenseRequired(w, featureAIAutoFixKey, "Patrol fix actions require Pulse Pro")}func (a aiAutoFixFreeAdapter) HandleListApprovals(w http.ResponseWriter, req *http.Request) {@@ -298,6 +323,7 @@ func newAIAutoFixRuntime(r *Router) extensions.AIAutoFixRuntime {func newAIAutoFixHandlerDeps(r *Router) extensions.AIAutoFixHandlerDeps {h := r.aiSettingsHandler+ toolAdapter := &assistantToolAdapter{handler: h}return extensions.AIAutoFixHandlerDeps{GetInvestigationStore: func(orgID string) aicontracts.InvestigationStore {h.investigationMu.RLock()@@ -310,10 +336,10 @@ func newAIAutoFixHandlerDeps(r *Router) extensions.AIAutoFixHandlerDeps {}return &approvalStoreAdapter{}},- MCPExecutor: &mcpToolAdapter{handler: h},- AgentExecutor: &agentCommandAdapter{handler: h},- FindingUpdater: &findingOutcomeAdapter{handler: h},- FixVerifier: &fixVerificationAdapter{handler: h},+ AssistantToolExecutor: toolAdapter,+ AgentExecutor: &agentCommandAdapter{handler: h},+ FindingUpdater: &findingOutcomeAdapter{handler: h},+ FixVerifier: &fixVerificationAdapter{handler: h},PatrolConfig: func(req *http.Request) aicontracts.PatrolConfigAccessor {svc := h.GetAIService(req.Context())if svc == nil {@@ -636,14 +662,15 @@ func preflightInfoToRequest(preflight *aicontracts.ActionPreflightInfo) *approva}}-// mcpToolAdapter implements aicontracts.MCPToolExecutor by wrapping the chat service.-type mcpToolAdapter struct {+// assistantToolAdapter executes approved native Assistant tool invocations by+// wrapping the chat service's shared registry execution path.+type assistantToolAdapter struct {handler *AISettingsHandler}-var _ aicontracts.MCPToolExecutor = (*mcpToolAdapter)(nil)+var _ aicontracts.ApprovedAssistantToolExecutor = (*assistantToolAdapter)(nil)-func (m *mcpToolAdapter) ExecuteMCPTool(ctx context.Context, command, approvalID string) (string, int, error) {+func (m *assistantToolAdapter) ExecuteApprovedAssistantTool(ctx context.Context, command, approvalID string) (string, int, error) {if m.handler.chatHandler == nil {return "", -1, fmt.Errorf("chat handler not available")}@@ -655,15 +682,13 @@ func (m *mcpToolAdapter) ExecuteMCPTool(ctx context.Context, command, approvalIDif !ok {return "", -1, fmt.Errorf("chat service type mismatch")}- toolName, args, err := parseMCPToolCall(command)+ params, err := agentcapabilities.ParseTextToolInvocation(command)if err != nil {return "", -1, fmt.Errorf("failed to parse tool call: %w", err)}- if approvalID != "" {- args["_approval_id"] = approvalID- }- log.Info().Str("tool", toolName).Str("approvalID", approvalID).Interface("args", args).Msg("Executing MCP tool fix with pre-approval")- result, toolErr := chatService.ExecuteMCPTool(ctx, toolName, args)+ params.Arguments = agentcapabilities.WithApprovalArgument(params.Arguments, approvalID)+ log.Info().Str("tool", params.Name).Str("approvalID", approvalID).Interface("args", params.Arguments).Msg("Executing Assistant tool fix with pre-approval")+ result, toolErr := chatService.ExecuteAssistantTool(ctx, params.Name, params.Arguments)if toolErr != nil {return result, 1, toolErr}@@ -872,15 +897,6 @@ func (u *patrolConfigUpdateAdapter) ReloadConfig(ctx context.Context) error {// Pure helper functions (used by adapters)// ----------------------------------------------------------------------------// isMCPToolCall checks if a command is an MCP tool call (vs a shell command).-func isMCPToolCall(command string) bool {- return strings.HasPrefix(command, "pulse_") ||- strings.HasPrefix(command, "default_api:") ||- strings.Contains(command, "pulse_control_guest") ||- strings.Contains(command, "pulse_run_command") ||- strings.Contains(command, "pulse_get_resource")-}-// cleanTargetHost extracts just the hostname from a target host string.// Handles cases like "pve-node (The container's host is 'pve-node')" → "pve-node".func cleanTargetHost(targetHost string) string {@@ -896,81 +912,6 @@ func cleanTargetHost(targetHost string) string {return strings.TrimSpace(targetHost)}-// parseMCPToolCall parses an MCP tool call string into tool name and arguments.-func parseMCPToolCall(command string) (string, map[string]interface{}, error) {- command = strings.TrimPrefix(command, "default_api:")- openParen := strings.Index(command, "(")- if openParen == -1 {- return "", nil, fmt.Errorf("no opening parenthesis in tool call")- }- toolName := strings.TrimSpace(command[:openParen])- closeParen := strings.LastIndex(command, ")")- if closeParen == -1 || closeParen <= openParen {- return "", nil, fmt.Errorf("no closing parenthesis in tool call")- }- argsStr := command[openParen+1 : closeParen]- args := make(map[string]interface{})- if strings.TrimSpace(argsStr) == "" {- return toolName, args, nil- }- pairs := splitToolArgs(argsStr)- for _, pair := range pairs {- parts := strings.SplitN(pair, "=", 2)- if len(parts) != 2 {- continue- }- key := strings.TrimSpace(parts[0])- value := strings.TrimSpace(parts[1])- value = strings.Trim(value, "'\"")- args[key] = value- }- return toolName, args, nil-}--// splitToolArgs splits tool arguments respecting quoted strings.-func splitToolArgs(argsStr string) []string {- var result []string- var current strings.Builder- var inQuote rune- var escaped bool- for _, r := range argsStr {- if escaped {- current.WriteRune(r)- escaped = false- continue- }- if r == '\\' {- escaped = true- current.WriteRune(r)- continue- }- if inQuote != 0 {- current.WriteRune(r)- if r == inQuote {- inQuote = 0- }- continue- }- if r == '\'' || r == '"' {- inQuote = r- current.WriteRune(r)- continue- }- if r == ',' {- if s := strings.TrimSpace(current.String()); s != "" {- result = append(result, s)- }- current.Reset()- continue- }- current.WriteRune(r)- }- if s := strings.TrimSpace(current.String()); s != "" {- result = append(result, s)- }- return result-}-func newAIAlertAnalysisRuntime(r *Router) extensions.AIAlertAnalysisRuntime {return extensions.AIAlertAnalysisRuntime{HasLicenseFeature: func(req *http.Request, feature string) bool {diff --git a/internal/api/router_routes_monitoring.go b/internal/api/router_routes_monitoring.goindex 7d061dea2b..a3e7a7256d 100644--- a/internal/api/router_routes_monitoring.go+++ b/internal/api/router_routes_monitoring.go@@ -4,6 +4,7 @@ import ("net/http""strings"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/config")@@ -52,10 +53,16 @@ func (r *Router) registerMonitoringResourceRoutes(if !ensureScope(w, req, config.ScopeMonitoringRead) {return}+ r.recordExternalAgentCapabilityActivity(req, agentcapabilities.GetOperatorStateCapabilityName)case http.MethodPut, http.MethodDelete:if !ensureScope(w, req, config.ScopeMonitoringWrite) {return}+ if req.Method == http.MethodPut {+ r.recordExternalAgentCapabilityActivity(req, agentcapabilities.SetOperatorStateCapabilityName)+ } else {+ r.recordExternalAgentCapabilityActivity(req, agentcapabilities.ClearOperatorStateCapabilityName)+ }default:http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return@@ -78,28 +85,60 @@ func (r *Router) registerMonitoringResourceRoutes(// (in-process Patrol/Assistant or external) that needs the full// situated picture of a resource in one read instead of chaining// resource + operator-state + findings + audit calls.- r.mux.HandleFunc("/api/agent/resource-context/{id}", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.agentContextHandler.HandleResourceContext)))+ r.mux.HandleFunc("/api/agent/resource-context/{id}", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.withExternalAgentCapabilityActivity(+ agentcapabilities.ResourceContextCapabilityName,+ r.agentContextHandler.HandleResourceContext,+ ))))// Agent-consumable fleet triage view — thin per-resource rollups// across the org so an agent can pick a focus in one read instead// of walking every resource id and bundling each. Companion to the// per-resource context endpoint: this is "where do I look?", that// is "tell me everything about this one."- r.mux.HandleFunc("/api/agent/fleet-context", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.agentContextHandler.HandleFleetContext)))+ r.mux.HandleFunc("/api/agent/fleet-context", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.withExternalAgentCapabilityActivity(+ agentcapabilities.FleetContextCapabilityName,+ r.agentContextHandler.HandleFleetContext,+ ))))+ // Content-safe Patrol control status: the shared Patrol, Assistant,+ // governed action, verification, Patrol control proof, and optional MCP+ // readiness projection for native UI and external agents.+ r.mux.HandleFunc(agentcapabilities.PatrolControlStatusCapabilityPath, RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.withExternalAgentCapabilityActivity(+ agentcapabilities.PatrolControlStatusCapabilityName,+ r.agentContextHandler.HandleOperationsLoopStatus,+ ))))+ // Legacy operations-loop route kept for older external-agent clients. New+ // clients should discover the Patrol control route from the manifest.+ r.mux.HandleFunc(agentcapabilities.OperationsLoopStatusCompatibilityPath, RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.withExternalAgentCapabilityActivity(+ agentcapabilities.OperationsLoopStatusCapabilityName,+ r.agentContextHandler.HandleOperationsLoopStatus,+ ))))// Agent capabilities manifest — discovery document. Unauthenticated// because it only describes the agent surface; the capabilities// themselves keep their own auth scopes. Agents fetch this once at// startup to learn what's available.r.mux.HandleFunc("/api/agent/capabilities", HandleAgentCapabilitiesManifest)+ r.mux.HandleFunc("POST /api/agent/workflow-prompt-activity", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.HandleAgentWorkflowPromptActivity)))// Agent SSE event stream — agents subscribe once and receive// real-time notifications instead of polling. Auth at// monitoring:read because the stream surfaces the same// information already available via the read endpoints.if r.agentEventBroadcaster != nil {- r.mux.HandleFunc("/api/agent/events", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.agentEventBroadcaster.HandleAgentEvents)))+ r.mux.HandleFunc("/api/agent/events", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.withExternalAgentCapabilityActivity(+ agentcapabilities.EventSubscriptionCapabilityName,+ r.agentEventBroadcaster.HandleAgentEvents,+ ))))}- r.mux.HandleFunc("POST /api/actions/plan", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.resourceHandlers.HandlePlanAction)))- r.mux.HandleFunc("POST /api/actions/{id}/decision", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.resourceHandlers.HandleDecideAction)))- r.mux.HandleFunc("POST /api/actions/{id}/execute", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.resourceHandlers.HandleExecuteAction)))+ r.mux.HandleFunc("POST /api/actions/plan", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.withExternalAgentCapabilityActivity(+ agentcapabilities.PlanActionCapabilityName,+ r.resourceHandlers.HandlePlanAction,+ ))))+ r.mux.HandleFunc("POST /api/actions/{id}/decision", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.withExternalAgentCapabilityActivity(+ agentcapabilities.DecideActionCapabilityName,+ r.resourceHandlers.HandleDecideAction,+ ))))+ r.mux.HandleFunc("POST /api/actions/{id}/execute", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.withExternalAgentCapabilityActivity(+ agentcapabilities.ExecuteActionCapabilityName,+ r.resourceHandlers.HandleExecuteAction,+ ))))// Guest metadata routesr.mux.HandleFunc("/api/guests/metadata", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, guestMetadataHandler.HandleGetMetadata)))r.mux.HandleFunc("/api/guests/metadata/", RequireAuth(r.config, func(w http.ResponseWriter, req *http.Request) {@@ -222,7 +261,10 @@ func (r *Router) registerMonitoringResourceRoutes(}infraUpdateHandlers.HandleGetInfraUpdateForResource(w, req, resourceID)})))- r.mux.HandleFunc("/api/discover", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.configHandlers.HandleDiscoverServers)))+ r.mux.HandleFunc("/api/discover", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(+ agentcapabilities.DiscoverLANCapabilityName,+ r.configHandlers.HandleDiscoverServers,+ ))))// Alert routes enforce read/write scopes inside HandleAlerts per endpoint method.r.mux.HandleFunc("/api/alerts/", RequireAuth(r.config, r.alertHandlers.HandleAlerts))diff --git a/internal/api/router_routes_registration.go b/internal/api/router_routes_registration.goindex f3614fdbcc..ee8cf35598 100644--- a/internal/api/router_routes_registration.go+++ b/internal/api/router_routes_registration.go@@ -7,6 +7,7 @@ import ("strings""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/websocket""github.com/rs/zerolog/log"@@ -132,9 +133,15 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {r.mux.HandleFunc("/api/config/nodes", func(w http.ResponseWriter, req *http.Request) {switch req.Method {case http.MethodGet:- RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.configHandlers.HandleGetNodes))(w, req)+ RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.withExternalAgentCapabilityActivity(+ agentcapabilities.ListNodesCapabilityName,+ r.configHandlers.HandleGetNodes,+ )))(w, req)case http.MethodPost:- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.configHandlers.HandleAddNode))(w, req)+ RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(+ agentcapabilities.AddNodeCapabilityName,+ r.configHandlers.HandleAddNode,+ )))(w, req)default:http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)}@@ -142,7 +149,10 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {// Test node configuration endpoint (for new nodes)r.mux.HandleFunc("/api/config/nodes/test-config", func(w http.ResponseWriter, req *http.Request) {if req.Method == http.MethodPost {- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.configHandlers.HandleTestNodeConfig))(w, req)+ RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(+ agentcapabilities.TestNodeCredentialsCapabilityName,+ r.configHandlers.HandleTestNodeConfig,+ )))(w, req)} else {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)}@@ -159,15 +169,27 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {r.mux.HandleFunc("/api/config/nodes/", func(w http.ResponseWriter, req *http.Request) {switch req.Method {case http.MethodPut:- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.configHandlers.HandleUpdateNode))(w, req)+ RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(+ agentcapabilities.UpdateNodeCapabilityName,+ r.configHandlers.HandleUpdateNode,+ )))(w, req)case http.MethodDelete:- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.configHandlers.HandleDeleteNode))(w, req)+ RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(+ agentcapabilities.RemoveNodeCapabilityName,+ r.configHandlers.HandleDeleteNode,+ )))(w, req)case http.MethodPost:// Handle test endpoint and refresh-cluster endpointif strings.HasSuffix(req.URL.Path, "/test") {- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.configHandlers.HandleTestNode))(w, req)+ RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(+ agentcapabilities.TestNodeConnectionCapabilityName,+ r.configHandlers.HandleTestNode,+ )))(w, req)} else if strings.HasSuffix(req.URL.Path, "/refresh-cluster") {- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.configHandlers.HandleRefreshClusterNodes))(w, req)+ RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(+ agentcapabilities.RefreshNodeClusterMembershipCapabilityName,+ r.configHandlers.HandleRefreshClusterNodes,+ )))(w, req)} else {http.Error(w, "Not found", http.StatusNotFound)}diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.goindex 637a0ed5a1..b7387f4ef6 100644--- a/internal/api/security_regression_test.go+++ b/internal/api/security_regression_test.go@@ -1573,6 +1573,9 @@ func TestRelayMobileAccessScopeDeniesAdjacentAIRoutes(t *testing.T) {}{{method: http.MethodGet, path: "/api/ai/models", body: "", want: config.ScopeAIChat},{method: http.MethodGet, path: "/api/ai/status", body: "", want: config.ScopeAIChat},+ {method: http.MethodGet, path: "/api/ai/assistant/surface-tools", body: "", want: config.ScopeAIChat},+ {method: http.MethodPost, path: "/api/ai/workflow-prompts/render", body: `{}`, want: config.ScopeAIChat},+ {method: http.MethodPost, path: "/api/ai/workflow-prompts/activity", body: `{}`, want: config.ScopeAIChat},{method: http.MethodGet, path: "/api/ai/agents", body: "", want: config.ScopeAIExecute},{method: http.MethodGet, path: "/api/ai/approvals/approval-1", body: "", want: config.ScopeAIExecute},{method: http.MethodDelete, path: "/api/ai/patrol/findings", body: "", want: config.ScopeAIExecute},@@ -3214,6 +3217,9 @@ func TestAIChatEndpointsRequireAIChatScope(t *testing.T) {body string}{{method: http.MethodGet, path: "/api/ai/models", body: ""},+ {method: http.MethodGet, path: "/api/ai/assistant/surface-tools", body: ""},+ {method: http.MethodPost, path: "/api/ai/workflow-prompts/render", body: `{}`},+ {method: http.MethodPost, path: "/api/ai/workflow-prompts/activity", body: `{}`},{method: http.MethodPost, path: "/api/ai/chat", body: `{}`},{method: http.MethodGet, path: "/api/ai/sessions", body: ""},{method: http.MethodGet, path: "/api/ai/sessions/session-1", body: ""},diff --git a/internal/api/telemetry_pulse_intelligence.go b/internal/api/telemetry_pulse_intelligence.gonew file mode 100644index 0000000000..dc70f5db8c--- /dev/null+++ b/internal/api/telemetry_pulse_intelligence.go@@ -0,0 +1,278 @@+package api++import (+ "strings"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/telemetry"+ unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+ "github.com/rs/zerolog/log"+)++// GetPulseIntelligenceActionTelemetry returns count-only action-governance+// telemetry for the anonymous Pulse Intelligence loop. It deliberately drops+// command text, approval actors/reasons, action outputs, and resource IDs.+func (r *Router) GetPulseIntelligenceActionTelemetry(since time.Time) telemetry.PulseIntelligenceActionSnapshot {+ var snapshot telemetry.PulseIntelligenceActionSnapshot+ if r == nil || r.resourceHandlers == nil {+ return snapshot+ }++ for _, orgID := range r.pulseIntelligenceTelemetryOrgIDs() {+ store, err := r.resourceHandlers.getStore(orgID)+ if err != nil || store == nil {+ log.Warn().Err(err).Str("org_id", orgID).Msg("Unable to resolve action audit store for telemetry summary")+ continue+ }+ approvedAttemptIDs, approvedSuccessIDs := pulseIntelligenceApprovedActionOutcomeIDs(store, orgID, since)+ rejectedDecisionIDs := pulseIntelligenceRejectedActionDecisionIDs(store, orgID, since)+ approvedDecisionIDs := pulseIntelligenceApprovedActionDecisionIDs(store, orgID, since)+ records, err := store.GetActionAudits("", since, 0)+ if err != nil {+ log.Warn().Err(err).Str("org_id", orgID).Msg("Unable to query action audit telemetry summary")+ continue+ }+ for _, record := range records {+ snapshot.ActionPlans30d+++ if pulseIntelligenceActionRequiresApproval(record) {+ snapshot.ApprovalRequests30d+++ }+ if pulseIntelligenceActionWasRejected(record) {+ if actionID := strings.TrimSpace(record.ID); actionID != "" {+ rejectedDecisionIDs[actionID] = struct{}{}+ }+ }+ if pulseIntelligenceActionWasApprovedSince(record, since) {+ if actionID := strings.TrimSpace(record.ID); actionID != "" {+ approvedDecisionIDs[actionID] = struct{}{}+ }+ }+ if pulseIntelligenceApprovedActionAttempt(record) {+ if actionID := strings.TrimSpace(record.ID); actionID != "" {+ approvedAttemptIDs[actionID] = struct{}{}+ }+ }+ if pulseIntelligenceApprovedActionSuccess(record) {+ if actionID := strings.TrimSpace(record.ID); actionID != "" {+ approvedSuccessIDs[actionID] = struct{}{}+ }+ }+ }+ snapshot.RejectedActionDecisions30d += len(rejectedDecisionIDs)+ snapshot.ApprovedActionDecisions30d += len(approvedDecisionIDs)+ snapshot.ApprovedActionAttempts30d += len(approvedAttemptIDs)+ snapshot.ApprovedActionSuccesses30d += len(approvedSuccessIDs)+ }++ return snapshot+}++func (r *Router) pulseIntelligenceTelemetryOrgIDs() []string {+ if r == nil || r.multiTenant == nil {+ return []string{"default"}+ }+ orgs, err := r.multiTenant.ListOrganizations()+ if err != nil {+ log.Warn().Err(err).Msg("Unable to list organizations for telemetry summary")+ return []string{"default"}+ }+ seen := map[string]struct{}{}+ orgIDs := make([]string, 0, len(orgs))+ for _, org := range orgs {+ if org == nil {+ continue+ }+ orgID := strings.TrimSpace(org.ID)+ if orgID == "" {+ orgID = "default"+ }+ if _, ok := seen[orgID]; ok {+ continue+ }+ seen[orgID] = struct{}{}+ orgIDs = append(orgIDs, orgID)+ }+ if len(orgIDs) == 0 {+ return []string{"default"}+ }+ return orgIDs+}++func pulseIntelligenceActionRequiresApproval(record unifiedresources.ActionAuditRecord) bool {+ if record.Plan.RequiresApproval {+ return true+ }+ return len(record.Approvals) > 0 || record.State == unifiedresources.ActionStatePending ||+ record.State == unifiedresources.ActionStateApproved || record.State == unifiedresources.ActionStateRejected+}++func pulseIntelligenceApprovedActionOutcomeIDs(store unifiedresources.ResourceStore, orgID string, since time.Time) (map[string]struct{}, map[string]struct{}) {+ attemptIDs := map[string]struct{}{}+ successIDs := map[string]struct{}{}+ if store == nil {+ return attemptIDs, successIDs+ }+ events, err := store.GetActionLifecycleEvents("", since, 0)+ if err != nil {+ log.Warn().Err(err).Str("org_id", orgID).Msg("Unable to query action lifecycle telemetry summary")+ return attemptIDs, successIDs+ }+ for _, event := range events {+ if !pulseIntelligenceActionLifecycleIndicatesAttempt(event) {+ continue+ }+ actionID := strings.TrimSpace(event.ActionID)+ if actionID == "" {+ continue+ }+ record, ok, err := store.GetActionAudit(actionID)+ if err != nil {+ log.Warn().Err(err).Str("org_id", orgID).Msg("Unable to resolve action audit for lifecycle telemetry summary")+ continue+ }+ if ok && pulseIntelligenceActionWasApproved(record) {+ attemptIDs[actionID] = struct{}{}+ if event.State == unifiedresources.ActionStateCompleted && pulseIntelligenceApprovedActionSuccess(record) {+ successIDs[actionID] = struct{}{}+ }+ }+ }+ return attemptIDs, successIDs+}++func pulseIntelligenceRejectedActionDecisionIDs(store unifiedresources.ResourceStore, orgID string, since time.Time) map[string]struct{} {+ decisionIDs := map[string]struct{}{}+ if store == nil {+ return decisionIDs+ }+ events, err := store.GetActionLifecycleEvents("", since, 0)+ if err != nil {+ log.Warn().Err(err).Str("org_id", orgID).Msg("Unable to query rejected action lifecycle telemetry summary")+ return decisionIDs+ }+ for _, event := range events {+ if event.State != unifiedresources.ActionStateRejected {+ continue+ }+ actionID := strings.TrimSpace(event.ActionID)+ if actionID == "" {+ continue+ }+ record, ok, err := store.GetActionAudit(actionID)+ if err != nil {+ log.Warn().Err(err).Str("org_id", orgID).Msg("Unable to resolve rejected action audit for telemetry summary")+ continue+ }+ if ok && pulseIntelligenceActionWasRejected(record) {+ decisionIDs[actionID] = struct{}{}+ }+ }+ return decisionIDs+}++func pulseIntelligenceApprovedActionDecisionIDs(store unifiedresources.ResourceStore, orgID string, since time.Time) map[string]struct{} {+ decisionIDs := map[string]struct{}{}+ if store == nil {+ return decisionIDs+ }+ events, err := store.GetActionLifecycleEvents("", since, 0)+ if err != nil {+ log.Warn().Err(err).Str("org_id", orgID).Msg("Unable to query approved action lifecycle telemetry summary")+ return decisionIDs+ }+ for _, event := range events {+ if event.State != unifiedresources.ActionStateApproved {+ continue+ }+ actionID := strings.TrimSpace(event.ActionID)+ if actionID == "" {+ continue+ }+ record, ok, err := store.GetActionAudit(actionID)+ if err != nil {+ log.Warn().Err(err).Str("org_id", orgID).Msg("Unable to resolve approved action audit for telemetry summary")+ continue+ }+ if ok && pulseIntelligenceActionWasApproved(record) {+ decisionIDs[actionID] = struct{}{}+ }+ }+ return decisionIDs+}++func pulseIntelligenceApprovedActionAttempt(record unifiedresources.ActionAuditRecord) bool {+ if !pulseIntelligenceActionWasApproved(record) {+ return false+ }+ switch record.State {+ case unifiedresources.ActionStateExecuting, unifiedresources.ActionStateCompleted, unifiedresources.ActionStateFailed:+ return true+ default:+ return false+ }+}++func pulseIntelligenceApprovedActionSuccess(record unifiedresources.ActionAuditRecord) bool {+ if record.State != unifiedresources.ActionStateCompleted {+ return false+ }+ return pulseIntelligenceActionVerifiedOutcome(record)+}++func pulseIntelligenceActionVerifiedOutcome(record unifiedresources.ActionAuditRecord) bool {+ if !pulseIntelligenceActionWasApproved(record) {+ return false+ }+ outcome := unifiedresources.NormalizeVerificationOutcome(record.VerificationOutcome)+ if outcome.Status == unifiedresources.VerificationVerified {+ return true+ }+ verification := unifiedresources.CanonicalActionVerification(record)+ return verification != nil && verification.Ran && verification.Success+}++func pulseIntelligenceActionLifecycleIndicatesAttempt(event unifiedresources.ActionLifecycleEvent) bool {+ switch event.State {+ case unifiedresources.ActionStateExecuting, unifiedresources.ActionStateCompleted, unifiedresources.ActionStateFailed:+ return true+ default:+ return false+ }+}++func pulseIntelligenceActionWasApproved(record unifiedresources.ActionAuditRecord) bool {+ if record.State == unifiedresources.ActionStateApproved {+ return true+ }+ for _, approval := range record.Approvals {+ if approval.Outcome == unifiedresources.OutcomeApproved {+ return true+ }+ }+ return false+}++func pulseIntelligenceActionWasApprovedSince(record unifiedresources.ActionAuditRecord, since time.Time) bool {+ for _, approval := range record.Approvals {+ if approval.Outcome != unifiedresources.OutcomeApproved {+ continue+ }+ if approval.Timestamp.IsZero() || approval.Timestamp.Before(since) {+ continue+ }+ return true+ }+ return false+}++func pulseIntelligenceActionWasRejected(record unifiedresources.ActionAuditRecord) bool {+ if record.State == unifiedresources.ActionStateRejected {+ return true+ }+ for _, approval := range record.Approvals {+ if approval.Outcome == unifiedresources.OutcomeRejected {+ return true+ }+ }+ return false+}diff --git a/internal/api/telemetry_pulse_intelligence_test.go b/internal/api/telemetry_pulse_intelligence_test.gonew file mode 100644index 0000000000..f08ec5a2aa--- /dev/null+++ b/internal/api/telemetry_pulse_intelligence_test.go@@ -0,0 +1,276 @@+package api++import (+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/telemetry"+ unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++func TestGetPulseIntelligenceActionTelemetry_SummarizesActionGovernanceOnly(t *testing.T) {+ now := time.Date(2026, 6, 20, 9, 30, 0, 0, time.UTC)+ since := now.Add(-telemetry.PulseIntelligenceTelemetryWindow)+ dataDir := t.TempDir()+ mtPersistence := config.NewMultiTenantPersistence(dataDir)+ if err := mtPersistence.SaveOrganization(&models.Organization{ID: "tenant-a", DisplayName: "Tenant A"}); err != nil {+ t.Fatalf("SaveOrganization: %v", err)+ }++ router := &Router{+ multiTenant: mtPersistence,+ resourceHandlers: NewResourceHandlers(&config.Config{DataPath: dataDir}),+ }++ defaultStore, err := router.resourceHandlers.getStore("default")+ if err != nil {+ t.Fatalf("default getStore: %v", err)+ }+ tenantStore, err := router.resourceHandlers.getStore("tenant-a")+ if err != nil {+ t.Fatalf("tenant getStore: %v", err)+ }++ approvedCompleted := pulseTelemetryActionRecord("approved-completed", now.Add(-35*time.Minute), unifiedresources.ActionStateCompleted, true, []unifiedresources.ActionApprovalRecord{+ {Outcome: unifiedresources.OutcomeApproved, Method: unifiedresources.MethodUI, Timestamp: now.Add(-34 * time.Minute), Actor: "operator"},+ })+ approvedCompleted.Result = &unifiedresources.ExecutionResult{Success: true}+ approvedCompleted.VerificationOutcome = unifiedresources.VerificationOutcome{Status: unifiedresources.VerificationVerified}+ records := map[unifiedresources.ResourceStore][]unifiedresources.ActionAuditRecord{+ defaultStore: {+ pulseTelemetryActionRecord("plan-only", now.Add(-time.Hour), unifiedresources.ActionStatePlanned, false, nil),+ pulseTelemetryActionRecord("pending", now.Add(-50*time.Minute), unifiedresources.ActionStatePending, true, nil),+ pulseTelemetryActionRecord("approved-executing", now.Add(-40*time.Minute), unifiedresources.ActionStateExecuting, true, []unifiedresources.ActionApprovalRecord{+ {Outcome: unifiedresources.OutcomeApproved, Method: unifiedresources.MethodUI, Timestamp: now.Add(-39 * time.Minute), Actor: "operator"},+ }),+ approvedCompleted,+ pulseTelemetryActionRecord("old-approved", since.Add(-time.Minute), unifiedresources.ActionStateCompleted, true, []unifiedresources.ActionApprovalRecord{+ {Outcome: unifiedresources.OutcomeApproved, Method: unifiedresources.MethodUI, Timestamp: since.Add(-2 * time.Minute), Actor: "operator"},+ }),+ },+ tenantStore: {+ pulseTelemetryActionRecord("tenant-approved-failed", now.Add(-30*time.Minute), unifiedresources.ActionStateFailed, true, []unifiedresources.ActionApprovalRecord{+ {Outcome: unifiedresources.OutcomeApproved, Method: unifiedresources.MethodAPI, Timestamp: now.Add(-29 * time.Minute), Actor: "operator"},+ }),+ pulseTelemetryActionRecord("tenant-rejected", now.Add(-20*time.Minute), unifiedresources.ActionStateRejected, true, []unifiedresources.ActionApprovalRecord{+ {Outcome: unifiedresources.OutcomeRejected, Method: unifiedresources.MethodUI, Timestamp: now.Add(-19 * time.Minute), Actor: "operator"},+ }),+ },+ }+ for store, storeRecords := range records {+ for _, record := range storeRecords {+ if err := store.RecordActionAudit(record); err != nil {+ t.Fatalf("RecordActionAudit(%s): %v", record.ID, err)+ }+ }+ }++ got := router.GetPulseIntelligenceActionTelemetry(since)++ if got.ActionPlans30d != 6 {+ t.Fatalf("ActionPlans30d = %d, want 6", got.ActionPlans30d)+ }+ if got.ApprovalRequests30d != 5 {+ t.Fatalf("ApprovalRequests30d = %d, want 5", got.ApprovalRequests30d)+ }+ if got.RejectedActionDecisions30d != 1 {+ t.Fatalf("RejectedActionDecisions30d = %d, want 1", got.RejectedActionDecisions30d)+ }+ if got.ApprovedActionDecisions30d != 3 {+ t.Fatalf("ApprovedActionDecisions30d = %d, want 3", got.ApprovedActionDecisions30d)+ }+ if got.ApprovedActionAttempts30d != 3 {+ t.Fatalf("ApprovedActionAttempts30d = %d, want 3", got.ApprovedActionAttempts30d)+ }+ if got.ApprovedActionSuccesses30d != 1 {+ t.Fatalf("ApprovedActionSuccesses30d = %d, want 1", got.ApprovedActionSuccesses30d)+ }+}++func TestGetPulseIntelligenceActionTelemetry_CountsApprovedLifecycleAttemptsInsideWindow(t *testing.T) {+ now := time.Date(2026, 6, 20, 10, 30, 0, 0, time.UTC)+ since := now.Add(-telemetry.PulseIntelligenceTelemetryWindow)+ dataDir := t.TempDir()+ router := &Router{+ resourceHandlers: NewResourceHandlers(&config.Config{DataPath: dataDir}),+ }+ store, err := router.resourceHandlers.getStore("default")+ if err != nil {+ t.Fatalf("getStore: %v", err)+ }++ currentApproved := pulseTelemetryActionRecord("current-approved-executed", now.Add(-2*time.Hour), unifiedresources.ActionStateApproved, true, []unifiedresources.ActionApprovalRecord{+ {Outcome: unifiedresources.OutcomeApproved, Method: unifiedresources.MethodUI, Timestamp: now.Add(-110 * time.Minute), Actor: "operator"},+ })+ if err := store.RecordActionAudit(currentApproved); err != nil {+ t.Fatalf("RecordActionAudit(currentApproved): %v", err)+ }+ started, startEvent, err := unifiedresources.BeginActionExecution(currentApproved, "operator", now.Add(-90*time.Minute))+ if err != nil {+ t.Fatalf("BeginActionExecution(currentApproved): %v", err)+ }+ if err := store.RecordActionExecutionStart(started, startEvent); err != nil {+ t.Fatalf("RecordActionExecutionStart(currentApproved): %v", err)+ }+ completed, doneEvent, err := unifiedresources.CompleteActionExecution(started, &unifiedresources.ExecutionResult{Success: true}, "operator", now.Add(-80*time.Minute))+ if err != nil {+ t.Fatalf("CompleteActionExecution(currentApproved): %v", err)+ }+ completed.VerificationOutcome = unifiedresources.VerificationOutcome{Status: unifiedresources.VerificationVerified}+ if err := store.RecordActionExecutionResult(completed, doneEvent); err != nil {+ t.Fatalf("RecordActionExecutionResult(currentApproved): %v", err)+ }++ oldCreatedAt := since.Add(-time.Minute)+ oldApproved := pulseTelemetryActionRecord("old-approved-executed", oldCreatedAt, unifiedresources.ActionStateApproved, true, []unifiedresources.ActionApprovalRecord{+ {Outcome: unifiedresources.OutcomeApproved, Method: unifiedresources.MethodAPI, Timestamp: oldCreatedAt.Add(time.Minute), Actor: "operator"},+ })+ oldApproved.Plan.ExpiresAt = now.Add(time.Hour)+ if err := store.RecordActionAudit(oldApproved); err != nil {+ t.Fatalf("RecordActionAudit(oldApproved): %v", err)+ }+ started, startEvent, err = unifiedresources.BeginActionExecution(oldApproved, "operator", now.Add(-60*time.Minute))+ if err != nil {+ t.Fatalf("BeginActionExecution(oldApproved): %v", err)+ }+ if err := store.RecordActionExecutionStart(started, startEvent); err != nil {+ t.Fatalf("RecordActionExecutionStart(oldApproved): %v", err)+ }++ oldRefused := pulseTelemetryActionRecord("old-approved-refused", oldCreatedAt, unifiedresources.ActionStateApproved, true, []unifiedresources.ActionApprovalRecord{+ {Outcome: unifiedresources.OutcomeApproved, Method: unifiedresources.MethodAPI, Timestamp: oldCreatedAt.Add(time.Minute), Actor: "operator"},+ })+ oldRefused.Plan.ExpiresAt = now.Add(time.Hour)+ if err := store.RecordActionAudit(oldRefused); err != nil {+ t.Fatalf("RecordActionAudit(oldRefused): %v", err)+ }+ if _, err := recordRefusedActionExecution(store, oldRefused, "operator", now.Add(-30*time.Minute), unifiedresources.ErrActionPlanDrift); err != nil {+ t.Fatalf("recordRefusedActionExecution(oldRefused): %v", err)+ }++ unapprovedRefused := pulseTelemetryActionRecord("old-unapproved-refused", oldCreatedAt, unifiedresources.ActionStatePlanned, false, nil)+ unapprovedRefused.Plan.ExpiresAt = now.Add(time.Hour)+ if err := store.RecordActionAudit(unapprovedRefused); err != nil {+ t.Fatalf("RecordActionAudit(unapprovedRefused): %v", err)+ }+ if _, err := recordRefusedActionExecution(store, unapprovedRefused, "operator", now.Add(-15*time.Minute), unifiedresources.ErrActionPlanDrift); err != nil {+ t.Fatalf("recordRefusedActionExecution(unapprovedRefused): %v", err)+ }++ oldRejected := pulseTelemetryActionRecord("old-rejected-decision", oldCreatedAt, unifiedresources.ActionStatePending, true, nil)+ oldRejected.Plan.ExpiresAt = now.Add(time.Hour)+ if err := store.RecordActionAudit(oldRejected); err != nil {+ t.Fatalf("RecordActionAudit(oldRejected): %v", err)+ }+ rejected, rejectedEvent, err := unifiedresources.ApplyActionDecision(oldRejected, unifiedresources.ActionApprovalRecord{+ Outcome: unifiedresources.OutcomeRejected,+ Method: unifiedresources.MethodAPI,+ Actor: "operator",+ }, now.Add(-10*time.Minute))+ if err != nil {+ t.Fatalf("ApplyActionDecision(oldRejected): %v", err)+ }+ if err := store.RecordActionDecision(rejected, rejectedEvent); err != nil {+ t.Fatalf("RecordActionDecision(oldRejected): %v", err)+ }++ got := router.GetPulseIntelligenceActionTelemetry(since)++ if got.ActionPlans30d != 1 {+ t.Fatalf("ActionPlans30d = %d, want 1", got.ActionPlans30d)+ }+ if got.ApprovalRequests30d != 1 {+ t.Fatalf("ApprovalRequests30d = %d, want 1", got.ApprovalRequests30d)+ }+ if got.RejectedActionDecisions30d != 1 {+ t.Fatalf("RejectedActionDecisions30d = %d, want 1", got.RejectedActionDecisions30d)+ }+ if got.ApprovedActionDecisions30d != 1 {+ t.Fatalf("ApprovedActionDecisions30d = %d, want 1", got.ApprovedActionDecisions30d)+ }+ if got.ApprovedActionAttempts30d != 3 {+ t.Fatalf("ApprovedActionAttempts30d = %d, want 3", got.ApprovedActionAttempts30d)+ }+ if got.ApprovedActionSuccesses30d != 1 {+ t.Fatalf("ApprovedActionSuccesses30d = %d, want 1", got.ApprovedActionSuccesses30d)+ }+}++func TestGetPulseIntelligenceActionTelemetry_RequiresVerifiedOutcomeForApprovedSuccess(t *testing.T) {+ now := time.Date(2026, 6, 20, 11, 30, 0, 0, time.UTC)+ since := now.Add(-telemetry.PulseIntelligenceTelemetryWindow)+ dataDir := t.TempDir()+ router := &Router{+ resourceHandlers: NewResourceHandlers(&config.Config{DataPath: dataDir}),+ }+ store, err := router.resourceHandlers.getStore("default")+ if err != nil {+ t.Fatalf("getStore: %v", err)+ }++ approved := []unifiedresources.ActionApprovalRecord{{+ Outcome: unifiedresources.OutcomeApproved,+ Method: unifiedresources.MethodUI,+ Timestamp: now.Add(-50 * time.Minute),+ Actor: "operator",+ }}+ successOnly := pulseTelemetryActionRecord("success-only", now.Add(-55*time.Minute), unifiedresources.ActionStateCompleted, true, approved)+ successOnly.Result = &unifiedresources.ExecutionResult{Success: true}++ outcomeVerified := pulseTelemetryActionRecord("outcome-verified", now.Add(-45*time.Minute), unifiedresources.ActionStateCompleted, true, approved)+ outcomeVerified.Result = &unifiedresources.ExecutionResult{Success: true}+ outcomeVerified.VerificationOutcome = unifiedresources.VerificationOutcome{Status: unifiedresources.VerificationVerified}++ legacyVerification := pulseTelemetryActionRecord("legacy-verification", now.Add(-35*time.Minute), unifiedresources.ActionStateCompleted, true, approved)+ legacyVerification.Result = &unifiedresources.ExecutionResult{Success: true}+ legacyVerification.Verification = &unifiedresources.ActionVerificationResult{+ Ran: true,+ Success: true,+ RanAt: now.Add(-30 * time.Minute),+ }++ for _, record := range []unifiedresources.ActionAuditRecord{successOnly, outcomeVerified, legacyVerification} {+ if err := store.RecordActionAudit(record); err != nil {+ t.Fatalf("RecordActionAudit(%s): %v", record.ID, err)+ }+ }++ got := router.GetPulseIntelligenceActionTelemetry(since)++ if got.ApprovedActionSuccesses30d != 2 {+ t.Fatalf("ApprovedActionSuccesses30d = %d, want 2 verified outcomes; bare successful execution must not count", got.ApprovedActionSuccesses30d)+ }+}++func pulseTelemetryActionRecord(+ id string,+ createdAt time.Time,+ state unifiedresources.ActionState,+ requiresApproval bool,+ approvals []unifiedresources.ActionApprovalRecord,+) unifiedresources.ActionAuditRecord {+ return unifiedresources.ActionAuditRecord{+ ID: id,+ CreatedAt: createdAt,+ UpdatedAt: createdAt,+ State: state,+ Request: unifiedresources.ActionRequest{+ RequestID: "req-" + id,+ ResourceID: "vm:101",+ CapabilityName: "pulse_exec",+ Reason: "test",+ RequestedBy: "pulse_assistant",+ },+ Plan: unifiedresources.ActionPlan{+ ActionID: id,+ RequestID: "req-" + id,+ Allowed: true,+ RequiresApproval: requiresApproval,+ PlannedAt: createdAt,+ ExpiresAt: createdAt.Add(time.Hour),+ },+ Approvals: approvals,+ }+}diff --git a/internal/cloudcp/portal/frontend/dev.mjs b/internal/cloudcp/portal/frontend/dev.mjsindex 00bb1db320..c64f60f989 100644--- a/internal/cloudcp/portal/frontend/dev.mjs+++ b/internal/cloudcp/portal/frontend/dev.mjs@@ -981,9 +981,9 @@ function routeCommercialAPI(request, response, url, scenario) {if (request.method === 'GET' && route === '/v1/public/pricing-model') {sendJSON(response, 200, {title: 'Simple self-hosted pricing for Pulse',- description: 'Community keeps core monitoring free. Relay gives secure remote access to the Pulse web UI, mobile app pairing, push notifications, and 14-day history. Pro adds root-cause analysis, safe remediation workflows, and 90-day history.',+ description: 'Community keeps core monitoring free. Relay gives secure remote access to the Pulse web UI, mobile app pairing, push notifications, and 14-day history. Pro adds Patrol control, alert investigation, verified fixes, and 90-day history.',explainer:- 'Community keeps core monitoring free. Relay gets your Pulse web UI securely reachable from anywhere. Pro adds root-cause analysis, safe remediation workflows, and 90-day history.',+ 'Community keeps core monitoring free. Relay gets your Pulse web UI securely reachable from anywhere. Pro adds Patrol control, alert investigation, verified fixes, and 90-day history.',plans: [{badge: 'Recommended',@@ -1009,12 +1009,12 @@ function routeCommercialAPI(request, response, url, scenario) {title: 'Pro',price: '$79/year',period: 'or $8.99/month',- blurb: 'The operator tier for root-cause analysis, safe remediation workflows, and 90-day history.',+ blurb: 'The operator tier for Patrol control, alert investigation, verified fixes, and 90-day history.',features: [{ tone: 'check', html: 'Core <strong>self-hosted monitoring</strong> included' },{ tone: 'check', html: 'Everything in Relay' },- { tone: 'check', html: 'Alert-triggered root-cause analysis' },- { tone: 'check', html: 'Safe remediation workflows with approval or autonomous mode' },+ { tone: 'check', html: 'Patrol investigates alerts' },+ { tone: 'check', html: 'Patrol fixes safe issues within your control level' },{ tone: 'check', html: '90-day history' },],buttons: [diff --git a/internal/cloudcp/portal/frontend/src/billing_view.test.ts b/internal/cloudcp/portal/frontend/src/billing_view.test.tsindex 1b0da6c470..ef29c77bd3 100644--- a/internal/cloudcp/portal/frontend/src/billing_view.test.ts+++ b/internal/cloudcp/portal/frontend/src/billing_view.test.ts@@ -240,14 +240,14 @@ describe('services view', function() {title: 'Pricing',description: 'Canonical pricing model',explainer:- 'Community keeps core monitoring free. Relay gets your Pulse web UI securely reachable from anywhere. Pro adds root-cause analysis, safe remediation workflows, and 90-day history.',+ 'Community keeps core monitoring free. Relay gets your Pulse web UI securely reachable from anywhere. Pro adds Patrol control, alert investigation, verified fixes, and 90-day history.',plans: [{tierKicker: 'Pro',title: 'Pro',price: '$79/year',period: 'or $8.99/month',- blurb: 'The operator tier for root-cause analysis, safe remediation workflows, and 90-day history.',+ blurb: 'The operator tier for Patrol control, alert investigation, verified fixes, and 90-day history.',features: [{ tone: 'check', html: 'Core <strong>self-hosted monitoring</strong> included' }],buttons: [{@@ -273,7 +273,7 @@ describe('services view', function() {'Pulse Account keeps checkout tied to the Pulse instance that opened it, so completed Relay or Pro purchases return to the right Plans page automatically.',);expect(document.getElementById('upgrade-billing-root')?.innerHTML).toContain(- 'Community keeps core monitoring free. Relay gets your Pulse web UI securely reachable from anywhere. Pro adds root-cause analysis, safe remediation workflows, and 90-day history.',+ 'Community keeps core monitoring free. Relay gets your Pulse web UI securely reachable from anywhere. Pro adds Patrol control, alert investigation, verified fixes, and 90-day history.',);expect(document.getElementById('upgrade-billing-root')?.innerHTML).not.toMatch(/Unlimited[\s\S]{0,80}self-hosted monitoring/i,@@ -349,7 +349,7 @@ describe('services view', function() {title: 'Pro',price: '$8.99',period: '$79/year available too',- blurb: 'Root-cause analysis, alert analysis, and safe remediation workflows.',+ blurb: 'Patrol control, alert investigation, and verified fixes.',features: [{ tone: 'check', html: 'Core <strong>self-hosted monitoring</strong> included' }],buttons: [{@@ -389,7 +389,7 @@ describe('services view', function() {title: 'Pro',price: '$8.99',period: '$79/year available too',- blurb: 'Root-cause analysis, alert analysis, and safe remediation workflows.',+ blurb: 'Patrol control, alert investigation, and verified fixes.',features: [{ tone: 'check', html: 'Core <strong>self-hosted monitoring</strong> included' }],buttons: [{diff --git a/internal/config/ai.go b/internal/config/ai.goindex b95bd32ab7..67fdc97f98 100644--- a/internal/config/ai.go+++ b/internal/config/ai.go@@ -6,6 +6,8 @@ import ("strconv""strings""time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")// AuthMethod represents how Anthropic authentication is performed@@ -14,7 +16,7 @@ type AuthMethod stringconst (// AuthMethodAPIKey uses a traditional API key (pay-per-use billing)AuthMethodAPIKey AuthMethod = "api_key"- // AuthMethodOAuth uses OAuth tokens (subscription-based, Pro/Max plans)+ // AuthMethodOAuth is a legacy stored value retained only so old tokens can be cleared.AuthMethodOAuth AuthMethod = "oauth")@@ -46,11 +48,11 @@ type AIConfig struct {OllamaKeepAlive string `json:"ollama_keep_alive"` // Ollama keep_alive value; empty uses the server defaultOpenAIBaseURL string `json:"openai_base_url,omitempty"` // Custom OpenAI-compatible base URL (optional)- // OAuth fields for Claude Pro/Max subscription authentication- AuthMethod AuthMethod `json:"auth_method,omitempty"` // "api_key" or "oauth" (for anthropic only)- OAuthAccessToken string `json:"oauth_access_token,omitempty"` // OAuth access token (encrypted at rest)- OAuthRefreshToken string `json:"oauth_refresh_token,omitempty"` // OAuth refresh token (encrypted at rest)- OAuthExpiresAt time.Time `json:"oauth_expires_at,omitempty"` // Token expiration time+ // Legacy Anthropic OAuth fields are retained only for cleanup/migration.+ AuthMethod AuthMethod `json:"auth_method,omitempty"` // "api_key" or legacy "oauth"+ OAuthAccessToken string `json:"oauth_access_token,omitempty"` // legacy OAuth access token (encrypted at rest)+ OAuthRefreshToken string `json:"oauth_refresh_token,omitempty"` // legacy OAuth refresh token (encrypted at rest)+ OAuthExpiresAt time.Time `json:"oauth_expires_at,omitempty"` // legacy token expiration time// Patrol settings for background AI monitoringPatrolEnabled bool `json:"patrol_enabled"` // Enable background AI health patrol@@ -120,11 +122,11 @@ const (// AI Control Level constantsconst (// ControlLevelReadOnly - AI can only query infrastructure, no control tools available- ControlLevelReadOnly = "read_only"+ ControlLevelReadOnly = string(agentcapabilities.ControlLevelReadOnly)// ControlLevelControlled - AI can execute with per-command approval- ControlLevelControlled = "controlled"+ ControlLevelControlled = string(agentcapabilities.ControlLevelControlled)// ControlLevelAutonomous - AI executes without approval (requires Pro license)- ControlLevelAutonomous = "autonomous"+ ControlLevelAutonomous = string(agentcapabilities.ControlLevelAutonomous))// Patrol Autonomy Level constants@@ -345,10 +347,6 @@ func (c *AIConfig) IsConfigured() bool {func (c *AIConfig) HasProvider(provider string) bool {switch provider {case AIProviderAnthropic:- // Anthropic can use API key OR OAuth- if c.AuthMethod == AuthMethodOAuth && c.OAuthAccessToken != "" {- return true- }return c.AnthropicAPIKey != ""case AIProviderOpenAI:return c.OpenAIAPIKey != ""@@ -440,9 +438,10 @@ func (c *AIConfig) GetBaseURLForProvider(provider string) string {return ""}-// IsUsingOAuth returns true if OAuth authentication is configured for Anthropic+// IsUsingOAuth is retained for legacy config introspection. OAuth is not a+// supported runtime authentication method for Anthropic provider execution.func (c *AIConfig) IsUsingOAuth() bool {- return c.AuthMethod == AuthMethodOAuth && c.OAuthAccessToken != ""+ return false}// ParseModelString parses a model string in "provider:model-name" format@@ -612,14 +611,14 @@ func (c *AIConfig) GetAutoFixModel() string {return c.GetPatrolModel()}-// ClearOAuthTokens clears OAuth tokens (used when switching back to API key auth)+// ClearOAuthTokens clears legacy OAuth tokens.func (c *AIConfig) ClearOAuthTokens() {c.OAuthAccessToken = ""c.OAuthRefreshToken = ""c.OAuthExpiresAt = time.Time{}}-// ClearAPIKey clears the Anthropic API key (used when switching to OAuth auth)+// ClearAPIKey clears the Anthropic API key.func (c *AIConfig) ClearAPIKey() {c.AnthropicAPIKey = ""}@@ -766,12 +765,7 @@ func (c *AIConfig) GetControlLevel() string {if c.ControlLevel == "" {return ControlLevelReadOnly}- switch c.ControlLevel {- case ControlLevelReadOnly, ControlLevelControlled, ControlLevelAutonomous:- return c.ControlLevel- default:- return ControlLevelReadOnly- }+ return string(agentcapabilities.NormalizeControlLevel(c.ControlLevel))}// EffectiveControlLevelForEntitlement returns the control level that may be@@ -798,8 +792,7 @@ func (c *AIConfig) GetEffectiveControlLevel(autonomousAllowed bool) string {// IsControlEnabled returns true if AI has any control capability beyond read-onlyfunc (c *AIConfig) IsControlEnabled() bool {- level := c.GetControlLevel()- return level != ControlLevelReadOnly+ return agentcapabilities.ControlLevelAllowsControlTools(agentcapabilities.ControlLevel(c.GetControlLevel()))}// IsAutonomous returns true if AI is configured for autonomous operation (no approval needed)@@ -809,12 +802,7 @@ func (c *AIConfig) IsAutonomous() bool {// IsValidControlLevel checks if a control level string is validfunc IsValidControlLevel(level string) bool {- switch level {- case ControlLevelReadOnly, ControlLevelControlled, ControlLevelAutonomous:- return true- default:- return false- }+ return agentcapabilities.IsValidControlLevel(level)}// GetProtectedGuests returns the list of protected guests (VMIDs or names)diff --git a/internal/config/ai_config_test.go b/internal/config/ai_config_test.goindex 2e8059301e..95784329e2 100644--- a/internal/config/ai_config_test.go+++ b/internal/config/ai_config_test.go@@ -4,6 +4,8 @@ import ("encoding/json""testing""time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")func TestEffectiveControlLevelForEntitlement(t *testing.T) {@@ -48,6 +50,24 @@ func TestEffectiveControlLevelForEntitlement(t *testing.T) {}}+func TestAIConfigControlLevelsUseSharedAgentCapabilityVocabulary(t *testing.T) {+ if ControlLevelReadOnly != string(agentcapabilities.ControlLevelReadOnly) {+ t.Fatalf("ControlLevelReadOnly = %q, want shared %q", ControlLevelReadOnly, agentcapabilities.ControlLevelReadOnly)+ }+ if ControlLevelControlled != string(agentcapabilities.ControlLevelControlled) {+ t.Fatalf("ControlLevelControlled = %q, want shared %q", ControlLevelControlled, agentcapabilities.ControlLevelControlled)+ }+ if ControlLevelAutonomous != string(agentcapabilities.ControlLevelAutonomous) {+ t.Fatalf("ControlLevelAutonomous = %q, want shared %q", ControlLevelAutonomous, agentcapabilities.ControlLevelAutonomous)+ }+ if !(&AIConfig{ControlLevel: ControlLevelControlled}).IsControlEnabled() {+ t.Fatalf("controlled config should allow control tools through the shared predicate")+ }+ if (&AIConfig{ControlLevel: "bad"}).IsControlEnabled() {+ t.Fatalf("unknown config control level should fail closed through the shared predicate")+ }+}+func TestAIConfig_IsConfigured(t *testing.T) {tests := []struct {name string@@ -100,13 +120,13 @@ func TestAIConfig_IsConfigured(t *testing.T) {expected: true,},{- name: "enabled with oauth",+ name: "enabled with legacy oauth only",config: AIConfig{Enabled: true,AuthMethod: AuthMethodOAuth,OAuthAccessToken: "oauth-token",},- expected: true,+ expected: false,},{name: "enabled but no credentials",@@ -170,13 +190,13 @@ func TestAIConfig_HasProvider(t *testing.T) {expected: true,},{- name: "anthropic with oauth",+ name: "anthropic with legacy oauth only",config: AIConfig{AuthMethod: AuthMethodOAuth,OAuthAccessToken: "token",},provider: AIProviderAnthropic,- expected: true,+ expected: false,},{name: "openai configured",@@ -430,7 +450,7 @@ func TestAIConfig_OllamaKeepAliveDefaultsAndValidation(t *testing.T) {}}-func TestAIConfig_IsUsingOAuth(t *testing.T) {+func TestAIConfig_IsUsingOAuthUnsupported(t *testing.T) {tests := []struct {name stringconfig AIConfig@@ -449,12 +469,12 @@ func TestAIConfig_IsUsingOAuth(t *testing.T) {expected: false,},{- name: "using oauth with token",+ name: "legacy oauth with token",config: AIConfig{AuthMethod: AuthMethodOAuth,OAuthAccessToken: "token",},- expected: true,+ expected: false,},}diff --git a/internal/config/ai_usage_persistence_test.go b/internal/config/ai_usage_persistence_test.goindex 7eb01feb64..6c15a5c155 100644--- a/internal/config/ai_usage_persistence_test.go+++ b/internal/config/ai_usage_persistence_test.go@@ -12,14 +12,15 @@ func TestSaveLoadAIUsageHistory(t *testing.T) {now := time.Now()events := []AIUsageEventRecord{{- Timestamp: now,- Provider: "openai",- RequestModel: "openai:gpt-4o",- InputTokens: 123,- OutputTokens: 45,- UseCase: "chat",- TargetType: "vm",- TargetID: "vm-101",+ Timestamp: now,+ Provider: "openai",+ RequestModel: "openai:gpt-4o",+ InputTokens: 123,+ OutputTokens: 45,+ UseCase: "chat",+ ToolCallCount: 2,+ TargetType: "vm",+ TargetID: "vm-101",},}@@ -38,4 +39,139 @@ func TestSaveLoadAIUsageHistory(t *testing.T) {if loaded.Events[0].Provider != "openai" || loaded.Events[0].InputTokens != 123 {t.Fatalf("loaded event mismatch: %+v", loaded.Events[0])}+ if loaded.Events[0].ToolCallCount != 2 {+ t.Fatalf("loaded tool call count = %d, want 2", loaded.Events[0].ToolCallCount)+ }+}++func TestSaveLoadExternalAgentActivityHistory(t *testing.T) {+ dir := t.TempDir()+ cp := NewConfigPersistence(dir)++ now := time.Now().UTC()+ events := []ExternalAgentActivityRecord{+ {+ Timestamp: now,+ Surface: ExternalAgentActivitySurfaceAgentAPI,+ Activity: ExternalAgentActivityFleetContext,+ },+ }++ if err := cp.SaveExternalAgentActivityHistory(events); err != nil {+ t.Fatalf("SaveExternalAgentActivityHistory: %v", err)+ }++ loaded, err := cp.LoadExternalAgentActivityHistory()+ if err != nil {+ t.Fatalf("LoadExternalAgentActivityHistory: %v", err)+ }++ if len(loaded.Events) != 1 {+ t.Fatalf("expected 1 event, got %d", len(loaded.Events))+ }+ if loaded.Events[0].Surface != ExternalAgentActivitySurfaceAgentAPI ||+ loaded.Events[0].Activity != ExternalAgentActivityFleetContext {+ t.Fatalf("loaded event mismatch: %+v", loaded.Events[0])+ }+}++func TestRecordExternalAgentActivityPrunesAndNormalizes(t *testing.T) {+ dir := t.TempDir()+ cp := NewConfigPersistence(dir)++ now := time.Now().UTC()+ if err := cp.SaveExternalAgentActivityHistory([]ExternalAgentActivityRecord{+ {+ Timestamp: now.Add(-(externalAgentActivityHistoryRetention + time.Hour)),+ Surface: ExternalAgentActivitySurfaceAgentAPI,+ Activity: ExternalAgentActivityResourceContext,+ },+ }); err != nil {+ t.Fatalf("SaveExternalAgentActivityHistory: %v", err)+ }++ if err := cp.RecordExternalAgentActivity(ExternalAgentActivityRecord{+ Timestamp: now,+ Activity: ExternalAgentActivityActionPlan,+ }); err != nil {+ t.Fatalf("RecordExternalAgentActivity: %v", err)+ }++ loaded, err := cp.LoadExternalAgentActivityHistory()+ if err != nil {+ t.Fatalf("LoadExternalAgentActivityHistory: %v", err)+ }+ if len(loaded.Events) != 1 {+ t.Fatalf("expected only recent event after prune, got %d: %+v", len(loaded.Events), loaded.Events)+ }+ if loaded.Events[0].Surface != ExternalAgentActivitySurfaceAgentAPI ||+ loaded.Events[0].Activity != ExternalAgentActivityActionPlan {+ t.Fatalf("recorded event mismatch: %+v", loaded.Events[0])+ }+}++func TestSaveLoadWorkflowPromptActivityHistory(t *testing.T) {+ dir := t.TempDir()+ cp := NewConfigPersistence(dir)++ now := time.Now().UTC()+ events := []WorkflowPromptActivityRecord{+ {+ Timestamp: now,+ Surface: WorkflowPromptActivitySurfacePulseMCP,+ PromptName: "pulse_operations_loop",+ },+ }++ if err := cp.SaveWorkflowPromptActivityHistory(events); err != nil {+ t.Fatalf("SaveWorkflowPromptActivityHistory: %v", err)+ }++ loaded, err := cp.LoadWorkflowPromptActivityHistory()+ if err != nil {+ t.Fatalf("LoadWorkflowPromptActivityHistory: %v", err)+ }++ if len(loaded.Events) != 1 {+ t.Fatalf("expected 1 event, got %d", len(loaded.Events))+ }+ if loaded.Events[0].Surface != WorkflowPromptActivitySurfacePulseMCP ||+ loaded.Events[0].PromptName != "pulse_operations_loop" {+ t.Fatalf("loaded event mismatch: %+v", loaded.Events[0])+ }+}++func TestRecordWorkflowPromptActivityPrunesAndNormalizes(t *testing.T) {+ dir := t.TempDir()+ cp := NewConfigPersistence(dir)++ now := time.Now().UTC()+ if err := cp.SaveWorkflowPromptActivityHistory([]WorkflowPromptActivityRecord{+ {+ Timestamp: now.Add(-(workflowPromptActivityHistoryRetention + time.Hour)),+ Surface: WorkflowPromptActivitySurfacePulseMCP,+ PromptName: "pulse_operations_loop",+ },+ }); err != nil {+ t.Fatalf("SaveWorkflowPromptActivityHistory: %v", err)+ }++ if err := cp.RecordWorkflowPromptActivity(WorkflowPromptActivityRecord{+ Timestamp: now,+ PromptName: " pulse_operations_loop ",+ }); err != nil {+ t.Fatalf("RecordWorkflowPromptActivity: %v", err)+ }++ loaded, err := cp.LoadWorkflowPromptActivityHistory()+ if err != nil {+ t.Fatalf("LoadWorkflowPromptActivityHistory: %v", err)+ }+ if len(loaded.Events) != 1 {+ t.Fatalf("expected only recent event after prune, got %d: %+v", len(loaded.Events), loaded.Events)+ }+ if loaded.Events[0].Surface != WorkflowPromptActivitySurfacePulseAssistant ||+ loaded.Events[0].PromptName != "pulse_operations_loop" {+ t.Fatalf("recorded event mismatch: %+v", loaded.Events[0])+ }}diff --git a/internal/config/code_standards_test.go b/internal/config/code_standards_test.goindex ab50002eda..7b16254ae7 100644--- a/internal/config/code_standards_test.go+++ b/internal/config/code_standards_test.go@@ -18,22 +18,24 @@ import (func TestNoPersistenceBoilerplate(t *testing.T) {// Methods with domain-specific logic that legitimately can't use the generics.allowedMethods := map[string]bool{- "SaveAlertConfig": true, // 400+ lines of validation- "SaveAPITokens": true, // backup + sanitize- "SaveNodesConfig": true, // wipe guard, multi-type- "SaveNodesConfigAllowEmpty": true, // wipe guard variant- "SaveSystemSettings": true, // .env file update- "SaveSSOConfig": true, // nil guard, clone, clear overrides- "SaveAppriseConfig": true, // normalize config- "SaveOrganization": true, // uses fs.WriteFile directly- "SaveEmailConfig": true, // domain-specific logging- "SaveWebhooks": true, // domain-specific logging with count- "SaveAIConfig": true, // complex AI-specific logic- "SaveAIFindings": true, // versioned envelope- "SaveAIChatSessions": true, // versioned envelope- "SaveAIChatSession": true, // delegates to SaveAIChatSessions- "SaveAIUsageHistory": true, // versioned envelope- "SavePatrolRunHistory": true, // versioned envelope+ "SaveAlertConfig": true, // 400+ lines of validation+ "SaveAPITokens": true, // backup + sanitize+ "SaveNodesConfig": true, // wipe guard, multi-type+ "SaveNodesConfigAllowEmpty": true, // wipe guard variant+ "SaveSystemSettings": true, // .env file update+ "SaveSSOConfig": true, // nil guard, clone, clear overrides+ "SaveAppriseConfig": true, // normalize config+ "SaveOrganization": true, // uses fs.WriteFile directly+ "SaveEmailConfig": true, // domain-specific logging+ "SaveWebhooks": true, // domain-specific logging with count+ "SaveAIConfig": true, // complex AI-specific logic+ "SaveAIFindings": true, // versioned envelope+ "SaveAIChatSessions": true, // versioned envelope+ "SaveAIChatSession": true, // delegates to SaveAIChatSessions+ "SaveAIUsageHistory": true, // versioned envelope+ "SaveExternalAgentActivityHistory": true, // versioned envelope+ "SaveWorkflowPromptActivityHistory": true, // versioned envelope+ "SavePatrolRunHistory": true, // versioned envelope}data, err := os.ReadFile("persistence.go")@@ -83,23 +85,25 @@ func TestNoPersistenceBoilerplate(t *testing.T) {func TestNoPersistenceLoadBoilerplate(t *testing.T) {// Methods with domain-specific logic that legitimately can't use generic loaders.allowedMethods := map[string]bool{- "LoadAlertConfig": true, // complex validation- "LoadAPITokens": true, // ensureScopes post-processing- "LoadNodesConfig": true, // multi-type- "LoadSystemSettings": true, // complex with defaults- "LoadSSOConfig": true, // nil fallback + encrypted payload handling- "LoadAppriseConfig": true, // complex with defaults- "LoadEmailConfig": true, // complex with defaults- "LoadWebhooks": true, // legacy migration- "LoadOrganization": true, // different error handling- "LoadAIConfig": true, // complex migration logic- "LoadAIFindings": true, // versioned envelope- "LoadAIChatSessions": true, // versioned envelope- "LoadAIUsageHistory": true, // versioned envelope- "LoadPatrolRunHistory": true, // versioned envelope- "LoadGuestMetadata": true, // metadata store- "LoadDockerMetadata": true, // metadata store- "LoadHostMetadata": true, // metadata store+ "LoadAlertConfig": true, // complex validation+ "LoadAPITokens": true, // ensureScopes post-processing+ "LoadNodesConfig": true, // multi-type+ "LoadSystemSettings": true, // complex with defaults+ "LoadSSOConfig": true, // nil fallback + encrypted payload handling+ "LoadAppriseConfig": true, // complex with defaults+ "LoadEmailConfig": true, // complex with defaults+ "LoadWebhooks": true, // legacy migration+ "LoadOrganization": true, // different error handling+ "LoadAIConfig": true, // complex migration logic+ "LoadAIFindings": true, // versioned envelope+ "LoadAIChatSessions": true, // versioned envelope+ "LoadAIUsageHistory": true, // versioned envelope+ "LoadExternalAgentActivityHistory": true, // versioned envelope+ "LoadWorkflowPromptActivityHistory": true, // versioned envelope+ "LoadPatrolRunHistory": true, // versioned envelope+ "LoadGuestMetadata": true, // metadata store+ "LoadDockerMetadata": true, // metadata store+ "LoadHostMetadata": true, // metadata store}data, err := os.ReadFile("persistence.go")diff --git a/internal/config/persistence.go b/internal/config/persistence.goindex be1fa23b23..761c25919f 100644--- a/internal/config/persistence.go+++ b/internal/config/persistence.go@@ -25,31 +25,33 @@ import (// ConfigPersistence handles saving and loading configurationtype ConfigPersistence struct {- mu sync.RWMutex- tx *importTransaction- configDir string- alertFile string- emailFile string- webhookFile string- appriseFile string- nodesFile string- trueNASFile string- vmwareFile string- availabilityFile string- systemFile string- ssoFile string- apiTokensFile string- aiFile string- aiFindingsFile string- aiPatrolRunsFile string- aiUsageHistoryFile string- agentProfilesFile string- agentAssignmentsFile string- aiChatSessionsFile string- orgFile string- relayFile string- crypto *crypto.CryptoManager- fs FileSystem+ mu sync.RWMutex+ tx *importTransaction+ configDir string+ alertFile string+ emailFile string+ webhookFile string+ appriseFile string+ nodesFile string+ trueNASFile string+ vmwareFile string+ availabilityFile string+ systemFile string+ ssoFile string+ apiTokensFile string+ aiFile string+ aiFindingsFile string+ aiPatrolRunsFile string+ aiUsageHistoryFile string+ externalAgentActivityFile string+ workflowPromptActivityFile string+ agentProfilesFile string+ agentAssignmentsFile string+ aiChatSessionsFile string+ orgFile string+ relayFile string+ crypto *crypto.CryptoManager+ fs FileSystem// Lazy loaded metadata storesguestMetadataStore *GuestMetadataStore@@ -102,26 +104,28 @@ type alertScheduleGroupingPresence struct {}type resolvedConfigPersistencePaths struct {- alertFile string- emailFile string- webhookFile string- appriseFile string- nodesFile string- trueNASFile string- vmwareFile string- availabilityFile string- systemFile string- ssoFile string- apiTokensFile string- aiFile string- aiFindingsFile string- aiPatrolRunsFile string- aiUsageHistoryFile string- agentProfilesFile string- agentAssignmentsFile string- aiChatSessionsFile string- orgFile string- relayFile string+ alertFile string+ emailFile string+ webhookFile string+ appriseFile string+ nodesFile string+ trueNASFile string+ vmwareFile string+ availabilityFile string+ systemFile string+ ssoFile string+ apiTokensFile string+ aiFile string+ aiFindingsFile string+ aiPatrolRunsFile string+ aiUsageHistoryFile string+ externalAgentActivityFile string+ workflowPromptActivityFile string+ agentProfilesFile string+ agentAssignmentsFile string+ aiChatSessionsFile string+ orgFile string+ relayFile string}func resolveConfigPersistencePaths(configDir string) (string, resolvedConfigPersistencePaths, error) {@@ -194,6 +198,14 @@ func resolveConfigPersistencePaths(configDir string) (string, resolvedConfigPersif err != nil {return "", resolvedConfigPersistencePaths{}, fmt.Errorf("resolve ai_usage_history.json: %w", err)}+ externalAgentActivityFile, err := resolveLeaf("external_agent_activity.json")+ if err != nil {+ return "", resolvedConfigPersistencePaths{}, fmt.Errorf("resolve external_agent_activity.json: %w", err)+ }+ workflowPromptActivityFile, err := resolveLeaf("workflow_prompt_activity.json")+ if err != nil {+ return "", resolvedConfigPersistencePaths{}, fmt.Errorf("resolve workflow_prompt_activity.json: %w", err)+ }agentProfilesFile, err := resolveLeaf("agent_profiles.json")if err != nil {return "", resolvedConfigPersistencePaths{}, fmt.Errorf("resolve agent_profiles.json: %w", err)@@ -216,26 +228,28 @@ func resolveConfigPersistencePaths(configDir string) (string, resolvedConfigPers}return normalizedConfigDir, resolvedConfigPersistencePaths{- alertFile: alertFile,- emailFile: emailFile,- webhookFile: webhookFile,- appriseFile: appriseFile,- nodesFile: nodesFile,- trueNASFile: trueNASFile,- vmwareFile: vmwareFile,- availabilityFile: availabilityFile,- systemFile: systemFile,- ssoFile: ssoFile,- apiTokensFile: apiTokensFile,- aiFile: aiFile,- aiFindingsFile: aiFindingsFile,- aiPatrolRunsFile: aiPatrolRunsFile,- aiUsageHistoryFile: aiUsageHistoryFile,- agentProfilesFile: agentProfilesFile,- agentAssignmentsFile: agentAssignmentsFile,- aiChatSessionsFile: aiChatSessionsFile,- orgFile: orgFile,- relayFile: relayFile,+ alertFile: alertFile,+ emailFile: emailFile,+ webhookFile: webhookFile,+ appriseFile: appriseFile,+ nodesFile: nodesFile,+ trueNASFile: trueNASFile,+ vmwareFile: vmwareFile,+ availabilityFile: availabilityFile,+ systemFile: systemFile,+ ssoFile: ssoFile,+ apiTokensFile: apiTokensFile,+ aiFile: aiFile,+ aiFindingsFile: aiFindingsFile,+ aiPatrolRunsFile: aiPatrolRunsFile,+ aiUsageHistoryFile: aiUsageHistoryFile,+ externalAgentActivityFile: externalAgentActivityFile,+ workflowPromptActivityFile: workflowPromptActivityFile,+ agentProfilesFile: agentProfilesFile,+ agentAssignmentsFile: agentAssignmentsFile,+ aiChatSessionsFile: aiChatSessionsFile,+ orgFile: orgFile,+ relayFile: relayFile,}, nil}@@ -266,29 +280,31 @@ func newConfigPersistence(configDir string) (*ConfigPersistence, error) {}cp := &ConfigPersistence{- configDir: resolvedConfigDir,- alertFile: resolvedPaths.alertFile,- emailFile: resolvedPaths.emailFile,- webhookFile: resolvedPaths.webhookFile,- appriseFile: resolvedPaths.appriseFile,- nodesFile: resolvedPaths.nodesFile,- trueNASFile: resolvedPaths.trueNASFile,- vmwareFile: resolvedPaths.vmwareFile,- availabilityFile: resolvedPaths.availabilityFile,- systemFile: resolvedPaths.systemFile,- ssoFile: resolvedPaths.ssoFile,- apiTokensFile: resolvedPaths.apiTokensFile,- aiFile: resolvedPaths.aiFile,- aiFindingsFile: resolvedPaths.aiFindingsFile,- aiPatrolRunsFile: resolvedPaths.aiPatrolRunsFile,- aiUsageHistoryFile: resolvedPaths.aiUsageHistoryFile,- agentProfilesFile: resolvedPaths.agentProfilesFile,- agentAssignmentsFile: resolvedPaths.agentAssignmentsFile,- aiChatSessionsFile: resolvedPaths.aiChatSessionsFile,- orgFile: resolvedPaths.orgFile,- relayFile: resolvedPaths.relayFile,- crypto: cryptoMgr,- fs: defaultFileSystem{},+ configDir: resolvedConfigDir,+ alertFile: resolvedPaths.alertFile,+ emailFile: resolvedPaths.emailFile,+ webhookFile: resolvedPaths.webhookFile,+ appriseFile: resolvedPaths.appriseFile,+ nodesFile: resolvedPaths.nodesFile,+ trueNASFile: resolvedPaths.trueNASFile,+ vmwareFile: resolvedPaths.vmwareFile,+ availabilityFile: resolvedPaths.availabilityFile,+ systemFile: resolvedPaths.systemFile,+ ssoFile: resolvedPaths.ssoFile,+ apiTokensFile: resolvedPaths.apiTokensFile,+ aiFile: resolvedPaths.aiFile,+ aiFindingsFile: resolvedPaths.aiFindingsFile,+ aiPatrolRunsFile: resolvedPaths.aiPatrolRunsFile,+ aiUsageHistoryFile: resolvedPaths.aiUsageHistoryFile,+ externalAgentActivityFile: resolvedPaths.externalAgentActivityFile,+ workflowPromptActivityFile: resolvedPaths.workflowPromptActivityFile,+ agentProfilesFile: resolvedPaths.agentProfilesFile,+ agentAssignmentsFile: resolvedPaths.agentAssignmentsFile,+ aiChatSessionsFile: resolvedPaths.aiChatSessionsFile,+ orgFile: resolvedPaths.orgFile,+ relayFile: resolvedPaths.relayFile,+ crypto: cryptoMgr,+ fs: defaultFileSystem{},}log.Debug().@@ -2795,6 +2811,8 @@ type AIUsageEventRecord struct {RequestModel string `json:"request_model"`ResponseModel string `json:"response_model,omitempty"`UseCase string `json:"use_case,omitempty"` // "chat" or "patrol"+ ContextScope string `json:"context_scope,omitempty"`+ ToolCallCount int `json:"tool_call_count,omitempty"`InputTokens int `json:"input_tokens,omitempty"`OutputTokens int `json:"output_tokens,omitempty"`TargetType string `json:"target_type,omitempty"`@@ -2802,6 +2820,171 @@ type AIUsageEventRecord struct {FindingID string `json:"finding_id,omitempty"`}+const (+ ExternalAgentActivitySurfaceAgentAPI = "agent_api"+ ExternalAgentActivitySurfacePulseMCP = "pulse_mcp"++ ExternalAgentActivityResourceContext = "resource_context"+ ExternalAgentActivityFleetContext = "fleet_context"+ ExternalAgentActivityEventStream = "event_stream"+ ExternalAgentActivityProvisioning = "provisioning"+ ExternalAgentActivityOperatorState = "operator_state"+ ExternalAgentActivityFindingList = "finding_list"+ ExternalAgentActivityFindingDecision = "finding_decision"+ ExternalAgentActivityActionPlan = "action_plan"+ ExternalAgentActivityActionDecision = "action_decision"+ ExternalAgentActivityActionExecute = "action_execute"++ maxExternalAgentActivityHistoryRecords = 500+ externalAgentActivityHistoryRetention = 90 * 24 * time.Hour++ WorkflowPromptActivitySurfacePulseAssistant = "pulse_assistant"+ WorkflowPromptActivitySurfacePulsePatrol = "pulse_patrol"+ WorkflowPromptActivitySurfacePatrolControl = "patrol_control"+ WorkflowPromptActivitySurfacePatrolAutonomy = "patrol_autonomy"+ WorkflowPromptActivitySurfaceProActivation = "pulse_pro_activation"+ WorkflowPromptActivitySurfaceAgentAPI = "agent_api"+ WorkflowPromptActivitySurfacePulseMCP = "pulse_mcp"++ maxWorkflowPromptActivityHistoryRecords = 500+ workflowPromptActivityHistoryRetention = 90 * 24 * time.Hour+)++// ExternalAgentActivityHistoryData represents persisted external-agent surface+// activity with metadata. Events intentionally carry only coarse activity+// classes; token identity, route parameters, resource IDs, prompts, findings,+// command payloads, and outputs do not belong in this telemetry source.+type ExternalAgentActivityHistoryData struct {+ Version int `json:"version"`+ LastSaved time.Time `json:"last_saved"`+ Events []ExternalAgentActivityRecord `json:"events"`+}++// ExternalAgentActivityRecord is a content-free marker that an authenticated+// external-agent-capable caller reached one of the manifest-backed agent+// surfaces.+type ExternalAgentActivityRecord struct {+ Timestamp time.Time `json:"timestamp"`+ Surface string `json:"surface"`+ Activity string `json:"activity"`+}++// WorkflowPromptActivityHistoryData represents persisted workflow-starter+// activity with metadata. Events intentionally carry only the manifest prompt+// name and coarse surface; prompt arguments, rendered text, resource IDs,+// finding IDs, user text, model output, and token identity do not belong here.+type WorkflowPromptActivityHistoryData struct {+ Version int `json:"version"`+ LastSaved time.Time `json:"last_saved"`+ Events []WorkflowPromptActivityRecord `json:"events"`+}++// WorkflowPromptActivityRecord is a content-free marker that a Pulse workflow+// starter was rendered on a first-party or external-agent surface.+type WorkflowPromptActivityRecord struct {+ Timestamp time.Time `json:"timestamp"`+ Surface string `json:"surface"`+ PromptName string `json:"prompt_name"`+}++func normalizeExternalAgentActivityRecord(record ExternalAgentActivityRecord) (ExternalAgentActivityRecord, bool) {+ if record.Timestamp.IsZero() {+ return ExternalAgentActivityRecord{}, false+ }+ record.Timestamp = record.Timestamp.UTC()+ record.Surface = strings.TrimSpace(record.Surface)+ if record.Surface == "" {+ record.Surface = ExternalAgentActivitySurfaceAgentAPI+ }+ record.Activity = strings.TrimSpace(record.Activity)+ if record.Activity == "" {+ return ExternalAgentActivityRecord{}, false+ }+ return record, true+}++func normalizeExternalAgentActivityRecords(records []ExternalAgentActivityRecord) []ExternalAgentActivityRecord {+ if records == nil {+ return make([]ExternalAgentActivityRecord, 0)+ }+ normalized := make([]ExternalAgentActivityRecord, 0, len(records))+ for _, record := range records {+ record, ok := normalizeExternalAgentActivityRecord(record)+ if !ok {+ continue+ }+ normalized = append(normalized, record)+ }+ return normalized+}++func pruneExternalAgentActivityRecords(records []ExternalAgentActivityRecord, cutoff time.Time, maxRecords int) []ExternalAgentActivityRecord {+ normalized := normalizeExternalAgentActivityRecords(records)+ if !cutoff.IsZero() {+ kept := normalized[:0]+ for _, record := range normalized {+ if record.Timestamp.Before(cutoff) {+ continue+ }+ kept = append(kept, record)+ }+ normalized = kept+ }+ if maxRecords > 0 && len(normalized) > maxRecords {+ normalized = normalized[len(normalized)-maxRecords:]+ }+ return normalized+}++func normalizeWorkflowPromptActivityRecord(record WorkflowPromptActivityRecord) (WorkflowPromptActivityRecord, bool) {+ if record.Timestamp.IsZero() {+ return WorkflowPromptActivityRecord{}, false+ }+ record.Timestamp = record.Timestamp.UTC()+ record.Surface = strings.TrimSpace(record.Surface)+ if record.Surface == "" {+ record.Surface = WorkflowPromptActivitySurfacePulseAssistant+ }+ record.PromptName = strings.TrimSpace(record.PromptName)+ if record.PromptName == "" {+ return WorkflowPromptActivityRecord{}, false+ }+ return record, true+}++func normalizeWorkflowPromptActivityRecords(records []WorkflowPromptActivityRecord) []WorkflowPromptActivityRecord {+ if records == nil {+ return make([]WorkflowPromptActivityRecord, 0)+ }+ normalized := make([]WorkflowPromptActivityRecord, 0, len(records))+ for _, record := range records {+ record, ok := normalizeWorkflowPromptActivityRecord(record)+ if !ok {+ continue+ }+ normalized = append(normalized, record)+ }+ return normalized+}++func pruneWorkflowPromptActivityRecords(records []WorkflowPromptActivityRecord, cutoff time.Time, maxRecords int) []WorkflowPromptActivityRecord {+ normalized := normalizeWorkflowPromptActivityRecords(records)+ if !cutoff.IsZero() {+ kept := normalized[:0]+ for _, record := range normalized {+ if record.Timestamp.Before(cutoff) {+ continue+ }+ kept = append(kept, record)+ }+ normalized = kept+ }+ if maxRecords > 0 && len(normalized) > maxRecords {+ normalized = normalized[len(normalized)-maxRecords:]+ }+ return normalized+}+// saveHistoryData is the save-side counterpart of loadHistoryData: it// marshals the payload, encrypts it when crypto is configured, and writes it// under the persistence lock. errLabel is the lowercase error-wrapping label@@ -2855,6 +3038,179 @@ func newEmptyAIUsageHistoryData() *AIUsageHistoryData {}}+// SaveExternalAgentActivityHistory persists external-agent activity markers to+// disk.+func (c *ConfigPersistence) SaveExternalAgentActivityHistory(events []ExternalAgentActivityRecord) error {+ normalized := normalizeExternalAgentActivityRecords(events)+ data := ExternalAgentActivityHistoryData{+ Version: 1,+ LastSaved: time.Now(),+ Events: normalized,+ }+ return saveHistoryData(c, c.externalAgentActivityFile, data, len(normalized), "external agent activity history", "External agent activity history")+}++func newEmptyExternalAgentActivityHistoryData() *ExternalAgentActivityHistoryData {+ return &ExternalAgentActivityHistoryData{+ Version: 1,+ Events: make([]ExternalAgentActivityRecord, 0),+ }+}++// SaveWorkflowPromptActivityHistory persists content-free workflow prompt+// activity markers to disk.+func (c *ConfigPersistence) SaveWorkflowPromptActivityHistory(events []WorkflowPromptActivityRecord) error {+ normalized := normalizeWorkflowPromptActivityRecords(events)+ data := WorkflowPromptActivityHistoryData{+ Version: 1,+ LastSaved: time.Now(),+ Events: normalized,+ }+ return saveHistoryData(c, c.workflowPromptActivityFile, data, len(normalized), "workflow prompt activity history", "Workflow prompt activity history")+}++func newEmptyWorkflowPromptActivityHistoryData() *WorkflowPromptActivityHistoryData {+ return &WorkflowPromptActivityHistoryData{+ Version: 1,+ Events: make([]WorkflowPromptActivityRecord, 0),+ }+}++// RecordExternalAgentActivity appends one content-free external-agent activity+// marker and prunes old records while holding the persistence lock, avoiding+// load-append-save races between concurrent agent requests.+func (c *ConfigPersistence) RecordExternalAgentActivity(record ExternalAgentActivityRecord) error {+ if c == nil {+ return nil+ }+ now := time.Now().UTC()+ if record.Timestamp.IsZero() {+ record.Timestamp = now+ }+ record, ok := normalizeExternalAgentActivityRecord(record)+ if !ok {+ return nil+ }++ c.mu.Lock()+ defer c.mu.Unlock()++ if err := c.EnsureConfigDir(); err != nil {+ return fmt.Errorf("prepare config directory for external agent activity history: %w", err)+ }++ history := newEmptyExternalAgentActivityHistoryData()+ data, err := c.fs.ReadFile(c.externalAgentActivityFile)+ if err != nil {+ if !os.IsNotExist(err) {+ return fmt.Errorf("read external agent activity history: %w", err)+ }+ } else {+ if c.crypto != nil {+ if decrypted, decErr := c.crypto.Decrypt(data); decErr == nil {+ data = decrypted+ }+ }+ if unmarshalErr := json.Unmarshal(data, history); unmarshalErr != nil {+ log.Debug().Err(unmarshalErr).Str("file", c.externalAgentActivityFile).Msg("Resetting unreadable external agent activity history")+ history = newEmptyExternalAgentActivityHistoryData()+ }+ }++ history.Events = append(history.Events, record)+ history.Events = pruneExternalAgentActivityRecords(+ history.Events,+ record.Timestamp.Add(-externalAgentActivityHistoryRetention),+ maxExternalAgentActivityHistoryRecords,+ )+ history.Version = 1+ history.LastSaved = now++ jsonData, err := json.Marshal(history)+ if err != nil {+ return fmt.Errorf("marshal external agent activity history: %w", err)+ }+ if c.crypto != nil {+ encrypted, encErr := c.crypto.Encrypt(jsonData)+ if encErr != nil {+ return fmt.Errorf("encrypt external agent activity history: %w", encErr)+ }+ jsonData = encrypted+ }+ if err := c.writeConfigFileLocked(c.externalAgentActivityFile, jsonData, 0600); err != nil {+ return fmt.Errorf("persist external agent activity history: %w", err)+ }+ return nil+}++// RecordWorkflowPromptActivity appends one content-free workflow prompt+// activity marker and prunes old records while holding the persistence lock,+// avoiding load-append-save races between concurrent Assistant and MCP+// requests.+func (c *ConfigPersistence) RecordWorkflowPromptActivity(record WorkflowPromptActivityRecord) error {+ if c == nil {+ return nil+ }+ now := time.Now().UTC()+ if record.Timestamp.IsZero() {+ record.Timestamp = now+ }+ record, ok := normalizeWorkflowPromptActivityRecord(record)+ if !ok {+ return nil+ }++ c.mu.Lock()+ defer c.mu.Unlock()++ if err := c.EnsureConfigDir(); err != nil {+ return fmt.Errorf("prepare config directory for workflow prompt activity history: %w", err)+ }++ history := newEmptyWorkflowPromptActivityHistoryData()+ data, err := c.fs.ReadFile(c.workflowPromptActivityFile)+ if err != nil {+ if !os.IsNotExist(err) {+ return fmt.Errorf("read workflow prompt activity history: %w", err)+ }+ } else {+ if c.crypto != nil {+ if decrypted, decErr := c.crypto.Decrypt(data); decErr == nil {+ data = decrypted+ }+ }+ if unmarshalErr := json.Unmarshal(data, history); unmarshalErr != nil {+ log.Debug().Err(unmarshalErr).Str("file", c.workflowPromptActivityFile).Msg("Resetting unreadable workflow prompt activity history")+ history = newEmptyWorkflowPromptActivityHistoryData()+ }+ }++ history.Events = append(history.Events, record)+ history.Events = pruneWorkflowPromptActivityRecords(+ history.Events,+ record.Timestamp.Add(-workflowPromptActivityHistoryRetention),+ maxWorkflowPromptActivityHistoryRecords,+ )+ history.Version = 1+ history.LastSaved = now++ jsonData, err := json.Marshal(history)+ if err != nil {+ return fmt.Errorf("marshal workflow prompt activity history: %w", err)+ }+ if c.crypto != nil {+ encrypted, encErr := c.crypto.Encrypt(jsonData)+ if encErr != nil {+ return fmt.Errorf("encrypt workflow prompt activity history: %w", encErr)+ }+ jsonData = encrypted+ }+ if err := c.writeConfigFileLocked(c.workflowPromptActivityFile, jsonData, 0600); err != nil {+ return fmt.Errorf("persist workflow prompt activity history: %w", err)+ }+ return nil+}+// loadHistoryData generic helper for loading history data from disk.// When crypto is non-nil, attempts to decrypt before parsing; falls back to// plaintext on decryption failure (transparent migration from unencrypted files).@@ -2944,6 +3300,64 @@ func (c *ConfigPersistence) LoadAIUsageHistory() (*AIUsageHistoryData, error) {)}+// LoadExternalAgentActivityHistory loads external-agent activity markers from+// disk.+func (c *ConfigPersistence) LoadExternalAgentActivityHistory() (*ExternalAgentActivityHistoryData, error) {+ return loadHistoryData(+ c.fs,+ &c.mu,+ c.externalAgentActivityFile,+ c.crypto,+ newEmptyExternalAgentActivityHistoryData,+ func(data *ExternalAgentActivityHistoryData) {+ data.Events = normalizeExternalAgentActivityRecords(data.Events)+ },+ func(data *ExternalAgentActivityHistoryData) error {+ jsonData, err := json.Marshal(data)+ if err != nil {+ return fmt.Errorf("marshal external agent activity history migration rewrite: %w", err)+ }+ return rewriteEncryptedJSONLocked(c, c.externalAgentActivityFile, jsonData, "external agent activity history migration rewrite")+ },+ func(data *ExternalAgentActivityHistoryData) int {+ return len(data.Events)+ },+ func(data *ExternalAgentActivityHistoryData) time.Time {+ return data.LastSaved+ },+ "External agent activity history",+ )+}++// LoadWorkflowPromptActivityHistory loads content-free workflow prompt activity+// markers from disk.+func (c *ConfigPersistence) LoadWorkflowPromptActivityHistory() (*WorkflowPromptActivityHistoryData, error) {+ return loadHistoryData(+ c.fs,+ &c.mu,+ c.workflowPromptActivityFile,+ c.crypto,+ newEmptyWorkflowPromptActivityHistoryData,+ func(data *WorkflowPromptActivityHistoryData) {+ data.Events = normalizeWorkflowPromptActivityRecords(data.Events)+ },+ func(data *WorkflowPromptActivityHistoryData) error {+ jsonData, err := json.Marshal(data)+ if err != nil {+ return fmt.Errorf("marshal workflow prompt activity history migration rewrite: %w", err)+ }+ return rewriteEncryptedJSONLocked(c, c.workflowPromptActivityFile, jsonData, "workflow prompt activity history migration rewrite")+ },+ func(data *WorkflowPromptActivityHistoryData) int {+ return len(data.Events)+ },+ func(data *WorkflowPromptActivityHistoryData) time.Time {+ return data.LastSaved+ },+ "Workflow prompt activity history",+ )+}+// SavePatrolRunHistory persists patrol run history to diskfunc (c *ConfigPersistence) SavePatrolRunHistory(runs []PatrolRunRecord) error {data := PatrolRunHistoryData{diff --git a/internal/config/persistence_ai_branches_test.go b/internal/config/persistence_ai_branches_test.goindex 8973cbe231..0d7e3e16c7 100644--- a/internal/config/persistence_ai_branches_test.go+++ b/internal/config/persistence_ai_branches_test.go@@ -221,6 +221,132 @@ func TestLoadAIUsageHistory_MigratesPlaintextFile(t *testing.T) {}}+func TestLoadExternalAgentActivityHistory_Branches(t *testing.T) {+ tempDir := t.TempDir()+ cp := NewConfigPersistence(tempDir)+ activityFile := filepath.Join(tempDir, "external_agent_activity.json")++ // 1. Not Exists+ os.Remove(activityFile)+ data, err := cp.LoadExternalAgentActivityHistory()+ assert.NoError(t, err)+ assert.NotNil(t, data)+ assert.Empty(t, data.Events)++ // 2. Unmarshal Error+ _ = os.WriteFile(activityFile, []byte("not json"), 0600)+ data, err = cp.LoadExternalAgentActivityHistory()+ assert.NoError(t, err)+ assert.Empty(t, data.Events)++ // 3. Read Error+ mfs := &mockFSError{FileSystem: defaultFileSystem{}, readError: errors.New("read error")}+ cp.SetFileSystem(mfs)+ _, err = cp.LoadExternalAgentActivityHistory()+ assert.Error(t, err)+ assert.Contains(t, err.Error(), "read error")+}++func TestLoadExternalAgentActivityHistory_MigratesPlaintextFile(t *testing.T) {+ tempDir := t.TempDir()+ cp := NewConfigPersistence(tempDir)+ activityFile := filepath.Join(tempDir, "external_agent_activity.json")++ plaintext := ExternalAgentActivityHistoryData{+ Version: 1,+ Events: []ExternalAgentActivityRecord{{+ Timestamp: time.Now().UTC(),+ Surface: ExternalAgentActivitySurfaceAgentAPI,+ Activity: ExternalAgentActivityFleetContext,+ }},+ LastSaved: time.Now().UTC(),+ }+ raw, err := json.Marshal(plaintext)+ if err != nil {+ t.Fatalf("marshal plaintext external agent activity history: %v", err)+ }+ if err := os.WriteFile(activityFile, raw, 0o600); err != nil {+ t.Fatalf("WriteFile: %v", err)+ }++ data, err := cp.LoadExternalAgentActivityHistory()+ if err != nil {+ t.Fatalf("LoadExternalAgentActivityHistory: %v", err)+ }+ assert.NotNil(t, data)++ rewritten, err := os.ReadFile(activityFile)+ if err != nil {+ t.Fatalf("ReadFile rewritten external agent activity history: %v", err)+ }+ if bytes.Equal(rewritten, raw) {+ t.Fatalf("expected plaintext external agent activity history file to be rewritten encrypted")+ }+}++func TestLoadWorkflowPromptActivityHistory_Branches(t *testing.T) {+ tempDir := t.TempDir()+ cp := NewConfigPersistence(tempDir)+ activityFile := filepath.Join(tempDir, "workflow_prompt_activity.json")++ // 1. Not Exists+ os.Remove(activityFile)+ data, err := cp.LoadWorkflowPromptActivityHistory()+ assert.NoError(t, err)+ assert.NotNil(t, data)+ assert.Empty(t, data.Events)++ // 2. Unmarshal Error+ _ = os.WriteFile(activityFile, []byte("not json"), 0600)+ data, err = cp.LoadWorkflowPromptActivityHistory()+ assert.NoError(t, err)+ assert.Empty(t, data.Events)++ // 3. Read Error+ mfs := &mockFSError{FileSystem: defaultFileSystem{}, readError: errors.New("read error")}+ cp.SetFileSystem(mfs)+ _, err = cp.LoadWorkflowPromptActivityHistory()+ assert.Error(t, err)+ assert.Contains(t, err.Error(), "read error")+}++func TestLoadWorkflowPromptActivityHistory_MigratesPlaintextFile(t *testing.T) {+ tempDir := t.TempDir()+ cp := NewConfigPersistence(tempDir)+ activityFile := filepath.Join(tempDir, "workflow_prompt_activity.json")++ plaintext := WorkflowPromptActivityHistoryData{+ Version: 1,+ Events: []WorkflowPromptActivityRecord{{+ Timestamp: time.Now().UTC(),+ Surface: WorkflowPromptActivitySurfacePulseAssistant,+ PromptName: "pulse_operations_loop",+ }},+ LastSaved: time.Now().UTC(),+ }+ raw, err := json.Marshal(plaintext)+ if err != nil {+ t.Fatalf("marshal plaintext workflow prompt activity history: %v", err)+ }+ if err := os.WriteFile(activityFile, raw, 0o600); err != nil {+ t.Fatalf("WriteFile: %v", err)+ }++ data, err := cp.LoadWorkflowPromptActivityHistory()+ if err != nil {+ t.Fatalf("LoadWorkflowPromptActivityHistory: %v", err)+ }+ assert.NotNil(t, data)++ rewritten, err := os.ReadFile(activityFile)+ if err != nil {+ t.Fatalf("ReadFile rewritten workflow prompt activity history: %v", err)+ }+ if bytes.Equal(rewritten, raw) {+ t.Fatalf("expected plaintext workflow prompt activity history file to be rewritten encrypted")+ }+}+func TestLoadPatrolRunHistory_Branches(t *testing.T) {tempDir := t.TempDir()cp := NewConfigPersistence(tempDir)diff --git a/internal/license/coverage_additional_test.go b/internal/license/coverage_additional_test.goindex 2de347f09c..a73dcb6fd0 100644--- a/internal/license/coverage_additional_test.go+++ b/internal/license/coverage_additional_test.go@@ -78,8 +78,8 @@ func TestGetFeatureDisplayNameCoversKnownFeaturesAndFallback(t *testing.T) {want string}{{feature: FeatureAIPatrol, want: "Pulse Patrol (Background Health Checks)"},- {feature: FeatureAIAlerts, want: "Alert Analysis"},- {feature: FeatureAIAutoFix, want: "Safe Remediation Workflows"},+ {feature: FeatureAIAlerts, want: "Patrol Investigates Issues"},+ {feature: FeatureAIAutoFix, want: "Patrol Handles Safe Fixes"},{feature: FeatureKubernetesAI, want: "Kubernetes AI Analysis (Compatibility)"},{feature: FeatureUpdateAlerts, want: "Update Alerts (Container/Package Updates)"},{feature: FeatureRBAC, want: "Role-Based Access Control (RBAC)"},diff --git a/internal/telemetry/pulse_intelligence_evidence.go b/internal/telemetry/pulse_intelligence_evidence.gonew file mode 100644index 0000000000..99dec04416--- /dev/null+++ b/internal/telemetry/pulse_intelligence_evidence.go@@ -0,0 +1,159 @@+package telemetry++import (+ "strings"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+)++// PulseIntelligenceAIUsageEvidence is the content-free subset of AI usage+// history used to prove Pulse Intelligence loop collaboration.+type PulseIntelligenceAIUsageEvidence struct {+ AssistantAICalls int+ AssistantContextAICalls int+ AssistantToolCalls int+ PatrolAICalls int+}++// AssistantCollaborationActive reports whether Assistant produced contextual+// or tool-backed collaboration, not merely a starter prompt render.+func (e PulseIntelligenceAIUsageEvidence) AssistantCollaborationActive() bool {+ return e.AssistantContextAICalls > 0 || e.AssistantToolCalls > 0+}++// PulseIntelligenceAIUsageEvidenceFromHistory projects AI usage history into+// the same anonymous Pulse Intelligence evidence used by telemetry and the+// agent operations-loop status endpoint.+func PulseIntelligenceAIUsageEvidenceFromHistory(history *config.AIUsageHistoryData, since time.Time) PulseIntelligenceAIUsageEvidence {+ var evidence PulseIntelligenceAIUsageEvidence+ if history == nil {+ return evidence+ }+ for _, event := range history.Events {+ if event.Timestamp.IsZero() || event.Timestamp.Before(since) {+ continue+ }+ switch strings.ToLower(strings.TrimSpace(event.UseCase)) {+ case "chat":+ evidence.AssistantAICalls+++ if PulseIntelligenceAssistantContextEvent(event) {+ evidence.AssistantContextAICalls+++ }+ if event.ToolCallCount > 0 {+ evidence.AssistantToolCalls += event.ToolCallCount+ }+ case "patrol":+ evidence.PatrolAICalls+++ }+ }+ return evidence+}++// PulseIntelligenceAssistantContextEvent reports whether a chat usage event+// carried governed context. It deliberately ignores prompt text and responses.+func PulseIntelligenceAssistantContextEvent(event config.AIUsageEventRecord) bool {+ return strings.TrimSpace(event.ContextScope) != "" ||+ strings.TrimSpace(event.TargetType) != "" ||+ strings.TrimSpace(event.TargetID) != "" ||+ strings.TrimSpace(event.FindingID) != ""+}++// PulseIntelligenceExternalAgentEvidence is the content-free subset of+// authenticated agent/MCP route activity used to prove external collaboration.+type PulseIntelligenceExternalAgentEvidence struct {+ Used bool+ MCPAdapterUsed bool+ ContextRequests int+ EventStreamRequests int+ ProvisioningRequests int+ OperatorStateRequests int+ FindingRequests int+ ActionRequests int+}++// CollaborationActive reports whether an external agent or MCP adapter used a+// manifest-published Pulse Intelligence capability in the evidence window.+func (e PulseIntelligenceExternalAgentEvidence) CollaborationActive() bool {+ return e.Used ||+ e.MCPAdapterUsed ||+ e.ContextRequests > 0 ||+ e.EventStreamRequests > 0 ||+ e.ProvisioningRequests > 0 ||+ e.OperatorStateRequests > 0 ||+ e.FindingRequests > 0 ||+ e.ActionRequests > 0+}++// CollaborationCount returns a coarse activity count for step-level rollups.+func (e PulseIntelligenceExternalAgentEvidence) CollaborationCount() int {+ count := e.ContextRequests ++ e.EventStreamRequests ++ e.ProvisioningRequests ++ e.OperatorStateRequests ++ e.FindingRequests ++ e.ActionRequests+ if count > 0 {+ return count+ }+ if e.Used || e.MCPAdapterUsed {+ return 1+ }+ return 0+}++// PulseIntelligenceExternalAgentEvidenceFromHistory projects external-agent+// activity history into anonymous collaboration evidence.+func PulseIntelligenceExternalAgentEvidenceFromHistory(history *config.ExternalAgentActivityHistoryData, since time.Time) PulseIntelligenceExternalAgentEvidence {+ var evidence PulseIntelligenceExternalAgentEvidence+ if history == nil {+ return evidence+ }+ for _, event := range history.Events {+ if event.Timestamp.IsZero() || event.Timestamp.Before(since) {+ continue+ }+ if !PulseIntelligenceExternalAgentActivitySurface(event.Surface) {+ continue+ }+ evidence.Used = true+ if strings.TrimSpace(event.Surface) == config.ExternalAgentActivitySurfacePulseMCP {+ evidence.MCPAdapterUsed = true+ }+ evidence.ApplyActivity(event.Activity)+ }+ return evidence+}++// PulseIntelligenceExternalAgentActivitySurface reports whether a persisted+// activity surface is part of the governed external-agent contract.+func PulseIntelligenceExternalAgentActivitySurface(surface string) bool {+ switch strings.TrimSpace(surface) {+ case config.ExternalAgentActivitySurfaceAgentAPI, config.ExternalAgentActivitySurfacePulseMCP:+ return true+ default:+ return false+ }+}++// ApplyActivity increments the matching content-free external-agent activity+// bucket.+func (e *PulseIntelligenceExternalAgentEvidence) ApplyActivity(activity string) {+ if e == nil {+ return+ }+ switch strings.TrimSpace(activity) {+ case config.ExternalAgentActivityResourceContext, config.ExternalAgentActivityFleetContext:+ e.ContextRequests+++ case config.ExternalAgentActivityEventStream:+ e.EventStreamRequests+++ case config.ExternalAgentActivityProvisioning:+ e.ProvisioningRequests+++ case config.ExternalAgentActivityOperatorState:+ e.OperatorStateRequests+++ case config.ExternalAgentActivityFindingList, config.ExternalAgentActivityFindingDecision:+ e.FindingRequests+++ case config.ExternalAgentActivityActionPlan, config.ExternalAgentActivityActionDecision, config.ExternalAgentActivityActionExecute:+ e.ActionRequests+++ }+}diff --git a/internal/telemetry/telemetry.go b/internal/telemetry/telemetry.goindex d581f82b39..9c99887ff7 100644--- a/internal/telemetry/telemetry.go+++ b/internal/telemetry/telemetry.go@@ -28,13 +28,23 @@// - Whether multi-tenant mode is enabled// - Whether a paid license is active// - Whether any API tokens are configured+// - Patrol, Assistant, and external-agent usage counters over the current install-ID rotation window:+// configured/active/governed-action/approved-execution/resolved-loop state,+// Patrol control completed-loop and resolved-loop proof reported through+// legacy pro_activation metric keys for cohort continuity,+// operations-loop workflow starter request counts by surface, Assistant/Patrol AI calls,+// Patrol runs/new findings/investigations/resolved findings/autofixes,+// external-agent readiness/usage, action plans, approval requests, rejected+// action decisions, approved action decisions, approved action attempts,+// and approved action successes//// # What is NOT sent//// - No IP addresses are stored server-side// - No hostnames, node names, VM names, or any infrastructure identifiers// - No Proxmox credentials, API tokens, or passwords-// - No alert content, AI prompts, or chat messages+// - No alert content, AI prompts, chat messages, command text, action output, or token values+// - No action targets, resource IDs, finding IDs, approval actors, or approval reasons// - No personally identifiable information of any kind//// # How to disable@@ -89,6 +99,12 @@ const (// installIDRotationWindow limits how long the same pseudonymous identifier// can be reused before it is rotated locally.installIDRotationWindow = 30 * 24 * time.Hour++ // PulseIntelligenceTelemetryWindow is the rolling, content-free usage+ // window used for Patrol, Assistant, and external-agent usage counters. It+ // intentionally matches the install-ID rotation window so counters cannot+ // be linked to one stable pseudonymous identifier indefinitely.+ PulseIntelligenceTelemetryWindow = installIDRotationWindow)type installIDRecord struct {@@ -149,46 +165,327 @@ type Ping struct {MultiTenant bool `json:"multi_tenant"`PaidLicense bool `json:"paid_license"`HasAPITokens bool `json:"has_api_tokens"`++ // Pulse Intelligence usage (30-day counts/booleans — no prompts, commands, outputs, resource IDs, or token values)+ PulseIntelligenceLoopConfigured bool `json:"pulse_intelligence_loop_configured"`+ PulseIntelligenceLoopActive30d bool `json:"pulse_intelligence_loop_active_30d"`+ PulseIntelligenceCompleteOperationsLoop30d bool `json:"pulse_intelligence_complete_operations_loop_30d"`+ PulseIntelligenceApprovedExecutionLoop30d bool `json:"pulse_intelligence_approved_execution_loop_30d"`+ PulseIntelligenceResolvedOperationsLoop30d bool `json:"pulse_intelligence_resolved_operations_loop_30d"`+ PulseIntelligencePatrolControlCompletedOperationsLoop30d bool `json:"pulse_intelligence_patrol_control_completed_operations_loop_30d"`+ PulseIntelligencePatrolControlResolvedOperationsLoop30d bool `json:"pulse_intelligence_patrol_control_resolved_operations_loop_30d"`+ PulseIntelligencePatrolControlPaidCompletedOperationsLoop30d bool `json:"pulse_intelligence_patrol_control_paid_completed_operations_loop_30d"`+ PulseIntelligencePatrolControlPaidResolvedOperationsLoop30d bool `json:"pulse_intelligence_patrol_control_paid_resolved_operations_loop_30d"`+ PulseIntelligenceProActivationCompletedOperationsLoop30d bool `json:"pulse_intelligence_pro_activation_completed_operations_loop_30d"`+ PulseIntelligenceProActivationResolvedOperationsLoop30d bool `json:"pulse_intelligence_pro_activation_resolved_operations_loop_30d"`+ PulseIntelligenceProActivationPaidCompletedOperationsLoop30d bool `json:"pulse_intelligence_pro_activation_paid_completed_operations_loop_30d"`+ PulseIntelligenceProActivationPaidResolvedOperationsLoop30d bool `json:"pulse_intelligence_pro_activation_paid_resolved_operations_loop_30d"`+ PulseIntelligenceGovernedActionActive30d bool `json:"pulse_intelligence_governed_action_active_30d"`+ PulseIntelligenceAssistantOperationsLoop30d bool `json:"pulse_intelligence_assistant_operations_loop_30d"`+ PulseIntelligenceAssistantApprovedExecutionLoop30d bool `json:"pulse_intelligence_assistant_approved_execution_loop_30d"`+ PulseIntelligenceAssistantApprovedActionSuccessLoop30d bool `json:"pulse_intelligence_assistant_approved_action_success_loop_30d"`+ PulseIntelligenceAssistantResolvedOperationsLoop30d bool `json:"pulse_intelligence_assistant_resolved_operations_loop_30d"`+ PulseIntelligenceExternalAgentOperationsLoop30d bool `json:"pulse_intelligence_external_agent_operations_loop_30d"`+ PulseIntelligenceExternalAgentApprovedExecutionLoop30d bool `json:"pulse_intelligence_external_agent_approved_execution_loop_30d"`+ PulseIntelligenceExternalAgentApprovedActionSuccessLoop30d bool `json:"pulse_intelligence_external_agent_approved_action_success_loop_30d"`+ PulseIntelligenceExternalAgentResolvedOperationsLoop30d bool `json:"pulse_intelligence_external_agent_resolved_operations_loop_30d"`+ PulseIntelligenceMCPAdapterOperationsLoop30d bool `json:"pulse_intelligence_mcp_adapter_operations_loop_30d"`+ PulseIntelligenceMCPAdapterApprovedExecutionLoop30d bool `json:"pulse_intelligence_mcp_adapter_approved_execution_loop_30d"`+ PulseIntelligenceMCPAdapterApprovedActionSuccessLoop30d bool `json:"pulse_intelligence_mcp_adapter_approved_action_success_loop_30d"`+ PulseIntelligenceMCPAdapterResolvedOperationsLoop30d bool `json:"pulse_intelligence_mcp_adapter_resolved_operations_loop_30d"`+ PulseIntelligenceOperationsLoopStarterRequests30d int `json:"pulse_intelligence_operations_loop_starter_requests_30d"`+ PulseIntelligenceAssistantOperationsLoopStarterRequests30d int `json:"pulse_intelligence_assistant_operations_loop_starter_requests_30d"`+ PulseIntelligencePatrolOperationsLoopStarterRequests30d int `json:"pulse_intelligence_patrol_operations_loop_starter_requests_30d"`+ PulseIntelligencePatrolControlOperationsLoopStarterRequests30d int `json:"pulse_intelligence_patrol_control_operations_loop_starter_requests_30d"`+ PulseIntelligenceProActivationOperationsLoopStarterRequests30d int `json:"pulse_intelligence_pro_activation_operations_loop_starter_requests_30d"`+ PulseIntelligenceMCPOperationsLoopStarterRequests30d int `json:"pulse_intelligence_mcp_operations_loop_starter_requests_30d"`+ PulseIntelligenceAssistantAICalls30d int `json:"pulse_intelligence_assistant_ai_calls_30d"`+ PulseIntelligenceAssistantContextAICalls30d int `json:"pulse_intelligence_assistant_context_ai_calls_30d"`+ PulseIntelligenceAssistantToolCalls30d int `json:"pulse_intelligence_assistant_tool_calls_30d"`+ PulseIntelligencePatrolAICalls30d int `json:"pulse_intelligence_patrol_ai_calls_30d"`+ PulseIntelligencePatrolRuns30d int `json:"pulse_intelligence_patrol_runs_30d"`+ PulseIntelligencePatrolNewFindings30d int `json:"pulse_intelligence_patrol_new_findings_30d"`+ PulseIntelligencePatrolInvestigations30d int `json:"pulse_intelligence_patrol_investigations_30d"`+ PulseIntelligencePatrolResolvedFindings30d int `json:"pulse_intelligence_patrol_resolved_findings_30d"`+ PulseIntelligencePatrolAutofixes30d int `json:"pulse_intelligence_patrol_autofixes_30d"`+ PulseIntelligenceExternalAgentEnabled bool `json:"pulse_intelligence_external_agent_enabled"`+ PulseIntelligenceExternalAgentUsed30d bool `json:"pulse_intelligence_external_agent_used_30d"`+ PulseIntelligenceMCPAdapterUsed30d bool `json:"pulse_intelligence_mcp_adapter_used_30d"`+ PulseIntelligenceExternalAgentContextRequests30d int `json:"pulse_intelligence_external_agent_context_requests_30d"`+ PulseIntelligenceExternalAgentEventStreamRequests30d int `json:"pulse_intelligence_external_agent_event_stream_requests_30d"`+ PulseIntelligenceExternalAgentProvisioningRequests30d int `json:"pulse_intelligence_external_agent_provisioning_requests_30d"`+ PulseIntelligenceExternalAgentOperatorStateRequests30d int `json:"pulse_intelligence_external_agent_operator_state_requests_30d"`+ PulseIntelligenceExternalAgentFindingRequests30d int `json:"pulse_intelligence_external_agent_finding_requests_30d"`+ PulseIntelligenceExternalAgentActionRequests30d int `json:"pulse_intelligence_external_agent_action_requests_30d"`+ PulseIntelligenceActionPlans30d int `json:"pulse_intelligence_action_plans_30d"`+ PulseIntelligenceApprovalRequests30d int `json:"pulse_intelligence_approval_requests_30d"`+ PulseIntelligenceRejectedActionDecisions30d int `json:"pulse_intelligence_rejected_action_decisions_30d"`+ PulseIntelligenceApprovedActionDecisions30d int `json:"pulse_intelligence_approved_action_decisions_30d"`+ PulseIntelligenceApprovedActionAttempts30d int `json:"pulse_intelligence_approved_action_attempts_30d"`+ PulseIntelligenceApprovedActionSuccesses30d int `json:"pulse_intelligence_approved_action_successes_30d"`}// Snapshot holds the dynamic state gathered at ping time.// The telemetry package calls a user-provided SnapshotFunc to populate this,// keeping the package decoupled from monitor/config internals.type Snapshot struct {- PVENodes int- PBSInstances int- PMGInstances int- VMs int- Containers int- AgentHosts int- DockerHosts int- DockerContainers int- KubernetesClusters int- KubernetesNodes int- KubernetesPods int- KubernetesDeployments int- StoragePools int- PhysicalDisks int- CephClusters int- NetworkShares int- TrueNASSystems int- TrueNASVMs int- TrueNASApps int- VMwareHosts int- VMwareVMs int- VMwareDatastores int- AvailabilityTargets int- AIEnabled bool- PatrolEnabled bool- DiscoveryEnabled bool- NotificationsEnabled bool- AIActionsEnabled bool- ActiveAlerts int- RelayEnabled bool- SSOEnabled bool- MultiTenant bool- PaidLicense bool- HasAPITokens bool+ PVENodes int+ PBSInstances int+ PMGInstances int+ VMs int+ Containers int+ AgentHosts int+ DockerHosts int+ DockerContainers int+ KubernetesClusters int+ KubernetesNodes int+ KubernetesPods int+ KubernetesDeployments int+ StoragePools int+ PhysicalDisks int+ CephClusters int+ NetworkShares int+ TrueNASSystems int+ TrueNASVMs int+ TrueNASApps int+ VMwareHosts int+ VMwareVMs int+ VMwareDatastores int+ AvailabilityTargets int+ AIEnabled bool+ PatrolEnabled bool+ DiscoveryEnabled bool+ NotificationsEnabled bool+ AIActionsEnabled bool+ ActiveAlerts int+ RelayEnabled bool+ SSOEnabled bool+ MultiTenant bool+ PaidLicense bool+ HasAPITokens bool+ PulseIntelligenceLoopConfigured bool+ PulseIntelligenceLoopActive30d bool+ PulseIntelligenceCompleteOperationsLoop30d bool+ PulseIntelligenceApprovedExecutionLoop30d bool+ PulseIntelligenceResolvedOperationsLoop30d bool+ PulseIntelligencePatrolControlCompletedOperationsLoop30d bool+ PulseIntelligencePatrolControlResolvedOperationsLoop30d bool+ PulseIntelligencePatrolControlPaidCompletedOperationsLoop30d bool+ PulseIntelligencePatrolControlPaidResolvedOperationsLoop30d bool+ PulseIntelligenceProActivationCompletedOperationsLoop30d bool+ PulseIntelligenceProActivationResolvedOperationsLoop30d bool+ PulseIntelligenceProActivationPaidCompletedOperationsLoop30d bool+ PulseIntelligenceProActivationPaidResolvedOperationsLoop30d bool+ PulseIntelligenceGovernedActionActive30d bool+ PulseIntelligenceAssistantOperationsLoop30d bool+ PulseIntelligenceAssistantApprovedExecutionLoop30d bool+ PulseIntelligenceAssistantApprovedActionSuccessLoop30d bool+ PulseIntelligenceAssistantResolvedOperationsLoop30d bool+ PulseIntelligenceExternalAgentOperationsLoop30d bool+ PulseIntelligenceExternalAgentApprovedExecutionLoop30d bool+ PulseIntelligenceExternalAgentApprovedActionSuccessLoop30d bool+ PulseIntelligenceExternalAgentResolvedOperationsLoop30d bool+ PulseIntelligenceMCPAdapterOperationsLoop30d bool+ PulseIntelligenceMCPAdapterApprovedExecutionLoop30d bool+ PulseIntelligenceMCPAdapterApprovedActionSuccessLoop30d bool+ PulseIntelligenceMCPAdapterResolvedOperationsLoop30d bool+ PulseIntelligenceOperationsLoopStarterRequests30d int+ PulseIntelligenceAssistantOperationsLoopStarterRequests30d int+ PulseIntelligencePatrolOperationsLoopStarterRequests30d int+ PulseIntelligencePatrolControlOperationsLoopStarterRequests30d int+ PulseIntelligenceProActivationOperationsLoopStarterRequests30d int+ PulseIntelligenceMCPOperationsLoopStarterRequests30d int+ PulseIntelligenceAssistantAICalls30d int+ PulseIntelligenceAssistantContextAICalls30d int+ PulseIntelligenceAssistantToolCalls30d int+ PulseIntelligencePatrolAICalls30d int+ PulseIntelligencePatrolRuns30d int+ PulseIntelligencePatrolNewFindings30d int+ PulseIntelligencePatrolInvestigations30d int+ PulseIntelligencePatrolResolvedFindings30d int+ PulseIntelligencePatrolAutofixes30d int+ PulseIntelligenceExternalAgentEnabled bool+ PulseIntelligenceExternalAgentOperationsLoopReady bool+ PulseIntelligenceExternalAgentUsed30d bool+ PulseIntelligenceMCPAdapterUsed30d bool+ PulseIntelligenceExternalAgentContextRequests30d int+ PulseIntelligenceExternalAgentEventStreamRequests30d int+ PulseIntelligenceExternalAgentProvisioningRequests30d int+ PulseIntelligenceExternalAgentOperatorStateRequests30d int+ PulseIntelligenceExternalAgentFindingRequests30d int+ PulseIntelligenceExternalAgentActionRequests30d int+ PulseIntelligenceActionPlans30d int+ PulseIntelligenceApprovalRequests30d int+ PulseIntelligenceRejectedActionDecisions30d int+ PulseIntelligenceApprovedActionDecisions30d int+ PulseIntelligenceApprovedActionAttempts30d int+ PulseIntelligenceApprovedActionSuccesses30d int+}++// PulseIntelligenceActionSnapshot is the action-governance portion of the+// Pulse Intelligence telemetry loop. It is intentionally count-only so callers+// can aggregate local audit records without exporting action details.+type PulseIntelligenceActionSnapshot struct {+ ActionPlans30d int+ ApprovalRequests30d int+ RejectedActionDecisions30d int+ ApprovedActionDecisions30d int+ ApprovedActionAttempts30d int+ ApprovedActionSuccesses30d int+}++const (+ PulseIntelligenceProActivationValueProofNotStarted = "not_started"+ PulseIntelligenceProActivationValueProofInProgress = "in_progress"+ PulseIntelligenceProActivationValueProofGovernedDecisionRecorded = "governed_decision_recorded"+ // PulseIntelligenceProActivationValueProofVerifiedNeedsExternalMCP remains a+ // tolerated legacy value for API consumers, but MCP readiness is no longer a+ // required Patrol control value gate.+ PulseIntelligenceProActivationValueProofVerifiedNeedsExternalMCP = "verified_needs_mcp"+ PulseIntelligenceProActivationValueProofVerified = "verified"+)++// PulseIntelligencePatrolControlProofInput is the count-only evidence needed+// to classify whether the first-party Patrol control loop reached governed+// operations value.+type PulseIntelligencePatrolControlProofInput struct {+ PatrolControlStarterCount int+ PatrolIssueEvidenceCount int+ ContextualCollaborationCount int+ ApprovedDecisionCount int+ RejectedDecisionCount int+ VerifiedOutcomeCount int+ // ExternalAgentReady is retained for callers that also report optional MCP+ // readiness; it is not part of the Patrol control value classifier.+ ExternalAgentReady bool+}++// PulseIntelligencePatrolControlProof is the shared classification used by+// the native status endpoint and anonymous outbound telemetry.+type PulseIntelligencePatrolControlProof struct {+ Completed bool+ Resolved bool+ ValueProofState string+}++// PulseIntelligencePatrolAutonomyProofInput is the legacy count-only evidence+// shape for the same Patrol control value proof. Keep this type stable for+// existing callers and persisted event surfaces.+type PulseIntelligencePatrolAutonomyProofInput struct {+ PatrolAutonomyStarterCount int+ PatrolIssueEvidenceCount int+ ContextualCollaborationCount int+ ApprovedDecisionCount int+ RejectedDecisionCount int+ VerifiedOutcomeCount int+ // ExternalAgentReady is retained for callers that also report optional MCP+ // readiness; it is not part of the Patrol control value classifier.+ ExternalAgentReady bool+}++// PulseIntelligencePatrolAutonomyProof is the legacy name for+// PulseIntelligencePatrolControlProof.+type PulseIntelligencePatrolAutonomyProof = PulseIntelligencePatrolControlProof++// PulseIntelligenceProActivationProofInput is the legacy metric/storage shape+// for the same Patrol control value proof. Keep this type stable for existing+// telemetry callers and persisted event surfaces.+type PulseIntelligenceProActivationProofInput struct {+ ProActivationStarterCount int+ PatrolIssueEvidenceCount int+ ContextualCollaborationCount int+ ApprovedDecisionCount int+ RejectedDecisionCount int+ VerifiedOutcomeCount int+ // ExternalAgentReady is retained for callers that also report optional MCP+ // readiness; it is not part of the Patrol control value classifier.+ ExternalAgentReady bool+}++// PulseIntelligenceProActivationProof is the legacy name for+// PulseIntelligencePatrolControlProof.+type PulseIntelligenceProActivationProof = PulseIntelligencePatrolControlProof++// ClassifyPulseIntelligencePatrolControlProof classifies the Patrol control+// loop from counters only. It intentionally mirrors the product proof contract:+// a completed loop can end in an approved verified outcome or a rejected+// governed decision, while resolved value requires approved verification.+func ClassifyPulseIntelligencePatrolControlProof(input PulseIntelligencePatrolControlProofInput) PulseIntelligencePatrolControlProof {+ return classifyPulseIntelligenceOperationsValueProof(+ input.PatrolControlStarterCount,+ input.PatrolIssueEvidenceCount,+ input.ContextualCollaborationCount,+ input.ApprovedDecisionCount,+ input.RejectedDecisionCount,+ input.VerifiedOutcomeCount,+ )+}++// ClassifyPulseIntelligencePatrolAutonomyProof classifies the legacy Patrol+// autonomy proof shape. New callers should use+// ClassifyPulseIntelligencePatrolControlProof.+func ClassifyPulseIntelligencePatrolAutonomyProof(input PulseIntelligencePatrolAutonomyProofInput) PulseIntelligencePatrolAutonomyProof {+ proof := ClassifyPulseIntelligencePatrolControlProof(PulseIntelligencePatrolControlProofInput{+ PatrolControlStarterCount: input.PatrolAutonomyStarterCount,+ PatrolIssueEvidenceCount: input.PatrolIssueEvidenceCount,+ ContextualCollaborationCount: input.ContextualCollaborationCount,+ ApprovedDecisionCount: input.ApprovedDecisionCount,+ RejectedDecisionCount: input.RejectedDecisionCount,+ VerifiedOutcomeCount: input.VerifiedOutcomeCount,+ ExternalAgentReady: input.ExternalAgentReady,+ })+ return PulseIntelligencePatrolAutonomyProof(proof)+}++// ClassifyPulseIntelligenceProActivationProof classifies the legacy Pro+// activation proof shape. New callers should use+// ClassifyPulseIntelligencePatrolControlProof.+func ClassifyPulseIntelligenceProActivationProof(input PulseIntelligenceProActivationProofInput) PulseIntelligenceProActivationProof {+ proof := ClassifyPulseIntelligencePatrolControlProof(PulseIntelligencePatrolControlProofInput{+ PatrolControlStarterCount: input.ProActivationStarterCount,+ PatrolIssueEvidenceCount: input.PatrolIssueEvidenceCount,+ ContextualCollaborationCount: input.ContextualCollaborationCount,+ ApprovedDecisionCount: input.ApprovedDecisionCount,+ RejectedDecisionCount: input.RejectedDecisionCount,+ VerifiedOutcomeCount: input.VerifiedOutcomeCount,+ ExternalAgentReady: input.ExternalAgentReady,+ })+ return PulseIntelligenceProActivationProof(proof)+}++func classifyPulseIntelligenceOperationsValueProof(starterCount int, patrolIssueEvidenceCount int, contextualCollaborationCount int, approvedDecisionCount int, rejectedDecisionCount int, verifiedOutcomeCount int) PulseIntelligencePatrolControlProof {+ starterActive := starterCount > 0+ patrolIssueEvidenceActive := patrolIssueEvidenceCount > 0+ contextualCollaborationActive := contextualCollaborationCount > 0+ approvedVerifiedOutcomeActive := approvedDecisionCount > 0 && verifiedOutcomeCount > 0+ rejectedDecisionWithoutApproval := rejectedDecisionCount > 0 && approvedDecisionCount == 0++ resolved := starterActive &&+ patrolIssueEvidenceActive &&+ contextualCollaborationActive &&+ approvedVerifiedOutcomeActive+ completed := starterActive &&+ patrolIssueEvidenceActive &&+ contextualCollaborationActive &&+ (rejectedDecisionCount > 0 || approvedVerifiedOutcomeActive)++ valueProofState := PulseIntelligenceProActivationValueProofInProgress+ switch {+ case !starterActive:+ valueProofState = PulseIntelligenceProActivationValueProofNotStarted+ case resolved:+ valueProofState = PulseIntelligenceProActivationValueProofVerified+ case rejectedDecisionWithoutApproval:+ valueProofState = PulseIntelligenceProActivationValueProofGovernedDecisionRecorded+ case completed:+ valueProofState = PulseIntelligenceProActivationValueProofGovernedDecisionRecorded+ }++ return PulseIntelligencePatrolControlProof{+ Completed: completed,+ Resolved: resolved,+ ValueProofState: valueProofState,+ }}// SnapshotFunc returns the current state snapshot for telemetry.@@ -247,7 +544,7 @@ func Start(ctx context.Context, cfg Config) {log.Info().Str("platform", base.Platform).- Msg("Anonymous outbound telemetry enabled — sends a rotating install ID, version identity, platform, OS/arch, resource counts, and feature flags (nothing else)")+ Msg("Anonymous outbound telemetry enabled — sends a rotating install ID, version identity, platform, OS/arch, resource counts, feature flags, and coarse Patrol, Assistant, and external-agent usage counters (nothing else)")r.wg.Add(1)go func() {@@ -394,6 +691,62 @@ func applySnapshot(base Ping, fn SnapshotFunc) Ping {ping.MultiTenant = s.MultiTenantping.PaidLicense = s.PaidLicenseping.HasAPITokens = s.HasAPITokens+ ping.PulseIntelligenceLoopConfigured = s.PulseIntelligenceLoopConfigured+ ping.PulseIntelligenceLoopActive30d = s.PulseIntelligenceLoopActive30d+ ping.PulseIntelligenceCompleteOperationsLoop30d = s.PulseIntelligenceCompleteOperationsLoop30d+ ping.PulseIntelligenceApprovedExecutionLoop30d = s.PulseIntelligenceApprovedExecutionLoop30d+ ping.PulseIntelligenceResolvedOperationsLoop30d = s.PulseIntelligenceResolvedOperationsLoop30d+ ping.PulseIntelligencePatrolControlCompletedOperationsLoop30d = s.PulseIntelligencePatrolControlCompletedOperationsLoop30d+ ping.PulseIntelligencePatrolControlResolvedOperationsLoop30d = s.PulseIntelligencePatrolControlResolvedOperationsLoop30d+ ping.PulseIntelligencePatrolControlPaidCompletedOperationsLoop30d = s.PulseIntelligencePatrolControlPaidCompletedOperationsLoop30d+ ping.PulseIntelligencePatrolControlPaidResolvedOperationsLoop30d = s.PulseIntelligencePatrolControlPaidResolvedOperationsLoop30d+ ping.PulseIntelligenceProActivationCompletedOperationsLoop30d = s.PulseIntelligenceProActivationCompletedOperationsLoop30d+ ping.PulseIntelligenceProActivationResolvedOperationsLoop30d = s.PulseIntelligenceProActivationResolvedOperationsLoop30d+ ping.PulseIntelligenceProActivationPaidCompletedOperationsLoop30d = s.PulseIntelligenceProActivationPaidCompletedOperationsLoop30d+ ping.PulseIntelligenceProActivationPaidResolvedOperationsLoop30d = s.PulseIntelligenceProActivationPaidResolvedOperationsLoop30d+ ping.PulseIntelligenceGovernedActionActive30d = s.PulseIntelligenceGovernedActionActive30d+ ping.PulseIntelligenceAssistantOperationsLoop30d = s.PulseIntelligenceAssistantOperationsLoop30d+ ping.PulseIntelligenceAssistantApprovedExecutionLoop30d = s.PulseIntelligenceAssistantApprovedExecutionLoop30d+ ping.PulseIntelligenceAssistantApprovedActionSuccessLoop30d = s.PulseIntelligenceAssistantApprovedActionSuccessLoop30d+ ping.PulseIntelligenceAssistantResolvedOperationsLoop30d = s.PulseIntelligenceAssistantResolvedOperationsLoop30d+ ping.PulseIntelligenceExternalAgentOperationsLoop30d = s.PulseIntelligenceExternalAgentOperationsLoop30d+ ping.PulseIntelligenceExternalAgentApprovedExecutionLoop30d = s.PulseIntelligenceExternalAgentApprovedExecutionLoop30d+ ping.PulseIntelligenceExternalAgentApprovedActionSuccessLoop30d = s.PulseIntelligenceExternalAgentApprovedActionSuccessLoop30d+ ping.PulseIntelligenceExternalAgentResolvedOperationsLoop30d = s.PulseIntelligenceExternalAgentResolvedOperationsLoop30d+ ping.PulseIntelligenceMCPAdapterOperationsLoop30d = s.PulseIntelligenceMCPAdapterOperationsLoop30d+ ping.PulseIntelligenceMCPAdapterApprovedExecutionLoop30d = s.PulseIntelligenceMCPAdapterApprovedExecutionLoop30d+ ping.PulseIntelligenceMCPAdapterApprovedActionSuccessLoop30d = s.PulseIntelligenceMCPAdapterApprovedActionSuccessLoop30d+ ping.PulseIntelligenceMCPAdapterResolvedOperationsLoop30d = s.PulseIntelligenceMCPAdapterResolvedOperationsLoop30d+ ping.PulseIntelligenceOperationsLoopStarterRequests30d = s.PulseIntelligenceOperationsLoopStarterRequests30d+ ping.PulseIntelligenceAssistantOperationsLoopStarterRequests30d = s.PulseIntelligenceAssistantOperationsLoopStarterRequests30d+ ping.PulseIntelligencePatrolOperationsLoopStarterRequests30d = s.PulseIntelligencePatrolOperationsLoopStarterRequests30d+ ping.PulseIntelligencePatrolControlOperationsLoopStarterRequests30d = s.PulseIntelligencePatrolControlOperationsLoopStarterRequests30d+ ping.PulseIntelligenceProActivationOperationsLoopStarterRequests30d = s.PulseIntelligenceProActivationOperationsLoopStarterRequests30d+ ping.PulseIntelligenceMCPOperationsLoopStarterRequests30d = s.PulseIntelligenceMCPOperationsLoopStarterRequests30d+ ping.PulseIntelligenceAssistantAICalls30d = s.PulseIntelligenceAssistantAICalls30d+ ping.PulseIntelligenceAssistantContextAICalls30d = s.PulseIntelligenceAssistantContextAICalls30d+ ping.PulseIntelligenceAssistantToolCalls30d = s.PulseIntelligenceAssistantToolCalls30d+ ping.PulseIntelligencePatrolAICalls30d = s.PulseIntelligencePatrolAICalls30d+ ping.PulseIntelligencePatrolRuns30d = s.PulseIntelligencePatrolRuns30d+ ping.PulseIntelligencePatrolNewFindings30d = s.PulseIntelligencePatrolNewFindings30d+ ping.PulseIntelligencePatrolInvestigations30d = s.PulseIntelligencePatrolInvestigations30d+ ping.PulseIntelligencePatrolResolvedFindings30d = s.PulseIntelligencePatrolResolvedFindings30d+ ping.PulseIntelligencePatrolAutofixes30d = s.PulseIntelligencePatrolAutofixes30d+ ping.PulseIntelligenceExternalAgentEnabled = s.PulseIntelligenceExternalAgentEnabled+ ping.PulseIntelligenceExternalAgentUsed30d = s.PulseIntelligenceExternalAgentUsed30d+ ping.PulseIntelligenceMCPAdapterUsed30d = s.PulseIntelligenceMCPAdapterUsed30d+ ping.PulseIntelligenceExternalAgentContextRequests30d = s.PulseIntelligenceExternalAgentContextRequests30d+ ping.PulseIntelligenceExternalAgentEventStreamRequests30d = s.PulseIntelligenceExternalAgentEventStreamRequests30d+ ping.PulseIntelligenceExternalAgentProvisioningRequests30d = s.PulseIntelligenceExternalAgentProvisioningRequests30d+ ping.PulseIntelligenceExternalAgentOperatorStateRequests30d = s.PulseIntelligenceExternalAgentOperatorStateRequests30d+ ping.PulseIntelligenceExternalAgentFindingRequests30d = s.PulseIntelligenceExternalAgentFindingRequests30d+ ping.PulseIntelligenceExternalAgentActionRequests30d = s.PulseIntelligenceExternalAgentActionRequests30d+ ping.PulseIntelligenceActionPlans30d = s.PulseIntelligenceActionPlans30d+ ping.PulseIntelligenceApprovalRequests30d = s.PulseIntelligenceApprovalRequests30d+ ping.PulseIntelligenceRejectedActionDecisions30d = s.PulseIntelligenceRejectedActionDecisions30d+ ping.PulseIntelligenceApprovedActionDecisions30d = s.PulseIntelligenceApprovedActionDecisions30d+ ping.PulseIntelligenceApprovedActionAttempts30d = s.PulseIntelligenceApprovedActionAttempts30d+ ping.PulseIntelligenceApprovedActionSuccesses30d = s.PulseIntelligenceApprovedActionSuccesses30dreturn ping}diff --git a/internal/telemetry/telemetry_test.go b/internal/telemetry/telemetry_test.goindex a37ed8fd2e..98486252a0 100644--- a/internal/telemetry/telemetry_test.go+++ b/internal/telemetry/telemetry_test.go@@ -7,6 +7,8 @@ import ("net/http/httptest""os""path/filepath"+ "reflect"+ "strings""sync/atomic""testing""time"@@ -143,6 +145,181 @@ func TestIsEnabled(t *testing.T) {}}+func TestClassifyPulseIntelligenceProActivationProof(t *testing.T) {+ tests := []struct {+ name string+ input PulseIntelligenceProActivationProofInput+ want PulseIntelligenceProActivationProof+ }{+ {+ name: "not started",+ want: PulseIntelligenceProActivationProof{+ ValueProofState: PulseIntelligenceProActivationValueProofNotStarted,+ },+ },+ {+ name: "starter only stays in progress",+ input: PulseIntelligenceProActivationProofInput{+ ProActivationStarterCount: 1,+ },+ want: PulseIntelligenceProActivationProof{+ ValueProofState: PulseIntelligenceProActivationValueProofInProgress,+ },+ },+ {+ name: "approved verified outcome resolves without external agent readiness",+ input: PulseIntelligenceProActivationProofInput{+ ProActivationStarterCount: 1,+ PatrolIssueEvidenceCount: 1,+ ContextualCollaborationCount: 1,+ ApprovedDecisionCount: 1,+ VerifiedOutcomeCount: 1,+ },+ want: PulseIntelligenceProActivationProof{+ Completed: true,+ Resolved: true,+ ValueProofState: PulseIntelligenceProActivationValueProofVerified,+ },+ },+ {+ name: "rejected governed decision records proof state before full completion",+ input: PulseIntelligenceProActivationProofInput{+ ProActivationStarterCount: 1,+ RejectedDecisionCount: 1,+ },+ want: PulseIntelligenceProActivationProof{+ ValueProofState: PulseIntelligenceProActivationValueProofGovernedDecisionRecorded,+ },+ },+ {+ name: "rejected governed decision completes without resolving",+ input: PulseIntelligenceProActivationProofInput{+ ProActivationStarterCount: 1,+ PatrolIssueEvidenceCount: 1,+ ContextualCollaborationCount: 1,+ RejectedDecisionCount: 1,+ },+ want: PulseIntelligenceProActivationProof{+ Completed: true,+ ValueProofState: PulseIntelligenceProActivationValueProofGovernedDecisionRecorded,+ },+ },+ {+ name: "approved verified outcome resolves",+ input: PulseIntelligenceProActivationProofInput{+ ProActivationStarterCount: 1,+ PatrolIssueEvidenceCount: 1,+ ContextualCollaborationCount: 1,+ ApprovedDecisionCount: 1,+ VerifiedOutcomeCount: 1,+ ExternalAgentReady: true,+ },+ want: PulseIntelligenceProActivationProof{+ Completed: true,+ Resolved: true,+ ValueProofState: PulseIntelligenceProActivationValueProofVerified,+ },+ },+ {+ name: "approved decision without verified outcome stays in progress",+ input: PulseIntelligenceProActivationProofInput{+ ProActivationStarterCount: 1,+ PatrolIssueEvidenceCount: 1,+ ContextualCollaborationCount: 1,+ ApprovedDecisionCount: 1,+ ExternalAgentReady: true,+ },+ want: PulseIntelligenceProActivationProof{+ ValueProofState: PulseIntelligenceProActivationValueProofInProgress,+ },+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := ClassifyPulseIntelligenceProActivationProof(tt.input); got != tt.want {+ t.Fatalf("ClassifyPulseIntelligenceProActivationProof() = %#v, want %#v", got, tt.want)+ }+ })+ }+}++func TestClassifyPulseIntelligencePatrolControlProof(t *testing.T) {+ tests := []struct {+ name string+ input PulseIntelligencePatrolControlProofInput+ want PulseIntelligencePatrolControlProof+ }{+ {+ name: "not started",+ want: PulseIntelligencePatrolControlProof{+ ValueProofState: PulseIntelligenceProActivationValueProofNotStarted,+ },+ },+ {+ name: "starter only stays in progress",+ input: PulseIntelligencePatrolControlProofInput{+ PatrolControlStarterCount: 1,+ },+ want: PulseIntelligencePatrolControlProof{+ ValueProofState: PulseIntelligenceProActivationValueProofInProgress,+ },+ },+ {+ name: "rejected governed decision completes without resolving",+ input: PulseIntelligencePatrolControlProofInput{+ PatrolControlStarterCount: 1,+ PatrolIssueEvidenceCount: 1,+ ContextualCollaborationCount: 1,+ RejectedDecisionCount: 1,+ },+ want: PulseIntelligencePatrolControlProof{+ Completed: true,+ ValueProofState: PulseIntelligenceProActivationValueProofGovernedDecisionRecorded,+ },+ },+ {+ name: "approved verified outcome resolves",+ input: PulseIntelligencePatrolControlProofInput{+ PatrolControlStarterCount: 1,+ PatrolIssueEvidenceCount: 1,+ ContextualCollaborationCount: 1,+ ApprovedDecisionCount: 1,+ VerifiedOutcomeCount: 1,+ ExternalAgentReady: true,+ },+ want: PulseIntelligencePatrolControlProof{+ Completed: true,+ Resolved: true,+ ValueProofState: PulseIntelligenceProActivationValueProofVerified,+ },+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := ClassifyPulseIntelligencePatrolControlProof(tt.input); got != tt.want {+ t.Fatalf("ClassifyPulseIntelligencePatrolControlProof() = %#v, want %#v", got, tt.want)+ }+ })+ }++ legacy := ClassifyPulseIntelligencePatrolAutonomyProof(PulseIntelligencePatrolAutonomyProofInput{+ PatrolAutonomyStarterCount: 1,+ PatrolIssueEvidenceCount: 1,+ ContextualCollaborationCount: 1,+ ApprovedDecisionCount: 1,+ VerifiedOutcomeCount: 1,+ })+ if legacy != (PulseIntelligencePatrolAutonomyProof{+ Completed: true,+ Resolved: true,+ ValueProofState: PulseIntelligenceProActivationValueProofVerified,+ }) {+ t.Fatalf("legacy Patrol autonomy classifier alias drifted: %#v", legacy)+ }+}+func TestApplySnapshot(t *testing.T) {base := Ping{InstallID: "test-id",@@ -154,26 +331,82 @@ func TestApplySnapshot(t *testing.T) {snap := func() Snapshot {return Snapshot{- PVENodes: 3,- VMs: 10,- Containers: 5,- AgentHosts: 2,- DockerContainers: 12,- KubernetesPods: 18,- StoragePools: 4,- PhysicalDisks: 9,- TrueNASSystems: 1,- TrueNASApps: 3,- VMwareHosts: 2,- AvailabilityTargets: 6,- AIEnabled: true,- PatrolEnabled: true,- DiscoveryEnabled: true,- NotificationsEnabled: true,- AIActionsEnabled: true,- ActiveAlerts: 2,- PaidLicense: true,- HasAPITokens: true,+ PVENodes: 3,+ VMs: 10,+ Containers: 5,+ AgentHosts: 2,+ DockerContainers: 12,+ KubernetesPods: 18,+ StoragePools: 4,+ PhysicalDisks: 9,+ TrueNASSystems: 1,+ TrueNASApps: 3,+ VMwareHosts: 2,+ AvailabilityTargets: 6,+ AIEnabled: true,+ PatrolEnabled: true,+ DiscoveryEnabled: true,+ NotificationsEnabled: true,+ AIActionsEnabled: true,+ ActiveAlerts: 2,+ PaidLicense: true,+ HasAPITokens: true,+ PulseIntelligenceLoopConfigured: true,+ PulseIntelligenceLoopActive30d: true,+ PulseIntelligenceCompleteOperationsLoop30d: true,+ PulseIntelligenceApprovedExecutionLoop30d: true,+ PulseIntelligenceResolvedOperationsLoop30d: true,+ PulseIntelligencePatrolControlCompletedOperationsLoop30d: true,+ PulseIntelligencePatrolControlResolvedOperationsLoop30d: true,+ PulseIntelligencePatrolControlPaidCompletedOperationsLoop30d: true,+ PulseIntelligencePatrolControlPaidResolvedOperationsLoop30d: true,+ PulseIntelligenceProActivationCompletedOperationsLoop30d: true,+ PulseIntelligenceProActivationResolvedOperationsLoop30d: true,+ PulseIntelligenceProActivationPaidCompletedOperationsLoop30d: true,+ PulseIntelligenceProActivationPaidResolvedOperationsLoop30d: true,+ PulseIntelligenceGovernedActionActive30d: true,+ PulseIntelligenceAssistantOperationsLoop30d: true,+ PulseIntelligenceAssistantApprovedExecutionLoop30d: true,+ PulseIntelligenceAssistantApprovedActionSuccessLoop30d: true,+ PulseIntelligenceAssistantResolvedOperationsLoop30d: true,+ PulseIntelligenceExternalAgentOperationsLoop30d: true,+ PulseIntelligenceExternalAgentApprovedExecutionLoop30d: true,+ PulseIntelligenceExternalAgentApprovedActionSuccessLoop30d: true,+ PulseIntelligenceExternalAgentResolvedOperationsLoop30d: true,+ PulseIntelligenceMCPAdapterOperationsLoop30d: true,+ PulseIntelligenceMCPAdapterApprovedExecutionLoop30d: true,+ PulseIntelligenceMCPAdapterApprovedActionSuccessLoop30d: true,+ PulseIntelligenceMCPAdapterResolvedOperationsLoop30d: true,+ PulseIntelligenceOperationsLoopStarterRequests30d: 5,+ PulseIntelligenceAssistantOperationsLoopStarterRequests30d: 2,+ PulseIntelligencePatrolOperationsLoopStarterRequests30d: 1,+ PulseIntelligencePatrolControlOperationsLoopStarterRequests30d: 3,+ PulseIntelligenceProActivationOperationsLoopStarterRequests30d: 1,+ PulseIntelligenceMCPOperationsLoopStarterRequests30d: 1,+ PulseIntelligenceAssistantAICalls30d: 7,+ PulseIntelligenceAssistantContextAICalls30d: 4,+ PulseIntelligenceAssistantToolCalls30d: 9,+ PulseIntelligencePatrolAICalls30d: 3,+ PulseIntelligencePatrolRuns30d: 4,+ PulseIntelligencePatrolNewFindings30d: 5,+ PulseIntelligencePatrolInvestigations30d: 6,+ PulseIntelligencePatrolResolvedFindings30d: 3,+ PulseIntelligencePatrolAutofixes30d: 2,+ PulseIntelligenceExternalAgentEnabled: true,+ PulseIntelligenceExternalAgentUsed30d: true,+ PulseIntelligenceMCPAdapterUsed30d: true,+ PulseIntelligenceExternalAgentContextRequests30d: 8,+ PulseIntelligenceExternalAgentEventStreamRequests30d: 2,+ PulseIntelligenceExternalAgentProvisioningRequests30d: 1,+ PulseIntelligenceExternalAgentOperatorStateRequests30d: 3,+ PulseIntelligenceExternalAgentFindingRequests30d: 5,+ PulseIntelligenceExternalAgentActionRequests30d: 4,+ PulseIntelligenceActionPlans30d: 6,+ PulseIntelligenceApprovalRequests30d: 2,+ PulseIntelligenceRejectedActionDecisions30d: 1,+ PulseIntelligenceApprovedActionDecisions30d: 1,+ PulseIntelligenceApprovedActionAttempts30d: 1,+ PulseIntelligenceApprovedActionSuccesses30d: 1,}}@@ -209,6 +442,135 @@ func TestApplySnapshot(t *testing.T) {if !ping.HasAPITokens {t.Fatal("HasAPITokens should be true")}+ if !ping.PulseIntelligenceLoopConfigured || !ping.PulseIntelligenceLoopActive30d ||+ !ping.PulseIntelligenceCompleteOperationsLoop30d ||+ !ping.PulseIntelligenceApprovedExecutionLoop30d ||+ !ping.PulseIntelligenceResolvedOperationsLoop30d ||+ !ping.PulseIntelligencePatrolControlCompletedOperationsLoop30d ||+ !ping.PulseIntelligencePatrolControlResolvedOperationsLoop30d ||+ !ping.PulseIntelligencePatrolControlPaidCompletedOperationsLoop30d ||+ !ping.PulseIntelligencePatrolControlPaidResolvedOperationsLoop30d ||+ !ping.PulseIntelligenceProActivationCompletedOperationsLoop30d ||+ !ping.PulseIntelligenceProActivationResolvedOperationsLoop30d ||+ !ping.PulseIntelligenceProActivationPaidCompletedOperationsLoop30d ||+ !ping.PulseIntelligenceProActivationPaidResolvedOperationsLoop30d ||+ !ping.PulseIntelligenceGovernedActionActive30d ||+ !ping.PulseIntelligenceAssistantOperationsLoop30d ||+ !ping.PulseIntelligenceAssistantApprovedExecutionLoop30d ||+ !ping.PulseIntelligenceAssistantApprovedActionSuccessLoop30d ||+ !ping.PulseIntelligenceAssistantResolvedOperationsLoop30d ||+ !ping.PulseIntelligenceExternalAgentOperationsLoop30d ||+ !ping.PulseIntelligenceExternalAgentApprovedExecutionLoop30d ||+ !ping.PulseIntelligenceExternalAgentApprovedActionSuccessLoop30d ||+ !ping.PulseIntelligenceExternalAgentResolvedOperationsLoop30d ||+ !ping.PulseIntelligenceMCPAdapterOperationsLoop30d ||+ !ping.PulseIntelligenceMCPAdapterApprovedExecutionLoop30d ||+ !ping.PulseIntelligenceMCPAdapterApprovedActionSuccessLoop30d ||+ !ping.PulseIntelligenceMCPAdapterResolvedOperationsLoop30d {+ t.Fatalf("Pulse Intelligence adoption state not applied: %#v", ping)+ }+ if ping.PulseIntelligenceAssistantAICalls30d != 7 ||+ ping.PulseIntelligenceOperationsLoopStarterRequests30d != 5 ||+ ping.PulseIntelligenceAssistantOperationsLoopStarterRequests30d != 2 ||+ ping.PulseIntelligencePatrolOperationsLoopStarterRequests30d != 1 ||+ ping.PulseIntelligencePatrolControlOperationsLoopStarterRequests30d != 3 ||+ ping.PulseIntelligenceProActivationOperationsLoopStarterRequests30d != 1 ||+ ping.PulseIntelligenceMCPOperationsLoopStarterRequests30d != 1 ||+ ping.PulseIntelligenceAssistantContextAICalls30d != 4 ||+ ping.PulseIntelligenceAssistantToolCalls30d != 9 ||+ ping.PulseIntelligencePatrolAICalls30d != 3 ||+ ping.PulseIntelligencePatrolRuns30d != 4 ||+ ping.PulseIntelligencePatrolNewFindings30d != 5 ||+ ping.PulseIntelligencePatrolInvestigations30d != 6 ||+ ping.PulseIntelligencePatrolResolvedFindings30d != 3 ||+ ping.PulseIntelligencePatrolAutofixes30d != 2 ||+ ping.PulseIntelligenceActionPlans30d != 6 ||+ ping.PulseIntelligenceApprovalRequests30d != 2 ||+ ping.PulseIntelligenceRejectedActionDecisions30d != 1 ||+ ping.PulseIntelligenceApprovedActionDecisions30d != 1 ||+ ping.PulseIntelligenceApprovedActionAttempts30d != 1 ||+ ping.PulseIntelligenceApprovedActionSuccesses30d != 1 {+ t.Fatalf("Pulse Intelligence counters not applied: %#v", ping)+ }+ if !ping.PulseIntelligenceExternalAgentEnabled || !ping.PulseIntelligenceExternalAgentUsed30d ||+ !ping.PulseIntelligenceMCPAdapterUsed30d {+ t.Fatalf("Pulse Intelligence external-agent booleans not applied: %#v", ping)+ }+ if ping.PulseIntelligenceExternalAgentContextRequests30d != 8 ||+ ping.PulseIntelligenceExternalAgentEventStreamRequests30d != 2 ||+ ping.PulseIntelligenceExternalAgentProvisioningRequests30d != 1 ||+ ping.PulseIntelligenceExternalAgentOperatorStateRequests30d != 3 ||+ ping.PulseIntelligenceExternalAgentFindingRequests30d != 5 ||+ ping.PulseIntelligenceExternalAgentActionRequests30d != 4 {+ t.Fatalf("Pulse Intelligence external-agent class counters not applied: %#v", ping)+ }+}++func TestPulseIntelligenceTelemetryFieldsAreDisclosed(t *testing.T) {+ pingType := reflect.TypeOf(Ping{})+ fieldLabels := make([]string, 0)+ for i := 0; i < pingType.NumField(); i++ {+ jsonName := strings.Split(pingType.Field(i).Tag.Get("json"), ",")[0]+ if !strings.HasPrefix(jsonName, "pulse_intelligence_") {+ continue+ }+ fieldLabels = append(fieldLabels, normalizedTelemetryDisclosureLabel(jsonName))+ }+ if len(fieldLabels) == 0 {+ t.Fatal("expected Pulse Intelligence telemetry fields on Ping")+ }++ for _, relativePath := range []string{+ filepath.Join("..", "..", "docs", "PRIVACY.md"),+ filepath.Join("..", "..", "frontend-modern", "public", "docs", "PRIVACY.md"),+ } {+ raw, err := os.ReadFile(relativePath)+ if err != nil {+ t.Fatalf("read %s: %v", relativePath, err)+ }+ doc := normalizedTelemetryDisclosureTableText(string(raw))+ for _, label := range fieldLabels {+ if !strings.Contains(doc, label) {+ t.Errorf("%s must disclose Pulse Intelligence telemetry field %q", relativePath, label)+ }+ }+ }+}++func normalizedTelemetryDisclosureTableText(value string) string {+ tableLines := make([]string, 0)+ for _, line := range strings.Split(value, "\n") {+ if strings.HasPrefix(strings.TrimSpace(line), "|") {+ tableLines = append(tableLines, line)+ }+ }+ return normalizedTelemetryDisclosureText(strings.Join(tableLines, "\n"))+}++func normalizedTelemetryDisclosureLabel(jsonName string) string {+ label := strings.TrimPrefix(jsonName, "pulse_intelligence_")+ return normalizedTelemetryDisclosureText("Pulse Intelligence " + strings.ReplaceAll(label, "_", " "))+}++func normalizedTelemetryDisclosureText(value string) string {+ value = strings.ToLower(value)+ replacer := strings.NewReplacer(+ "`", " ",+ "|", " ",+ "_", " ",+ "-", " ",+ "/", " ",+ ",", " ",+ ".", " ",+ ":", " ",+ ";", " ",+ "(", " ",+ ")", " ",+ "[", " ",+ "]", " ",+ )+ value = replacer.Replace(value)+ return strings.Join(strings.Fields(value), " ")}func TestApplySnapshot_NilFunc(t *testing.T) {diff --git a/pkg/aicontracts/contracts_test.go b/pkg/aicontracts/contracts_test.goindex a58ec5b908..a3c7d5145e 100644--- a/pkg/aicontracts/contracts_test.go+++ b/pkg/aicontracts/contracts_test.go@@ -4,6 +4,8 @@ import ("encoding/json""strings""testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")func TestEmptyOrchestratorMessage_UsesCanonicalEmptyCollections(t *testing.T) {@@ -39,6 +41,61 @@ func TestEmptyOrchestratorToolCallInfo_UsesCanonicalEmptyCollections(t *testing.}}+func TestOrchestratorToolCallInfoUsesSharedProviderProjection(t *testing.T) {+ input := map[string]interface{}{+ "resource_id": "vm/100",+ "body": map[string]interface{}{+ "tags": []interface{}{"prod"},+ },+ }+ signature := json.RawMessage(`{"provider":"gemini"}`)++ info := OrchestratorToolCallInfoFromProvider(agentcapabilities.ProviderToolCall{+ ID: "call-1",+ Name: "diagnose",+ Input: input,+ ThoughtSignature: signature,+ })+ if info.ID != "call-1" || info.Name != "diagnose" || info.Input == nil {+ t.Fatalf("orchestrator tool call info = %+v", info)+ }+ info.Input["resource_id"] = "vm/101"+ info.Input["body"].(map[string]interface{})["tags"].([]interface{})[0] = "changed"+ info.ThoughtSignature[0] = '['+ if input["resource_id"] != "vm/100" || input["body"].(map[string]interface{})["tags"].([]interface{})[0] != "prod" {+ t.Fatalf("orchestrator projection must not alias provider input: source=%#v info=%#v", input, info.Input)+ }+ if string(signature) != `{"provider":"gemini"}` {+ t.Fatalf("orchestrator projection must not alias provider thought signature: source=%s info=%s", signature, info.ThoughtSignature)+ }++ orchestratorInput := map[string]interface{}{"resource_id": "vm/300"}+ infoForProvider := OrchestratorToolCallInfo{+ ID: "call-2",+ Name: "inspect",+ Input: orchestratorInput,+ ThoughtSignature: json.RawMessage(`{"provider":"gemini"}`),+ }.NormalizeCollections()+ provider := infoForProvider.ProviderToolCall()+ provider.Input["resource_id"] = "vm/102"+ provider.ThoughtSignature[0] = '['+ if infoForProvider.Input["resource_id"] != "vm/300" || string(infoForProvider.ThoughtSignature) != `{"provider":"gemini"}` {+ t.Fatalf("provider projection must not alias orchestrator tool call info: info=%#v provider=%#v", infoForProvider, provider)+ }+}++func TestOrchestratorToolResultInfoUsesSharedProviderProjection(t *testing.T) {+ info := OrchestratorToolResultInfoFromProvider(agentcapabilities.NewProviderToolResult("call-1", "done", true))+ if info.ToolUseID != "call-1" || info.Content != "done" || !info.IsError {+ t.Fatalf("orchestrator tool result info = %+v", info)+ }++ var shared agentcapabilities.ProviderToolResult = info.ProviderToolResult()+ if shared.ToolUseID != "call-1" || shared.Content != "done" || !shared.IsError {+ t.Fatalf("shared provider tool result = %+v", shared)+ }+}+func TestEmptyInvestigationSession_UsesCanonicalEmptyCollections(t *testing.T) {payload, err := json.Marshal(EmptyInvestigationSession())if err != nil {@@ -71,6 +128,20 @@ func TestEmptyInvestigationRecord_UsesCanonicalEmptyCollections(t *testing.T) {}}+func TestInvestigationOutcomeFixRejected_IsCanonicalWireValue(t *testing.T) {+ payload, err := json.Marshal(struct {+ Outcome InvestigationOutcome `json:"outcome"`+ }{+ Outcome: OutcomeFixRejected,+ })+ if err != nil {+ t.Fatalf("marshal rejected investigation outcome: %v", err)+ }+ if !strings.Contains(string(payload), `"outcome":"fix_rejected"`) {+ t.Fatalf("expected rejected investigation outcome wire value, got %s", payload)+ }+}+func TestEmptyFix_UsesCanonicalEmptyCollections(t *testing.T) {payload, err := json.Marshal(EmptyFix())if err != nil {diff --git a/pkg/aicontracts/fix_execution.go b/pkg/aicontracts/fix_execution.goindex dadf8f42d3..4c20b61205 100644--- a/pkg/aicontracts/fix_execution.go+++ b/pkg/aicontracts/fix_execution.go@@ -88,9 +88,10 @@ type ApprovalStoreAccessor interface {AssessRiskLevel(command, targetType string) string}-// MCPToolExecutor executes MCP tool calls via the chat service.-type MCPToolExecutor interface {- ExecuteMCPTool(ctx context.Context, command, approvalID string) (output string, exitCode int, err error)+// ApprovedAssistantToolExecutor executes approved native Assistant tool+// invocations via the shared Pulse tool registry.+type ApprovedAssistantToolExecutor interface {+ ExecuteApprovedAssistantTool(ctx context.Context, command, approvalID string) (output string, exitCode int, err error)}// AgentCommandExecutor executes shell commands via connected agents.diff --git a/pkg/aicontracts/investigation.go b/pkg/aicontracts/investigation.goindex 8bb9706401..a369374fcf 100644--- a/pkg/aicontracts/investigation.go+++ b/pkg/aicontracts/investigation.go@@ -39,6 +39,7 @@ const (OutcomeFixQueued InvestigationOutcome = "fix_queued"OutcomeFixExecuted InvestigationOutcome = "fix_executed"OutcomeFixFailed InvestigationOutcome = "fix_failed"+ OutcomeFixRejected InvestigationOutcome = "fix_rejected"OutcomeFixVerified InvestigationOutcome = "fix_verified"OutcomeFixVerificationFailed InvestigationOutcome = "fix_verification_failed"OutcomeFixVerificationUnknown InvestigationOutcome = "fix_verification_unknown"diff --git a/pkg/aicontracts/orchestrator_deps.go b/pkg/aicontracts/orchestrator_deps.goindex 205f3801ad..a7ae297a93 100644--- a/pkg/aicontracts/orchestrator_deps.go+++ b/pkg/aicontracts/orchestrator_deps.go@@ -4,6 +4,8 @@ import ("context""encoding/json""time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities")// ---------------------------------------------------------------------------@@ -120,9 +122,10 @@ func (m OrchestratorMessage) NormalizeCollections() OrchestratorMessage {// OrchestratorToolCallInfo represents a tool invocation.type OrchestratorToolCallInfo struct {- ID string `json:"id"`- Name string `json:"name"`- Input map[string]interface{} `json:"input"`+ ID string `json:"id"`+ Name string `json:"name"`+ Input map[string]interface{} `json:"input"`+ ThoughtSignature json.RawMessage `json:"thought_signature,omitempty"`}func EmptyOrchestratorToolCallInfo() OrchestratorToolCallInfo {@@ -130,10 +133,31 @@ func EmptyOrchestratorToolCallInfo() OrchestratorToolCallInfo {}func (t OrchestratorToolCallInfo) NormalizeCollections() OrchestratorToolCallInfo {- if t.Input == nil {- t.Input = map[string]interface{}{}+ return OrchestratorToolCallInfoFromProvider(t.ProviderToolCall())+}++// OrchestratorToolCallInfoFromProvider projects the shared provider-facing+// tool-call shape into the public orchestrator contract without duplicating+// Pulse Intelligence normalization rules.+func OrchestratorToolCallInfoFromProvider(tc agentcapabilities.ProviderToolCall) OrchestratorToolCallInfo {+ tc = tc.NormalizeCollections()+ return OrchestratorToolCallInfo{+ ID: tc.ID,+ Name: tc.Name,+ Input: tc.Input,+ ThoughtSignature: tc.ThoughtSignature,}- return t+}++// ProviderToolCall returns the shared provider-facing shape used by Assistant+// and MCP-facing Pulse Intelligence tool projections.+func (t OrchestratorToolCallInfo) ProviderToolCall() agentcapabilities.ProviderToolCall {+ return agentcapabilities.ProviderToolCall{+ ID: t.ID,+ Name: t.Name,+ Input: t.Input,+ ThoughtSignature: t.ThoughtSignature,+ }.NormalizeCollections()}// OrchestratorToolResultInfo represents the result of a tool invocation.@@ -143,6 +167,22 @@ type OrchestratorToolResultInfo struct {IsError bool `json:"is_error,omitempty"`}+// OrchestratorToolResultInfoFromProvider projects the shared provider-facing+// result shape into the public orchestrator contract.+func OrchestratorToolResultInfoFromProvider(result agentcapabilities.ProviderToolResult) OrchestratorToolResultInfo {+ return OrchestratorToolResultInfo{+ ToolUseID: result.ToolUseID,+ Content: result.Content,+ IsError: result.IsError,+ }+}++// ProviderToolResult returns the shared provider-facing result shape used by+// Assistant and MCP-facing Pulse Intelligence tool projections.+func (r OrchestratorToolResultInfo) ProviderToolResult() agentcapabilities.ProviderToolResult {+ return agentcapabilities.NewProviderToolResult(r.ToolUseID, r.Content, r.IsError)+}+// OrchestratorApproval represents a queued approval request.type OrchestratorApproval struct {ID string `json:"id"`diff --git a/pkg/aicontracts/safety.go b/pkg/aicontracts/safety.goindex 8e7e8d8452..f52fd1798c 100644--- a/pkg/aicontracts/safety.go+++ b/pkg/aicontracts/safety.go@@ -104,6 +104,83 @@ func IsDestructiveCommand(command string) bool {return IsBlockedCommand(command)}+// ClassifyAutomationRisk classifies a command for governed autonomous execution.+// It is intentionally stricter than approval-list risk display: unknown write+// commands are high risk until Pulse can prove they are safe enough to run+// without an operator decision.+func ClassifyAutomationRisk(command string) RiskLevel {+ cmd := strings.TrimSpace(command)+ if cmd == "" {+ return RiskHigh+ }+ if IsBlockedCommand(cmd) {+ return RiskCritical+ }+ if containsStdoutRedirection(cmd) || containsAutomationRiskPattern(cmd, highAutomationRiskPatterns) {+ return RiskHigh+ }+ if IsReadOnlyCommand(cmd) {+ return RiskLow+ }+ if containsAutomationRiskPattern(cmd, mediumAutomationRiskPatterns) {+ return RiskMedium+ }+ return RiskHigh+}++var highAutomationRiskPatterns = []string{+ "rm ", "rm\t", "rmdir",+ "shutdown", "reboot", "poweroff", "halt",+ "systemctl restart", "systemctl stop", "systemctl start",+ "systemctl enable", "systemctl disable",+ "service ",+ "apt ", "apt-get ", "yum ", "dnf ", "pacman ", "apk ", "brew ",+ "pip install", "pip uninstall", "npm install", "npm uninstall", "cargo install",+ "docker rm", "docker stop", "docker kill", "docker restart", "docker exec",+ "kubectl exec",+ "kill ", "killall ", "pkill ",+ "dd ", "mkfs", "fdisk", "parted", "mkswap",+ "iptables", "firewall-cmd", "ufw ",+ "truncate",+ "chmod ", "chown ", "chgrp ",+ "useradd", "userdel", "usermod", "passwd", "chpasswd",+ "crontab -", "visudo", "vipw",+ "mount ", "umount ", "modprobe", "rmmod", "insmod", "sysctl -w",+ "sudo",+ "| tee ",+}++var mediumAutomationRiskPatterns = []string{+ "mv ", "cp ",+ "sed -i", "awk -i",+ "touch ", "mkdir ",+ "wget -o", "wget --output",+ "tar -x", "tar x", "unzip ", "gunzip ",+}++func containsAutomationRiskPattern(command string, patterns []string) bool {+ cmdLower := strings.ToLower(command)+ for _, pattern := range patterns {+ if strings.Contains(cmdLower, pattern) {+ return true+ }+ }+ return false+}++func containsStdoutRedirection(command string) bool {+ for i := 0; i < len(command); i++ {+ if command[i] != '>' {+ continue+ }+ if i > 0 && command[i-1] == '2' {+ continue+ }+ return true+ }+ return false+}+// ReadOnlyPatterns defines commands that are safe to execute without approval.var ReadOnlyPatterns = []string{// File/system inspectiondiff --git a/pkg/aicontracts/safety_test.go b/pkg/aicontracts/safety_test.gonew file mode 100644index 0000000000..f4cb427b81--- /dev/null+++ b/pkg/aicontracts/safety_test.go@@ -0,0 +1,55 @@+package aicontracts++import "testing"++func TestClassifyAutomationRisk(t *testing.T) {+ tests := []struct {+ name string+ command string+ want RiskLevel+ }{+ {+ name: "read only command is low risk",+ command: "systemctl status nginx",+ want: RiskLow,+ },+ {+ name: "stderr redirection on read only command stays low risk",+ command: "find /var/log -name '*.log' 2>/dev/null",+ want: RiskLow,+ },+ {+ name: "file mutation is medium risk",+ command: "touch /tmp/pulse-marker",+ want: RiskMedium,+ },+ {+ name: "service restart is high risk",+ command: "systemctl restart nginx",+ want: RiskHigh,+ },+ {+ name: "stdout redirection is high risk",+ command: "cat /etc/hosts > /tmp/hosts",+ want: RiskHigh,+ },+ {+ name: "blocked command is critical risk",+ command: "rm -rf /tmp/pulse-data",+ want: RiskCritical,+ },+ {+ name: "unknown write capability defaults high risk",+ command: "custom-repair-tool --apply",+ want: RiskHigh,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := ClassifyAutomationRisk(tt.command); got != tt.want {+ t.Fatalf("ClassifyAutomationRisk(%q) = %q, want %q", tt.command, got, tt.want)+ }+ })+ }+}diff --git a/pkg/extensions/ai_autofix.go b/pkg/extensions/ai_autofix.goindex e9249b4d04..bc435f9791 100644--- a/pkg/extensions/ai_autofix.go+++ b/pkg/extensions/ai_autofix.go@@ -57,8 +57,8 @@ type AIAutoFixHandlerDeps struct {Approvals func() aicontracts.ApprovalStoreAccessor// Command execution- MCPExecutor aicontracts.MCPToolExecutor- AgentExecutor aicontracts.AgentCommandExecutor+ AssistantToolExecutor aicontracts.ApprovedAssistantToolExecutor+ AgentExecutor aicontracts.AgentCommandExecutor// Finding/patrol operationsFindingUpdater aicontracts.FindingOutcomeUpdater@@ -86,6 +86,12 @@ type AIAutoFixHandlerDeps struct {GetClientIP func(r *http.Request) string}+// ResolveApprovedAssistantToolExecutor returns the native approved Assistant+// tool executor.+func (d AIAutoFixHandlerDeps) ResolveApprovedAssistantToolExecutor() aicontracts.ApprovedAssistantToolExecutor {+ return d.AssistantToolExecutor+}+// BindAIAutoFixEndpointsFunc allows enterprise modules to bind replacement// AI auto-fix endpoints while retaining access to default handlers.type BindAIAutoFixEndpointsFunc func(defaults AIAutoFixEndpoints, runtime AIAutoFixRuntime) AIAutoFixEndpointsdiff --git a/pkg/extensions/ai_autofix_test.go b/pkg/extensions/ai_autofix_test.gonew file mode 100644index 0000000000..db95051077--- /dev/null+++ b/pkg/extensions/ai_autofix_test.go@@ -0,0 +1,50 @@+package extensions++import (+ "context"+ "testing"+)++type recordingApprovedAssistantToolExecutor struct {+ calls int+ command string+ approvalID string+ output string+ exitCode int+ err error+}++func (e *recordingApprovedAssistantToolExecutor) ExecuteApprovedAssistantTool(_ context.Context, command, approvalID string) (string, int, error) {+ e.calls+++ e.command = command+ e.approvalID = approvalID+ return e.output, e.exitCode, e.err+}++func TestAIAutoFixHandlerDepsResolveApprovedAssistantToolExecutorReturnsNative(t *testing.T) {+ native := &recordingApprovedAssistantToolExecutor{output: "native-ok"}++ executor := (AIAutoFixHandlerDeps{+ AssistantToolExecutor: native,+ }).ResolveApprovedAssistantToolExecutor()+ if executor == nil {+ t.Fatal("expected native approved Assistant executor")+ }++ output, exitCode, err := executor.ExecuteApprovedAssistantTool(context.Background(), "pulse_control_guest()", "approval-1")+ if err != nil {+ t.Fatalf("ExecuteApprovedAssistantTool returned error: %v", err)+ }+ if output != "native-ok" || exitCode != 0 {+ t.Fatalf("ExecuteApprovedAssistantTool = (%q, %d), want native output", output, exitCode)+ }+ if native.calls != 1 || native.command != "pulse_control_guest()" || native.approvalID != "approval-1" {+ t.Fatalf("native executor was not called with approved tool request: %+v", native)+ }+}++func TestAIAutoFixHandlerDepsResolveApprovedAssistantToolExecutorReturnsNilWhenUnwired(t *testing.T) {+ if executor := (AIAutoFixHandlerDeps{}).ResolveApprovedAssistantToolExecutor(); executor != nil {+ t.Fatalf("ResolveApprovedAssistantToolExecutor() = %T, want nil", executor)+ }+}diff --git a/pkg/licensing/features.go b/pkg/licensing/features.goindex a920525e89..fa5e4e72d7 100644--- a/pkg/licensing/features.go+++ b/pkg/licensing/features.go@@ -27,7 +27,7 @@ const (// Pro tier features (everything in Relay, plus:)FeatureAIAlerts = "ai_alerts" // AI analysis when alerts fire- FeatureAIAutoFix = "ai_autofix" // Governed remediation workflows+ FeatureAIAutoFix = "ai_autofix" // Governed Patrol fixesFeatureKubernetesAI = "kubernetes_ai" // Legacy Kubernetes analysis compatibility gate (NOT basic monitoring)FeatureAgentProfiles = "agent_profiles" // Centralized agent configuration profilesFeatureRBAC = "rbac" // Role-Based Access Control@@ -225,7 +225,7 @@ var freeFeatures = []string{FeatureUpdateAlerts,FeatureSSO,FeatureAdvancedSSO,- FeatureAIPatrol, // Patrol is free with BYOK; remediation workflows require Pro.+ FeatureAIPatrol, // Patrol is free with BYOK; governed fixes require Pro.}// relayFeatures adds remote access and mobile on top of free.diff --git a/pkg/licensing/features_test.go b/pkg/licensing/features_test.goindex 185cf935a9..1567398676 100644--- a/pkg/licensing/features_test.go+++ b/pkg/licensing/features_test.go@@ -127,6 +127,21 @@ func TestDeriveCapabilitiesFromTier_Sorted(t *testing.T) {}}+func TestPatrolGovernedFixesStayProFeature(t *testing.T) {+ if !TierHasFeature(TierFree, FeatureAIPatrol) {+ t.Fatal("community tier must include watch-only Patrol with BYOK")+ }+ if TierHasFeature(TierFree, FeatureAIAutoFix) {+ t.Fatal("community tier must not include governed Patrol fixes")+ }+ if TierHasFeature(TierRelay, FeatureAIAutoFix) {+ t.Fatal("relay tier must not include governed Patrol fixes")+ }+ if !TierHasFeature(TierPro, FeatureAIAutoFix) {+ t.Fatal("pro tier must include governed Patrol fixes")+ }+}+func TestWhiteLabelBrandingRemainsExplicitEnterpriseEntitlement(t *testing.T) {if TierHasFeature(TierFree, FeatureWhiteLabel) {t.Fatal("community tier must not include white_label report branding")@@ -356,8 +371,8 @@ func TestGetFeatureDisplayName(t *testing.T) {want string}{{FeatureAIPatrol, "Pulse Patrol (Background Health Checks)"},- {FeatureAIAlerts, "Alert Analysis"},- {FeatureAIAutoFix, "Safe Remediation Workflows"},+ {FeatureAIAlerts, "Patrol Investigates Issues"},+ {FeatureAIAutoFix, "Patrol Handles Safe Fixes"},{FeatureKubernetesAI, "Kubernetes AI Analysis (Compatibility)"},{FeatureUpdateAlerts, "Update Alerts (Container/Package Updates)"},{FeatureRBAC, "Role-Based Access Control (RBAC)"},diff --git a/pkg/licensing/self_hosted_feature_catalog.go b/pkg/licensing/self_hosted_feature_catalog.goindex 56f178dcc6..0a7106ac80 100644--- a/pkg/licensing/self_hosted_feature_catalog.go+++ b/pkg/licensing/self_hosted_feature_catalog.go@@ -147,8 +147,8 @@ var featureMetadataCatalog = map[string]FeatureMetadata{},FeatureAIAlerts: {Key: FeatureAIAlerts,- DisplayName: "Alert Analysis",- ComparisonName: "Alert Root-Cause Analysis",+ DisplayName: "Patrol Investigates Issues",+ ComparisonName: "Patrol Investigates Issues",ShowInComparisonTable: true,DisplayableInPlanUI: true,SelfHostedRoles: SelfHostedFeatureRoles{@@ -156,13 +156,13 @@ var featureMetadataCatalog = map[string]FeatureMetadata{Relay: SelfHostedFeatureRoleHidden,Pro: SelfHostedFeatureRolePrimaryPillar,},- UpgradeReason: "Upgrade to Pro so alerts arrive with root-cause analysis instead of a stack of symptoms.",+ UpgradeReason: "Upgrade to Pro so Patrol can investigate issues instead of handing you a stack of symptoms.",UpgradePriority: 4,},FeatureAIAutoFix: {Key: FeatureAIAutoFix,- DisplayName: "Safe Remediation Workflows",- ComparisonName: "Safe Remediation Workflows",+ DisplayName: "Patrol Handles Safe Fixes",+ ComparisonName: "Patrol Handles Safe Fixes",ShowInComparisonTable: true,DisplayableInPlanUI: true,SelfHostedRoles: SelfHostedFeatureRoles{@@ -170,7 +170,7 @@ var featureMetadataCatalog = map[string]FeatureMetadata{Relay: SelfHostedFeatureRoleHidden,Pro: SelfHostedFeatureRolePrimaryPillar,},- UpgradeReason: "Upgrade to Pro so Pulse can move from finding issues to governed remediation with your approval or autonomy policy.",+ UpgradeReason: "Upgrade to Pro so Patrol can investigate issues, handle safe fixes within Patrol mode, and verify the outcome.",UpgradePriority: 3,},FeatureKubernetesAI: {diff --git a/pkg/licensing/upgrade_test.go b/pkg/licensing/upgrade_test.goindex 23e2757334..991db41e5e 100644--- a/pkg/licensing/upgrade_test.go+++ b/pkg/licensing/upgrade_test.go@@ -95,8 +95,8 @@ func TestOperatorOutcomeUpgradeReasonsRemainCanonical(t *testing.T) {expected := map[string]string{FeatureRelay: "Get Relay so Pulse stays reachable securely from anywhere instead of only on the local dashboard.",FeatureLongTermMetrics: "Get Relay for 14 days of history, or Pro for 90 days, so you can see what changed before and after an incident.",- FeatureAIAlerts: "Upgrade to Pro so alerts arrive with root-cause analysis instead of a stack of symptoms.",- FeatureAIAutoFix: "Upgrade to Pro so Pulse can move from finding issues to governed remediation with your approval or autonomy policy.",+ FeatureAIAlerts: "Upgrade to Pro so Patrol can investigate issues instead of handing you a stack of symptoms.",+ FeatureAIAutoFix: "Upgrade to Pro so Patrol can investigate issues, handle safe fixes within Patrol mode, and verify the outcome.",}for _, entry := range UpgradeReasonMatrix {diff --git a/pkg/server/server.go b/pkg/server/server.goindex 7c5a4d5f25..ef3e6dc7a4 100644--- a/pkg/server/server.go+++ b/pkg/server/server.go@@ -541,6 +541,13 @@ func Run(ctx context.Context, version string) error {}}+ now := time.Now().UTC()+ var actionSnapshot telemetry.PulseIntelligenceActionSnapshot+ if router != nil {+ actionSnapshot = router.GetPulseIntelligenceActionTelemetry(now.Add(-telemetry.PulseIntelligenceTelemetryWindow))+ }+ applyPulseIntelligenceTelemetrySnapshot(&snap, telemetryPersistence, currentCfg, actionSnapshot, now)+return snap},}diff --git a/pkg/server/telemetry_pulse_intelligence.go b/pkg/server/telemetry_pulse_intelligence.gonew file mode 100644index 0000000000..db0dffed47--- /dev/null+++ b/pkg/server/telemetry_pulse_intelligence.go@@ -0,0 +1,411 @@+package server++import (+ "strings"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/telemetry"+)++func applyPulseIntelligenceTelemetrySnapshot(+ snap *telemetry.Snapshot,+ persistence *config.ConfigPersistence,+ currentCfg *config.Config,+ actionSnapshot telemetry.PulseIntelligenceActionSnapshot,+ now time.Time,+) {+ if snap == nil {+ return+ }+ if now.IsZero() {+ now = time.Now()+ }+ now = now.UTC()+ since := now.Add(-telemetry.PulseIntelligenceTelemetryWindow)++ applyPulseIntelligenceAIUsageSnapshot(snap, persistence, since)+ applyPulseIntelligencePatrolRunSnapshot(snap, persistence, since)+ applyPulseIntelligenceFindingSnapshot(snap, persistence, since)+ applyPulseIntelligenceExternalAgentSnapshot(snap, persistence, currentCfg, since, now)+ applyPulseIntelligenceWorkflowPromptSnapshot(snap, persistence, since)++ snap.PulseIntelligenceActionPlans30d = actionSnapshot.ActionPlans30d+ snap.PulseIntelligenceApprovalRequests30d = actionSnapshot.ApprovalRequests30d+ snap.PulseIntelligenceRejectedActionDecisions30d = actionSnapshot.RejectedActionDecisions30d+ snap.PulseIntelligenceApprovedActionDecisions30d = actionSnapshot.ApprovedActionDecisions30d+ snap.PulseIntelligenceApprovedActionAttempts30d = actionSnapshot.ApprovedActionAttempts30d+ snap.PulseIntelligenceApprovedActionSuccesses30d = actionSnapshot.ApprovedActionSuccesses30d++ applyPulseIntelligenceAdoptionSnapshot(snap)+}++func applyPulseIntelligenceAdoptionSnapshot(snap *telemetry.Snapshot) {+ if snap == nil {+ return+ }++ snap.PulseIntelligenceLoopConfigured = snap.AIEnabled ||+ snap.PatrolEnabled ||+ snap.AIActionsEnabled ||+ snap.PulseIntelligenceExternalAgentEnabled++ snap.PulseIntelligenceGovernedActionActive30d =+ snap.PulseIntelligenceActionPlans30d > 0 ||+ snap.PulseIntelligenceApprovalRequests30d > 0 ||+ snap.PulseIntelligenceRejectedActionDecisions30d > 0 ||+ snap.PulseIntelligenceApprovedActionDecisions30d > 0 ||+ snap.PulseIntelligenceApprovedActionAttempts30d > 0++ patrolActive := snap.PulseIntelligencePatrolAICalls30d > 0 ||+ snap.PulseIntelligencePatrolRuns30d > 0 ||+ snap.PulseIntelligencePatrolNewFindings30d > 0 ||+ snap.PulseIntelligencePatrolInvestigations30d > 0 ||+ snap.PulseIntelligencePatrolResolvedFindings30d > 0 ||+ snap.PulseIntelligencePatrolAutofixes30d > 0+ patrolIssueEvidenceCount := snap.PulseIntelligencePatrolNewFindings30d ++ snap.PulseIntelligencePatrolInvestigations30d ++ snap.PulseIntelligencePatrolResolvedFindings30d ++ snap.PulseIntelligencePatrolAutofixes30d+ patrolIssueEvidenceActive := patrolIssueEvidenceCount > 0+ assistantCollaborationCount := snap.PulseIntelligenceAssistantContextAICalls30d ++ snap.PulseIntelligenceAssistantToolCalls30d+ assistantCollaborationActive := assistantCollaborationCount > 0+ externalAgentCollaborationActive := pulseIntelligenceExternalAgentActivity(snap)+ externalAgentCollaborationCount := 0+ if externalAgentCollaborationActive {+ externalAgentCollaborationCount = 1+ }+ mcpAdapterCollaborationActive := snap.PulseIntelligenceMCPAdapterUsed30d+ contextualCollaborationCount := assistantCollaborationCount + externalAgentCollaborationCount+ contextualCollaborationActive := contextualCollaborationCount > 0+ governedActionDecisionActive := snap.PulseIntelligenceRejectedActionDecisions30d > 0 ||+ snap.PulseIntelligenceApprovedActionDecisions30d > 0 ||+ snap.PulseIntelligenceApprovedActionAttempts30d > 0+ approvedExecutionActive := snap.PulseIntelligenceApprovedActionAttempts30d > 0+ approvedSuccessActive := snap.PulseIntelligenceApprovedActionSuccesses30d > 0+ resolutionOutcomeActive := snap.PulseIntelligencePatrolResolvedFindings30d > 0+ patrolControlProof := telemetry.ClassifyPulseIntelligencePatrolControlProof(telemetry.PulseIntelligencePatrolControlProofInput{+ PatrolControlStarterCount: snap.PulseIntelligencePatrolControlOperationsLoopStarterRequests30d,+ PatrolIssueEvidenceCount: patrolIssueEvidenceCount,+ ContextualCollaborationCount: contextualCollaborationCount,+ ApprovedDecisionCount: snap.PulseIntelligenceApprovedActionDecisions30d,+ RejectedDecisionCount: snap.PulseIntelligenceRejectedActionDecisions30d,+ VerifiedOutcomeCount: snap.PulseIntelligenceApprovedActionSuccesses30d,+ })+ snap.PulseIntelligenceCompleteOperationsLoop30d =+ patrolIssueEvidenceActive &&+ contextualCollaborationActive &&+ governedActionDecisionActive+ snap.PulseIntelligenceApprovedExecutionLoop30d =+ patrolIssueEvidenceActive &&+ contextualCollaborationActive &&+ approvedExecutionActive+ snap.PulseIntelligenceResolvedOperationsLoop30d =+ resolutionOutcomeActive &&+ contextualCollaborationActive &&+ approvedSuccessActive+ snap.PulseIntelligencePatrolControlCompletedOperationsLoop30d = patrolControlProof.Completed+ snap.PulseIntelligencePatrolControlResolvedOperationsLoop30d = patrolControlProof.Resolved+ snap.PulseIntelligencePatrolControlPaidCompletedOperationsLoop30d =+ snap.PaidLicense && snap.PulseIntelligencePatrolControlCompletedOperationsLoop30d+ snap.PulseIntelligencePatrolControlPaidResolvedOperationsLoop30d =+ snap.PaidLicense && snap.PulseIntelligencePatrolControlResolvedOperationsLoop30d+ // Legacy Pro activation cohort fields mirror Patrol control for continuity.+ snap.PulseIntelligenceProActivationCompletedOperationsLoop30d = snap.PulseIntelligencePatrolControlCompletedOperationsLoop30d+ snap.PulseIntelligenceProActivationResolvedOperationsLoop30d = snap.PulseIntelligencePatrolControlResolvedOperationsLoop30d+ snap.PulseIntelligenceProActivationPaidCompletedOperationsLoop30d =+ snap.PulseIntelligencePatrolControlPaidCompletedOperationsLoop30d+ snap.PulseIntelligenceProActivationPaidResolvedOperationsLoop30d =+ snap.PulseIntelligencePatrolControlPaidResolvedOperationsLoop30d+ snap.PulseIntelligenceAssistantOperationsLoop30d =+ patrolIssueEvidenceActive &&+ assistantCollaborationActive &&+ governedActionDecisionActive+ snap.PulseIntelligenceAssistantApprovedExecutionLoop30d =+ patrolIssueEvidenceActive &&+ assistantCollaborationActive &&+ approvedExecutionActive+ snap.PulseIntelligenceAssistantApprovedActionSuccessLoop30d =+ patrolIssueEvidenceActive &&+ assistantCollaborationActive &&+ approvedSuccessActive+ snap.PulseIntelligenceAssistantResolvedOperationsLoop30d =+ resolutionOutcomeActive &&+ assistantCollaborationActive &&+ approvedSuccessActive+ snap.PulseIntelligenceExternalAgentOperationsLoop30d =+ patrolIssueEvidenceActive &&+ externalAgentCollaborationActive &&+ governedActionDecisionActive+ snap.PulseIntelligenceExternalAgentApprovedExecutionLoop30d =+ patrolIssueEvidenceActive &&+ externalAgentCollaborationActive &&+ approvedExecutionActive+ snap.PulseIntelligenceExternalAgentApprovedActionSuccessLoop30d =+ patrolIssueEvidenceActive &&+ externalAgentCollaborationActive &&+ approvedSuccessActive+ snap.PulseIntelligenceExternalAgentResolvedOperationsLoop30d =+ resolutionOutcomeActive &&+ externalAgentCollaborationActive &&+ approvedSuccessActive+ snap.PulseIntelligenceMCPAdapterOperationsLoop30d =+ patrolIssueEvidenceActive &&+ mcpAdapterCollaborationActive &&+ governedActionDecisionActive+ snap.PulseIntelligenceMCPAdapterApprovedExecutionLoop30d =+ patrolIssueEvidenceActive &&+ mcpAdapterCollaborationActive &&+ approvedExecutionActive+ snap.PulseIntelligenceMCPAdapterApprovedActionSuccessLoop30d =+ patrolIssueEvidenceActive &&+ mcpAdapterCollaborationActive &&+ approvedSuccessActive+ snap.PulseIntelligenceMCPAdapterResolvedOperationsLoop30d =+ resolutionOutcomeActive &&+ mcpAdapterCollaborationActive &&+ approvedSuccessActive++ snap.PulseIntelligenceLoopActive30d =+ snap.PulseIntelligenceAssistantAICalls30d > 0 ||+ snap.PulseIntelligenceOperationsLoopStarterRequests30d > 0 ||+ patrolActive ||+ pulseIntelligenceExternalAgentActivity(snap) ||+ snap.PulseIntelligenceGovernedActionActive30d+}++func pulseIntelligenceExternalAgentActivity(snap *telemetry.Snapshot) bool {+ if snap == nil {+ return false+ }+ evidence := telemetry.PulseIntelligenceExternalAgentEvidence{+ Used: snap.PulseIntelligenceExternalAgentUsed30d,+ MCPAdapterUsed: snap.PulseIntelligenceMCPAdapterUsed30d,+ ContextRequests: snap.PulseIntelligenceExternalAgentContextRequests30d,+ EventStreamRequests: snap.PulseIntelligenceExternalAgentEventStreamRequests30d,+ ProvisioningRequests: snap.PulseIntelligenceExternalAgentProvisioningRequests30d,+ OperatorStateRequests: snap.PulseIntelligenceExternalAgentOperatorStateRequests30d,+ FindingRequests: snap.PulseIntelligenceExternalAgentFindingRequests30d,+ ActionRequests: snap.PulseIntelligenceExternalAgentActionRequests30d,+ }+ return evidence.CollaborationActive()+}++func applyPulseIntelligenceAIUsageSnapshot(snap *telemetry.Snapshot, persistence *config.ConfigPersistence, since time.Time) {+ if snap == nil || persistence == nil {+ return+ }+ history, err := persistence.LoadAIUsageHistory()+ if err != nil || history == nil {+ return+ }+ evidence := telemetry.PulseIntelligenceAIUsageEvidenceFromHistory(history, since)+ snap.PulseIntelligenceAssistantAICalls30d = evidence.AssistantAICalls+ snap.PulseIntelligenceAssistantContextAICalls30d = evidence.AssistantContextAICalls+ snap.PulseIntelligenceAssistantToolCalls30d = evidence.AssistantToolCalls+ snap.PulseIntelligencePatrolAICalls30d = evidence.PatrolAICalls+}++func applyPulseIntelligencePatrolRunSnapshot(snap *telemetry.Snapshot, persistence *config.ConfigPersistence, since time.Time) {+ if snap == nil || persistence == nil {+ return+ }+ history, err := persistence.LoadPatrolRunHistory()+ if err != nil || history == nil {+ return+ }+ for _, run := range history.Runs {+ observedAt := run.CompletedAt+ if observedAt.IsZero() {+ observedAt = run.StartedAt+ }+ if observedAt.IsZero() || observedAt.Before(since) {+ continue+ }+ snap.PulseIntelligencePatrolRuns30d+++ if run.NewFindings > 0 {+ snap.PulseIntelligencePatrolNewFindings30d += run.NewFindings+ }+ if run.AutoFixCount > 0 {+ snap.PulseIntelligencePatrolAutofixes30d += run.AutoFixCount+ }+ }+}++func applyPulseIntelligenceFindingSnapshot(snap *telemetry.Snapshot, persistence *config.ConfigPersistence, since time.Time) {+ if snap == nil || persistence == nil {+ return+ }+ data, err := persistence.LoadAIFindings()+ if err != nil || data == nil {+ return+ }+ for _, finding := range data.Findings {+ if pulseIntelligenceFindingInvestigatedSince(finding, since) {+ snap.PulseIntelligencePatrolInvestigations30d+++ }+ if pulseIntelligenceFindingResolvedSince(finding, since) {+ snap.PulseIntelligencePatrolResolvedFindings30d+++ }+ }+}++func pulseIntelligenceFindingInvestigatedSince(finding *config.AIFindingRecord, since time.Time) bool {+ if finding == nil {+ return false+ }+ if finding.LastInvestigatedAt != nil && !finding.LastInvestigatedAt.IsZero() && !finding.LastInvestigatedAt.Before(since) {+ return true+ }+ record := finding.InvestigationRecord+ if record == nil {+ return false+ }+ if !record.StartedAt.IsZero() && !record.StartedAt.Before(since) {+ return true+ }+ return record.CompletedAt != nil && !record.CompletedAt.IsZero() && !record.CompletedAt.Before(since)+}++func pulseIntelligenceFindingResolvedSince(finding *config.AIFindingRecord, since time.Time) bool {+ if finding == nil {+ return false+ }+ if finding.ResolvedAt != nil && !finding.ResolvedAt.IsZero() && !finding.ResolvedAt.Before(since) {+ return true+ }+ switch strings.TrimSpace(finding.InvestigationOutcome) {+ case "resolved", "fix_verified":+ default:+ return false+ }+ if finding.LastInvestigatedAt != nil && !finding.LastInvestigatedAt.IsZero() && !finding.LastInvestigatedAt.Before(since) {+ return true+ }+ record := finding.InvestigationRecord+ return record != nil && record.CompletedAt != nil && !record.CompletedAt.IsZero() && !record.CompletedAt.Before(since)+}++func applyPulseIntelligenceExternalAgentSnapshot(+ snap *telemetry.Snapshot,+ persistence *config.ConfigPersistence,+ currentCfg *config.Config,+ since time.Time,+ now time.Time,+) {+ if snap == nil {+ return+ }+ if currentCfg != nil {+ surfaceScopes := pulseIntelligenceExternalAgentSurfaceScopes(agentcapabilities.CanonicalManifest())+ if len(surfaceScopes) > 0 {+ for _, token := range currentCfg.APITokens {+ if pulseIntelligenceExternalAgentToken(token, surfaceScopes, now) {+ snap.PulseIntelligenceExternalAgentEnabled = true+ }+ if pulseIntelligenceExternalAgentOperationsLoopToken(token, surfaceScopes, now) {+ snap.PulseIntelligenceExternalAgentOperationsLoopReady = true+ }+ if snap.PulseIntelligenceExternalAgentEnabled && snap.PulseIntelligenceExternalAgentOperationsLoopReady {+ break+ }+ }+ }+ }+ if persistence == nil {+ return+ }+ history, err := persistence.LoadExternalAgentActivityHistory()+ if err != nil || history == nil {+ return+ }+ evidence := telemetry.PulseIntelligenceExternalAgentEvidenceFromHistory(history, since)+ snap.PulseIntelligenceExternalAgentUsed30d = evidence.Used+ snap.PulseIntelligenceMCPAdapterUsed30d = evidence.MCPAdapterUsed+ snap.PulseIntelligenceExternalAgentContextRequests30d = evidence.ContextRequests+ snap.PulseIntelligenceExternalAgentEventStreamRequests30d = evidence.EventStreamRequests+ snap.PulseIntelligenceExternalAgentProvisioningRequests30d = evidence.ProvisioningRequests+ snap.PulseIntelligenceExternalAgentOperatorStateRequests30d = evidence.OperatorStateRequests+ snap.PulseIntelligenceExternalAgentFindingRequests30d = evidence.FindingRequests+ snap.PulseIntelligenceExternalAgentActionRequests30d = evidence.ActionRequests+}++func applyPulseIntelligenceWorkflowPromptSnapshot(snap *telemetry.Snapshot, persistence *config.ConfigPersistence, since time.Time) {+ if snap == nil || persistence == nil {+ return+ }+ history, err := persistence.LoadWorkflowPromptActivityHistory()+ if err != nil || history == nil {+ return+ }+ for _, event := range history.Events {+ if event.Timestamp.IsZero() || event.Timestamp.Before(since) {+ continue+ }+ if strings.TrimSpace(event.PromptName) != agentcapabilities.PulseWorkflowPromptOperationsLoop {+ continue+ }+ snap.PulseIntelligenceOperationsLoopStarterRequests30d+++ switch strings.TrimSpace(event.Surface) {+ case config.WorkflowPromptActivitySurfacePulseAssistant:+ snap.PulseIntelligenceAssistantOperationsLoopStarterRequests30d+++ case config.WorkflowPromptActivitySurfacePulsePatrol:+ snap.PulseIntelligencePatrolOperationsLoopStarterRequests30d+++ snap.PulseIntelligencePatrolControlOperationsLoopStarterRequests30d+++ case config.WorkflowPromptActivitySurfacePatrolControl:+ snap.PulseIntelligencePatrolControlOperationsLoopStarterRequests30d+++ case config.WorkflowPromptActivitySurfacePatrolAutonomy:+ snap.PulseIntelligencePatrolControlOperationsLoopStarterRequests30d+++ // This telemetry field is the compatibility aggregate for paid Patrol autonomy handoffs.+ snap.PulseIntelligenceProActivationOperationsLoopStarterRequests30d+++ case config.WorkflowPromptActivitySurfaceProActivation:+ snap.PulseIntelligencePatrolControlOperationsLoopStarterRequests30d+++ snap.PulseIntelligenceProActivationOperationsLoopStarterRequests30d+++ case config.WorkflowPromptActivitySurfacePulseMCP:+ snap.PulseIntelligenceMCPOperationsLoopStarterRequests30d+++ }+ }+}++func pulseIntelligenceExternalAgentSurfaceScopes(manifest agentcapabilities.Manifest) []string {+ return agentcapabilities.RequiredCapabilityScopes(+ agentcapabilities.ManifestSurfaceToolCapabilities(manifest, agentcapabilities.SurfaceIDPulseMCP),+ )+}++func pulseIntelligenceExternalAgentToken(token config.APITokenRecord, surfaceScopes []string, now time.Time) bool {+ if token.ExpiresAt != nil && now.After(token.ExpiresAt.UTC()) {+ return false+ }+ token = token.Clone()+ for _, scope := range surfaceScopes {+ if strings.TrimSpace(scope) == "" {+ continue+ }+ if token.HasScope(scope) {+ return true+ }+ }+ return false+}++func pulseIntelligenceExternalAgentOperationsLoopToken(token config.APITokenRecord, surfaceScopes []string, now time.Time) bool {+ if token.ExpiresAt != nil && now.After(token.ExpiresAt.UTC()) {+ return false+ }+ token = token.Clone()+ coversLoop := false+ for _, scope := range surfaceScopes {+ scope = strings.TrimSpace(scope)+ if scope == "" {+ continue+ }+ coversLoop = true+ if !token.HasScope(scope) {+ return false+ }+ }+ return coversLoop+}diff --git a/pkg/server/telemetry_pulse_intelligence_test.go b/pkg/server/telemetry_pulse_intelligence_test.gonew file mode 100644index 0000000000..a01dac4952--- /dev/null+++ b/pkg/server/telemetry_pulse_intelligence_test.go@@ -0,0 +1,1004 @@+package server++import (+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/telemetry"+ "github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"+)++func TestApplyPulseIntelligenceTelemetrySnapshot_AggregatesContentFreeLoopCounts(t *testing.T) {+ now := time.Date(2026, 6, 20, 9, 30, 0, 0, time.UTC)+ recent := now.Add(-2 * time.Hour)+ old := now.Add(-(telemetry.PulseIntelligenceTelemetryWindow + time.Hour))++ persistence := config.NewConfigPersistence(t.TempDir())+ if err := persistence.SaveAIUsageHistory([]config.AIUsageEventRecord{+ {Timestamp: recent, UseCase: "chat"},+ {Timestamp: recent.Add(-time.Minute), UseCase: "CHAT", ContextScope: "resource_context", ToolCallCount: 3},+ {Timestamp: recent.Add(-2 * time.Minute), UseCase: "chat", FindingID: "finding-123", ToolCallCount: 2},+ {Timestamp: recent, UseCase: "patrol"},+ {Timestamp: recent, UseCase: "unknown", ToolCallCount: 99},+ {Timestamp: old, UseCase: "chat", ToolCallCount: 99},+ }); err != nil {+ t.Fatalf("SaveAIUsageHistory: %v", err)+ }+ if err := persistence.SavePatrolRunHistory([]config.PatrolRunRecord{+ {StartedAt: recent.Add(-5 * time.Minute), CompletedAt: recent, NewFindings: 2, AutoFixCount: 1},+ {StartedAt: recent.Add(-time.Hour), CompletedAt: recent.Add(-30 * time.Minute), NewFindings: 3},+ {StartedAt: old, CompletedAt: old, NewFindings: 99, AutoFixCount: 99},+ }); err != nil {+ t.Fatalf("SavePatrolRunHistory: %v", err)+ }+ if err := persistence.SaveAIFindings(map[string]*config.AIFindingRecord{+ "recent-last-investigated": {+ ID: "recent-last-investigated",+ LastInvestigatedAt: &recent,+ },+ "recent-record-started": {+ ID: "recent-record-started",+ InvestigationRecord: &aicontracts.InvestigationRecord{+ ID: "investigation-recent",+ FindingID: "recent-record-started",+ StartedAt: recent.Add(-15 * time.Minute),+ },+ },+ "recent-resolved": {+ ID: "recent-resolved",+ ResolvedAt: &recent,+ },+ "recent-fix-verified": {+ ID: "recent-fix-verified",+ InvestigationOutcome: "fix_verified",+ InvestigationRecord: &aicontracts.InvestigationRecord{+ ID: "investigation-verified",+ FindingID: "recent-fix-verified",+ CompletedAt: &recent,+ },+ },+ "old-last-investigated": {+ ID: "old-last-investigated",+ LastInvestigatedAt: &old,+ },+ "old-resolved": {+ ID: "old-resolved",+ ResolvedAt: &old,+ },+ }); err != nil {+ t.Fatalf("SaveAIFindings: %v", err)+ }+ if err := persistence.SaveExternalAgentActivityHistory([]config.ExternalAgentActivityRecord{+ {Timestamp: recent, Surface: config.ExternalAgentActivitySurfaceAgentAPI, Activity: config.ExternalAgentActivityFleetContext},+ {Timestamp: recent.Add(-time.Minute), Surface: config.ExternalAgentActivitySurfaceAgentAPI, Activity: config.ExternalAgentActivityResourceContext},+ {Timestamp: recent.Add(-2 * time.Minute), Surface: config.ExternalAgentActivitySurfaceAgentAPI, Activity: config.ExternalAgentActivityEventStream},+ {Timestamp: recent.Add(-3 * time.Minute), Surface: config.ExternalAgentActivitySurfaceAgentAPI, Activity: config.ExternalAgentActivityProvisioning},+ {Timestamp: recent.Add(-4 * time.Minute), Surface: config.ExternalAgentActivitySurfaceAgentAPI, Activity: config.ExternalAgentActivityOperatorState},+ {Timestamp: recent.Add(-5 * time.Minute), Surface: config.ExternalAgentActivitySurfaceAgentAPI, Activity: config.ExternalAgentActivityFindingList},+ {Timestamp: recent.Add(-6 * time.Minute), Surface: config.ExternalAgentActivitySurfaceAgentAPI, Activity: config.ExternalAgentActivityFindingDecision},+ {Timestamp: recent.Add(-7 * time.Minute), Surface: config.ExternalAgentActivitySurfaceAgentAPI, Activity: config.ExternalAgentActivityActionPlan},+ {Timestamp: recent.Add(-8 * time.Minute), Surface: config.ExternalAgentActivitySurfaceAgentAPI, Activity: config.ExternalAgentActivityActionDecision},+ {Timestamp: recent.Add(-9 * time.Minute), Surface: config.ExternalAgentActivitySurfaceAgentAPI, Activity: config.ExternalAgentActivityActionExecute},+ {Timestamp: recent.Add(-10 * time.Minute), Surface: config.ExternalAgentActivitySurfacePulseMCP, Activity: config.ExternalAgentActivityActionExecute},+ {Timestamp: recent.Add(-10 * time.Minute), Surface: "support_api", Activity: config.ExternalAgentActivityResourceContext},+ {Timestamp: old, Surface: config.ExternalAgentActivitySurfaceAgentAPI, Activity: config.ExternalAgentActivityResourceContext},+ }); err != nil {+ t.Fatalf("SaveExternalAgentActivityHistory: %v", err)+ }+ if err := persistence.SaveWorkflowPromptActivityHistory([]config.WorkflowPromptActivityRecord{+ {Timestamp: recent, Surface: config.WorkflowPromptActivitySurfacePulseAssistant, PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop},+ {Timestamp: recent.Add(-time.Minute), Surface: config.WorkflowPromptActivitySurfacePulseMCP, PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop},+ {Timestamp: recent.Add(-2 * time.Minute), Surface: config.WorkflowPromptActivitySurfacePulsePatrol, PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop},+ {Timestamp: recent.Add(-2*time.Minute - time.Second), Surface: config.WorkflowPromptActivitySurfacePatrolControl, PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop},+ {Timestamp: recent.Add(-3 * time.Minute), Surface: config.WorkflowPromptActivitySurfacePatrolAutonomy, PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop},+ {Timestamp: recent.Add(-4 * time.Minute), Surface: config.WorkflowPromptActivitySurfaceProActivation, PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop},+ {Timestamp: recent.Add(-2 * time.Minute), Surface: config.WorkflowPromptActivitySurfacePulseAssistant, PromptName: agentcapabilities.PulseWorkflowPromptTriageFleet},+ {Timestamp: old, Surface: config.WorkflowPromptActivitySurfacePulseAssistant, PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop},+ }); err != nil {+ t.Fatalf("SaveWorkflowPromptActivityHistory: %v", err)+ }++ expiredAt := now.Add(-time.Minute)+ cfg := &config.Config{+ APITokens: []config.APITokenRecord{+ {Scopes: []string{config.ScopeWildcard}, CreatedAt: recent},+ {Scopes: []string{config.ScopeWildcard}, ExpiresAt: &expiredAt, CreatedAt: recent},+ },+ }++ snap := telemetry.Snapshot{PaidLicense: true}+ actions := telemetry.PulseIntelligenceActionSnapshot{+ ActionPlans30d: 4,+ ApprovalRequests30d: 2,+ RejectedActionDecisions30d: 1,+ ApprovedActionDecisions30d: 1,+ ApprovedActionAttempts30d: 1,+ ApprovedActionSuccesses30d: 1,+ }+ applyPulseIntelligenceTelemetrySnapshot(&snap, persistence, cfg, actions, now)++ if snap.PulseIntelligenceAssistantAICalls30d != 3 {+ t.Fatalf("assistant AI calls = %d, want 3", snap.PulseIntelligenceAssistantAICalls30d)+ }+ if snap.PulseIntelligenceAssistantContextAICalls30d != 2 {+ t.Fatalf("assistant context AI calls = %d, want 2", snap.PulseIntelligenceAssistantContextAICalls30d)+ }+ if snap.PulseIntelligenceAssistantToolCalls30d != 5 {+ t.Fatalf("assistant tool calls = %d, want 5", snap.PulseIntelligenceAssistantToolCalls30d)+ }+ if snap.PulseIntelligencePatrolAICalls30d != 1 {+ t.Fatalf("patrol AI calls = %d, want 1", snap.PulseIntelligencePatrolAICalls30d)+ }+ if snap.PulseIntelligencePatrolRuns30d != 2 {+ t.Fatalf("patrol runs = %d, want 2", snap.PulseIntelligencePatrolRuns30d)+ }+ if snap.PulseIntelligencePatrolNewFindings30d != 5 {+ t.Fatalf("patrol new findings = %d, want 5", snap.PulseIntelligencePatrolNewFindings30d)+ }+ if snap.PulseIntelligencePatrolInvestigations30d != 3 {+ t.Fatalf("patrol investigations = %d, want 3", snap.PulseIntelligencePatrolInvestigations30d)+ }+ if snap.PulseIntelligencePatrolResolvedFindings30d != 2 {+ t.Fatalf("patrol resolved findings = %d, want 2", snap.PulseIntelligencePatrolResolvedFindings30d)+ }+ if snap.PulseIntelligencePatrolAutofixes30d != 1 {+ t.Fatalf("patrol autofixes = %d, want 1", snap.PulseIntelligencePatrolAutofixes30d)+ }+ if !snap.PulseIntelligenceExternalAgentEnabled || !snap.PulseIntelligenceExternalAgentUsed30d {+ t.Fatalf("external-agent booleans = enabled %v used %v, want true/true", snap.PulseIntelligenceExternalAgentEnabled, snap.PulseIntelligenceExternalAgentUsed30d)+ }+ if !snap.PulseIntelligenceExternalAgentOperationsLoopReady {+ t.Fatalf("wildcard token should make the Pulse MCP operations loop ready: %#v", snap)+ }+ if !snap.PulseIntelligenceMCPAdapterUsed30d {+ t.Fatalf("MCP adapter use should be true when a recent pulse_mcp activity marker exists: %#v", snap)+ }+ if snap.PulseIntelligenceExternalAgentContextRequests30d != 2 ||+ snap.PulseIntelligenceExternalAgentEventStreamRequests30d != 1 ||+ snap.PulseIntelligenceExternalAgentProvisioningRequests30d != 1 ||+ snap.PulseIntelligenceExternalAgentOperatorStateRequests30d != 1 ||+ snap.PulseIntelligenceExternalAgentFindingRequests30d != 2 ||+ snap.PulseIntelligenceExternalAgentActionRequests30d != 4 {+ t.Fatalf("external-agent class counters not applied: %#v", snap)+ }+ if snap.PulseIntelligenceActionPlans30d != 4 ||+ snap.PulseIntelligenceApprovalRequests30d != 2 ||+ snap.PulseIntelligenceRejectedActionDecisions30d != 1 ||+ snap.PulseIntelligenceApprovedActionDecisions30d != 1 ||+ snap.PulseIntelligenceApprovedActionAttempts30d != 1 ||+ snap.PulseIntelligenceApprovedActionSuccesses30d != 1 {+ t.Fatalf("action telemetry = %#v, want action plans 4, approval requests 2, rejected decisions 1, approved decisions 1, approved attempts 1, approved successes 1", snap)+ }+ if snap.PulseIntelligenceOperationsLoopStarterRequests30d != 6 ||+ snap.PulseIntelligenceAssistantOperationsLoopStarterRequests30d != 1 ||+ snap.PulseIntelligencePatrolOperationsLoopStarterRequests30d != 1 ||+ snap.PulseIntelligencePatrolControlOperationsLoopStarterRequests30d != 4 ||+ snap.PulseIntelligenceProActivationOperationsLoopStarterRequests30d != 2 ||+ snap.PulseIntelligenceMCPOperationsLoopStarterRequests30d != 1 {+ t.Fatalf("workflow starter telemetry = %#v, want total 6, assistant 1, patrol 1, patrol-control 4, legacy pro activation 2, mcp 1", snap)+ }+ if !snap.PulseIntelligenceLoopConfigured {+ t.Fatalf("Pulse Intelligence loop should be configured when an external-agent token exists: %#v", snap)+ }+ if !snap.PulseIntelligenceLoopActive30d {+ t.Fatalf("Pulse Intelligence loop should be active when recent Assistant, Patrol, external-agent, or action activity exists: %#v", snap)+ }+ if !snap.PulseIntelligenceCompleteOperationsLoop30d {+ t.Fatalf("Pulse Intelligence complete operations loop should be active when Patrol issue evidence, contextual collaboration, and governed action decisions all exist: %#v", snap)+ }+ if !snap.PulseIntelligenceApprovedExecutionLoop30d {+ t.Fatalf("Pulse Intelligence approved-execution loop should be active when the complete loop includes an approved action attempt: %#v", snap)+ }+ if !snap.PulseIntelligenceResolvedOperationsLoop30d {+ t.Fatalf("Pulse Intelligence resolved operations loop should be active when contextual collaboration, approved success, and Patrol resolution all exist: %#v", snap)+ }+ if !snap.PulseIntelligencePatrolControlResolvedOperationsLoop30d {+ t.Fatalf("Patrol-control resolved operations loop should be active when Patrol-control starter, issue evidence, contextual collaboration, approved decision, and verified outcome all exist: %#v", snap)+ }+ if !snap.PulseIntelligencePatrolControlCompletedOperationsLoop30d {+ t.Fatalf("Patrol-control completed operations loop should be active when Patrol-control starter, issue evidence, contextual collaboration, and terminal decision proof all exist: %#v", snap)+ }+ if !snap.PulseIntelligencePatrolControlPaidCompletedOperationsLoop30d ||+ !snap.PulseIntelligencePatrolControlPaidResolvedOperationsLoop30d {+ t.Fatalf("paid Patrol-control loop cohorts should be active when paid posture and Patrol-control proof coexist: %#v", snap)+ }+ if !snap.PulseIntelligenceProActivationCompletedOperationsLoop30d ||+ !snap.PulseIntelligenceProActivationResolvedOperationsLoop30d ||+ !snap.PulseIntelligenceProActivationPaidCompletedOperationsLoop30d ||+ !snap.PulseIntelligenceProActivationPaidResolvedOperationsLoop30d {+ t.Fatalf("legacy Pro-activation cohorts should mirror Patrol-control proof for continuity: %#v", snap)+ }+ if !snap.PulseIntelligenceGovernedActionActive30d {+ t.Fatalf("Pulse Intelligence governed-action loop should be active when recent action/approval records exist: %#v", snap)+ }+ if !snap.PulseIntelligenceAssistantOperationsLoop30d ||+ !snap.PulseIntelligenceAssistantApprovedExecutionLoop30d ||+ !snap.PulseIntelligenceAssistantApprovedActionSuccessLoop30d ||+ !snap.PulseIntelligenceAssistantResolvedOperationsLoop30d {+ t.Fatalf("Assistant source-specific loop evidence should be active when Assistant collaboration completes the loop: %#v", snap)+ }+ if !snap.PulseIntelligenceExternalAgentOperationsLoop30d ||+ !snap.PulseIntelligenceExternalAgentApprovedExecutionLoop30d ||+ !snap.PulseIntelligenceExternalAgentApprovedActionSuccessLoop30d ||+ !snap.PulseIntelligenceExternalAgentResolvedOperationsLoop30d {+ t.Fatalf("external-agent source-specific loop evidence should be active when external-agent collaboration completes the loop: %#v", snap)+ }+ if !snap.PulseIntelligenceMCPAdapterOperationsLoop30d ||+ !snap.PulseIntelligenceMCPAdapterApprovedExecutionLoop30d ||+ !snap.PulseIntelligenceMCPAdapterApprovedActionSuccessLoop30d ||+ !snap.PulseIntelligenceMCPAdapterResolvedOperationsLoop30d {+ t.Fatalf("MCP adapter source-specific loop evidence should be active when pulse-mcp collaboration completes the loop: %#v", snap)+ }+}++func TestApplyPulseIntelligenceTelemetrySnapshot_OperationsLoopStarterIsActiveNotComplete(t *testing.T) {+ now := time.Date(2026, 6, 20, 9, 30, 0, 0, time.UTC)+ persistence := config.NewConfigPersistence(t.TempDir())+ if err := persistence.SaveWorkflowPromptActivityHistory([]config.WorkflowPromptActivityRecord{{+ Timestamp: now.Add(-time.Hour),+ Surface: config.WorkflowPromptActivitySurfacePulseAssistant,+ PromptName: agentcapabilities.PulseWorkflowPromptOperationsLoop,+ }}); err != nil {+ t.Fatalf("SaveWorkflowPromptActivityHistory: %v", err)+ }++ snap := telemetry.Snapshot{AIEnabled: true}+ applyPulseIntelligenceTelemetrySnapshot(&snap, persistence, nil, telemetry.PulseIntelligenceActionSnapshot{}, now)++ if snap.PulseIntelligenceOperationsLoopStarterRequests30d != 1 ||+ snap.PulseIntelligenceAssistantOperationsLoopStarterRequests30d != 1 ||+ snap.PulseIntelligencePatrolOperationsLoopStarterRequests30d != 0 ||+ snap.PulseIntelligencePatrolControlOperationsLoopStarterRequests30d != 0 ||+ snap.PulseIntelligenceProActivationOperationsLoopStarterRequests30d != 0 ||+ snap.PulseIntelligenceMCPOperationsLoopStarterRequests30d != 0 {+ t.Fatalf("workflow starter telemetry = %#v, want one assistant operation-loop starter", snap)+ }+ if !snap.PulseIntelligenceLoopConfigured || !snap.PulseIntelligenceLoopActive30d {+ t.Fatalf("starter use should configure and activate the Pulse Intelligence loop when AI is enabled: %#v", snap)+ }+ if snap.PulseIntelligenceCompleteOperationsLoop30d ||+ snap.PulseIntelligenceApprovedExecutionLoop30d ||+ snap.PulseIntelligenceResolvedOperationsLoop30d ||+ snap.PulseIntelligencePatrolControlCompletedOperationsLoop30d ||+ snap.PulseIntelligencePatrolControlResolvedOperationsLoop30d ||+ snap.PulseIntelligenceProActivationCompletedOperationsLoop30d ||+ snap.PulseIntelligenceProActivationResolvedOperationsLoop30d ||+ snap.PulseIntelligenceGovernedActionActive30d ||+ snap.PulseIntelligenceAssistantOperationsLoop30d ||+ snap.PulseIntelligenceAssistantApprovedExecutionLoop30d ||+ snap.PulseIntelligenceAssistantApprovedActionSuccessLoop30d ||+ snap.PulseIntelligenceAssistantResolvedOperationsLoop30d ||+ snap.PulseIntelligenceExternalAgentOperationsLoop30d ||+ snap.PulseIntelligenceExternalAgentApprovedExecutionLoop30d ||+ snap.PulseIntelligenceExternalAgentApprovedActionSuccessLoop30d ||+ snap.PulseIntelligenceExternalAgentResolvedOperationsLoop30d ||+ snap.PulseIntelligenceMCPAdapterOperationsLoop30d ||+ snap.PulseIntelligenceMCPAdapterApprovedExecutionLoop30d ||+ snap.PulseIntelligenceMCPAdapterApprovedActionSuccessLoop30d ||+ snap.PulseIntelligenceMCPAdapterResolvedOperationsLoop30d {+ t.Fatalf("starter-only activity must not satisfy completed, approved, resolved, or governed action loops: %#v", snap)+ }+}++func TestApplyPulseIntelligenceAdoptionSnapshot_PatrolControlResolvedRequiresStatusProof(t *testing.T) {+ base := telemetry.Snapshot{+ PulseIntelligencePatrolControlOperationsLoopStarterRequests30d: 1,+ PulseIntelligencePatrolNewFindings30d: 1,+ PulseIntelligenceAssistantContextAICalls30d: 1,+ PulseIntelligenceApprovedActionDecisions30d: 1,+ PulseIntelligenceApprovedActionSuccesses30d: 1,+ PulseIntelligenceExternalAgentEnabled: true,+ PulseIntelligenceExternalAgentOperationsLoopReady: true,+ }++ tests := []struct {+ name string+ mut func(*telemetry.Snapshot)+ want bool+ }{+ {+ name: "complete status proof",+ want: true,+ },+ {+ name: "missing Patrol-control starter",+ mut: func(snap *telemetry.Snapshot) {+ snap.PulseIntelligencePatrolControlOperationsLoopStarterRequests30d = 0+ },+ },+ {+ name: "missing patrol issue evidence",+ mut: func(snap *telemetry.Snapshot) {+ snap.PulseIntelligencePatrolNewFindings30d = 0+ },+ },+ {+ name: "missing contextual collaboration",+ mut: func(snap *telemetry.Snapshot) {+ snap.PulseIntelligenceAssistantContextAICalls30d = 0+ },+ },+ {+ name: "approved success without approved decision",+ mut: func(snap *telemetry.Snapshot) {+ snap.PulseIntelligenceApprovedActionDecisions30d = 0+ },+ },+ {+ name: "approved decision without verified outcome",+ mut: func(snap *telemetry.Snapshot) {+ snap.PulseIntelligenceApprovedActionSuccesses30d = 0+ },+ },+ {+ name: "MCP readiness is not required",+ mut: func(snap *telemetry.Snapshot) {+ snap.PulseIntelligenceExternalAgentOperationsLoopReady = false+ },+ want: true,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ snap := base+ if tt.mut != nil {+ tt.mut(&snap)+ }++ applyPulseIntelligenceAdoptionSnapshot(&snap)++ if snap.PulseIntelligencePatrolControlResolvedOperationsLoop30d != tt.want {+ t.Fatalf("PulseIntelligencePatrolControlResolvedOperationsLoop30d = %v, want %v: %#v",+ snap.PulseIntelligencePatrolControlResolvedOperationsLoop30d,+ tt.want,+ snap,+ )+ }+ if snap.PulseIntelligenceProActivationResolvedOperationsLoop30d != snap.PulseIntelligencePatrolControlResolvedOperationsLoop30d {+ t.Fatalf("legacy Pro-activation resolved loop should mirror Patrol-control proof: %#v", snap)+ }+ })+ }+}++func TestApplyPulseIntelligenceAdoptionSnapshot_PatrolControlCompletedIncludesRejectedDecision(t *testing.T) {+ base := telemetry.Snapshot{+ PulseIntelligencePatrolControlOperationsLoopStarterRequests30d: 1,+ PulseIntelligencePatrolNewFindings30d: 1,+ PulseIntelligenceAssistantContextAICalls30d: 1,+ PulseIntelligenceRejectedActionDecisions30d: 1,+ PulseIntelligenceExternalAgentEnabled: true,+ PulseIntelligenceExternalAgentOperationsLoopReady: true,+ }++ tests := []struct {+ name string+ mut func(*telemetry.Snapshot)+ want bool+ }{+ {+ name: "rejected governed decision completes the Patrol-control loop",+ want: true,+ },+ {+ name: "approved decision needs verified outcome",+ mut: func(snap *telemetry.Snapshot) {+ snap.PulseIntelligenceRejectedActionDecisions30d = 0+ snap.PulseIntelligenceApprovedActionDecisions30d = 1+ },+ },+ {+ name: "approved decision with verified outcome completes the Patrol-control loop",+ mut: func(snap *telemetry.Snapshot) {+ snap.PulseIntelligenceRejectedActionDecisions30d = 0+ snap.PulseIntelligenceApprovedActionDecisions30d = 1+ snap.PulseIntelligenceApprovedActionSuccesses30d = 1+ },+ want: true,+ },+ {+ name: "starter is required",+ mut: func(snap *telemetry.Snapshot) {+ snap.PulseIntelligencePatrolControlOperationsLoopStarterRequests30d = 0+ },+ },+ {+ name: "patrol issue evidence is required",+ mut: func(snap *telemetry.Snapshot) {+ snap.PulseIntelligencePatrolNewFindings30d = 0+ },+ },+ {+ name: "contextual collaboration is required",+ mut: func(snap *telemetry.Snapshot) {+ snap.PulseIntelligenceAssistantContextAICalls30d = 0+ },+ },+ {+ name: "MCP readiness is not required",+ mut: func(snap *telemetry.Snapshot) {+ snap.PulseIntelligenceExternalAgentOperationsLoopReady = false+ },+ want: true,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ snap := base+ if tt.mut != nil {+ tt.mut(&snap)+ }++ applyPulseIntelligenceAdoptionSnapshot(&snap)++ if snap.PulseIntelligencePatrolControlCompletedOperationsLoop30d != tt.want {+ t.Fatalf("PulseIntelligencePatrolControlCompletedOperationsLoop30d = %v, want %v: %#v",+ snap.PulseIntelligencePatrolControlCompletedOperationsLoop30d,+ tt.want,+ snap,+ )+ }+ if snap.PulseIntelligenceProActivationCompletedOperationsLoop30d != snap.PulseIntelligencePatrolControlCompletedOperationsLoop30d {+ t.Fatalf("legacy Pro-activation completed loop should mirror Patrol-control proof: %#v", snap)+ }+ if snap.PulseIntelligencePatrolControlResolvedOperationsLoop30d && snap.PulseIntelligenceRejectedActionDecisions30d > 0 {+ t.Fatalf("rejected terminal decision must not set resolved-loop proof: %#v", snap)+ }+ })+ }+}++func TestApplyPulseIntelligenceAdoptionSnapshot_PaidPatrolControlCohortsRequirePaidLicense(t *testing.T) {+ verified := telemetry.Snapshot{+ PulseIntelligencePatrolControlOperationsLoopStarterRequests30d: 1,+ PulseIntelligencePatrolNewFindings30d: 1,+ PulseIntelligenceAssistantContextAICalls30d: 1,+ PulseIntelligenceApprovedActionDecisions30d: 1,+ PulseIntelligenceApprovedActionSuccesses30d: 1,+ PulseIntelligenceExternalAgentEnabled: true,+ PulseIntelligenceExternalAgentOperationsLoopReady: true,+ }+ rejected := telemetry.Snapshot{+ PulseIntelligencePatrolControlOperationsLoopStarterRequests30d: 1,+ PulseIntelligencePatrolNewFindings30d: 1,+ PulseIntelligenceAssistantContextAICalls30d: 1,+ PulseIntelligenceRejectedActionDecisions30d: 1,+ PulseIntelligenceExternalAgentEnabled: true,+ PulseIntelligenceExternalAgentOperationsLoopReady: true,+ }++ tests := []struct {+ name string+ snapshot telemetry.Snapshot+ wantCompleted bool+ wantResolved bool+ }{+ {+ name: "paid verified loop records paid completed and paid resolved cohorts",+ snapshot: func() telemetry.Snapshot { s := verified; s.PaidLicense = true; return s }(),+ wantCompleted: true,+ wantResolved: true,+ },+ {+ name: "paid rejected terminal loop records paid completed only",+ snapshot: func() telemetry.Snapshot { s := rejected; s.PaidLicense = true; return s }(),+ wantCompleted: true,+ },+ {+ name: "free verified loop does not record paid cohorts",+ snapshot: verified,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ snap := tt.snapshot++ applyPulseIntelligenceAdoptionSnapshot(&snap)++ if snap.PulseIntelligencePatrolControlPaidCompletedOperationsLoop30d != tt.wantCompleted {+ t.Fatalf("PulseIntelligencePatrolControlPaidCompletedOperationsLoop30d = %v, want %v: %#v",+ snap.PulseIntelligencePatrolControlPaidCompletedOperationsLoop30d,+ tt.wantCompleted,+ snap,+ )+ }+ if snap.PulseIntelligencePatrolControlPaidResolvedOperationsLoop30d != tt.wantResolved {+ t.Fatalf("PulseIntelligencePatrolControlPaidResolvedOperationsLoop30d = %v, want %v: %#v",+ snap.PulseIntelligencePatrolControlPaidResolvedOperationsLoop30d,+ tt.wantResolved,+ snap,+ )+ }+ if snap.PulseIntelligenceProActivationPaidCompletedOperationsLoop30d != snap.PulseIntelligencePatrolControlPaidCompletedOperationsLoop30d ||+ snap.PulseIntelligenceProActivationPaidResolvedOperationsLoop30d != snap.PulseIntelligencePatrolControlPaidResolvedOperationsLoop30d {+ t.Fatalf("legacy Pro-activation paid cohorts should mirror Patrol-control paid cohorts: %#v", snap)+ }+ })+ }+}++func TestPulseIntelligenceExternalAgentActivityRecognizesContentFreeCollaboration(t *testing.T) {+ if pulseIntelligenceExternalAgentActivity(nil) {+ t.Fatal("nil snapshot should not report external-agent activity")+ }+ if !pulseIntelligenceExternalAgentActivity(&telemetry.Snapshot{+ PulseIntelligenceExternalAgentContextRequests30d: 1,+ }) {+ t.Fatal("context request count should report external-agent collaboration")+ }+ if !pulseIntelligenceExternalAgentActivity(&telemetry.Snapshot{+ PulseIntelligenceMCPAdapterUsed30d: true,+ }) {+ t.Fatal("MCP adapter marker should report external-agent collaboration")+ }+}++func TestApplyPulseIntelligenceTelemetrySnapshot_DoesNotPromoteOrdinaryAIToken(t *testing.T) {+ now := time.Date(2026, 6, 20, 9, 30, 0, 0, time.UTC)+ lastUsed := now.Add(-time.Hour)+ cfg := &config.Config{+ APITokens: []config.APITokenRecord{+ {Scopes: []string{config.ScopeAIChat}, LastUsedAt: &lastUsed, CreatedAt: now.Add(-2 * time.Hour)},+ },+ }++ snap := telemetry.Snapshot{}+ applyPulseIntelligenceTelemetrySnapshot(&snap, nil, cfg, telemetry.PulseIntelligenceActionSnapshot{}, now)++ if snap.PulseIntelligenceExternalAgentEnabled || snap.PulseIntelligenceExternalAgentUsed30d {+ t.Fatalf("ordinary AI token should not be treated as external-agent capable: %#v", snap)+ }+ if snap.PulseIntelligenceLoopConfigured || snap.PulseIntelligenceLoopActive30d ||+ snap.PulseIntelligenceCompleteOperationsLoop30d ||+ snap.PulseIntelligenceApprovedExecutionLoop30d ||+ snap.PulseIntelligenceResolvedOperationsLoop30d ||+ snap.PulseIntelligenceGovernedActionActive30d {+ t.Fatalf("ordinary AI token should not set Pulse Intelligence adoption state: %#v", snap)+ }+}++func TestApplyPulseIntelligenceTelemetrySnapshot_PromotesReadOnlyMCPTokenAsConfiguredOnly(t *testing.T) {+ now := time.Date(2026, 6, 20, 9, 30, 0, 0, time.UTC)+ expiredAt := now.Add(-time.Minute)+ cfg := &config.Config{+ APITokens: []config.APITokenRecord{+ {Scopes: []string{config.ScopeMonitoringRead}, CreatedAt: now.Add(-2 * time.Hour)},+ {Scopes: []string{config.ScopeSettingsWrite}, ExpiresAt: &expiredAt, CreatedAt: now.Add(-3 * time.Hour)},+ },+ }++ snap := telemetry.Snapshot{}+ applyPulseIntelligenceTelemetrySnapshot(&snap, config.NewConfigPersistence(t.TempDir()), cfg, telemetry.PulseIntelligenceActionSnapshot{}, now)++ if !snap.PulseIntelligenceExternalAgentEnabled {+ t.Fatalf("read-only MCP-capable token should configure the external-agent surface: %#v", snap)+ }+ if snap.PulseIntelligenceExternalAgentOperationsLoopReady {+ t.Fatalf("read-only MCP-capable token must not satisfy full operations-loop readiness: %#v", snap)+ }+ if snap.PulseIntelligenceExternalAgentUsed30d {+ t.Fatalf("configured MCP-capable token should not count as external-agent activity without route activity: %#v", snap)+ }+ if !snap.PulseIntelligenceLoopConfigured ||+ snap.PulseIntelligenceLoopActive30d ||+ snap.PulseIntelligenceCompleteOperationsLoop30d ||+ snap.PulseIntelligenceApprovedExecutionLoop30d ||+ snap.PulseIntelligenceResolvedOperationsLoop30d {+ t.Fatalf("configured but unused MCP-capable token should configure, not activate, the Pulse Intelligence loop: %#v", snap)+ }+}++func TestApplyPulseIntelligenceTelemetrySnapshot_PromotesFullMCPTokenAsOperationsLoopReady(t *testing.T) {+ now := time.Date(2026, 6, 20, 9, 30, 0, 0, time.UTC)+ cfg := &config.Config{+ APITokens: []config.APITokenRecord{+ {+ Scopes: pulseIntelligenceExternalAgentSurfaceScopes(agentcapabilities.CanonicalManifest()),+ CreatedAt: now.Add(-2 * time.Hour),+ },+ },+ }++ snap := telemetry.Snapshot{}+ applyPulseIntelligenceTelemetrySnapshot(&snap, config.NewConfigPersistence(t.TempDir()), cfg, telemetry.PulseIntelligenceActionSnapshot{}, now)++ if !snap.PulseIntelligenceExternalAgentEnabled ||+ !snap.PulseIntelligenceExternalAgentOperationsLoopReady {+ t.Fatalf("full Pulse MCP token should configure and ready the operations loop: %#v", snap)+ }+}++func TestApplyPulseIntelligenceTelemetrySnapshot_DoesNotCombinePartialMCPTokensForOperationsLoopReadiness(t *testing.T) {+ now := time.Date(2026, 6, 20, 9, 30, 0, 0, time.UTC)+ surfaceScopes := pulseIntelligenceExternalAgentSurfaceScopes(agentcapabilities.CanonicalManifest())+ if len(surfaceScopes) < 2 {+ t.Fatalf("Pulse MCP operations loop should require multiple scopes, got %v", surfaceScopes)+ }+ cfg := &config.Config{+ APITokens: []config.APITokenRecord{+ {Scopes: []string{surfaceScopes[0]}, CreatedAt: now.Add(-2 * time.Hour)},+ {Scopes: []string{surfaceScopes[1]}, CreatedAt: now.Add(-time.Hour)},+ },+ }++ snap := telemetry.Snapshot{}+ applyPulseIntelligenceTelemetrySnapshot(&snap, config.NewConfigPersistence(t.TempDir()), cfg, telemetry.PulseIntelligenceActionSnapshot{}, now)++ if !snap.PulseIntelligenceExternalAgentEnabled {+ t.Fatalf("partial Pulse MCP tokens should still configure the external-agent surface: %#v", snap)+ }+ if snap.PulseIntelligenceExternalAgentOperationsLoopReady {+ t.Fatalf("split partial Pulse MCP tokens must not satisfy full operations-loop readiness: %#v", snap)+ }+}++func TestApplyPulseIntelligenceTelemetrySnapshot_DoesNotInferExternalAgentUsageFromGenericTokenLastUse(t *testing.T) {+ now := time.Date(2026, 6, 20, 9, 30, 0, 0, time.UTC)+ lastUsed := now.Add(-time.Hour)+ cfg := &config.Config{+ APITokens: []config.APITokenRecord{+ {Scopes: []string{config.ScopeWildcard}, LastUsedAt: &lastUsed, CreatedAt: now.Add(-2 * time.Hour)},+ },+ }++ snap := telemetry.Snapshot{}+ applyPulseIntelligenceTelemetrySnapshot(&snap, config.NewConfigPersistence(t.TempDir()), cfg, telemetry.PulseIntelligenceActionSnapshot{}, now)++ if !snap.PulseIntelligenceExternalAgentEnabled {+ t.Fatalf("external-agent capable token should configure the surface: %#v", snap)+ }+ if !snap.PulseIntelligenceExternalAgentOperationsLoopReady {+ t.Fatalf("wildcard token should satisfy full operations-loop readiness: %#v", snap)+ }+ if snap.PulseIntelligenceExternalAgentUsed30d {+ t.Fatalf("generic token last-use should not count as external-agent activity without route activity: %#v", snap)+ }+ if !snap.PulseIntelligenceLoopConfigured ||+ snap.PulseIntelligenceLoopActive30d ||+ snap.PulseIntelligenceCompleteOperationsLoop30d ||+ snap.PulseIntelligenceApprovedExecutionLoop30d ||+ snap.PulseIntelligenceResolvedOperationsLoop30d {+ t.Fatalf("configured but unused external-agent surface should not activate the 30-day loop: %#v", snap)+ }+}++func TestApplyPulseIntelligenceTelemetrySnapshot_DerivesConfiguredWithoutRecentActivity(t *testing.T) {+ now := time.Date(2026, 6, 20, 9, 30, 0, 0, time.UTC)++ snap := telemetry.Snapshot{+ AIEnabled: true,+ PatrolEnabled: true,+ AIActionsEnabled: true,+ }+ applyPulseIntelligenceTelemetrySnapshot(&snap, nil, nil, telemetry.PulseIntelligenceActionSnapshot{}, now)++ if !snap.PulseIntelligenceLoopConfigured {+ t.Fatalf("enabled Assistant/Patrol/action settings should configure the Pulse Intelligence loop: %#v", snap)+ }+ if snap.PulseIntelligenceLoopActive30d {+ t.Fatalf("configured settings without recent usage should not count as 30-day activity: %#v", snap)+ }+ if snap.PulseIntelligenceCompleteOperationsLoop30d {+ t.Fatalf("configured settings without recent usage should not count as complete operations-loop activity: %#v", snap)+ }+ if snap.PulseIntelligenceApprovedExecutionLoop30d {+ t.Fatalf("configured settings without recent usage should not count as approved-execution loop activity: %#v", snap)+ }+ if snap.PulseIntelligenceResolvedOperationsLoop30d {+ t.Fatalf("configured settings without recent usage should not count as resolved operations-loop activity: %#v", snap)+ }+ if snap.PulseIntelligenceGovernedActionActive30d {+ t.Fatalf("enabled action settings without action audit records should not count as governed-action activity: %#v", snap)+ }+}++func TestApplyPulseIntelligenceAdoptionSnapshot_SourceSpecificLoopEvidence(t *testing.T) {+ tests := []struct {+ name string+ snap telemetry.Snapshot+ wantAssistantLoop bool+ wantAssistantResolved bool+ wantExternalLoop bool+ wantExternalResolved bool+ wantMCPLoop bool+ wantMCPResolved bool+ }{+ {+ name: "assistant collaboration stays first party",+ snap: telemetry.Snapshot{+ PulseIntelligencePatrolNewFindings30d: 1,+ PulseIntelligencePatrolResolvedFindings30d: 1,+ PulseIntelligenceAssistantContextAICalls30d: 1,+ PulseIntelligenceApprovalRequests30d: 1,+ PulseIntelligenceApprovedActionDecisions30d: 1,+ PulseIntelligenceApprovedActionAttempts30d: 1,+ PulseIntelligenceApprovedActionSuccesses30d: 1,+ },+ wantAssistantLoop: true,+ wantAssistantResolved: true,+ },+ {+ name: "external agent activity stays outside mcp subset",+ snap: telemetry.Snapshot{+ PulseIntelligencePatrolNewFindings30d: 1,+ PulseIntelligencePatrolResolvedFindings30d: 1,+ PulseIntelligenceExternalAgentContextRequests30d: 1,+ PulseIntelligenceApprovalRequests30d: 1,+ PulseIntelligenceApprovedActionDecisions30d: 1,+ PulseIntelligenceApprovedActionAttempts30d: 1,+ PulseIntelligenceApprovedActionSuccesses30d: 1,+ },+ wantExternalLoop: true,+ wantExternalResolved: true,+ },+ {+ name: "pulse mcp is the mcp subset and external-agent umbrella",+ snap: telemetry.Snapshot{+ PulseIntelligencePatrolNewFindings30d: 1,+ PulseIntelligencePatrolResolvedFindings30d: 1,+ PulseIntelligenceMCPAdapterUsed30d: true,+ PulseIntelligenceApprovalRequests30d: 1,+ PulseIntelligenceApprovedActionDecisions30d: 1,+ PulseIntelligenceApprovedActionAttempts30d: 1,+ PulseIntelligenceApprovedActionSuccesses30d: 1,+ },+ wantExternalLoop: true,+ wantExternalResolved: true,+ wantMCPLoop: true,+ wantMCPResolved: true,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ snap := tt.snap+ applyPulseIntelligenceAdoptionSnapshot(&snap)+ if snap.PulseIntelligenceAssistantOperationsLoop30d != tt.wantAssistantLoop ||+ snap.PulseIntelligenceAssistantApprovedExecutionLoop30d != tt.wantAssistantLoop ||+ snap.PulseIntelligenceAssistantApprovedActionSuccessLoop30d != tt.wantAssistantResolved ||+ snap.PulseIntelligenceAssistantResolvedOperationsLoop30d != tt.wantAssistantResolved {+ t.Fatalf("Assistant loop evidence mismatch: %#v", snap)+ }+ if snap.PulseIntelligenceExternalAgentOperationsLoop30d != tt.wantExternalLoop ||+ snap.PulseIntelligenceExternalAgentApprovedExecutionLoop30d != tt.wantExternalLoop ||+ snap.PulseIntelligenceExternalAgentApprovedActionSuccessLoop30d != tt.wantExternalResolved ||+ snap.PulseIntelligenceExternalAgentResolvedOperationsLoop30d != tt.wantExternalResolved {+ t.Fatalf("external-agent loop evidence mismatch: %#v", snap)+ }+ if snap.PulseIntelligenceMCPAdapterOperationsLoop30d != tt.wantMCPLoop ||+ snap.PulseIntelligenceMCPAdapterApprovedExecutionLoop30d != tt.wantMCPLoop ||+ snap.PulseIntelligenceMCPAdapterApprovedActionSuccessLoop30d != tt.wantMCPResolved ||+ snap.PulseIntelligenceMCPAdapterResolvedOperationsLoop30d != tt.wantMCPResolved {+ t.Fatalf("MCP adapter loop evidence mismatch: %#v", snap)+ }+ })+ }+}++func TestApplyPulseIntelligenceAdoptionSnapshot_CompleteLoopRequiresIssueEvidenceCollaborationAndDecision(t *testing.T) {+ tests := []struct {+ name string+ snap telemetry.Snapshot+ wantActive bool+ wantComplete bool+ wantApproved bool+ wantResolved bool+ }{+ {+ name: "generic assistant and governed action is active but incomplete",+ snap: telemetry.Snapshot{+ PulseIntelligenceAssistantAICalls30d: 3,+ PulseIntelligenceActionPlans30d: 1,+ },+ wantActive: true,+ wantComplete: false,+ wantApproved: false,+ wantResolved: false,+ },+ {+ name: "patrol and governed action without contextual collaboration is incomplete",+ snap: telemetry.Snapshot{+ PulseIntelligencePatrolRuns30d: 1,+ PulseIntelligenceActionPlans30d: 1,+ },+ wantActive: true,+ wantComplete: false,+ wantApproved: false,+ wantResolved: false,+ },+ {+ name: "patrol and contextual collaboration without governed action is incomplete",+ snap: telemetry.Snapshot{+ PulseIntelligencePatrolRuns30d: 1,+ PulseIntelligenceAssistantContextAICalls30d: 1,+ },+ wantActive: true,+ wantComplete: false,+ wantApproved: false,+ wantResolved: false,+ },+ {+ name: "patrol run assistant tool collaboration and approval request is active but incomplete",+ snap: telemetry.Snapshot{+ PulseIntelligencePatrolRuns30d: 1,+ PulseIntelligenceAssistantToolCalls30d: 2,+ PulseIntelligenceApprovalRequests30d: 1,+ },+ wantActive: true,+ wantComplete: false,+ wantApproved: false,+ wantResolved: false,+ },+ {+ name: "patrol issue assistant collaboration and rejected action decision completes governed action only",+ snap: telemetry.Snapshot{+ PulseIntelligencePatrolNewFindings30d: 1,+ PulseIntelligenceAssistantContextAICalls30d: 1,+ PulseIntelligenceRejectedActionDecisions30d: 1,+ },+ wantActive: true,+ wantComplete: true,+ wantApproved: false,+ wantResolved: false,+ },+ {+ name: "patrol issue assistant collaboration and approved action decision completes without execution",+ snap: telemetry.Snapshot{+ PulseIntelligencePatrolNewFindings30d: 1,+ PulseIntelligenceAssistantContextAICalls30d: 1,+ PulseIntelligenceApprovedActionDecisions30d: 1,+ },+ wantActive: true,+ wantComplete: true,+ wantApproved: false,+ wantResolved: false,+ },+ {+ name: "generic patrol run with approved action attempt remains incomplete without issue evidence",+ snap: telemetry.Snapshot{+ PulseIntelligencePatrolRuns30d: 1,+ PulseIntelligenceExternalAgentUsed30d: true,+ PulseIntelligenceApprovedActionAttempts30d: 1,+ },+ wantActive: true,+ wantComplete: false,+ wantApproved: false,+ wantResolved: false,+ },+ {+ name: "patrol issue external-agent collaboration and governed action completes the loop",+ snap: telemetry.Snapshot{+ PulseIntelligencePatrolNewFindings30d: 1,+ PulseIntelligenceExternalAgentUsed30d: true,+ PulseIntelligenceApprovedActionAttempts30d: 1,+ },+ wantActive: true,+ wantComplete: true,+ wantApproved: true,+ wantResolved: false,+ },+ {+ name: "patrol issue external-agent capability activity and governed action completes the loop",+ snap: telemetry.Snapshot{+ PulseIntelligencePatrolNewFindings30d: 1,+ PulseIntelligenceExternalAgentContextRequests30d: 1,+ PulseIntelligenceApprovedActionAttempts30d: 1,+ },+ wantActive: true,+ wantComplete: true,+ wantApproved: true,+ wantResolved: false,+ },+ {+ name: "patrol issue MCP adapter collaboration and governed action completes the loop",+ snap: telemetry.Snapshot{+ PulseIntelligencePatrolNewFindings30d: 1,+ PulseIntelligenceMCPAdapterUsed30d: true,+ PulseIntelligenceApprovedActionAttempts30d: 1,+ },+ wantActive: true,+ wantComplete: true,+ wantApproved: true,+ wantResolved: false,+ },+ {+ name: "external-agent capability activity without patrol is active but incomplete",+ snap: telemetry.Snapshot{+ PulseIntelligenceExternalAgentActionRequests30d: 1,+ },+ wantActive: true,+ wantComplete: false,+ wantApproved: false,+ wantResolved: false,+ },+ {+ name: "patrol AI call assistant context and approval request is active but incomplete",+ snap: telemetry.Snapshot{+ PulseIntelligencePatrolAICalls30d: 1,+ PulseIntelligenceAssistantContextAICalls30d: 1,+ PulseIntelligenceApprovalRequests30d: 1,+ },+ wantActive: true,+ wantComplete: false,+ wantApproved: false,+ wantResolved: false,+ },+ {+ name: "patrol investigation assistant context and approval request waits for a decision",+ snap: telemetry.Snapshot{+ PulseIntelligencePatrolInvestigations30d: 1,+ PulseIntelligenceAssistantContextAICalls30d: 1,+ PulseIntelligenceApprovalRequests30d: 1,+ },+ wantActive: true,+ wantComplete: false,+ wantApproved: false,+ wantResolved: false,+ },+ {+ name: "resolved operations loop requires patrol resolution collaboration and approved success",+ snap: telemetry.Snapshot{+ PulseIntelligencePatrolResolvedFindings30d: 1,+ PulseIntelligenceAssistantContextAICalls30d: 1,+ PulseIntelligenceApprovedActionAttempts30d: 1,+ PulseIntelligenceApprovedActionSuccesses30d: 1,+ },+ wantActive: true,+ wantComplete: true,+ wantApproved: true,+ wantResolved: true,+ },+ {+ name: "patrol resolution without governed action decision does not complete or resolve the operations loop",+ snap: telemetry.Snapshot{+ PulseIntelligencePatrolResolvedFindings30d: 1,+ PulseIntelligenceAssistantContextAICalls30d: 1,+ PulseIntelligenceApprovalRequests30d: 1,+ },+ wantActive: true,+ wantComplete: false,+ wantApproved: false,+ wantResolved: false,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ snap := tt.snap+ applyPulseIntelligenceAdoptionSnapshot(&snap)+ if snap.PulseIntelligenceLoopActive30d != tt.wantActive {+ t.Fatalf("PulseIntelligenceLoopActive30d = %v, want %v: %#v",+ snap.PulseIntelligenceLoopActive30d,+ tt.wantActive,+ snap,+ )+ }+ if snap.PulseIntelligenceCompleteOperationsLoop30d != tt.wantComplete {+ t.Fatalf("PulseIntelligenceCompleteOperationsLoop30d = %v, want %v: %#v",+ snap.PulseIntelligenceCompleteOperationsLoop30d,+ tt.wantComplete,+ snap,+ )+ }+ if snap.PulseIntelligenceApprovedExecutionLoop30d != tt.wantApproved {+ t.Fatalf("PulseIntelligenceApprovedExecutionLoop30d = %v, want %v: %#v",+ snap.PulseIntelligenceApprovedExecutionLoop30d,+ tt.wantApproved,+ snap,+ )+ }+ if snap.PulseIntelligenceResolvedOperationsLoop30d != tt.wantResolved {+ t.Fatalf("PulseIntelligenceResolvedOperationsLoop30d = %v, want %v: %#v",+ snap.PulseIntelligenceResolvedOperationsLoop30d,+ tt.wantResolved,+ snap,+ )+ }+ })+ }+}diff --git a/scripts/generate-pulse-intelligence-docs.go b/scripts/generate-pulse-intelligence-docs.gonew file mode 100644index 0000000000..b0392946c9--- /dev/null+++ b/scripts/generate-pulse-intelligence-docs.go@@ -0,0 +1,125 @@+package main++import (+ "fmt"+ "os"+ "path/filepath"+ "strings"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+)++func main() {+ if err := regeneratePulseIntelligenceDocs(); err != nil {+ fmt.Fprintf(os.Stderr, "generate-pulse-intelligence-docs: %v\n", err)+ os.Exit(1)+ }+}++func regeneratePulseIntelligenceDocs() error {+ manifest := agentcapabilities.CanonicalManifest()+ if err := regeneratePulseMCPReadme(filepath.Join("cmd", "pulse-mcp", "README.md"), manifest); err != nil {+ return err+ }+ if err := regeneratePublicPulseIntelligenceOverview(filepath.Join("docs", "AI.md"), manifest); err != nil {+ return err+ }+ return nil+}++func regeneratePulseMCPReadme(path string, manifest agentcapabilities.Manifest) error {+ raw, err := os.ReadFile(path)+ if err != nil {+ return fmt.Errorf("read %s: %w", path, err)+ }++ content := string(raw)+ replacements := []struct {+ start string+ end string+ body string+ }{+ {+ start: agentcapabilities.MCPReadmeSurfaceContractStartMarker,+ end: agentcapabilities.MCPReadmeSurfaceContractEndMarker,+ body: agentcapabilities.MCPSurfaceContractMarkdown(manifest.SurfaceContract),+ },+ {+ start: agentcapabilities.MCPReadmeScopeListStartMarker,+ end: agentcapabilities.MCPReadmeScopeListEndMarker,+ body: agentcapabilities.ManifestRequiredScopeMarkdownList(manifest),+ },+ {+ start: agentcapabilities.MCPReadmeClientConfigStartMarker,+ end: agentcapabilities.MCPReadmeClientConfigEndMarker,+ body: agentcapabilities.MCPClientConfigMarkdown(manifest.MCPAdapter),+ },+ {+ start: agentcapabilities.MCPReadmeToolInventoryStartMarker,+ end: agentcapabilities.MCPReadmeToolInventoryEndMarker,+ body: agentcapabilities.MCPToolCapabilityInventoryMarkdown(manifest),+ },+ {+ start: agentcapabilities.MCPReadmePromptInventoryStartMarker,+ end: agentcapabilities.MCPReadmePromptInventoryEndMarker,+ body: agentcapabilities.MCPPromptInventoryMarkdown(manifest),+ },+ {+ start: agentcapabilities.MCPReadmeErrorInventoryStartMarker,+ end: agentcapabilities.MCPReadmeErrorInventoryEndMarker,+ body: agentcapabilities.MCPErrorCodeInventoryMarkdown(manifest),+ },+ }++ var replaceErr error+ for _, replacement := range replacements {+ content, replaceErr = replaceMarkedBlock(content, replacement.start, replacement.end, replacement.body)+ if replaceErr != nil {+ return replaceErr+ }+ }+ if content == string(raw) {+ return nil+ }+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {+ return fmt.Errorf("write %s: %w", path, err)+ }+ return nil+}++func regeneratePublicPulseIntelligenceOverview(path string, manifest agentcapabilities.Manifest) error {+ raw, err := os.ReadFile(path)+ if err != nil {+ return fmt.Errorf("read %s: %w", path, err)+ }+ content, err := replaceMarkedBlock(+ string(raw),+ agentcapabilities.PulseIntelligenceOverviewStartMarker,+ agentcapabilities.PulseIntelligenceOverviewEndMarker,+ agentcapabilities.PulseIntelligenceOverviewMarkdown(manifest.SurfaceContract),+ )+ if err != nil {+ return err+ }+ if content == string(raw) {+ return nil+ }+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {+ return fmt.Errorf("write %s: %w", path, err)+ }+ return nil+}++func replaceMarkedBlock(content, startMarker, endMarker, body string) (string, error) {+ start := strings.Index(content, startMarker)+ if start < 0 {+ return "", fmt.Errorf("missing marker %s", startMarker)+ }+ bodyStart := start + len(startMarker)+ end := strings.Index(content[bodyStart:], endMarker)+ if end < 0 {+ return "", fmt.Errorf("missing marker %s", endMarker)+ }+ bodyEnd := bodyStart + end+ return content[:bodyStart] + "\n" + strings.TrimSpace(body) + "\n" + content[bodyEnd:], nil+}diff --git a/scripts/generate-types.go b/scripts/generate-types.goindex f01f94e12a..f1ada8f62e 100644--- a/scripts/generate-types.go+++ b/scripts/generate-types.go@@ -1,7 +1,9 @@// Generates TypeScript types for frontend consumption from Go types.//-// Currently this focuses on Pulse Assistant chat SSE event payloads.-// Source of truth: internal/ai/chat event data structs.+// Currently this covers Pulse Assistant chat SSE event payloads and the+// Pulse Intelligence agent capabilities discovery manifest.+// Sources of truth: internal/ai/chat event data structs and+// internal/agentcapabilities manifest structs.//// Usage://@@ -10,6 +12,7 @@// Output://// frontend-modern/src/api/generated/aiChatEvents.ts+// frontend-modern/src/api/generated/agentCapabilities.ts//go:build ignorepackage main@@ -23,6 +26,7 @@ import ("sort""strings"+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/ai/chat")@@ -32,9 +36,7 @@ type tsTypeDef struct {}func main() {- outPath := filepath.Join("frontend-modern", "src", "api", "generated", "aiChatEvents.ts")-- defs := []reflect.Type{+ chatDefs := []reflect.Type{reflect.TypeOf(chat.ContentData{}),reflect.TypeOf(chat.ThinkingData{}),reflect.TypeOf(chat.WorkflowStateData{}),@@ -54,24 +56,90 @@ func main() {reflect.TypeOf(chat.ErrorData{}),}- tsDefs := make([]tsTypeDef, 0, len(defs)+4)+ if err := writeTypeScriptDefinitions(+ filepath.Join("frontend-modern", "src", "api", "generated", "aiChatEvents.ts"),+ "internal/ai/chat event payload structs.",+ chatDefs,+ "",+ chatStreamEventUnion(),+ ); err != nil {+ fatal(err)+ }++ agentCapabilityDefs := []reflect.Type{+ reflect.TypeOf(agentcapabilities.Capability{}),+ reflect.TypeOf(agentcapabilities.CapabilityCategory{}),+ reflect.TypeOf(agentcapabilities.Manifest{}),+ reflect.TypeOf(agentcapabilities.MCPAdapterConfigFamily{}),+ reflect.TypeOf(agentcapabilities.MCPAdapterContract{}),+ reflect.TypeOf(agentcapabilities.OperatorSurfaceContract{}),+ reflect.TypeOf(agentcapabilities.PulseWorkflowPrompt{}),+ reflect.TypeOf(agentcapabilities.PulseWorkflowPromptArgument{}),+ reflect.TypeOf(agentcapabilities.SurfaceAffordanceContract{}),+ reflect.TypeOf(agentcapabilities.SurfaceContract{}),+ reflect.TypeOf(agentcapabilities.SurfaceContractComponent{}),+ reflect.TypeOf(agentcapabilities.SurfaceToolContract{}),+ }++ if err := writeTypeScriptDefinitions(+ filepath.Join("frontend-modern", "src", "api", "generated", "agentCapabilities.ts"),+ "internal/agentcapabilities manifest structs.",+ agentCapabilityDefs,+ agentCapabilitiesAliases(),+ "",+ ); err != nil {+ fatal(err)+ }+}++func writeTypeScriptDefinitions(outPath, source string, defs []reflect.Type, extraHeader, extraFooter string) error {+ tsDefs := make([]tsTypeDef, 0, len(defs))for _, t := range defs {tsDefs = append(tsDefs, tsTypeDef{Name: t.Name(), Body: renderInterface(t)})}-// Sort for stable output.sort.Slice(tsDefs, func(i, j int) bool { return tsDefs[i].Name < tsDefs[j].Name })var buf bytes.Buffer- buf.WriteString("// Code generated by scripts/generate-types.go; DO NOT EDIT.\n")- buf.WriteString("// Source: internal/ai/chat event payload structs.\n\n")+ buf.WriteString("// This file is generated from scripts/generate-types.go; DO NOT EDIT.\n")+ buf.WriteString("// Source: ")+ buf.WriteString(source)+ buf.WriteString("\n\n")buf.WriteString("/* eslint-disable */\n\n")+ if extraHeader != "" {+ buf.WriteString(extraHeader)+ if !strings.HasSuffix(extraHeader, "\n\n") {+ buf.WriteString("\n\n")+ }+ }for _, d := range tsDefs {buf.WriteString(d.Body)buf.WriteString("\n\n")}+ if extraFooter != "" {+ buf.WriteString(extraFooter)+ }++ if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil {+ return err+ }+ content := bytes.TrimRight(buf.Bytes(), "\n")+ content = append(content, '\n')+ if err := os.WriteFile(outPath, content, 0o644); err != nil {+ return err+ }+ return nil+}++func fatal(err error) {+ fmt.Fprintln(os.Stderr, err.Error())+ os.Exit(1)+}++func chatStreamEventUnion() string {+ var buf strings.Builder// Stream event union matches internal/api/contract_test.go snapshots.buf.WriteString("export type AIChatStreamEvent =\n")buf.WriteString(" | { type: 'session'; data: SessionData }\n")@@ -89,18 +157,14 @@ func main() {buf.WriteString(" | { type: 'question'; data: QuestionData & { session_id?: string } }\n")buf.WriteString(" | { type: 'done'; data?: DoneData }\n")buf.WriteString(" | { type: 'error'; data: ErrorData };\n")-- if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil {- fatal(err)- }- if err := os.WriteFile(outPath, buf.Bytes(), 0o644); err != nil {- fatal(err)- }+ return buf.String()}-func fatal(err error) {- fmt.Fprintln(os.Stderr, err.Error())- os.Exit(1)+func agentCapabilitiesAliases() string {+ return strings.Join([]string{+ "export type AgentCapabilityActionMode = 'read' | 'mixed' | 'write';",+ "export type AgentCapabilityApprovalPolicy = 'scope_only' | 'action_plan';",+ }, "\n") + "\n\n"}func renderInterface(t reflect.Type) string {@@ -161,6 +225,17 @@ func jsonFieldName(f reflect.StructField) (name string, optional bool) {}func goTypeToTS(t reflect.Type) string {+ if t.PkgPath() == "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities" {+ switch t.Name() {+ case "ActionMode":+ return "AgentCapabilityActionMode"+ case "ApprovalPolicy":+ return "AgentCapabilityApprovalPolicy"+ }+ }+ if t.PkgPath() == "encoding/json" && t.Name() == "RawMessage" {+ return "Record<string, unknown>"+ }switch t.Kind() {case reflect.String:return "string"diff --git a/scripts/hot-dev-bg.sh b/scripts/hot-dev-bg.shindex 2c1d1b28ff..1c52fb2a7d 100755--- a/scripts/hot-dev-bg.sh+++ b/scripts/hot-dev-bg.sh@@ -26,6 +26,7 @@ DEFAULT_HOT_DEV_BG_PID_FILE="${ROOT_DIR}/tmp/hot-dev.bg.pid"PID_FILE="${HOT_DEV_BG_PID_FILE:-${DEFAULT_HOT_DEV_BG_PID_FILE}}"LOG_FILE="${HOT_DEV_BG_LOG_FILE:-${ROOT_DIR}/tmp/hot-dev.bg.log}"HOT_DEV_VERIFY_LOCK="${HOT_DEV_VERIFY_LOCK_FILE:-${ROOT_DIR}/tmp/hot-dev.verify.lock}"+HOT_DEV_LAB_MODE_FILE="${HOT_DEV_LAB_MODE_FILE:-${ROOT_DIR}/tmp/hot-dev.lab-agents-mode}"hot_dev_configure_network_defaults@@ -579,6 +580,7 @@ start_hot_dev_child() {PULSE_ENABLE_PROXMOX_GUEST_DOCKER_DETECTION="${PULSE_ENABLE_PROXMOX_GUEST_DOCKER_DETECTION:-}" \PULSE_ENABLE_PROXMOX_GUEST_DOCKER_INVENTORY="${PULSE_ENABLE_PROXMOX_GUEST_DOCKER_INVENTORY:-}" \PULSE_PROXMOX_GUEST_DOCKER_INVENTORY_VMIDS="${PULSE_PROXMOX_GUEST_DOCKER_INVENTORY_VMIDS:-}" \+ HOT_DEV_LAB_MODE_FILE="${HOT_DEV_LAB_MODE_FILE:-}" \HOT_DEV_SKIP_NPM_CLEANUP=true \ROOT_DIR="${ROOT_DIR}" \python3 - <<'PY' &@@ -667,6 +669,7 @@ spawn_detached_supervisor() {PULSE_ENABLE_PROXMOX_GUEST_DOCKER_DETECTION="${PULSE_ENABLE_PROXMOX_GUEST_DOCKER_DETECTION:-}" \PULSE_ENABLE_PROXMOX_GUEST_DOCKER_INVENTORY="${PULSE_ENABLE_PROXMOX_GUEST_DOCKER_INVENTORY:-}" \PULSE_PROXMOX_GUEST_DOCKER_INVENTORY_VMIDS="${PULSE_PROXMOX_GUEST_DOCKER_INVENTORY_VMIDS:-}" \+ HOT_DEV_LAB_MODE_FILE="${HOT_DEV_LAB_MODE_FILE:-}" \ROOT_DIR="${ROOT_DIR}" \LOG_FILE="${LOG_FILE}" \HOT_DEV_BG_SCRIPT="${ROOT_DIR}/scripts/hot-dev-bg.sh" \diff --git a/scripts/hot-dev.sh b/scripts/hot-dev.shindex 2170860711..d6bed9a28d 100755--- a/scripts/hot-dev.sh+++ b/scripts/hot-dev.sh@@ -57,6 +57,8 @@ source "${SCRIPT_DIR}/lib/hot-dev-auth.sh"# shellcheck disable=SC1091source "${SCRIPT_DIR}/lib/hot-dev-runtime.sh"+HOT_DEV_LAB_MODE_FILE="${HOT_DEV_LAB_MODE_FILE:-${ROOT_DIR}/tmp/hot-dev.lab-agents-mode}"+# --- Helper Functions ---log_info() { printf "\033[0;34m[hot-dev]\033[0m %s\n" "$1"; }@@ -362,6 +364,7 @@ PULSE_AUTH_PASS="$(hot_dev_resolve_auth_pass)"export FRONTEND_PORT PULSE_DEV_API_PORT PORT PULSE_DEV ALLOW_ADMIN_BYPASS PULSE_AUTH_USER PULSE_AUTH_PASS LOG_LEVEL PULSE_DEV_DISABLE_BACKGROUND_AIexport PULSE_DEV_LAN PULSE_DEV_LAB_AGENTS BIND_ADDRESS ALLOWED_ORIGINSexport PULSE_ENABLE_PROXMOX_GUEST_DOCKER_DETECTION PULSE_ENABLE_PROXMOX_GUEST_DOCKER_INVENTORY PULSE_PROXMOX_GUEST_DOCKER_INVENTORY_VMIDS+export HOT_DEV_LAB_MODE_FILE# Data Directory Setup# Mock and real mode use SEPARATE data directories so switching between themdiff --git a/scripts/installtests/build_release_assets_test.go b/scripts/installtests/build_release_assets_test.goindex bb25c1b01d..5f30ff1eda 100644--- a/scripts/installtests/build_release_assets_test.go+++ b/scripts/installtests/build_release_assets_test.go@@ -962,6 +962,7 @@ func TestBuildReleasePackagesPulseMcpForAllPlatforms(t *testing.T) {// publish them as the canonical curl-pipe-bash entry// point.`cp scripts/install-mcp.sh "$RELEASE_DIR/install-mcp.sh"`,+ `[ -f scripts/install-mcp.ps1 ] && cp scripts/install-mcp.ps1 "$RELEASE_DIR/install-mcp.ps1"`,}for _, needle := range required {if !strings.Contains(script, needle) {@@ -1000,6 +1001,22 @@ func TestBuildReleasePackagesPulseMcpForAllPlatforms(t *testing.T) {t.Fatalf("install-mcp.sh missing required helper or guard: %s", needle)}}++ mcpPowerShell, err := os.ReadFile(repoFile("scripts", "install-mcp.ps1"))+ if err != nil {+ t.Fatalf("read install-mcp.ps1: %v", err)+ }+ for _, needle := range []string{+ `function Resolve-Architecture`,+ `PULSE_MCP_NO_VERIFY`,+ `checksums.txt`,+ `Get-FileHash -Path $tmp -Algorithm SHA256`,+ `sha256 mismatch`,+ } {+ if !strings.Contains(string(mcpPowerShell), needle) {+ t.Fatalf("install-mcp.ps1 missing required helper or guard: %s", needle)+ }+ }}// The release-pipeline downstream workflows and private Pro publication pathdiff --git a/scripts/lib/hot-dev-runtime.sh b/scripts/lib/hot-dev-runtime.shindex faa42da3c3..e4bdf57ba9 100644--- a/scripts/lib/hot-dev-runtime.sh+++ b/scripts/lib/hot-dev-runtime.sh@@ -64,7 +64,58 @@ hot_dev_lab_agents_enabled() {hot_dev_truthy "${PULSE_DEV_LAB_AGENTS:-false}"}+hot_dev_lab_agent_mode_file_enabled() {+ local mode_file="${HOT_DEV_LAB_MODE_FILE:-}"++ [[ -n "${mode_file}" && -r "${mode_file}" ]] || return 1+ grep -Eq '^[[:space:]]*PULSE_DEV_LAB_AGENTS[[:space:]]*=[[:space:]]*true[[:space:]]*$' "${mode_file}"+}++hot_dev_remember_lab_agent_mode() {+ local mode_file="${HOT_DEV_LAB_MODE_FILE:-}"++ [[ -n "${mode_file}" ]] || return 0+ mkdir -p "$(dirname "${mode_file}")"+ {+ printf '# Managed by Pulse hot-dev. Remove this file or set PULSE_DEV_LAB_AGENTS=false to return to loopback-only dev.\n'+ printf 'PULSE_DEV_LAB_AGENTS=true\n'+ } > "${mode_file}"+}++hot_dev_clear_remembered_lab_agent_mode() {+ local mode_file="${HOT_DEV_LAB_MODE_FILE:-}"++ [[ -n "${mode_file}" ]] || return 0+ rm -f "${mode_file}" 2>/dev/null || true+}++hot_dev_apply_remembered_lab_agent_mode() {+ if [[ -n "${PULSE_DEV_LAB_AGENTS+x}" ]]; then+ if hot_dev_lab_agents_enabled; then+ hot_dev_remember_lab_agent_mode+ else+ hot_dev_clear_remembered_lab_agent_mode+ fi+ return 0+ fi++ if [[ -n "${PULSE_DEV_LAN+x}" ]] && ! hot_dev_lan_enabled; then+ hot_dev_clear_remembered_lab_agent_mode+ return 0+ fi++ if hot_dev_lab_agent_mode_file_enabled; then+ PULSE_DEV_LAB_AGENTS=true+ export PULSE_DEV_LAB_AGENTS+ if declare -F log_warn >/dev/null 2>&1; then+ log_warn "Remembered lab-agent mode is enabled for this workspace. Starting with LAN agent access; set PULSE_DEV_LAB_AGENTS=false once to return to loopback-only dev."+ fi+ fi+}+hot_dev_apply_lab_agent_defaults() {+ hot_dev_apply_remembered_lab_agent_mode+if ! hot_dev_lab_agents_enabled; thenreturn 0fidiff --git a/scripts/release_control/ai_runtime_docs_policy_test.py b/scripts/release_control/ai_runtime_docs_policy_test.pyindex c7e06e97e6..2136097e07 100644--- a/scripts/release_control/ai_runtime_docs_policy_test.py+++ b/scripts/release_control/ai_runtime_docs_policy_test.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""Guard public AI docs against retired commercial AI shorthand."""+"""Guard public Pulse Intelligence docs against retired AI shorthand."""from __future__ import annotations@@ -7,11 +7,22 @@ import unittestfrom repo_file_io import read_repo_text+PUBLIC_AI_DOC_PATHS = (+ "docs/AI.md",+ "docs/AI_AUTONOMY.md",+ "docs/API.md",+ "docs/FAQ.md",+ "docs/PULSE_PRO.md",+ "docs/README.md",+)+class AIRuntimeDocsPolicyTest(unittest.TestCase):def test_public_ai_overview_uses_productized_context_language(self) -> None:content = read_repo_text("docs/AI.md")+ normalized_content = " ".join(content.split())+ self.assertIn("# Pulse Intelligence", content)self.assertIn("Uses prior alert context, Patrol run history, and resource timelines",content,@@ -19,12 +30,78 @@ class AIRuntimeDocsPolicyTest(unittest.TestCase):self.assertIn("Investigation Context", content)self.assertIn("the configured LLM owns diagnosis", content)self.assertIn(- "Pulse supplies context, tools, safety gates, approval state, and audit trails",+ "Pulse supplies context, capabilities, safety gates, approval state, and audit trails",content,)+ self.assertIn("shared **Pulse Intelligence Core**", content)+ self.assertIn("<!-- pulse-intelligence-overview:start -->", content)+ self.assertIn("<!-- pulse-intelligence-overview:end -->", content)+ self.assertIn(+ "Canonical context, governed actions, safety gates, approval state, action audit, and verification",+ normalized_content,+ )+ self.assertIn("Patrol as the primary built-in operator", normalized_content)+ self.assertIn(+ "Pulse Patrol**: Patrol is the first-party operations surface: it watches, investigates, acts within the chosen Patrol mode, verifies outcomes, and records what happened.",+ normalized_content,+ )+ self.assertIn(+ "Pulse Assistant**: The contextual explanation, approval, and handoff surface for Patrol findings, governed actions, verification, and operator questions. Affordances: tools and interactive questions.",+ normalized_content,+ )+ self.assertIn(+ "Pulse MCP**: The external-agent adapter that projects canonical Pulse Intelligence capabilities as MCP tools. Affordances: tools, resources, prompts, and capability metadata.",+ normalized_content,+ )+ self.assertIn("Pulse MCP", content)+ self.assertIn("### Tool Inventory", content)+ self.assertIn("The Assistant tool list is registry-owned at runtime", content)+ self.assertIn(+ "Each turn receives an available-tool manifest generated from Pulse's governed tool registry",+ normalized_content,+ )+ self.assertIn(+ "tool-result handling, approval boundaries, and Patrol-only tool filtering",+ normalized_content,+ )+ self.assertIn(+ "use the live `/api/agent/capabilities` manifest or `pulse-mcp` `tools/list`",+ normalized_content,+ )+ self.assertIn(+ "The same manifest also carries reusable `workflowPrompts` metadata",+ normalized_content,+ )+ self.assertIn(+ "Pulse Assistant-compatible starters and MCP `prompts/list` clients discover the same fleet triage, resource investigation, and Patrol finding review workflows",+ normalized_content,+ )+ self.assertIn(+ "Pulse Assistant and `pulse-mcp` are sibling surfaces over Pulse Intelligence",+ normalized_content,+ )+ self.assertIn("Patrol mode and governed Pulse Intelligence operations", normalized_content)+ self.assertIn("not competing implementations, and neither replaces the other", normalized_content)+ self.assertIn(+ "New operational capabilities should be added to the canonical API manifest first",+ normalized_content,+ )+ self.assertIn(+ "MCP-only actions and Assistant-only copies of the same business logic are drift",+ normalized_content,+ )+ self.assertNotIn("two supported operator-facing surfaces", normalized_content)+ self.assertNotIn("Pulse Assistant should be replaced by", normalized_content)+ self.assertNotIn("MCP replaces Pulse Assistant", normalized_content)+ self.assertNotIn("Assistant can be removed", normalized_content)+ self.assertIn("- **Anthropic** (API key)", content)+ self.assertIn("Anthropic OAuth is not a supported runtime authentication method", normalized_content)+ self.assertIn("does not make Anthropic configured", normalized_content)self.assertIn("go run ./cmd/eval -scenario resource-context", content)self.assertIn("EVAL_RESOURCE_CONTEXT_FORBIDDEN", content)self.assertIn("Pulse does not convert them into Pulse-authored findings", content)+ self.assertNotIn("Anthropic** (API key or OAuth)", content)+ self.assertNotIn("Anthropic API key or OAuth", content)self.assertNotIn("successful remediations (incident memory)", content)self.assertNotIn("**Incident memory**", content)self.assertNotIn("**Incident Memory**", content)@@ -33,11 +110,67 @@ class AIRuntimeDocsPolicyTest(unittest.TestCase):self.assertNotIn("multi-layered intelligence platform", content)self.assertNotIn("capacity predictions", content)self.assertNotIn("Deterministic Signal Detection", content)+ self.assertNotIn("Pulse AI is built", content)+ self.assertNotIn("counts and feature flags only", normalized_content)+ self.assertNotIn("### Available Tools", content)+ self.assertNotIn("| Tool | Classification | Purpose |", content)+ self.assertNotIn("| `pulse_query`, `pulse_discovery` |", content)+ self.assertNotIn("| `patrol_report_finding` | Patrol |", content)self.assertNotIn("active_alert", content)self.assertNotIn("auto-recovery", content)self.assertNotIn('EVAL_RESOURCE_CONTEXT_FORBIDDEN="/mnt/pve/finance-db,/var/lib/homeassistant,secret"', content)self.assertNotRegex(content, r"(?i)understands resources before you ask")+ def test_public_ai_docs_use_current_surface_naming(self) -> None:+ for doc_path in PUBLIC_AI_DOC_PATHS:+ with self.subTest(doc_path=doc_path):+ content = read_repo_text(doc_path)+ self.assertNotIn("Pulse AI", content)+ self.assertNotIn("Settings → System → AI Assistant", content)+ self.assertNotIn("Settings > System > AI Assistant", content)+ self.assertNotIn("Settings > Pulse Assistant", content)++ def test_public_patrol_docs_use_mode_language(self) -> None:+ overview = read_repo_text("docs/AI.md")+ control_doc = read_repo_text("docs/AI_AUTONOMY.md")++ self.assertIn("Pro adds hands-on Patrol modes, issue investigation, governed fixes, verified outcomes, and 90-day history", overview)+ self.assertIn("## Patrol Modes", overview)+ self.assertIn("four modes", overview)+ self.assertIn("**Watch only**", overview)+ self.assertIn("**Ask before changes**", overview)+ self.assertIn("**Auto-fix safe issues**", overview)+ self.assertIn("**Policy autopilot**", overview)+ self.assertIn("When a finding is created in a Pro Patrol mode", overview)+ self.assertIn("**Patrol modes (Pro and above)**", overview)+ self.assertIn("**Governed fixes (Pro and above)**", overview)+ self.assertIn("**Issue investigation (Pro and above)**", overview)+ self.assertIn("Patrol mode and governed Pulse Intelligence operations", overview)+ self.assertNotIn("## Patrol Control Levels", overview)+ self.assertNotIn("four control levels", overview)+ self.assertNotIn("When a finding is created in a Pro control level", overview)+ self.assertNotIn("**Patrol control (Pro and above)**", overview)+ self.assertNotIn("**Alert investigation (Pro and above)**", overview)+ self.assertNotIn("Patrol control and governed Pulse Intelligence operations", overview)+ self.assertNotIn("## Autonomy Levels", overview)+ self.assertNotIn("autonomy modes", overview)++ self.assertIn("# Pulse Intelligence Modes and Safety Configuration", control_doc)+ self.assertIn("**Patrol Mode**", control_doc)+ self.assertIn("Patrol mode is configured on the **Patrol** page.", control_doc)+ self.assertIn("## Patrol Modes", control_doc)+ self.assertIn("Patrol mode sets how far Pulse can go", control_doc)+ self.assertIn("**UI:** Patrol → Patrol mode", control_doc)+ self.assertIn("The API keeps the autonomy_level field name for compatibility.", control_doc)+ self.assertNotIn("Patrol Control Level", control_doc)+ self.assertNotIn("## Patrol Control Levels", control_doc)+ self.assertNotIn("Patrol control is configured on the **Patrol** page.", control_doc)+ self.assertNotIn("Patrol control sets how far Pulse can go", control_doc)+ self.assertNotIn("**UI:** Patrol → Patrol control", control_doc)+ self.assertNotIn("Patrol Autonomy Levels", control_doc)+ self.assertNotIn("Patrol autonomy controls", control_doc)+ self.assertNotIn("Patrol Autonomy Level", control_doc)+if __name__ == "__main__":unittest.main()diff --git a/scripts/release_control/documentation_currentness_test.py b/scripts/release_control/documentation_currentness_test.pyindex bf1fbfac4c..ecdd2342d6 100644--- a/scripts/release_control/documentation_currentness_test.py+++ b/scripts/release_control/documentation_currentness_test.py@@ -123,7 +123,7 @@ class DocumentationCurrentnessTest(unittest.TestCase):pulse_pro_doc = read("docs/PULSE_PRO.md")self.assertIn(- "| **Investigate** | Investigates findings and proposes fixes. All fixes require approval before execution. | Pro / hosted Cloud |",+ "| **Ask before changes** | Investigates findings and proposes fixes. All fixes require approval before execution. | Pro / hosted Cloud |",ai_doc,)self.assertIn(@@ -140,13 +140,17 @@ class DocumentationCurrentnessTest(unittest.TestCase):)self.assertNotIn("Upgrade to Assisted", autonomy_doc)self.assertIn(- "| **Investigate** | Investigates findings and proposes fixes. All remediation actions require approval. | Pro / hosted Cloud |",+ "| **Ask before changes** | Investigates findings and proposes fixes. All fixes require approval before execution. | Pro / hosted Cloud |",pulse_pro_doc,)self.assertNotIn(- "| **Investigate** | Investigates findings and proposes fixes. All remediation actions require approval. | Community / Relay |",+ "| **Ask before changes** | Investigates findings and proposes fixes. All fixes require approval before execution. | Community / Relay |",pulse_pro_doc,)+ for rel in ("docs/AI.md", "docs/PULSE_PRO.md", "docs/FAQ.md", "docs/README.md"):+ content = read(rel)+ self.assertNotIn("alert-triggered root-cause analysis", content)+ self.assertNotIn("safe remediation workflows", content)def test_public_self_hosted_docs_avoid_unlimited_monitoring_claims(self) -> None:public_docs = (diff --git a/scripts/release_control/internal/paid_feature_claims_proof.py b/scripts/release_control/internal/paid_feature_claims_proof.pyindex 9bffadc622..e1fb4a93bb 100644--- a/scripts/release_control/internal/paid_feature_claims_proof.py+++ b/scripts/release_control/internal/paid_feature_claims_proof.py@@ -63,8 +63,8 @@ PUBLIC_COPY_AUDIT_FILES: tuple[CopyAuditFileSpec, ...] = (r"monitored[-\s]system volume is no longer the paid gate",r"Relay.*14[-\s]day history",r"Pro.*90[-\s]day history",- r"Alert-triggered root-cause analysis",- r"Safe remediation workflows",+ r"Patrol investigates issues",+ r"Patrol handles safe fixes",),),CopyAuditFileSpec(@@ -72,7 +72,7 @@ PUBLIC_COPY_AUDIT_FILES: tuple[CopyAuditFileSpec, ...] = (relative_path="docs/AI.md",required_patterns=(r"Pulse Patrol is available to everyone on the Community plan with BYOK",- r"Pro adds alert-triggered root-cause analysis and safe remediation workflows",+ r"Pro adds hands-on Patrol modes, issue investigation, governed fixes, verified outcomes, and 90-day history",r"Community and Relay installs can still run scheduled Patrol findings with BYOK",),),@@ -101,10 +101,10 @@ PUBLIC_COPY_AUDIT_FILES: tuple[CopyAuditFileSpec, ...] = (repo="pulse",relative_path="frontend-modern/src/utils/selfHostedPlans.ts",required_patterns=(- r"Self-hosted Pulse includes core monitoring for free",+ r"Self-hosted Pulse includes core monitoring and watch-only Patrol for free",r"Remote web access, pairing, and push",r"14-day metric history",- r"Root-cause analysis, safe remediation workflows, 90-day history",+ r"hands-on Patrol modes, verified fixes, 90-day history",r"admin/reporting extras",),),@@ -115,7 +115,7 @@ PUBLIC_COPY_AUDIT_FILES: tuple[CopyAuditFileSpec, ...] = (r"Relay Tier.*14-day history",r"Pulse Relay.*secure remote access",r"No inbound firewall ports",- r"Self-hosted Pro should be sold on root-cause analysis",+ r"Self-hosted Pro should be sold on hands-on Patrol modes",),),CopyAuditFileSpec(@@ -124,7 +124,7 @@ PUBLIC_COPY_AUDIT_FILES: tuple[CopyAuditFileSpec, ...] = (required_patterns=(r"Community keeps core monitoring free",r"(?:Pulse Mobile|mobile app) pairing(?: for handoff)?, push notifications, and 14-day history",- r"root-cause analysis, safe remediation workflows, and 90-day history",+ r"hands-on Patrol modes, issue investigation, verified fixes, and 90-day history",r"Do Relay or Pro charge by server\?",r"Existing Pulse Pro and legacy Pro\+ holders keep their paid runtime access",),@@ -135,7 +135,7 @@ PUBLIC_COPY_AUDIT_FILES: tuple[CopyAuditFileSpec, ...] = (required_patterns=(r"Community keeps core monitoring free",r"(?:Pulse Mobile|mobile app) pairing(?: for handoff)?, push notifications, and 14-day history",- r"root-cause analysis, safe remediation workflows, team controls, and 90-day history",+ r"hands-on Patrol modes, issue investigation, verified fixes, team controls, and 90-day history",r"not as the self-hosted paid gate",),),diff --git a/scripts/release_control/internal/paid_feature_claims_proof_test.py b/scripts/release_control/internal/paid_feature_claims_proof_test.pyindex b203a446e6..bc966ee7cb 100644--- a/scripts/release_control/internal/paid_feature_claims_proof_test.py+++ b/scripts/release_control/internal/paid_feature_claims_proof_test.py@@ -39,15 +39,15 @@ def write_public_copy_fixture(root: Path) -> tuple[Path, Path]:monitored-system volume is no longer the paid gate.Relay gives 14-day history.Pro gives 90-day history.- Alert-triggered root-cause analysis.- Safe remediation workflows.+ Patrol investigates issues.+ Patrol handles safe fixes.""",encoding="utf-8",)(pulse_dir / "docs" / "AI.md").write_text("""Pulse Patrol is available to everyone on the Community plan with BYOK.- Pro adds alert-triggered root-cause analysis and safe remediation workflows.+ Pro adds hands-on Patrol modes, issue investigation, governed fixes, verified outcomes, and 90-day history.Community and Relay installs can still run scheduled Patrol findings with BYOK.""",encoding="utf-8",@@ -73,10 +73,10 @@ def write_public_copy_fixture(root: Path) -> tuple[Path, Path]:)(pulse_dir / "frontend-modern" / "src" / "utils" / "selfHostedPlans.ts").write_text("""- Self-hosted Pulse includes core monitoring for free.+ Self-hosted Pulse includes core monitoring and watch-only Patrol for free.Remote web access, pairing, and push.14-day metric history.- Root-cause analysis, safe remediation workflows, 90-day history.+ hands-on Patrol modes, verified fixes, 90-day history.admin/reporting extras.""",encoding="utf-8",@@ -86,7 +86,7 @@ def write_public_copy_fixture(root: Path) -> tuple[Path, Path]:Relay Tier includes 14-day history.Pulse Relay provides secure remote access.No inbound firewall ports.- Self-hosted Pro should be sold on root-cause analysis.+ Self-hosted Pro should be sold on hands-on Patrol modes.""",encoding="utf-8",)@@ -94,7 +94,7 @@ def write_public_copy_fixture(root: Path) -> tuple[Path, Path]:"""Community keeps core monitoring free.Pulse Mobile pairing for handoff, push notifications, and 14-day history.- root-cause analysis, safe remediation workflows, and 90-day history.+ hands-on Patrol modes, issue investigation, verified fixes, and 90-day history.Do Relay or Pro charge by server?Existing Pulse Pro and legacy Pro+ holders keep their paid runtime access.""",@@ -104,7 +104,7 @@ def write_public_copy_fixture(root: Path) -> tuple[Path, Path]:"""Community keeps core monitoring free.Pulse Mobile pairing for handoff, push notifications, and 14-day history.- root-cause analysis, safe remediation workflows, team controls, and 90-day history.+ hands-on Patrol modes, issue investigation, verified fixes, team controls, and 90-day history.not as the self-hosted paid gate.""",encoding="utf-8",diff --git a/scripts/release_control/registry_audit_test.py b/scripts/release_control/registry_audit_test.pyindex 0090005f96..8406cee10b 100644--- a/scripts/release_control/registry_audit_test.py+++ b/scripts/release_control/registry_audit_test.py@@ -77,7 +77,7 @@ class RegistryAuditTest(unittest.TestCase):**registry_audit.DEFAULT_CONTROL_PLANE,"subsystems_dir_path": str(contracts_dir),},- ):+ ), patch.dict(os.environ, self.hook_env_for_worktree(linked_worktree), clear=False):files = tracked_workspace_files(active_repos=["pulse"],local_repo=canonical_repo_id(linked_worktree),diff --git a/scripts/release_control/render_release_body_test.py b/scripts/release_control/render_release_body_test.pyindex 7a5abc3420..0ffc923135 100644--- a/scripts/release_control/render_release_body_test.py+++ b/scripts/release_control/render_release_body_test.py@@ -225,6 +225,20 @@ Old metadata section.self.assertIn("/api/agent/capabilities", blurb)self.assertIn("cmd/pulse-mcp", blurb)self.assertIn("cmd/agent-probe", blurb)+ self.assertIn("OpenCode, other MCP clients", blurb)+ self.assertIn("client-ready MCP config snippets", blurb)+ self.assertIn("OpenCode's native", blurb)+ self.assertIn("common `mcpServers` shape", blurb)+ self.assertIn("Drivable from MCP clients in one command", blurb)+ self.assertIn("Wire it into any MCP-speaking client", blurb)+ self.assertIn("manifest `requiredScopes`", blurb)+ self.assertIn("read-only subset", blurb)+ self.assertNotIn("common MCP config snippet", blurb)+ self.assertNotIn("clients that accept\n `mcpServers`", blurb)+ self.assertNotIn("Claude Desktop / Claude Code", blurb)+ self.assertNotIn("Drivable from Claude in one command", blurb)+ self.assertNotIn("adapter for Claude Desktop and Claude Code", blurb)+ self.assertNotIn("`monitoring:read` (and", blurb)# The four-axis frame is the substrate's load-bearing claim;# if any axis name drifts in the blurb, agents reading# release notes will look for a different surface than whatdiff --git a/scripts/release_control/repo_file_io.py b/scripts/release_control/repo_file_io.pyindex e7be4e0171..307cedd6f5 100644--- a/scripts/release_control/repo_file_io.py+++ b/scripts/release_control/repo_file_io.py@@ -96,13 +96,18 @@ def repo_common_dir(git_dir: Path) -> Path | None:def git_env_targets_repo(env: dict[str, str], repo_root: Path) -> bool:- if not any(name in env for name in REPO_TARGET_GIT_ENV_VARS):+ target_vars = {name for name in REPO_TARGET_GIT_ENV_VARS if name in env}+ if not target_vars:return Truerepo_root = repo_root.resolve()work_tree = env.get("GIT_WORK_TREE")if not work_tree:- return False+ # A standalone temporary index is how verify_commit_slice.py runs+ # staged-index checks without mutating the user's real index. It is+ # still scoped by the subprocess cwd. Environments that also carry+ # GIT_DIR/GIT_COMMON_DIR need an explicit worktree to prove identity.+ return target_vars == {"GIT_INDEX_FILE"}try:if resolve_env_path(work_tree, repo_root) != repo_root:diff --git a/scripts/release_control/repo_file_io_test.py b/scripts/release_control/repo_file_io_test.pyindex cdb4ba12a2..f416d53eab 100644--- a/scripts/release_control/repo_file_io_test.py+++ b/scripts/release_control/repo_file_io_test.py@@ -62,6 +62,58 @@ class RepoFileIoTest(unittest.TestCase):self.assertEqual(read_repo_text(rel, staged=True), '{"version": "staged"}\n')self.assertEqual(load_repo_json(rel, staged=True), {"version": "staged"})+ def test_staged_reads_preserve_standalone_temporary_index(self) -> None:+ with tempfile.TemporaryDirectory() as tmpdir:+ repo_root = Path(tmpdir)+ rel = "docs/release-control/v6/internal/status.json"+ path = repo_root / rel+ path.parent.mkdir(parents=True, exist_ok=True)++ self.git(repo_root, "init")+ path.write_text('{"version": "head"}\n', encoding="utf-8")+ self.git(repo_root, "add", rel)+ self.git(+ repo_root,+ "-c",+ "user.name=Pulse Test",+ "-c",+ "[email protected]",+ "commit",+ "-m",+ "initial",+ )++ with tempfile.TemporaryDirectory() as index_tmpdir:+ index_path = Path(index_tmpdir) / "copied-index"+ env = {"PATH": os.environ.get("PATH", ""), "GIT_INDEX_FILE": str(index_path)}+ path.write_text('{"version": "temporary-index"}\n', encoding="utf-8")+ subprocess.run(+ ["git", "read-tree", "HEAD"],+ cwd=repo_root,+ check=True,+ capture_output=True,+ text=True,+ env=env,+ )+ subprocess.run(+ ["git", "add", rel],+ cwd=repo_root,+ check=True,+ capture_output=True,+ text=True,+ env=env,+ )+ path.write_text('{"version": "working-tree"}\n', encoding="utf-8")++ with (+ patch("repo_file_io.REPO_ROOT", repo_root),+ patch("repo_file_io.DEFAULT_REPO_ROOT", repo_root),+ patch.dict(os.environ, env, clear=True),+ ):+ self.assertEqual(read_repo_text(rel), '{"version": "working-tree"}\n')+ self.assertEqual(read_repo_text(rel, staged=True), '{"version": "temporary-index"}\n')+ self.assertEqual(load_repo_json(rel, staged=True), {"version": "temporary-index"})+def test_strict_staged_read_rejects_worktree_only_file(self) -> None:with tempfile.TemporaryDirectory() as tmpdir:repo_root = Path(tmpdir)diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.pyindex 5773efe277..5c0bf07e62 100644--- a/scripts/release_control/subsystem_lookup_test.py+++ b/scripts/release_control/subsystem_lookup_test.py@@ -13,11 +13,13 @@ RECOVERY_PRODUCT_SURFACE_EXACT_FILES = [PATROL_PAGE_AND_STATE_EXACT_FILES = ["frontend-modern/src/components/Brand/__tests__/PulsePatrolLogo.test.tsx",+ "frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceHeader.test.ts","frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts","frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx","frontend-modern/src/stores/__tests__/aiIntelligence.test.ts","frontend-modern/src/stores/__tests__/aiIntelligenceSummaryModel.test.ts","frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts",+ "frontend-modern/src/utils/__tests__/patrolPagePresentation.test.ts","tests/integration/tests/18-patrol-runtime-state.spec.ts","tests/integration/tests/73-patrol-assistant-operator-briefing.spec.ts",]@@ -813,6 +815,32 @@ class SubsystemLookupTest(unittest.TestCase):self.assertEqual(match["lane_context"]["lane_id"], lane_id)self.assertEqual(match["verification_requirement"]["id"], requirement_id)+ def test_lookup_paths_reports_assistant_chat_frontend_client_as_shared_boundary(self) -> None:+ result = lookup_paths(["frontend-modern/src/api/aiChat.ts"])+ self.assertEqual(result["unowned_runtime_files"], [])+ self.assertEqual(+ {item["subsystem"] for item in result["impacted_subsystems"]},+ {"ai-runtime", "api-contracts"},+ )+ file_entry = result["files"][0]+ self.assertEqual(file_entry["classification"], "runtime")+ self.assertEqual(+ {match["subsystem"] for match in file_entry["matches"]},+ {"ai-runtime", "api-contracts"},+ )+ self.assertEqual(+ file_entry["shared_ownership"]["subsystems"],+ ["ai-runtime", "api-contracts"],+ )+ expected = {+ "ai-runtime": ("L6", "ai-api-surface"),+ "api-contracts": ("L6", "frontend-api-clients"),+ }+ for match in file_entry["matches"]:+ lane_id, requirement_id = expected[match["subsystem"]]+ self.assertEqual(match["lane_context"]["lane_id"], lane_id)+ self.assertEqual(match["verification_requirement"]["id"], requirement_id)+def test_lookup_paths_reports_agent_profiles_client_as_shared_boundary(self) -> None:result = lookup_paths(["frontend-modern/src/api/agentProfiles.ts"])self.assertEqual(result["unowned_runtime_files"], [])@@ -1185,6 +1213,33 @@ class SubsystemLookupTest(unittest.TestCase):self.assertEqual(match["lane_context"]["lane_id"], lane_id)self.assertEqual(match["verification_requirement"]["id"], requirement_id)+ def test_lookup_paths_reports_pulse_mcp_adapter_as_shared_boundary(self) -> None:+ result = lookup_paths(["cmd/pulse-mcp", "cmd/pulse-mcp/session_policy.go"])+ self.assertEqual(result["unowned_runtime_files"], [])+ self.assertEqual(+ {item["subsystem"] for item in result["impacted_subsystems"]},+ {"ai-runtime", "api-contracts"},+ )++ directory_entry = result["files"][0]+ self.assertEqual(directory_entry["classification"], "runtime")+ self.assertIsNone(directory_entry["shared_ownership"])++ expected = {+ "ai-runtime": ("L6", "pulse-mcp-adapter"),+ "api-contracts": ("L6", "pulse-mcp-manifest-adapter"),+ }+ for file_entry in result["files"]:+ self.assertEqual(file_entry["classification"], "runtime")+ self.assertEqual(+ {match["subsystem"] for match in file_entry["matches"]},+ {"ai-runtime", "api-contracts"},+ )+ for match in file_entry["matches"]:+ lane_id, requirement_id = expected[match["subsystem"]]+ self.assertEqual(match["lane_context"]["lane_id"], lane_id)+ self.assertEqual(match["verification_requirement"]["id"], requirement_id)+def test_lookup_paths_reports_config_setup_backend_as_shared_boundary(self) -> None:result = lookup_paths(["internal/api/config_setup_handlers.go"])self.assertEqual(result["unowned_runtime_files"], [])@@ -2857,14 +2912,14 @@ class SubsystemLookupTest(unittest.TestCase):self.assertEqual(api_match["matched_contract_references"],[- {- "heading": "## Shared Boundaries",- "path": "internal/api/access_control_handlers.go",- "line": 476,- "heading_line": 123,- }- ],- )+ {+ "heading": "## Shared Boundaries",+ "path": "internal/api/access_control_handlers.go",+ "line": 1047,+ "heading_line": 136,+ }+ ],+ )organization_match = by_subsystem["organization-settings"]self.assertEqual(@@ -2961,6 +3016,36 @@ class SubsystemLookupTest(unittest.TestCase):PATROL_PAGE_AND_STATE_EXACT_FILES,)+ def test_lookup_paths_assigns_patrol_control_presentation_to_patrol_intelligence(+ self,+ ) -> None:+ result = lookup_paths(["frontend-modern/src/features/patrol/patrolControlPresentation.ts"])+ self.assertEqual(result["unowned_runtime_files"], [])+ self.assertEqual(+ {item["subsystem"] for item in result["impacted_subsystems"]},+ {"patrol-intelligence"},+ )+ file_entry = result["files"][0]+ self.assertEqual(file_entry["classification"], "runtime")+ self.assertEqual(+ {match["subsystem"] for match in file_entry["matches"]},+ {"patrol-intelligence"},+ )+ match = file_entry["matches"][0]+ self.assertEqual(+ match["contract"],+ "docs/release-control/v6/internal/subsystems/patrol-intelligence.md",+ )+ self.assertEqual(match["lane_context"]["lane_id"], "L6")+ self.assertEqual(+ match["verification_requirement"]["id"],+ "patrol-page-and-state",+ )+ self.assertEqual(+ match["verification_requirement"]["exact_files"],+ PATROL_PAGE_AND_STATE_EXACT_FILES,+ )+def test_lookup_paths_assigns_patrol_state_hook_to_patrol_intelligence(self) -> None:result = lookup_paths(["frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts"])self.assertEqual(result["unowned_runtime_files"], [])@@ -3311,6 +3396,34 @@ class SubsystemLookupTest(unittest.TestCase):],)+ def test_lookup_paths_assigns_mcp_installers_to_deployment_installability(self) -> None:+ result = lookup_paths(["scripts/install-mcp.sh", "scripts/install-mcp.ps1"])+ self.assertEqual(result["unowned_runtime_files"], [])+ self.assertEqual(+ {item["subsystem"] for item in result["impacted_subsystems"]},+ {"deployment-installability"},+ )+ for file_entry in result["files"]:+ self.assertEqual(file_entry["classification"], "runtime")+ self.assertEqual(+ {match["subsystem"] for match in file_entry["matches"]},+ {"deployment-installability"},+ )+ match = file_entry["matches"][0]+ self.assertEqual(+ match["contract"],+ "docs/release-control/v6/internal/subsystems/deployment-installability.md",+ )+ self.assertEqual(match["lane_context"]["lane_id"], "L1")+ self.assertEqual(+ match["verification_requirement"]["id"],+ "pulse-mcp-installer-release-runtime",+ )+ self.assertEqual(+ match["verification_requirement"]["exact_files"],+ ["scripts/installtests/build_release_assets_test.go"],+ )+def test_lookup_paths_assigns_container_installer_to_deployment_installability(self) -> None:result = lookup_paths(["scripts/install-container-agent.sh"])self.assertEqual(result["unowned_runtime_files"], [])@@ -4119,7 +4232,7 @@ class SubsystemLookupTest(unittest.TestCase):),_contract_reference("docs/release-control/v6/internal/subsystems/ai-runtime.md",- "4. `internal/api/ai_handler.go` shared with `api-contracts`",+ "35. `internal/api/ai_handler.go` shared with `api-contracts`","internal/api/ai_handler.go",),_contract_reference(@@ -4131,17 +4244,17 @@ class SubsystemLookupTest(unittest.TestCase):api_contracts_expected = [_contract_reference("docs/release-control/v6/internal/subsystems/api-contracts.md",- "33. `internal/api/ai_handler.go` shared with `ai-runtime`",+ "63. `internal/api/ai_handler.go` shared with `ai-runtime`","internal/api/ai_handler.go",),_contract_reference("docs/release-control/v6/internal/subsystems/api-contracts.md",- "22. Keep hosted AI settings bootstrap on the shared API contract",+ "23. Keep hosted AI settings bootstrap on the shared API contract","internal/api/ai_handler.go",),_contract_reference("docs/release-control/v6/internal/subsystems/api-contracts.md",- "23. Keep post-boot AI enablement contract-backed on the shared AI/mobile approval surface",+ "24. Keep post-boot AI enablement contract-backed on the shared AI/mobile approval surface","internal/api/ai_handler.go",),]@@ -4175,17 +4288,17 @@ class SubsystemLookupTest(unittest.TestCase):[_contract_reference("docs/release-control/v6/internal/subsystems/api-contracts.md",- "33. `internal/api/ai_handler.go` shared with `ai-runtime`",+ "63. `internal/api/ai_handler.go` shared with `ai-runtime`","internal/api/ai_handler.go",)["line"],_contract_reference("docs/release-control/v6/internal/subsystems/api-contracts.md",- "22. Keep hosted AI settings bootstrap on the shared API contract",+ "23. Keep hosted AI settings bootstrap on the shared API contract","internal/api/ai_handler.go",)["line"],_contract_reference("docs/release-control/v6/internal/subsystems/api-contracts.md",- "23. Keep post-boot AI enablement contract-backed on the shared AI/mobile approval surface",+ "24. Keep post-boot AI enablement contract-backed on the shared AI/mobile approval surface","internal/api/ai_handler.go",)["line"],],@@ -4195,8 +4308,8 @@ class SubsystemLookupTest(unittest.TestCase):rendered = render_pretty(lookup_paths(["internal/api/ai_handler.go"], lean=True))self.assertIn("contract focus: "- f"{_contract_reference('docs/release-control/v6/internal/subsystems/api-contracts.md', '33. `internal/api/ai_handler.go` shared with `ai-runtime`', 'internal/api/ai_handler.go')['heading']} "- f"@L{_contract_reference('docs/release-control/v6/internal/subsystems/api-contracts.md', '33. `internal/api/ai_handler.go` shared with `ai-runtime`', 'internal/api/ai_handler.go')['line']}: "+ f"{_contract_reference('docs/release-control/v6/internal/subsystems/api-contracts.md', '63. `internal/api/ai_handler.go` shared with `ai-runtime`', 'internal/api/ai_handler.go')['heading']} "+ f"@L{_contract_reference('docs/release-control/v6/internal/subsystems/api-contracts.md', '63. `internal/api/ai_handler.go` shared with `ai-runtime`', 'internal/api/ai_handler.go')['line']}: ""internal/api/ai_handler.go",rendered,)diff --git a/scripts/telemetry_adoption_report.py b/scripts/telemetry_adoption_report.pyindex fb76d7ed7a..ca77118757 100644--- a/scripts/telemetry_adoption_report.py+++ b/scripts/telemetry_adoption_report.py@@ -66,6 +66,760 @@ FEATURE_BOOL_FIELDS = (("paid_license", "Paid license"),("has_api_tokens", "Has API tokens"),)+PULSE_INTELLIGENCE_ASSISTANT_LOOP_BOOL_FIELDS = (+ "pulse_intelligence_assistant_operations_loop_30d",+ "pulse_intelligence_assistant_approved_execution_loop_30d",+ "pulse_intelligence_assistant_approved_action_success_loop_30d",+ "pulse_intelligence_assistant_resolved_operations_loop_30d",+)+PULSE_INTELLIGENCE_EXTERNAL_AGENT_LOOP_BOOL_FIELDS = (+ "pulse_intelligence_external_agent_operations_loop_30d",+ "pulse_intelligence_external_agent_approved_execution_loop_30d",+ "pulse_intelligence_external_agent_approved_action_success_loop_30d",+ "pulse_intelligence_external_agent_resolved_operations_loop_30d",+)+PULSE_INTELLIGENCE_MCP_ADAPTER_LOOP_BOOL_FIELDS = (+ "pulse_intelligence_mcp_adapter_operations_loop_30d",+ "pulse_intelligence_mcp_adapter_approved_execution_loop_30d",+ "pulse_intelligence_mcp_adapter_approved_action_success_loop_30d",+ "pulse_intelligence_mcp_adapter_resolved_operations_loop_30d",+)+PULSE_INTELLIGENCE_PATROL_CONTROL_COMPLETED_BOOL_FIELDS = (+ "pulse_intelligence_patrol_control_completed_operations_loop_30d",+ "pulse_intelligence_pro_activation_completed_operations_loop_30d",+)+PULSE_INTELLIGENCE_PATROL_CONTROL_RESOLVED_BOOL_FIELDS = (+ "pulse_intelligence_patrol_control_resolved_operations_loop_30d",+ "pulse_intelligence_pro_activation_resolved_operations_loop_30d",+)+PULSE_INTELLIGENCE_PATROL_CONTROL_PAID_COMPLETED_BOOL_FIELDS = (+ "pulse_intelligence_patrol_control_paid_completed_operations_loop_30d",+ "pulse_intelligence_pro_activation_paid_completed_operations_loop_30d",+)+PULSE_INTELLIGENCE_PATROL_CONTROL_PAID_RESOLVED_BOOL_FIELDS = (+ "pulse_intelligence_patrol_control_paid_resolved_operations_loop_30d",+ "pulse_intelligence_pro_activation_paid_resolved_operations_loop_30d",+)+PULSE_INTELLIGENCE_PATROL_CONTROL_STARTER_COUNT_FIELDS = (+ "pulse_intelligence_patrol_control_operations_loop_starter_requests_30d",+ "pulse_intelligence_patrol_operations_loop_starter_requests_30d",+ "pulse_intelligence_pro_activation_operations_loop_starter_requests_30d",+)+PULSE_INTELLIGENCE_BOOL_FIELDS = (+ ("pulse_intelligence_loop_configured", "Loop configured"),+ ("pulse_intelligence_loop_active_30d", "Loop active 30d"),+ ("pulse_intelligence_complete_operations_loop_30d", "Complete operations loop 30d"),+ ("pulse_intelligence_approved_execution_loop_30d", "Approved execution loop 30d"),+ ("pulse_intelligence_resolved_operations_loop_30d", "Resolved operations loop 30d"),+ (+ "pulse_intelligence_patrol_control_completed_operations_loop_30d",+ "Patrol control completed operations loop 30d",+ ),+ (+ "pulse_intelligence_patrol_control_resolved_operations_loop_30d",+ "Patrol control resolved operations loop 30d",+ ),+ (+ "pulse_intelligence_patrol_control_paid_completed_operations_loop_30d",+ "Patrol control paid completed operations loop 30d",+ ),+ (+ "pulse_intelligence_patrol_control_paid_resolved_operations_loop_30d",+ "Patrol control paid resolved operations loop 30d",+ ),+ (+ "pulse_intelligence_pro_activation_completed_operations_loop_30d",+ "Legacy Pro activation completed operations loop 30d",+ ),+ (+ "pulse_intelligence_pro_activation_resolved_operations_loop_30d",+ "Legacy Pro activation resolved operations loop 30d",+ ),+ (+ "pulse_intelligence_pro_activation_paid_completed_operations_loop_30d",+ "Legacy Pro activation paid completed operations loop 30d",+ ),+ (+ "pulse_intelligence_pro_activation_paid_resolved_operations_loop_30d",+ "Legacy Pro activation paid resolved operations loop 30d",+ ),+ ("pulse_intelligence_governed_action_active_30d", "Governed action active 30d"),+ ("pulse_intelligence_assistant_operations_loop_30d", "Assistant operations loop 30d"),+ (+ "pulse_intelligence_assistant_approved_execution_loop_30d",+ "Assistant approved execution loop 30d",+ ),+ (+ "pulse_intelligence_assistant_approved_action_success_loop_30d",+ "Assistant approved action success loop 30d",+ ),+ (+ "pulse_intelligence_assistant_resolved_operations_loop_30d",+ "Assistant resolved operations loop 30d",+ ),+ ("pulse_intelligence_external_agent_operations_loop_30d", "External-agent operations loop 30d"),+ (+ "pulse_intelligence_external_agent_approved_execution_loop_30d",+ "External-agent approved execution loop 30d",+ ),+ (+ "pulse_intelligence_external_agent_approved_action_success_loop_30d",+ "External-agent approved action success loop 30d",+ ),+ (+ "pulse_intelligence_external_agent_resolved_operations_loop_30d",+ "External-agent resolved operations loop 30d",+ ),+ ("pulse_intelligence_mcp_adapter_operations_loop_30d", "Pulse MCP adapter operations loop 30d"),+ (+ "pulse_intelligence_mcp_adapter_approved_execution_loop_30d",+ "Pulse MCP adapter approved execution loop 30d",+ ),+ (+ "pulse_intelligence_mcp_adapter_approved_action_success_loop_30d",+ "Pulse MCP adapter approved action success loop 30d",+ ),+ (+ "pulse_intelligence_mcp_adapter_resolved_operations_loop_30d",+ "Pulse MCP adapter resolved operations loop 30d",+ ),+ ("pulse_intelligence_external_agent_enabled", "External agent enabled"),+ ("pulse_intelligence_external_agent_used_30d", "External agent used 30d"),+ ("pulse_intelligence_mcp_adapter_used_30d", "Pulse MCP adapter used 30d"),+)+PULSE_INTELLIGENCE_EXTERNAL_AGENT_CAPABILITY_COUNT_FIELDS = (+ (+ "pulse_intelligence_external_agent_context_requests_30d",+ "External agent context requests 30d",+ ),+ (+ "pulse_intelligence_external_agent_event_stream_requests_30d",+ "External agent event-stream requests 30d",+ ),+ (+ "pulse_intelligence_external_agent_provisioning_requests_30d",+ "External agent provisioning requests 30d",+ ),+ (+ "pulse_intelligence_external_agent_operator_state_requests_30d",+ "External agent operator-state requests 30d",+ ),+ (+ "pulse_intelligence_external_agent_finding_requests_30d",+ "External agent finding requests 30d",+ ),+ (+ "pulse_intelligence_external_agent_action_requests_30d",+ "External agent action requests 30d",+ ),+)+PULSE_INTELLIGENCE_EXTERNAL_AGENT_CAPABILITY_COUNT_FIELD_NAMES = tuple(+ field for field, _ in PULSE_INTELLIGENCE_EXTERNAL_AGENT_CAPABILITY_COUNT_FIELDS+)+PULSE_INTELLIGENCE_EXTERNAL_AGENT_ACTIVITY_BOOL_FIELD_NAMES = (+ "pulse_intelligence_external_agent_used_30d",+ "pulse_intelligence_mcp_adapter_used_30d",+)+PULSE_INTELLIGENCE_COUNT_FIELDS = (+ (+ "pulse_intelligence_operations_loop_starter_requests_30d",+ "Operations-loop starter requests 30d",+ ),+ (+ "pulse_intelligence_assistant_operations_loop_starter_requests_30d",+ "Assistant operations-loop starter requests 30d",+ ),+ (+ "pulse_intelligence_patrol_operations_loop_starter_requests_30d",+ "Patrol operations-loop starter requests 30d",+ ),+ (+ "pulse_intelligence_patrol_control_operations_loop_starter_requests_30d",+ "Patrol control operations-loop starter requests 30d",+ ),+ (+ "pulse_intelligence_pro_activation_operations_loop_starter_requests_30d",+ "Legacy Pro activation operations-loop starter requests 30d",+ ),+ (+ "pulse_intelligence_mcp_operations_loop_starter_requests_30d",+ "Pulse MCP operations-loop starter requests 30d",+ ),+ ("pulse_intelligence_assistant_ai_calls_30d", "Assistant AI calls 30d"),+ ("pulse_intelligence_assistant_context_ai_calls_30d", "Assistant governed-context AI calls 30d"),+ ("pulse_intelligence_assistant_tool_calls_30d", "Assistant governed-tool calls 30d"),+ ("pulse_intelligence_patrol_ai_calls_30d", "Patrol AI calls 30d"),+ ("pulse_intelligence_patrol_runs_30d", "Patrol runs 30d"),+ ("pulse_intelligence_patrol_new_findings_30d", "Patrol new findings 30d"),+ ("pulse_intelligence_patrol_investigations_30d", "Patrol investigations 30d"),+ ("pulse_intelligence_patrol_resolved_findings_30d", "Patrol resolved findings 30d"),+ ("pulse_intelligence_patrol_autofixes_30d", "Patrol autofixes 30d"),+ *PULSE_INTELLIGENCE_EXTERNAL_AGENT_CAPABILITY_COUNT_FIELDS,+ ("pulse_intelligence_action_plans_30d", "Action plans 30d"),+ ("pulse_intelligence_approval_requests_30d", "Approval requests 30d"),+ ("pulse_intelligence_rejected_action_decisions_30d", "Rejected action decisions 30d"),+ ("pulse_intelligence_approved_action_decisions_30d", "Approved action decisions 30d"),+ ("pulse_intelligence_approved_action_attempts_30d", "Approved action attempts 30d"),+ ("pulse_intelligence_approved_action_successes_30d", "Approved action successes 30d"),+)+PULSE_INTELLIGENCE_OUTCOME_COHORTS = (+ (+ "loop_configured",+ "Loop configured",+ ("pulse_intelligence_loop_configured",),+ (),+ ),+ (+ "loop_active_30d",+ "Loop active 30d",+ ("pulse_intelligence_loop_active_30d",),+ tuple(field for field, _ in PULSE_INTELLIGENCE_COUNT_FIELDS),+ ),+ (+ "complete_operations_loop_30d",+ "Complete operations loop 30d",+ ("pulse_intelligence_complete_operations_loop_30d",),+ (),+ ),+ (+ "approved_execution_loop_30d",+ "Approved execution loop 30d",+ ("pulse_intelligence_approved_execution_loop_30d",),+ (),+ ),+ (+ "resolved_operations_loop_30d",+ "Resolved operations loop 30d",+ ("pulse_intelligence_resolved_operations_loop_30d",),+ (),+ ),+ (+ "patrol_control_completed_operations_loop_30d",+ "Patrol control completed operations loop 30d",+ PULSE_INTELLIGENCE_PATROL_CONTROL_COMPLETED_BOOL_FIELDS,+ (),+ ),+ (+ "patrol_control_resolved_operations_loop_30d",+ "Patrol control resolved operations loop 30d",+ PULSE_INTELLIGENCE_PATROL_CONTROL_RESOLVED_BOOL_FIELDS,+ (),+ ),+ (+ "patrol_control_paid_completed_operations_loop_30d",+ "Paid Patrol control completed operations loop 30d",+ PULSE_INTELLIGENCE_PATROL_CONTROL_PAID_COMPLETED_BOOL_FIELDS,+ (),+ ),+ (+ "patrol_control_paid_resolved_operations_loop_30d",+ "Paid Patrol control resolved operations loop 30d",+ PULSE_INTELLIGENCE_PATROL_CONTROL_PAID_RESOLVED_BOOL_FIELDS,+ (),+ ),+ (+ "assistant_operations_loop_30d",+ "Assistant operations loop 30d",+ ("pulse_intelligence_assistant_operations_loop_30d",),+ (),+ ),+ (+ "assistant_approved_execution_loop_30d",+ "Assistant approved execution loop 30d",+ ("pulse_intelligence_assistant_approved_execution_loop_30d",),+ (),+ ),+ (+ "assistant_approved_action_success_loop_30d",+ "Assistant approved action success loop 30d",+ ("pulse_intelligence_assistant_approved_action_success_loop_30d",),+ (),+ ),+ (+ "assistant_resolved_operations_loop_30d",+ "Assistant resolved operations loop 30d",+ ("pulse_intelligence_assistant_resolved_operations_loop_30d",),+ (),+ ),+ (+ "external_agent_operations_loop_30d",+ "External-agent operations loop 30d",+ (+ "pulse_intelligence_external_agent_operations_loop_30d",+ "pulse_intelligence_mcp_adapter_operations_loop_30d",+ ),+ (),+ ),+ (+ "external_agent_approved_execution_loop_30d",+ "External-agent approved execution loop 30d",+ (+ "pulse_intelligence_external_agent_approved_execution_loop_30d",+ "pulse_intelligence_mcp_adapter_approved_execution_loop_30d",+ ),+ (),+ ),+ (+ "external_agent_approved_action_success_loop_30d",+ "External-agent approved action success loop 30d",+ (+ "pulse_intelligence_external_agent_approved_action_success_loop_30d",+ "pulse_intelligence_mcp_adapter_approved_action_success_loop_30d",+ ),+ (),+ ),+ (+ "external_agent_resolved_operations_loop_30d",+ "External-agent resolved operations loop 30d",+ (+ "pulse_intelligence_external_agent_resolved_operations_loop_30d",+ "pulse_intelligence_mcp_adapter_resolved_operations_loop_30d",+ ),+ (),+ ),+ (+ "mcp_adapter_operations_loop_30d",+ "Pulse MCP adapter operations loop 30d",+ ("pulse_intelligence_mcp_adapter_operations_loop_30d",),+ (),+ ),+ (+ "mcp_adapter_approved_execution_loop_30d",+ "Pulse MCP adapter approved execution loop 30d",+ ("pulse_intelligence_mcp_adapter_approved_execution_loop_30d",),+ (),+ ),+ (+ "mcp_adapter_approved_action_success_loop_30d",+ "Pulse MCP adapter approved action success loop 30d",+ ("pulse_intelligence_mcp_adapter_approved_action_success_loop_30d",),+ (),+ ),+ (+ "mcp_adapter_resolved_operations_loop_30d",+ "Pulse MCP adapter resolved operations loop 30d",+ ("pulse_intelligence_mcp_adapter_resolved_operations_loop_30d",),+ (),+ ),+ (+ "operations_loop_starter_requests",+ "Operations-loop starter requests",+ (),+ ("pulse_intelligence_operations_loop_starter_requests_30d",),+ ),+ (+ "assistant_operations_loop_starter_requests",+ "Assistant operations-loop starter requests",+ (),+ ("pulse_intelligence_assistant_operations_loop_starter_requests_30d",),+ ),+ (+ "patrol_operations_loop_starter_requests",+ "Patrol operations-loop starter requests",+ (),+ ("pulse_intelligence_patrol_operations_loop_starter_requests_30d",),+ ),+ (+ "patrol_control_operations_loop_starter_requests",+ "Patrol control operations-loop starter requests",+ (),+ PULSE_INTELLIGENCE_PATROL_CONTROL_STARTER_COUNT_FIELDS,+ ),+ (+ "pro_activation_operations_loop_starter_requests",+ "Legacy Pro activation operations-loop starter requests",+ (),+ ("pulse_intelligence_pro_activation_operations_loop_starter_requests_30d",),+ ),+ (+ "mcp_operations_loop_starter_requests",+ "Pulse MCP operations-loop starter requests",+ (),+ ("pulse_intelligence_mcp_operations_loop_starter_requests_30d",),+ ),+ (+ "assistant_activity",+ "Assistant activity",+ (),+ ("pulse_intelligence_assistant_ai_calls_30d",),+ ),+ (+ "assistant_context_activity",+ "Assistant governed-context activity",+ (),+ ("pulse_intelligence_assistant_context_ai_calls_30d",),+ ),+ (+ "assistant_tool_activity",+ "Assistant governed-tool activity",+ (),+ ("pulse_intelligence_assistant_tool_calls_30d",),+ ),+ (+ "patrol_activity",+ "Patrol activity",+ (),+ (+ "pulse_intelligence_patrol_ai_calls_30d",+ "pulse_intelligence_patrol_runs_30d",+ "pulse_intelligence_patrol_new_findings_30d",+ "pulse_intelligence_patrol_investigations_30d",+ "pulse_intelligence_patrol_resolved_findings_30d",+ "pulse_intelligence_patrol_autofixes_30d",+ ),+ ),+ (+ "patrol_resolution_30d",+ "Patrol resolution 30d",+ (),+ ("pulse_intelligence_patrol_resolved_findings_30d",),+ ),+ (+ "external_agent_used_30d",+ "External agent/MCP used 30d",+ PULSE_INTELLIGENCE_EXTERNAL_AGENT_ACTIVITY_BOOL_FIELD_NAMES,+ PULSE_INTELLIGENCE_EXTERNAL_AGENT_CAPABILITY_COUNT_FIELD_NAMES,+ ),+ (+ "mcp_adapter_used_30d",+ "Pulse MCP adapter used 30d",+ ("pulse_intelligence_mcp_adapter_used_30d",),+ (),+ ),+ *(+ (+ field.removeprefix("pulse_intelligence_").removesuffix("_30d"),+ label,+ (),+ (field,),+ )+ for field, label in PULSE_INTELLIGENCE_EXTERNAL_AGENT_CAPABILITY_COUNT_FIELDS+ ),+ (+ "governed_action_active_30d",+ "Governed action active 30d",+ ("pulse_intelligence_governed_action_active_30d",),+ (+ "pulse_intelligence_action_plans_30d",+ "pulse_intelligence_approval_requests_30d",+ "pulse_intelligence_rejected_action_decisions_30d",+ "pulse_intelligence_approved_action_decisions_30d",+ "pulse_intelligence_approved_action_attempts_30d",+ "pulse_intelligence_approved_action_successes_30d",+ ),+ ),+ (+ "approved_action_decision_30d",+ "Approved action decision 30d",+ (),+ ("pulse_intelligence_approved_action_decisions_30d",),+ ),+ (+ "approved_action_execution_30d",+ "Approved action execution 30d",+ (),+ ("pulse_intelligence_approved_action_attempts_30d",),+ ),+ (+ "approved_action_success_30d",+ "Approved action success 30d",+ (),+ ("pulse_intelligence_approved_action_successes_30d",),+ ),+)+PULSE_INTELLIGENCE_OPERATION_SIGNAL_GROUPS = {+ "configured": (+ ("pulse_intelligence_loop_configured",),+ (),+ ),+ "patrol": (+ (),+ (+ "pulse_intelligence_patrol_ai_calls_30d",+ "pulse_intelligence_patrol_runs_30d",+ "pulse_intelligence_patrol_new_findings_30d",+ "pulse_intelligence_patrol_investigations_30d",+ "pulse_intelligence_patrol_resolved_findings_30d",+ "pulse_intelligence_patrol_autofixes_30d",+ ),+ ),+ "patrol_resolution": (+ (),+ ("pulse_intelligence_patrol_resolved_findings_30d",),+ ),+ "patrol_issue": (+ (),+ (+ "pulse_intelligence_patrol_new_findings_30d",+ "pulse_intelligence_patrol_investigations_30d",+ "pulse_intelligence_patrol_resolved_findings_30d",+ "pulse_intelligence_patrol_autofixes_30d",+ ),+ ),+ "collaboration": (+ (+ *PULSE_INTELLIGENCE_ASSISTANT_LOOP_BOOL_FIELDS,+ *PULSE_INTELLIGENCE_EXTERNAL_AGENT_LOOP_BOOL_FIELDS,+ *PULSE_INTELLIGENCE_MCP_ADAPTER_LOOP_BOOL_FIELDS,+ *PULSE_INTELLIGENCE_EXTERNAL_AGENT_ACTIVITY_BOOL_FIELD_NAMES,+ ),+ (+ "pulse_intelligence_assistant_context_ai_calls_30d",+ "pulse_intelligence_assistant_tool_calls_30d",+ *PULSE_INTELLIGENCE_EXTERNAL_AGENT_CAPABILITY_COUNT_FIELD_NAMES,+ ),+ ),+ "assistant_collaboration": (+ PULSE_INTELLIGENCE_ASSISTANT_LOOP_BOOL_FIELDS,+ (+ "pulse_intelligence_assistant_context_ai_calls_30d",+ "pulse_intelligence_assistant_tool_calls_30d",+ ),+ ),+ "external_agent_collaboration": (+ (+ *PULSE_INTELLIGENCE_EXTERNAL_AGENT_LOOP_BOOL_FIELDS,+ *PULSE_INTELLIGENCE_EXTERNAL_AGENT_ACTIVITY_BOOL_FIELD_NAMES,+ ),+ PULSE_INTELLIGENCE_EXTERNAL_AGENT_CAPABILITY_COUNT_FIELD_NAMES,+ ),+ "mcp_adapter": (+ (+ *PULSE_INTELLIGENCE_MCP_ADAPTER_LOOP_BOOL_FIELDS,+ "pulse_intelligence_mcp_adapter_used_30d",+ ),+ (),+ ),+ "governed_action": (+ ("pulse_intelligence_governed_action_active_30d",),+ (+ "pulse_intelligence_action_plans_30d",+ "pulse_intelligence_approval_requests_30d",+ "pulse_intelligence_rejected_action_decisions_30d",+ "pulse_intelligence_approved_action_decisions_30d",+ "pulse_intelligence_approved_action_attempts_30d",+ "pulse_intelligence_approved_action_successes_30d",+ ),+ ),+ "governed_decision": (+ (),+ (+ "pulse_intelligence_rejected_action_decisions_30d",+ "pulse_intelligence_approved_action_decisions_30d",+ "pulse_intelligence_approved_action_attempts_30d",+ ),+ ),+ "approved_execution": (+ (+ "pulse_intelligence_approved_execution_loop_30d",+ "pulse_intelligence_assistant_approved_execution_loop_30d",+ "pulse_intelligence_external_agent_approved_execution_loop_30d",+ "pulse_intelligence_mcp_adapter_approved_execution_loop_30d",+ ),+ ("pulse_intelligence_approved_action_attempts_30d",),+ ),+ "approved_success": (+ (+ "pulse_intelligence_assistant_approved_action_success_loop_30d",+ "pulse_intelligence_external_agent_approved_action_success_loop_30d",+ "pulse_intelligence_mcp_adapter_approved_action_success_loop_30d",+ ),+ ("pulse_intelligence_approved_action_successes_30d",),+ ),+ "complete_operations_loop": (+ (+ "pulse_intelligence_complete_operations_loop_30d",+ *PULSE_INTELLIGENCE_PATROL_CONTROL_COMPLETED_BOOL_FIELDS,+ "pulse_intelligence_assistant_operations_loop_30d",+ "pulse_intelligence_external_agent_operations_loop_30d",+ "pulse_intelligence_mcp_adapter_operations_loop_30d",+ ),+ (),+ ),+ "approved_execution_loop": (+ (+ "pulse_intelligence_approved_execution_loop_30d",+ "pulse_intelligence_assistant_approved_execution_loop_30d",+ "pulse_intelligence_external_agent_approved_execution_loop_30d",+ "pulse_intelligence_mcp_adapter_approved_execution_loop_30d",+ ),+ (),+ ),+ "resolved_operations_loop": (+ (+ "pulse_intelligence_resolved_operations_loop_30d",+ *PULSE_INTELLIGENCE_PATROL_CONTROL_RESOLVED_BOOL_FIELDS,+ "pulse_intelligence_assistant_resolved_operations_loop_30d",+ "pulse_intelligence_external_agent_resolved_operations_loop_30d",+ "pulse_intelligence_mcp_adapter_resolved_operations_loop_30d",+ ),+ (),+ ),+ "patrol_control_completed_operations_loop": (+ PULSE_INTELLIGENCE_PATROL_CONTROL_COMPLETED_BOOL_FIELDS,+ (),+ ),+ "patrol_control_resolved_operations_loop": (+ PULSE_INTELLIGENCE_PATROL_CONTROL_RESOLVED_BOOL_FIELDS,+ (),+ ),+ "assistant_operations_loop": (+ ("pulse_intelligence_assistant_operations_loop_30d",),+ (),+ ),+ "assistant_approved_execution_loop": (+ ("pulse_intelligence_assistant_approved_execution_loop_30d",),+ (),+ ),+ "assistant_approved_success_loop": (+ ("pulse_intelligence_assistant_approved_action_success_loop_30d",),+ (),+ ),+ "assistant_resolved_operations_loop": (+ ("pulse_intelligence_assistant_resolved_operations_loop_30d",),+ (),+ ),+ "external_agent_operations_loop": (+ (+ "pulse_intelligence_external_agent_operations_loop_30d",+ "pulse_intelligence_mcp_adapter_operations_loop_30d",+ ),+ (),+ ),+ "external_agent_approved_execution_loop": (+ (+ "pulse_intelligence_external_agent_approved_execution_loop_30d",+ "pulse_intelligence_mcp_adapter_approved_execution_loop_30d",+ ),+ (),+ ),+ "external_agent_approved_success_loop": (+ (+ "pulse_intelligence_external_agent_approved_action_success_loop_30d",+ "pulse_intelligence_mcp_adapter_approved_action_success_loop_30d",+ ),+ (),+ ),+ "external_agent_resolved_operations_loop": (+ (+ "pulse_intelligence_external_agent_resolved_operations_loop_30d",+ "pulse_intelligence_mcp_adapter_resolved_operations_loop_30d",+ ),+ (),+ ),+ "mcp_adapter_operations_loop": (+ ("pulse_intelligence_mcp_adapter_operations_loop_30d",),+ (),+ ),+ "mcp_adapter_approved_execution_loop": (+ ("pulse_intelligence_mcp_adapter_approved_execution_loop_30d",),+ (),+ ),+ "mcp_adapter_approved_success_loop": (+ ("pulse_intelligence_mcp_adapter_approved_action_success_loop_30d",),+ (),+ ),+ "mcp_adapter_resolved_operations_loop": (+ ("pulse_intelligence_mcp_adapter_resolved_operations_loop_30d",),+ (),+ ),+}+PULSE_INTELLIGENCE_OPERATIONS_FUNNEL_STAGES = (+ ("configured", "Configured", ("configured",)),+ ("patrol_activity", "Patrol detection/investigation", ("patrol",)),+ ("patrol_issue_evidence", "Patrol issue evidence", ("patrol_issue",)),+ ("assistant_mcp_collaboration", "Assistant/MCP collaboration", ("collaboration",)),+ ("governed_action", "Governed action activity", ("governed_action",)),+ ("governed_decision", "Approve/reject decision", ("governed_decision",)),+ ("approved_action_execution", "Approved action execution", ("approved_execution",)),+ ("approved_action_success", "Approved action success", ("approved_success",)),+ ("patrol_resolution", "Patrol resolution", ("patrol_resolution",)),+ (+ "complete_operations_loop",+ "Complete operations loop",+ ("complete_operations_loop",),+ ),+ (+ "approved_execution_loop",+ "Approved execution loop",+ ("approved_execution_loop",),+ ),+ (+ "resolved_operations_loop",+ "Resolved operations loop",+ ("resolved_operations_loop",),+ ),+ (+ "patrol_control_completed_operations_loop",+ "Patrol control completed operations loop",+ ("patrol_control_completed_operations_loop",),+ ),+ (+ "patrol_control_resolved_operations_loop",+ "Patrol control resolved operations loop",+ ("patrol_control_resolved_operations_loop",),+ ),+ (+ "assistant_operations_loop",+ "Assistant operations loop",+ ("assistant_operations_loop",),+ ),+ (+ "assistant_approved_execution_loop",+ "Assistant approved execution loop",+ ("assistant_approved_execution_loop",),+ ),+ (+ "assistant_approved_success_loop",+ "Assistant approved action success loop",+ ("assistant_approved_success_loop",),+ ),+ (+ "assistant_resolved_operations_loop",+ "Assistant resolved operations loop",+ ("assistant_resolved_operations_loop",),+ ),+ (+ "external_agent_operations_loop",+ "External-agent operations loop",+ ("external_agent_operations_loop",),+ ),+ (+ "external_agent_approved_execution_loop",+ "External-agent approved execution loop",+ ("external_agent_approved_execution_loop",),+ ),+ (+ "external_agent_approved_success_loop",+ "External-agent approved action success loop",+ ("external_agent_approved_success_loop",),+ ),+ (+ "external_agent_resolved_operations_loop",+ "External-agent resolved operations loop",+ ("external_agent_resolved_operations_loop",),+ ),+ (+ "mcp_adapter_operations_loop",+ "Pulse MCP adapter operations loop",+ ("mcp_adapter_operations_loop",),+ ),+ (+ "mcp_adapter_approved_execution_loop",+ "Pulse MCP adapter approved execution loop",+ ("mcp_adapter_approved_execution_loop",),+ ),+ (+ "mcp_adapter_approved_success_loop",+ "Pulse MCP adapter approved success loop",+ ("mcp_adapter_approved_success_loop",),+ ),+ (+ "mcp_adapter_resolved_operations_loop",+ "Pulse MCP adapter resolved operations loop",+ ("mcp_adapter_resolved_operations_loop",),+ ),+)DEEP_SIGNAL_FIELDS = (("agent_hosts", "Agent hosts", "count"),("docker_containers", "Docker containers", "count"),@@ -87,6 +841,14 @@ DEEP_SIGNAL_FIELDS = (("discovery_enabled", "Discovery enabled", "bool"),("notifications_enabled", "Notifications enabled", "bool"),("ai_actions_enabled", "AI actions enabled", "bool"),+ *(+ (field, label, "bool")+ for field, label in PULSE_INTELLIGENCE_BOOL_FIELDS+ ),+ *(+ (field, label, "count")+ for field, label in PULSE_INTELLIGENCE_COUNT_FIELDS+ ),)GIT_DESCRIBE_RE = re.compile(r"^(?P<base>\d+\.\d+\.\d+(?:-[0-9A-Za-z\.-]+)?)-(?P<count>\d+)-g(?P<sha>[0-9a-fA-F]+)(?P<dirty>-dirty)?$"@@ -512,6 +1274,429 @@ def summarize_deep_signal_sources(return result+def summarize_pulse_intelligence_value_loop(+ latest_by_install: dict[str, dict[str, Any]],+ *,+ now: datetime | None = None,+ window: timedelta = timedelta(days=7),+) -> dict[str, Any]:+ current_time = now or datetime.now(timezone.utc)+ active_installs = 0+ paid_installs = 0+ free_installs = 0++ bool_signals = {+ field: {+ "field": field,+ "label": label,+ "installs": 0,+ "paid_installs": 0,+ "free_installs": 0,+ }+ for field, label in PULSE_INTELLIGENCE_BOOL_FIELDS+ }+ count_signals = {+ field: {+ "field": field,+ "label": label,+ "installs": 0,+ "paid_installs": 0,+ "free_installs": 0,+ "total": 0,+ "paid_total": 0,+ "free_total": 0,+ }+ for field, label in PULSE_INTELLIGENCE_COUNT_FIELDS+ }++ for row in latest_by_install.values():+ received_at = parse_received_at(str(row["received_at"]))+ if current_time - received_at > window:+ continue++ active_installs += 1+ paid = parse_optional_bool(row.get("paid_license")) is True+ if paid:+ paid_installs += 1+ else:+ free_installs += 1++ for field, _ in PULSE_INTELLIGENCE_BOOL_FIELDS:+ if not parse_optional_bool(row.get(field)):+ continue+ signal = bool_signals[field]+ signal["installs"] += 1+ if paid:+ signal["paid_installs"] += 1+ else:+ signal["free_installs"] += 1++ for field, _ in PULSE_INTELLIGENCE_COUNT_FIELDS:+ value = parse_optional_nonnegative_int(row.get(field))+ if value <= 0:+ continue+ signal = count_signals[field]+ signal["installs"] += 1+ signal["total"] += value+ if paid:+ signal["paid_installs"] += 1+ signal["paid_total"] += value+ else:+ signal["free_installs"] += 1+ signal["free_total"] += value++ return {+ "window": "7d",+ "active_installs": active_installs,+ "paid_installs": paid_installs,+ "free_installs": free_installs,+ "boolean_signals": list(bool_signals.values()),+ "count_signals": list(count_signals.values()),+ }+++def pulse_intelligence_row_matches_cohort(+ row: dict[str, Any],+ bool_fields: tuple[str, ...],+ count_fields: tuple[str, ...],+) -> bool:+ return any(parse_optional_bool(row.get(field)) for field in bool_fields) or any(+ parse_optional_nonnegative_int(row.get(field)) > 0 for field in count_fields+ )+++def pulse_intelligence_timed_rows(+ install_rows: Iterable[dict[str, Any]],+) -> list[tuple[datetime, dict[str, Any], bool | None]]:+ timed_rows = [+ (+ parse_received_at(str(row["received_at"])),+ row,+ parse_optional_bool(row.get("paid_license")),+ )+ for row in install_rows+ ]+ timed_rows.sort(key=lambda entry: entry[0])+ return timed_rows+++def pulse_intelligence_first_paid_at(+ timed_rows: Iterable[tuple[datetime, dict[str, Any], bool | None]],+) -> datetime | None:+ paid_times = [received_at for received_at, _, posture in timed_rows if posture is True]+ return min(paid_times) if paid_times else None+++def pulse_intelligence_observed_conversion(+ install_rows: Iterable[dict[str, Any]],+) -> tuple[bool, bool]:+ explicit_postures: list[tuple[datetime, bool]] = []+ for received_at, _, posture in pulse_intelligence_timed_rows(install_rows):+ if posture is not None:+ explicit_postures.append((received_at, posture))+ if not explicit_postures:+ return False, False+ first_free_at = next(+ (received_at for received_at, posture in explicit_postures if posture is False),+ None,+ )+ first_paid_at = next(+ (received_at for received_at, posture in explicit_postures if posture is True),+ None,+ )+ observed_free_start = first_free_at is not None and (+ first_paid_at is None or first_free_at < first_paid_at+ )+ observed_free_to_paid = (+ observed_free_start+ and first_paid_at is not None+ and first_free_at is not None+ and first_free_at < first_paid_at+ )+ return observed_free_start, observed_free_to_paid+++def pulse_intelligence_signal_observed_conversion(+ install_rows: Iterable[dict[str, Any]],+ bool_fields: tuple[str, ...],+ count_fields: tuple[str, ...],+) -> tuple[bool, bool]:+ timed_rows = pulse_intelligence_timed_rows(install_rows)+ first_paid_at = pulse_intelligence_first_paid_at(timed_rows)+ first_free_signal_at: datetime | None = None+ for received_at, row, posture in timed_rows:+ if posture is not False:+ continue+ if first_paid_at is not None and received_at >= first_paid_at:+ continue+ if pulse_intelligence_row_matches_cohort(row, bool_fields, count_fields):+ first_free_signal_at = received_at+ break++ observed_free_signal = first_free_signal_at is not None+ observed_signal_to_paid = observed_free_signal and first_paid_at is not None+ return observed_free_signal, observed_signal_to_paid+++def pulse_intelligence_row_signal_groups(row: dict[str, Any]) -> set[str]:+ groups: set[str] = set()+ for group, (bool_fields, count_fields) in PULSE_INTELLIGENCE_OPERATION_SIGNAL_GROUPS.items():+ if pulse_intelligence_row_matches_cohort(row, bool_fields, count_fields):+ groups.add(group)+ return pulse_intelligence_derive_signal_groups(groups)+++def pulse_intelligence_derive_signal_groups(groups: set[str]) -> set[str]:+ if {"patrol_issue", "collaboration", "governed_decision"}.issubset(groups):+ groups.add("complete_operations_loop")+ if {"patrol_issue", "collaboration", "approved_execution"}.issubset(groups):+ groups.add("approved_execution_loop")+ if {"patrol_resolution", "collaboration", "approved_success"}.issubset(groups):+ groups.add("resolved_operations_loop")+ if {"patrol_issue", "assistant_collaboration", "governed_decision"}.issubset(groups):+ groups.add("assistant_operations_loop")+ if {"patrol_issue", "assistant_collaboration", "approved_execution"}.issubset(groups):+ groups.add("assistant_approved_execution_loop")+ if {"patrol_issue", "assistant_collaboration", "approved_success"}.issubset(groups):+ groups.add("assistant_approved_success_loop")+ if {"patrol_resolution", "assistant_collaboration", "approved_success"}.issubset(groups):+ groups.add("assistant_resolved_operations_loop")+ if {"patrol_issue", "external_agent_collaboration", "governed_decision"}.issubset(groups):+ groups.add("external_agent_operations_loop")+ if {"patrol_issue", "external_agent_collaboration", "approved_execution"}.issubset(groups):+ groups.add("external_agent_approved_execution_loop")+ if {"patrol_issue", "external_agent_collaboration", "approved_success"}.issubset(groups):+ groups.add("external_agent_approved_success_loop")+ if {"patrol_resolution", "external_agent_collaboration", "approved_success"}.issubset(groups):+ groups.add("external_agent_resolved_operations_loop")+ if {"patrol_issue", "mcp_adapter", "governed_decision"}.issubset(groups):+ groups.add("mcp_adapter_operations_loop")+ if {"patrol_issue", "mcp_adapter", "approved_execution"}.issubset(groups):+ groups.add("mcp_adapter_approved_execution_loop")+ if {"patrol_issue", "mcp_adapter", "approved_success"}.issubset(groups):+ groups.add("mcp_adapter_approved_success_loop")+ if {"patrol_resolution", "mcp_adapter", "approved_success"}.issubset(groups):+ groups.add("mcp_adapter_resolved_operations_loop")+ return groups+++def pulse_intelligence_stage_signal_observed_conversion(+ install_rows: Iterable[dict[str, Any]],+ required_groups: tuple[str, ...],+) -> tuple[bool, bool]:+ timed_rows = pulse_intelligence_timed_rows(install_rows)+ first_paid_at = pulse_intelligence_first_paid_at(timed_rows)+ groups_seen_while_free: set[str] = set()+ for received_at, row, posture in timed_rows:+ if posture is not False:+ continue+ if first_paid_at is not None and received_at >= first_paid_at:+ continue+ groups_seen_while_free.update(pulse_intelligence_row_signal_groups(row))+ pulse_intelligence_derive_signal_groups(groups_seen_while_free)++ observed_free_signal = all(group in groups_seen_while_free for group in required_groups)+ observed_signal_to_paid = observed_free_signal and first_paid_at is not None+ return observed_free_signal, observed_signal_to_paid+++def pulse_intelligence_rate_pct(part: int, total: int) -> float:+ if total <= 0 or part <= 0:+ return 0.0+ return round((part / total) * 100, 2)+++def summarize_pulse_intelligence_install_outcomes(+ install_ids: Iterable[str],+ latest_by_install: dict[str, dict[str, Any]],+ rows_by_install: dict[str, list[dict[str, Any]]],+ current_time: datetime,+ retention_window: timedelta,+ signal_outcomes_by_install: dict[str, tuple[bool, bool]] | None = None,+) -> dict[str, int]:+ install_id_list = list(install_ids)+ retained_installs = 0+ paid_latest = 0+ free_latest = 0+ observed_free_starts = 0+ observed_free_to_paid = 0+ observed_signal_free_starts = 0+ observed_signal_free_to_paid = 0++ for install_id in install_id_list:+ latest = latest_by_install.get(install_id)+ if latest is None:+ continue+ latest_received_at = parse_received_at(str(latest["received_at"]))+ if current_time - latest_received_at <= retention_window:+ retained_installs += 1+ if parse_optional_bool(latest.get("paid_license")) is True:+ paid_latest += 1+ else:+ free_latest += 1+ free_start, converted = pulse_intelligence_observed_conversion(+ rows_by_install.get(install_id, [])+ )+ if free_start:+ observed_free_starts += 1+ if converted:+ observed_free_to_paid += 1+ if signal_outcomes_by_install is not None:+ signal_free_start, signal_converted = signal_outcomes_by_install.get(+ install_id,+ (False, False),+ )+ if signal_free_start:+ observed_signal_free_starts += 1+ if signal_converted:+ observed_signal_free_to_paid += 1++ return {+ "installs": len(install_id_list),+ "retained_7d": retained_installs,+ "retained_7d_rate_pct": pulse_intelligence_rate_pct(+ retained_installs,+ len(install_id_list),+ ),+ "paid_latest": paid_latest,+ "paid_latest_rate_pct": pulse_intelligence_rate_pct(+ paid_latest,+ len(install_id_list),+ ),+ "free_latest": free_latest,+ "observed_free_starts": observed_free_starts,+ "observed_free_to_paid": observed_free_to_paid,+ "observed_free_to_paid_rate_pct": pulse_intelligence_rate_pct(+ observed_free_to_paid,+ observed_free_starts,+ ),+ "observed_signal_free_starts": observed_signal_free_starts,+ "observed_signal_free_to_paid": observed_signal_free_to_paid,+ "observed_signal_free_to_paid_rate_pct": pulse_intelligence_rate_pct(+ observed_signal_free_to_paid,+ observed_signal_free_starts,+ ),+ }+++def group_pulse_intelligence_rows_by_install(+ rows: Iterable[dict[str, Any]],+) -> dict[str, list[dict[str, Any]]]:+ rows_by_install: dict[str, list[dict[str, Any]]] = {}+ for row in rows:+ install_id = str(row.get("install_id") or "").strip()+ if install_id:+ rows_by_install.setdefault(install_id, []).append(row)+ return rows_by_install+++def summarize_pulse_intelligence_outcome_cohorts(+ rows: Iterable[dict[str, Any]],+ latest_by_install: dict[str, dict[str, Any]],+ *,+ now: datetime | None = None,+ retention_window: timedelta = timedelta(days=7),+) -> dict[str, Any]:+ current_time = now or datetime.now(timezone.utc)+ cohort_install_ids: dict[str, set[str]] = {+ key: set() for key, _, _, _ in PULSE_INTELLIGENCE_OUTCOME_COHORTS+ }+ rows_by_install = group_pulse_intelligence_rows_by_install(rows)++ for install_id, install_rows in rows_by_install.items():+ for row in install_rows:+ for key, _, bool_fields, count_fields in PULSE_INTELLIGENCE_OUTCOME_COHORTS:+ if pulse_intelligence_row_matches_cohort(row, bool_fields, count_fields):+ cohort_install_ids[key].add(install_id)++ cohorts: list[dict[str, Any]] = []+ for key, label, bool_fields, count_fields in PULSE_INTELLIGENCE_OUTCOME_COHORTS:+ install_ids = cohort_install_ids[key]+ signal_outcomes_by_install = {+ install_id: pulse_intelligence_signal_observed_conversion(+ install_rows,+ bool_fields,+ count_fields,+ )+ for install_id, install_rows in rows_by_install.items()+ }+ cohorts.append(+ {+ "key": key,+ "label": label,+ **summarize_pulse_intelligence_install_outcomes(+ install_ids,+ latest_by_install,+ rows_by_install,+ current_time,+ retention_window,+ signal_outcomes_by_install,+ ),+ }+ )++ return {+ "retention_window": "7d",+ "cohorts": cohorts,+ }+++def summarize_pulse_intelligence_operations_funnel(+ rows: Iterable[dict[str, Any]],+ latest_by_install: dict[str, dict[str, Any]],+ *,+ now: datetime | None = None,+ retention_window: timedelta = timedelta(days=7),+) -> dict[str, Any]:+ current_time = now or datetime.now(timezone.utc)+ rows_by_install = group_pulse_intelligence_rows_by_install(rows)+ signal_groups_by_install: dict[str, set[str]] = {+ install_id: set() for install_id in rows_by_install+ }++ for install_id, install_rows in rows_by_install.items():+ for row in install_rows:+ signal_groups_by_install[install_id].update(+ pulse_intelligence_row_signal_groups(row)+ )+ pulse_intelligence_derive_signal_groups(signal_groups_by_install[install_id])++ stages: list[dict[str, Any]] = []+ for key, label, required_groups in PULSE_INTELLIGENCE_OPERATIONS_FUNNEL_STAGES:+ install_ids = [+ install_id+ for install_id, groups in signal_groups_by_install.items()+ if all(group in groups for group in required_groups)+ ]+ signal_outcomes_by_install = {+ install_id: pulse_intelligence_stage_signal_observed_conversion(+ install_rows,+ required_groups,+ )+ for install_id, install_rows in rows_by_install.items()+ }+ stages.append(+ {+ "key": key,+ "label": label,+ "required_signal_groups": list(required_groups),+ **summarize_pulse_intelligence_install_outcomes(+ install_ids,+ latest_by_install,+ rows_by_install,+ current_time,+ retention_window,+ signal_outcomes_by_install,+ ),+ }+ )++ return {+ "retention_window": "7d",+ "stages": stages,+ }++def telemetry_signal_specs() -> list[dict[str, str]]:deep_fields = {key for key, _, _ in DEEP_SIGNAL_FIELDS}specs: list[dict[str, str]] = []@@ -590,8 +1775,9 @@ def summarize_rows(published_versions: set[str],target_version: str | None = None,) -> dict[str, Any]:+ row_list = list(rows)latest_by_install: dict[str, dict[str, Any]] = {}- for row in rows:+ for row in row_list:install_id = str(row["install_id"])existing = latest_by_install.get(install_id)if existing is None or str(row["received_at"]) > str(existing["received_at"]):@@ -614,6 +1800,20 @@ def summarize_rows(published_versions,now=current_time,),+ "pulse_intelligence_value_loop_7d": summarize_pulse_intelligence_value_loop(+ latest_by_install,+ now=current_time,+ ),+ "pulse_intelligence_outcome_cohorts": summarize_pulse_intelligence_outcome_cohorts(+ row_list,+ latest_by_install,+ now=current_time,+ ),+ "pulse_intelligence_operations_loop_funnel": summarize_pulse_intelligence_operations_funnel(+ row_list,+ latest_by_install,+ now=current_time,+ ),"target_release_coverage_7d": summarize_target_version_coverage(latest_by_install,published_versions,@@ -642,6 +1842,44 @@ def format_target_signal(signal: dict[str, Any]) -> str:return text+def format_paid_install_split(installs: int, paid_installs: int, free_installs: int) -> str:+ install_word = "install" if installs == 1 else "installs"+ return f"{installs} {install_word} (paid {paid_installs}, free/community {free_installs})"+++def format_paid_count_split(signal: dict[str, Any]) -> str:+ install_word = "install" if signal["installs"] == 1 else "installs"+ return (+ f"{signal['installs']} {install_word}, total {signal['total']} "+ f"(paid {signal['paid_installs']} / {signal['paid_total']}; "+ f"free/community {signal['free_installs']} / {signal['free_total']})"+ )+++def format_rate(part: int, total: int) -> str:+ if total <= 0:+ return "0.0%"+ return f"{(part / total) * 100:.1f}%"+++def format_pulse_intelligence_cohort(entry: dict[str, Any]) -> str:+ install_word = "install" if entry["installs"] == 1 else "installs"+ observed_free_starts = int(entry.get("observed_free_starts", 0))+ observed_free_to_paid = int(entry.get("observed_free_to_paid", 0))+ observed_signal_free_starts = int(entry.get("observed_signal_free_starts", 0))+ observed_signal_free_to_paid = int(entry.get("observed_signal_free_to_paid", 0))+ return (+ f"{entry['label']}: {entry['installs']} {install_word}, "+ f"retained 7d {entry['retained_7d']} ({format_rate(entry['retained_7d'], entry['installs'])}), "+ f"latest paid {entry['paid_latest']}, latest free/community {entry['free_latest']}, "+ f"observed free/community starts {observed_free_starts}, "+ f"free-to-paid {observed_free_to_paid} ({format_rate(observed_free_to_paid, observed_free_starts)}), "+ f"signal while free/community {observed_signal_free_starts}, "+ f"signal-to-paid {observed_signal_free_to_paid} "+ f"({format_rate(observed_signal_free_to_paid, observed_signal_free_starts)})"+ )++def format_text(summary: dict[str, Any], repo: str, since_days: int) -> str:lines = ["Pulse telemetry adoption report",@@ -691,6 +1929,68 @@ def format_text(summary: dict[str, Any], repo: str, since_days: int) -> str:else:lines.append(" - none")+ pulse_loop = summary.get("pulse_intelligence_value_loop_7d")+ if pulse_loop:+ lines.extend(+ [+ "",+ "Pulse Intelligence value loop (7d):",+ f"- active installs: {pulse_loop['active_installs']}",+ f"- paid posture: paid {pulse_loop['paid_installs']}, free/community {pulse_loop['free_installs']}",+ "- adoption flags:",+ ]+ )+ bool_signals = [entry for entry in pulse_loop.get("boolean_signals", []) if entry["installs"] > 0]+ if bool_signals:+ lines.extend(+ f" - {entry['label']}: "+ + format_paid_install_split(entry["installs"], entry["paid_installs"], entry["free_installs"])+ for entry in bool_signals+ )+ else:+ lines.append(" - none")++ lines.append("- activity counters:")+ count_signals = [entry for entry in pulse_loop.get("count_signals", []) if entry["total"] > 0]+ if count_signals:+ lines.extend(f" - {entry['label']}: {format_paid_count_split(entry)}" for entry in count_signals)+ else:+ lines.append(" - none")++ pulse_cohorts = summary.get("pulse_intelligence_outcome_cohorts")+ if pulse_cohorts:+ lines.extend(+ [+ "",+ "Pulse Intelligence activation and retention:",+ f"- source window: last {since_days} day(s)",+ f"- retention definition: latest ping within {pulse_cohorts.get('retention_window', '7d')}",+ "- cohorts:",+ ]+ )+ cohorts = [entry for entry in pulse_cohorts.get("cohorts", []) if entry["installs"] > 0]+ if cohorts:+ lines.extend(f" - {format_pulse_intelligence_cohort(entry)}" for entry in cohorts)+ else:+ lines.append(" - none")++ pulse_funnel = summary.get("pulse_intelligence_operations_loop_funnel")+ if pulse_funnel:+ lines.extend(+ [+ "",+ "Pulse Intelligence operations loop funnel:",+ f"- source window: last {since_days} day(s)",+ f"- retention definition: latest ping within {pulse_funnel.get('retention_window', '7d')}",+ "- stages:",+ ]+ )+ stages = [entry for entry in pulse_funnel.get("stages", []) if entry["installs"] > 0]+ if stages:+ lines.extend(f" - {format_pulse_intelligence_cohort(entry)}" for entry in stages)+ else:+ lines.append(" - none")+target_coverage = summary.get("target_release_coverage_7d")if target_coverage:lines.extend(diff --git a/scripts/tests/test-hot-dev-bg.sh b/scripts/tests/test-hot-dev-bg.shindex 5a300b3f10..74bb5ab1ba 100755--- a/scripts/tests/test-hot-dev-bg.sh+++ b/scripts/tests/test-hot-dev-bg.sh@@ -211,10 +211,14 @@ EOF}test_managed_wrapper_defaults_to_local_only_runtime() {- local output+ local output test_dir+ test_dir="$(mktemp -d)"+ temp_dirs+=("${test_dir}")+output="$(LAN_IP=192.168.50.10 \ALL_IPS="192.168.50.10" \+ HOT_DEV_LAB_MODE_FILE="${test_dir}/hot-dev.lab-agents-mode" \HOT_DEV_BG_PATH="${HOT_DEV_BG}" \bash -lc 'source "${HOT_DEV_BG_PATH}"@@ -952,6 +956,7 @@ test_hot_dev_bg_preserves_proxmox_guest_docker_env() {assert_contains "hot-dev-bg child preserves lab-agent mode" "${output}" 'PULSE_DEV_LAB_AGENTS="${PULSE_DEV_LAB_AGENTS:-}"'assert_contains "hot-dev-bg child preserves LAN opt-in" "${output}" 'PULSE_DEV_LAN="${PULSE_DEV_LAN:-}"'assert_contains "hot-dev-bg child preserves backend bind address" "${output}" 'BIND_ADDRESS="${BIND_ADDRESS:-}"'+ assert_contains "hot-dev-bg child preserves remembered lab-agent mode file" "${output}" 'HOT_DEV_LAB_MODE_FILE="${HOT_DEV_LAB_MODE_FILE:-}"'assert_contains "hot-dev-bg child preserves debug log level" "${output}" 'LOG_LEVEL="${LOG_LEVEL:-}"'assert_contains "hot-dev-bg restart takeover clears launchd before env-sensitive relaunch" "${output}" 'stop_launchd_hot_dev_job'}diff --git a/scripts/tests/test-hot-dev-runtime.sh b/scripts/tests/test-hot-dev-runtime.shindex ed12fd199d..d948522161 100755--- a/scripts/tests/test-hot-dev-runtime.sh+++ b/scripts/tests/test-hot-dev-runtime.sh@@ -244,6 +244,57 @@ test_hot_dev_lab_agent_mode_enables_lan_and_guest_docker_inventory_defaults() {assert_contains "lab-agent mode allows the wildcard dev origin Electron may report" "${output}" "http://0.0.0.0:5173"}+test_hot_dev_remembers_explicit_lab_agent_mode_for_later_managed_starts() {+ local test_dir output+ test_dir="$(make_temp_dir)"++ output="$(+ HOT_DEV_RUNTIME_LIB="${HOT_DEV_RUNTIME_LIB}" \+ HOT_DEV_LAB_MODE_FILE="${test_dir}/hot-dev.lab-agents-mode" \+ bash -c '+ set -euo pipefail+ source "${HOT_DEV_RUNTIME_LIB}"+ reset_network_env() {+ unset FRONTEND_PORT PORT FRONTEND_DEV_HOST FRONTEND_DEV_PORT BIND_ADDRESS+ unset PULSE_DEV_LAN PULSE_DEV_API_HOST PULSE_DEV_API_PORT PULSE_DEV_API_URL PULSE_DEV_WS_URL+ unset PULSE_ENABLE_PROXMOX_GUEST_DOCKER_DETECTION PULSE_ENABLE_PROXMOX_GUEST_DOCKER_INVENTORY+ unset ALLOWED_ORIGINS+ LAN_IP=192.168.50.10+ ALL_IPS="192.168.50.10"+ }++ reset_network_env+ PULSE_DEV_LAB_AGENTS=true+ hot_dev_configure_network_defaults+ printf "first_lab=%s\n" "${PULSE_DEV_LAB_AGENTS}"+ printf "first_bind=%s\n" "${BIND_ADDRESS}"+ printf "remembered_after_first=%s\n" "$(test -f "${HOT_DEV_LAB_MODE_FILE}" && echo yes || echo no)"++ reset_network_env+ unset PULSE_DEV_LAB_AGENTS+ hot_dev_configure_network_defaults+ printf "remembered_lab=%s\n" "${PULSE_DEV_LAB_AGENTS:-}"+ printf "remembered_bind=%s\n" "${BIND_ADDRESS}"++ reset_network_env+ PULSE_DEV_LAB_AGENTS=false+ hot_dev_configure_network_defaults+ printf "cleared_lab=%s\n" "${PULSE_DEV_LAB_AGENTS:-}"+ printf "cleared_bind=%s\n" "${BIND_ADDRESS}"+ printf "remembered_after_clear=%s\n" "$(test -f "${HOT_DEV_LAB_MODE_FILE}" && echo yes || echo no)"+ '+ )"++ assert_contains "explicit lab-agent mode starts in lab mode" "${output}" "first_lab=true"+ assert_contains "explicit lab-agent mode binds backend on all interfaces" "${output}" "first_bind=0.0.0.0"+ assert_contains "explicit lab-agent mode is remembered locally" "${output}" "remembered_after_first=yes"+ assert_contains "ordinary later start inherits remembered lab-agent mode" "${output}" "remembered_lab=true"+ assert_contains "remembered lab-agent mode keeps LAN backend binding" "${output}" "remembered_bind=0.0.0.0"+ assert_contains "explicit false override clears lab-agent mode" "${output}" "cleared_lab=false"+ assert_contains "explicit false override returns backend to loopback" "${output}" "cleared_bind=127.0.0.1"+ assert_contains "explicit false override removes remembered lab-agent state" "${output}" "remembered_after_clear=no"+}+test_hot_dev_browser_urls_distinguish_bind_and_browser_hosts() {local outputoutput="$(@@ -272,6 +323,7 @@ test_hot_dev_preserves_proxmox_guest_docker_envtest_hot_dev_avoids_self_killing_npm_wrappertest_hot_dev_network_defaults_are_local_first_with_explicit_lan_opt_intest_hot_dev_lab_agent_mode_enables_lan_and_guest_docker_inventory_defaults+test_hot_dev_remembers_explicit_lab_agent_mode_for_later_managed_startstest_hot_dev_browser_urls_distinguish_bind_and_browser_hostsif (( failures > 0 )); thendiff --git a/scripts/tests/test_telemetry_adoption_report.py b/scripts/tests/test_telemetry_adoption_report.pyindex 3fad941544..1cff38589f 100644--- a/scripts/tests/test_telemetry_adoption_report.py+++ b/scripts/tests/test_telemetry_adoption_report.py@@ -120,6 +120,14 @@ class TelemetryAdoptionReportTest(unittest.TestCase):"platform": "binary","received_at": (now - timedelta(hours=2)).strftime("%Y-%m-%d %H:%M:%S"),"event": "heartbeat",+ "paid_license": 1,+ "pulse_intelligence_loop_configured": 1,+ "pulse_intelligence_loop_active_30d": 1,+ "pulse_intelligence_assistant_ai_calls_30d": 9,+ "pulse_intelligence_assistant_context_ai_calls_30d": 4,+ "pulse_intelligence_external_agent_enabled": 1,+ "pulse_intelligence_external_agent_used_30d": 1,+ "pulse_intelligence_mcp_adapter_used_30d": 1,},{"install_id": "install-b",@@ -130,6 +138,15 @@ class TelemetryAdoptionReportTest(unittest.TestCase):"received_at": (now - timedelta(hours=5)).strftime("%Y-%m-%d %H:%M:%S"),"event": "heartbeat","agent_hosts": 3,+ "paid_license": 0,+ "pulse_intelligence_loop_configured": 1,+ "pulse_intelligence_loop_active_30d": 1,+ "pulse_intelligence_governed_action_active_30d": 1,+ "pulse_intelligence_patrol_runs_30d": 2,+ "pulse_intelligence_action_plans_30d": 2,+ "pulse_intelligence_approval_requests_30d": 1,+ "pulse_intelligence_approved_action_attempts_30d": 1,+ "pulse_intelligence_approved_action_successes_30d": 1,},{"install_id": "install-b",@@ -145,15 +162,36 @@ class TelemetryAdoptionReportTest(unittest.TestCase):"received_at": (now - timedelta(days=2, hours=1)).strftime("%Y-%m-%d %H:%M:%S"),"event": "heartbeat","agent_hosts": 2,+ "paid_license": 1,"patrol_enabled": 1,+ "pulse_intelligence_loop_configured": 1,+ },+ {+ "install_id": "install-d",+ "version": "v6.0.0-rc.1",+ "version_channel": "rc",+ "version_is_published_release": 1,+ "platform": "binary",+ "received_at": (now - timedelta(days=20)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_loop_configured": 1,+ "pulse_intelligence_loop_active_30d": 1,+ "pulse_intelligence_complete_operations_loop_30d": 1,+ "pulse_intelligence_approved_execution_loop_30d": 1,+ "pulse_intelligence_external_agent_used_30d": 1,+ "pulse_intelligence_patrol_runs_30d": 1,+ "pulse_intelligence_action_plans_30d": 1,+ "pulse_intelligence_approved_action_attempts_30d": 1,+ "pulse_intelligence_approved_action_successes_30d": 1,},]summary = report.summarize_rows({"latest_ping": rows[0]["received_at"],- "total_rows": 4,- "total_distinct_installs": 3,+ "total_rows": 5,+ "total_distinct_installs": 4,},rows,published_versions={"6.0.0-rc.1"},@@ -233,6 +271,984 @@ class TelemetryAdoptionReportTest(unittest.TestCase):self.assertEqual(signals["agent_hosts"]["total"], 3)self.assertEqual(signals["agent_hosts"]["group"], "deep")self.assertEqual(signals["pve_nodes"]["group"], "core")+ pulse_loop = summary["pulse_intelligence_value_loop_7d"]+ self.assertEqual(pulse_loop["active_installs"], 3)+ self.assertEqual(pulse_loop["paid_installs"], 2)+ self.assertEqual(pulse_loop["free_installs"], 1)+ loop_flags = {entry["field"]: entry for entry in pulse_loop["boolean_signals"]}+ self.assertEqual(loop_flags["pulse_intelligence_loop_configured"]["installs"], 3)+ self.assertEqual(loop_flags["pulse_intelligence_loop_configured"]["paid_installs"], 2)+ self.assertEqual(loop_flags["pulse_intelligence_loop_active_30d"]["installs"], 2)+ self.assertEqual(loop_flags["pulse_intelligence_governed_action_active_30d"]["free_installs"], 1)+ loop_counts = {entry["field"]: entry for entry in pulse_loop["count_signals"]}+ self.assertEqual(loop_counts["pulse_intelligence_assistant_ai_calls_30d"]["total"], 9)+ self.assertEqual(loop_counts["pulse_intelligence_assistant_ai_calls_30d"]["paid_total"], 9)+ self.assertEqual(loop_counts["pulse_intelligence_assistant_context_ai_calls_30d"]["total"], 4)+ self.assertEqual(loop_counts["pulse_intelligence_assistant_context_ai_calls_30d"]["paid_total"], 4)+ self.assertEqual(loop_counts["pulse_intelligence_action_plans_30d"]["free_total"], 2)+ self.assertEqual(loop_counts["pulse_intelligence_approved_action_successes_30d"]["free_total"], 1)+ cohorts = {+ entry["key"]: entry+ for entry in summary["pulse_intelligence_outcome_cohorts"]["cohorts"]+ }+ self.assertEqual(cohorts["loop_configured"]["installs"], 4)+ self.assertEqual(cohorts["loop_configured"]["retained_7d"], 3)+ self.assertEqual(cohorts["loop_configured"]["retained_7d_rate_pct"], 75)+ self.assertEqual(cohorts["loop_configured"]["paid_latest"], 2)+ self.assertEqual(cohorts["loop_configured"]["paid_latest_rate_pct"], 50)+ self.assertEqual(cohorts["loop_configured"]["free_latest"], 2)+ self.assertEqual(cohorts["loop_active_30d"]["installs"], 3)+ self.assertEqual(cohorts["loop_active_30d"]["retained_7d"], 2)+ self.assertEqual(cohorts["loop_active_30d"]["retained_7d_rate_pct"], 66.67)+ self.assertEqual(cohorts["complete_operations_loop_30d"]["installs"], 1)+ self.assertEqual(cohorts["complete_operations_loop_30d"]["free_latest"], 1)+ self.assertEqual(cohorts["complete_operations_loop_30d"]["retained_7d"], 0)+ self.assertEqual(cohorts["complete_operations_loop_30d"]["retained_7d_rate_pct"], 0)+ self.assertEqual(cohorts["approved_execution_loop_30d"]["installs"], 1)+ self.assertEqual(cohorts["approved_execution_loop_30d"]["free_latest"], 1)+ self.assertEqual(cohorts["assistant_activity"]["installs"], 1)+ self.assertEqual(cohorts["assistant_context_activity"]["installs"], 1)+ self.assertEqual(cohorts["patrol_activity"]["installs"], 2)+ self.assertEqual(cohorts["patrol_activity"]["retained_7d"], 1)+ self.assertEqual(cohorts["external_agent_used_30d"]["installs"], 2)+ self.assertEqual(cohorts["external_agent_used_30d"]["retained_7d"], 1)+ self.assertEqual(cohorts["mcp_adapter_used_30d"]["installs"], 1)+ self.assertEqual(cohorts["mcp_adapter_used_30d"]["retained_7d"], 1)+ self.assertEqual(cohorts["governed_action_active_30d"]["installs"], 2)+ self.assertEqual(cohorts["governed_action_active_30d"]["retained_7d"], 1)+ self.assertEqual(cohorts["approved_action_execution_30d"]["installs"], 2)+ self.assertEqual(cohorts["approved_action_execution_30d"]["retained_7d"], 1)+ self.assertEqual(cohorts["approved_action_success_30d"]["installs"], 2)+ self.assertEqual(cohorts["approved_action_success_30d"]["retained_7d"], 1)+ funnel = {+ entry["key"]: entry+ for entry in summary["pulse_intelligence_operations_loop_funnel"]["stages"]+ }+ self.assertEqual(funnel["configured"]["installs"], 4)+ self.assertEqual(funnel["configured"]["retained_7d"], 3)+ self.assertEqual(funnel["configured"]["retained_7d_rate_pct"], 75)+ self.assertEqual(funnel["patrol_activity"]["installs"], 2)+ self.assertEqual(funnel["patrol_activity"]["retained_7d"], 1)+ self.assertEqual(funnel["patrol_activity"]["retained_7d_rate_pct"], 50)+ self.assertEqual(funnel["assistant_mcp_collaboration"]["installs"], 2)+ self.assertEqual(funnel["assistant_mcp_collaboration"]["retained_7d"], 1)+ self.assertEqual(funnel["governed_action"]["installs"], 2)+ self.assertEqual(funnel["governed_action"]["retained_7d"], 1)+ self.assertEqual(funnel["approved_action_execution"]["installs"], 2)+ self.assertEqual(funnel["approved_action_execution"]["retained_7d"], 1)+ self.assertEqual(funnel["approved_action_success"]["installs"], 2)+ self.assertEqual(funnel["approved_action_success"]["retained_7d"], 1)+ self.assertEqual(funnel["complete_operations_loop"]["installs"], 1)+ self.assertEqual(funnel["complete_operations_loop"]["retained_7d"], 0)+ self.assertEqual(funnel["complete_operations_loop"]["free_latest"], 1)+ self.assertEqual(funnel["approved_execution_loop"]["installs"], 1)+ self.assertEqual(funnel["approved_execution_loop"]["retained_7d"], 0)+ self.assertEqual(funnel["approved_execution_loop"]["free_latest"], 1)++ def test_pulse_intelligence_outcome_cohorts_record_observed_conversion(self) -> None:+ now = datetime.now(timezone.utc).replace(microsecond=0)+ rows = [+ {+ "install_id": "converted",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(days=2)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_loop_configured": 1,+ "pulse_intelligence_assistant_ai_calls_30d": 1,+ "pulse_intelligence_assistant_context_ai_calls_30d": 1,+ "pulse_intelligence_mcp_adapter_used_30d": 1,+ },+ {+ "install_id": "converted",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ "pulse_intelligence_loop_active_30d": 1,+ "pulse_intelligence_assistant_ai_calls_30d": 3,+ "pulse_intelligence_assistant_context_ai_calls_30d": 3,+ "pulse_intelligence_mcp_adapter_used_30d": 1,+ },+ {+ "install_id": "still-free",+ "version": "v6.0.0-rc.1",+ "platform": "docker",+ "received_at": (now - timedelta(hours=2)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_loop_configured": 1,+ "pulse_intelligence_patrol_runs_30d": 1,+ },+ {+ "install_id": "paid-first",+ "version": "v6.0.0-rc.1",+ "platform": "docker",+ "received_at": (now - timedelta(hours=3)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ "pulse_intelligence_loop_active_30d": 1,+ },+ {+ "install_id": "unknown-first",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(hours=4)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "pulse_intelligence_loop_configured": 1,+ },+ ]++ summary = report.summarize_rows(+ {+ "latest_ping": rows[1]["received_at"],+ "total_rows": len(rows),+ "total_distinct_installs": 4,+ },+ rows,+ published_versions={"6.0.0-rc.1"},+ )++ cohorts = {+ entry["key"]: entry+ for entry in summary["pulse_intelligence_outcome_cohorts"]["cohorts"]+ }+ self.assertEqual(cohorts["loop_configured"]["installs"], 3)+ self.assertEqual(cohorts["loop_configured"]["paid_latest"], 1)+ self.assertEqual(cohorts["loop_configured"]["free_latest"], 2)+ self.assertEqual(cohorts["loop_configured"]["observed_free_starts"], 2)+ self.assertEqual(cohorts["loop_configured"]["observed_free_to_paid"], 1)+ self.assertEqual(cohorts["loop_configured"]["observed_free_to_paid_rate_pct"], 50)+ self.assertEqual(cohorts["loop_configured"]["observed_signal_free_starts"], 2)+ self.assertEqual(cohorts["loop_configured"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(cohorts["loop_configured"]["observed_signal_free_to_paid_rate_pct"], 50)+ self.assertEqual(cohorts["loop_active_30d"]["installs"], 3)+ self.assertEqual(cohorts["loop_active_30d"]["observed_free_starts"], 2)+ self.assertEqual(cohorts["loop_active_30d"]["observed_free_to_paid"], 1)+ self.assertEqual(cohorts["loop_active_30d"]["observed_free_to_paid_rate_pct"], 50)+ self.assertEqual(cohorts["loop_active_30d"]["observed_signal_free_starts"], 2)+ self.assertEqual(cohorts["loop_active_30d"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(cohorts["loop_active_30d"]["observed_signal_free_to_paid_rate_pct"], 50)+ self.assertEqual(cohorts["assistant_activity"]["installs"], 1)+ self.assertEqual(cohorts["assistant_activity"]["observed_free_starts"], 1)+ self.assertEqual(cohorts["assistant_activity"]["observed_free_to_paid"], 1)+ self.assertEqual(cohorts["assistant_activity"]["observed_free_to_paid_rate_pct"], 100)+ self.assertEqual(cohorts["assistant_activity"]["observed_signal_free_starts"], 1)+ self.assertEqual(cohorts["assistant_activity"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(cohorts["assistant_activity"]["observed_signal_free_to_paid_rate_pct"], 100)+ self.assertEqual(cohorts["assistant_context_activity"]["installs"], 1)+ self.assertEqual(cohorts["assistant_context_activity"]["observed_free_starts"], 1)+ self.assertEqual(cohorts["assistant_context_activity"]["observed_free_to_paid"], 1)+ self.assertEqual(cohorts["assistant_context_activity"]["observed_signal_free_starts"], 1)+ self.assertEqual(cohorts["assistant_context_activity"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(cohorts["mcp_adapter_used_30d"]["installs"], 1)+ self.assertEqual(cohorts["mcp_adapter_used_30d"]["observed_free_starts"], 1)+ self.assertEqual(cohorts["mcp_adapter_used_30d"]["observed_free_to_paid"], 1)+ self.assertEqual(cohorts["mcp_adapter_used_30d"]["observed_signal_free_starts"], 1)+ self.assertEqual(cohorts["mcp_adapter_used_30d"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(cohorts["patrol_activity"]["installs"], 1)+ self.assertEqual(cohorts["patrol_activity"]["observed_free_starts"], 1)+ self.assertEqual(cohorts["patrol_activity"]["observed_free_to_paid"], 0)+ self.assertEqual(cohorts["patrol_activity"]["observed_signal_free_starts"], 1)+ self.assertEqual(cohorts["patrol_activity"]["observed_signal_free_to_paid"], 0)++ def test_pulse_intelligence_mcp_adapter_counts_as_external_agent_outcome(self) -> None:+ now = datetime.now(timezone.utc).replace(microsecond=0)+ rows = [+ {+ "install_id": "adapter-only",+ "version": "v6.0.0-rc.1",+ "platform": "docker",+ "received_at": (now - timedelta(days=2)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_mcp_adapter_used_30d": 1,+ },+ {+ "install_id": "adapter-only",+ "version": "v6.0.0-rc.1",+ "platform": "docker",+ "received_at": (now - timedelta(hours=2)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ },+ ]++ summary = report.summarize_rows(+ {+ "latest_ping": rows[1]["received_at"],+ "total_rows": len(rows),+ "total_distinct_installs": 1,+ },+ rows,+ published_versions={"6.0.0-rc.1"},+ )++ cohorts = {+ entry["key"]: entry+ for entry in summary["pulse_intelligence_outcome_cohorts"]["cohorts"]+ }+ self.assertEqual(cohorts["external_agent_used_30d"]["label"], "External agent/MCP used 30d")+ self.assertEqual(cohorts["external_agent_used_30d"]["installs"], 1)+ self.assertEqual(cohorts["external_agent_used_30d"]["paid_latest"], 1)+ self.assertEqual(cohorts["external_agent_used_30d"]["observed_signal_free_starts"], 1)+ self.assertEqual(cohorts["external_agent_used_30d"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(cohorts["mcp_adapter_used_30d"]["installs"], 1)++ stages = {+ entry["key"]: entry+ for entry in summary["pulse_intelligence_operations_loop_funnel"]["stages"]+ }+ self.assertEqual(stages["assistant_mcp_collaboration"]["installs"], 1)+ self.assertEqual(stages["assistant_mcp_collaboration"]["observed_signal_free_to_paid"], 1)++ def test_pulse_intelligence_operations_funnel_requires_all_loop_parts(self) -> None:+ now = datetime.now(timezone.utc).replace(microsecond=0)+ rows = [+ {+ "install_id": "full-loop-before-paid",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(days=3)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_loop_configured": 1,+ "pulse_intelligence_patrol_runs_30d": 1,+ "pulse_intelligence_patrol_new_findings_30d": 1,+ "pulse_intelligence_external_agent_used_30d": 1,+ "pulse_intelligence_governed_action_active_30d": 1,+ "pulse_intelligence_approved_action_attempts_30d": 1,+ "pulse_intelligence_approved_action_successes_30d": 1,+ },+ {+ "install_id": "full-loop-before-paid",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(hours=6)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ },+ {+ "install_id": "paid-first-full-loop",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(hours=7)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ "pulse_intelligence_loop_configured": 1,+ "pulse_intelligence_patrol_runs_30d": 1,+ "pulse_intelligence_patrol_new_findings_30d": 1,+ "pulse_intelligence_external_agent_used_30d": 1,+ "pulse_intelligence_governed_action_active_30d": 1,+ "pulse_intelligence_approved_action_attempts_30d": 1,+ "pulse_intelligence_approved_action_successes_30d": 1,+ },+ {+ "install_id": "full-loop",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(days=2)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_loop_configured": 1,+ "pulse_intelligence_patrol_runs_30d": 1,+ "pulse_intelligence_patrol_new_findings_30d": 1,+ },+ {+ "install_id": "full-loop",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ "pulse_intelligence_external_agent_used_30d": 1,+ "pulse_intelligence_assistant_ai_calls_30d": 2,+ "pulse_intelligence_governed_action_active_30d": 1,+ "pulse_intelligence_action_plans_30d": 1,+ "pulse_intelligence_approved_action_attempts_30d": 1,+ "pulse_intelligence_approved_action_successes_30d": 1,+ },+ {+ "install_id": "patrol-only",+ "version": "v6.0.0-rc.1",+ "platform": "docker",+ "received_at": (now - timedelta(hours=2)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_loop_configured": 1,+ "pulse_intelligence_patrol_new_findings_30d": 1,+ },+ {+ "install_id": "collaboration-action",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(hours=3)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ "pulse_intelligence_loop_configured": 1,+ "pulse_intelligence_assistant_ai_calls_30d": 4,+ "pulse_intelligence_assistant_context_ai_calls_30d": 4,+ "pulse_intelligence_action_plans_30d": 1,+ },+ {+ "install_id": "patrol-collaboration",+ "version": "v6.0.0-rc.1",+ "platform": "docker",+ "received_at": (now - timedelta(hours=4)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_loop_configured": 1,+ "pulse_intelligence_patrol_runs_30d": 2,+ "pulse_intelligence_external_agent_used_30d": 1,+ },+ {+ "install_id": "generic-chat-action",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(hours=5)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ "pulse_intelligence_loop_configured": 1,+ "pulse_intelligence_assistant_ai_calls_30d": 5,+ "pulse_intelligence_action_plans_30d": 1,+ },+ ]++ summary = report.summarize_rows(+ {+ "latest_ping": rows[1]["received_at"],+ "total_rows": len(rows),+ "total_distinct_installs": 7,+ },+ rows,+ published_versions={"6.0.0-rc.1"},+ )++ stages = {+ entry["key"]: entry+ for entry in summary["pulse_intelligence_operations_loop_funnel"]["stages"]+ }+ self.assertEqual(stages["configured"]["installs"], 7)+ self.assertEqual(stages["patrol_activity"]["installs"], 5)+ self.assertEqual(stages["assistant_mcp_collaboration"]["installs"], 5)+ self.assertEqual(stages["governed_action"]["installs"], 5)+ self.assertEqual(stages["approved_action_execution"]["installs"], 3)+ self.assertEqual(stages["approved_action_success"]["installs"], 3)+ self.assertEqual(stages["approved_action_success"]["observed_signal_free_starts"], 1)+ self.assertEqual(stages["approved_action_success"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(stages["complete_operations_loop"]["installs"], 3)+ self.assertEqual(stages["complete_operations_loop"]["paid_latest"], 3)+ self.assertEqual(stages["complete_operations_loop"]["retained_7d"], 3)+ self.assertEqual(stages["complete_operations_loop"]["observed_free_starts"], 2)+ self.assertEqual(stages["complete_operations_loop"]["observed_free_to_paid"], 2)+ self.assertEqual(stages["complete_operations_loop"]["observed_signal_free_starts"], 1)+ self.assertEqual(stages["complete_operations_loop"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(stages["approved_execution_loop"]["installs"], 3)+ self.assertEqual(stages["approved_execution_loop"]["paid_latest"], 3)+ self.assertEqual(stages["approved_execution_loop"]["observed_signal_free_starts"], 1)+ self.assertEqual(stages["approved_execution_loop"]["observed_signal_free_to_paid"], 1)++ def test_pulse_intelligence_operations_funnel_reports_mcp_adapter_loop_value(self) -> None:+ now = datetime.now(timezone.utc).replace(microsecond=0)+ rows = [+ {+ "install_id": "adapter-loop-before-paid",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(days=3)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_patrol_runs_30d": 1,+ "pulse_intelligence_patrol_new_findings_30d": 1,+ "pulse_intelligence_mcp_adapter_used_30d": 1,+ "pulse_intelligence_governed_action_active_30d": 1,+ "pulse_intelligence_action_plans_30d": 1,+ "pulse_intelligence_approved_action_attempts_30d": 1,+ "pulse_intelligence_approved_action_successes_30d": 1,+ },+ {+ "install_id": "adapter-loop-before-paid",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ },+ {+ "install_id": "direct-agent-loop",+ "version": "v6.0.0-rc.1",+ "platform": "docker",+ "received_at": (now - timedelta(hours=2)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ "pulse_intelligence_patrol_runs_30d": 1,+ "pulse_intelligence_patrol_new_findings_30d": 1,+ "pulse_intelligence_external_agent_used_30d": 1,+ "pulse_intelligence_governed_action_active_30d": 1,+ "pulse_intelligence_approved_action_attempts_30d": 1,+ "pulse_intelligence_approved_action_successes_30d": 1,+ },+ {+ "install_id": "adapter-without-patrol",+ "version": "v6.0.0-rc.1",+ "platform": "docker",+ "received_at": (now - timedelta(hours=3)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_mcp_adapter_used_30d": 1,+ "pulse_intelligence_governed_action_active_30d": 1,+ "pulse_intelligence_action_plans_30d": 1,+ },+ {+ "install_id": "adapter-without-action",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(hours=4)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ "pulse_intelligence_patrol_runs_30d": 1,+ "pulse_intelligence_mcp_adapter_used_30d": 1,+ },+ ]++ summary = report.summarize_rows(+ {+ "latest_ping": rows[1]["received_at"],+ "total_rows": len(rows),+ "total_distinct_installs": 4,+ },+ rows,+ published_versions={"6.0.0-rc.1"},+ )++ stages = {+ entry["key"]: entry+ for entry in summary["pulse_intelligence_operations_loop_funnel"]["stages"]+ }+ self.assertEqual(stages["complete_operations_loop"]["installs"], 2)+ self.assertEqual(stages["approved_execution_loop"]["installs"], 2)+ self.assertEqual(stages["approved_action_success"]["installs"], 2)++ adapter_loop = stages["mcp_adapter_operations_loop"]+ self.assertEqual(adapter_loop["label"], "Pulse MCP adapter operations loop")+ self.assertEqual(+ adapter_loop["required_signal_groups"],+ ["mcp_adapter_operations_loop"],+ )+ self.assertEqual(adapter_loop["installs"], 1)+ self.assertEqual(adapter_loop["retained_7d"], 1)+ self.assertEqual(adapter_loop["retained_7d_rate_pct"], 100)+ self.assertEqual(adapter_loop["paid_latest"], 1)+ self.assertEqual(adapter_loop["paid_latest_rate_pct"], 100)+ self.assertEqual(adapter_loop["observed_free_starts"], 1)+ self.assertEqual(adapter_loop["observed_free_to_paid"], 1)+ self.assertEqual(adapter_loop["observed_free_to_paid_rate_pct"], 100)+ self.assertEqual(adapter_loop["observed_signal_free_starts"], 1)+ self.assertEqual(adapter_loop["observed_signal_free_to_paid"], 1)+ self.assertEqual(adapter_loop["observed_signal_free_to_paid_rate_pct"], 100)++ adapter_approved = stages["mcp_adapter_approved_execution_loop"]+ self.assertEqual(+ adapter_approved["required_signal_groups"],+ ["mcp_adapter_approved_execution_loop"],+ )+ self.assertEqual(adapter_approved["installs"], 1)+ self.assertEqual(adapter_approved["retained_7d_rate_pct"], 100)+ self.assertEqual(adapter_approved["paid_latest_rate_pct"], 100)+ self.assertEqual(adapter_approved["observed_signal_free_to_paid_rate_pct"], 100)++ adapter_success = stages["mcp_adapter_approved_success_loop"]+ self.assertEqual(+ adapter_success["required_signal_groups"],+ ["mcp_adapter_approved_success_loop"],+ )+ self.assertEqual(adapter_success["installs"], 1)+ self.assertEqual(adapter_success["retained_7d_rate_pct"], 100)+ self.assertEqual(adapter_success["paid_latest_rate_pct"], 100)+ self.assertEqual(adapter_success["observed_signal_free_to_paid_rate_pct"], 100)++ def test_pulse_intelligence_reports_source_specific_loop_value(self) -> None:+ now = datetime.now(timezone.utc).replace(microsecond=0)+ rows = [+ {+ "install_id": "assistant-before-paid",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(days=3)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_operations_loop_starter_requests_30d": 2,+ "pulse_intelligence_assistant_operations_loop_starter_requests_30d": 2,+ "pulse_intelligence_assistant_operations_loop_30d": 1,+ "pulse_intelligence_assistant_approved_execution_loop_30d": 1,+ "pulse_intelligence_assistant_approved_action_success_loop_30d": 1,+ "pulse_intelligence_assistant_resolved_operations_loop_30d": 1,+ "pulse_intelligence_rejected_action_decisions_30d": 1,+ },+ {+ "install_id": "assistant-before-paid",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ "pulse_intelligence_operations_loop_starter_requests_30d": 2,+ "pulse_intelligence_assistant_operations_loop_starter_requests_30d": 2,+ "pulse_intelligence_assistant_operations_loop_30d": 1,+ "pulse_intelligence_assistant_approved_execution_loop_30d": 1,+ "pulse_intelligence_assistant_approved_action_success_loop_30d": 1,+ "pulse_intelligence_assistant_resolved_operations_loop_30d": 1,+ "pulse_intelligence_rejected_action_decisions_30d": 1,+ },+ {+ "install_id": "direct-agent-loop",+ "version": "v6.0.0-rc.1",+ "platform": "docker",+ "received_at": (now - timedelta(hours=2)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ "pulse_intelligence_external_agent_operations_loop_30d": 1,+ "pulse_intelligence_external_agent_approved_execution_loop_30d": 1,+ "pulse_intelligence_external_agent_approved_action_success_loop_30d": 1,+ "pulse_intelligence_external_agent_resolved_operations_loop_30d": 1,+ },+ {+ "install_id": "patrol-before-paid",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(days=4)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_operations_loop_starter_requests_30d": 1,+ "pulse_intelligence_patrol_operations_loop_starter_requests_30d": 1,+ },+ {+ "install_id": "patrol-before-paid",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(minutes=40)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ "pulse_intelligence_operations_loop_starter_requests_30d": 1,+ "pulse_intelligence_patrol_operations_loop_starter_requests_30d": 1,+ },+ {+ "install_id": "legacy-pro-entry-before-paid",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(days=5)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_operations_loop_starter_requests_30d": 1,+ "pulse_intelligence_patrol_control_operations_loop_starter_requests_30d": 1,+ "pulse_intelligence_pro_activation_operations_loop_starter_requests_30d": 1,+ },+ {+ "install_id": "legacy-pro-entry-before-paid",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(minutes=20)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ "pulse_intelligence_operations_loop_starter_requests_30d": 1,+ "pulse_intelligence_patrol_control_operations_loop_starter_requests_30d": 1,+ "pulse_intelligence_pro_activation_operations_loop_starter_requests_30d": 1,+ },+ {+ "install_id": "mcp-before-paid",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(days=2)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_external_agent_operations_loop_30d": 1,+ "pulse_intelligence_external_agent_approved_execution_loop_30d": 1,+ "pulse_intelligence_external_agent_approved_action_success_loop_30d": 1,+ "pulse_intelligence_external_agent_resolved_operations_loop_30d": 1,+ "pulse_intelligence_mcp_adapter_operations_loop_30d": 1,+ "pulse_intelligence_mcp_adapter_approved_execution_loop_30d": 1,+ "pulse_intelligence_mcp_adapter_approved_action_success_loop_30d": 1,+ "pulse_intelligence_mcp_adapter_resolved_operations_loop_30d": 1,+ "pulse_intelligence_operations_loop_starter_requests_30d": 1,+ "pulse_intelligence_mcp_operations_loop_starter_requests_30d": 1,+ },+ {+ "install_id": "mcp-before-paid",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(minutes=30)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ "pulse_intelligence_external_agent_operations_loop_30d": 1,+ "pulse_intelligence_external_agent_approved_execution_loop_30d": 1,+ "pulse_intelligence_external_agent_approved_action_success_loop_30d": 1,+ "pulse_intelligence_external_agent_resolved_operations_loop_30d": 1,+ "pulse_intelligence_mcp_adapter_operations_loop_30d": 1,+ "pulse_intelligence_mcp_adapter_approved_execution_loop_30d": 1,+ "pulse_intelligence_mcp_adapter_approved_action_success_loop_30d": 1,+ "pulse_intelligence_mcp_adapter_resolved_operations_loop_30d": 1,+ "pulse_intelligence_operations_loop_starter_requests_30d": 1,+ "pulse_intelligence_mcp_operations_loop_starter_requests_30d": 1,+ },+ ]++ summary = report.summarize_rows(+ {+ "latest_ping": (now - timedelta(minutes=20)).strftime("%Y-%m-%d %H:%M:%S"),+ "total_rows": len(rows),+ "total_distinct_installs": 5,+ },+ rows,+ published_versions={"6.0.0-rc.1"},+ )++ loop_flags = {+ entry["field"]: entry+ for entry in summary["pulse_intelligence_value_loop_7d"]["boolean_signals"]+ }+ self.assertEqual(loop_flags["pulse_intelligence_assistant_operations_loop_30d"]["installs"], 1)+ self.assertEqual(loop_flags["pulse_intelligence_external_agent_operations_loop_30d"]["installs"], 2)+ self.assertEqual(loop_flags["pulse_intelligence_mcp_adapter_operations_loop_30d"]["installs"], 1)+ self.assertEqual(+ loop_flags["pulse_intelligence_mcp_adapter_resolved_operations_loop_30d"]["paid_installs"],+ 1,+ )++ loop_counts = {+ entry["field"]: entry+ for entry in summary["pulse_intelligence_value_loop_7d"]["count_signals"]+ }+ self.assertEqual(loop_counts["pulse_intelligence_operations_loop_starter_requests_30d"]["total"], 5)+ self.assertEqual(+ loop_counts["pulse_intelligence_assistant_operations_loop_starter_requests_30d"]["total"],+ 2,+ )+ self.assertEqual(+ loop_counts["pulse_intelligence_patrol_operations_loop_starter_requests_30d"]["total"],+ 1,+ )+ self.assertEqual(+ loop_counts["pulse_intelligence_patrol_control_operations_loop_starter_requests_30d"]["total"],+ 1,+ )+ self.assertEqual(+ loop_counts["pulse_intelligence_pro_activation_operations_loop_starter_requests_30d"]["total"],+ 1,+ )+ self.assertEqual(+ loop_counts["pulse_intelligence_mcp_operations_loop_starter_requests_30d"]["total"],+ 1,+ )+ self.assertEqual(loop_counts["pulse_intelligence_rejected_action_decisions_30d"]["total"], 1)++ cohorts = {+ entry["key"]: entry+ for entry in summary["pulse_intelligence_outcome_cohorts"]["cohorts"]+ }+ self.assertEqual(cohorts["assistant_operations_loop_30d"]["installs"], 1)+ self.assertEqual(cohorts["assistant_operations_loop_30d"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(cohorts["assistant_resolved_operations_loop_30d"]["installs"], 1)+ self.assertEqual(cohorts["external_agent_operations_loop_30d"]["installs"], 2)+ self.assertEqual(cohorts["external_agent_operations_loop_30d"]["paid_latest"], 2)+ self.assertEqual(cohorts["external_agent_resolved_operations_loop_30d"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(cohorts["mcp_adapter_operations_loop_30d"]["installs"], 1)+ self.assertEqual(cohorts["mcp_adapter_resolved_operations_loop_30d"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(cohorts["operations_loop_starter_requests"]["installs"], 4)+ self.assertEqual(cohorts["patrol_operations_loop_starter_requests"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(+ cohorts["patrol_control_operations_loop_starter_requests"]["observed_signal_free_to_paid"],+ 2,+ )+ self.assertEqual(+ cohorts["pro_activation_operations_loop_starter_requests"]["observed_signal_free_to_paid"],+ 1,+ )+ self.assertEqual(cohorts["mcp_operations_loop_starter_requests"]["observed_signal_free_to_paid"], 1)++ stages = {+ entry["key"]: entry+ for entry in summary["pulse_intelligence_operations_loop_funnel"]["stages"]+ }+ self.assertEqual(stages["complete_operations_loop"]["installs"], 3)+ self.assertEqual(stages["approved_execution_loop"]["installs"], 3)+ self.assertEqual(stages["resolved_operations_loop"]["installs"], 3)+ self.assertEqual(stages["assistant_operations_loop"]["installs"], 1)+ self.assertEqual(stages["assistant_operations_loop"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(stages["assistant_approved_success_loop"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(stages["assistant_resolved_operations_loop"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(stages["external_agent_operations_loop"]["installs"], 2)+ self.assertEqual(stages["external_agent_resolved_operations_loop"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(stages["mcp_adapter_operations_loop"]["installs"], 1)+ self.assertEqual(stages["mcp_adapter_resolved_operations_loop"]["observed_signal_free_to_paid"], 1)++ def test_pulse_intelligence_reports_patrol_control_resolved_loop_as_first_class_signal(self) -> None:+ now = datetime.now(timezone.utc).replace(microsecond=0)+ rows = [+ {+ "install_id": "legacy-pro-completed-loop",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(days=4)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_pro_activation_operations_loop_starter_requests_30d": 1,+ "pulse_intelligence_pro_activation_completed_operations_loop_30d": 1,+ },+ {+ "install_id": "legacy-pro-completed-loop",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(hours=2)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ "pulse_intelligence_pro_activation_operations_loop_starter_requests_30d": 1,+ "pulse_intelligence_pro_activation_completed_operations_loop_30d": 1,+ "pulse_intelligence_pro_activation_paid_completed_operations_loop_30d": 1,+ },+ {+ "install_id": "explicit-patrol-control-completed-loop",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(days=2)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_patrol_control_operations_loop_starter_requests_30d": 1,+ "pulse_intelligence_patrol_control_completed_operations_loop_30d": 1,+ },+ {+ "install_id": "explicit-patrol-control-completed-loop",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(minutes=90)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ "pulse_intelligence_patrol_control_operations_loop_starter_requests_30d": 1,+ "pulse_intelligence_patrol_control_completed_operations_loop_30d": 1,+ "pulse_intelligence_patrol_control_paid_completed_operations_loop_30d": 1,+ },+ {+ "install_id": "explicit-patrol-control-resolved-loop",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(days=3)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_patrol_control_operations_loop_starter_requests_30d": 1,+ "pulse_intelligence_patrol_control_resolved_operations_loop_30d": 1,+ },+ {+ "install_id": "explicit-patrol-control-resolved-loop",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ "pulse_intelligence_patrol_control_operations_loop_starter_requests_30d": 1,+ "pulse_intelligence_patrol_control_resolved_operations_loop_30d": 1,+ "pulse_intelligence_patrol_control_paid_resolved_operations_loop_30d": 1,+ },+ {+ "install_id": "legacy-pro-resolved-loop",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(days=3)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_pro_activation_operations_loop_starter_requests_30d": 1,+ "pulse_intelligence_pro_activation_resolved_operations_loop_30d": 1,+ },+ {+ "install_id": "legacy-pro-resolved-loop",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(minutes=45)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ "pulse_intelligence_pro_activation_operations_loop_starter_requests_30d": 1,+ "pulse_intelligence_pro_activation_resolved_operations_loop_30d": 1,+ "pulse_intelligence_pro_activation_paid_resolved_operations_loop_30d": 1,+ },+ ]++ summary = report.summarize_rows(+ {+ "latest_ping": rows[-1]["received_at"],+ "total_rows": len(rows),+ "total_distinct_installs": 4,+ },+ rows,+ published_versions={"6.0.0-rc.1"},+ )++ loop_flags = {+ entry["field"]: entry+ for entry in summary["pulse_intelligence_value_loop_7d"]["boolean_signals"]+ }+ patrol_control_completed = loop_flags[+ "pulse_intelligence_patrol_control_completed_operations_loop_30d"+ ]+ self.assertEqual(patrol_control_completed["installs"], 1)+ self.assertEqual(patrol_control_completed["paid_installs"], 1)+ patrol_control_resolved = loop_flags[+ "pulse_intelligence_patrol_control_resolved_operations_loop_30d"+ ]+ self.assertEqual(patrol_control_resolved["installs"], 1)+ self.assertEqual(patrol_control_resolved["paid_installs"], 1)+ legacy_completed = loop_flags["pulse_intelligence_pro_activation_completed_operations_loop_30d"]+ self.assertEqual(legacy_completed["installs"], 1)+ self.assertEqual(legacy_completed["paid_installs"], 1)+ legacy_resolved = loop_flags["pulse_intelligence_pro_activation_resolved_operations_loop_30d"]+ self.assertEqual(legacy_resolved["installs"], 1)+ self.assertEqual(legacy_resolved["paid_installs"], 1)++ cohorts = {+ entry["key"]: entry+ for entry in summary["pulse_intelligence_outcome_cohorts"]["cohorts"]+ }+ self.assertEqual(cohorts["patrol_control_operations_loop_starter_requests"]["installs"], 4)+ self.assertEqual(cohorts["pro_activation_operations_loop_starter_requests"]["installs"], 2)+ self.assertEqual(cohorts["patrol_control_completed_operations_loop_30d"]["installs"], 2)+ self.assertEqual(+ cohorts["patrol_control_completed_operations_loop_30d"]["observed_signal_free_to_paid"],+ 2,+ )+ self.assertEqual(cohorts["patrol_control_resolved_operations_loop_30d"]["installs"], 2)+ self.assertEqual(+ cohorts["patrol_control_resolved_operations_loop_30d"]["observed_signal_free_to_paid"],+ 2,+ )+ self.assertEqual(cohorts["patrol_control_paid_completed_operations_loop_30d"]["paid_latest"], 2)+ self.assertEqual(cohorts["patrol_control_paid_resolved_operations_loop_30d"]["paid_latest"], 2)++ stages = {+ entry["key"]: entry+ for entry in summary["pulse_intelligence_operations_loop_funnel"]["stages"]+ }+ self.assertNotIn("pro_activation_completed_operations_loop", stages)+ self.assertNotIn("pro_activation_resolved_operations_loop", stages)+ self.assertEqual(stages["complete_operations_loop"]["installs"], 2)+ self.assertEqual(stages["resolved_operations_loop"]["installs"], 2)+ self.assertEqual(stages["patrol_control_completed_operations_loop"]["installs"], 2)+ self.assertEqual(+ stages["patrol_control_completed_operations_loop"]["observed_signal_free_to_paid"],+ 2,+ )+ self.assertEqual(stages["patrol_control_resolved_operations_loop"]["installs"], 2)+ self.assertEqual(+ stages["patrol_control_resolved_operations_loop"]["observed_signal_free_to_paid"],+ 2,+ )++ def test_pulse_intelligence_reports_external_agent_capability_activity(self) -> None:+ now = datetime.now(timezone.utc).replace(microsecond=0)+ rows = [+ {+ "install_id": "capability-loop-before-paid",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(days=2)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_loop_configured": 1,+ "pulse_intelligence_patrol_runs_30d": 1,+ "pulse_intelligence_patrol_new_findings_30d": 1,+ "pulse_intelligence_external_agent_context_requests_30d": 2,+ "pulse_intelligence_external_agent_action_requests_30d": 1,+ "pulse_intelligence_governed_action_active_30d": 1,+ "pulse_intelligence_approved_action_attempts_30d": 1,+ "pulse_intelligence_approved_action_successes_30d": 1,+ },+ {+ "install_id": "capability-loop-before-paid",+ "version": "v6.0.0-rc.1",+ "platform": "binary",+ "received_at": (now - timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 1,+ "pulse_intelligence_loop_configured": 1,+ "pulse_intelligence_patrol_runs_30d": 1,+ "pulse_intelligence_patrol_new_findings_30d": 1,+ "pulse_intelligence_external_agent_context_requests_30d": 3,+ "pulse_intelligence_external_agent_action_requests_30d": 2,+ "pulse_intelligence_governed_action_active_30d": 1,+ "pulse_intelligence_approved_action_attempts_30d": 1,+ "pulse_intelligence_approved_action_successes_30d": 1,+ },+ {+ "install_id": "assistant-only",+ "version": "v6.0.0-rc.1",+ "platform": "docker",+ "received_at": (now - timedelta(hours=2)).strftime("%Y-%m-%d %H:%M:%S"),+ "event": "heartbeat",+ "paid_license": 0,+ "pulse_intelligence_assistant_ai_calls_30d": 4,+ },+ ]++ summary = report.summarize_rows(+ {+ "latest_ping": rows[1]["received_at"],+ "total_rows": len(rows),+ "total_distinct_installs": 2,+ },+ rows,+ published_versions={"6.0.0-rc.1"},+ )++ loop_counts = {+ entry["field"]: entry+ for entry in summary["pulse_intelligence_value_loop_7d"]["count_signals"]+ }+ self.assertEqual(+ loop_counts["pulse_intelligence_external_agent_context_requests_30d"]["installs"],+ 1,+ )+ self.assertEqual(+ loop_counts["pulse_intelligence_external_agent_context_requests_30d"]["total"],+ 3,+ )+ self.assertEqual(+ loop_counts["pulse_intelligence_external_agent_context_requests_30d"]["paid_total"],+ 3,+ )+ self.assertEqual(loop_counts["pulse_intelligence_approved_action_successes_30d"]["installs"], 1)++ cohorts = {+ entry["key"]: entry+ for entry in summary["pulse_intelligence_outcome_cohorts"]["cohorts"]+ }+ self.assertEqual(cohorts["external_agent_used_30d"]["installs"], 1)+ self.assertEqual(cohorts["external_agent_used_30d"]["paid_latest"], 1)+ self.assertEqual(cohorts["external_agent_used_30d"]["observed_signal_free_starts"], 1)+ self.assertEqual(cohorts["external_agent_used_30d"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(cohorts["external_agent_context_requests"]["installs"], 1)+ self.assertEqual(cohorts["external_agent_context_requests"]["paid_latest"], 1)+ self.assertEqual(cohorts["external_agent_context_requests"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(cohorts["external_agent_action_requests"]["installs"], 1)+ self.assertEqual(cohorts["external_agent_action_requests"]["paid_latest"], 1)+ self.assertEqual(cohorts["approved_action_success_30d"]["installs"], 1)+ self.assertEqual(cohorts["approved_action_success_30d"]["paid_latest"], 1)++ stages = {+ entry["key"]: entry+ for entry in summary["pulse_intelligence_operations_loop_funnel"]["stages"]+ }+ self.assertEqual(stages["assistant_mcp_collaboration"]["installs"], 1)+ self.assertEqual(stages["assistant_mcp_collaboration"]["paid_latest"], 1)+ self.assertEqual(stages["complete_operations_loop"]["installs"], 1)+ self.assertEqual(stages["complete_operations_loop"]["paid_latest"], 1)+ self.assertEqual(stages["complete_operations_loop"]["observed_signal_free_starts"], 1)+ self.assertEqual(stages["complete_operations_loop"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(stages["approved_execution_loop"]["installs"], 1)+ self.assertEqual(stages["approved_execution_loop"]["paid_latest"], 1)+ self.assertEqual(stages["approved_execution_loop"]["observed_signal_free_starts"], 1)+ self.assertEqual(stages["approved_execution_loop"]["observed_signal_free_to_paid"], 1)+ self.assertEqual(stages["approved_action_success"]["installs"], 1)+ self.assertEqual(stages["approved_action_success"]["paid_latest"], 1)+ self.assertEqual(stages["approved_action_success"]["observed_signal_free_starts"], 1)+ self.assertEqual(stages["approved_action_success"]["observed_signal_free_to_paid"], 1)def test_format_text_includes_latest_install_windows(self) -> None:summary = {@@ -289,6 +1305,109 @@ class TelemetryAdoptionReportTest(unittest.TestCase):],},],+ "pulse_intelligence_value_loop_7d": {+ "active_installs": 157,+ "paid_installs": 42,+ "free_installs": 115,+ "boolean_signals": [+ {+ "field": "pulse_intelligence_loop_configured",+ "label": "Loop configured",+ "installs": 31,+ "paid_installs": 18,+ "free_installs": 13,+ },+ {+ "field": "pulse_intelligence_governed_action_active_30d",+ "label": "Governed action active 30d",+ "installs": 6,+ "paid_installs": 5,+ "free_installs": 1,+ },+ ],+ "count_signals": [+ {+ "field": "pulse_intelligence_assistant_ai_calls_30d",+ "label": "Assistant AI calls 30d",+ "installs": 21,+ "paid_installs": 12,+ "free_installs": 9,+ "total": 88,+ "paid_total": 61,+ "free_total": 27,+ },+ {+ "field": "pulse_intelligence_action_plans_30d",+ "label": "Action plans 30d",+ "installs": 4,+ "paid_installs": 4,+ "free_installs": 0,+ "total": 9,+ "paid_total": 9,+ "free_total": 0,+ },+ ],+ },+ "pulse_intelligence_outcome_cohorts": {+ "retention_window": "7d",+ "cohorts": [+ {+ "key": "loop_configured",+ "label": "Loop configured",+ "installs": 51,+ "retained_7d": 31,+ "paid_latest": 24,+ "free_latest": 27,+ "observed_free_starts": 19,+ "observed_free_to_paid": 6,+ "observed_signal_free_starts": 12,+ "observed_signal_free_to_paid": 5,+ },+ {+ "key": "assistant_activity",+ "label": "Assistant activity",+ "installs": 21,+ "retained_7d": 18,+ "paid_latest": 12,+ "free_latest": 9,+ "observed_free_starts": 8,+ "observed_free_to_paid": 3,+ "observed_signal_free_starts": 6,+ "observed_signal_free_to_paid": 3,+ },+ ],+ },+ "pulse_intelligence_operations_loop_funnel": {+ "retention_window": "7d",+ "stages": [+ {+ "key": "patrol_activity",+ "label": "Patrol detection/investigation",+ "required_signal_groups": ["patrol"],+ "installs": 17,+ "retained_7d": 14,+ "paid_latest": 11,+ "free_latest": 6,+ "observed_free_starts": 7,+ "observed_free_to_paid": 2,+ "observed_signal_free_starts": 5,+ "observed_signal_free_to_paid": 2,+ },+ {+ "key": "complete_operations_loop",+ "label": "Complete operations loop",+ "required_signal_groups": ["patrol_issue", "collaboration", "governed_decision"],+ "installs": 9,+ "retained_7d": 8,+ "paid_latest": 7,+ "free_latest": 2,+ "observed_free_starts": 4,+ "observed_free_to_paid": 2,+ "observed_signal_free_starts": 3,+ "observed_signal_free_to_paid": 1,+ },+ ],+ },"target_release_coverage_7d": {"version": "6.0.0-rc.6","active_installs": 74,@@ -344,6 +1463,42 @@ class TelemetryAdoptionReportTest(unittest.TestCase):self.assertIn(" - PVE nodes: 55 installs, total 131", rendered)self.assertIn(" - AI enabled: 19 installs", rendered)self.assertIn(" - Agent hosts, Patrol enabled", rendered)+ self.assertIn("Pulse Intelligence value loop (7d):", rendered)+ self.assertIn("- paid posture: paid 42, free/community 115", rendered)+ self.assertIn(" - Loop configured: 31 installs (paid 18, free/community 13)", rendered)+ self.assertIn(" - Action plans 30d: 4 installs, total 9 (paid 4 / 9; free/community 0 / 0)", rendered)+ self.assertIn("Pulse Intelligence activation and retention:", rendered)+ self.assertIn("- source window: last 7 day(s)", rendered)+ self.assertIn("- retention definition: latest ping within 7d", rendered)+ self.assertIn(+ " - Loop configured: 51 installs, retained 7d 31 (60.8%), latest paid 24, latest free/community 27",+ rendered,+ )+ self.assertIn(+ "observed free/community starts 19, free-to-paid 6 (31.6%), signal while free/community 12, signal-to-paid 5 (41.7%)",+ rendered,+ )+ self.assertIn(+ " - Assistant activity: 21 installs, retained 7d 18 (85.7%), latest paid 12, latest free/community 9",+ rendered,+ )+ self.assertIn(+ "observed free/community starts 8, free-to-paid 3 (37.5%), signal while free/community 6, signal-to-paid 3 (50.0%)",+ rendered,+ )+ self.assertIn("Pulse Intelligence operations loop funnel:", rendered)+ self.assertIn(+ " - Patrol detection/investigation: 17 installs, retained 7d 14 (82.4%), latest paid 11, latest free/community 6",+ rendered,+ )+ self.assertIn(+ " - Complete operations loop: 9 installs, retained 7d 8 (88.9%), latest paid 7, latest free/community 2",+ rendered,+ )+ self.assertIn(+ "observed free/community starts 4, free-to-paid 2 (50.0%), signal while free/community 3, signal-to-paid 1 (33.3%)",+ rendered,+ )def test_privacy_docs_keep_relay_mobile_handoff_copy_aligned(self) -> None:repo_root = Path(__file__).resolve().parents[2]@@ -358,6 +1513,38 @@ class TelemetryAdoptionReportTest(unittest.TestCase):self.assertNotIn("mobile app pairing", canonical)self.assertNotIn("mobile app pairing", bundled)+ def test_privacy_docs_disclose_derived_pulse_intelligence_reports(self) -> None:+ repo_root = Path(__file__).resolve().parents[2]+ privacy_docs = (+ repo_root / "docs" / "PRIVACY.md",+ repo_root / "frontend-modern" / "public" / "docs" / "PRIVACY.md",+ )++ for path in privacy_docs:+ with self.subTest(path=path.relative_to(repo_root)):+ content = path.read_text(encoding="utf-8")+ self.assertIn("aggregate Pulse Intelligence adoption reports", content)+ self.assertIn("Assistant, direct external-agent, or MCP collaboration", content)+ self.assertIn("Pulse Intelligence Assistant operations loop 30d", content)+ self.assertIn("Pulse Intelligence external agent operations loop 30d", content)+ self.assertIn("Pulse Intelligence Patrol control completed operations loop 30d", content)+ self.assertIn("Pulse Intelligence MCP operations loop starter requests 30d", content)+ self.assertIn("Pulse Intelligence Assistant context AI calls 30d", content)+ self.assertIn("approved action success", content)+ self.assertIn("rejected action decisions", content)+ self.assertIn("Patrol-control completed-work proof", content)+ self.assertIn("observed free-to-paid movement", content)+ self.assertIn(+ "Pulse Intelligence agent/MCP route in the current 30-day telemetry window",+ content,+ )+ self.assertIn("Pulse Intelligence MCP adapter used 30d", content)+ self.assertIn("Compatibility mirror of the Patrol control completed field", content)+ self.assertNotIn("Pro activation completed-loop proof", content)+ self.assertIn("route parameters, resource IDs", content)+ self.assertIn("Those reports do not add prompts, findings", content)+ self.assertIn("account links, or exact commercial tiers", content)+if __name__ == "__main__":unittest.main()diff --git a/tests/integration/tests/18-patrol-runtime-state.spec.ts b/tests/integration/tests/18-patrol-runtime-state.spec.tsindex d429e54596..cfa3e7276d 100644--- a/tests/integration/tests/18-patrol-runtime-state.spec.ts+++ b/tests/integration/tests/18-patrol-runtime-state.spec.ts@@ -956,7 +956,7 @@ test.describe("Patrol runtime-state browser contract", () => {await expect(page.getByText("Failed to start patrol run")).toHaveCount(0);});- test("surfaces scoped trigger context inside the summary and split trigger controls on the Patrol page", async ({+ test("keeps scoped trigger context out of the default Patrol status strip", async ({page,}, testInfo) => {test.skip(@@ -978,15 +978,18 @@ test.describe("Patrol runtime-state browser contract", () => {page.getByText("Recent activity mix: 1 full, 1 alert-triggered, 1 anomaly-triggered",),- ).toBeVisible();+ ).toHaveCount(0);await expect(page.getByText("Trigger mode: 4 queued · busy mode · anomalies off"),- ).toBeVisible();+ ).toHaveCount(0);await expect(- page.getByText("Trigger status: 4 queued · busy mode · anomalies off"),+ page.getByText("Automation: 4 queued · busy mode · anomalies off"),).toBeVisible();- await page.getByRole("button", { name: "Configure Patrol" }).click();+ await expect(+ page.getByRole("link", { name: "Open Patrol settings" }),+ ).toHaveAttribute("href", "/settings/pulse-intelligence/patrol");+ await page.getByRole("link", { name: "Open Patrol settings" }).click();await expect(page.getByText("Alert-Triggered Patrols")).toBeVisible();await expect(page.getByText("Anomaly-Triggered Patrols")).toBeVisible();@@ -995,9 +998,9 @@ test.describe("Patrol runtime-state browser contract", () => {"Alert and anomaly triggers run targeted scoped checks that update",),).toBeVisible();- await expect(page.getByText("Last full patrol")).toBeVisible();- await page.getByRole("button", { name: "Runs" }).click();+ await page.goto("/patrol", { waitUntil: "domcontentloaded" });+ await page.getByRole("button", { name: "History" }).click();await page.getByRole("button", { name: /Alert fired/i }).click();await expect(page.getByText("Selected model does not support Patrol tools"),@@ -1009,7 +1012,7 @@ test.describe("Patrol runtime-state browser contract", () => {await expect(page.getByText(/No endpoints found/)).toHaveCount(0);await expect(page.getByRole("link", { name: "Open Patrol provider settings" }),- ).toHaveAttribute("href", "/settings/system-ai");+ ).toHaveAttribute("href", "/settings/pulse-intelligence/provider");await page.getByTestId("patrol-run-assistant-button").click();const assistantContext = page.getByLabel("Assistant context");@@ -1044,18 +1047,16 @@ test.describe("Patrol runtime-state browser contract", () => {await page.goto("/patrol", { waitUntil: "domcontentloaded" });await expect(- page.getByText(`Trigger status: ${PATROL_EVENT_TRIGGERS_BLOCKED}`),+ page.getByText(`Automation: ${PATROL_EVENT_TRIGGERS_BLOCKED}`),).toBeVisible();await expect(page.getByText(`Trigger mode: ${PATROL_EVENT_TRIGGERS_BLOCKED}`),- ).toBeVisible();+ ).toHaveCount(0);await expect(page.getByText("alerts off")).toHaveCount(0);await expect(page.getByText("anomalies off")).toHaveCount(0);- await page.getByRole("button", { name: "Configure Patrol" }).click();- const configPanel = page.getByRole("dialog", {- name: "Patrol Configuration",- });+ await page.getByRole("link", { name: "Open Patrol settings" }).click();+ const configPanel = page.getByRole("main");await expect(configPanel.getByRole("button", { name: "Alert-Triggered Patrols" }),).toHaveAttribute("aria-pressed", "true");diff --git a/tests/integration/tests/55-self-hosted-upgrade-return.spec.ts b/tests/integration/tests/55-self-hosted-upgrade-return.spec.tsindex 6ac65ae223..dc9cd867f9 100644--- a/tests/integration/tests/55-self-hosted-upgrade-return.spec.ts+++ b/tests/integration/tests/55-self-hosted-upgrade-return.spec.ts@@ -459,7 +459,7 @@ async function openMonitoredSystemUpgradeArrival(page: Page) {);await expect(page.getByText(- "Community includes core monitoring at no cost. Relay is optional for secure access from anywhere, and Pulse Pro adds root-cause analysis, safe remediation workflows, and 90-day history.",+ "Community includes core monitoring at no cost. Relay is optional for secure access from anywhere. Pulse Pro adds Patrol control, alert investigation, verified fixes, and 90-day history.",),).toBeVisible();await expect(page.getByRole("button", { name: "Hide counting rules" })).toHaveCount(0);@@ -535,7 +535,7 @@ test.describe("Self-hosted upgrade return flow", () => {),).toBeVisible();await expect(activationSummary.getByText("Available now on this instance")).toBeVisible();- await expect(activationSummary.getByText("Safe Remediation Workflows")).toBeVisible();+ await expect(activationSummary.getByText("Patrol Fixes Safe Issues")).toBeVisible();await expect(page.getByRole("link", { name: "Review usage" })).toHaveCount(0);await expect(page.getByRole("link", { name: "Review plan" })).toHaveCount(0);});@@ -572,7 +572,7 @@ test.describe("Self-hosted upgrade return flow", () => {page.getByText("Checkout completed and this instance is now running Pulse Pro."),).toHaveCount(0);await expect(page.getByText("Current plan: Community")).toBeVisible();- await expect(page.getByText("Safe Remediation Workflows")).toHaveCount(0);+ await expect(page.getByText("Patrol Fixes Safe Issues")).toHaveCount(0);await expect.poll(() => requestCounts.inactive.entitlements).toBeGreaterThan(0);expect(requestCounts.activated.entitlements).toBe(0);});@@ -655,7 +655,7 @@ test.describe("Self-hosted upgrade return flow", () => {),).toBeVisible();await expect(activationSummary.getByText("Available now on this instance")).toBeVisible();- await expect(activationSummary.getByText("Safe Remediation Workflows")).toBeVisible();+ await expect(activationSummary.getByText("Patrol Fixes Safe Issues")).toBeVisible();await expect(page.getByRole("link", { name: "Review plan" })).toHaveCount(0);await expect(page.getByRole("link", { name: "Review usage" })).toHaveCount(0);});diff --git a/tests/integration/tests/56-pulse-account-upgrade-bootstrap.spec.ts b/tests/integration/tests/56-pulse-account-upgrade-bootstrap.spec.tsindex 1a44fdeee5..c7ba3d812f 100644--- a/tests/integration/tests/56-pulse-account-upgrade-bootstrap.spec.ts+++ b/tests/integration/tests/56-pulse-account-upgrade-bootstrap.spec.ts@@ -80,7 +80,7 @@ test.describe("Pulse Account upgrade bootstrap", () => {).toBeVisible();await expect(page.getByText(- "Community keeps core monitoring free. Relay gets your Pulse web UI securely reachable from anywhere. Pro adds root-cause analysis, safe remediation workflows, and 90-day history.",+ "Community keeps core monitoring free. Relay gets your Pulse web UI securely reachable from anywhere. Pro adds Patrol control, alert investigation, verified fixes, and 90-day history.",),).toBeVisible();await expect(diff --git a/tests/integration/tests/59-self-hosted-plans-entitlement-summary.spec.ts b/tests/integration/tests/59-self-hosted-plans-entitlement-summary.spec.tsindex 81c1ed7cba..216ef5dc7b 100644--- a/tests/integration/tests/59-self-hosted-plans-entitlement-summary.spec.ts+++ b/tests/integration/tests/59-self-hosted-plans-entitlement-summary.spec.ts@@ -220,7 +220,7 @@ test.describe('Self-hosted plans entitlement summary', () => {await expect(currentPlanCard.getByText('Current plan: Pulse Pro')).toBeVisible();await expect(currentPlanCard.getByText(- 'Pulse Pro is active on this instance. Root-cause analysis, safe remediation workflows, 90-day history, and admin/reporting extras are available right now.',+ 'Pulse Pro is active on this instance. Patrol control, alert investigation, verified fixes, 90-day history, and admin/reporting extras are available right now.',),).toBeVisible();await expect(currentPlanCard.getByText('Grandfathered price')).toBeVisible();@@ -248,10 +248,10 @@ test.describe('Self-hosted plans entitlement summary', () => {await expect(currentPlanCard.getByText('Primary capabilities')).toBeVisible();await expect(currentPlanCard.getByText('Included extras')).toBeVisible();await expect(- currentPlanCard.getByText('Safe Remediation Workflows', { exact: true }),+ currentPlanCard.getByText('Patrol Fixes Safe Issues', { exact: true }),).toBeVisible();await expect(- currentPlanCard.getByText('Alert Root-Cause Analysis', { exact: true }),+ currentPlanCard.getByText('Patrol Investigates Alerts', { exact: true }),).toBeVisible();await expect(currentPlanCard.getByText('PDF/CSV Reporting', { exact: true })).toBeVisible();await expect(diff --git a/tests/integration/tests/69-diagnostics-onboarding.spec.ts b/tests/integration/tests/69-diagnostics-onboarding.spec.tsindex 91ae4f4c97..284cfb84f2 100644--- a/tests/integration/tests/69-diagnostics-onboarding.spec.ts+++ b/tests/integration/tests/69-diagnostics-onboarding.spec.ts@@ -188,7 +188,7 @@ const DIAGNOSTICS_PAYLOAD = {enabled: true,running: true,healthy: true,- mcpConnected: true,+ assistantRuntimeConnected: true,notes: [],},errors: [],diff --git a/tests/integration/tests/70-self-hosted-manual-activation-success.spec.ts b/tests/integration/tests/70-self-hosted-manual-activation-success.spec.tsindex a97e4b9113..2c55154cf2 100644--- a/tests/integration/tests/70-self-hosted-manual-activation-success.spec.ts+++ b/tests/integration/tests/70-self-hosted-manual-activation-success.spec.ts@@ -251,8 +251,8 @@ test.describe('Self-hosted manual activation success', () => {),).toBeVisible();await expect(activationSummary.getByText('Available now on this instance')).toBeVisible();- await expect(activationSummary.getByText('Safe Remediation Workflows')).toBeVisible();- await expect(activationSummary.getByText('Alert Root-Cause Analysis')).toBeVisible();+ await expect(activationSummary.getByText('Patrol Fixes Safe Issues')).toBeVisible();+ await expect(activationSummary.getByText('Patrol Investigates Alerts')).toBeVisible();await expect.poll(() => requestCounts.activate).toBe(1);await expect.poll(() => requestCounts.active.entitlements).toBeGreaterThan(0);await expect.poll(() => requestCounts.active.runtimeCapabilities).toBeGreaterThan(0);@@ -265,7 +265,7 @@ test.describe('Self-hosted manual activation success', () => {.first();await expect(currentPlanCard.getByText(- 'Pulse Pro is active on this instance. Root-cause analysis, safe remediation workflows, 90-day history, and admin/reporting extras are available right now.',+ 'Pulse Pro is active on this instance. Patrol control, alert investigation, verified fixes, 90-day history, and admin/reporting extras are available right now.',),).toBeVisible();await expect(currentPlanCard.getByText('Included extras')).toBeVisible();diff --git a/tests/integration/tests/75-agent-integrations-surface-contract.spec.ts b/tests/integration/tests/75-agent-integrations-surface-contract.spec.tsnew file mode 100644index 0000000000..7f2aa4d0fe--- /dev/null+++ b/tests/integration/tests/75-agent-integrations-surface-contract.spec.ts@@ -0,0 +1,143 @@+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { expect, test as base } from "@playwright/test";+import { createAuthenticatedStorageState } from "./helpers";++const __dirname = path.dirname(fileURLToPath(import.meta.url));++type WorkerFixtures = {+ authStorageStatePath: string;+};++const test = base.extend<{}, WorkerFixtures>({+ storageState: async ({ authStorageStatePath }, use) => {+ await use(authStorageStatePath);+ },+ authStorageStatePath: [+ async ({ browser }, use, workerInfo) => {+ const storageStatePath = path.resolve(+ __dirname,+ "..",+ "..",+ "tmp",+ "playwright-auth",+ `agent-integrations-surface-contract-${workerInfo.project.name}.json`,+ );+ fs.mkdirSync(path.dirname(storageStatePath), { recursive: true });+ await createAuthenticatedStorageState(browser, storageStatePath);+ try {+ await use(storageStatePath);+ } finally {+ fs.rmSync(storageStatePath, { force: true });+ }+ },+ { scope: "worker" },+ ],+});++test.describe("Agent integrations surface contract", () => {+ test("projects Pulse Intelligence surfaces from the live capabilities manifest", async ({+ page,+ }) => {+ const manifestResponse = page.waitForResponse(+ (response) =>+ response.url().includes("/api/agent/capabilities") &&+ response.request().method() === "GET",+ );++ await page.goto("/settings/security/api", {+ waitUntil: "domcontentloaded",+ });+ await page.waitForURL(/\/settings\/security\/api/, { timeout: 15_000 });+ await expect(+ page.getByRole("heading", { level: 2, name: "Agent integrations" }),+ ).toBeVisible();++ const response = await manifestResponse;+ expect(response.ok()).toBeTruthy();++ const surfaces = page.getByRole("heading", {+ level: 3,+ name: "Pulse Intelligence surfaces",+ });+ await expect(surfaces).toBeVisible();++ const surfaceSection = surfaces.locator("..");+ for (const label of [+ "Pulse Intelligence Core",+ "Pulse Patrol",+ "Pulse Assistant",+ "Pulse MCP",+ ]) {+ await expect(+ surfaceSection.getByText(label, { exact: true }),+ ).toBeVisible();+ }++ await expect(+ surfaceSection.getByText("Native surface", { exact: true }),+ ).toBeVisible();+ await expect(+ surfaceSection.getByText("External adapter", { exact: true }),+ ).toBeVisible();+ await expect(+ surfaceSection.getByText("Tools", { exact: true }).first(),+ ).toBeVisible();+ await expect(+ surfaceSection.getByText("Interactive questions", { exact: true }),+ ).toBeVisible();+ await expect(+ surfaceSection.getByText("Capability metadata", { exact: true }),+ ).toBeVisible();+ await expect(+ surfaceSection.getByText(+ "Canonical context, governed actions, safety gates, approval state, action audit, and verification shared by Pulse Assistant, Pulse MCP, and Pulse Patrol.",+ { exact: true },+ ),+ ).toBeVisible();++ const horizontalOverflow = await surfaceSection+ .locator("ul")+ .evaluate((node) => ({+ clientWidth: node.clientWidth,+ scrollWidth: node.scrollWidth,+ }));+ expect(horizontalOverflow.scrollWidth).toBeLessThanOrEqual(+ horizontalOverflow.clientWidth + 1,+ );++ const createTokenLink = page.getByRole("link", {+ name: "Create token",+ });+ await expect(page.getByText("Token setup", { exact: true })).toBeVisible();+ await expect(+ page.getByText("Pulse Intelligence agent", { exact: true }).last(),+ ).toBeVisible();+ await expect(+ page.getByText("Stable failure codes", { exact: true }),+ ).toBeVisible();+ await expect(page.getByText("resource_not_found").first()).toBeVisible();+ await expect(createTokenLink).toHaveAttribute("href", "#api-token-create");+ await expect(+ page.getByRole("heading", { level: 3, name: "MCP client config" }),+ ).toBeVisible();+ await expect(+ page.getByRole("heading", { level: 4, name: /OpenCode.*opencode\.json/ }),+ ).toBeVisible();+ await expect(+ page.getByRole("heading", { level: 4, name: /mcpServers/ }),+ ).toBeVisible();+ await expect(page.getByText("PULSE_API_TOKEN").first()).toBeVisible();+ await expect(page.getByText("--base-url").first()).toBeVisible();++ await createTokenLink.click();+ await expect(page).toHaveURL(/#api-token-create$/);+ await expect(+ page.getByRole("heading", { level: 2, name: "Create token" }),+ ).toBeVisible();+ await expect(+ page.getByRole("button", { name: "Pulse Intelligence agent" }),+ ).toBeVisible();+ });+});