Skip to content

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

Go

MUL-5831 fix(agent): fail opencode runs that end on an empty step (#6545)

Bohan Jiang37e2b0709417
diff --git a/server/internal/service/task_complete_race_test.go b/server/internal/service/task_complete_race_test.go
index 1b8355145e..5489a27273 100644
--- a/server/internal/service/task_complete_race_test.go
+++ b/server/internal/service/task_complete_race_test.go
@@ -280,6 +280,104 @@ func TestTaskFailureClassifiers(t *testing.T) {
}
}
+// TestOpencodeStreamEndedFailureRetries walks the full chain for #6522: the
+// error string pkg/agent/opencode.go's terminal-signal guard produces, through
+// taskfailure.Classify, into the retry gate.
+//
+// The trap this guards: a run that ends on an empty step now goes red instead
+// of false-green, but that alone delivers nothing. The reason it classifies to
+// has to be on retryableReasons, or the task simply dies with a better label
+// and max_attempts never applies — which is exactly where these three errors
+// used to land (process_failure for the two "terminal signal" variants, via
+// the word "signal", and unknown for the empty-step one).
+//
+// The second trap, one layer out: FailTask only classifies when the daemon sent
+// no reason. An installed daemon predating the rule-7 entry sends a non-empty
+// one, so the fix reaches it through NormalizeDaemonReason or not at all — the
+// installed-daemon cadence problem that shim exists for. Hence the matrix below
+// walks both wire shapes, not just the current-daemon one.
+func TestOpencodeStreamEndedFailureRetries(t *testing.T) {
+ guardErrors := []struct {
+ name string
+ errMsg string
+ }{
+ {"empty final step", "opencode stream ended on an empty step (no text, no tool call, no reported usage) — the provider produced nothing"},
+ {"step open at EOF", "opencode stream ended without a terminal signal (step still open at EOF)"},
+ {"continuation never started", "opencode stream ended without a terminal signal (last step required a continuation that never started)"},
+ }
+
+ mkTask := func(attempt, max int32) db.AgentTaskQueue {
+ return db.AgentTaskQueue{
+ Attempt: attempt,
+ MaxAttempts: max,
+ IssueID: pgtype.UUID{Bytes: [16]byte{1}, Valid: true},
+ }
+ }
+
+ // The reason a daemon puts on the wire. "" is a current daemon, which sends
+ // nothing and lets the server classify. The rest are what an installed
+ // daemon predating rule 7 reports: a NON-EMPTY reason, which skips
+ // FailTask's classify-when-empty branch entirely and only NormalizeDaemonReason
+ // can still fix. Testing Classify alone would miss that boundary — and did.
+ daemonReasons := []struct {
+ name string
+ reported string
+ }{
+ {"current daemon (server classifies)", ""},
+ {"legacy daemon reporting process_failure", string(taskfailure.ReasonAgentProcessFailure)},
+ {"legacy daemon reporting unknown", string(taskfailure.ReasonAgentUnknown)},
+ {"pre-MUL-1949 daemon reporting coarse agent_error", "agent_error"},
+ }
+
+ // resolveFailureReason mirrors the two steps FailTask runs in order before
+ // it decides retry eligibility.
+ resolveFailureReason := func(reported, errMsg string) string {
+ if reported == "" {
+ reported = taskfailure.Classify(errMsg).String()
+ }
+ return taskfailure.NormalizeDaemonReason(reported, errMsg).String()
+ }
+
+ for _, tc := range guardErrors {
+ for _, dr := range daemonReasons {
+ t.Run(tc.name+"/"+dr.name, func(t *testing.T) {
+ reason := resolveFailureReason(dr.reported, tc.errMsg)
+ if reason != string(taskfailure.ReasonAgentProviderNetwork) {
+ t.Fatalf("resolveFailureReason(%q, %q) = %q, want %q",
+ dr.reported, tc.errMsg, reason, taskfailure.ReasonAgentProviderNetwork)
+ }
+ // Resume-safe, so the retry child inherits the session and
+ // continues rather than redoing the work already paid for.
+ if resumeUnsafeFailureReason(reason) {
+ t.Errorf("resumeUnsafeFailureReason(%q) = true, want false", reason)
+ }
+ // With an attempt left, the failure produces a retry task.
+ if !retryEligible(reason, mkTask(1, 2)) {
+ t.Errorf("retryEligible(%q, attempt=1/max=2) = false, want true", reason)
+ }
+ // And still terminates once the ceiling is reached, so a
+ // deterministically broken provider cannot loop forever.
+ if retryEligible(reason, mkTask(providerNetworkMaxAttempts, 2)) {
+ t.Errorf("retryEligible(%q, attempt=%d/max=2) = true, want false at the ceiling",
+ reason, providerNetworkMaxAttempts)
+ }
+ })
+ }
+ }
+
+ // The prefix is what identifies the guard's own message. An unrelated
+ // failure that merely mentions opencode must keep the daemon's label —
+ // upgrading on a loose substring would relabel real crashes as transient
+ // stream cuts and retry them.
+ t.Run("unrelated opencode failure keeps its reason", func(t *testing.T) {
+ const crash = "opencode exited with error: exit status 2 (opencode stream ended is not why)"
+ got := taskfailure.NormalizeDaemonReason(string(taskfailure.ReasonAgentProcessFailure), crash).String()
+ if got != string(taskfailure.ReasonAgentProcessFailure) {
+ t.Errorf("NormalizeDaemonReason(process_failure, %q) = %q, want it left alone", crash, got)
+ }
+ })
+}
+
// TestSkillBundleFailureFromLegacyDaemonRetries is the mixed-version
// regression for MUL-5370. It walks the exact chain FailTask runs for a task
// an un-upgraded daemon just failed, and asserts the user-visible outcome:
diff --git a/server/pkg/agent/opencode.go b/server/pkg/agent/opencode.go
index 1a19ca481a..970064376d 100644
--- a/server/pkg/agent/opencode.go
+++ b/server/pkg/agent/opencode.go
@@ -272,7 +272,7 @@ type eventResult struct {
output string
sessionID string
usage TokenUsage // accumulated token usage across all steps
- noTerminalSignal bool // guard fired: stream reached EOF before a step or required continuation completed
+ noTerminalSignal bool // guard fired: the stream ended without evidence the run actually finished
}
// processEvents reads JSON lines from r, dispatches events to ch, and returns
@@ -304,6 +304,23 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventRes
stepHasContinuationTool := false // current step has a local tool result OpenCode must feed back
awaitingContinuation := false // the last step_finish still required another step
+ // Step bracketing still misses a third shape: a step that opens and closes
+ // cleanly while carrying nothing at all — no text, no tool call, and no
+ // reported usage whatsoever (#6522, observed as step_finish reason "unknown"
+ // with every token counter and the cost at 0). No usage means the provider
+ // round-trip never happened, so that step is a dead stream wearing a clean
+ // finish, and ending a run on one is another false-green completion.
+ //
+ // The criterion is deliberately "this step produced nothing", NOT "the run
+ // produced no text": a task whose only deliverable is a tool side effect is
+ // legitimate and must stay green. Any single sign of life — text, a tool
+ // call, or any usage field the protocol reports — keeps the step productive.
+ // This is also why the reason itself is not consulted: a missing or
+ // unrecognised reason stays terminal for protocol compatibility (see the
+ // back-compat regression), and voidness is orthogonal to it.
+ stepProducedOutput := false // current step emitted text, a tool call, or reported usage
+ lastStepVoid := false // the most recently closed step produced nothing at all
+
scanner := newAgentStreamScanner(r)
for scanner.Scan() {
@@ -324,8 +341,12 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventRes
switch event.Type {
case "text":
b.handleTextEvent(event, ch, &output)
+ if event.Part.Text != "" {
+ stepProducedOutput = true
+ }
case "tool_use":
b.handleToolUseEvent(event, ch)
+ stepProducedOutput = true
if event.Part.Metadata == nil || !event.Part.Metadata.ProviderExecuted {
stepHasContinuationTool = true
}
@@ -335,13 +356,17 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventRes
openStep = true
stepHasContinuationTool = false
awaitingContinuation = false
+ stepProducedOutput = false
trySend(ch, Message{Type: MessageStatus, Status: "running"})
case "step_finish":
openStep = false
awaitingContinuation = event.Part.Reason == "tool-calls" ||
(event.Part.Reason != "" && stepHasContinuationTool)
stepHasContinuationTool = false
- // Accumulate token usage from step_finish events.
+ // Accumulate token usage from step_finish events. Only the fields
+ // TokenUsage models are billed; every reported field additionally
+ // counts as proof the provider round-trip happened, which is what
+ // keeps a productive step out of the void-step guard below.
if t := event.Part.Tokens; t != nil {
usage.InputTokens += t.Input
usage.OutputTokens += t.Output
@@ -350,6 +375,10 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventRes
usage.CacheWriteTokens += t.Cache.Write
}
}
+ if stepReportedUsage(&event.Part) {
+ stepProducedOutput = true
+ }
+ lastStepVoid = !stepProducedOutput
}
}
@@ -363,20 +392,27 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventRes
}
// Require a positive terminal signal. A clean EOF while a step is still
- // open — or right after a step that finished with reason "tool-calls",
- // whose continuation step never started — means the run did not finish:
- // its provider stream died and `opencode run` exited without emitting an
- // error event. Fail closed on that structural evidence rather than
- // reporting a false-green completion.
+ // open — right after a step that finished with reason "tool-calls", whose
+ // continuation step never started — or on a step that carried nothing at
+ // all means the run did not finish: its provider stream died and
+ // `opencode run` exited without emitting an error event. Fail closed on
+ // that structural evidence rather than reporting a false-green completion.
noTerminalSignal := false
- if finalStatus == "completed" && (openStep || awaitingContinuation) {
- finalStatus = "failed"
- if openStep {
+ if finalStatus == "completed" {
+ switch {
+ case openStep:
+ finalStatus = "failed"
finalError = "opencode stream ended without a terminal signal (step still open at EOF)"
- } else {
+ noTerminalSignal = true
+ case awaitingContinuation:
+ finalStatus = "failed"
finalError = "opencode stream ended without a terminal signal (last step required a continuation that never started)"
+ noTerminalSignal = true
+ case lastStepVoid:
+ finalStatus = "failed"
+ finalError = "opencode stream ended on an empty step (no text, no tool call, no reported usage) — the provider produced nothing"
+ noTerminalSignal = true
}
- noTerminalSignal = true
}
return eventResult{
@@ -389,6 +425,35 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventRes
}
}
+// stepReportedUsage reports whether a step_finish part carries any evidence
+// that the provider round-trip actually happened.
+//
+// OpenCode's protocol keeps reasoning and the aggregate total in fields of
+// their own alongside input/output/cache, and reports cost as a sibling of the
+// whole token block — a step can legitimately land with reasoning or cost
+// positive while input and output are both zero. Checking only input/output
+// would therefore call such a step void and fail a healthy run, so every field
+// the protocol reports counts. Only an across-the-board zero means no model
+// call happened.
+//
+// The reasoning and total counters are read as evidence only, deliberately not
+// folded into TokenUsage: total is derived (adding it would double-count) and
+// TokenUsage has no reasoning bucket, so recording either here would change
+// billing figures rather than fix this bug.
+func stepReportedUsage(part *opencodeEventPart) bool {
+ if part.Cost > 0 {
+ return true
+ }
+ t := part.Tokens
+ if t == nil {
+ return false
+ }
+ if t.Input > 0 || t.Output > 0 || t.Reasoning > 0 || t.Total > 0 {
+ return true
+ }
+ return t.Cache != nil && (t.Cache.Read > 0 || t.Cache.Write > 0)
+}
+
func (b *opencodeBackend) handleTextEvent(event opencodeEvent, ch chan<- Message, output *strings.Builder) {
text := event.Part.Text
if text != "" {
@@ -558,6 +623,11 @@ type opencodeEventPart struct {
// step_finish token usage
Tokens *opencodeTokens `json:"tokens,omitempty"`
+ // step_finish cost, a sibling of the token block rather than a member of
+ // it. Read only as round-trip evidence by stepReportedUsage; opencode's
+ // billing figures come from the token counters above.
+ Cost float64 `json:"cost,omitempty"`
+
// step_finish reason (FinishReason: "stop", "tool-calls", …). Absent on
// older opencode versions whose step-finish parts predate the field.
Reason string `json:"reason,omitempty"`
@@ -567,11 +637,16 @@ type opencodePartMetadata struct {
ProviderExecuted bool `json:"providerExecuted,omitempty"`
}
-// opencodeTokens represents token usage in a step_finish event.
+// opencodeTokens represents token usage in a step_finish event. Reasoning and
+// Total are separate counters in the protocol, not components of Input/Output,
+// so a step can report either while both of those are zero; they are parsed so
+// stepReportedUsage can see them.
type opencodeTokens struct {
- Input int64 `json:"input"`
- Output int64 `json:"output"`
- Cache *opencodeCacheTokens `json:"cache,omitempty"`
+ Input int64 `json:"input"`
+ Output int64 `json:"output"`
+ Reasoning int64 `json:"reasoning,omitempty"`
+ Total int64 `json:"total,omitempty"`
+ Cache *opencodeCacheTokens `json:"cache,omitempty"`
}
type opencodeCacheTokens struct {
diff --git a/server/pkg/agent/opencode_test.go b/server/pkg/agent/opencode_test.go
index 05d1bca452..6c5e77a548 100644
--- a/server/pkg/agent/opencode_test.go
+++ b/server/pkg/agent/opencode_test.go
@@ -1011,6 +1011,180 @@ func TestOpencodeProcessEventsToolErrorThenCleanFinish(t *testing.T) {
}
}
+func TestOpencodeProcessEventsEmptyFinalStepFails(t *testing.T) {
+ t.Parallel()
+
+ b := &opencodeBackend{cfg: Config{Logger: slog.Default()}}
+ ch := make(chan Message, 256)
+
+ // Regression for #6522. The run did real work, then the provider stream
+ // died: the final step opened, emitted a reasoning part (which carries no
+ // deliverable and no tokens), and closed with reason "unknown" and an
+ // all-zero token block. `opencode run` exited 0, so the daemon reported
+ // `completed` with an empty agent_error and the task stalled with no
+ // deliverable. Zero input tokens means the provider round-trip never
+ // happened — that is a dead stream, not a completion.
+ lines := strings.Join([]string{
+ `{"type":"step_start","timestamp":1000,"sessionID":"ses_void","part":{"type":"step-start"}}`,
+ `{"type":"text","timestamp":1001,"sessionID":"ses_void","part":{"type":"text","text":"All context gathered. Let me set up and begin."}}`,
+ `{"type":"tool_use","timestamp":1002,"sessionID":"ses_void","part":{"type":"tool","tool":"bash","callID":"call_1","state":{"status":"completed","input":{"command":"ls"},"output":"ok\n"}}}`,
+ `{"type":"step_finish","timestamp":1003,"sessionID":"ses_void","part":{"type":"step-finish","reason":"tool-calls","tokens":{"input":14585,"output":89,"cache":{"write":0,"read":0}}}}`,
+ `{"type":"step_start","timestamp":1004,"sessionID":"ses_void","part":{"type":"step-start"}}`,
+ `{"type":"reasoning","timestamp":1005,"sessionID":"ses_void","part":{"type":"reasoning","text":"thinking..."}}`,
+ `{"type":"step_finish","timestamp":1006,"sessionID":"ses_void","part":{"type":"step-finish","reason":"unknown","tokens":{"input":0,"output":0,"reasoning":0,"cache":{"write":0,"read":0}},"cost":0}}`,
+ }, "\n")
+
+ result := b.processEvents(strings.NewReader(lines), ch)
+
+ if result.status != "failed" {
+ t.Errorf("status: got %q, want %q (an empty final step must not complete the run)", result.status, "failed")
+ }
+ if !strings.Contains(result.errMsg, "empty step") {
+ t.Errorf("errMsg: got %q, want it to name the empty step", result.errMsg)
+ }
+ // The error text is the input to taskfailure.Classify, which routes this
+ // failure to the retryable provider_network bucket — see the matching
+ // cases in pkg/taskfailure/classify_test.go. Keep the two in sync.
+ if !strings.HasPrefix(result.errMsg, "opencode stream ended") {
+ t.Errorf("errMsg: got %q, want the classifier's opencode stream-ended prefix", result.errMsg)
+ }
+ if !result.noTerminalSignal {
+ t.Error("noTerminalSignal: got false, want true")
+ }
+ // Work done before the stream died must still be reported, so the failure
+ // stays diagnosable and the usage already paid for is not lost.
+ if result.output != "All context gathered. Let me set up and begin." {
+ t.Errorf("output: got %q, want the text emitted before the empty step", result.output)
+ }
+ if result.usage.InputTokens != 14585 || result.usage.OutputTokens != 89 {
+ t.Errorf("usage: got %+v, want the first step's tokens preserved", result.usage)
+ }
+
+ close(ch)
+}
+
+func TestOpencodeProcessEventsEmptyStepMidRunRecovers(t *testing.T) {
+ t.Parallel()
+
+ b := &opencodeBackend{cfg: Config{Logger: slog.Default()}}
+ ch := make(chan Message, 256)
+
+ // Only the step the run *ends* on matters. A void step that the run
+ // recovers from — the next step produces real output and closes cleanly —
+ // is not evidence of a dead stream and must stay "completed".
+ lines := strings.Join([]string{
+ `{"type":"step_start","timestamp":1000,"sessionID":"ses_recover","part":{"type":"step-start"}}`,
+ `{"type":"step_finish","timestamp":1001,"sessionID":"ses_recover","part":{"type":"step-finish","reason":"unknown","tokens":{"input":0,"output":0,"cache":{"write":0,"read":0}}}}`,
+ `{"type":"step_start","timestamp":1002,"sessionID":"ses_recover","part":{"type":"step-start"}}`,
+ `{"type":"text","timestamp":1003,"sessionID":"ses_recover","part":{"type":"text","text":"recovered and done"}}`,
+ `{"type":"step_finish","timestamp":1004,"sessionID":"ses_recover","part":{"type":"step-finish","reason":"stop","tokens":{"input":120,"output":8,"cache":{"write":0,"read":0}}}}`,
+ }, "\n")
+
+ result := b.processEvents(strings.NewReader(lines), ch)
+
+ if result.status != "completed" {
+ t.Errorf("status: got %q, want %q (a recovered void step must not fail the run)", result.status, "completed")
+ }
+ if result.errMsg != "" {
+ t.Errorf("errMsg: got %q, want empty", result.errMsg)
+ }
+
+ close(ch)
+}
+
+func TestOpencodeProcessEventsToolOnlyFinalStepStaysCompleted(t *testing.T) {
+ t.Parallel()
+
+ b := &opencodeBackend{cfg: Config{Logger: slog.Default()}}
+ ch := make(chan Message, 256)
+
+ // The guard must key on "this step produced nothing", not "the run produced
+ // no text". A task whose only deliverable is a tool side effect — here a
+ // provider-executed tool, so no continuation step is owed — legitimately
+ // ends without any assistant prose and must stay green.
+ lines := strings.Join([]string{
+ `{"type":"step_start","timestamp":1000,"sessionID":"ses_toolonly","part":{"type":"step-start"}}`,
+ `{"type":"tool_use","timestamp":1001,"sessionID":"ses_toolonly","part":{"type":"tool","tool":"web_search","callID":"call_1","metadata":{"providerExecuted":true},"state":{"status":"completed","input":{"query":"weather"},"output":"sunny"}}}`,
+ `{"type":"step_finish","timestamp":1002,"sessionID":"ses_toolonly","part":{"type":"step-finish","reason":"stop","tokens":{"input":0,"output":0,"cache":{"write":0,"read":0}}}}`,
+ }, "\n")
+
+ result := b.processEvents(strings.NewReader(lines), ch)
+
+ if result.status != "completed" {
+ t.Errorf("status: got %q, want %q (a tool call is a productive step)", result.status, "completed")
+ }
+ if result.errMsg != "" {
+ t.Errorf("errMsg: got %q, want empty", result.errMsg)
+ }
+
+ close(ch)
+}
+
+func TestOpencodeProcessEventsUsageOnlyFinalStepStaysCompleted(t *testing.T) {
+ t.Parallel()
+
+ // A step that emitted neither text nor a tool call but reports usage did
+ // reach the provider, so it is not the zero-round-trip shape the guard
+ // targets and must stay green. OpenCode reports reasoning and the
+ // aggregate total in their own fields and cost as a sibling of the token
+ // block, so each of them alone has to be enough — a guard that only looked
+ // at input/output would fail these healthy runs.
+ usageCases := []struct {
+ name string
+ final string
+ }{
+ {
+ name: "input only",
+ final: `{"type":"step_finish","timestamp":1005,"sessionID":"ses_usage","part":{"type":"step-finish","reason":"stop","tokens":{"input":950,"output":0,"cache":{"write":0,"read":0}}}}`,
+ },
+ {
+ name: "reasoning only",
+ final: `{"type":"step_finish","timestamp":1005,"sessionID":"ses_usage","part":{"type":"step-finish","reason":"stop","tokens":{"input":0,"output":0,"reasoning":82,"cache":{"write":0,"read":0}}}}`,
+ },
+ {
+ name: "aggregate total only",
+ final: `{"type":"step_finish","timestamp":1005,"sessionID":"ses_usage","part":{"type":"step-finish","reason":"stop","tokens":{"total":14674,"input":0,"output":0,"cache":{"write":0,"read":0}}}}`,
+ },
+ {
+ name: "cost only",
+ final: `{"type":"step_finish","timestamp":1005,"sessionID":"ses_usage","part":{"type":"step-finish","reason":"stop","tokens":{"input":0,"output":0,"cache":{"write":0,"read":0}},"cost":0.0021}}`,
+ },
+ {
+ name: "cache read only",
+ final: `{"type":"step_finish","timestamp":1005,"sessionID":"ses_usage","part":{"type":"step-finish","reason":"stop","tokens":{"input":0,"output":0,"cache":{"write":0,"read":512}}}}`,
+ },
+ }
+
+ for _, tc := range usageCases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ b := &opencodeBackend{cfg: Config{Logger: slog.Default()}}
+ ch := make(chan Message, 256)
+
+ lines := strings.Join([]string{
+ `{"type":"step_start","timestamp":1000,"sessionID":"ses_usage","part":{"type":"step-start"}}`,
+ `{"type":"text","timestamp":1001,"sessionID":"ses_usage","part":{"type":"text","text":"answer"}}`,
+ `{"type":"step_finish","timestamp":1002,"sessionID":"ses_usage","part":{"type":"step-finish","reason":"stop","tokens":{"input":900,"output":40,"cache":{"write":0,"read":0}}}}`,
+ `{"type":"step_start","timestamp":1003,"sessionID":"ses_usage","part":{"type":"step-start"}}`,
+ `{"type":"reasoning","timestamp":1004,"sessionID":"ses_usage","part":{"type":"reasoning","text":"thinking..."}}`,
+ tc.final,
+ }, "\n")
+
+ result := b.processEvents(strings.NewReader(lines), ch)
+
+ if result.status != "completed" {
+ t.Errorf("status: got %q, want %q (reported usage proves the provider round-trip happened)", result.status, "completed")
+ }
+ if result.errMsg != "" {
+ t.Errorf("errMsg: got %q, want empty", result.errMsg)
+ }
+
+ close(ch)
+ })
+ }
+}
+
// ── Windows native-binary resolution tests ──
// fakeStat returns a statFn that reports any path in `present` as existing
diff --git a/server/pkg/taskfailure/classify.go b/server/pkg/taskfailure/classify.go
index 132c82610f..d7728cb9bc 100644
--- a/server/pkg/taskfailure/classify.go
+++ b/server/pkg/taskfailure/classify.go
@@ -178,9 +178,22 @@ func Classify(rawError string) Reason {
// Note this only catches deadlines that arrive as a bare string;
// callers holding the error value should classify structurally
// instead (see taskRunFailureReason in daemon/daemon.go).
+ // "opencode stream ended" is the shared prefix of every failure the
+ // OpenCode terminal-signal guard raises (pkg/agent/opencode.go): a step
+ // left open at EOF, a continuation that never started, and a run that
+ // ended on a step with no text, no tool call and no reported usage.
+ // All three mean the same thing — the provider stream died and
+ // `opencode run` still exited 0 — which is this bucket by definition,
+ // and being resume-safe the retry continues the truncated session
+ // instead of redoing the work. Before this they landed in
+ // agent_error.process_failure (the word "signal" in "terminal signal"
+ // matching rule 13 by accident) and agent_error.unknown respectively;
+ // neither is on the retry allowlist, so a transient cut ended the task
+ // outright and max_attempts never applied (#6522).
// Mirror these substrings into the MUL-1949 offline backfill SQL.
case containsAny(lower,
"stream disconnected",
+ opencodeStreamEndedPrefix,
"connection closed",
"mid-response",
"error sending request",
@@ -320,6 +333,29 @@ var legacyContextOverflowReasons = map[string]bool{
"agent_error": true,
}
+// opencodeStreamEndedPrefix opens every failure the OpenCode terminal-signal
+// guard raises (pkg/agent/opencode.go). Exactly one code path emits it, and it
+// is a PREFIX of the whole error rather than a phrase somewhere inside it, so
+// its presence identifies the failure outright.
+const opencodeStreamEndedPrefix = "opencode stream ended"
+
+// legacyOpencodeStreamEndedReasons are the buckets a daemon predating rule 7's
+// entry lands these errors in: process_failure for the two "terminal signal"
+// variants, whose word "signal" its rule 13 matches by accident, unknown for
+// anything its rules miss, and the pre-MUL-1949 coarse agent_error.
+//
+// Wider than legacyContextOverflowReasons on purpose, and the witness is why.
+// That rule leaves refined reasons alone because a phrase appearing somewhere
+// in an error blob says less than the bucket an earlier rule already picked.
+// Here the witness is the guard's own message from its first character, so the
+// old bucket cannot be describing some other, better-identified cause — it is
+// the same failure under a label that predates knowing what it was.
+var legacyOpencodeStreamEndedReasons = map[string]bool{
+ string(ReasonAgentProcessFailure): true,
+ string(ReasonAgentUnknown): true,
+ "agent_error": true,
+}
+
// NormalizeDaemonReason upgrades a failure_reason reported by an older daemon
// onto the taxonomy this server understands, using the raw error text as the
// witness. It returns the reason unchanged when nothing applies.
@@ -352,6 +388,18 @@ func NormalizeDaemonReason(reason, rawError string) Reason {
containsAny(strings.ToLower(rawError), contextWindowExceededWitnesses...) {
return ReasonAgentContextOverflow
}
+ // #6522: the same gap once more. Rule 7 only decides where these land when
+ // THIS server classifies them, and it classifies only when the daemon sent
+ // no reason at all. An installed daemon predating that entry reports a
+ // non-empty agent_error.process_failure instead, which the empty-reason
+ // branch in FailTask deliberately skips — so the run stays off the retry
+ // allowlist on exactly the un-upgraded hosts most likely to be hitting a
+ // flaky provider. Upgrading here makes the retry work the moment the server
+ // deploys, without waiting on the daemon fleet.
+ if legacyOpencodeStreamEndedReasons[reason] &&
+ strings.HasPrefix(strings.ToLower(strings.TrimSpace(rawError)), opencodeStreamEndedPrefix) {
+ return ReasonAgentProviderNetwork
+ }
return Reason(reason)
}
diff --git a/server/pkg/taskfailure/classify_test.go b/server/pkg/taskfailure/classify_test.go
index 487f7f5496..1ca35d8294 100644
--- a/server/pkg/taskfailure/classify_test.go
+++ b/server/pkg/taskfailure/classify_test.go
@@ -113,6 +113,14 @@ func TestClassifyRules(t *testing.T) {
{"context deadline exceeded", "context deadline exceeded", ReasonAgentProviderNetwork},
{"wrapped context deadline", `Post "https://api.example.com/v1": context deadline exceeded`, ReasonAgentProviderNetwork},
{"http client timeout", `Get "https://api.example.com": net/http: request canceled (Client.Timeout exceeded while awaiting headers)`, ReasonAgentProviderNetwork},
+ // #6522: all three OpenCode terminal-signal guard failures are silent
+ // provider stream cuts. The two "terminal signal" variants used to hit
+ // rule 13 by accident (the word "signal") and the empty-step one fell
+ // to agent_error.unknown; neither bucket is retryable.
+ {"opencode step open at EOF", "opencode stream ended without a terminal signal (step still open at EOF)", ReasonAgentProviderNetwork},
+ {"opencode continuation never started", "opencode stream ended without a terminal signal (last step required a continuation that never started)", ReasonAgentProviderNetwork},
+ {"opencode empty final step", "opencode stream ended on an empty step (no text, no tool call, no reported usage) — the provider produced nothing", ReasonAgentProviderNetwork},
+ {"opencode empty step with process exit appended", "opencode stream ended on an empty step (no text, no tool call, no reported usage) — the provider produced nothing; opencode exited with error: exit status 1", ReasonAgentProviderNetwork},
// 8. Model not found / unavailable.
{"model not found", "Error: model claude-3-opus-99 not found", ReasonAgentModelNotFoundOrUnavailable},