Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(agent): fail a run whose provider session ran out of context (MUL-5739) (#6422)

Bohan Jiangc1bd4f995c05
diff --git a/server/internal/daemon/context_exhausted_test.go b/server/internal/daemon/context_exhausted_test.go
new file mode 100644
index 0000000000..7f143d7858
--- /dev/null
+++ b/server/internal/daemon/context_exhausted_test.go
@@ -0,0 +1,76 @@
+package daemon
+
+import (
+ "testing"
+
+ "github.com/multica-ai/multica/server/pkg/agent"
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
+)
+
+// TestContextExhaustionNeverReplaysTheTask pins the boundary between the two
+// questions GH #6402's fix has to keep apart.
+//
+// "Did this run produce an answer?" is decided by the output alone —
+// classifyPoisonedOutput takes no tool count, and it must not grow one: a
+// context window fills up mid-task far more often than on the first turn, so a
+// tools == 0 gate would miss the common case and leave exactly the silent
+// stall the issue reports.
+//
+// "May we re-run it?" is where the tool count belongs, and the answer here is
+// always no. A saturated session is not a rejected resume, so there is nothing
+// a fresh-session retry of THIS task would cure that letting the NEXT task
+// start clean does not — while replaying a run that already used tools
+// duplicates its side effects.
+func TestContextExhaustionNeverReplaysTheTask(t *testing.T) {
+ failed := agent.Result{
+ Status: "failed",
+ SessionID: "sess-full",
+ Error: "claude ended the turn with terminal_reason=" + taskfailure.TerminalReasonPromptTooLong +
+ ": the session's context window is exhausted and compaction could not recover it (Prompt is too long)",
+ }
+
+ for _, tools := range []int32{0, 1, 17} {
+ if shouldRetryWithFreshSession(failed, "sess-full", tools, "claude") {
+ t.Errorf("tools=%d: a full context window must not trigger an in-task replay", tools)
+ }
+ }
+}
+
+// TestContextExhaustionClassifiesRegardlessOfToolUse is the other half: the
+// reclassification itself is reachable for a run that got real work done before
+// the window filled, because it is decided by the output and nothing else.
+func TestContextExhaustionClassifiesRegardlessOfToolUse(t *testing.T) {
+ // The daemon's completed branch calls this with the run's output and no
+ // other state; a mid-task overflow reaches it identically to a first-turn
+ // one.
+ reason, ok := classifyPoisonedOutput(
+ "Prompt is too long · this conversation is a single exchange and cannot be compacted — " +
+ "the request size comes mostly from system prompt, tool definitions, or attachments.")
+ if !ok {
+ t.Fatal("expected the context-exhaustion notice to be classified as poisoned output")
+ }
+ if reason != string(taskfailure.ReasonAgentContextOverflow) {
+ t.Fatalf("reason = %q, want %q", reason, taskfailure.ReasonAgentContextOverflow)
+ }
+ // The reason must be one the platform refuses to auto-retry: the run may
+ // have executed tools, and re-running it has no idempotency key.
+ if retryableFromDaemonPerspective(reason) {
+ t.Fatalf("%q must not be auto-retryable", reason)
+ }
+}
+
+// retryableFromDaemonPerspective mirrors the server's retryableReasons
+// allowlist for the reasons the daemon can emit. Kept local so this package's
+// test does not import internal/service, and deliberately exhaustive: if a
+// future change adds context_overflow to the server allowlist, this test still
+// documents why it should not be there.
+func retryableFromDaemonPerspective(reason string) bool {
+ switch reason {
+ case "runtime_offline", "runtime_recovery", "timeout", "codex_semantic_inactivity",
+ string(taskfailure.ReasonAgentProviderNetwork),
+ string(taskfailure.ReasonSkillBundleUnavailable):
+ return true
+ default:
+ return false
+ }
+}
diff --git a/server/internal/daemon/poisoned.go b/server/internal/daemon/poisoned.go
index 0dd0b36492..a28d6e905c 100644
--- a/server/internal/daemon/poisoned.go
+++ b/server/internal/daemon/poisoned.go
@@ -15,7 +15,8 @@ import (
//
// Two flavors:
// - Output-side: agent "completed" with output that is actually a known
-// fallback marker (gave up mid-thought, emitted a meta message). Detected
+// fallback marker (gave up mid-thought, emitted a meta message) or the
+// provider's context-window-exhausted notice (GH #6402). Detected
// via classifyPoisonedOutput.
// - Error-side: the LLM API itself rejected the request with a 400
// invalid_request_error (oversized payload, malformed image, etc.).
@@ -70,6 +71,22 @@ var poisonedMarkers = []struct {
// turn, so anything beyond ~one paragraph is treated as a real result
// even if it contains a marker substring.
func classifyPoisonedOutput(output string) (string, bool) {
+ // GH #6402: the provider's "this session's context window is full" notice,
+ // reported as the run's successful answer. Same poisoning shape as the
+ // markers below — resuming reproduces it forever, since a session already
+ // over the limit cannot compact its way back under — but recognised by the
+ // shared classifier so the server's /complete boundary applies the identical
+ // rule to daemons too old to carry this check.
+ //
+ // Note what is NOT a condition here: how many tools the run executed. A
+ // context window fills up mid-task far more often than on the first turn, so
+ // gating on tools == 0 would miss the common case. The tool count governs
+ // only whether a run may be REPLAYED, and nothing here replays anything —
+ // agent_error.context_overflow is absent from retryableReasons, so the task
+ // fails once, its session is retired, and the next trigger starts fresh.
+ if taskfailure.ContextExhaustedCompletion(output) {
+ return string(taskfailure.ReasonAgentContextOverflow), true
+ }
trimmed := strings.TrimSpace(output)
if trimmed == "" || len(trimmed) > poisonedOutputMaxLen {
return "", false
diff --git a/server/internal/daemon/poisoned_test.go b/server/internal/daemon/poisoned_test.go
index 1618217e0a..321b170c45 100644
--- a/server/internal/daemon/poisoned_test.go
+++ b/server/internal/daemon/poisoned_test.go
@@ -5,6 +5,7 @@ import (
"testing"
"github.com/multica-ai/multica/server/pkg/agent"
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
)
func TestClassifyPoisonedOutput(t *testing.T) {
@@ -72,6 +73,37 @@ on long outputs.`,
output: strings.Repeat("All checks passed and the bug is fixed. ", 10) + "i reached the iteration limit while debugging earlier.",
wantOK: false,
},
+ {
+ // GH #6402: the provider's context-exhaustion notice arriving as
+ // the run's successful answer. Same poisoning shape as the markers
+ // above — a session already over the limit cannot compact its way
+ // back under, so every resume reproduces it — and the reason has to
+ // be the one the resume blacklist covers.
+ name: "context exhaustion with the provider's full wording",
+ output: "Prompt is too long · the request is ~274931 tokens (limit 200000) but this conversation is only ~1597 tokens — the rest is system prompt, tool definitions, and attachment content. A single-exchange conversation cannot be compacted; reduce attached files/tools or start with less context.",
+ wantOK: true,
+ wantReason: string(taskfailure.ReasonAgentContextOverflow),
+ },
+ {
+ name: "compaction exhausted",
+ output: "Compaction failed · conversation could not be reduced below the context limit",
+ wantOK: true,
+ wantReason: string(taskfailure.ReasonAgentContextOverflow),
+ },
+ {
+ name: "an agent discussing /compact is a real answer",
+ output: "The session is getting long; run /compact before the next batch.",
+ wantOK: false,
+ },
+ {
+ // The CLI's bare sentence is not matched on the success path: an
+ // agent asked about prompt length can answer exactly this, and the
+ // real provider frame always carries is_error, so it reaches the
+ // failure path where Classify already handles it.
+ name: "bare provider sentence is left to the failure path",
+ output: "Prompt is too long",
+ wantOK: false,
+ },
}
for _, tc := range cases {
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index f202bfa46e..9e5c8874d6 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -30,6 +30,7 @@ import (
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
"github.com/multica-ai/multica/server/pkg/redact"
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
)
// ---------------------------------------------------------------------------
@@ -2982,6 +2983,33 @@ func (h *Handler) CompleteTask(w http.ResponseWriter, r *http.Request) {
return
}
+ // GH #6402: a daemon whose backend does not (yet) read the provider's
+ // structured terminal reason reports a context-exhausted run as a clean
+ // success, with the CLI's "your context window is full" notice as the
+ // answer. Re-route it to the failure path here so the fix does not have to
+ // wait for every installed daemon to update: an un-upgraded host would
+ // otherwise keep publishing that notice as the agent's reply AND keep the
+ // dead session pinned as the resume pointer, which is a permanently stuck
+ // (agent, issue) pair rather than a mislabelled row. Same argument, and the
+ // same shared classifier, as taskfailure.NormalizeDaemonReason on the fail
+ // boundary (MUL-5370). A current daemon classifies this before it ever calls
+ // /complete, so this branch is dead weight for it — by design.
+ if taskfailure.ContextExhaustedCompletion(req.Output) {
+ slog.Warn("complete task: output is a provider context-exhaustion notice, recording as failed",
+ "task_id", taskID,
+ "failure_reason", taskfailure.ReasonAgentContextOverflow,
+ )
+ h.failTask(w, r, taskID, workspaceID, TaskFailRequest{
+ Error: req.Output,
+ FailureReason: string(taskfailure.ReasonAgentContextOverflow),
+ SessionID: req.SessionID,
+ WorkDir: req.WorkDir,
+ SessionRolloutMissing: req.SessionRolloutMissing,
+ RetiredSessionID: req.RetiredSessionID,
+ })
+ return
+ }
+
result, _ := json.Marshal(req)
// MUL-5305: SessionRolloutMissing is applied inside CompleteTask's terminal
// transaction (force session_id NULL + flag the row), so an auto-retry the
@@ -3642,6 +3670,15 @@ func (h *Handler) FailTask(w http.ResponseWriter, r *http.Request) {
return
}
+ h.failTask(w, r, taskID, workspaceID, req)
+}
+
+// failTask records a terminal failure and writes the response. Shared by the
+// /fail endpoint and by CompleteTask's context-exhaustion normalization so a
+// run re-classified at the /complete boundary lands through exactly the same
+// transaction, token revocation and runtime wake-up as one the daemon reported
+// as failed itself.
+func (h *Handler) failTask(w http.ResponseWriter, r *http.Request, taskID, workspaceID string, req TaskFailRequest) {
// MUL-5305: SessionRolloutMissing is applied inside FailTask's terminal
// transaction — forcing session_id NULL (overriding the COALESCE that would
// keep a stale mid-flight pin) and flagging the row in the same commit that
diff --git a/server/internal/handler/daemon_context_exhausted_test.go b/server/internal/handler/daemon_context_exhausted_test.go
new file mode 100644
index 0000000000..c583375105
--- /dev/null
+++ b/server/internal/handler/daemon_context_exhausted_test.go
@@ -0,0 +1,227 @@
+package handler
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
+)
+
+// TestCompleteTask_ContextExhaustionFromOlderDaemonIsRecordedAsFailed is the
+// mixed-version regression for GH #6402.
+//
+// A daemon whose backend does not read the provider's structured terminal
+// reason reports a context-exhausted run through /complete, with the CLI's
+// "your context window is full" notice as the answer. Installed daemons upgrade
+// on their own cadence, so without a server-side rule an un-upgraded host keeps
+// publishing that notice as the agent's reply AND keeps the dead session as the
+// resume pointer — every later trigger on the issue resumes it and reproduces
+// the same non-answer. That is a permanently stuck (agent, issue) pair, not a
+// mislabelled row, which is why the normalization lives at the boundary rather
+// than only in the daemon.
+//
+// Asserts the whole chain: the task lands failed with the reason the resume
+// blacklist covers, and the saturated session stops being handed to the next
+// task.
+func TestCompleteTask_ContextExhaustionFromOlderDaemonIsRecordedAsFailed(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+
+ var agentID, runtimeID string
+ if err := testPool.QueryRow(ctx, `
+ SELECT a.id, a.runtime_id FROM agent a WHERE a.workspace_id = $1 LIMIT 1
+ `, testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {
+ t.Fatalf("setup: get agent: %v", err)
+ }
+
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)
+ VALUES ($1, 'gh-6402 context exhaustion fixture', 'in_progress', 'none', $2, 'member', 6402, 0)
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("setup: create issue: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at)
+ VALUES ($1, $2, $3, 'running', 0, now())
+ RETURNING id
+ `, agentID, runtimeID, issueID).Scan(&taskID); err != nil {
+ t.Fatalf("setup: create task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+
+ // Exactly what an older daemon posts: a successful completion whose output
+ // is the provider's notice, carrying the saturated session id.
+ w := httptest.NewRecorder()
+ req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",
+ map[string]any{
+ "output": "Prompt is too long · the request is ~274931 tokens (limit 200000) but this conversation is only ~1597 tokens — " +
+ "the rest is system prompt, tool definitions, and attachment content. A single-exchange conversation cannot be " +
+ "compacted; reduce attached files/tools or start with less context.",
+ "session_id": "sess-saturated-6402",
+ "work_dir": "/tmp/gh6402",
+ },
+ testWorkspaceID, "legit-daemon")
+ rctx := chi.NewRouteContext()
+ rctx.URLParams.Add("taskId", taskID)
+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
+
+ testHandler.CompleteTask(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("CompleteTask: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var status, failureReason string
+ if err := testPool.QueryRow(ctx, `
+ SELECT status, COALESCE(failure_reason, '') FROM agent_task_queue WHERE id = $1
+ `, taskID).Scan(&status, &failureReason); err != nil {
+ t.Fatalf("read task: %v", err)
+ }
+ if status != "failed" {
+ t.Fatalf("task status = %q, want failed — a context-exhausted run produced no work", status)
+ }
+ if failureReason != string(taskfailure.ReasonAgentContextOverflow) {
+ t.Fatalf("failure_reason = %q, want %q", failureReason, taskfailure.ReasonAgentContextOverflow)
+ }
+
+ // The payoff: the next task on this (agent, issue) must not be handed the
+ // session that just proved it cannot answer. This is the automated form of
+ // the reporter's manual workaround — archiving the transcript on disk.
+ got, err := testHandler.Queries.GetLastTaskSession(ctx, db.GetLastTaskSessionParams{
+ AgentID: parseUUID(agentID),
+ IssueID: parseUUID(issueID),
+ })
+ if err == nil && got.SessionID.Valid && got.SessionID.String == "sess-saturated-6402" {
+ t.Fatal("the saturated session is still offered as the resume pointer")
+ }
+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("GetLastTaskSession: %v", err)
+ }
+
+ // And nothing was published as the agent's answer: the run failed, so the
+ // completion path's fallback comment never ran.
+ var agentComments int
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*) FROM comment
+ WHERE issue_id = $1 AND author_type = 'agent' AND author_id = $2 AND type = 'comment'
+ `, issueID, agentID).Scan(&agentComments); err != nil {
+ t.Fatalf("count agent comments: %v", err)
+ }
+ if agentComments != 0 {
+ t.Fatalf("expected the provider notice NOT to be posted as an answer, got %d agent comment(s)", agentComments)
+ }
+}
+
+// TestCompleteTask_RealAnswerStillCompletes is the companion guard: outputs a
+// real agent can legitimately produce go through the completion path untouched.
+//
+// The second case is the one that shaped the classifier. "Prompt is too long"
+// IS a wording the CLI emits, but it is also a complete, ordinary English
+// answer to "is my prompt too long?" — so the success-path predicate must not
+// claim it. Matching it would fail a task that succeeded and retire a healthy
+// session, which is strictly worse than the miss: the real provider frame
+// carries is_error, so that shape reaches the server through /fail, where
+// Classify routes it to context_overflow anyway.
+func TestCompleteTask_RealAnswerStillCompletes(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+
+ var agentID, runtimeID string
+ if err := testPool.QueryRow(ctx, `
+ SELECT a.id, a.runtime_id FROM agent a WHERE a.workspace_id = $1 LIMIT 1
+ `, testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {
+ t.Fatalf("setup: get agent: %v", err)
+ }
+
+ tests := []struct {
+ name string
+ number int32
+ output string
+ }{
+ {
+ name: "an answer that mentions compacting",
+ number: 6403,
+ output: "Ran /compact first because the session was getting long, then fixed the redirect and pushed.",
+ },
+ {
+ name: "an answer that IS the provider's bare sentence",
+ number: 6404,
+ output: "Prompt is too long",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)
+ VALUES ($1, 'gh-6402 control fixture', 'in_progress', 'none', $2, 'member', $3, 0)
+ RETURNING id
+ `, testWorkspaceID, testUserID, tc.number).Scan(&issueID); err != nil {
+ t.Fatalf("setup: create issue: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at)
+ VALUES ($1, $2, $3, 'running', 0, now())
+ RETURNING id
+ `, agentID, runtimeID, issueID).Scan(&taskID); err != nil {
+ t.Fatalf("setup: create task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+
+ w := httptest.NewRecorder()
+ req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",
+ map[string]any{"output": tc.output, "session_id": "sess-healthy"},
+ testWorkspaceID, "legit-daemon")
+ rctx := chi.NewRouteContext()
+ rctx.URLParams.Add("taskId", taskID)
+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
+
+ testHandler.CompleteTask(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("CompleteTask: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var status string
+ if err := testPool.QueryRow(ctx, `
+ SELECT status FROM agent_task_queue WHERE id = $1
+ `, taskID).Scan(&status); err != nil {
+ t.Fatalf("read task: %v", err)
+ }
+ if status != "completed" {
+ t.Fatalf("task status = %q, want completed", status)
+ }
+
+ // And the healthy session stays available to the next task.
+ got, err := testHandler.Queries.GetLastTaskSession(ctx, db.GetLastTaskSessionParams{
+ AgentID: parseUUID(agentID),
+ IssueID: parseUUID(issueID),
+ })
+ if err != nil {
+ t.Fatalf("GetLastTaskSession: %v", err)
+ }
+ if got.SessionID.String != "sess-healthy" {
+ t.Fatalf("expected the healthy session to remain resumable, got %q", got.SessionID.String)
+ }
+ })
+ }
+}
diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.go
index 6a96dd62a3..99399d0fb2 100644
--- a/server/pkg/agent/claude.go
+++ b/server/pkg/agent/claude.go
@@ -14,6 +14,8 @@ import (
"sync/atomic"
"syscall"
"time"
+
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
)
// claudeTerminateGraceNanos optionally overrides, in nanoseconds, how long a
@@ -172,6 +174,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
var finalResultText string
sawResult := false
resultIsError := false
+ terminalReasonError := ""
var sessionID string
sawAsyncLaunch := false
usage := make(map[string]TokenUsage)
@@ -252,6 +255,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
sawResult = true
finalResultText = msg.ResultText
resultIsError = msg.IsError
+ terminalReasonError = claudeTerminalReasonFailure(msg.TerminalReason, msg.ResultText)
sessionID = msg.SessionID
if resultUsage := claudeResultUsage(msg, opts.Model); len(resultUsage) > 0 {
usage = resultUsage
@@ -300,11 +304,12 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
exitErr,
sessionID,
streamTerminalState{
- lastAssistantText: lastAssistantText,
- finalResultText: finalResultText,
- sawResult: sawResult,
- resultIsError: resultIsError,
- scanErr: scanErr,
+ lastAssistantText: lastAssistantText,
+ finalResultText: finalResultText,
+ sawResult: sawResult,
+ resultIsError: resultIsError,
+ scanErr: scanErr,
+ terminalReasonError: terminalReasonError,
},
completionGuardError,
)
@@ -532,12 +537,16 @@ type claudeSDKMessage struct {
Model string `json:"model,omitempty"`
// result fields
- ResultText string `json:"result,omitempty"`
- IsError bool `json:"is_error,omitempty"`
- DurationMs float64 `json:"duration_ms,omitempty"`
- NumTurns int `json:"num_turns,omitempty"`
- Usage *claudeUsage `json:"usage,omitempty"`
- ModelUsage map[string]claudeResultModelUsage `json:"modelUsage,omitempty"`
+ ResultText string `json:"result,omitempty"`
+ IsError bool `json:"is_error,omitempty"`
+ // TerminalReason is Claude Code's structured statement of why the turn
+ // ended. Read separately from IsError because the CLI computes the two
+ // independently — see claudeTerminalReasonFailure.
+ TerminalReason string `json:"terminal_reason,omitempty"`
+ DurationMs float64 `json:"duration_ms,omitempty"`
+ NumTurns int `json:"num_turns,omitempty"`
+ Usage *claudeUsage `json:"usage,omitempty"`
+ ModelUsage map[string]claudeResultModelUsage `json:"modelUsage,omitempty"`
// log fields
Log *claudeLogEntry `json:"log,omitempty"`
@@ -573,6 +582,38 @@ type claudeResultModelUsage struct {
CacheCreationInputTokens int64 `json:"cacheCreationInputTokens"`
}
+// claudeTerminalReasonFailure turns Claude Code's structured terminal_reason
+// into an error string when the reason means the turn did not actually produce
+// an answer, and returns "" when it says nothing of the sort.
+//
+// Only prompt_too_long is recognised, and deliberately so. Every other terminal
+// reason the CLI can report either already arrives with is_error set (api_error,
+// model_error, error_max_turns …) or is a legitimate completion, so widening
+// this would second-guess a contract that works — while prompt_too_long is the
+// one case observed reaching the platform as a clean success (GH #6402). The
+// CLI computes is_error from whether the last message it rendered was an API
+// error and terminal_reason from why the turn stopped; when compaction fails
+// and the run ends on a message that is not itself flagged, the two disagree
+// and only terminal_reason is telling the truth.
+//
+// The returned text quotes the enum token so taskfailure.Classify lands it in
+// agent_error.context_overflow without depending on the CLI's prose, which
+// varies by release and is empty in some shapes. That reason is on the resume
+// blacklist (GetLastTaskSession / GetLastChatTaskSession), so the saturated
+// session is retired and the next task on the issue starts fresh — the
+// automated form of the transcript-archiving workaround #6402 reported.
+func claudeTerminalReasonFailure(terminalReason, resultText string) string {
+ if strings.TrimSpace(terminalReason) != taskfailure.TerminalReasonPromptTooLong {
+ return ""
+ }
+ msg := "claude ended the turn with terminal_reason=" + taskfailure.TerminalReasonPromptTooLong +
+ ": the session's context window is exhausted and compaction could not recover it"
+ if detail := strings.TrimSpace(resultText); detail != "" {
+ msg += " (" + detail + ")"
+ }
+ return msg
+}
+
func claudeResultUsage(msg claudeSDKMessage, fallbackModel string) map[string]TokenUsage {
if len(msg.ModelUsage) > 0 {
usage := make(map[string]TokenUsage, len(msg.ModelUsage))
diff --git a/server/pkg/agent/claude_context_exhausted_test.go b/server/pkg/agent/claude_context_exhausted_test.go
new file mode 100644
index 0000000000..69a601d9f9
--- /dev/null
+++ b/server/pkg/agent/claude_context_exhausted_test.go
@@ -0,0 +1,312 @@
+package agent
+
+import (
+ "context"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
+)
+
+// TestClaudeTerminalReasonFailure covers the mapping in isolation: only the one
+// terminal reason that has been observed escaping as a success is recognised,
+// and the message it produces has to classify as a context overflow.
+func TestClaudeTerminalReasonFailure(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ terminalReason string
+ resultText string
+ wantFailure bool
+ }{
+ {
+ name: "prompt_too_long is a failure",
+ terminalReason: "prompt_too_long",
+ resultText: "Prompt is too long",
+ wantFailure: true,
+ },
+ {
+ name: "prompt_too_long with no prose",
+ terminalReason: "prompt_too_long",
+ wantFailure: true,
+ },
+ {
+ name: "surrounding whitespace still matches",
+ terminalReason: " prompt_too_long ",
+ wantFailure: true,
+ },
+ {
+ name: "a normal completion is untouched",
+ terminalReason: "completed",
+ resultText: "Done — pushed the fix.",
+ },
+ {
+ name: "an absent field is untouched",
+ // Every backend and every CLI version that does not emit the field
+ // keeps the pre-existing is_error contract.
+ terminalReason: "",
+ resultText: "Done — pushed the fix.",
+ },
+ {
+ name: "other terminal reasons are left to is_error",
+ // These already arrive with is_error set; claiming them here would
+ // second-guess a contract that works.
+ terminalReason: "max_turns",
+ resultText: "Reached maximum number of turns (10)",
+ },
+ {
+ name: "api_error is left to is_error",
+ terminalReason: "api_error",
+ resultText: "API Error: 500",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got := claudeTerminalReasonFailure(tc.terminalReason, tc.resultText)
+ if (got != "") != tc.wantFailure {
+ t.Fatalf("claudeTerminalReasonFailure(%q, %q) = %q, wantFailure=%v",
+ tc.terminalReason, tc.resultText, got, tc.wantFailure)
+ }
+ if !tc.wantFailure {
+ return
+ }
+ if reason := taskfailure.Classify(got); reason != taskfailure.ReasonAgentContextOverflow {
+ t.Fatalf("error %q classifies as %q, want %q", got, reason, taskfailure.ReasonAgentContextOverflow)
+ }
+ if tc.resultText != "" && !strings.Contains(got, tc.resultText) {
+ t.Fatalf("the provider's own wording must survive for diagnosis; got %q", got)
+ }
+ })
+ }
+}
+
+// claudeContextExhaustedFixture is the verbatim stream-json transcript Claude
+// Code 2.1.220 — the version GH #6402 reports — writes when a saturated session
+// is resumed. Captured by resuming a saturated transcript against an endpoint
+// returning the provider's 400 prompt-too-long shape; only the init frame's
+// local tool/skill inventory and absolute paths were stripped.
+const claudeContextExhaustedFixture = "testdata/claude-code-2.1.220-context-exhausted-resume.jsonl"
+
+// TestClaudeExecuteFailsOnCapturedContextExhaustion replays that transcript
+// unedited.
+//
+// What it pins, and why it is not merely "is_error already handled this": the
+// captured terminal frame sets is_error AND terminal_reason together. The
+// is_error path alone labels the failure with whatever prose the CLI put in
+// `result` — here "Prompt is too long", which Classify happens to recognise.
+// The next two tests take that luck away.
+func TestClaudeExecuteFailsOnCapturedContextExhaustion(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ frames, err := os.ReadFile(claudeContextExhaustedFixture)
+ if err != nil {
+ t.Fatalf("read captured frames: %v", err)
+ }
+ result := runClaudeFixture(t, string(frames), "7ff8bf88-4d29-47f6-8c54-87f7ec0b080b")
+
+ if result.Status != "failed" {
+ t.Fatalf("expected status=failed, got %q (output %q)", result.Status, result.Output)
+ }
+ // A failed run must publish no answer at all — the whole defect was the
+ // provider's notice reaching the issue as the agent's conclusion.
+ if result.Output != "" {
+ t.Fatalf("expected no output on a failed run, got %q", result.Output)
+ }
+ if reason := taskfailure.Classify(result.Error); reason != taskfailure.ReasonAgentContextOverflow {
+ t.Fatalf("error %q classifies as %q, want %q", result.Error, reason, taskfailure.ReasonAgentContextOverflow)
+ }
+ // The failure has to name the structured reason, not just carry prose that
+ // happens to classify — that is what makes the label survive a CLI reword.
+ if !strings.Contains(result.Error, taskfailure.TerminalReasonPromptTooLong) {
+ t.Fatalf("error should quote the structured terminal reason, got %q", result.Error)
+ }
+ // The session id must still be reported. It is not a rejected resume — the
+ // transcript loaded fine, it is simply full — and the daemon needs the id
+ // to record which session the failure retires.
+ if result.SessionID != "7ff8bf88-4d29-47f6-8c54-87f7ec0b080b" {
+ t.Fatalf("expected the session id to be reported, got %q", result.SessionID)
+ }
+ if result.ResumeRejected {
+ t.Fatal("a full context window is not a rejected resume")
+ }
+}
+
+// TestClaudeExecuteClassifiesContextExhaustionWithoutUsableProse is the
+// regression for the ordering bug: with is_error checked first, a frame whose
+// `result` is empty or reworded falls back to the generic
+// "returned an error result without details" and classifies as
+// agent_error.unknown — a reason no resume blacklist covers, so the saturated
+// session stays pinned and #6402's stall returns. The structured field is
+// present in both cases and has to decide.
+func TestClaudeExecuteClassifiesContextExhaustionWithoutUsableProse(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ tests := []struct {
+ name string
+ frame string
+ }{
+ {
+ name: "empty result text",
+ frame: `{"type":"result","subtype":"success","is_error":true,"terminal_reason":"prompt_too_long","api_error_status":400,"session_id":"sess-full","result":""}`,
+ },
+ {
+ name: "prose reworded by a future release",
+ // Carries none of Classify's context-overflow phrases, which is
+ // exactly the drift the structured field exists to survive.
+ frame: `{"type":"result","subtype":"success","is_error":true,"terminal_reason":"prompt_too_long","api_error_status":400,"session_id":"sess-full","result":"This chat has gotten too big to continue."}`,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ frames := `{"type":"system","subtype":"init","session_id":"sess-full"}` + "\n" + tc.frame + "\n"
+ result := runClaudeFixture(t, frames, "sess-full")
+
+ if result.Status != "failed" {
+ t.Fatalf("expected status=failed, got %q", result.Status)
+ }
+ if reason := taskfailure.Classify(result.Error); reason != taskfailure.ReasonAgentContextOverflow {
+ t.Fatalf("error %q classifies as %q, want %q — the session would not be retired",
+ result.Error, reason, taskfailure.ReasonAgentContextOverflow)
+ }
+ })
+ }
+}
+
+// TestClaudeExecuteKeepsIsErrorFailuresUnlabelled is the counterpart: a failure
+// with NO recognised terminal reason still reports the CLI's own error text,
+// unchanged. Guards against the reordering swallowing every other failure's
+// diagnostics.
+func TestClaudeExecuteKeepsIsErrorFailuresUnlabelled(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ frames := `{"type":"system","subtype":"init","session_id":"sess-x"}` + "\n" +
+ `{"type":"result","subtype":"success","is_error":true,"terminal_reason":"api_error","session_id":"sess-x","result":"API Error: 529 overloaded"}` + "\n"
+ result := runClaudeFixture(t, frames, "")
+
+ if result.Status != "failed" {
+ t.Fatalf("expected status=failed, got %q", result.Status)
+ }
+ if !strings.Contains(result.Error, "529 overloaded") {
+ t.Fatalf("the CLI's own error text must survive, got %q", result.Error)
+ }
+ if reason := taskfailure.Classify(result.Error); reason != taskfailure.ReasonAgentProviderCapacityOrRateLimit {
+ t.Fatalf("error %q classifies as %q, want %q", result.Error, reason, taskfailure.ReasonAgentProviderCapacityOrRateLimit)
+ }
+}
+
+// runClaudeFixture runs the claude backend against a fake executable that
+// replays `frames` on stdout, and returns the terminal Result.
+func runClaudeFixture(t *testing.T, frames, resumeSessionID string) Result {
+ t.Helper()
+
+ fixturePath := filepath.Join(t.TempDir(), "frames.jsonl")
+ if err := os.WriteFile(fixturePath, []byte(frames), 0o600); err != nil {
+ t.Fatalf("write frames: %v", err)
+ }
+ fakePath := filepath.Join(t.TempDir(), "claude")
+ writeTestExecutable(t, fakePath, []byte("#!/bin/sh\nIFS= read -r _\ncat "+fixturePath+"\n"))
+
+ backend, err := New("claude", Config{
+ ExecutablePath: fakePath,
+ Env: map[string]string{"IS_SANDBOX": "1"},
+ Logger: slog.Default(),
+ })
+ if err != nil {
+ t.Fatalf("new claude backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ session, err := backend.Execute(ctx, "prompt", ExecOptions{
+ ResumeSessionID: resumeSessionID,
+ Timeout: 5 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ select {
+ case result, ok := <-session.Result:
+ if !ok {
+ t.Fatal("result channel closed without a value")
+ }
+ return result
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout waiting for result")
+ return Result{}
+ }
+}
+
+// The counterpart: a genuinely successful run that reports terminal_reason
+// "completed" keeps completing. Guards against the new check swallowing normal
+// traffic.
+func TestClaudeExecuteKeepsCompletedTerminalReason(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ fakePath := filepath.Join(t.TempDir(), "claude")
+ script := "#!/bin/sh\n" +
+ "IFS= read -r _\n" +
+ `echo '{"type":"system","subtype":"init","session_id":"sess-ok"}'` + "\n" +
+ `echo '{"type":"result","subtype":"success","is_error":false,"terminal_reason":"completed","session_id":"sess-ok","result":"Fixed the redirect and pushed."}'` + "\n"
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ backend, err := New("claude", Config{
+ ExecutablePath: fakePath,
+ Env: map[string]string{"IS_SANDBOX": "1"},
+ Logger: slog.Default(),
+ })
+ if err != nil {
+ t.Fatalf("new claude backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ session, err := backend.Execute(ctx, "prompt", ExecOptions{Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ select {
+ case result, ok := <-session.Result:
+ if !ok {
+ t.Fatal("result channel closed without a value")
+ }
+ if result.Status != "completed" {
+ t.Fatalf("expected status=completed, got %q (error %q)", result.Status, result.Error)
+ }
+ if result.Output != "Fixed the redirect and pushed." {
+ t.Fatalf("unexpected output %q", result.Output)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout waiting for result")
+ }
+}
diff --git a/server/pkg/agent/stream_json_result.go b/server/pkg/agent/stream_json_result.go
index 51b31e7950..65e42e54fb 100644
--- a/server/pkg/agent/stream_json_result.go
+++ b/server/pkg/agent/stream_json_result.go
@@ -22,6 +22,17 @@ type streamTerminalState struct {
sawResult bool
resultIsError bool
scanErr error
+ // terminalReasonError, when non-empty, is a failure the backend read out of
+ // a STRUCTURED field on the terminal result event.
+ //
+ // It is not a claim that is_error missed the failure — on every frame
+ // captured so far the two fire together. It is a claim about which one
+ // NAMES the failure: Claude Code sets is_error from whether the last
+ // message it rendered was an API error, and terminal_reason from why the
+ // turn ended, so only the latter identifies the condition without relying
+ // on the CLI's prose (GH #6402). Backends that read no such field leave
+ // this empty and keep the pre-existing contract.
+ terminalReasonError string
}
// finalizeStreamResult applies the shared fail-closed terminal contract used by
@@ -40,7 +51,28 @@ func finalizeStreamResult(
completionGuardError string,
) (status, output, errMsg string) {
status = "completed"
- if state.resultIsError {
+ switch {
+ case state.terminalReasonError != "":
+ // A recognised structured terminal reason wins outright — including
+ // over is_error, which is the ordering that matters in practice.
+ //
+ // On the shape actually captured from Claude Code 2.1.220/2.1.221, a
+ // context-exhausted turn arrives as is_error:true AND
+ // terminal_reason:prompt_too_long together. Letting is_error go first
+ // makes the structured branch dead code on the only frame we have, and
+ // hands the failure whatever prose the CLI happened to put in `result`:
+ // today that string classifies correctly by luck, but an empty or
+ // reworded `result` degrades to "returned an error result without
+ // details" → agent_error.unknown, which no resume blacklist covers, so
+ // the saturated session stays pinned and the stall returns (GH #6402).
+ //
+ // Ordering it first costs nothing: the branch only fires for a reason
+ // the backend positively recognised, and the message it builds carries
+ // the CLI's own `result` text along as detail, so nothing is lost for
+ // diagnosis.
+ status = "failed"
+ errMsg = state.terminalReasonError
+ case state.resultIsError:
status = "failed"
errMsg = state.finalResultText
if errMsg == "" {
diff --git a/server/pkg/agent/testdata/claude-code-2.1.220-context-exhausted-resume.jsonl b/server/pkg/agent/testdata/claude-code-2.1.220-context-exhausted-resume.jsonl
new file mode 100644
index 0000000000..77d9b7a753
--- /dev/null
+++ b/server/pkg/agent/testdata/claude-code-2.1.220-context-exhausted-resume.jsonl
@@ -0,0 +1,5 @@
+{"type":"system","subtype":"init","session_id":"7ff8bf88-4d29-47f6-8c54-87f7ec0b080b","model":"claude-sonnet-4-5-20250929","permissionMode":"bypassPermissions","apiKeySource":"ANTHROPIC_API_KEY","claude_code_version":"2.1.220"}
+{"type":"system","subtype":"status","status":"compacting","session_id":"7ff8bf88-4d29-47f6-8c54-87f7ec0b080b","uuid":"d9237279-e609-4bb7-9370-43ada3d4b14a"}
+{"type":"system","subtype":"status","status":null,"compact_result":"failed","compact_error":"exhausted","session_id":"7ff8bf88-4d29-47f6-8c54-87f7ec0b080b","uuid":"c6dbe12f-4a46-48be-b391-cba19fad2622"}
+{"type":"assistant","message":{"id":"351ceb80-5685-4323-8149-7ac7fe847125","container":null,"model":"<synthetic>","role":"assistant","stop_details":null,"stop_reason":"stop_sequence","stop_sequence":"","type":"message","usage":{"input_tokens":0,"output_tokens":0,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":null,"cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":null,"iterations":null,"speed":null},"content":[{"type":"text","text":"Prompt is too long"}],"context_management":null},"parent_tool_use_id":null,"session_id":"7ff8bf88-4d29-47f6-8c54-87f7ec0b080b","uuid":"421f784d-da7f-4cef-a96a-ba5a25f5b739","timestamp":"2026-08-05T06:39:55.693Z","error":"invalid_request","request_id":"req_fake220","is_api_error_message":true}
+{"is_error":true,"duration_api_ms":0,"num_turns":1,"stop_reason":"stop_sequence","session_id":"7ff8bf88-4d29-47f6-8c54-87f7ec0b080b","total_cost_usd":0,"usage":{"input_tokens":0,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":0,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"modelUsage":{},"permission_denials":[],"terminal_reason":"prompt_too_long","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","subtype":"success","api_error_status":400,"result":"Prompt is too long","type":"result","duration_ms":862,"uuid":"45897866-619f-40de-80b5-a4f2f740285b"}
diff --git a/server/pkg/taskfailure/classify.go b/server/pkg/taskfailure/classify.go
index 042bfc8b95..132c82610f 100644
--- a/server/pkg/taskfailure/classify.go
+++ b/server/pkg/taskfailure/classify.go
@@ -271,9 +271,19 @@ func Classify(rawError string) Reason {
// NormalizeDaemonReason reuse them to upgrade an older daemon's catchall
// server-side. Matched against pre-lowercased text.
// Mirror these substrings into the MUL-1949 offline backfill SQL.
+//
+// terminal_reason=prompt_too_long joins them for GH #6402: it is the structured
+// enum value Claude Code puts on the result frame when the turn ended because
+// the context window is full, and the daemon quotes it verbatim into the error
+// it reports (see claudeTerminalReasonFailure in pkg/agent/claude.go). Being an
+// enum token rather than prose, it is at least as unambiguous as the two above
+// — no free-form provider message produces it by accident — so a run classified
+// from it lands in context_overflow even when the CLI's accompanying copy is
+// empty or reworded between releases.
var contextWindowExceededWitnesses = []string{
"context window limit",
"model_context_window_exceeded",
+ TerminalReasonPromptTooLong,
}
// legacySkillBundlePrefix is the exact wrapper a pre-MUL-5370 daemon put on a
diff --git a/server/pkg/taskfailure/context_exhausted.go b/server/pkg/taskfailure/context_exhausted.go
new file mode 100644
index 0000000000..70d710eb54
--- /dev/null
+++ b/server/pkg/taskfailure/context_exhausted.go
@@ -0,0 +1,113 @@
+package taskfailure
+
+import "strings"
+
+// TerminalReasonPromptTooLong is the value Claude Code writes into the
+// stream-json result event's `terminal_reason` when the turn ended because the
+// request no longer fits the model's context window — either the conversation
+// was already over the limit on resume, or auto-compaction ran and could not
+// get it back under.
+//
+// It is a structured enum value, not prose: the CLI carries it alongside
+// image_error / model_error / max_turns / completed and friends, on the
+// SUCCESS-subtype result frame. It is the only field on that frame that states
+// why the turn ended. `is_error` answers a different question — the CLI sets it
+// from whether the LAST message it rendered was an API-error message — and the
+// two are computed independently, so a run's real terminal condition must be
+// read from this field rather than inferred from that flag.
+//
+// Captured from Claude Code 2.1.220 (the version GH #6402 reports) by resuming
+// a saturated transcript against an endpoint returning the provider's 400
+// prompt-too-long shape; the frames are fixtured verbatim in
+// pkg/agent/testdata/claude-code-2.1.220-context-exhausted-resume.jsonl. Auto-
+// compaction runs, reports compact_result=failed / compact_error=exhausted, and
+// the turn ends:
+//
+// {"type":"result","subtype":"success","is_error":true,
+// "terminal_reason":"prompt_too_long","api_error_status":400,
+// "result":"Prompt is too long"}
+//
+// 2.1.221 produces the same shape. Two things follow, and the second is the
+// reason this constant exists:
+//
+// - The field is present on the reported version, so keying on it reaches the
+// hosts that hit the bug rather than only future ones.
+// - On this frame is_error and terminal_reason BOTH fire. Whichever the
+// runtime reads first decides the failure's label, and only terminal_reason
+// is guaranteed to name the condition — the `result` prose is empty in some
+// shapes and rewords between releases.
+//
+// Note what the capture does not show: is_error false. The exact escape that
+// produced a `completed` task on the reporter's host is not reproduced here, so
+// the text-side predicate below stays a bounded backstop rather than the
+// load-bearing part of the fix.
+const TerminalReasonPromptTooLong = "prompt_too_long"
+
+// contextExhaustedOutputMaxLen caps how long a reported-successful output can
+// be and still be re-read as a context-exhaustion notice. Every wording below
+// is a terse one-liner the CLI emits INSTEAD of an answer; an agent that
+// actually did the work and then discussed context limits writes far more than
+// this. Same rationale and same value as poisonedOutputMaxLen in
+// internal/daemon — a miss costs the pre-fix behaviour, a false positive turns
+// a real result into a failure and retires a healthy session.
+const contextExhaustedOutputMaxLen = 320
+
+// ContextExhaustedCompletion reports whether an output the agent runtime
+// reported as a SUCCESSFUL final answer is really the provider telling us the
+// session's context window is full.
+//
+// This is the text-side counterpart to TerminalReasonPromptTooLong, and it
+// exists for the two places the structured field is not available:
+//
+// - Backends whose CLI has no equivalent structured field.
+// - The server's /complete boundary, where the caller may be an installed
+// daemon too old to carry the structured check. Daemons upgrade on their
+// own cadence, so a daemon-only fix reaches nobody until every host
+// updates — and one un-upgraded host means a permanently stuck (agent,
+// issue) pair, not just a mislabelled row (same argument as
+// NormalizeDaemonReason, MUL-5370).
+//
+// EVERY clause is composite, and none is a bare natural-language sentence. The
+// GitHub report paraphrased the CLI as "context too long, please run /compact",
+// and neither half of that is safe alone: "/compact" appears in ordinary Claude
+// Code advice and "context too long" is a phrase an agent can legitimately
+// write about its own run. Each clause below pins a full, distinctive wording
+// taken from the Claude Code binary itself rather than from the report:
+//
+// "Prompt is too long · … A single-exchange conversation cannot be compacted; …" (3 variants, all carrying "cannot be compacted")
+// "Conversation too long. Press esc twice to go up a few messages and try again."
+// "Compaction failed · conversation could not be reduced below the context limit"
+//
+// The CLI's bare "Prompt is too long" is deliberately NOT matched here, even
+// though it is a real terminal result — matching it would mean declaring a
+// task failed because its whole answer was one common English sentence, which
+// an agent asked "is my prompt too long?" can legitimately produce. And this
+// predicate only ever sees output a caller believed was a SUCCESS, so a match
+// costs a real task and a healthy session.
+//
+// Leaving it out costs nothing on the evidence we have: in the 2.1.220 and
+// 2.1.221 frames captured for GH #6402 the bare form arrives with is_error set,
+// which routes it through /fail, where Classify's rule 1 has always mapped
+// "prompt is too long" to context_overflow. That is a statement about those
+// captures, not about every build — if a frame ever carries the bare sentence
+// as a clean success, it will be missed here, and that is the deliberate
+// direction to err in.
+func ContextExhaustedCompletion(output string) bool {
+ trimmed := strings.TrimSpace(output)
+ if trimmed == "" || len(trimmed) > contextExhaustedOutputMaxLen {
+ return false
+ }
+ lowered := strings.ToLower(trimmed)
+ switch {
+ case strings.Contains(lowered, "prompt is too long") &&
+ strings.Contains(lowered, "cannot be compacted"):
+ return true
+ case strings.Contains(lowered, "conversation too long") &&
+ strings.Contains(lowered, "press esc twice"):
+ return true
+ case strings.Contains(lowered, "compaction failed") &&
+ strings.Contains(lowered, "reduced below the context limit"):
+ return true
+ }
+ return false
+}
diff --git a/server/pkg/taskfailure/context_exhausted_test.go b/server/pkg/taskfailure/context_exhausted_test.go
new file mode 100644
index 0000000000..0db1045482
--- /dev/null
+++ b/server/pkg/taskfailure/context_exhausted_test.go
@@ -0,0 +1,177 @@
+package taskfailure
+
+import (
+ "strings"
+ "testing"
+)
+
+// TestContextExhaustedCompletion is the precision regression for GH #6402.
+// The wordings marked "captured" were taken from the Claude Code binary /
+// a live reproduction (resuming a saturated transcript against an endpoint
+// returning the provider's 400 prompt-too-long shape), not from the issue
+// report's paraphrase — the report said "a message like ...", which is exactly
+// what a matcher must not be built on.
+func TestContextExhaustedCompletion(t *testing.T) {
+ tests := []struct {
+ name string
+ output string
+ want bool
+ }{
+ // ── the real thing ──
+ {
+ name: "captured: single-exchange variant with token counts",
+ output: "Prompt is too long · the request is ~274931 tokens (limit 200000) but this conversation is only ~1597 tokens — the rest is system prompt, tool definitions, and attachment content. A single-exchange conversation cannot be compacted; reduce attached files/tools or start with less context.",
+ want: true,
+ },
+ {
+ name: "captured: single-exchange variant without token counts",
+ output: "Prompt is too long · this conversation is a single exchange and cannot be compacted — the request size comes mostly from system prompt, tool definitions, or attachments.",
+ want: true,
+ },
+ {
+ name: "captured: conversation-too-long thrown by the compaction path",
+ output: "Conversation too long. Press esc twice to go up a few messages and try again.",
+ want: true,
+ },
+ {
+ name: "captured: compaction exhausted",
+ output: "Compaction failed · conversation could not be reduced below the context limit",
+ want: true,
+ },
+
+ // ── near misses: each holds ONE half of a composite fingerprint ──
+ {
+ // The CLI's own bare terminal result, and still not a match here.
+ // An agent asked "is my prompt too long?" can answer exactly this
+ // sentence, and this predicate only ever sees output someone
+ // believed was a success — so declaring it a failure would fail a
+ // real task and retire a healthy session. Nothing is lost: the bare
+ // form always arrives with is_error set (see the fixture in
+ // pkg/agent/testdata), which routes it through the failure path
+ // where Classify already handles it — pinned by
+ // TestBarePromptTooLongIsCoveredByTheFailurePath below.
+ name: "bare provider sentence is left to the failure path",
+ output: "Prompt is too long",
+ want: false,
+ },
+ {
+ name: "the issue report's paraphrase is not a fingerprint",
+ // GH #6402 wrote "a message like 'context too long, please run
+ // /compact'". Neither half is safe alone, so the paraphrase itself
+ // must not match — matching it would mean matching every agent
+ // reply that suggests /compact.
+ output: "context too long, please run /compact",
+ want: false,
+ },
+ {
+ name: "advice to compact is not a failure",
+ output: "This session is getting big — run /compact before continuing.",
+ want: false,
+ },
+ {
+ name: "an agent quoting the phrase in a real answer",
+ output: `Added a guard for the "Prompt is too long" case and pushed it.`,
+ want: false,
+ },
+ {
+ name: "a compaction failure with a different cause",
+ output: "Compaction failed · attached media exceeds size limits",
+ want: false,
+ },
+ {
+ name: "empty output",
+ output: "",
+ want: false,
+ },
+ {
+ name: "whitespace only",
+ output: " \n\t ",
+ want: false,
+ },
+ {
+ name: "a long answer that discusses the exact wording",
+ // The length cap is the backstop behind the composite match: a real
+ // conclusion can legitimately contain every marker at once (this
+ // review comment does), and it must still be delivered as a result.
+ output: "I looked into why the agent stalled. Claude Code emits \"Prompt is too long\" when a single-exchange conversation cannot be compacted, and \"Conversation too long. Press esc twice to go up a few messages and try again.\" when the compaction path throws; the underlying failure is \"Compaction failed · conversation could not be reduced below the context limit\". I've added a classifier for all three and opened a PR — the daemon now retires the session instead of publishing the notice as an answer.",
+ want: false,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := ContextExhaustedCompletion(tc.output); got != tc.want {
+ t.Errorf("ContextExhaustedCompletion(%q) = %v, want %v", tc.output, got, tc.want)
+ }
+ })
+ }
+}
+
+// TestBarePromptTooLongIsCoveredByTheFailurePath is the other half of the
+// argument for leaving the CLI's bare sentence out of the completed-output
+// predicate: on the captured frames it always arrives with is_error set, so it
+// reaches the server as a FAILURE, where Classify has routed it to
+// context_overflow since long before GH #6402. Leaving it out of the
+// success-path predicate therefore costs no coverage — it only removes the
+// chance of failing a task whose entire answer was that one English sentence.
+func TestBarePromptTooLongIsCoveredByTheFailurePath(t *testing.T) {
+ for _, raw := range []string{
+ "Prompt is too long",
+ "prompt is too long: 274931 tokens > 200000 maximum",
+ } {
+ if got := Classify(raw); got != ReasonAgentContextOverflow {
+ t.Errorf("Classify(%q) = %q, want %q", raw, got, ReasonAgentContextOverflow)
+ }
+ }
+}
+
+// TestContextExhaustedCompletionLengthCap pins the boundary so a future edit
+// to the cap has to be deliberate: the marker is identical on both sides and
+// only the length decides.
+func TestContextExhaustedCompletionLengthCap(t *testing.T) {
+ base := "Prompt is too long · a single-exchange conversation cannot be compacted. "
+ atCap := base + strings.Repeat("x", contextExhaustedOutputMaxLen-len(base))
+ overCap := atCap + "x"
+
+ if !ContextExhaustedCompletion(atCap) {
+ t.Errorf("output of exactly %d bytes should classify", contextExhaustedOutputMaxLen)
+ }
+ if ContextExhaustedCompletion(overCap) {
+ t.Errorf("output of %d bytes should be treated as a real answer", len(overCap))
+ }
+}
+
+// TestTerminalReasonPromptTooLongClassifies pins the other half of the
+// contract: the daemon quotes the structured terminal reason into the error it
+// reports, and Classify must land that on the reason the resume blacklist
+// covers. Without this the run would fail as agent_error.unknown — labelled
+// wrong AND resume-safe by omission, which is the stuck (agent, issue) pair
+// GH #6402 describes.
+func TestTerminalReasonPromptTooLongClassifies(t *testing.T) {
+ errMsg := "claude ended the turn with terminal_reason=" + TerminalReasonPromptTooLong +
+ ": the session's context window is exhausted and compaction could not recover it"
+ if got := Classify(errMsg); got != ReasonAgentContextOverflow {
+ t.Errorf("Classify(%q) = %q, want %q", errMsg, got, ReasonAgentContextOverflow)
+ }
+ // And with no provider prose attached at all.
+ bare := "terminal_reason=" + TerminalReasonPromptTooLong
+ if got := Classify(bare); got != ReasonAgentContextOverflow {
+ t.Errorf("Classify(%q) = %q, want %q", bare, got, ReasonAgentContextOverflow)
+ }
+}
+
+// TestNormalizeDaemonReasonUpgradesPromptTooLong: an older daemon that carries
+// the structured check but not the taxonomy entry reports the catchall. The
+// witness in the error text is unambiguous enough to upgrade it server-side,
+// which is what retires the session without waiting for that host to update.
+func TestNormalizeDaemonReasonUpgradesPromptTooLong(t *testing.T) {
+ raw := "claude ended the turn with terminal_reason=" + TerminalReasonPromptTooLong + ": ..."
+ if got := NormalizeDaemonReason(string(ReasonAgentUnknown), raw); got != ReasonAgentContextOverflow {
+ t.Errorf("NormalizeDaemonReason = %q, want %q", got, ReasonAgentContextOverflow)
+ }
+ // A refined reason says more about what ended the run than a witness
+ // appearing somewhere in the same blob, so it is left alone.
+ if got := NormalizeDaemonReason(string(ReasonAgentProcessFailure), raw); got != ReasonAgentProcessFailure {
+ t.Errorf("NormalizeDaemonReason overwrote a refined reason: got %q", got)
+ }
+}