Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9313: fix CodeBuddy failure diagnostics (#10668)
Bohan Jiangc6ec8f208155
diff --git a/server/internal/daemon/poisoned.go b/server/internal/daemon/poisoned.goindex 14b9955312..ec152e44fb 100644--- a/server/internal/daemon/poisoned.go+++ b/server/internal/daemon/poisoned.go@@ -137,6 +137,7 @@ func classifyPoisonedOutput(output string) (string, bool) {// the conversation by ANY backend — see its doc comment for why the defect// has to be recognised by wording rather than by status code or provider.func classifyPoisonedError(errMsg string) (string, bool) {+ errMsg = taskfailure.WithoutCodebuddyProtocolSummary(errMsg)if errMsg == "" {return "", false}diff --git a/server/internal/daemon/poisoned_test.go b/server/internal/daemon/poisoned_test.goindex dafa51c5e4..729bdebfa9 100644--- a/server/internal/daemon/poisoned_test.go+++ b/server/internal/daemon/poisoned_test.go@@ -1,6 +1,7 @@package daemonimport (+ "fmt""strings""testing"@@ -9,6 +10,30 @@ import ("github.com/multica-ai/multica/server/pkg/taskfailure")+func TestClassifyPoisonedErrorIgnoresCodebuddyProtocolSummary(t *testing.T) {+ for _, count := range []int{400, 1400, 4000} {+ summary := fmt.Sprintf("\n[codebuddy protocol: exit_code=0 stdout_bytes=%d stderr_bytes=0 event_count=1 invalid_event_count=0 assistant_event_count=0 tool_use_count=0 saw_result=true result_is_error=true result_bytes=0 last_assistant_bytes=0 scanner_error=false]", count)+ for _, tc := range []struct {+ raw string+ want taskfailure.Reason+ }{+ {`HTTP 404 {"type":"invalid_request_error","message":"unknown model test-model","code":"model_not_found"}`, taskfailure.ReasonAgentModelNotFoundOrUnavailable},+ {`HTTP 401 {"type":"invalid_request_error","message":"invalid api key","code":"invalid_api_key"}`, taskfailure.ReasonAgentProviderAuthOrAccess},+ } {+ raw := tc.raw + summary+ if reason, poisoned := classifyPoisonedError(raw); poisoned || reason != "" {+ t.Errorf("count=%d: non-poisoning failure classified as %q", count, reason)+ }+ if got := taskfailure.Classify(raw); got != tc.want {+ t.Errorf("count=%d: provider reason=%s, want %s", count, got, tc.want)+ }+ }+ if reason, poisoned := classifyPoisonedError(`HTTP 400 {"type":"invalid_request_error","message":"Could not process image"}` + summary); !poisoned || reason != FailureReasonAPIInvalidRequest {+ t.Errorf("count=%d: lost actual poisoned request: %q/%v", count, reason, poisoned)+ }+ }+}+func TestClassifyPoisonedOutput(t *testing.T) {cases := []struct {name stringdiff --git a/server/internal/handler/codebuddy_resume_test.go b/server/internal/handler/codebuddy_resume_test.gonew file mode 100644index 0000000000..6638eaaeab--- /dev/null+++ b/server/internal/handler/codebuddy_resume_test.go@@ -0,0 +1,58 @@+package handler++import (+ "context"+ "testing"++ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestCodebuddyProtocolSummaryResumeQueries(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ const summary = "\n[codebuddy protocol: exit_code=0 stdout_bytes=1400 stderr_bytes=0 event_count=1 invalid_event_count=0 assistant_event_count=0 tool_use_count=0 saw_result=true result_is_error=true result_bytes=0 last_assistant_bytes=0 scanner_error=false]"+ ctx := context.Background()+ for _, tc := range []struct {+ name, reason, raw, wantSession string+ }{+ {"model", "agent_error.model_not_found_or_unavailable", `HTTP 404 {"type":"invalid_request_error","code":"model_not_found"}`, "current"},+ {"auth", "agent_error.provider_auth_or_access", `HTTP 401 {"type":"invalid_request_error","code":"invalid_api_key"}`, "current"},+ {"actual poisoned request", "agent_error.unknown", `HTTP 400 {"type":"invalid_request_error","message":"Could not process image"}`, "healthy"},+ } {+ for _, scope := range []string{"issue", "chat"} {+ t.Run(tc.name+"/"+scope, func(t *testing.T) {+ agentID, runtimeID, _ := createRuntimeGuardAgent(t, ctx)+ column := "issue_id"+ var scopeID string+ if scope == "issue" {+ scopeID = dbfx.Issue(t, "CodeBuddy diagnostic resume")+ } else {+ column = "chat_session_id"+ scopeID = dbfx.ChatSession(t, agentID)+ }+ dbfx.Task(t, agentID, testutil.Cols{+ column: scopeID, "runtime_id": runtimeID, "session_id": "healthy", "status": "completed",+ "completed_at": testutil.Raw("now() - interval '2 minutes'"),+ })+ dbfx.Task(t, agentID, testutil.Cols{+ column: scopeID, "runtime_id": runtimeID, "session_id": "current", "status": "failed",+ "error": tc.raw + summary, "failure_reason": tc.reason,+ "completed_at": testutil.Raw("now() - interval '1 minute'"),+ })+ if scope == "issue" {+ got, err := testHandler.Queries.GetLastTaskSession(ctx, db.GetLastTaskSessionParams{AgentID: parseUUID(agentID), IssueID: parseUUID(scopeID)})+ if err != nil || got.SessionID.String != tc.wantSession {+ t.Fatalf("issue session=%q, err=%v, want %q", got.SessionID.String, err, tc.wantSession)+ }+ } else {+ got, err := testHandler.Queries.GetLastChatTaskSession(ctx, db.GetLastChatTaskSessionParams{ChatSessionID: parseUUID(scopeID)})+ if err != nil || got.SessionID.String != tc.wantSession {+ t.Fatalf("chat session=%q, err=%v, want %q", got.SessionID.String, err, tc.wantSession)+ }+ }+ })+ }+ }+}diff --git a/server/internal/service/resume_unsafe_test.go b/server/internal/service/resume_unsafe_test.goindex e3c1d9d39c..0c51d7af41 100644--- a/server/internal/service/resume_unsafe_test.go+++ b/server/internal/service/resume_unsafe_test.go@@ -2,6 +2,25 @@ package serviceimport "testing"+func TestResumeUnsafeFailureIgnoresCodebuddyProtocolSummary(t *testing.T) {+ const summary = "\n[codebuddy protocol: exit_code=0 stdout_bytes=1400 stderr_bytes=0 event_count=1 invalid_event_count=0 assistant_event_count=0 tool_use_count=0 saw_result=true result_is_error=true result_bytes=0 last_assistant_bytes=0 scanner_error=false]"+ for _, tc := range []struct {+ name, reason, raw string+ want bool+ }{+ {"model", "agent_error.model_not_found_or_unavailable", `HTTP 404 {"type":"invalid_request_error","code":"model_not_found"}`, false},+ {"auth", "agent_error.provider_auth_or_access", `HTTP 401 {"type":"invalid_request_error","code":"invalid_api_key"}`, false},+ {"actual poisoned request", "agent_error.unknown", `HTTP 400 {"type":"invalid_request_error","message":"Could not process image"}`, true},+ {"already retired reason", "api_invalid_request", "no details", true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if got := ResumeUnsafeFailure(tc.reason, tc.raw+summary); got != tc.want {+ t.Errorf("ResumeUnsafeFailure = %v, want %v", got, tc.want)+ }+ })+ }+}+// TestResumeUnsafeFailureEmptyHistoryMessage covers the manual-retry half of// GH #6066. The claim handler resolves a rerun's session from the exact source// task via ResumeUnsafeFailure rather than GetLastTaskSession, so a gap herediff --git a/server/internal/service/task.go b/server/internal/service/task.goindex f7f28722d0..da69676401 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -5662,6 +5662,7 @@ func ResumeUnsafeFailure(failureReason, errorText string) bool {if resumeUnsafeFailureReason(failureReason) {return true}+ errorText = taskfailure.WithoutCodebuddyProtocolSummary(errorText)lower := strings.ToLower(errorText)if strings.Contains(lower, "400") && strings.Contains(lower, "invalid_request_error") {return truediff --git a/server/pkg/agent/codebuddy.go b/server/pkg/agent/codebuddy.goindex 9e0f155877..372caab1f8 100644--- a/server/pkg/agent/codebuddy.go+++ b/server/pkg/agent/codebuddy.go@@ -203,6 +203,7 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts ExecstartTime := time.Now()var lastAssistantText stringvar finalResultText string+ var resultErrorText stringsawResult := falseresultIsError := falsesawBackgroundTask := false@@ -225,7 +226,8 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Exec_ = stdout.Close()}()- scanner := newAgentStreamScanner(stdout)+ countedStdout := &byteCountingReader{Reader: stdout}+ scanner := newAgentStreamScanner(countedStdout)for scanner.Scan() {line := strings.TrimSpace(scanner.Text())@@ -271,6 +273,10 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts ExecsawResult = truefinalResultText = msg.ResultTextresultIsError = msg.IsError+ resultErrorText = ""+ if msg.IsError {+ resultErrorText = codebuddyResultError(msg)+ }sessionID = msg.SessionIDif resultUsage := codebuddyResultUsage(msg, opts.Model); len(resultUsage) > 0 {usage = resultUsage@@ -337,11 +343,12 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts ExecexitErr,sessionID,streamTerminalState{- lastAssistantText: lastAssistantText,- finalResultText: finalResultText,- sawResult: sawResult,- resultIsError: resultIsError,- scanErr: scanErr,+ lastAssistantText: lastAssistantText,+ finalResultText: finalResultText,+ sawResult: sawResult,+ resultIsError: resultIsError,+ scanErr: scanErr,+ terminalReasonError: resultErrorText,},completionGuardError,)@@ -360,7 +367,8 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Execif finalError != "" {finalError = withAgentStderr(finalError, "codebuddy", stderrTail)}- logStreamProtocolObservation(b.cfg.Logger, streamProtocolObservation{+ // Context shutdown closes stdout itself; exclude that read error.+ observation := streamProtocolObservation{provider: "codebuddy",cliVersion: b.cfg.CLIVersion,model: opts.Model,@@ -373,10 +381,14 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts ExecresultIsError: resultIsError,resultBytes: len(finalResultText),lastAssistantBytes: len(lastAssistantText),- scannerError: scanErr != nil,+ scannerError: scanErr != nil && runCtx.Err() == nil,unreadableAssistantCount: unreadableAssistantCount,anthropicBaseURLConfigured: strings.TrimSpace(b.cfg.Env["ANTHROPIC_BASE_URL"]) != "",- })+ }+ logStreamProtocolObservation(b.cfg.Logger, observation)+ if finalError != "" {+ finalError = codebuddyFailureDiagnostic(finalError, observation, countedStdout.bytes, stderrBuf.TotalBytes())+ }b.cfg.Logger.Info("codebuddy finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())@@ -626,6 +638,8 @@ type codebuddySDKMessage struct {// shipped @tencent-ai/codebuddy-code 2.150.0 protocol.ResultText string `json:"result,omitempty"`IsError bool `json:"is_error,omitempty"`+ Errors json.RawMessage `json:"errors,omitempty"`+ ErrorsInfo json.RawMessage `json:"errors_info,omitempty"`DurationMs float64 `json:"duration_ms,omitempty"`NumTurns int `json:"num_turns,omitempty"`Usage *codebuddyUsage `json:"usage,omitempty"`diff --git a/server/pkg/agent/codebuddy_failure.go b/server/pkg/agent/codebuddy_failure.gonew file mode 100644index 0000000000..4afa630945--- /dev/null+++ b/server/pkg/agent/codebuddy_failure.go@@ -0,0 +1,81 @@+package agent++import (+ "encoding/json"+ "fmt"+ "io"+ "strings"+)++// Optional diagnostic fields are decoded independently so a new error shape+// cannot make an otherwise valid terminal result disappear from the stream.+func codebuddyResultError(msg codebuddySDKMessage) string {+ var parts []string+ seen := make(map[string]bool)+ add := func(text string) {+ text = strings.TrimSpace(text)+ if text != "" && !seen[text] {+ parts = append(parts, text)+ seen[text] = true+ }+ }+ add(msg.ResultText)+ var errors []json.RawMessage+ if json.Unmarshal(msg.Errors, &errors) == nil {+ for _, raw := range errors {+ var text string+ if json.Unmarshal(raw, &text) == nil {+ add(text)+ }+ }+ }+ var infos []json.RawMessage+ if json.Unmarshal(msg.ErrorsInfo, &infos) == nil {+ for _, raw := range infos {+ var info struct {+ Status json.RawMessage `json:"status"`+ Details json.RawMessage `json:"details"`+ }+ if json.Unmarshal(raw, &info) != nil {+ continue+ }+ var status int+ // Only the HTTP status dimension is an HTTP witness. The separate+ // business/SDK code can also be numeric (including 401 or 429).+ if json.Unmarshal(info.Status, &status) == nil && status >= 400 && status <= 599 {+ add(fmt.Sprintf("HTTP %d", status))+ }+ var details string+ if json.Unmarshal(info.Details, &details) == nil {+ add(details)+ }+ }+ }+ return strings.Join(parts, "; ")+}++type byteCountingReader struct {+ io.Reader+ bytes int64+}++func (r *byteCountingReader) Read(p []byte) (int, error) {+ n, err := r.Reader.Read(p)+ r.bytes += int64(n)+ return n, err+}++func codebuddyFailureDiagnostic(errMsg string, obs streamProtocolObservation, stdoutBytes, stderrBytes int64) string {+ const maxDetailBytes = 8192+ const truncated = " [truncated]"+ detail := sanitizeAgentDiagnostic(errMsg)+ if len(detail) > maxDetailBytes {+ detail = truncateUTF8(detail, maxDetailBytes-len(truncated)) + truncated+ }+ // Keep this numeric/boolean line in sync with taskfailure's filter. Counts+ // are diagnostic evidence and must never act as provider HTTP status codes.+ return fmt.Sprintf("%s\n[codebuddy protocol: exit_code=%d stdout_bytes=%d stderr_bytes=%d event_count=%d invalid_event_count=%d assistant_event_count=%d tool_use_count=%d saw_result=%t result_is_error=%t result_bytes=%d last_assistant_bytes=%d scanner_error=%t]",+ detail, obs.exitCode, stdoutBytes, stderrBytes, obs.eventCount, obs.invalidEventCount,+ obs.assistantEventCount, obs.toolUseCount, obs.sawResult, obs.resultIsError,+ obs.resultBytes, obs.lastAssistantBytes, obs.scannerError)+}diff --git a/server/pkg/agent/codebuddy_failure_test.go b/server/pkg/agent/codebuddy_failure_test.gonew file mode 100644index 0000000000..889983265f--- /dev/null+++ b/server/pkg/agent/codebuddy_failure_test.go@@ -0,0 +1,220 @@+package agent++import (+ "context"+ "fmt"+ "io"+ "log/slog"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+ "time"+ "unicode/utf8"++ "github.com/multica-ai/multica/server/pkg/taskfailure"+)++func TestCodebuddyFailureDetails(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixtures are POSIX-only")+ }+ tests := []struct {+ name string+ frame string+ exitCode int+ wantReason taskfailure.Reason+ want []string+ }{+ {+ name: "errors array",+ frame: `{"type":"result","is_error":true,"errors":["unknown model review-model"]}`,+ wantReason: taskfailure.ReasonAgentModelNotFoundOrUnavailable,+ want: []string{"unknown model review-model", "saw_result=true", "result_is_error=true", "result_bytes=0"},+ },+ {+ name: "structured details with null entries",+ frame: `{"type":"result","is_error":true,"errors_info":[null,{"status":404,"details":"unknown model review-model","code":"MODEL_NOT_FOUND"}]}`,+ wantReason: taskfailure.ReasonAgentModelNotFoundOrUnavailable,+ want: []string{"unknown model review-model", "HTTP 404"},+ },+ {+ name: "all error sources",+ frame: `{"type":"result","is_error":true,"result":"request rejected","errors":["unknown model review-model"],"errors_info":[{"status":404,"details":"use an available model"}]}`,+ wantReason: taskfailure.ReasonAgentModelNotFoundOrUnavailable,+ want: []string{"request rejected", "unknown model review-model", "use an available model", "HTTP 404"},+ },+ {+ name: "HTTP auth without prose",+ frame: `{"type":"result","is_error":true,"errors_info":[{"status":401,"code":10006}]}`,+ wantReason: taskfailure.ReasonAgentProviderAuthOrAccess,+ want: []string{"HTTP 401"},+ },+ {+ name: "HTTP quota",+ frame: `{"type":"result","is_error":true,"errors_info":[{"status":402,"details":"balance is too low"}]}`,+ wantReason: taskfailure.ReasonAgentProviderQuotaLimit,+ want: []string{"HTTP 402", "balance is too low"},+ },+ {+ name: "HTTP capacity",+ frame: `{"type":"result","is_error":true,"errors_info":[{"status":429}]}`,+ wantReason: taskfailure.ReasonAgentProviderCapacityOrRateLimit,+ want: []string{"HTTP 429"},+ },+ {+ name: "HTTP server failure",+ frame: `{"type":"result","is_error":true,"errors_info":[{"status":503}]}`,+ wantReason: taskfailure.ReasonAgentProviderServerError,+ want: []string{"HTTP 503"},+ },+ {+ name: "null diagnostics",+ frame: `{"type":"result","is_error":true,"errors":null,"errors_info":[null,{}]}`,+ wantReason: taskfailure.ReasonAgentUnknown,+ want: []string{"returned an error result without details", "event_count=1", "stderr_bytes=0"},+ },+ {+ name: "business code is not HTTP status",+ frame: `{"type":"result","is_error":true,"errors_info":[{"code":401}]}`,+ wantReason: taskfailure.ReasonAgentUnknown,+ want: []string{"returned an error result without details"},+ },+ {+ name: "explicit error keeps actual exit code",+ frame: `{"type":"result","is_error":true}`,+ exitCode: 7,+ wantReason: taskfailure.ReasonAgentUnknown,+ want: []string{"returned an error result without details", "exit_code=7"},+ },+ {+ name: "no terminal event",+ frame: `{"type":"system","session_id":"review-session"}`,+ wantReason: taskfailure.ReasonAgentUnknown,+ want: []string{"stream ended without terminal result", "saw_result=false", "event_count=1"},+ },+ {+ name: "empty stdout",+ wantReason: taskfailure.ReasonAgentUnknown,+ want: []string{"stdout_bytes=0", "event_count=0", "invalid_event_count=0", "saw_result=false"},+ },+ {+ name: "malformed stdout",+ frame: "not-json",+ wantReason: taskfailure.ReasonAgentUnknown,+ want: []string{"stdout_bytes=9", "event_count=0", "invalid_event_count=1"},+ },+ {+ name: "unparseable optional error fields preserve terminal event",+ frame: `{"type":"result","is_error":true,"errors":"unexpected","errors_info":[{"status":"unexpected","details":"unknown model review-model"}]}`,+ wantReason: taskfailure.ReasonAgentModelNotFoundOrUnavailable,+ want: []string{"saw_result=true", "unknown model review-model"},+ },+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ t.Parallel()+ script := ""+ if tt.frame != "" {+ script = fmt.Sprintf("printf '%%s\\n' '%s'\n", tt.frame)+ }+ script += fmt.Sprintf("exit %d\n", tt.exitCode)+ result := runCodebuddyFailureFixture(t, script)+ if result.Status != "failed" || result.Output != "" {+ t.Fatalf("outcome = %s/%q, error=%q", result.Status, result.Output, result.Error)+ }+ for _, want := range tt.want {+ if !strings.Contains(result.Error, want) {+ t.Errorf("error %q does not contain %q", result.Error, want)+ }+ }+ if got := taskfailure.Classify(result.Error); got != tt.wantReason {+ t.Errorf("Classify = %s, want %s; error=%q", got, tt.wantReason, result.Error)+ }+ })+ }+}++func TestCodebuddyFailureDiagnosticsAreBoundedAndRedacted(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }+ result := runCodebuddyFailureFixture(t, `printf '%s\n' '{"type":"result","is_error":true,"errors":["unknown model review-model; api_key=private-key"]}'+printf '%s\n' 'Authorization: Bearer private-token' >&2+`)+ for _, secret := range []string{"private-key", "private-token"} {+ if strings.Contains(result.Error, secret) {+ t.Errorf("persisted error contains %q: %s", secret, result.Error)+ }+ }+ if !strings.Contains(result.Error, "[REDACTED]") || !strings.Contains(result.Error, "stderr_bytes=36") {+ t.Errorf("missing redaction or original stderr byte count: %s", result.Error)+ }+ large := runCodebuddyFailureFixture(t, "printf '%s\\n' '{\"type\":\"result\",\"is_error\":true,\"errors\":[\""+strings.Repeat("界", 10000)+"\"]}'\n")+ if !utf8.ValidString(large.Error) || len(large.Error) > 9000 || !strings.Contains(large.Error, "[truncated]") || !strings.Contains(large.Error, "saw_result=true") {+ t.Errorf("invalid or unbounded diagnostic: bytes=%d, valid_utf8=%v", len(large.Error), utf8.ValidString(large.Error))+ }+}++func TestCodebuddySuccessIgnoresErrorMetadata(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }+ result := runCodebuddyFailureFixture(t, `printf '%s\n' '{"type":"result","is_error":false,"result":"answer","errors":["stale error"],"errors_info":[{"status":401}]}'`+"\n")+ if result.Status != "completed" || result.Output != "answer" || result.Error != "" {+ t.Fatalf("successful result changed: %+v", result)+ }+}++func TestCodebuddyFailureDiagnosticsContextEnd(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixtures are POSIX-only")+ }+ for _, outcome := range []string{"aborted", "timeout"} {+ t.Run(outcome, func(t *testing.T) {+ t.Parallel()+ fakePath := filepath.Join(t.TempDir(), "codebuddy")+ writeTestExecutable(t, fakePath, []byte("#!/bin/sh\nIFS= read -r _\n"+`printf '%s\n' '{"type":"system","session_id":"context-end"}'`+"\nsleep 60\n"))+ b := &codebuddyBackend{cfg: Config{ExecutablePath: fakePath, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}}+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ opts := ExecOptions{}+ if outcome == "timeout" {+ opts.Timeout = 300 * time.Millisecond+ }+ session, err := b.Execute(ctx, "fixture", opts)+ if err != nil {+ t.Fatal(err)+ }+ for msg := range session.Messages {+ if outcome == "aborted" && msg.Type == MessageStatus {+ cancel()+ }+ }+ result := <-session.Result+ if result.Status != outcome || !strings.Contains(result.Error, "scanner_error=false") {+ t.Fatalf("context shutdown reported as a scanner error: %+v", result)+ }+ })+ }+}++func runCodebuddyFailureFixture(t *testing.T, body string) Result {+ t.Helper()+ fakePath := filepath.Join(t.TempDir(), "codebuddy")+ writeTestExecutable(t, fakePath, []byte("#!/bin/sh\nIFS= read -r _\n"+body))+ b := &codebuddyBackend{cfg: Config{ExecutablePath: fakePath, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}}+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ t.Cleanup(cancel)+ session, err := b.Execute(ctx, "fixture", ExecOptions{Timeout: 10 * time.Second})+ if err != nil {+ t.Fatal(err)+ }+ for range session.Messages {+ }+ result, ok := <-session.Result+ if !ok {+ t.Fatal("result channel closed without a value")+ }+ return result+}diff --git a/server/pkg/agent/stream_json_final_output_test.go b/server/pkg/agent/stream_json_final_output_test.goindex 3a5580b24f..d84f55eead 100644--- a/server/pkg/agent/stream_json_final_output_test.go+++ b/server/pkg/agent/stream_json_final_output_test.go@@ -174,6 +174,7 @@ printf '%s\n' '{"type":"user","message":{"role":"user","content":[{"type":"tool_wantStatus stringwantOutput stringwantError string+ wantScanError boolforbiddenOutput []string}{{@@ -273,9 +274,10 @@ printf '%s\n' '{"type":"user","message":{"role":"user","content":[{"type":"tool_`dd if=/dev/zero bs=1048576 count=%d 2>/dev/null | tr '\000' x; printf '\n'`,agentStreamMaxLineBytes/(1024*1024)+1,) + "\n",- wantStatus: "failed",- wantOutput: "",- wantError: "stdout read error",+ wantStatus: "failed",+ wantOutput: "",+ wantError: "stdout read error",+ wantScanError: true,},}@@ -324,6 +326,9 @@ printf '%s\n' '{"type":"user","message":{"role":"user","content":[{"type":"tool_if tt.wantError != "" && !strings.Contains(result.Error, tt.wantError) {t.Fatalf("error = %q, want substring %q", result.Error, tt.wantError)}+ if provider == "codebuddy" && result.Status != "completed" && !strings.Contains(result.Error, fmt.Sprintf("scanner_error=%t", tt.wantScanError)) {+ t.Fatalf("incorrect scanner diagnostic: %q", result.Error)+ }for _, forbidden := range tt.forbiddenOutput {if strings.Contains(result.Output, forbidden) {t.Fatalf("output leaked %q: %q", forbidden, result.Output)diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 136356c16a..664e3fdd58 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -4343,7 +4343,10 @@ WITH retired_sessions AS ()), latest_per_session AS (SELECT DISTINCT ON (t.session_id)- t.session_id, t.work_dir, t.runtime_id, t.status, t.failure_reason, t.error,+ t.session_id, t.work_dir, t.runtime_id, t.status, t.failure_reason,+ -- Counts in the adapter summary are not upstream HTTP statuses.+ -- Keep this pattern aligned with taskfailure.WithoutCodebuddyProtocolSummary.+ regexp_replace(COALESCE(t.error, ''), '^\[codebuddy protocol: exit_code=-?[0-9]+ stdout_bytes=[0-9]+ stderr_bytes=[0-9]+ event_count=[0-9]+ invalid_event_count=[0-9]+ assistant_event_count=[0-9]+ tool_use_count=[0-9]+ saw_result=(true|false) result_is_error=(true|false) result_bytes=[0-9]+ last_assistant_bytes=[0-9]+ scanner_error=(true|false)\]$', '', 'gn') AS error,t.started_at, t.issue_snapshot,COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at) AS terminal_atFROM agent_task_queue tdiff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex 9ea6a1be4c..4b97c167eb 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -978,7 +978,10 @@ WITH retired_sessions AS ()), latest_per_session AS (SELECT DISTINCT ON (t.session_id)- t.session_id, t.work_dir, t.runtime_id, t.status, t.failure_reason, t.error, t.completed_at+ t.session_id, t.work_dir, t.runtime_id, t.status, t.failure_reason,+ -- Match the issue resume query and taskfailure.WithoutCodebuddyProtocolSummary.+ regexp_replace(COALESCE(t.error, ''), '^\[codebuddy protocol: exit_code=-?[0-9]+ stdout_bytes=[0-9]+ stderr_bytes=[0-9]+ event_count=[0-9]+ invalid_event_count=[0-9]+ assistant_event_count=[0-9]+ tool_use_count=[0-9]+ saw_result=(true|false) result_is_error=(true|false) result_bytes=[0-9]+ last_assistant_bytes=[0-9]+ scanner_error=(true|false)\]$', '', 'gn') AS error,+ t.completed_atFROM agent_task_queue tWHERE t.chat_session_id = $1AND (diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex a2c3cc0ffa..d69f45b5cc 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -1081,7 +1081,10 @@ WITH retired_sessions AS ()), latest_per_session AS (SELECT DISTINCT ON (t.session_id)- t.session_id, t.work_dir, t.runtime_id, t.status, t.failure_reason, t.error,+ t.session_id, t.work_dir, t.runtime_id, t.status, t.failure_reason,+ -- Counts in the adapter summary are not upstream HTTP statuses.+ -- Keep this pattern aligned with taskfailure.WithoutCodebuddyProtocolSummary.+ regexp_replace(COALESCE(t.error, ''), '^\[codebuddy protocol: exit_code=-?[0-9]+ stdout_bytes=[0-9]+ stderr_bytes=[0-9]+ event_count=[0-9]+ invalid_event_count=[0-9]+ assistant_event_count=[0-9]+ tool_use_count=[0-9]+ saw_result=(true|false) result_is_error=(true|false) result_bytes=[0-9]+ last_assistant_bytes=[0-9]+ scanner_error=(true|false)\]$', '', 'gn') AS error,t.started_at, t.issue_snapshot,COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at) AS terminal_atFROM agent_task_queue tdiff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex cbd6f28c3c..a2967e485e 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -1267,7 +1267,10 @@ WITH retired_sessions AS ()), latest_per_session AS (SELECT DISTINCT ON (t.session_id)- t.session_id, t.work_dir, t.runtime_id, t.status, t.failure_reason, t.error, t.completed_at+ t.session_id, t.work_dir, t.runtime_id, t.status, t.failure_reason,+ -- Match the issue resume query and taskfailure.WithoutCodebuddyProtocolSummary.+ regexp_replace(COALESCE(t.error, ''), '^\[codebuddy protocol: exit_code=-?[0-9]+ stdout_bytes=[0-9]+ stderr_bytes=[0-9]+ event_count=[0-9]+ invalid_event_count=[0-9]+ assistant_event_count=[0-9]+ tool_use_count=[0-9]+ saw_result=(true|false) result_is_error=(true|false) result_bytes=[0-9]+ last_assistant_bytes=[0-9]+ scanner_error=(true|false)\]$', '', 'gn') AS error,+ t.completed_atFROM agent_task_queue tWHERE t.chat_session_id = sqlc.arg('chat_session_id')AND (diff --git a/server/pkg/taskfailure/classify.go b/server/pkg/taskfailure/classify.goindex 286fae4b9b..c8303370fa 100644--- a/server/pkg/taskfailure/classify.go+++ b/server/pkg/taskfailure/classify.go@@ -86,7 +86,7 @@ func isUsageLimit403(lower string) bool {// failure_reason today and lets per-backend structured upgrades land// independently.func Classify(rawError string) Reason {- trimmed := strings.TrimSpace(rawError)+ trimmed := strings.TrimSpace(WithoutCodebuddyProtocolSummary(rawError))if trimmed == "" {// SQL maps NULL/empty to a separate bucket ("empty_error"),// but that bucket is not part of the canonical taxonomy. In-flight@@ -666,6 +666,7 @@ var legacyUsageLimit403Reasons = map[string]bool{// can be deleted once no daemon old enough to produce its wire shape is still// reporting.func NormalizeDaemonReason(reason, rawError string) Reason {+ rawError = WithoutCodebuddyProtocolSummary(rawError)if legacyConcurrentRequestLimitReasons[reason] &&strings.Contains(strings.ToLower(rawError), concurrentRequestLimitWitness) {return ReasonAgentProviderCapacityOrRateLimitdiff --git a/server/pkg/taskfailure/codebuddy_diagnostics.go b/server/pkg/taskfailure/codebuddy_diagnostics.gonew file mode 100644index 0000000000..6c4ae4ddc7--- /dev/null+++ b/server/pkg/taskfailure/codebuddy_diagnostics.go@@ -0,0 +1,14 @@+package taskfailure++import "regexp"++// Match only the adapter's complete numeric/boolean summary line; provider+// error text and HTTP statuses remain classification evidence. Keep the format+// in sync with agent.codebuddyFailureDiagnostic.+var codebuddyProtocolSummaryRe = regexp.MustCompile(`(?m)^\[codebuddy protocol: exit_code=-?[0-9]+ stdout_bytes=[0-9]+ stderr_bytes=[0-9]+ event_count=[0-9]+ invalid_event_count=[0-9]+ assistant_event_count=[0-9]+ tool_use_count=[0-9]+ saw_result=(true|false) result_is_error=(true|false) result_bytes=[0-9]+ last_assistant_bytes=[0-9]+ scanner_error=(true|false)\]$`)++// WithoutCodebuddyProtocolSummary removes adapter metadata before error text+// is used to classify a failure or decide whether its session is resumable.+func WithoutCodebuddyProtocolSummary(raw string) string {+ return codebuddyProtocolSummaryRe.ReplaceAllString(raw, "")+}diff --git a/server/pkg/taskfailure/codebuddy_diagnostics_test.go b/server/pkg/taskfailure/codebuddy_diagnostics_test.gonew file mode 100644index 0000000000..dd767e1466--- /dev/null+++ b/server/pkg/taskfailure/codebuddy_diagnostics_test.go@@ -0,0 +1,32 @@+package taskfailure++import (+ "fmt"+ "testing"+)++func TestCodebuddyProtocolSummaryDoesNotClassifyCounts(t *testing.T) {+ for _, count := range []int{401, 402, 403, 429, 500, 529} {+ summary := fmt.Sprintf("\n[codebuddy protocol: exit_code=0 stdout_bytes=%d stderr_bytes=%d event_count=%d invalid_event_count=0 assistant_event_count=0 tool_use_count=0 saw_result=true result_is_error=true result_bytes=0 last_assistant_bytes=0 scanner_error=false]", count, count, count)+ for _, tc := range []struct {+ raw string+ want Reason+ }{+ {"codebuddy returned an error result without details", ReasonAgentUnknown},+ {"unknown model test-model", ReasonAgentModelNotFoundOrUnavailable},+ {"HTTP 401: Unauthorized", ReasonAgentProviderAuthOrAccess},+ {"codebuddy exited with error: exit status 7", ReasonAgentProcessFailure},+ } {+ if got := Classify(tc.raw + summary); got != tc.want {+ t.Errorf("count=%d Classify(%q) = %s, want %s", count, tc.raw, got, tc.want)+ }+ }+ // A byte count is not evidence of the special HTTP-403 quota shape.+ if got := NormalizeDaemonReason(ReasonAgentUnknown.String(), "codebuddy usage limit"+summary); got != ReasonAgentUnknown {+ t.Errorf("count=%d normalized from summary alone: %s", count, got)+ }+ if got := NormalizeDaemonReason(ReasonAgentUnknown.String(), "HTTP 403: usage limit"+summary); got != ReasonAgentProviderQuotaLimit {+ t.Errorf("count=%d lost real quota evidence: %s", count, got)+ }+ }+}