Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-4860 fix(acp/kiro): GPT-5.6 Sol completion — object rawOutput + positive-proof guard (follow-up to #5511) (#5515)
Multica Evef0d7a444ac3d
diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.goindex 7126b4f15e..c321387487 100644--- a/server/pkg/agent/hermes.go+++ b/server/pkg/agent/hermes.go@@ -1203,8 +1203,8 @@ func (c *hermesClient) handleToolCallUpdate(data json.RawMessage) {RawInput map[string]any `json:"rawInput"`Input map[string]any `json:"input"`Parameters map[string]any `json:"parameters"`- RawOutput string `json:"rawOutput"`- Output string `json:"output"`+ RawOutput json.RawMessage `json:"rawOutput"`+ Output json.RawMessage `json:"output"`Content []json.RawMessage `json:"content"`}if err := json.Unmarshal(data, &msg); err != nil {@@ -1240,9 +1240,9 @@ func (c *hermesClient) handleToolCallUpdate(data json.RawMessage) {pending := c.takePendingTool(msg.ToolCallID)c.emitDeferredToolUse(pending, msg.ToolCallID, title, msg.Kind, rawInput)- output := msg.RawOutput+ output := acpRawText(msg.RawOutput)if output == "" {- output = msg.Output+ output = acpRawText(msg.Output)}if output == "" {output = extractACPToolCallText(msg.Content)@@ -1367,6 +1367,27 @@ func parseToolArgsJSON(argsText string) map[string]any {// as a minimal unified-diff header so the UI distinguishes writes// from reads without needing a diff viewer.//+// acpRawText renders an ACP output field (rawOutput / output) that may arrive+// as either a JSON string or a structured value. Some model adapters — notably+// Kiro's GPT-5.6 Sol path — send the completed tool_call_update's rawOutput as+// an object like {"items":[{"Json":{...}}]} rather than a string. Declaring+// that field as a Go string made json.Unmarshal fail, which made+// handleToolCallUpdate return early and silently DROP the entire update —+// including its status:"completed" — so the completion signal was lost and the+// task was wrongly marked failed (issue #5509 / MUL-4860). Accept both shapes.+func acpRawText(raw json.RawMessage) string {+ if len(raw) == 0 {+ return ""+ }+ var s string+ if err := json.Unmarshal(raw, &s); err == nil {+ return s+ }+ // Non-string (object / array / number): keep the raw JSON as text so the+ // output is preserved rather than discarded.+ return string(raw)+}+// Terminal blocks ({type:"terminal", terminalId}) reference a remote// terminal the client would normally subscribe to via terminal/output;// we don't advertise terminal capability so we never receive those indiff --git a/server/pkg/agent/hermes_test.go b/server/pkg/agent/hermes_test.goindex 7a531bb795..d1eda15921 100644--- a/server/pkg/agent/hermes_test.go+++ b/server/pkg/agent/hermes_test.go@@ -2444,3 +2444,28 @@ func TestStripHermesProfileArgs(t *testing.T) {t.Error("hermesBlockedArgs must not unconditionally strip --profile")}}++// TestACPRawText covers the rawOutput/output shape tolerance added for the+// GPT-5.6 Sol path (#5509): a string is returned verbatim, an object/array is+// preserved as raw JSON text, and empty input yields "".+func TestACPRawText(t *testing.T) {+ t.Parallel()++ tests := []struct {+ name string+ raw string+ want string+ }{+ {"empty", ``, ""},+ {"json null", `null`, ""},+ {"plain string", `"created comment"`, "created comment"},+ {"object (gpt-5.6-sol shape)", `{"items":[{"Json":{"stdout":"ok\n"}}]}`, `{"items":[{"Json":{"stdout":"ok\n"}}]}`},+ {"array", `["a","b"]`, `["a","b"]`},+ }+ for _, tt := range tests {+ got := acpRawText(json.RawMessage(tt.raw))+ if got != tt.want {+ t.Errorf("%s: acpRawText(%q) = %q, want %q", tt.name, tt.raw, got, tt.want)+ }+ }+}diff --git a/server/pkg/agent/kiro.go b/server/pkg/agent/kiro.goindex 1facffaa8e..6875b71173 100644--- a/server/pkg/agent/kiro.go+++ b/server/pkg/agent/kiro.go@@ -108,28 +108,28 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptiovar output strings.Buildervar streamingCurrentTurn atomic.Bool// Completion-preservation state for the -32603 close-handshake guard.- // We track each finish-signalling tool (goal_complete, `multica issue- // comment add`) along three axes so the guard can tell three cases- // apart:- // - saw*Use: we observed the tool being invoked this turn.- // - saw*Result: we observed a terminal ToolResult for it (any status).- // - sawCompleted*: that terminal ToolResult was status=="completed".- // The Claude/Kiro path always emits a completed ToolResult, so- // sawCompleted* is enough there. The GPT-5.6 Sol adapter, however, can- // leave the terminal tool parked at "running" and never emit a- // completed/failed ToolCallUpdate — so no ToolResult is ever produced- // (hermes.handleToolCallUpdate only dispatches on completed/failed).- // For that path we fall back to "saw the use but never saw a result"- // (see the guard below), which stays safe because a genuinely failed- // tool still emits a failed ToolResult and trips saw*Result.- var sawCompletedGoalComplete atomic.Bool- var sawCompletedIssueComment atomic.Bool- var sawGoalCompleteUse atomic.Bool- var sawGoalCompleteResult atomic.Bool- var sawIssueCommentUse atomic.Bool- var sawIssueCommentResult atomic.Bool+ //+ // Kiro raises `session/prompt -32603 "failed to generate a response"`+ // when the model fails to produce its closing turn AFTER the task has+ // already done its work. We keep such a run "completed" only when we+ // have POSITIVE proof the finishing step succeeded — never from the mere+ // absence of a result. A mid-command crash or internal session failure+ // produces the very same "tool use, no result, -32603" shape, and+ // treating that as success would mark a genuinely-unfinished task+ // completed (see the review on #5511 / MUL-4860).+ //+ // The only positive proof available at this layer is a terminal+ // ToolResult with status=="completed" for a finishing tool+ // (goal_complete or `multica issue comment add`). We record the status+ // of the MOST RECENT such result (ordered, keyed per CallID) so a later+ // failed delivery correctly overrides an earlier success — e.g.+ // "progress comment completed → final comment failed → -32603" must stay+ // failed, while "first attempt failed → retry completed → -32603" is a+ // real completion.var goalCompleteCallIDs sync.Mapvar issueCommentCallIDs sync.Map+ var finishingMu sync.Mutex+ var lastFinishingResultStatus string // "", "completed", or "failed"promptDone := make(chan hermesPromptResult, 1)@@ -149,33 +149,29 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptiomsg.Tool = kiroToolNameFromTitle(msg.Tool)if msg.Tool == "goal_complete" && msg.CallID != "" {goalCompleteCallIDs.Store(msg.CallID, struct{}{})- sawGoalCompleteUse.Store(true)}// Recognize `multica issue comment add` by its command// payload regardless of how the adapter titled the tool.// GPT-5.6 Sol may label the shell tool something other than// the aliases kiroToolNameFromTitle folds into "terminal"// (e.g. "execute"/"run"), so gating on msg.Tool=="terminal"- // here would miss it entirely.- if isKiroIssueCommentAddTool(msg) {- sawIssueCommentUse.Store(true)- if msg.CallID != "" {- issueCommentCallIDs.Store(msg.CallID, struct{}{})- }+ // here would miss it entirely (issue #5509). We still require+ // a CallID so the tool use can be correlated to its result.+ if msg.CallID != "" && isKiroIssueCommentAddTool(msg) {+ issueCommentCallIDs.Store(msg.CallID, struct{}{})}}if msg.Type == MessageToolResult {- if _, ok := goalCompleteCallIDs.LoadAndDelete(msg.CallID); ok {- sawGoalCompleteResult.Store(true)- if msg.Status == "completed" {- sawCompletedGoalComplete.Store(true)- }- }- if _, ok := issueCommentCallIDs.LoadAndDelete(msg.CallID); ok {- sawIssueCommentResult.Store(true)- if msg.Status == "completed" {- sawCompletedIssueComment.Store(true)- }+ _, isGoal := goalCompleteCallIDs.LoadAndDelete(msg.CallID)+ _, isComment := issueCommentCallIDs.LoadAndDelete(msg.CallID)+ if isGoal || isComment {+ // Record this finishing tool's terminal outcome. The+ // most recent result wins, so the guard sees the final+ // delivery attempt's status and a later failure+ // overrides an earlier success.+ finishingMu.Lock()+ lastFinishingResultStatus = msg.Status+ finishingMu.Unlock()}}if msg.Type == MessageText {@@ -368,23 +364,18 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio} else {finalStatus = "failed"finalError = fmt.Sprintf("kiro session/prompt failed: %v", err)- // Completion-preservation guard for the -32603 close- // handshake Kiro raises after a task has finished its work.- //- // completedResult — we saw a completed ToolResult for- // goal_complete / comment-add (Claude path).- // useWithoutResult — we saw the finishing tool invoked but- // never saw ANY terminal ToolResult for it- // (GPT-5.6 Sol path: the tool stays parked- // at "running"). We deliberately exclude- // the case where a failed ToolResult DID- // arrive — that is a real failure and must- // stay failed.- completedResult := sawCompletedGoalComplete.Load() || sawCompletedIssueComment.Load()- useWithoutResult := (sawGoalCompleteUse.Load() && !sawGoalCompleteResult.Load()) ||- (sawIssueCommentUse.Load() && !sawIssueCommentResult.Load())- if (completedResult || useWithoutResult) && isKiroGoalCompleteCloseError(err) {- b.cfg.Logger.Warn("kiro session/prompt failed after completed task result; preserving completed task status", "error", err)+ // Preserve completion only on POSITIVE proof: the most+ // recent finishing-tool ToolResult we observed was+ // status=="completed", paired with the specific -32603 close+ // handshake. A missing result is NOT proof — a mid-command+ // crash produces the same result-less shape (Must-fix #1) —+ // and because we key on the most recent outcome, a later+ // failed delivery overrides an earlier success (Must-fix #2).+ finishingMu.Lock()+ lastFinishing := lastFinishingResultStatus+ finishingMu.Unlock()+ if lastFinishing == "completed" && isKiroGoalCompleteCloseError(err) {+ b.cfg.Logger.Warn("kiro session/prompt failed after a completed finishing-tool result; preserving completed task status", "error", err)finalStatus = "completed"finalError = ""} else if opts.ResumeSessionID != "" && isACPSessionNotFound(err) {diff --git a/server/pkg/agent/kiro_test.go b/server/pkg/agent/kiro_test.goindex 116ae532f2..e284567c85 100644--- a/server/pkg/agent/kiro_test.go+++ b/server/pkg/agent/kiro_test.go@@ -449,13 +449,52 @@ func TestKiroIssueCommentAddToolIgnoresToolTitle(t *testing.T) {}}-// fakeKiroACPRunningToolCloseErrorScript reproduces the GPT-5.6 Sol failure-// mode from #5509: the finishing tool is invoked (ToolCall notification) but-// the adapter never emits a completed/failed ToolCallUpdate — the tool stays-// parked at "running", so no ToolResult is ever produced. Kiro then raises the-// -32603 "failed to generate a response" close handshake. `toolName` lets the-// caller pick a title that does NOT normalize to "terminal", and `command`-// selects goal_complete vs comment-add.+// runKiroCloseErrorScript executes a fake-kiro script that ends in the -32603+// close handshake and returns the final Result.+func runKiroCloseErrorScript(t *testing.T, script string) Result {+ t.Helper()+ fakePath := filepath.Join(t.TempDir(), "kiro-cli")+ writeTestExecutable(t, fakePath, []byte(script))++ backend, err := New("kiro", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new kiro backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ session, err := backend.Execute(ctx, "prompt-ignored", 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")+ }+ return result+ case <-time.After(10 * time.Second):+ t.Fatal("timeout waiting for result")+ return Result{}+ }+}++// closeErrorFrame is the -32603 "failed to generate a response" close+// handshake Kiro raises after the task has already finished its work.+const closeErrorFrame = `printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"Internal error","data":"Kiro failed to generate a response"}}\n' "$id"`++// fakeKiroACPRunningToolCloseErrorScript reproduces the GPT-5.6 Sol shape from+// #5509: the finishing tool is invoked (ToolCall notification) but the adapter+// never emits a completed/failed ToolCallUpdate — the tool stays parked at+// "running", so no ToolResult is ever produced. Kiro then raises the -32603+// close handshake. `toolName` picks a title that does NOT normalize to+// "terminal"; `command` selects goal_complete (empty) vs comment-add.func fakeKiroACPRunningToolCloseErrorScript(toolName, command string) string {params := `{}`if command != "" {@@ -469,11 +508,11 @@ while IFS= read -r line; doprintf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true}}}\n' "$id";;*'"method":"session/new"'*)- printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_running_done"}}\n' "$id"+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_running"}}\n' "$id";;*'"method":"session/prompt"'*)- printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_running_done","update":{"type":"ToolCall","toolCallId":"tc-running","name":"` + toolName + `","status":"pending","parameters":` + params + `}}}\n'- printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"Internal error","data":"Kiro failed to generate a response"}}\n' "$id"+ printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_running","update":{"type":"ToolCall","toolCallId":"tc-running","name":"` + toolName + `","status":"pending","parameters":` + params + `}}}\n'+ ` + closeErrorFrame + `exit 0;;esac@@ -481,97 +520,203 @@ done`}-// TestKiroBackendTreatsRunningCommentAddCloseErrorAsCompleted is the primary-// #5509 regression: a `multica issue comment add` shell tool titled with a-// non-terminal name, left at "running" (no completed ToolResult), followed by-// the -32603 close handshake, must be preserved as completed.-func TestKiroBackendTreatsRunningCommentAddCloseErrorAsCompleted(t *testing.T) {+// TestKiroBackendDoesNotCompleteRunningCommentAddWithoutResult is the core+// safety property from the #5511 review (Must-fix #1): a finishing tool that+// was only ever seen invoked — no terminal ToolResult — is NOT proof the work+// succeeded (a mid-command crash produces the same shape). It must stay failed.+func TestKiroBackendDoesNotCompleteRunningCommentAddWithoutResult(t *testing.T) {t.Parallel()- fakePath := filepath.Join(t.TempDir(), "kiro-cli")- writeTestExecutable(t, fakePath, []byte(fakeKiroACPRunningToolCloseErrorScript(+ result := runKiroCloseErrorScript(t, fakeKiroACPRunningToolCloseErrorScript("execute_bash","multica issue comment add issue-1 --content-file ./reply.md",- )))-- backend, err := New("kiro", Config{ExecutablePath: fakePath, Logger: slog.Default()})- if err != nil {- t.Fatalf("new kiro backend: %v", err)+ ))+ if result.Status != "failed" {+ t.Fatalf("expected status=failed for a result-less running comment-add, got %q (error=%q)", result.Status, result.Error)+ }+ if !strings.Contains(result.Error, "Kiro failed to generate a response") {+ t.Fatalf("expected original prompt error to be preserved, got %q", result.Error)}+}- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)- defer cancel()+// TestKiroBackendDoesNotCompleteRunningGoalCompleteWithoutResult is the+// goal_complete sibling of the result-less safety property.+func TestKiroBackendDoesNotCompleteRunningGoalCompleteWithoutResult(t *testing.T) {+ t.Parallel()- session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{Timeout: 5 * time.Second})- if err != nil {- t.Fatalf("execute: %v", err)+ result := runKiroCloseErrorScript(t, fakeKiroACPRunningToolCloseErrorScript("goal_complete", ""))+ if result.Status != "failed" {+ t.Fatalf("expected status=failed for a result-less running goal_complete, got %q (error=%q)", result.Status, result.Error)}- 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 for a running comment-add + close error, got %q (error=%q)", result.Status, result.Error)- }- if result.Error != "" {- t.Fatalf("expected close-handshake error to be suppressed, got %q", result.Error)- }- case <-time.After(10 * time.Second):- t.Fatal("timeout waiting for result")+// fakeKiroACPCompletedToolCloseErrorScript is the positive-proof path: the+// finishing tool emits a completed ToolCallUpdate (the real completion signal)+// before the -32603 close handshake. `toolName` deliberately uses a title that+// does NOT normalize to "terminal" to prove recognition is title-independent.+func fakeKiroACPCompletedToolCloseErrorScript(toolName, command string) string {+ params := `{}`+ if command != "" {+ params = `{"command":"` + command + `"}`}+ return `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true}}}\n' "$id"+ ;;+ *'"method":"session/new"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_completed"}}\n' "$id"+ ;;+ *'"method":"session/prompt"'*)+ printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_completed","update":{"type":"ToolCall","toolCallId":"tc-done","name":"` + toolName + `","status":"pending","parameters":` + params + `}}}\n'+ printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_completed","update":{"type":"ToolCallUpdate","toolCallId":"tc-done","status":"completed","name":"` + toolName + `","output":"ok"}}}\n'+ ` + closeErrorFrame + `+ exit 0+ ;;+ esac+done+`}-// TestKiroBackendTreatsRunningGoalCompleteCloseErrorAsCompleted covers the-// goal_complete sibling of the running-tool path.-func TestKiroBackendTreatsRunningGoalCompleteCloseErrorAsCompleted(t *testing.T) {+// TestKiroBackendTreatsCompletedCommentAddWithNonTerminalTitleAsCompleted is+// the #5509 fix proper: a comment-add whose shell tool is titled with a+// non-terminal name but DID complete (positive proof) must be preserved as+// completed through the -32603 close handshake.+func TestKiroBackendTreatsCompletedCommentAddWithNonTerminalTitleAsCompleted(t *testing.T) {t.Parallel()- fakePath := filepath.Join(t.TempDir(), "kiro-cli")- writeTestExecutable(t, fakePath, []byte(fakeKiroACPRunningToolCloseErrorScript("goal_complete", "")))+ result := runKiroCloseErrorScript(t, fakeKiroACPCompletedToolCloseErrorScript(+ "execute_bash",+ "multica issue comment add issue-1 --content-file ./reply.md",+ ))+ if result.Status != "completed" {+ t.Fatalf("expected status=completed for a completed comment-add + close error, got %q (error=%q)", result.Status, result.Error)+ }+ if result.Error != "" {+ t.Fatalf("expected close-handshake error to be suppressed, got %q", result.Error)+ }+}- backend, err := New("kiro", Config{ExecutablePath: fakePath, Logger: slog.Default()})- if err != nil {- t.Fatalf("new kiro backend: %v", err)+// fakeKiroACPRealGPT56SolCloseErrorScript reproduces the EXACT ACP frame shape+// captured from a live kiro-cli 2.12.3 + gpt-5.6-sol session (see #5509 /+// MUL-4860). Three things about this shape broke the older guards:+// - the shell tool_call title is "Running: <cmd>" with kind "execute", which+// normalizes to "running" — NOT "terminal";+// - the command lives in rawInput.command alongside __tool_use_purpose;+// - the completed tool_call_update sends rawOutput as an OBJECT+// ({"items":[{"Json":{...}}]}), which — when rawOutput was typed as a Go+// string — made json.Unmarshal fail and drop the whole update, status and+// all, so no completion signal ever reached the guard.+//+// Frames use the real wire form: method "session/update" + "sessionUpdate".+func fakeKiroACPRealGPT56SolCloseErrorScript(command string) string {+ return `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true}}}\n' "$id"+ ;;+ *'"method":"session/new"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_real","models":{"currentModelId":"gpt-5.6-sol"}}}\n' "$id"+ ;;+ *'"method":"session/prompt"'*)+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_real","update":{"sessionUpdate":"tool_call","toolCallId":"call_x","title":"Running: ` + command + `","kind":"execute","rawInput":{"command":"` + command + `","__tool_use_purpose":"deliver the final result"},"_meta":{"kiro":{"toolName":"shell"}}}}}\n'+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_real","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_x","content":[{"type":"content","content":{"type":"text","text":"created comment\\n"}}]}}}\n'+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_real","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_x","kind":"execute","status":"completed","title":"Running: ` + command + `","rawInput":{"command":"` + command + `"},"rawOutput":{"items":[{"Json":{"exit_status":"exit status: 0","stdout":"created comment\\n","stderr":""}}]}}}}\n'+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_real","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}}\n'+ ` + closeErrorFrame + `+ exit 0+ ;;+ esac+done+`+}++// TestKiroBackendPreservesCompletionOnRealGPT56SolFrames is the end-to-end+// #5509 regression against the real captured wire shape: a `multica issue+// comment add` run through GPT-5.6 Sol's shell tool (title "Running: ...",+// object rawOutput) that completes, then hits the -32603 close handshake, must+// stay completed. This fails without BOTH the object-rawOutput parse fix in+// hermes.go and the payload-based comment-add recognition in kiro.go.+func TestKiroBackendPreservesCompletionOnRealGPT56SolFrames(t *testing.T) {+ t.Parallel()++ result := runKiroCloseErrorScript(t, fakeKiroACPRealGPT56SolCloseErrorScript(+ "multica issue comment add issue-1 --content-file ./reply.md",+ ))+ if result.Status != "completed" {+ t.Fatalf("expected status=completed for the real GPT-5.6 Sol frame shape, got %q (error=%q)", result.Status, result.Error)}+ if result.Error != "" {+ t.Fatalf("expected close-handshake error to be suppressed, got %q", result.Error)+ }+}- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)- defer cancel()+// fakeKiroACPTwoCommentCloseErrorScript emits two comment-add tool calls with+// distinct CallIDs and configurable terminal statuses (in order), then the+// -32603 close handshake. This exercises ordering: only the most recent+// finishing-tool result should decide completion.+func fakeKiroACPTwoCommentCloseErrorScript(firstStatus, secondStatus string) string {+ return `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true}}}\n' "$id"+ ;;+ *'"method":"session/new"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_two"}}\n' "$id"+ ;;+ *'"method":"session/prompt"'*)+ printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_two","update":{"type":"ToolCall","toolCallId":"tc-1","name":"terminal","status":"pending","parameters":{"command":"multica issue comment add issue-1 --content-file ./progress.md"}}}}\n'+ printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_two","update":{"type":"ToolCallUpdate","toolCallId":"tc-1","status":"` + firstStatus + `","name":"terminal","output":"first"}}}\n'+ printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_two","update":{"type":"ToolCall","toolCallId":"tc-2","name":"terminal","status":"pending","parameters":{"command":"multica issue comment add issue-1 --content-file ./final.md"}}}}\n'+ printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_two","update":{"type":"ToolCallUpdate","toolCallId":"tc-2","status":"` + secondStatus + `","name":"terminal","output":"second"}}}\n'+ ` + closeErrorFrame + `+ exit 0+ ;;+ esac+done+`+}- session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{Timeout: 5 * time.Second})- if err != nil {- t.Fatalf("execute: %v", err)+// TestKiroBackendFailedFinalCommentOverridesEarlierSuccess is the #5511 review+// Must-fix #2: "progress comment completed → final comment failed → -32603"+// must stay failed. An earlier success must not mask a later failure.+func TestKiroBackendFailedFinalCommentOverridesEarlierSuccess(t *testing.T) {+ t.Parallel()++ result := runKiroCloseErrorScript(t, fakeKiroACPTwoCommentCloseErrorScript("completed", "failed"))+ if result.Status != "failed" {+ t.Fatalf("expected status=failed when the final comment failed after an earlier success, got %q (error=%q)", result.Status, result.Error)}- go func() {- for range session.Messages {- }- }()+ if !strings.Contains(result.Error, "Kiro failed to generate a response") {+ t.Fatalf("expected original prompt error to be preserved, got %q", result.Error)+ }+}- 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 for a running goal_complete + close error, got %q (error=%q)", result.Status, result.Error)- }- if result.Error != "" {- t.Fatalf("expected close-handshake error to be suppressed, got %q", result.Error)- }- case <-time.After(10 * time.Second):- t.Fatal("timeout waiting for result")+// TestKiroBackendCompletedRetryAfterEarlierFailureIsCompleted is the reverse+// ordering the review flagged: "first attempt failed → retry completed →+// -32603" is a real completion and must be preserved.+func TestKiroBackendCompletedRetryAfterEarlierFailureIsCompleted(t *testing.T) {+ t.Parallel()++ result := runKiroCloseErrorScript(t, fakeKiroACPTwoCommentCloseErrorScript("failed", "completed"))+ if result.Status != "completed" {+ t.Fatalf("expected status=completed when a retry completed after an earlier failure, got %q (error=%q)", result.Status, result.Error)+ }+ if result.Error != "" {+ t.Fatalf("expected close-handshake error to be suppressed, got %q", result.Error)}}-// fakeKiroACPFailedRunningToolCloseErrorScript is the safety counterpart: the-// finishing tool DID emit a failed ToolResult before the close error. That is-// a genuine failure and must stay failed even though we saw the tool use.-func fakeKiroACPFailedRunningToolCloseErrorScript() string {+// fakeKiroACPFailedCommentAddCloseErrorScript: the finishing tool emits a+// failed ToolResult before the close error — a genuine failure that must stay+// failed.+func fakeKiroACPFailedCommentAddCloseErrorScript() string {return `#!/bin/shwhile IFS= read -r line; doid=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')@@ -580,12 +725,12 @@ while IFS= read -r line; doprintf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true}}}\n' "$id";;*'"method":"session/new"'*)- printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_failed_done"}}\n' "$id"+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_failed"}}\n' "$id";;*'"method":"session/prompt"'*)- printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_failed_done","update":{"type":"ToolCall","toolCallId":"tc-fail","name":"execute_bash","status":"pending","parameters":{"command":"multica issue comment add issue-1 --content-file ./reply.md"}}}}\n'- printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_failed_done","update":{"type":"ToolCallUpdate","toolCallId":"tc-fail","status":"failed","name":"execute_bash","output":"exit status 1"}}}\n'- printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"Internal error","data":"Kiro failed to generate a response"}}\n' "$id"+ printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_failed","update":{"type":"ToolCall","toolCallId":"tc-fail","name":"execute_bash","status":"pending","parameters":{"command":"multica issue comment add issue-1 --content-file ./reply.md"}}}}\n'+ printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_failed","update":{"type":"ToolCallUpdate","toolCallId":"tc-fail","status":"failed","name":"execute_bash","output":"exit status 1"}}}\n'+ ` + closeErrorFrame + `exit 0;;esac@@ -593,13 +738,55 @@ done`}-// TestKiroBackendDoesNotCompleteAfterFailedCommentAddResult guards the-// tradeoff: a failed ToolResult must not be rescued by the running-tool path.+// TestKiroBackendDoesNotCompleteAfterFailedCommentAddResult guards the case+// where the finishing tool explicitly failed: it must stay failed.func TestKiroBackendDoesNotCompleteAfterFailedCommentAddResult(t *testing.T) {t.Parallel()+ result := runKiroCloseErrorScript(t, fakeKiroACPFailedCommentAddCloseErrorScript())+ if result.Status != "failed" {+ t.Fatalf("expected status=failed after a failed comment-add result, got %q (error=%q)", result.Status, result.Error)+ }+ if !strings.Contains(result.Error, "Kiro failed to generate a response") {+ t.Fatalf("expected original prompt error to be preserved, got %q", result.Error)+ }+}++// fakeKiroACPStaleLoadSetModelScript impersonates kiro when a resumed+// session is gone and the caller picked a model: session/load returns+// an empty result (so the requested id is kept), then+// session/set_model rejects the unknown session with kiro's observed+// wording — -32603 with "No session found with id ..." in data.+func fakeKiroACPStaleLoadSetModelScript() string {+ return `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true}}}\n' "$id"+ ;;+ *'"method":"session/load"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"+ ;;+ *'"method":"session/set_model"'*)+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"Internal error","data":"No session found with id ses_stale"}}\n' "$id"+ exit 0+ ;;+ esac+done+`+}++// TestKiroBackendClearsSessionIDWhenSetModelSessionNotFound pins the+// set_model sibling of the resumed-session fix: with a model override,+// session/set_model runs before session/prompt, so a dead resumed+// session surfaces there. The Result must carry an empty SessionID so+// the daemon's fresh-session retry (gated on SessionID == "") fires.+func TestKiroBackendClearsSessionIDWhenSetModelSessionNotFound(t *testing.T) {+ t.Parallel()+fakePath := filepath.Join(t.TempDir(), "kiro-cli")- writeTestExecutable(t, fakePath, []byte(fakeKiroACPFailedRunningToolCloseErrorScript()))+ writeTestExecutable(t, fakePath, []byte(fakeKiroACPStaleLoadSetModelScript()))backend, err := New("kiro", Config{ExecutablePath: fakePath, Logger: slog.Default()})if err != nil {@@ -609,7 +796,11 @@ func TestKiroBackendDoesNotCompleteAfterFailedCommentAddResult(t *testing.T) {ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()- session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{Timeout: 5 * time.Second})+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{+ Timeout: 5 * time.Second,+ ResumeSessionID: "ses_stale",+ Model: "auto",+ })if err != nil {t.Fatalf("execute: %v", err)}@@ -624,22 +815,25 @@ func TestKiroBackendDoesNotCompleteAfterFailedCommentAddResult(t *testing.T) {t.Fatal("result channel closed without a value")}if result.Status != "failed" {- t.Fatalf("expected status=failed after a failed comment-add result, got %q (error=%q)", result.Status, result.Error)+ t.Fatalf("expected status=failed, got %q (error=%q)", result.Status, result.Error)}- if !strings.Contains(result.Error, "Kiro failed to generate a response") {- t.Fatalf("expected original prompt error to be preserved, got %q", result.Error)+ if !strings.Contains(result.Error, `could not switch to model "auto"`) {+ t.Errorf("expected error to name the requested model, got %q", result.Error)+ }+ if result.SessionID != "" {+ t.Errorf("expected empty session id so the daemon's fresh-session retry fires, got %q", result.SessionID)}case <-time.After(10 * time.Second):t.Fatal("timeout waiting for result")}}-// fakeKiroACPStaleLoadSetModelScript impersonates kiro when a resumed-// session is gone and the caller picked a model: session/load returns-// an empty result (so the requested id is kept), then-// session/set_model rejects the unknown session with kiro's observed-// wording — -32603 with "No session found with id ..." in data.-func fakeKiroACPStaleLoadSetModelScript() string {+// fakeKiroACPStalePromptScript impersonates kiro when a resumed session is+// gone and there is NO model override: session/load returns an empty result+// (so the requested id is kept), then session/prompt — not set_model — is the+// call that surfaces the dead session, with kiro's observed -32603 ++// "No session found with id ..." wording.+func fakeKiroACPStalePromptScript() string {return `#!/bin/shwhile IFS= read -r line; doid=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')@@ -650,7 +844,7 @@ while IFS= read -r line; do*'"method":"session/load"'*)printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id";;- *'"method":"session/set_model"'*)+ *'"method":"session/prompt"'*)printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"Internal error","data":"No session found with id ses_stale"}}\n' "$id"exit 0;;@@ -659,16 +853,18 @@ done`}-// TestKiroBackendClearsSessionIDWhenSetModelSessionNotFound pins the-// set_model sibling of the resumed-session fix: with a model override,-// session/set_model runs before session/prompt, so a dead resumed-// session surfaces there. The Result must carry an empty SessionID so-// the daemon's fresh-session retry (gated on SessionID == "") fires.-func TestKiroBackendClearsSessionIDWhenSetModelSessionNotFound(t *testing.T) {+// TestKiroBackendClearsSessionIDWhenPromptSessionNotFound pins the prompt-path+// sibling of the stale-session fix. Without a model override, session/prompt+// (not session/set_model) is where a dead resumed session surfaces. The result+// MUST be failed with an empty SessionID so the daemon's fresh-session retry+// (gated on SessionID == "") fires. A regression in the -32603 guard once+// turned this into status="completed" + a preserved stale SessionID, which+// both faked success and skipped the retry.+func TestKiroBackendClearsSessionIDWhenPromptSessionNotFound(t *testing.T) {t.Parallel()fakePath := filepath.Join(t.TempDir(), "kiro-cli")- writeTestExecutable(t, fakePath, []byte(fakeKiroACPStaleLoadSetModelScript()))+ writeTestExecutable(t, fakePath, []byte(fakeKiroACPStalePromptScript()))backend, err := New("kiro", Config{ExecutablePath: fakePath, Logger: slog.Default()})if err != nil {@@ -681,7 +877,6 @@ func TestKiroBackendClearsSessionIDWhenSetModelSessionNotFound(t *testing.T) {session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{Timeout: 5 * time.Second,ResumeSessionID: "ses_stale",- Model: "auto",})if err != nil {t.Fatalf("execute: %v", err)@@ -697,10 +892,7 @@ func TestKiroBackendClearsSessionIDWhenSetModelSessionNotFound(t *testing.T) {t.Fatal("result channel closed without a value")}if result.Status != "failed" {- t.Fatalf("expected status=failed, got %q (error=%q)", result.Status, result.Error)- }- if !strings.Contains(result.Error, `could not switch to model "auto"`) {- t.Errorf("expected error to name the requested model, got %q", result.Error)+ t.Fatalf("expected status=failed for a stale resumed session at prompt time, got %q (error=%q)", result.Status, result.Error)}if result.SessionID != "" {t.Errorf("expected empty session id so the daemon's fresh-session retry fires, got %q", result.SessionID)