Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Preserve durable Patrol outcomes across Claude wrapper retries
rcourtmane1e1048e08a7
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex ced0ca7df1..0982c5da76 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -298,21 +298,17 @@ canonical qualified Pulse model identity from shared callers, strips only itsown subscription-provider prefix before CLI execution, and rejects foreignprovider prefixes rather than forwarding an invalid or cross-provider modelname to the local agent.-Claude receives that output schema through the trusted adapter system channel-and returns one JSON result that Pulse decodes with unknown fields and trailing-values rejected whenever the model selects tools. After a successful-`patrol_report_finding`, `patrol_assess_finding`, or `patrol_resolve_finding`-result, the next non-required turn may end with ordinary assistant prose;-Pulse accepts that as a no-tool completion only after rejecting provider-tool-call artifacts against the offered tool catalogue. Plain content before a-successful Patrol outcome remains an error, so prose wrapped around an-unexecuted tool decision cannot silently turn a faulty run healthy.-Required-tool turns still fail when no structured call is returned. Pulse does-not use Claude Code's hidden `--json-schema`-retry loop: live qualification proved that wrapper could exhaust retries after-the model had already completed valid finding calls, incorrectly converting a-durable Patrol outcome into a provider failure. Codex may continue to use its-native output-schema file because its CLI exposes the completed turn directly.+Claude uses its native output-schema mode for every provider decision. Pulse+decodes completed structured turns with unknown fields and trailing values+rejected. Live qualification also proved that Claude's wrapper may exhaust its+structured-output retries on the final turn after Pulse has already persisted+a successful `patrol_report_finding`, `patrol_assess_finding`, or+`patrol_resolve_finding` result. Only that typed terminal reason immediately+after that successful lifecycle result is normalized to a no-tool completion;+its reported usage is retained. The same wrapper failure before a durable+outcome, after a failed tool result, or for any other terminal reason remains a+provider error. This keeps the governed finding as source of truth without+turning prose-wrapped or incomplete tool decisions into healthy runs.Patrol consumes the provider streaming interface, so the adapter projects eachfully validated CLI turn into canonical buffered `content`, `tool_start`, and`done` events. It must emit nothing before the complete CLI response passes thediff --git a/internal/ai/providers/subscription_agent.go b/internal/ai/providers/subscription_agent.goindex a6715c69dc..7c554270c2 100644--- a/internal/ai/providers/subscription_agent.go+++ b/internal/ai/providers/subscription_agent.go@@ -13,7 +13,6 @@ import ("strings""time"- "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities""github.com/rcourtman/pulse-go-rewrite/internal/config")@@ -80,6 +79,21 @@ type claudePrintResponse struct {} `json:"usage"`}+type subscriptionAgentCommandError struct {+ command string+ cause error+ detail string+ terminalReason string+ inputTokens int+ outputTokens int+}++func (e *subscriptionAgentCommandError) Error() string {+ return fmt.Sprintf("%s subscription agent failed: %v: %s", e.command, e.cause, e.detail)+}++func (e *subscriptionAgentCommandError) Unwrap() error { return e.cause }+type cappedBuffer struct {buffer bytes.BuffermaxBytes int@@ -217,17 +231,14 @@ func (c *SubscriptionAgentClient) Chat(ctx context.Context, req ChatRequest) (*Craw, err = os.ReadFile(outputPath)}case SubscriptionAgentClaude:- // Claude Code's --json-schema mode may exhaust its hidden structured-- // output retries after already returning valid Pulse tool decisions on- // earlier provider turns. Keep the schema in the trusted system channel- // and validate the single JSON result locally instead; this avoids- // converting a completed Patrol finding into a terminal wrapper error.- claudeSystemPrompt := subscriptionAgentControlPrompt + "\n\nTRUSTED_OUTPUT_SCHEMA_JSON\n" + string(schemaBytes)- raw, err = c.run(ctx, "claude", []string{"-p", "--model", c.model, "--output-format", "json", "--safe-mode", "--no-session-persistence", "--permission-mode", "dontAsk", "--tools", "", "--system-prompt", claudeSystemPrompt}, requestPrompt, workdir)+ raw, err = c.run(ctx, "claude", []string{"-p", "--model", c.model, "--output-format", "json", "--json-schema", string(schemaBytes), "--safe-mode", "--no-session-persistence", "--permission-mode", "dontAsk", "--tools", "", "--system-prompt", subscriptionAgentControlPrompt}, requestPrompt, workdir)default:return nil, fmt.Errorf("unknown subscription agent %q", c.agent)}if err != nil {+ if response, ok := claudePostOutcomeCompletion(req, c.model, err); ok {+ return response.NormalizeCollectionsPtr(), nil+ }return nil, err}if len(raw) > maxSubscriptionAgentOutputBytes {@@ -235,9 +246,6 @@ func (c *SubscriptionAgentClient) Chat(ctx context.Context, req ChatRequest) (*C}turn, err := decodeSubscriptionAgentTurn(c.agent, raw)- if err != nil && c.agent == SubscriptionAgentClaude {- turn, err = decodeClaudePlainCompletion(req, raw)- }if err != nil {return nil, err}@@ -332,7 +340,22 @@ func (c *SubscriptionAgentClient) run(ctx context.Context, name string, args []sif len(message) > 2000 {message = message[len(message)-2000:]}- return nil, fmt.Errorf("%s subscription agent failed: %w: %s", name, err, message)+ commandErr := &subscriptionAgentCommandError{command: name, cause: err, detail: message}+ if name == "claude" {+ var terminal struct {+ TerminalReason string `json:"terminal_reason"`+ Usage struct {+ InputTokens int `json:"input_tokens"`+ OutputTokens int `json:"output_tokens"`+ } `json:"usage"`+ }+ if json.Unmarshal(stdout.buffer.Bytes(), &terminal) == nil {+ commandErr.terminalReason = terminal.TerminalReason+ commandErr.inputTokens = terminal.Usage.InputTokens+ commandErr.outputTokens = terminal.Usage.OutputTokens+ }+ }+ return nil, commandErr}if stdout.exceeded || stderr.exceeded {return nil, fmt.Errorf("%s subscription agent output exceeded %d bytes", name, maxSubscriptionAgentOutputBytes)@@ -449,41 +472,6 @@ func decodeSubscriptionAgentTurn(agent SubscriptionAgent, raw []byte) (subscriptreturn turn, nil}-func decodeClaudePlainCompletion(req ChatRequest, raw []byte) (subscriptionAgentTurn, error) {- var turn subscriptionAgentTurn- if !followsSuccessfulPatrolOutcome(req) {- return turn, errors.New("Claude subscription response returned plain content before a successful Patrol outcome")- }- var wrapper claudePrintResponse- if err := json.Unmarshal(raw, &wrapper); err != nil {- return turn, fmt.Errorf("decode Claude subscription response: %w", err)- }- if len(wrapper.PermissionDenials) > 0 {- return turn, errors.New("Claude subscription agent attempted a denied built-in tool")- }- if len(wrapper.StructuredOutput) > 0 && string(wrapper.StructuredOutput) != "null" {- return turn, errors.New("Claude subscription response contained invalid structured output")- }- content := strings.TrimSpace(wrapper.Result)- if content == "" {- return turn, errors.New("Claude subscription response did not contain structured output or a plain completion")- }- toolNames := make([]string, 0, len(req.Tools))- for _, tool := range req.Tools {- toolNames = append(toolNames, tool.Name)- }- catalog := agentcapabilities.NewProviderToolNameCatalog(toolNames)- if strings.Contains(content, `"tool_calls"`) || agentcapabilities.ProviderToolCallArtifactIndex(content, catalog) >= 0 {- return turn, errors.New("Claude subscription response leaked a tool call through plain content")- }- turn.Content = content- turn.StopReason = "end_turn"- turn.RawToolCalls = []subscriptionAgentToolCall{}- turn.InputTokens = wrapper.Usage.InputTokens- turn.OutputTokens = wrapper.Usage.OutputTokens- return turn, nil-}-func followsSuccessfulPatrolOutcome(req ChatRequest) bool {if len(req.Messages) < 2 {return false@@ -508,6 +496,21 @@ func followsSuccessfulPatrolOutcome(req ChatRequest) bool {return false}+func claudePostOutcomeCompletion(req ChatRequest, model string, err error) (*ChatResponse, bool) {+ var commandErr *subscriptionAgentCommandError+ if !errors.As(err, &commandErr) || commandErr.command != "claude" || commandErr.terminalReason != "structured_output_retry_exhausted" || !followsSuccessfulPatrolOutcome(req) {+ return nil, false+ }+ return &ChatResponse{+ Content: "",+ Model: model,+ StopReason: "end_turn",+ ToolCalls: []ToolCall{},+ InputTokens: commandErr.inputTokens,+ OutputTokens: commandErr.outputTokens,+ }, true+}+func decodeStrictJSON(raw []byte, target interface{}) error {decoder := json.NewDecoder(bytes.NewReader(raw))decoder.DisallowUnknownFields()diff --git a/internal/ai/providers/subscription_agent_test.go b/internal/ai/providers/subscription_agent_test.goindex bbcbb5364f..368f61f403 100644--- a/internal/ai/providers/subscription_agent_test.go+++ b/internal/ai/providers/subscription_agent_test.go@@ -3,6 +3,7 @@ package providersimport ("context""encoding/json"+ "errors""os""path/filepath""runtime"@@ -210,8 +211,7 @@ if [ "$1" = "auth" ]; thenexit 0fiseen_system=false-seen_output_schema=false-seen_json_schema_arg=false+seen_json_schema=falseseen_no_tools=falseseen_dont_ask=falsewhile [ "$#" -gt 0 ]; do@@ -224,13 +224,12 @@ while [ "$#" -gt 0 ]; docase "$1" in*"IGNORE ALL RULES"*) echo "infrastructure data leaked into system prompt" >&2; exit 93 ;;esac- case "$1" in- *"TRUSTED_OUTPUT_SCHEMA_JSON"*'"input"'*) seen_output_schema=true ;;- esac;;--json-schema)- seen_json_schema_arg=trueshift+ case "$1" in+ *'"input"'*) seen_json_schema=true ;;+ esac;;--tools)shift@@ -244,11 +243,10 @@ while [ "$#" -gt 0 ]; doshiftdone[ "$seen_system" = true ] || { echo "missing trusted system prompt" >&2; exit 94; }-[ "$seen_output_schema" = true ] || { echo "missing trusted output schema" >&2; exit 97; }-[ "$seen_json_schema_arg" = false ] || { echo "Claude hidden structured-output mode was enabled" >&2; exit 98; }+[ "$seen_json_schema" = true ] || { echo "missing native output schema" >&2; exit 97; }[ "$seen_no_tools" = true ] || { echo "Claude built-in tools not disabled" >&2; exit 95; }[ "$seen_dont_ask" = true ] || { echo "unexpected permission mode" >&2; exit 96; }-printf '%s' '{"result":"{\"content\":\"healthy\",\"stop_reason\":\"end_turn\",\"tool_calls\":[]}","usage":{"input_tokens":12,"output_tokens":3}}'+printf '%s' '{"structured_output":{"content":"healthy","stop_reason":"end_turn","tool_calls":[]},"usage":{"input_tokens":12,"output_tokens":3}}'`)t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))t.Setenv("OPENAI_API_KEY", "must-not-leak")@@ -349,35 +347,30 @@ func TestDecodeSubscriptionAgentTurnRejectsUnknownStructuredFields(t *testing.T)}}-func TestDecodeClaudePlainCompletionRejectsToolCallArtifacts(t *testing.T) {+func TestClaudePostOutcomeCompletionRequiresPersistedLifecycleResult(t *testing.T) {req := ChatRequest{- Tools: []Tool{{Name: "pulse_query"}},Messages: []Message{{Role: "assistant", ToolCalls: []ToolCall{{ID: "finding-1", Name: "patrol_report_finding", Input: map[string]interface{}{}}}},{Role: "user", ToolResult: &ToolResult{ToolUseID: "finding-1", Content: `{"ok":true}`}},},}- raw := []byte(`{"result":"Patrol completed without another tool call.","usage":{"input_tokens":4,"output_tokens":7}}`)- turn, err := decodeClaudePlainCompletion(req, raw)- if err != nil {- t.Fatal(err)- }- if turn.Content == "" || turn.StopReason != "end_turn" || turn.InputTokens != 4 || turn.OutputTokens != 7 {- t.Fatalf("plain completion = %#v", turn)+ err := &subscriptionAgentCommandError{command: "claude", cause: errors.New("exit status 1"), terminalReason: "structured_output_retry_exhausted", inputTokens: 4, outputTokens: 7}+ response, ok := claudePostOutcomeCompletion(req, "sonnet", err)+ if !ok || response.StopReason != "end_turn" || response.InputTokens != 4 || response.OutputTokens != 7 || len(response.ToolCalls) != 0 {+ t.Fatalf("post-outcome completion = (%#v, %t)", response, ok)}- leaked := []byte(`{"result":"pulse_query({\"action\":\"list\"})"}`)- if _, err := decodeClaudePlainCompletion(req, leaked); err == nil || !strings.Contains(err.Error(), "leaked a tool call") {- t.Fatalf("plain tool-call leak error = %v", err)+ if _, ok := claudePostOutcomeCompletion(ChatRequest{}, "sonnet", err); ok {+ t.Fatal("structured retry before a persisted Patrol outcome was accepted")}- embedded := []byte(`{"result":"Done. {\"content\":\"\",\"stop_reason\":\"tool_use\",\"tool_calls\":[{\"name\":\"pulse_query\"}]}"}`)- if _, err := decodeClaudePlainCompletion(req, embedded); err == nil || !strings.Contains(err.Error(), "leaked a tool call") {- t.Fatalf("embedded tool-call leak error = %v", err)+ other := &subscriptionAgentCommandError{command: "claude", cause: errors.New("exit status 1"), terminalReason: "other"}+ if _, ok := claudePostOutcomeCompletion(req, "sonnet", other); ok {+ t.Fatal("unrelated Claude terminal error was accepted")}-- initial := ChatRequest{Tools: req.Tools}- if _, err := decodeClaudePlainCompletion(initial, raw); err == nil || !strings.Contains(err.Error(), "before a successful Patrol outcome") {- t.Fatalf("premature plain completion error = %v", err)+ failedResult := req+ failedResult.Messages[1].ToolResult.IsError = true+ if _, ok := claudePostOutcomeCompletion(failedResult, "sonnet", err); ok {+ t.Fatal("failed Patrol lifecycle result was accepted")}}