Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Introduce the Patrol execution profiles: detection and investigation

rcourtman97a30b0600b6
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 0373068926..e491c8e5f4 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -284,7 +284,7 @@ call when building tool-result turns.
25. `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.
26. `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.
27. `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.
-28. `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_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; the shared invocation-blocked result is the stable refusal for every profile-denied mutation (pulse-state and infrastructure alike).
29. `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.
30. `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.
31. `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.
@@ -4625,6 +4625,35 @@ was removed; a projection whose remaining invocations mutate nothing
downgrades to scope-only approval metadata. Docker `check_updates`
classifies read/none: it queues a read-only scan and must not drive
verification workflow or make a read-only Docker projection look mixed.
+Execution posture is profile-owned through the core-only, never-
+serialized `tools.ExecutionProfile` (interactive Assistant, Patrol
+detection, Patrol investigation). Both Patrol profiles are
+non-interactive, deny infrastructure mutations, and clear any inherited
+autonomous mode; detection additionally restricts pulse-state mutations
+to an explicit allowlist of the finding lifecycle tools
+(patrol_report_finding / patrol_resolve_finding - a blanket pulse-state
+allowance would also permit alert dismissal and knowledge writes),
+while investigation denies all pulse-state mutations. Chat turns build
+ONE effective request executor (control level, autonomy, profile,
+resolved context) BEFORE provider projection and clone that executor
+for every provider attempt, so the offered schema and the runtime
+boundary always agree; scheduled Patrol (`ExecutePatrolStream`) applies
+the detection profile the same way, and `ListAvailableTools` projects
+through the identical path. Non-interactive profiles independently hide
+pulse_question from the manifest AND runtime-block it in the agentic
+loop before the interactive-call-set special case - a fabricated
+question call returns a non-interactive error without emitting a
+waiting event and sibling tool calls from the same provider turn keep
+processing; approval waits never block (they queue), and the
+tool-only-turn wrap-up guardrail is interactive-profile-owned rather
+than keyed on autonomy. The system prompt describes detection and
+investigation modes directly instead of claiming controlled or
+autonomous execution. Non-interactive operation grants no mutation
+authority. Profile proofs live in
+`internal/ai/tools/invocation_policy_test.go` (detection allowlist,
+investigation structural read-only, profile clone isolation) and
+`internal/ai/chat/service_tooling_test.go` (profile prompt modes,
+question-tool hiding, effective-executor projection).
Handler-level checks remain defense in depth, and pulse_read's
structural execution-intent classifier
(`ClassifyExecutionIntent` rejecting write-or-unknown command text
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 85d0965044..7a4d15ee98 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1192,7 +1192,7 @@ payload shape change when the portal presents compact client rows.
51. `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.
52. `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.
53. `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.
-54. `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_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; the shared invocation-blocked result is the stable refusal for every profile-denied mutation (pulse-state and infrastructure alike).
55. `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.
56. `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.
57. `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.
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index fe038ebc5d..a3b9c26cc4 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -636,7 +636,7 @@
},
{
"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",
+ "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; the shared invocation-blocked result is the stable refusal for every profile-denied mutation (pulse-state and infrastructure alike)",
"subsystems": [
"ai-runtime",
"api-contracts"
diff --git a/frontend-modern/src/components/Settings/NodeModalClusterMembersSection.tsx b/frontend-modern/src/components/Settings/NodeModalClusterMembersSection.tsx
new file mode 100644
index 0000000000..23423fc3dc
--- /dev/null
+++ b/frontend-modern/src/components/Settings/NodeModalClusterMembersSection.tsx
@@ -0,0 +1,96 @@
+import { Component, For, Show, createMemo } from 'solid-js';
+import type { ClusterEndpoint } from '@/types/nodes';
+import type { NodeModalProps } from '@/components/Settings/nodeModalModel';
+import type { NodeModalState } from '@/components/Settings/useNodeModalState';
+import { SectionHeader } from '@/components/shared/SectionHeader';
+import { controlClass, formHelpText } from '@/components/shared/Form';
+
+interface NodeModalClusterMembersSectionProps {
+ modalProps: NodeModalProps;
+ state: NodeModalState;
+}
+
+const discoveredAddress = (endpoint: ClusterEndpoint): string => {
+ const host = endpoint.host?.replace(/^https?:\/\//, '') ?? '';
+ if (endpoint.ip && host && !host.startsWith(endpoint.ip)) {
+ return `${host} (${endpoint.ip})`;
+ }
+ return host || endpoint.ip || '';
+};
+
+// Per-member connection addresses for an existing PVE cluster. The discovered
+// host and IP are rebuilt from cluster status on every re-discovery, so the
+// only durable user edit is the override (ClusterEndpoint.ipOverride), which
+// wins at poll time via EffectiveIP.
+export const NodeModalClusterMembersSection: Component<NodeModalClusterMembersSectionProps> = (
+ props,
+) => {
+ const { modalProps, state } = props;
+
+ const endpoints = createMemo<ClusterEndpoint[]>(() => {
+ const node = modalProps.editingNode;
+ if (!node || node.type !== 'pve' || !('clusterEndpoints' in node)) return [];
+ return node.clusterEndpoints ?? [];
+ });
+
+ return (
+ <Show when={endpoints().length > 0}>
+ <div>
+ <SectionHeader
+ title="Cluster members"
+ size="sm"
+ class="mb-1"
+ titleClass="text-base-content"
+ />
+ <p class="mb-3 text-xs text-muted">
+ Pulse found these nodes in the cluster and connects to each one directly. If a node's
+ discovered address isn't reachable from Pulse (for example when the cluster reports an
+ internal network IP), enter the address Pulse should use instead.
+ </p>
+ <div class="rounded-md border border-border">
+ <For each={endpoints()}>
+ {(endpoint) => (
+ <div class="flex flex-col gap-2 border-b border-border-subtle p-3 last:border-b-0 sm:flex-row sm:items-center">
+ <div class="min-w-0 sm:w-1/2">
+ <div class="flex items-center gap-1.5 text-sm text-base-content">
+ <span class="truncate">{endpoint.nodeName}</span>
+ <Show when={endpoint.pulseReachable === false}>
+ <span
+ class="inline-flex flex-shrink-0 items-center rounded-full bg-amber-100 px-2 py-0.5 text-[11px] font-medium text-amber-800 dark:bg-amber-950 dark:text-amber-300"
+ title={endpoint.pulseError || 'Pulse could not connect to this node'}
+ >
+ Unreachable
+ </span>
+ </Show>
+ </div>
+ <div class="truncate text-xs text-muted" title={discoveredAddress(endpoint)}>
+ Discovered: {discoveredAddress(endpoint)}
+ </div>
+ </div>
+ <div class="sm:w-1/2">
+ <input
+ type="text"
+ value={state.formData().clusterEndpointOverrides[endpoint.nodeName] ?? ''}
+ onInput={(event) =>
+ state.updateClusterEndpointOverride(
+ endpoint.nodeName,
+ event.currentTarget.value,
+ )
+ }
+ placeholder={endpoint.ip || 'IP or hostname'}
+ aria-label={`Connection address for ${endpoint.nodeName}`}
+ class={controlClass()}
+ />
+ </div>
+ </div>
+ )}
+ </For>
+ </div>
+ <p class={formHelpText}>
+ Optional. IP or hostname, with a port if it isn't 8006. Leave blank to use the discovered
+ address.
+ </p>
+ </div>
+ </Show>
+ );
+};
diff --git a/internal/agentcapabilities/invocation_test.go b/internal/agentcapabilities/invocation_test.go
index a342c692cf..d1f35b7f7b 100644
--- a/internal/agentcapabilities/invocation_test.go
+++ b/internal/agentcapabilities/invocation_test.go
@@ -1,6 +1,7 @@
package agentcapabilities
import (
+ "strings"
"testing"
)
@@ -131,3 +132,21 @@ func TestInvocationDescriptorForReturnsIsolatedCopies(t *testing.T) {
t.Fatalf("mutating a returned static class leaked into the canonical table: %#v", refetched.Static)
}
}
+
+func TestInvocationBlockedResultCoversAllMutationTargets(t *testing.T) {
+ // The blocked-invocation result is the shared refusal for every
+ // profile-denied mutation, not just infrastructure: pulse-state
+ // blocks (e.g. Patrol detection's finding-tool allowlist) use it too.
+ for _, target := range []MutationTarget{MutationPulseState, MutationInfrastructure} {
+ result := NewInvocationBlockedToolResult("pulse_alerts", InvocationClass{Kind: ToolCallKindWrite, Mutation: target})
+ text := ToolResultText(result)
+ if text == "" {
+ t.Fatal("blocked result must carry text")
+ }
+ for _, want := range []string{"Invocation blocked", "pulse_alerts", string(target), "propose a typed action"} {
+ if !strings.Contains(text, want) {
+ t.Fatalf("blocked result for %s missing %q: %s", target, want, text)
+ }
+ }
+ }
+}
diff --git a/internal/agentcapabilities/tool_call.go b/internal/agentcapabilities/tool_call.go
index e11996fdc0..22b31ee9f4 100644
--- a/internal/agentcapabilities/tool_call.go
+++ b/internal/agentcapabilities/tool_call.go
@@ -184,11 +184,10 @@ func NewControlToolsDisabledToolResult() ToolResult {
// NewInvocationBlockedToolResult is the stable shared result for a tool
// invocation the registry's invocation policy refuses before the handler
-// runs: an infrastructure-mutating (or unclassifiable, therefore
-// fail-closed) invocation under a read-only control level or a
-// deny-infrastructure-mutations request policy.
+// runs: a mutating (or unclassifiable, therefore fail-closed) invocation
+// the current execution profile does not permit.
func NewInvocationBlockedToolResult(toolName string, class InvocationClass) ToolResult {
return NewToolTextResultWithIsError(fmt.Sprintf(
- "Invocation blocked: this %s call classifies as an infrastructure-mutating action (%s), which the current session policy does not permit. Read-only investigation may gather evidence and propose a typed action instead of mutating directly.",
+ "Invocation blocked: this %s call classifies as a state-mutating action (mutation target: %s), which the current session policy does not permit. Gather evidence with read-only tools and propose a typed action instead of mutating directly.",
toolName, class.Mutation), true)
}
diff --git a/internal/ai/chat/agentic.go b/internal/ai/chat/agentic.go
index 400df461fc..a43382f8b8 100644
--- a/internal/ai/chat/agentic.go
+++ b/internal/ai/chat/agentic.go
@@ -496,6 +496,10 @@ type AgenticLoop struct {
aborted map[string]bool // sessionID -> aborted
pendingQs map[string]chan []QuestionAnswer // questionID -> answer channel
autonomousMode bool // When true, don't wait for approvals (for investigations)
+ // executionProfile is the core-owned request posture (interactive
+ // Assistant, Patrol detection, Patrol investigation). It owns
+ // non-interactive behavior and the prompt's execution-mode text.
+ executionProfile tools.ExecutionProfile
// Per-session FSMs for workflow enforcement (set before each execution)
sessionFSM *SessionFSM
@@ -1211,6 +1215,39 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
}
var pendingExec []pendingToolExec
+ // Non-interactive profiles (Patrol detection/investigation) cannot
+ // wait for user input. A fabricated pulse_question call must not
+ // reach the interactive-call-set path below - that path emits a
+ // "waiting for your answer" event and skips sibling tool calls.
+ // Instead, answer each question call with a non-interactive error
+ // and keep processing the other calls from the same provider turn.
+ if a.currentExecutionProfile().NonInteractive() {
+ remaining := toolCalls[:0]
+ for _, tc := range toolCalls {
+ if tc.Name != pulseQuestionToolName {
+ remaining = append(remaining, tc)
+ continue
+ }
+ log.Warn().
+ Str("id", tc.ID).
+ Str("session_id", sessionID).
+ Msg("[AgenticLoop] Blocked pulse_question in non-interactive execution profile")
+ projection := newProviderToolResultContextProjection(tc.ID,
+ "pulse_question is unavailable: this is a non-interactive run and no user can answer. Continue with the available evidence.", true)
+ providerMessages = append(providerMessages, providers.Message{
+ Role: "user",
+ ToolResult: &projection.Model,
+ })
+ }
+ toolCalls = remaining
+ if len(toolCalls) == 0 {
+ // Same next-turn bookkeeping as the interactive-set path.
+ currentTurnStartIndex = len(providerMessages)
+ turn++
+ continue
+ }
+ }
+
// pulse_question is interactive and must not run in parallel with other tools.
// If the provider emits multiple tool calls alongside pulse_question, skip the
// others and let the model retry after receiving the user's answer.
@@ -1639,14 +1676,17 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
// Instead, return with approval info so the orchestrator can queue it.
a.mu.Lock()
isAutonomous := a.autonomousMode
+ nonInteractive := a.executionProfile.NonInteractive()
loopOrgID := approval.NormalizeOrgID(a.orgID)
a.mu.Unlock()
- if isAutonomous {
+ // Non-interactive profiles must never block on a human
+ // decision either; they queue exactly like autonomous mode.
+ if isAutonomous || nonInteractive {
log.Debug().
Str("approval_id", approvalData.ApprovalID).
Str("command", approvalData.Command).
- Msg("[AgenticLoop] Autonomous mode: returning approval request without waiting")
+ Msg("[AgenticLoop] Non-blocking approval posture: returning approval request without waiting")
resultText = fmt.Sprintf("FIX_QUEUED: This action requires user approval. The fix has been queued for review. Approval ID: %s, Command: %s", approvalData.ApprovalID, approvalData.Command)
isError = false
} else {
@@ -1829,11 +1869,15 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
}
// Guardrail: in interactive chat mode, force wrap-up after repeated
- // tool-only turns to avoid long no-answer chains.
+ // tool-only turns to avoid long no-answer chains. Profile-owned:
+ // non-interactive Patrol runs are tool-only by design, so the
+ // guardrail applies only to the interactive Assistant profile
+ // (and, within it, keeps the historical autonomous exemption).
a.mu.Lock()
autonomousMode := a.autonomousMode
+ interactiveProfile := !a.executionProfile.NonInteractive()
a.mu.Unlock()
- if !autonomousMode && consecutiveToolOnlyTurns >= maxConsecutiveToolOnlyTurns {
+ if interactiveProfile && !autonomousMode && consecutiveToolOnlyTurns >= maxConsecutiveToolOnlyTurns {
toolBlockedLastTurn = true
log.Warn().
Int("consecutive_tool_only_turns", consecutiveToolOnlyTurns).
diff --git a/internal/ai/chat/agentic_control.go b/internal/ai/chat/agentic_control.go
index b9b19b6677..12b530dfe3 100644
--- a/internal/ai/chat/agentic_control.go
+++ b/internal/ai/chat/agentic_control.go
@@ -1,5 +1,9 @@
package chat
+import (
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
+)
+
// Abort aborts an ongoing session.
func (a *AgenticLoop) Abort(sessionID string) {
a.mu.Lock()
@@ -15,6 +19,23 @@ func (a *AgenticLoop) SetAutonomousMode(enabled bool) {
a.mu.Unlock()
}
+// SetExecutionProfile applies the core-owned execution profile for this
+// loop. The profile owns non-interactive behavior (question handling,
+// tool-only-turn wrap-up) and the prompt's execution-mode description;
+// it is deliberately separate from autonomous mode, which only affects
+// approval waiting and grants no mutation authority.
+func (a *AgenticLoop) SetExecutionProfile(profile tools.ExecutionProfile) {
+ a.mu.Lock()
+ a.executionProfile = profile
+ a.mu.Unlock()
+}
+
+func (a *AgenticLoop) currentExecutionProfile() tools.ExecutionProfile {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return a.executionProfile
+}
+
// SetSessionFSM sets the workflow FSM for the current session.
// This must be called before ExecuteWithTools to enable structural guarantees.
func (a *AgenticLoop) SetSessionFSM(fsm *SessionFSM) {
diff --git a/internal/ai/chat/agentic_prompt.go b/internal/ai/chat/agentic_prompt.go
index 0e5e06e0da..46bc037d32 100644
--- a/internal/ai/chat/agentic_prompt.go
+++ b/internal/ai/chat/agentic_prompt.go
@@ -3,6 +3,8 @@ package chat
import (
"fmt"
"time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
)
// getSystemPrompt builds the full system prompt including the current mode context.
@@ -13,21 +15,42 @@ import (
func (a *AgenticLoop) getSystemPrompt() string {
a.mu.Lock()
isAutonomous := a.autonomousMode
+ profile := a.executionProfile
a.mu.Unlock()
var modeContext string
- if isAutonomous {
+ switch profile {
+ case tools.ProfilePatrolDetection:
+ modeContext = `
+EXECUTION MODE: Patrol detection
+This is a non-interactive scheduled detection run. You cannot ask the user questions and you
+cannot change infrastructure. Inspect the estate with read-only tools and record what you find
+through the Patrol finding tools (report or resolve findings). Do not attempt any other
+state-changing action; such calls will be blocked.`
+ case tools.ProfilePatrolInvestigation:
modeContext = `
+EXECUTION MODE: Patrol investigation
+This is a non-interactive, strictly read-only investigation of one finding. You cannot ask the
+user questions and you cannot change anything - neither infrastructure nor Pulse's own records.
+Gather evidence with read-only tools and conclude with your diagnosis. If remediation is
+appropriate, propose a typed action referencing an advertised resource capability instead of
+attempting to perform it; every state-changing call will be blocked.`
+ case tools.ProfileInteractiveAssistant:
+ fallthrough
+ default:
+ if isAutonomous {
+ modeContext = `
EXECUTION MODE: Autonomous
Commands may execute without per-command approval when policy allows. Decide whether current
context is enough, whether read-only evidence is needed, or whether a state-changing tool is
appropriate. Prefer current evidence before changing state.`
- } else {
- modeContext = `
+ } else {
+ modeContext = `
EXECUTION MODE: Controlled
State-changing tools require governed approval when policy says approval is required. If the
user asks you to perform an action, choose the appropriate tool and Pulse will handle any
required approval prompt.`
+ }
}
// Give the model the current time directly. Without this the Assistant has no
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index 94dd451e88..82056b96bf 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -833,7 +833,20 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
// the full governed manifest, and the selected model decides whether to
// answer directly, ask, or call tools. The only manifest-boundary
// exception is the contract-sanctioned context-only resource handoff turn.
- filteredTools := s.toolsForExecutionMode(autonomousMode, false)
+ // Build ONE effective request executor before provider projection:
+ // control level, autonomy, execution profile, and resolved context are
+ // applied here, the manifest is projected from it, and every provider
+ // attempt clones this same effective executor - so the offered schema
+ // and the runtime enforcement boundary always agree.
+ var effectiveExecutor *tools.PulseToolExecutor
+ if baseExecutor != nil {
+ effectiveExecutor = baseExecutor.Clone()
+ effectiveExecutor.SetControlLevel(effectiveControlLevel)
+ effectiveExecutor.SetAutonomousMode(autonomousMode)
+ effectiveExecutor.ApplyExecutionProfile(tools.ProfileInteractiveAssistant)
+ effectiveExecutor.SetResolvedContext(resolvedCtx)
+ }
+ filteredTools := s.toolsForExecutor(effectiveExecutor, autonomousMode)
if resourceContextTurnIsContextOnly(req.Prompt, handoffResources, handoffMetadata) {
filteredTools = []providers.Tool{}
log.Debug().
@@ -874,15 +887,15 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
}
var executor *tools.PulseToolExecutor
- if baseExecutor != nil {
- executor = baseExecutor.Clone()
- executor.SetControlLevel(effectiveControlLevel)
- executor.SetAutonomousMode(autonomousMode)
- executor.SetResolvedContext(resolvedCtx)
+ if effectiveExecutor != nil {
+ // Clone the effective request executor (not the shared base):
+ // each attempt stays isolated while inheriting the exact
+ // policy the manifest was projected from.
+ executor = effectiveExecutor.Clone()
log.Debug().
Str("session_id", session.ID).
Int("resolved_resources", len(resolvedCtx.Resources)).
- Msg("[ChatService] Set resolved context on executor")
+ Msg("[ChatService] Cloned effective request executor for attempt")
}
// Create a per-attempt AgenticLoop to ensure complete isolation between
@@ -2743,6 +2756,12 @@ func (s *Service) ExecutePatrolStream(ctx context.Context, req PatrolRequest, ca
if baseExecutor != nil {
executor = baseExecutor.Clone()
executor.SetControlLevel(effectiveControlLevel)
+ // Scheduled Patrol runs under the detection profile: non-
+ // interactive, no infrastructure mutations, and Pulse-state
+ // mutations restricted to the finding lifecycle tools. This also
+ // clears any inherited autonomous mode - detection needs no
+ // mutation authority, only its allowlisted finding tools.
+ executor.ApplyExecutionProfile(tools.ProfilePatrolDetection)
}
// Determine model: use patrol model or fall back to chat model
@@ -2770,7 +2789,10 @@ func (s *Service) ExecutePatrolStream(ctx context.Context, req PatrolRequest, ca
}
tempLoop := NewAgenticLoop(provider, executor, systemPrompt)
tempLoop.SetOrgID(s.orgID)
- tempLoop.SetAutonomousMode(true) // Patrol runs without approval prompts
+ // The detection profile owns non-interactive behavior (question
+ // blocking, non-blocking approvals, tool-only turns); Patrol grants
+ // no autonomous mutation authority.
+ tempLoop.SetExecutionProfile(tools.ProfilePatrolDetection)
tempLoop.SetExecutionID(req.ExecutionID)
tempLoop.SetRequestSanitizer(modelboundary.RequestSanitizerForModel(patrolModel, unifiedResourceProvider))
if req.MaxTurns > 0 {
@@ -2837,8 +2859,9 @@ func (s *Service) ExecutePatrolStream(ctx context.Context, req PatrolRequest, ca
// this run's user prompt; the session is just a forensic log.
messages := []Message{userMsg}
- // Get governed tools for the Patrol run.
- filteredTools := s.toolsForExecutionMode(true, true)
+ // Get governed tools for the Patrol run, projected from the same
+ // effective executor that will run them under the detection profile.
+ filteredTools := s.toolsForExecutor(executor, false)
// Run the agentic loop
resultMessages, err := tempLoop.ExecuteWithTools(ctx, session.ID, messages, filteredTools, callback)
@@ -2971,15 +2994,23 @@ func (s *Service) createPatrolProviderForModel(modelStr string) (providers.Strea
func (s *Service) ListAvailableTools(ctx context.Context, prompt string) []string {
s.mu.RLock()
executor := s.executor
+ effectiveControlLevel := s.effectiveControlLevelLocked()
s.mu.RUnlock()
if executor == nil {
return nil
}
- tools := s.toolsForExecutionMode(s.isAutonomousModeEnabled(), false)
- names := make([]string, 0, len(tools))
- for _, tool := range tools {
+ // Project from an effective executor built the same way ExecuteStream
+ // builds one, so the advertised list matches what a turn would offer.
+ autonomousMode := s.isAutonomousModeEnabled()
+ effectiveExecutor := executor.Clone()
+ effectiveExecutor.SetControlLevel(effectiveControlLevel)
+ effectiveExecutor.SetAutonomousMode(autonomousMode)
+ effectiveExecutor.ApplyExecutionProfile(tools.ProfileInteractiveAssistant)
+ availableTools := s.toolsForExecutor(effectiveExecutor, autonomousMode)
+ names := make([]string, 0, len(availableTools))
+ for _, tool := range availableTools {
if tool.Name == "" {
continue
}
@@ -3929,21 +3960,33 @@ func firstNonEmptyRecentString(values ...string) string {
return ""
}
-func (s *Service) toolsForExecutionMode(autonomousMode bool, patrolMode bool) []providers.Tool {
- includeQuestionTool := !autonomousMode && !patrolMode
- providerTools := s.executor.AssistantProviderTools(agentcapabilities.AssistantProviderToolOptions{
+// toolsForExecutor projects the provider tool manifest from ONE effective
+// request executor: the same clone (control level, autonomy, execution
+// profile already applied) that will execute the calls at runtime, so the
+// offered schema and the enforcement boundary can never disagree. The
+// profile owns question-tool availability: non-interactive Patrol
+// profiles never offer it, and the interactive profile keeps the
+// historical autonomous exemption.
+func (s *Service) toolsForExecutor(executor *tools.PulseToolExecutor, autonomousMode bool) []providers.Tool {
+ if executor == nil {
+ executor = s.executor
+ }
+ profile := executor.ExecutionProfile()
+ includeQuestionTool := !profile.NonInteractive() && !autonomousMode
+ providerTools := 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.
- if patrolMode {
+ // Patrol detection may be scoped by explicit product configuration,
+ // but never by prompt keyword inference. The selected Patrol model
+ // owns tool choice within the profile-projected manifest.
+ if profile == tools.ProfilePatrolDetection {
filtered := s.filterToolsForPatrol(providerTools)
log.Debug().
Int("total_tools", len(providerTools)).
Int("tool_manifest_count", len(filtered)).
Bool("patrol_scope_filter", true).
- Msg("[toolsForExecutionMode] Built Patrol tool manifest from configured subsystem scope")
+ Msg("[toolsForExecutor] Built Patrol detection manifest from profile projection and subsystem scope")
return filtered
}
@@ -3951,8 +3994,9 @@ func (s *Service) toolsForExecutionMode(autonomousMode bool, patrolMode bool) []
log.Debug().
Int("total_tools", len(providerTools)).
Int("tool_manifest_count", len(filtered)).
+ Int("execution_profile", int(profile)).
Bool("autonomous", autonomousMode).
- Msg("[toolsForExecutionMode] Exposing governed tool manifest")
+ Msg("[toolsForExecutor] Exposing governed tool manifest")
return filtered
}
diff --git a/internal/ai/chat/service_test.go b/internal/ai/chat/service_test.go
index fc5553fb46..df7fee1095 100644
--- a/internal/ai/chat/service_test.go
+++ b/internal/ai/chat/service_test.go
@@ -635,7 +635,7 @@ func TestService_ToolsForExecutionMode_ExposesGovernedTools(t *testing.T) {
require.True(t, hasTool(service.executor.ListTools(), "pulse_docker"))
require.True(t, hasTool(service.executor.ListTools(), "pulse_query"))
- filtered := service.toolsForExecutionMode(true, false)
+ filtered := service.toolsForExecutor(nil, true)
assert.True(t, hasProviderTool(filtered, "pulse_control"))
assert.True(t, hasProviderTool(filtered, "pulse_docker"))
assert.True(t, hasProviderTool(filtered, "pulse_query"))
@@ -651,7 +651,7 @@ func TestService_ToolsForExecutionMode_InteractiveAddsQuestionTool(t *testing.T)
require.True(t, hasTool(service.executor.ListTools(), "pulse_docker"))
require.True(t, hasTool(service.executor.ListTools(), "pulse_query"))
- filtered := service.toolsForExecutionMode(false, false)
+ filtered := service.toolsForExecutor(nil, false)
assert.True(t, hasProviderTool(filtered, "pulse_control"))
assert.True(t, hasProviderTool(filtered, "pulse_docker"))
assert.True(t, hasProviderTool(filtered, "pulse_query"))
diff --git a/internal/ai/chat/service_tooling_test.go b/internal/ai/chat/service_tooling_test.go
index 66c3d23a81..00983d8137 100644
--- a/internal/ai/chat/service_tooling_test.go
+++ b/internal/ai/chat/service_tooling_test.go
@@ -122,7 +122,7 @@ func TestToolsForExecutionMode_InteractiveExposesGovernedTools(t *testing.T) {
},
}
- interactiveTools := svc.toolsForExecutionMode(false, false)
+ interactiveTools := svc.toolsForExecutor(nil, false)
interactiveSet := toolNameSet(interactiveTools)
if !interactiveSet["pulse_kubernetes"] ||
!interactiveSet["pulse_storage"] ||
@@ -283,7 +283,7 @@ func TestToolsForExecutionMode_AutonomousNonPatrolExposesGovernedTools(t *testin
})
svc := &Service{executor: exec}
- toolsList := svc.toolsForExecutionMode(true, false)
+ toolsList := svc.toolsForExecutor(nil, true)
set := toolNameSet(toolsList)
if !set["pulse_storage"] {
t.Fatalf("expected storage tool to be exposed without prompt keyword routing")
@@ -526,7 +526,7 @@ func TestToolsForExecutionMode_RecoveryOnlyKeepsStorage(t *testing.T) {
})
svc := &Service{executor: exec}
- toolsList := svc.toolsForExecutionMode(false, false)
+ toolsList := svc.toolsForExecutor(nil, false)
set := toolNameSet(toolsList)
if !set["pulse_storage"] {
t.Fatalf("expected storage tool to be kept when recovery points are the only storage source")
@@ -548,7 +548,8 @@ func TestToolsForExecutionMode_PatrolScopeUsesConfigNotPrompt(t *testing.T) {
},
}
- filtered := svc.toolsForExecutionMode(true, true)
+ exec.ApplyExecutionProfile(tools.ProfilePatrolDetection)
+ filtered := svc.toolsForExecutor(exec, false)
set := toolNameSet(filtered)
if set["pulse_docker"] {
@@ -1015,3 +1016,72 @@ func TestService_StartInitializesActionAuditStore(t *testing.T) {
t.Fatalf("expected action audit store to be cleared on stop")
}
}
+
+func TestExecutionProfilePromptModes(t *testing.T) {
+ loop := &AgenticLoop{baseSystemPrompt: "base"}
+
+ prompt := loop.getSystemPrompt()
+ if !strings.Contains(prompt, "EXECUTION MODE: Controlled") {
+ t.Fatalf("default interactive profile should describe controlled mode, got %q", prompt)
+ }
+
+ loop.SetAutonomousMode(true)
+ prompt = loop.getSystemPrompt()
+ if !strings.Contains(prompt, "EXECUTION MODE: Autonomous") {
+ t.Fatalf("interactive autonomous should describe autonomous mode, got %q", prompt)
+ }
+
+ // Patrol profiles own their mode text and never claim controlled or
+ // autonomous execution, regardless of inherited autonomy flags.
+ loop.SetExecutionProfile(tools.ProfilePatrolDetection)
+ prompt = loop.getSystemPrompt()
+ if !strings.Contains(prompt, "EXECUTION MODE: Patrol detection") ||
+ strings.Contains(prompt, "EXECUTION MODE: Autonomous") ||
+ strings.Contains(prompt, "EXECUTION MODE: Controlled") {
+ t.Fatalf("detection profile prompt wrong: %q", prompt)
+ }
+
+ loop.SetExecutionProfile(tools.ProfilePatrolInvestigation)
+ prompt = loop.getSystemPrompt()
+ if !strings.Contains(prompt, "EXECUTION MODE: Patrol investigation") {
+ t.Fatalf("investigation profile prompt wrong: %q", prompt)
+ }
+ if !strings.Contains(prompt, "propose a typed action") {
+ t.Fatalf("investigation prompt must direct toward typed proposals, got %q", prompt)
+ }
+}
+
+func TestToolsForExecutorHidesQuestionToolForPatrolProfiles(t *testing.T) {
+ exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{
+ ControlLevel: tools.ControlLevelControlled,
+ StateProvider: &mockStateProvider{},
+ AgentServer: &mockAgentServer{},
+ })
+ svc := &Service{executor: exec, cfg: &config.AIConfig{}}
+
+ interactive := svc.toolsForExecutor(nil, false)
+ if !toolNameSet(interactive)[pulseQuestionToolName] {
+ t.Fatal("interactive non-autonomous manifest must offer pulse_question")
+ }
+
+ detection := exec.Clone()
+ detection.ApplyExecutionProfile(tools.ProfilePatrolDetection)
+ detectionTools := svc.toolsForExecutor(detection, false)
+ if toolNameSet(detectionTools)[pulseQuestionToolName] {
+ t.Fatal("detection profile must hide pulse_question")
+ }
+
+ investigation := exec.Clone()
+ investigation.ApplyExecutionProfile(tools.ProfilePatrolInvestigation)
+ investigationTools := svc.toolsForExecutor(investigation, false)
+ set := toolNameSet(investigationTools)
+ if set[pulseQuestionToolName] {
+ t.Fatal("investigation profile must hide pulse_question")
+ }
+ if set["patrol_report_finding"] || set["pulse_control"] || set["pulse_file_edit"] {
+ t.Fatalf("investigation manifest must not offer mutation tools, got %v", set)
+ }
+ if !set["pulse_query"] || !set["pulse_read"] {
+ t.Fatalf("investigation manifest must keep read tools, got %v", set)
+ }
+}
diff --git a/internal/ai/tools/execution_profile.go b/internal/ai/tools/execution_profile.go
new file mode 100644
index 0000000000..0be718d0cb
--- /dev/null
+++ b/internal/ai/tools/execution_profile.go
@@ -0,0 +1,79 @@
+package tools
+
+import (
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
+)
+
+// ExecutionProfile is the core-owned, request-local execution posture for
+// one Assistant/Patrol run. It is deliberately an opaque integer with no
+// JSON tags, string round-trip, or public constructor from external input:
+// enterprise and transport code can never serialize, select, or relax a
+// profile. Profiles are applied by core call sites only (chat service and
+// the investigation adapter), and their policy is enforced twice - during
+// provider projection and again at registry execution.
+type ExecutionProfile int
+
+const (
+ // ProfileInteractiveAssistant is the default interactive chat
+ // posture: the operator's configured control level and autonomy
+ // govern, and the interactive question tool is available.
+ ProfileInteractiveAssistant ExecutionProfile = iota
+ // ProfilePatrolDetection is the scheduled Patrol detection posture:
+ // non-interactive, no infrastructure mutations, and Pulse-state
+ // mutations restricted to the finding lifecycle tools
+ // (patrol_report_finding / patrol_resolve_finding).
+ ProfilePatrolDetection
+ // ProfilePatrolInvestigation is the Patrol investigation posture:
+ // non-interactive and structurally read-only - no infrastructure and
+ // no Pulse-state mutations. Typed remediation leaves the profile only
+ // as a side-effect-free, mutation-none action proposal.
+ ProfilePatrolInvestigation
+)
+
+// NonInteractive reports whether the profile forbids interactive user
+// input. This is deliberately independent of autonomous mode: suppressing
+// questions grants no mutation authority, and mutation policy never
+// loosens because a run is interactive.
+func (p ExecutionProfile) NonInteractive() bool {
+ return p == ProfilePatrolDetection || p == ProfilePatrolInvestigation
+}
+
+// patrolDetectionPulseStateAllowlist names the only tools whose
+// pulse-state mutations the detection profile permits. A blanket
+// pulse-state allowance would also permit alert dismissal and knowledge
+// writes, which detection has no business performing.
+func patrolDetectionPulseStateAllowlist() map[string]bool {
+ return map[string]bool{
+ agentcapabilities.PatrolReportFindingToolName: true,
+ agentcapabilities.PatrolResolveFindingToolName: true,
+ }
+}
+
+// ApplyExecutionProfile applies the profile's policy to this executor
+// instance (normally a request-scoped clone). Both Patrol profiles deny
+// infrastructure mutations, clear any inherited autonomous mode, and mark
+// the executor non-interactive; they differ only in pulse-state policy.
+func (e *PulseToolExecutor) ApplyExecutionProfile(profile ExecutionProfile) {
+ e.executionProfile = profile
+ switch profile {
+ case ProfilePatrolDetection:
+ e.isAutonomous = false
+ e.denyInfrastructureMutations = true
+ e.pulseStateAllowlist = patrolDetectionPulseStateAllowlist()
+ case ProfilePatrolInvestigation:
+ e.isAutonomous = false
+ e.denyInfrastructureMutations = true
+ e.pulseStateAllowlist = map[string]bool{}
+ default:
+ e.denyInfrastructureMutations = false
+ e.pulseStateAllowlist = nil
+ }
+}
+
+// ExecutionProfile returns the profile applied to this executor instance.
+func (e *PulseToolExecutor) ExecutionProfile() ExecutionProfile {
+ if e == nil {
+ return ProfileInteractiveAssistant
+ }
+ return e.executionProfile
+}
diff --git a/internal/ai/tools/executor.go b/internal/ai/tools/executor.go
index a844154416..0d71bca8dc 100644
--- a/internal/ai/tools/executor.go
+++ b/internal/ai/tools/executor.go
@@ -567,6 +567,13 @@ type PulseToolExecutor struct {
// deliberately separate from isAutonomous, which only suppresses
// interactive questions and grants no mutation authority.
denyInfrastructureMutations bool
+ // pulseStateAllowlist restricts pulse-state mutations to the named
+ // tools when non-nil (empty map = deny all). Nil means the default
+ // posture: pulse-state mutations are not restricted by profile.
+ pulseStateAllowlist map[string]bool
+ // executionProfile is the core-owned request posture; see
+ // execution_profile.go.
+ executionProfile ExecutionProfile
// Session-scoped resolved context for resource validation
// This is set per-session by the agentic loop before tool execution
@@ -724,6 +731,8 @@ func (e *PulseToolExecutor) Clone() *PulseToolExecutor {
isAutonomous: e.isAutonomous,
orgID: e.orgID,
denyInfrastructureMutations: e.denyInfrastructureMutations,
+ pulseStateAllowlist: clonePulseStateAllowlist(e.pulseStateAllowlist),
+ executionProfile: e.executionProfile,
telemetryCallback: e.telemetryCallback,
reportNarrator: e.reportNarrator,
reportFleetNarrator: e.reportFleetNarrator,
@@ -987,6 +996,7 @@ func (e *PulseToolExecutor) invocationPolicy() InvocationPolicy {
return InvocationPolicy{
ControlLevel: e.controlLevel,
DenyInfrastructureMutations: e.denyInfrastructureMutations,
+ PulseStateAllowlist: clonePulseStateAllowlist(e.pulseStateAllowlist),
}
}
diff --git a/internal/ai/tools/invocation_policy_test.go b/internal/ai/tools/invocation_policy_test.go
index ceb17abce3..e88a90e91e 100644
--- a/internal/ai/tools/invocation_policy_test.go
+++ b/internal/ai/tools/invocation_policy_test.go
@@ -104,7 +104,7 @@ func TestProjectionAndRuntimeEnforcementAgree(t *testing.T) {
descriptor, ok := agentcapabilities.InvocationDescriptorFor(tool.Name)
require.True(t, ok, "offered tool %q must have a canonical descriptor", tool.Name)
if descriptor.Static != nil {
- assert.True(t, policy.Allows(*descriptor.Static), "offered static tool %q must be executable", tool.Name)
+ assert.True(t, policy.Allows(tool.Name, *descriptor.Static), "offered static tool %q must be executable", tool.Name)
continue
}
property, ok := tool.InputSchema.Properties[descriptor.Discriminator]
@@ -112,7 +112,7 @@ func TestProjectionAndRuntimeEnforcementAgree(t *testing.T) {
require.NotEmpty(t, property.Enum, "offered mixed tool %q must keep at least one enum value", tool.Name)
for _, value := range property.Enum {
class := descriptor.Classify(map[string]interface{}{descriptor.Discriminator: value})
- assert.True(t, policy.Allows(class),
+ assert.True(t, policy.Allows(tool.Name, class),
"tool %q offers enum %q that runtime enforcement would block", tool.Name, value)
}
}
@@ -150,9 +150,9 @@ func TestExecutorClonesKeepRequestPoliciesIsolated(t *testing.T) {
func TestInvocationPolicyDeniesUnknownMutationTargets(t *testing.T) {
policy := InvocationPolicy{ControlLevel: ControlLevelAutonomous}
- assert.False(t, policy.Allows(agentcapabilities.InvocationClass{Kind: agentcapabilities.ToolCallKindRead}),
+ assert.False(t, policy.Allows("demo_tool", agentcapabilities.InvocationClass{Kind: agentcapabilities.ToolCallKindRead}),
"an empty mutation target must be denied outright")
- assert.False(t, policy.Allows(agentcapabilities.InvocationClass{
+ assert.False(t, policy.Allows("demo_tool", agentcapabilities.InvocationClass{
Kind: agentcapabilities.ToolCallKindRead, Mutation: agentcapabilities.MutationTarget("estate"),
}), "an unknown mutation target must be denied outright")
}
@@ -255,3 +255,99 @@ func TestRegistrationAuthorityIsSplitAndAppendOnly(t *testing.T) {
registry.RegisterExtension(RegisteredTool{Definition: Tool{Name: "undescribed_tool"}})
})
}
+
+func TestPatrolDetectionProfileEnforcesAllowlistedPulseState(t *testing.T) {
+ exec := newInvocationPolicyExecutor(t)
+ exec.SetControlLevel(ControlLevelAutonomous)
+ exec.SetAutonomousMode(true)
+ exec.ApplyExecutionProfile(ProfilePatrolDetection)
+
+ // Applying a Patrol profile clears inherited autonomy and denies
+ // infrastructure outright.
+ if exec.isAutonomous {
+ t.Fatal("detection profile must clear inherited autonomous mode")
+ }
+ text := executeBlockedText(t, exec, "pulse_docker", map[string]interface{}{
+ "action": "update", "container": "nginx", "host": "tower",
+ })
+ assert.Contains(t, text, "Invocation blocked")
+
+ // Pulse-state mutations outside the finding allowlist are blocked
+ // before the handler: detection must not dismiss alerts or write
+ // knowledge.
+ text = executeBlockedText(t, exec, "pulse_alerts", map[string]interface{}{"action": "resolve", "alert_id": "a1"})
+ assert.Contains(t, text, "Invocation blocked")
+ text = executeBlockedText(t, exec, "pulse_knowledge", map[string]interface{}{"action": "remember", "resource_id": "vm:42"})
+ assert.Contains(t, text, "Invocation blocked")
+
+ // The finding lifecycle tools stay allowed (they fail on a missing
+ // finding creator, not on policy).
+ result, err := exec.registry.Execute(context.Background(), exec, "patrol_report_finding", map[string]interface{}{})
+ require.NoError(t, err)
+ require.NotEmpty(t, result.Content)
+ assert.NotContains(t, result.Content[0].Text, "Invocation blocked")
+
+ // Projection agrees: alerts offers only its read subactions.
+ for _, tool := range exec.registry.ListTools(exec.invocationPolicy()) {
+ if tool.Name != agentcapabilities.PulseAlertsToolName {
+ continue
+ }
+ enum := tool.InputSchema.Properties["action"].Enum
+ assert.NotContains(t, enum, "resolve")
+ assert.NotContains(t, enum, "dismiss")
+ assert.Contains(t, enum, "list")
+ }
+}
+
+func TestPatrolInvestigationProfileIsStructurallyReadOnly(t *testing.T) {
+ exec := newInvocationPolicyExecutor(t)
+ exec.SetControlLevel(ControlLevelAutonomous)
+ exec.SetAutonomousMode(true)
+ exec.ApplyExecutionProfile(ProfilePatrolInvestigation)
+
+ if exec.isAutonomous {
+ t.Fatal("investigation profile must clear inherited autonomous mode")
+ }
+
+ // No infrastructure mutations.
+ text := executeBlockedText(t, exec, "pulse_kubernetes", map[string]interface{}{"type": "scale"})
+ assert.Contains(t, text, "Invocation blocked")
+ // No Pulse-state mutations either - not even the Patrol finding tools.
+ text = executeBlockedText(t, exec, "patrol_report_finding", map[string]interface{}{})
+ assert.Contains(t, text, "Invocation blocked")
+ text = executeBlockedText(t, exec, "pulse_alerts", map[string]interface{}{"action": "dismiss", "alert_id": "a1"})
+ assert.Contains(t, text, "Invocation blocked")
+
+ // Reads and mutation-none invocations remain available.
+ result, err := exec.registry.Execute(context.Background(), exec, "pulse_alerts", map[string]interface{}{"action": "list"})
+ require.NoError(t, err)
+ require.NotEmpty(t, result.Content)
+ assert.NotContains(t, result.Content[0].Text, "Invocation blocked")
+
+ // Projection drops the write-only patrol mutation tools entirely.
+ offered := map[string]bool{}
+ for _, tool := range exec.registry.ListTools(exec.invocationPolicy()) {
+ offered[tool.Name] = true
+ }
+ assert.False(t, offered[agentcapabilities.PatrolReportFindingToolName])
+ assert.False(t, offered[agentcapabilities.PatrolResolveFindingToolName])
+ assert.True(t, offered[agentcapabilities.PulseQueryToolName])
+}
+
+func TestExecutionProfileSurvivesCloneIsolation(t *testing.T) {
+ base := newInvocationPolicyExecutor(t)
+ base.ApplyExecutionProfile(ProfilePatrolInvestigation)
+ clone := base.Clone()
+ assert.Equal(t, ProfilePatrolInvestigation, clone.ExecutionProfile())
+ assert.True(t, clone.invocationPolicy().DenyInfrastructureMutations)
+ if clone.pulseStateAllowlist == nil {
+ t.Fatal("clone must carry the pulse-state denylist")
+ }
+
+ // Resetting the clone to interactive must not affect the original.
+ clone.ApplyExecutionProfile(ProfileInteractiveAssistant)
+ assert.Equal(t, ProfilePatrolInvestigation, base.ExecutionProfile())
+ if base.pulseStateAllowlist == nil {
+ t.Fatal("original executor lost its profile policy after clone reset")
+ }
+}
diff --git a/internal/ai/tools/registry.go b/internal/ai/tools/registry.go
index ebae50a611..ed4f6be778 100644
--- a/internal/ai/tools/registry.go
+++ b/internal/ai/tools/registry.go
@@ -88,27 +88,52 @@ func NewToolRegistry() *ToolRegistry {
}
// InvocationPolicy is the request-scoped safety policy the registry
-// enforces on every invocation: the session control level plus an
-// optional deny-infrastructure-mutations restriction (e.g. Patrol
-// investigations). It is core-owned, never serialized, and consulted by
-// both provider projection and runtime execution so the offered schema
-// and the enforcement boundary can never disagree.
+// enforces on every invocation: the session control level plus the
+// execution profile's restrictions (deny infrastructure mutations, and
+// optionally an allowlist of tools permitted to mutate Pulse state). It
+// is core-owned, never serialized, and consulted by both provider
+// projection and runtime execution so the offered schema and the
+// enforcement boundary can never disagree.
type InvocationPolicy struct {
ControlLevel ControlLevel
DenyInfrastructureMutations bool
+ // PulseStateAllowlist restricts pulse-state mutations to the named
+ // tools when non-nil (an empty map denies all pulse-state
+ // mutations). Nil leaves pulse-state mutations unrestricted. An
+ // allowlist rather than a boolean: Patrol detection must record and
+ // resolve findings without also being able to dismiss alerts or
+ // write knowledge.
+ PulseStateAllowlist map[string]bool
}
-// Allows reports whether the policy permits an invocation class.
-// Infrastructure mutations require a control level that allows control
-// tools and are always blocked under the deny restriction; pulse-state
-// and non-mutating invocations are not control-gated here (handlers keep
-// their own defense-in-depth checks). Unknown mutation targets are
-// denied outright, independent of registration validation, so a class
-// that somehow bypasses Validate still cannot execute.
-func (p InvocationPolicy) Allows(class agentcapabilities.InvocationClass) bool {
+func clonePulseStateAllowlist(allowlist map[string]bool) map[string]bool {
+ if allowlist == nil {
+ return nil
+ }
+ clone := make(map[string]bool, len(allowlist))
+ for name, allowed := range allowlist {
+ clone[name] = allowed
+ }
+ return clone
+}
+
+// Allows reports whether the policy permits an invocation class for the
+// named tool. Infrastructure mutations require a control level that
+// allows control tools and are always blocked under the deny restriction;
+// pulse-state mutations honor the profile allowlist; non-mutating
+// invocations are not gated here (handlers keep their own
+// defense-in-depth checks). Unknown mutation targets are denied outright,
+// independent of registration validation, so a class that somehow
+// bypasses Validate still cannot execute.
+func (p InvocationPolicy) Allows(toolName string, class agentcapabilities.InvocationClass) bool {
switch class.Mutation {
- case agentcapabilities.MutationNone, agentcapabilities.MutationPulseState:
+ case agentcapabilities.MutationNone:
return true
+ case agentcapabilities.MutationPulseState:
+ if p.PulseStateAllowlist == nil {
+ return true
+ }
+ return p.PulseStateAllowlist[toolName]
case agentcapabilities.MutationInfrastructure:
if p.DenyInfrastructureMutations {
return false
@@ -270,7 +295,7 @@ func projectToolForPolicy(tool RegisteredTool, policy InvocationPolicy) (Registe
}
descriptor := *tool.Invocation
if descriptor.Static != nil {
- if !policy.Allows(*descriptor.Static) {
+ if !policy.Allows(tool.Definition.Name, *descriptor.Static) {
return RegisteredTool{}, false
}
return applyProjectedGovernance(tool, []agentcapabilities.InvocationClass{*descriptor.Static}), true
@@ -284,7 +309,7 @@ func projectToolForPolicy(tool RegisteredTool, policy InvocationPolicy) (Registe
classes := make([]agentcapabilities.InvocationClass, 0, len(property.Enum))
for _, value := range property.Enum {
class := descriptor.Classify(map[string]interface{}{descriptor.Discriminator: value})
- if !policy.Allows(class) {
+ if !policy.Allows(tool.Definition.Name, class) {
continue
}
allowed = append(allowed, value)
@@ -374,13 +399,14 @@ func (r *ToolRegistry) Execute(ctx context.Context, e *PulseToolExecutor, name s
if tool.Invocation != nil {
class = tool.Invocation.Classify(args)
}
- if class.Mutation == agentcapabilities.MutationInfrastructure {
- if e.invocationPolicy().DenyInfrastructureMutations {
- return agentcapabilities.NewInvocationBlockedToolResult(name, class), nil
- }
- if !agentcapabilities.ControlLevelAllowsControlTools(e.controlLevel) {
+ policy := e.invocationPolicy()
+ if !policy.Allows(name, class) {
+ if class.Mutation == agentcapabilities.MutationInfrastructure && !policy.DenyInfrastructureMutations {
+ // Refused purely by control level: keep the actionable
+ // operator guidance for enabling control tools.
return agentcapabilities.NewControlToolsDisabledToolResult(), nil
}
+ return agentcapabilities.NewInvocationBlockedToolResult(name, class), nil
}
// Legacy tool-level control check, kept as defense in depth.