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.

Build the narrow proposal channel: patrol_propose_action and its capture sink

rcourtman9bc51a8a35f9
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index e00eee2acb..f9b26c3456 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -4651,7 +4651,43 @@ investigation modes directly instead of claiming controlled or
autonomous execution. Non-interactive operation grants no mutation
authority. The profile vocabulary is closed: unknown profile values are
rejected at apply time and classify as non-interactive, never as the
-permissive interactive default. A blocked question call is persisted to
+permissive interactive default.
+The typed proposal channel rides the investigation profile.
+`patrol_propose_action` (side-effect-free, mutation-none, read-kind) is
+projected and executable ONLY under the investigation profile: the
+registry policy rejects a fabricated call under any other posture
+before the handler runs. The model's tool schema carries only
+resource_id, capability_name, params, and reason; proposal, finding,
+investigation, and evidence identity are injected from trusted
+orchestration context through the request-local proposal capture sink
+(`tools.ProposalCapture`), which executor clones share so one run has
+exactly one capture. Tool calls carry an explicit invocation envelope
+(tool-use ID, name, arguments) through `ExecuteInvocation`, and the
+sink keys on call identity plus payload fingerprint: an idempotent
+replay (same ID, same payload) re-succeeds; the same ID with a
+different payload latches a terminal integrity error; a second distinct
+valid proposal latches terminal ambiguity - and both terminal states
+INVALIDATE the captured proposal, because concurrent per-turn execution
+makes "first" nondeterministic. Proposals count only after catalog
+validation (advertised capability, declared/required/enum parameters,
+sensitive parameters rejected before success with no value echo in any
+output) and a successful tool result. `ExecuteInvestigationStream`
+returns proposal cardinality as a structured result - consumers never
+reconstruct proposals from session messages - with typed errors for
+ambiguity, integrity violations, and the failed-attempts-only case
+(zero successful proposals with failed attempts is an error outcome,
+never the valid zero-proposal conclusion); `ListInvestigationTools`
+projects through the identical profile path. Proposal parameter values
+exist only transiently for provider continuation and validation: the
+canonical exposure projector
+(`RedactToolCallArgumentsForExposure`) redacts them from the durable
+chat transcript and every tool_start/tool_progress/tool_end stream
+event, while the action audit remains their canonical durable home.
+Proofs: `internal/ai/tools/proposal_capture_test.go` (concurrent
+ambiguity with nil proposal, replay/integrity semantics by tool-use ID,
+failed-attempts typed error, sensitive rejection without echo,
+profile-only projection and execution) and the end-to-end loop
+redaction proof in `internal/ai/chat/service_tooling_test.go`. A blocked question call is persisted to
the durable transcript paired with its refusal result (the assistant
message records the call, so the transcript must never retain an
unanswered call). Profile proofs live in
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index f428d37e4f..21cabcfecb 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1863,6 +1863,15 @@ a new API state machine, queue contract, or verification-accounting field.
governed action can never lose deterministic correlation.
Plan-only proof: `TestContract_PatrolActionBrokerIsPlanOnly` in
`internal/api/contract_test.go`.
+ The proposal enters that broker from the investigation-only
+ `patrol_propose_action` capture (canonical name and descriptor in
+ `internal/agentcapabilities/`): mutation-none, side-effect-free,
+ rejected by registry policy outside the investigation profile, with
+ the model supplying only resource/capability/params/reason and all
+ correlation identity injected from trusted orchestration context.
+ Proposal parameter values are redacted from durable transcripts and
+ stream events by the shared exposure projector; the action audit is
+ their canonical durable home once the broker plans the proposal.
Executor-owned live readiness is part of planning, not a UI precheck:
after planner validation and before audit persistence, the lifecycle
service must ask
diff --git a/internal/agentcapabilities/invocation.go b/internal/agentcapabilities/invocation.go
index 3e7fb64d68..71f90dc70a 100644
--- a/internal/agentcapabilities/invocation.go
+++ b/internal/agentcapabilities/invocation.go
@@ -225,7 +225,12 @@ var registryInvocationDescriptors = map[string]InvocationDescriptor{
"remember": {Kind: ToolCallKindWrite, Mutation: MutationPulseState},
},
},
- PatrolGetFindingsToolName: staticClass(ToolCallKindRead, MutationNone),
+ PatrolGetFindingsToolName: staticClass(ToolCallKindRead, MutationNone),
+ // patrol_propose_action is side-effect-free capture (mutation-none)
+ // and read-kind so a concluding proposal never drives the FSM into
+ // write verification. It is additionally profile-gated: the registry
+ // policy rejects it outside the Patrol investigation profile.
+ PatrolProposeActionToolName: staticClass(ToolCallKindRead, MutationNone),
PatrolReportFindingToolName: staticClass(ToolCallKindWrite, MutationPulseState),
PatrolResolveFindingToolName: staticClass(ToolCallKindWrite, MutationPulseState),
}
@@ -268,3 +273,29 @@ func ClassifyRegisteredInvocation(toolName string, args map[string]interface{})
}
return descriptor.Classify(args)
}
+
+// RedactedProposalParamsMarker replaces proposal parameter values in every
+// durable or user-visible exposure of a patrol_propose_action call.
+const RedactedProposalParamsMarker = "[redacted-proposal-params]"
+
+// RedactToolCallArgumentsForExposure is the canonical exposure projector
+// for tool-call arguments: everything durable or user-visible (chat
+// transcripts, tool_start/tool_progress/tool_end stream events) must route
+// its arguments through here. Proposal parameter values exist only
+// transiently for provider continuation and validation; the action audit
+// is their canonical durable home. Returns the original map unchanged for
+// tools without exposure restrictions.
+func RedactToolCallArgumentsForExposure(toolName string, args map[string]interface{}) map[string]interface{} {
+ if strings.TrimSpace(toolName) != PatrolProposeActionToolName || args == nil {
+ return args
+ }
+ if _, ok := args["params"]; !ok {
+ return args
+ }
+ redacted := make(map[string]interface{}, len(args))
+ for key, value := range args {
+ redacted[key] = value
+ }
+ redacted["params"] = RedactedProposalParamsMarker
+ return redacted
+}
diff --git a/internal/agentcapabilities/tool_names.go b/internal/agentcapabilities/tool_names.go
index ea69d2a516..5828f95bb8 100644
--- a/internal/agentcapabilities/tool_names.go
+++ b/internal/agentcapabilities/tool_names.go
@@ -33,4 +33,10 @@ const (
PatrolGetFindingsToolName = "patrol_get_findings"
PatrolReportFindingToolName = "patrol_report_finding"
PatrolResolveFindingToolName = "patrol_resolve_finding"
+ // PatrolProposeActionToolName is the side-effect-free typed action
+ // proposal capture for Patrol investigations. Mutation-none: it
+ // records a validated proposal in the request-local capture sink;
+ // planning, approval, and execution stay on the canonical action
+ // lifecycle.
+ PatrolProposeActionToolName = "patrol_propose_action"
)
diff --git a/internal/ai/chat/agentic.go b/internal/ai/chat/agentic.go
index 30bdac3c95..00a49781ac 100644
--- a/internal/ai/chat/agentic.go
+++ b/internal/ai/chat/agentic.go
@@ -456,7 +456,7 @@ func stripProviderErrorPayload(msg string) string {
return cleaned
}
-func (a *AgenticLoop) executeToolSafely(ctx context.Context, name string, input map[string]interface{}) (result tools.CallToolResult, err error) {
+func (a *AgenticLoop) executeToolSafely(ctx context.Context, id, name string, input map[string]interface{}) (result tools.CallToolResult, err error) {
defer func() {
if recovered := recover(); recovered != nil {
panicErr := fmt.Errorf("tool panic in %s: %v", name, recovered)
@@ -469,7 +469,7 @@ func (a *AgenticLoop) executeToolSafely(ctx context.Context, name string, input
err = panicErr
}
}()
- return a.executor.ExecuteTool(ctx, name, input)
+ return a.executor.ExecuteInvocation(ctx, tools.ToolInvocation{ID: id, Name: name, Arguments: input})
}
// AgenticLoop handles the tool-calling loop with streaming
@@ -1574,13 +1574,13 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
defer wg.Done()
sem <- struct{}{}
defer func() { <-sem }()
- r, e := a.executeToolSafely(ctx, tc.Name, tc.Input)
+ r, e := a.executeToolSafely(ctx, tc.ID, tc.Name, tc.Input)
execResults[idx] = parallelToolResult{Result: r, Err: e}
}(j, pe.tc)
}
wg.Wait()
} else if len(pendingExec) == 1 {
- r, e := a.executeToolSafely(ctx, pendingExec[0].tc.Name, pendingExec[0].tc.Input)
+ r, e := a.executeToolSafely(ctx, pendingExec[0].tc.ID, pendingExec[0].tc.Name, pendingExec[0].tc.Input)
execResults[0] = parallelToolResult{Result: r, Err: e}
}
@@ -1727,7 +1727,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
inputWithApproval[k] = v
}
inputWithApproval = agentcapabilities.WithApprovalArgument(inputWithApproval, approvalData.ApprovalID)
- result, err = a.executeToolSafely(ctx, tc.Name, inputWithApproval)
+ result, err = a.executeToolSafely(ctx, tc.ID, tc.Name, inputWithApproval)
if err != nil {
toolResult := agentcapabilities.NewProviderToolErrorResult(tc.ID, fmt.Sprintf("Error after approval: %v", err))
resultText = toolResult.Content
diff --git a/internal/ai/chat/agentic_additional_test.go b/internal/ai/chat/agentic_additional_test.go
index 3598b3b8c2..7b022286c6 100644
--- a/internal/ai/chat/agentic_additional_test.go
+++ b/internal/ai/chat/agentic_additional_test.go
@@ -387,7 +387,7 @@ func TestExecuteToolSafely_RecoversPanic(t *testing.T) {
})
loop := &AgenticLoop{executor: exec}
- result, err := loop.executeToolSafely(context.Background(), "panic_tool", map[string]interface{}{})
+ result, err := loop.executeToolSafely(context.Background(), "call-1", "panic_tool", map[string]interface{}{})
if err == nil {
t.Fatalf("expected panic recovery error")
}
diff --git a/internal/ai/chat/agentic_tool_display.go b/internal/ai/chat/agentic_tool_display.go
index 2b71a82602..d4e0cc4ba6 100644
--- a/internal/ai/chat/agentic_tool_display.go
+++ b/internal/ai/chat/agentic_tool_display.go
@@ -8,6 +8,11 @@ import (
)
func formatToolInputForFrontend(toolName string, input map[string]interface{}, emptyIfNil bool) (inputStr string, rawInput string) {
+ // Canonical exposure projection: every user-visible or durable view
+ // of tool-call arguments routes through here, so restricted values
+ // (proposal params) never leave the transient provider/validation
+ // path.
+ input = agentcapabilities.RedactToolCallArgumentsForExposure(toolName, input)
if input == nil {
if emptyIfNil {
return "", ""
diff --git a/internal/ai/chat/service_investigation.go b/internal/ai/chat/service_investigation.go
new file mode 100644
index 0000000000..025b3135fb
--- /dev/null
+++ b/internal/ai/chat/service_investigation.go
@@ -0,0 +1,200 @@
+package chat
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/modelboundary"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
+ "github.com/rs/zerolog/log"
+)
+
+// InvestigationRunRequest is the core-owned request for one Patrol
+// investigation run. It deliberately carries no autonomy field and no
+// profile selector: the run always executes under the Patrol
+// investigation profile, and correlation identity comes from trusted
+// orchestration context, never from the model or a transport payload.
+type InvestigationRunRequest struct {
+ SessionID string
+ Prompt string
+ SystemPrompt string
+ MaxTurns int
+ ExecutionID string
+ // Identity is the trusted correlation identity injected into any
+ // captured proposal.
+ Identity tools.ProposalIdentity
+ // Catalog resolves advertised resource capabilities for proposal
+ // validation (ultimately the tenant-bound action lifecycle path).
+ Catalog tools.ProposalCatalog
+}
+
+// InvestigationRunResult is the structured outcome of one investigation
+// run. Proposal cardinality is a first-class field: consumers never
+// reconstruct proposals by parsing session messages.
+type InvestigationRunResult struct {
+ Content string
+ // Proposal is the single validated typed action proposal, nil for a
+ // valid zero-proposal conclusion.
+ Proposal *tools.CapturedProposal
+ // FailedProposalAttempts counts proposal calls that failed
+ // validation. When >0 with no captured proposal, the run error is
+ // tools.ErrProposalAttemptsFailed.
+ FailedProposalAttempts int
+ InputTokens int
+ OutputTokens int
+}
+
+// ExecuteInvestigationStream runs one Patrol investigation under the
+// investigation execution profile and returns the structured result.
+// Proposal-channel violations (ambiguity, integrity, failed-only
+// attempts) return the result alongside the typed proposal error.
+func (s *Service) ExecuteInvestigationStream(ctx context.Context, req InvestigationRunRequest, callback StreamCallback) (*InvestigationRunResult, error) {
+ s.mu.RLock()
+ if !s.started {
+ s.mu.RUnlock()
+ return nil, fmt.Errorf("service not started")
+ }
+ sessions := s.sessions
+ baseExecutor := s.executor
+ unifiedResourceProvider := s.unifiedResourceProvider
+ cfg := s.cfg
+ effectiveControlLevel := s.effectiveControlLevelLocked()
+ s.mu.RUnlock()
+
+ if baseExecutor == nil {
+ return nil, fmt.Errorf("no tool executor available")
+ }
+
+ // One effective request executor, built before projection; the
+ // proposal capture sink is shared by design (one run, one capture).
+ capture := tools.NewProposalCapture(req.Identity, req.Catalog)
+ executor := baseExecutor.Clone()
+ executor.SetControlLevel(effectiveControlLevel)
+ executor.ApplyExecutionProfile(tools.ProfilePatrolInvestigation)
+ executor.SetProposalCapture(capture)
+
+ // Investigation uses the Patrol model.
+ investigationModel := ""
+ if cfg != nil {
+ investigationModel = cfg.GetPatrolModel()
+ if investigationModel == "" {
+ investigationModel = cfg.GetChatModel()
+ }
+ }
+ if investigationModel == "" {
+ return nil, fmt.Errorf("no patrol model configured")
+ }
+ provider, err := s.createPatrolProviderForModel(investigationModel)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create investigation provider: %w", err)
+ }
+
+ systemPrompt := req.SystemPrompt
+ if systemPrompt == "" {
+ systemPrompt = s.buildSystemPrompt()
+ }
+ loop := NewAgenticLoop(provider, executor, systemPrompt)
+ loop.SetOrgID(s.orgID)
+ loop.SetExecutionProfile(tools.ProfilePatrolInvestigation)
+ loop.SetExecutionID(req.ExecutionID)
+ loop.SetRequestSanitizer(modelboundary.RequestSanitizerForModel(investigationModel, unifiedResourceProvider))
+ if req.MaxTurns > 0 {
+ loop.SetMaxTurns(req.MaxTurns)
+ }
+ if parts := strings.SplitN(investigationModel, ":", 2); len(parts) == 2 {
+ loop.SetProviderInfo(parts[0], parts[1])
+ }
+ if s.budgetChecker != nil {
+ loop.SetBudgetChecker(s.budgetChecker)
+ }
+
+ sessionID := req.SessionID
+ if sessionID == "" {
+ sessionID = "investigation-" + strings.TrimSpace(req.Identity.InvestigationID)
+ }
+ session, err := sessions.EnsureSession(sessionID)
+ if err != nil {
+ return nil, fmt.Errorf("failed to ensure investigation session: %w", err)
+ }
+ executor.SetResolvedContext(sessions.GetResolvedContext(session.ID))
+ loop.SetSessionFSM(sessions.GetSessionFSM(session.ID))
+ loop.SetKnowledgeAccumulator(sessions.NewKnowledgeAccumulatorForRun(session.ID))
+
+ userMsg := Message{
+ ID: uuid.New().String(),
+ Role: "user",
+ Content: req.Prompt,
+ Timestamp: time.Now(),
+ }
+ if err := sessions.AddMessage(session.ID, userMsg); err != nil {
+ log.Warn().Err(err).Msg("failed to save investigation user message")
+ }
+
+ // Investigation runs are stateless like Patrol detection: only this
+ // run's prompt is loaded; the session is a forensic log.
+ messages := []Message{userMsg}
+ filteredTools := s.toolsForExecutor(executor, false)
+
+ resultMessages, runErr := loop.ExecuteWithTools(ctx, session.ID, messages, filteredTools, callback)
+ for _, msg := range resultMessages {
+ if msg.Role == "user" && msg.ToolResult == nil {
+ continue
+ }
+ if err := sessions.AddMessage(session.ID, msg); err != nil {
+ log.Warn().Err(err).Msg("failed to save investigation message")
+ }
+ }
+
+ var contentBuilder strings.Builder
+ for _, msg := range resultMessages {
+ if msg.Role == "assistant" && msg.Content != "" {
+ contentBuilder.WriteString(msg.Content)
+ }
+ }
+
+ proposal, failedAttempts, proposalErr := capture.Outcome()
+ result := &InvestigationRunResult{
+ Content: contentBuilder.String(),
+ Proposal: proposal,
+ FailedProposalAttempts: failedAttempts,
+ InputTokens: loop.GetTotalInputTokens(),
+ OutputTokens: loop.GetTotalOutputTokens(),
+ }
+ if runErr != nil {
+ return result, runErr
+ }
+ if proposalErr != nil {
+ return result, proposalErr
+ }
+ return result, nil
+}
+
+// ListInvestigationTools names the tools an investigation run offers,
+// projected through the same investigation-profile path the run uses.
+func (s *Service) ListInvestigationTools() []string {
+ s.mu.RLock()
+ executor := s.executor
+ effectiveControlLevel := s.effectiveControlLevelLocked()
+ s.mu.RUnlock()
+ if executor == nil {
+ return nil
+ }
+ effective := executor.Clone()
+ effective.SetControlLevel(effectiveControlLevel)
+ effective.ApplyExecutionProfile(tools.ProfilePatrolInvestigation)
+ // The proposal tool is offered only when a capture could exist; for
+ // listing purposes project with a placeholder sink so the manifest
+ // reflects a real run.
+ effective.SetProposalCapture(tools.NewProposalCapture(tools.ProposalIdentity{}, nil))
+ offered := s.toolsForExecutor(effective, false)
+ names := make([]string, 0, len(offered))
+ for _, tool := range offered {
+ if tool.Name != "" {
+ names = append(names, tool.Name)
+ }
+ }
+ return names
+}
diff --git a/internal/ai/chat/service_tooling_test.go b/internal/ai/chat/service_tooling_test.go
index affcb81045..2e10d85725 100644
--- a/internal/ai/chat/service_tooling_test.go
+++ b/internal/ai/chat/service_tooling_test.go
@@ -1174,3 +1174,103 @@ func TestNonInteractiveProfileBlocksQuestionPersistsPairAndContinues(t *testing.
t.Fatal("loop must continue to the model's final answer after the blocked question")
}
}
+
+func TestInvestigationLoopRedactsProposalParamsEverywhereDurable(t *testing.T) {
+ turn := 0
+ provider := &stubStreamingProvider{}
+ provider.chatStream = func(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
+ turn++
+ if turn == 1 {
+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{
+ ToolCalls: []providers.ToolCall{{
+ ID: "p-1",
+ Name: agentcapabilities.PatrolProposeActionToolName,
+ Input: map[string]interface{}{
+ "resource_id": "vm:42",
+ "capability_name": "restart",
+ "params": map[string]interface{}{"mode": "graceful"},
+ "reason": "recover the stalled web tier",
+ },
+ }},
+ }})
+ return nil
+ }
+ // The provider continuation must still see the raw params from
+ // its own prior call.
+ for _, msg := range req.Messages {
+ for _, tc := range msg.ToolCalls {
+ if tc.Name == agentcapabilities.PatrolProposeActionToolName {
+ params, ok := tc.Input["params"].(map[string]interface{})
+ if !ok || params["mode"] != "graceful" {
+ t.Errorf("provider continuation lost raw proposal params: %#v", tc.Input["params"])
+ }
+ }
+ }
+ }
+ callback(providers.StreamEvent{Type: "content", Data: providers.ContentEvent{Text: "diagnosis: restart proposed"}})
+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{}})
+ return nil
+ }
+
+ capture := tools.NewProposalCapture(
+ tools.ProposalIdentity{ProposalID: "prop-9", FindingID: "f-9", InvestigationID: "inv-9"},
+ func(ctx context.Context, resourceID string) ([]ur.ResourceCapability, error) {
+ return []ur.ResourceCapability{{
+ Name: "restart",
+ Params: []ur.CapabilityParam{
+ {Name: "mode", Type: "string", Required: true, Enum: []string{"graceful", "force"}},
+ },
+ }}, nil
+ })
+ exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
+ exec.ApplyExecutionProfile(tools.ProfilePatrolInvestigation)
+ exec.SetProposalCapture(capture)
+
+ loop := NewAgenticLoop(provider, exec, "base prompt")
+ loop.SetExecutionProfile(tools.ProfilePatrolInvestigation)
+
+ var streamedRawParam bool
+ messages, err := loop.ExecuteWithTools(
+ context.Background(),
+ "session-investigation",
+ []Message{{Role: "user", Content: "investigate finding f-9"}},
+ nil,
+ func(event StreamEvent) {
+ if strings.Contains(string(event.Data), "graceful") {
+ streamedRawParam = true
+ }
+ },
+ )
+ if err != nil {
+ t.Fatalf("ExecuteWithTools: %v", err)
+ }
+ if streamedRawParam {
+ t.Fatal("stream events must never expose proposal parameter values")
+ }
+
+ // The durable transcript keeps the call but with redacted params.
+ var sawCall bool
+ for _, msg := range messages {
+ for _, tc := range msg.ToolCalls {
+ if tc.Name != agentcapabilities.PatrolProposeActionToolName {
+ continue
+ }
+ sawCall = true
+ if tc.Input["params"] != agentcapabilities.RedactedProposalParamsMarker {
+ t.Fatalf("transcript tool call must carry redacted params, got %#v", tc.Input["params"])
+ }
+ }
+ }
+ if !sawCall {
+ t.Fatal("transcript must retain the proposal tool call")
+ }
+
+ // The structured capture holds the validated raw values.
+ proposal, failed, outcomeErr := capture.Outcome()
+ if outcomeErr != nil || failed != 0 {
+ t.Fatalf("outcome = (%v, %d), want clean capture", outcomeErr, failed)
+ }
+ if proposal == nil || proposal.Params["mode"] != "graceful" || proposal.Identity.FindingID != "f-9" || proposal.InvocationID != "p-1" {
+ t.Fatalf("captured proposal = %#v", proposal)
+ }
+}
diff --git a/internal/ai/chat/types.go b/internal/ai/chat/types.go
index 61e7ce5b02..f260d45ccf 100644
--- a/internal/ai/chat/types.go
+++ b/internal/ai/chat/types.go
@@ -146,9 +146,13 @@ func (t ToolCall) NormalizeCollections() ToolCall {
func ToolCallFromProvider(tc agentcapabilities.ProviderToolCall) ToolCall {
tc = tc.NormalizeCollections()
return ToolCall{
- ID: tc.ID,
- Name: tc.Name,
- Input: tc.Input,
+ ID: tc.ID,
+ Name: tc.Name,
+ // The durable transcript routes through the canonical exposure
+ // projector: proposal params live only transiently for provider
+ // continuation and validation; the action audit is their
+ // canonical durable home.
+ Input: agentcapabilities.RedactToolCallArgumentsForExposure(tc.Name, tc.Input),
ThoughtSignature: tc.ThoughtSignature,
}.NormalizeCollections()
}
diff --git a/internal/ai/tools/executor.go b/internal/ai/tools/executor.go
index 0d71bca8dc..8e721130f6 100644
--- a/internal/ai/tools/executor.go
+++ b/internal/ai/tools/executor.go
@@ -574,6 +574,10 @@ type PulseToolExecutor struct {
// executionProfile is the core-owned request posture; see
// execution_profile.go.
executionProfile ExecutionProfile
+ // proposalCapture is the request-local typed-proposal sink for
+ // investigation runs; nil outside them. Clones share the pointer
+ // deliberately: one run, one capture.
+ proposalCapture *ProposalCapture
// Session-scoped resolved context for resource validation
// This is set per-session by the agentic loop before tool execution
@@ -733,6 +737,7 @@ func (e *PulseToolExecutor) Clone() *PulseToolExecutor {
denyInfrastructureMutations: e.denyInfrastructureMutations,
pulseStateAllowlist: clonePulseStateAllowlist(e.pulseStateAllowlist),
executionProfile: e.executionProfile,
+ proposalCapture: e.proposalCapture,
telemetryCallback: e.telemetryCallback,
reportNarrator: e.reportNarrator,
reportFleetNarrator: e.reportFleetNarrator,
@@ -997,6 +1002,7 @@ func (e *PulseToolExecutor) invocationPolicy() InvocationPolicy {
ControlLevel: e.controlLevel,
DenyInfrastructureMutations: e.denyInfrastructureMutations,
PulseStateAllowlist: clonePulseStateAllowlist(e.pulseStateAllowlist),
+ Profile: e.executionProfile,
}
}
@@ -1079,12 +1085,20 @@ func (e *PulseToolExecutor) isToolAvailable(name string) bool {
// ExecuteTool executes a tool and returns the result
func (e *PulseToolExecutor) ExecuteTool(ctx context.Context, name string, args map[string]interface{}) (CallToolResult, error) {
+ return e.ExecuteInvocation(ctx, ToolInvocation{Name: name, Arguments: args})
+}
+
+// ExecuteInvocation runs one tool call carrying its full invocation
+// envelope (tool-use ID, name, arguments). The ID rides the context so
+// stateful capture can key on call identity even under the loop's
+// concurrent per-turn execution.
+func (e *PulseToolExecutor) ExecuteInvocation(ctx context.Context, inv ToolInvocation) (CallToolResult, error) {
log.Debug().
- Str("tool", name).
- Interface("args", args).
+ Str("tool", inv.Name).
+ Str("invocation_id", inv.ID).
Msg("Executing Pulse tool")
- return e.registry.Execute(ctx, e, name, args)
+ return e.registry.Execute(withInvocationID(ctx, inv.ID), e, inv.Name, inv.Arguments)
}
// registerTools registers all available tools
@@ -1133,6 +1147,8 @@ func (e *PulseToolExecutor) registerTools() {
// These are always registered but only functional when patrolFindingCreator is set.
e.registerPatrolTools()
+ e.registerProposeTools()
+
// pulse_summarize - retrospective synthesis for one resource or a fleet
e.registerSummarizeTools()
}
diff --git a/internal/ai/tools/proposal_capture.go b/internal/ai/tools/proposal_capture.go
new file mode 100644
index 0000000000..2a50ab371d
--- /dev/null
+++ b/internal/ai/tools/proposal_capture.go
@@ -0,0 +1,285 @@
+package tools
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "sort"
+ "strings"
+ "sync"
+
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+// ToolInvocation is the explicit envelope for one tool call: the
+// provider-assigned tool-use ID plus name and arguments. The ID travels
+// with the call through the registry so stateful capture (proposal
+// cardinality, idempotent replay) can key on call identity instead of
+// guessing from payloads.
+type ToolInvocation struct {
+ ID string
+ Name string
+ Arguments map[string]interface{}
+}
+
+type invocationIDContextKey struct{}
+
+// withInvocationID stores the tool-use ID for the current call; handlers
+// that need call identity (the proposal capture) read it back with
+// InvocationIDFromContext. Context-carried because tool calls from one
+// provider turn execute concurrently on a shared executor clone.
+func withInvocationID(ctx context.Context, id string) context.Context {
+ if strings.TrimSpace(id) == "" {
+ return ctx
+ }
+ return context.WithValue(ctx, invocationIDContextKey{}, id)
+}
+
+// InvocationIDFromContext returns the tool-use ID for the current call.
+func InvocationIDFromContext(ctx context.Context) string {
+ id, _ := ctx.Value(invocationIDContextKey{}).(string)
+ return id
+}
+
+// ProposalIdentity is the trusted correlation identity for one
+// investigation run, injected by core orchestration context - never by
+// the model, whose tool schema carries only resource, capability, params,
+// and reason.
+type ProposalIdentity struct {
+ ProposalID string
+ FindingID string
+ InvestigationID string
+ EvidenceIDs []string
+}
+
+// CapturedProposal is one validated typed action proposal.
+type CapturedProposal struct {
+ InvocationID string
+ Identity ProposalIdentity
+ ResourceID string
+ CapabilityName string
+ Params map[string]interface{}
+ Reason string
+}
+
+// ProposalCatalog resolves a resource's advertised capabilities for
+// proposal validation. Injected by the core investigation entrypoint
+// (ultimately the tenant-bound action lifecycle Capabilities path).
+type ProposalCatalog func(ctx context.Context, resourceID string) ([]unified.ResourceCapability, error)
+
+// Typed terminal proposal errors surfaced on the structured run result.
+var (
+ // ErrProposalAmbiguous: two distinct valid proposal calls were made.
+ // The run's proposal is invalidated - concurrency makes "first"
+ // nondeterministic, so ambiguity latches terminally.
+ ErrProposalAmbiguous = errors.New("ambiguous investigation result: multiple distinct action proposals were submitted")
+ // ErrProposalIntegrity: the same tool-use ID re-submitted a different
+ // payload. Latches terminally and invalidates the capture.
+ ErrProposalIntegrity = errors.New("proposal integrity violation: one tool-use id submitted conflicting payloads")
+ // ErrProposalAttemptsFailed: no proposal was captured but proposal
+ // attempts failed validation - this is an error outcome, never the
+ // valid zero-proposal conclusion.
+ ErrProposalAttemptsFailed = errors.New("investigation made proposal attempts but none validated")
+)
+
+type proposalCaptureState int
+
+const (
+ proposalCaptureEmpty proposalCaptureState = iota
+ proposalCaptureHeld
+ proposalCaptureAmbiguous
+ proposalCaptureIntegrityViolated
+)
+
+// ProposalCapture is the request-local sink for typed action proposals.
+// One capture serves one investigation run; executor clones share it
+// deliberately so every provider attempt lands in the same sink. State
+// latches terminally: a second distinct valid proposal (or a conflicting
+// replay) invalidates the captured proposal for the whole run.
+type ProposalCapture struct {
+ mu sync.Mutex
+ identity ProposalIdentity
+ catalog ProposalCatalog
+ state proposalCaptureState
+ proposal *CapturedProposal
+ fingerprint string
+ failedAttempts int
+}
+
+// NewProposalCapture builds the sink with trusted identity and the
+// capability catalog used for validation.
+func NewProposalCapture(identity ProposalIdentity, catalog ProposalCatalog) *ProposalCapture {
+ return &ProposalCapture{identity: identity, catalog: catalog}
+}
+
+func proposalFingerprint(resourceID, capabilityName, reason string, params map[string]interface{}) string {
+ payload := struct {
+ ResourceID string `json:"resourceId"`
+ CapabilityName string `json:"capabilityName"`
+ Reason string `json:"reason"`
+ Params map[string]interface{} `json:"params"`
+ }{resourceID, capabilityName, reason, params}
+ encoded, err := json.Marshal(payload)
+ if err != nil {
+ return "unfingerprintable"
+ }
+ sum := sha256.Sum256(encoded)
+ return hex.EncodeToString(sum[:])
+}
+
+// RecordFailedAttempt tallies a proposal call that failed validation.
+// Failed attempts never count as proposals, but their presence turns a
+// zero-proposal run into a typed error rather than a valid conclusion.
+func (c *ProposalCapture) RecordFailedAttempt() {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.failedAttempts++
+}
+
+// Submit records one validated proposal call. Semantics by call identity
+// and payload fingerprint:
+// - first valid call: captured;
+// - same ID, same payload: idempotent replay (still captured);
+// - same ID, different payload: terminal integrity error, capture
+// invalidated;
+// - distinct ID, valid payload: terminal ambiguity, capture invalidated
+// (concurrent execution makes "first" nondeterministic, so neither
+// call wins).
+func (c *ProposalCapture) Submit(invocationID, resourceID, capabilityName, reason string, params map[string]interface{}) error {
+ invocationID = strings.TrimSpace(invocationID)
+ if invocationID == "" {
+ c.mu.Lock()
+ c.failedAttempts++
+ c.mu.Unlock()
+ return fmt.Errorf("proposal call carries no tool-use id; cannot establish call identity")
+ }
+ fingerprint := proposalFingerprint(resourceID, capabilityName, reason, params)
+
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ switch c.state {
+ case proposalCaptureAmbiguous:
+ return ErrProposalAmbiguous
+ case proposalCaptureIntegrityViolated:
+ return ErrProposalIntegrity
+ case proposalCaptureEmpty:
+ c.state = proposalCaptureHeld
+ c.fingerprint = fingerprint
+ c.proposal = &CapturedProposal{
+ InvocationID: invocationID,
+ Identity: c.identity,
+ ResourceID: resourceID,
+ CapabilityName: capabilityName,
+ Params: params,
+ Reason: reason,
+ }
+ return nil
+ default: // proposalCaptureHeld
+ if c.proposal != nil && c.proposal.InvocationID == invocationID {
+ if c.fingerprint == fingerprint {
+ // Idempotent replay of the same call.
+ return nil
+ }
+ c.state = proposalCaptureIntegrityViolated
+ c.proposal = nil
+ return ErrProposalIntegrity
+ }
+ c.state = proposalCaptureAmbiguous
+ c.proposal = nil
+ return ErrProposalAmbiguous
+ }
+}
+
+// Outcome reports the run's terminal proposal state: the captured
+// proposal (nil for a valid zero-proposal run) or the typed error that
+// invalidated the run. Zero proposals with failed attempts is an error,
+// never a valid conclusion.
+func (c *ProposalCapture) Outcome() (*CapturedProposal, int, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ switch c.state {
+ case proposalCaptureAmbiguous:
+ return nil, c.failedAttempts, ErrProposalAmbiguous
+ case proposalCaptureIntegrityViolated:
+ return nil, c.failedAttempts, ErrProposalIntegrity
+ case proposalCaptureHeld:
+ proposal := *c.proposal
+ return &proposal, c.failedAttempts, nil
+ default:
+ if c.failedAttempts > 0 {
+ return nil, c.failedAttempts, ErrProposalAttemptsFailed
+ }
+ return nil, 0, nil
+ }
+}
+
+// validateProposalAgainstCatalog checks the proposal against the
+// resource's advertised capability contract. Error messages never echo
+// parameter values: proposal params exist only transiently for provider
+// continuation and validation.
+func validateProposalAgainstCatalog(ctx context.Context, catalog ProposalCatalog, resourceID, capabilityName string, params map[string]interface{}) error {
+ if catalog == nil {
+ return errors.New("no capability catalog is wired for proposal validation")
+ }
+ capabilities, err := catalog(ctx, resourceID)
+ if err != nil {
+ return fmt.Errorf("capability catalog lookup failed for resource %q", resourceID)
+ }
+ var capability *unified.ResourceCapability
+ for i := range capabilities {
+ if strings.EqualFold(strings.TrimSpace(capabilities[i].Name), capabilityName) {
+ capability = &capabilities[i]
+ break
+ }
+ }
+ if capability == nil {
+ return fmt.Errorf("resource %q does not advertise capability %q", resourceID, capabilityName)
+ }
+
+ declared := map[string]unified.CapabilityParam{}
+ for _, param := range capability.Params {
+ declared[param.Name] = param
+ }
+ var missing []string
+ for _, param := range capability.Params {
+ if !param.Required {
+ continue
+ }
+ if _, ok := params[param.Name]; !ok {
+ missing = append(missing, param.Name)
+ }
+ }
+ sort.Strings(missing)
+ if len(missing) > 0 {
+ return fmt.Errorf("proposal is missing required parameter(s) %v for capability %q", missing, capabilityName)
+ }
+ for name, value := range params {
+ param, ok := declared[name]
+ if !ok {
+ return fmt.Errorf("parameter %q is not declared by capability %q", name, capabilityName)
+ }
+ if param.IsSensitive && value != nil {
+ return fmt.Errorf("parameter %q is sensitive and must be supplied by an operator on the canonical approval surface, never by an investigation", name)
+ }
+ if len(param.Enum) > 0 {
+ text, isString := value.(string)
+ if !isString {
+ return fmt.Errorf("parameter %q must be one of the declared enum values", name)
+ }
+ allowed := false
+ for _, candidate := range param.Enum {
+ if candidate == text {
+ allowed = true
+ break
+ }
+ }
+ if !allowed {
+ return fmt.Errorf("parameter %q must be one of the declared enum values", name)
+ }
+ }
+ }
+ return nil
+}
diff --git a/internal/ai/tools/proposal_capture_test.go b/internal/ai/tools/proposal_capture_test.go
new file mode 100644
index 0000000000..b938b4547f
--- /dev/null
+++ b/internal/ai/tools/proposal_capture_test.go
@@ -0,0 +1,227 @@
+package tools
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+func testProposalCatalog() ProposalCatalog {
+ return func(ctx context.Context, resourceID string) ([]unified.ResourceCapability, error) {
+ if resourceID != "vm:42" {
+ return nil, nil
+ }
+ return []unified.ResourceCapability{
+ {
+ Name: "restart",
+ MinimumApprovalLevel: unified.ApprovalAdmin,
+ Params: []unified.CapabilityParam{
+ {Name: "mode", Type: "string", Required: true, Enum: []string{"graceful", "force"}},
+ },
+ },
+ {
+ Name: "join_cluster",
+ MinimumApprovalLevel: unified.ApprovalAdmin,
+ Params: []unified.CapabilityParam{
+ {Name: "join_token", Type: "string", Required: true, IsSensitive: true},
+ },
+ },
+ }, nil
+ }
+}
+
+func newInvestigationExecutor(t *testing.T, capture *ProposalCapture) *PulseToolExecutor {
+ t.Helper()
+ exec := NewPulseToolExecutor(ExecutorConfig{})
+ exec.ApplyExecutionProfile(ProfilePatrolInvestigation)
+ exec.SetProposalCapture(capture)
+ return exec
+}
+
+func proposeArgs() map[string]interface{} {
+ return map[string]interface{}{
+ "resource_id": "vm:42",
+ "capability_name": "restart",
+ "params": map[string]interface{}{"mode": "graceful"},
+ "reason": "recover the stalled web tier",
+ }
+}
+
+func executePropose(t *testing.T, exec *PulseToolExecutor, id string, args map[string]interface{}) CallToolResult {
+ t.Helper()
+ result, err := exec.ExecuteInvocation(context.Background(), ToolInvocation{
+ ID: id,
+ Name: agentcapabilities.PatrolProposeActionToolName,
+ Arguments: args,
+ })
+ require.NoError(t, err)
+ require.NotEmpty(t, result.Content)
+ return result
+}
+
+// The essential proof: two concurrent valid proposal calls latch terminal
+// ambiguity with a nil proposal, regardless of execution order.
+func TestConcurrentValidProposalsLatchAmbiguityWithNoProposal(t *testing.T) {
+ capture := NewProposalCapture(ProposalIdentity{ProposalID: "prop-1", FindingID: "f-1", InvestigationID: "inv-1"}, testProposalCatalog())
+ exec := newInvestigationExecutor(t, capture)
+
+ second := proposeArgs()
+ second["reason"] = "an alternative remediation"
+
+ var wg sync.WaitGroup
+ wg.Add(2)
+ go func() { defer wg.Done(); executePropose(t, exec, "call-a", proposeArgs()) }()
+ go func() { defer wg.Done(); executePropose(t, exec, "call-b", second) }()
+ wg.Wait()
+
+ proposal, _, err := capture.Outcome()
+ if !errors.Is(err, ErrProposalAmbiguous) {
+ t.Fatalf("outcome error = %v, want ErrProposalAmbiguous", err)
+ }
+ if proposal != nil {
+ t.Fatalf("ambiguous run must invalidate the captured proposal, got %#v", proposal)
+ }
+}
+
+func TestProposalReplaySemanticsByInvocationID(t *testing.T) {
+ capture := NewProposalCapture(ProposalIdentity{InvestigationID: "inv-1"}, testProposalCatalog())
+ exec := newInvestigationExecutor(t, capture)
+
+ executePropose(t, exec, "call-a", proposeArgs())
+ // Same ID, same payload: idempotent replay.
+ replay := executePropose(t, exec, "call-a", proposeArgs())
+ assert.Contains(t, replay.Content[0].Text, "Proposal recorded")
+
+ proposal, failed, err := capture.Outcome()
+ require.NoError(t, err)
+ require.NotNil(t, proposal)
+ assert.Equal(t, 0, failed)
+ assert.Equal(t, "call-a", proposal.InvocationID)
+ assert.Equal(t, "inv-1", proposal.Identity.InvestigationID)
+
+ // Same ID, different payload: terminal integrity error, capture
+ // invalidated.
+ mutated := proposeArgs()
+ mutated["reason"] = "changed my mind"
+ conflict := executePropose(t, exec, "call-a", mutated)
+ assert.Contains(t, conflict.Content[0].Text, "integrity")
+
+ proposal, _, err = capture.Outcome()
+ if !errors.Is(err, ErrProposalIntegrity) {
+ t.Fatalf("outcome error = %v, want ErrProposalIntegrity", err)
+ }
+ assert.Nil(t, proposal)
+}
+
+func TestFailedAttemptsWithoutSuccessAreATypedError(t *testing.T) {
+ capture := NewProposalCapture(ProposalIdentity{}, testProposalCatalog())
+ exec := newInvestigationExecutor(t, capture)
+
+ bad := proposeArgs()
+ bad["capability_name"] = "detonate"
+ result := executePropose(t, exec, "call-a", bad)
+ assert.Contains(t, result.Content[0].Text, "does not advertise")
+
+ proposal, failed, err := capture.Outcome()
+ if !errors.Is(err, ErrProposalAttemptsFailed) {
+ t.Fatalf("outcome error = %v, want ErrProposalAttemptsFailed", err)
+ }
+ assert.Nil(t, proposal)
+ assert.Equal(t, 1, failed)
+
+ // A clean zero-proposal run stays a valid conclusion.
+ clean := NewProposalCapture(ProposalIdentity{}, testProposalCatalog())
+ proposal, failed, err = clean.Outcome()
+ require.NoError(t, err)
+ assert.Nil(t, proposal)
+ assert.Equal(t, 0, failed)
+}
+
+func TestSensitiveProposalParamsRejectedWithoutEcho(t *testing.T) {
+ capture := NewProposalCapture(ProposalIdentity{}, testProposalCatalog())
+ exec := newInvestigationExecutor(t, capture)
+
+ args := proposeArgs()
+ args["capability_name"] = "join_cluster"
+ args["params"] = map[string]interface{}{"join_token": "super-secret-token-value"}
+ result := executePropose(t, exec, "call-a", args)
+ text := result.Content[0].Text
+ assert.Contains(t, text, "sensitive")
+ assert.NotContains(t, text, "super-secret-token-value", "refusals must never echo parameter values")
+
+ proposal, failed, err := capture.Outcome()
+ if !errors.Is(err, ErrProposalAttemptsFailed) {
+ t.Fatalf("outcome error = %v, want ErrProposalAttemptsFailed", err)
+ }
+ assert.Nil(t, proposal)
+ assert.Equal(t, 1, failed)
+}
+
+func TestProposeActionIsInvestigationProfileOnly(t *testing.T) {
+ for _, profile := range []ExecutionProfile{ProfileInteractiveAssistant, ProfilePatrolDetection} {
+ exec := NewPulseToolExecutor(ExecutorConfig{})
+ exec.SetControlLevel(ControlLevelAutonomous)
+ exec.ApplyExecutionProfile(profile)
+ // Even with a capture wired, the registry policy rejects the
+ // fabricated call before the handler.
+ exec.SetProposalCapture(NewProposalCapture(ProposalIdentity{}, testProposalCatalog()))
+
+ result, err := exec.ExecuteInvocation(context.Background(), ToolInvocation{
+ ID: "call-x",
+ Name: agentcapabilities.PatrolProposeActionToolName,
+ Arguments: proposeArgs(),
+ })
+ require.NoError(t, err)
+ require.NotEmpty(t, result.Content)
+ assert.Contains(t, result.Content[0].Text, "Invocation blocked",
+ "profile %d must reject patrol_propose_action at the registry boundary", profile)
+
+ // And it never appears in the projected manifest.
+ for _, tool := range exec.registry.ListTools(exec.invocationPolicy()) {
+ if tool.Name == agentcapabilities.PatrolProposeActionToolName {
+ t.Fatalf("profile %d must not offer patrol_propose_action", profile)
+ }
+ }
+ }
+
+ // Under investigation the tool is both offered and executable.
+ capture := NewProposalCapture(ProposalIdentity{}, testProposalCatalog())
+ exec := newInvestigationExecutor(t, capture)
+ offered := false
+ for _, tool := range exec.registry.ListTools(exec.invocationPolicy()) {
+ if tool.Name == agentcapabilities.PatrolProposeActionToolName {
+ offered = true
+ }
+ }
+ assert.True(t, offered, "investigation profile must offer patrol_propose_action")
+ result := executePropose(t, exec, "call-a", proposeArgs())
+ assert.Contains(t, result.Content[0].Text, "Proposal recorded")
+}
+
+func TestProposalExposureProjectorRedactsParams(t *testing.T) {
+ args := proposeArgs()
+ redacted := agentcapabilities.RedactToolCallArgumentsForExposure(agentcapabilities.PatrolProposeActionToolName, args)
+ assert.Equal(t, agentcapabilities.RedactedProposalParamsMarker, redacted["params"])
+ assert.Equal(t, "vm:42", redacted["resource_id"])
+ // The transient map used for provider continuation and validation is
+ // untouched.
+ if _, ok := args["params"].(map[string]interface{}); !ok {
+ t.Fatal("projector must not mutate the original arguments")
+ }
+ if !strings.Contains(redacted["reason"].(string), "recover") {
+ t.Fatal("non-parameter fields stay exposed")
+ }
+ // Other tools pass through unchanged.
+ other := agentcapabilities.RedactToolCallArgumentsForExposure("pulse_query", args)
+ if _, ok := other["params"].(map[string]interface{}); !ok {
+ t.Fatal("non-proposal tools must not be redacted")
+ }
+}
diff --git a/internal/ai/tools/registry.go b/internal/ai/tools/registry.go
index ed4f6be778..8fa3825ace 100644
--- a/internal/ai/tools/registry.go
+++ b/internal/ai/tools/registry.go
@@ -104,6 +104,9 @@ type InvocationPolicy struct {
// resolve findings without also being able to dismiss alerts or
// write knowledge.
PulseStateAllowlist map[string]bool
+ // Profile is the execution posture; profile-restricted tools (the
+ // investigation-only proposal capture) key on it.
+ Profile ExecutionProfile
}
func clonePulseStateAllowlist(allowlist map[string]bool) map[string]bool {
@@ -126,6 +129,13 @@ func clonePulseStateAllowlist(allowlist map[string]bool) map[string]bool {
// independent of registration validation, so a class that somehow
// bypasses Validate still cannot execute.
func (p InvocationPolicy) Allows(toolName string, class agentcapabilities.InvocationClass) bool {
+ // patrol_propose_action is investigation-profile-only: a fabricated
+ // call under any other posture is rejected here, before the handler,
+ // and the same check keeps it out of every other profile's projected
+ // manifest.
+ if toolName == agentcapabilities.PatrolProposeActionToolName && p.Profile != ProfilePatrolInvestigation {
+ return false
+ }
switch class.Mutation {
case agentcapabilities.MutationNone:
return true
diff --git a/internal/ai/tools/tools_propose.go b/internal/ai/tools/tools_propose.go
new file mode 100644
index 0000000000..ec1219ae52
--- /dev/null
+++ b/internal/ai/tools/tools_propose.go
@@ -0,0 +1,104 @@
+package tools
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+// registerProposeTools registers the investigation-only typed action
+// proposal capture. The registry policy rejects this tool outside the
+// Patrol investigation profile before this handler runs; the handler
+// additionally requires the request-local capture sink, which only the
+// core investigation entrypoint wires.
+func (e *PulseToolExecutor) registerProposeTools() {
+ e.registry.registerBuiltin(RegisteredTool{
+ Definition: Tool{
+ Name: agentcapabilities.PatrolProposeActionToolName,
+ Description: `Propose ONE typed remediation action for the finding under investigation. Side-effect-free: the proposal is validated and recorded for governed planning and approval; nothing executes now.
+
+Reference an advertised resource capability (see the resource's capability catalog) and fill only its declared parameters. Never place secrets in params - sensitive parameters are supplied by an operator at approval time.
+
+Submit at most one proposal per investigation. If no safe remediation exists, conclude without proposing.`,
+ InputSchema: InputSchema{
+ Type: "object",
+ Properties: map[string]PropertySchema{
+ "resource_id": {
+ Type: "string",
+ Description: "Canonical resource ID the action targets",
+ },
+ "capability_name": {
+ Type: "string",
+ Description: "Advertised capability name on that resource",
+ },
+ "params": {
+ Type: "object",
+ Description: "Values for the capability's declared parameters (non-sensitive only)",
+ },
+ "reason": {
+ Type: "string",
+ Description: "Why this action remediates the finding",
+ },
+ },
+ Required: []string{"resource_id", "capability_name", "reason"},
+ },
+ },
+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {
+ return exec.executeProposeAction(ctx, args)
+ },
+ Governance: ToolGovernance{
+ ActionMode: ToolActionRead,
+ ApprovalPolicy: ToolApprovalScopeOnly,
+ ApprovalSummary: "side-effect-free proposal capture; the proposed action itself is planned and approved on the canonical action lifecycle",
+ Summary: "Records one validated typed action proposal during a Patrol investigation; planning, approval, and execution stay governed.",
+ },
+ })
+}
+
+// executeProposeAction validates and captures a typed action proposal.
+// Success and error outputs never echo parameter values.
+func (e *PulseToolExecutor) executeProposeAction(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {
+ capture := e.proposalCapture
+ if capture == nil {
+ return NewErrorResult(fmt.Errorf("action proposals are not available in this run")), nil
+ }
+
+ resourceID := unified.CanonicalResourceID(stringArg(args, "resource_id"))
+ capabilityName := strings.TrimSpace(stringArg(args, "capability_name"))
+ reason := strings.TrimSpace(stringArg(args, "reason"))
+ params, _ := args["params"].(map[string]interface{})
+ if params == nil {
+ params = map[string]interface{}{}
+ }
+ if resourceID == "" || capabilityName == "" || reason == "" {
+ capture.RecordFailedAttempt()
+ return NewErrorResult(fmt.Errorf("resource_id, capability_name, and reason are required")), nil
+ }
+
+ if err := validateProposalAgainstCatalog(ctx, capture.catalog, resourceID, capabilityName, params); err != nil {
+ capture.RecordFailedAttempt()
+ return NewErrorResult(err), nil
+ }
+
+ if err := capture.Submit(InvocationIDFromContext(ctx), resourceID, capabilityName, reason, params); err != nil {
+ return NewErrorResult(err), nil
+ }
+ return NewTextResult(fmt.Sprintf(
+ "Proposal recorded: capability %q on resource %q. It will be planned and routed for governed approval; nothing has executed. Conclude the investigation with your diagnosis.",
+ capabilityName, resourceID)), nil
+}
+
+func stringArg(args map[string]interface{}, key string) string {
+ value, _ := args[key].(string)
+ return value
+}
+
+// SetProposalCapture wires the request-local proposal sink. Only the core
+// investigation entrypoint calls this, on the effective request executor;
+// clones share the sink deliberately so one run has exactly one capture.
+func (e *PulseToolExecutor) SetProposalCapture(capture *ProposalCapture) {
+ e.proposalCapture = capture
+}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 67feefb4c5..e8577c5487 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -18398,7 +18398,7 @@ func TestContract_PulseMCPAdapterProjectsAgentCapabilitiesManifest(t *testing.T)
`agentcapabilities.SurfaceIDPulseAssistant`,
`fallbackAssistantToolGovernanceOfferedNames(manifest)`,
`agentcapabilities.ManifestSurfaceAffordances(`,
- `providerTools := s.executor.AssistantProviderTools(agentcapabilities.AssistantProviderToolOptions{`,
+ `providerTools := 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)`,
@@ -18568,7 +18568,8 @@ func TestContract_PulseMCPAdapterProjectsAgentCapabilitiesManifest(t *testing.T)
// Invocation-level enforcement runs before the handler and
// consumes the same descriptor the projection filters with.
`class = tool.Invocation.Classify(args)`,
- `if class.Mutation == agentcapabilities.MutationInfrastructure {`,
+ `if !policy.Allows(name, class) {`,
+ `if class.Mutation == agentcapabilities.MutationInfrastructure && !policy.DenyInfrastructureMutations {`,
`agentcapabilities.NewInvocationBlockedToolResult(name, class)`,
`descriptor.Validate(name, discriminatorEnum(tool.Definition, descriptor.Discriminator))`,
`func projectToolForPolicy(tool RegisteredTool, policy InvocationPolicy) (RegisteredTool, bool)`,