Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7359 perf(runtime): avoid echoing final comment bodies (#8390)
importcppb62cce56dab6
diff --git a/server/cmd/multica/cmd_comment_receipt_test.go b/server/cmd/multica/cmd_comment_receipt_test.gonew file mode 100644index 0000000000..379d1ed257--- /dev/null+++ b/server/cmd/multica/cmd_comment_receipt_test.go@@ -0,0 +1,135 @@+package main++import (+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "os"+ "strings"+ "sync/atomic"+ "testing"++ "github.com/multica-ai/multica/server/internal/daemon/execenv"+)++// Execute the rendered reply command's flags against the real CLI handler.+// The receipt must stay small without changing what reaches the comment API.+func TestCommentReplyReceipt(t *testing.T) {+ const issueID = "11111111-1111-4111-8111-111111111111"+ const parentID = "22222222-2222-4222-8222-222222222222"+ body := strings.Repeat("PASS regression\n", 4096) + "验收通过;integration verification pending."+ for _, mode := range []string{"suggested", "json"} {+ for _, status := range []int{http.StatusCreated, http.StatusForbidden} {+ name := mode + "/" + http.StatusText(status)+ t.Run(name, func(t *testing.T) {+ t.Chdir(t.TempDir())+ if err := os.WriteFile("reply.md", []byte(body), 0600); err != nil {+ t.Fatal(err)+ }+ var posts atomic.Int32+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/api/issues/"+issueID:+ if err := json.NewEncoder(w).Encode(map[string]any{"id": issueID, "identifier": "TST-1"}); err != nil {+ t.Error(err)+ }+ case r.Method == http.MethodPost && r.URL.Path == "/api/issues/"+issueID+"/comments":+ posts.Add(1)+ var submitted map[string]any+ if err := json.NewDecoder(r.Body).Decode(&submitted); err != nil {+ t.Error(err)+ w.WriteHeader(http.StatusBadRequest)+ return+ }+ if submitted["content"] != body || submitted["parent_id"] != parentID {+ t.Error("receipt mode changed the submitted body or reply target")+ }+ w.WriteHeader(status)+ response := map[string]any{"error": "forbidden"}+ if status == http.StatusCreated {+ response = map[string]any{"id": "new-comment", "content": body, "parent_id": parentID}+ }+ if err := json.NewEncoder(w).Encode(response); err != nil {+ t.Error(err)+ }+ default:+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)+ w.WriteHeader(http.StatusNotFound)+ }+ }))+ defer srv.Close()+ setCLITestServerEnv(t, srv.URL)+ t.Setenv("MULTICA_TOKEN", "mat_test-token")+ cmd := newIssueCommentAddTestCmd()+ var flags []string+ for _, line := range strings.Split(execenv.BuildCommentReplyInstructions("claude", issueID, parentID, false), "\n") {+ if strings.HasPrefix(strings.TrimSpace(line), "multica issue comment add "+issueID+" ") {+ flags = strings.Fields(line)[5:]+ }+ }+ if len(flags) == 0 {+ t.Fatal("reply instructions contain no posting command")+ }+ if err := cmd.Flags().Parse(flags); err != nil {+ t.Fatal(err)+ }+ if mode == "json" {+ if err := cmd.Flags().Set("output", "json"); err != nil {+ t.Fatal(err)+ }+ }+ // A file avoids blocking on the large JSON receipt's pipe buffer.+ outFile, err := os.CreateTemp(t.TempDir(), "receipt-*")+ if err != nil {+ t.Fatal(err)+ }+ orig := os.Stdout+ t.Cleanup(func() {+ os.Stdout = orig+ if err := outFile.Close(); err != nil {+ t.Error(err)+ }+ })+ os.Stdout = outFile+ stderr := captureStderr(t)+ runErr := runIssueCommentAdd(cmd, []string{issueID})+ os.Stdout = orig+ confirmation := stderr.read()+ if _, err := outFile.Seek(0, io.SeekStart); err != nil {+ t.Fatal(err)+ }+ out, err := io.ReadAll(outFile)+ if err != nil {+ t.Fatal(err)+ }+ if posts.Load() != 1 {+ t.Fatalf("POST count = %d, want exactly one", posts.Load())+ }+ if status == http.StatusForbidden {+ if runErr == nil || strings.Contains(confirmation, "Comment added") || len(out) != 0 {+ t.Fatalf("rejected post did not propagate failure: %v", runErr)+ }+ return+ }+ if runErr != nil || !strings.Contains(confirmation, "Comment added") {+ t.Fatalf("successful post lost confirmation: %v", runErr)+ }+ if mode == "suggested" {+ if len(out) != 0 {+ t.Fatalf("final reply echoed %d stdout bytes instead of only confirming success", len(out))+ }+ } else {+ var result map[string]any+ if err := json.Unmarshal(out, &result); err != nil {+ t.Fatal(err)+ }+ if result["id"] != "new-comment" || result["content"] != body || result["parent_id"] != parentID {+ t.Fatal("explicit JSON lost the returned comment object")+ }+ }+ t.Logf("body_bytes=%d stdout_bytes=%d confirmation_bytes=%d", len(body), len(out), len(confirmation))+ })+ }+ }+}diff --git a/server/internal/daemon/execenv/reply_instructions.go b/server/internal/daemon/execenv/reply_instructions.goindex 80a5faffe8..3014509ea6 100644--- a/server/internal/daemon/execenv/reply_instructions.go+++ b/server/internal/daemon/execenv/reply_instructions.go@@ -249,13 +249,27 @@ func buildCommentReplyInstructionsSlim(provider, issueID, triggerCommentID strinif squadLeader {lead = "Unless your outcome is `no_action`, post your reply as a comment — always use the trigger comment ID below, "}+ // Cleanup is GATED on the post succeeding, never a separate statement.+ // Agents hand the whole snippet to one shell call, and an unconditional+ // cleanup line runs — and SUCCEEDS — after a failed post, so the call's+ // exit status becomes the cleanup's 0. Under `--output table` a failed+ // and a successful post both write nothing to stdout, which leaves the+ // exit status as the only machine-checkable signal; masking it lets an+ // agent end its turn believing an unposted result was delivered. The+ // gate also keeps ./reply.md on disk after a failure, so the retry does+ // not have to regenerate the body.if runtimeGOOS == "windows" {+ // PowerShell 5.1 has no `&&` (it landed in PowerShell 7), so the+ // Windows variant checks $LASTEXITCODE — which carries the exit+ // code of the last NATIVE command — and propagates it instead.return fmt.Sprintf(lead+"do NOT reuse --parent values from previous turns in this session.\n\n"+"Write the body file first — never pipe via `--content-stdin` (PowerShell drops non-ASCII; full rules: ## Comment Formatting above):\n\n"+- " multica issue comment add %s --parent %s --content-file ./reply.md\n"++ " multica issue comment add %s --parent %s --content-file ./reply.md --output table\n"++ " if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }\n"+" Remove-Item ./reply.md\n\n"++ "Do NOT drop the exit-code check: a bare `Remove-Item` after a failed post reports success and deletes the body.\n\n"+"Do NOT write literal `\\n` escapes to simulate line breaks; the file preserves real newlines.\n",issueID, triggerCommentID,)@@ -264,8 +278,8 @@ func buildCommentReplyInstructionsSlim(provider, issueID, triggerCommentID strinlead+"do NOT reuse --parent values from previous turns in this session.\n\n"+"Write the body file first (rules: ## Comment Formatting above — MUL-2904 / #4182):\n\n"+- " multica issue comment add %s --parent %s --content-file ./reply.md\n"+- " rm ./reply.md\n\n"++ " multica issue comment add %s --parent %s --content-file ./reply.md --output table && rm ./reply.md\n\n"++ "Keep the `&&`: as two separate statements a failed post is masked by the cleanup's success, and the body file is deleted.\n\n"+"Do NOT write literal `\\n` escapes to simulate line breaks; the file preserves real newlines.\n",issueID, triggerCommentID,)diff --git a/server/internal/daemon/execenv/reply_instructions_shell_test.go b/server/internal/daemon/execenv/reply_instructions_shell_test.gonew file mode 100644index 0000000000..18c13a1ac7--- /dev/null+++ b/server/internal/daemon/execenv/reply_instructions_shell_test.go@@ -0,0 +1,146 @@+package execenv++import (+ "errors"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strconv"+ "strings"+ "testing"+)++// snippetLines returns the indented command block of a rendered reply+// cookbook — the lines an agent actually pastes into one shell call.+func snippetLines(t *testing.T, rendered string) []string {+ t.Helper()+ var out []string+ for _, line := range strings.Split(rendered, "\n") {+ if strings.HasPrefix(line, " ") && strings.TrimSpace(line) != "" {+ out = append(out, strings.TrimSpace(line))+ }+ }+ if len(out) == 0 {+ t.Fatalf("reply instructions contain no command block\n---\n%s", rendered)+ }+ return out+}++// stubMultica puts a fake `multica` on PATH that exits with the given code, so+// the snippet's failure handling can be exercised without the real CLI (and+// without any network or agent binary — see the default-test rule in+// CLAUDE.md). Returns the directory to prepend to PATH.+//+// The stub's form follows the HOST, not the snippet variant being rendered:+// PowerShell is cross-platform, so the Windows cookbook is exercised on a+// Linux runner too, and there a `.cmd` shim would never resolve.+func stubMultica(t *testing.T, exitCode int) string {+ t.Helper()+ dir := t.TempDir()+ name, body := "multica", "#!/bin/sh\nexit "+strconv.Itoa(exitCode)+"\n"+ if runtime.GOOS == "windows" {+ name, body = "multica.cmd", "@exit /b "+strconv.Itoa(exitCode)+"\r\n"+ }+ if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o755); err != nil {+ t.Fatal(err)+ }+ return dir+}++// runSnippet executes the snippet in a scratch workdir seeded with reply.md+// and reports the invocation's exit code plus whether reply.md survived.+func runSnippet(t *testing.T, shell string, args []string, stubDir string) (int, bool) {+ t.Helper()+ work := t.TempDir()+ body := filepath.Join(work, "reply.md")+ if err := os.WriteFile(body, []byte("final result"), 0o600); err != nil {+ t.Fatal(err)+ }+ cmd := exec.Command(shell, args...)+ cmd.Dir = work+ cmd.Env = append(os.Environ(), "PATH="+stubDir+string(os.PathListSeparator)+os.Getenv("PATH"))+ err := cmd.Run()+ code := 0+ var exitErr *exec.ExitError+ if errors.As(err, &exitErr) {+ code = exitErr.ExitCode()+ } else if err != nil {+ t.Fatalf("run snippet: %v", err)+ }+ _, statErr := os.Stat(body)+ return code, statErr == nil+}++// TestCommentReplySnippetPropagatesPostFailure is the regression guard for the+// receipt change: under `--output table` a failed and a successful post both+// write nothing to stdout, so the shell call's exit status is the only+// machine-checkable signal an agent has. A cleanup command that runs+// unconditionally SUCCEEDS after a failed post and overwrites that status with+// 0, which would let an agent end its turn believing an unposted final result+// was delivered — and would delete the body it would need to retry with.+//+// The assertion is deliberately made by EXECUTING the rendered snippet rather+// than matching its text: the property under test is a shell-composition+// behaviour, and a handler-level test (cmd_comment_receipt_test.go) can only+// prove the command itself returns an error, not that the pasted block+// preserves it.+//+// Not parallel: mutates the package-level runtimeGOOS.+func TestCommentReplySnippetPropagatesPostFailure(t *testing.T) {+ saved := runtimeGOOS+ t.Cleanup(func() { runtimeGOOS = saved })++ const issueID = "11111111-1111-1111-1111-111111111111"+ const triggerID = "22222222-2222-2222-2222-222222222222"++ for _, tc := range []struct {+ name string+ goos string+ shell string+ wrap func(script string) []string+ }{+ {+ name: "posix/sh",+ goos: "linux",+ shell: "sh",+ wrap: func(script string) []string { return []string{"-c", script} },+ },+ {+ // PowerShell is cross-platform, so this exercises the Windows+ // cookbook's $LASTEXITCODE gate wherever pwsh is installed.+ name: "windows/pwsh",+ goos: "windows",+ shell: "pwsh",+ wrap: func(script string) []string { return []string{"-NoProfile", "-Command", script} },+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ if _, err := exec.LookPath(tc.shell); err != nil {+ t.Skipf("%s not available: %v", tc.shell, err)+ }+ runtimeGOOS = tc.goos+ script := strings.Join(snippetLines(t, BuildCommentReplyInstructions("claude", issueID, triggerID, false)), "\n")++ t.Run("failed post keeps the failure and the body", func(t *testing.T) {+ code, bodyKept := runSnippet(t, tc.shell, tc.wrap(script), stubMultica(t, 3))+ if code == 0 {+ t.Errorf("failed post reported success (exit 0); the cleanup masked it\n---\n%s", script)+ }+ if !bodyKept {+ t.Errorf("failed post deleted ./reply.md; the retry would have to regenerate the body\n---\n%s", script)+ }+ })++ t.Run("successful post still cleans up", func(t *testing.T) {+ code, bodyKept := runSnippet(t, tc.shell, tc.wrap(script), stubMultica(t, 0))+ if code != 0 {+ t.Errorf("successful post reported exit %d\n---\n%s", code, script)+ }+ if bodyKept {+ t.Errorf("successful post left ./reply.md behind\n---\n%s", script)+ }+ })+ })+ }+}diff --git a/server/internal/daemon/execenv/reply_instructions_test.go b/server/internal/daemon/execenv/reply_instructions_test.goindex 00ee0d7984..0a4a2da0ea 100644--- a/server/internal/daemon/execenv/reply_instructions_test.go+++ b/server/internal/daemon/execenv/reply_instructions_test.go@@ -29,11 +29,11 @@ func TestBuildCommentReplyInstructionsCodexLinux(t *testing.T) {got := BuildCommentReplyInstructions("codex", issueID, triggerID, false)for _, want := range []string{- "multica issue comment add " + issueID + " --parent " + triggerID + " --content-file ./reply.md",+ "multica issue comment add " + issueID + " --parent " + triggerID + " --content-file ./reply.md --output table && rm ./reply.md","Write the body file first","--content-file ./reply.md","#4182",- "rm ./reply.md",+ "Keep the `&&`","Do NOT write literal `\\n` escapes to simulate line breaks","do NOT reuse --parent values from previous turns",} {@@ -85,14 +85,14 @@ func TestBuildCommentReplyInstructionsNonCodexLinux(t *testing.T) {got := BuildCommentReplyInstructions(provider, issueID, triggerID, false)for _, want := range []string{- "multica issue comment add " + issueID + " --parent " + triggerID + " --content-file ./reply.md",+ "multica issue comment add " + issueID + " --parent " + triggerID + " --content-file ./reply.md --output table && rm ./reply.md",// MUL-5442 cross-channel dedup: shell-hazard mechanics live in// the brief's Comment Formatting; the cookbook keeps the// file-first order, the command, and the pointer."Write the body file first","## Comment Formatting","#4182",- "rm ./reply.md",+ "Keep the `&&`","do NOT reuse --parent values from previous turns","Post your reply as a comment",} {@@ -140,11 +140,12 @@ func TestBuildCommentReplyInstructionsWindowsUsesContentFile(t *testing.T) {t.Run(provider+"/windows", func(t *testing.T) {got := BuildCommentReplyInstructions(provider, issueID, triggerID, false)for _, want := range []string{- "multica issue comment add " + issueID + " --parent " + triggerID + " --content-file",+ "multica issue comment add " + issueID + " --parent " + triggerID + " --content-file ./reply.md --output table",// MUL-5442 cross-channel dedup: the $OutputEncoding trap's// full mechanics live once, in the brief's Windows Comment// Formatting variant; the per-turn cookbook keeps the ban,// the one-line consequence, and the pointer.+ "if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }","Write the body file first","never pipe via `--content-stdin`","PowerShell drops non-ASCII",@@ -302,6 +303,10 @@ func TestInjectRuntimeConfigWindowsAssignmentBriefStaysFileOnly(t *testing.T) {"## Comment Formatting","On Windows, **always write the comment body to a UTF-8 file","do NOT pipe via `--content-stdin`",+ "use `--output table` to confirm success without echoing the body",+ "Use `--output json` instead when you need the returned comment ID, attachment details, or other response fields",+ "Gate the cleanup on the post succeeding",+ "empty stdout alone does not prove success",} {if !strings.Contains(s, want) {t.Errorf("%s missing Windows file-only guidance %q\n---\n%s", fileName, want, s)diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex f7beed7cbc..126e100180 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -379,6 +379,14 @@ func writeIssueBodyFormatting(b *strings.Builder) {b.WriteString("An issue title already serves as its H1. By default, do not add a Markdown H1 (`# ...`) to an issue body or description; start with prose or `##` subheadings. Only add an H1 when the user specifically requests one.\n\n")}+// commentReceiptRule picks the receipt mode for a posting command. It trails+// the file-first guardrail in both OS variants of `## Comment Formatting`:+// the guardrail is the section's correctness red line (a body mangled by the+// shell is a wrong comment), while the receipt mode only decides how much of+// an already-correct comment is echoed back, so it must not displace the+// guardrail from the section lede.+const commentReceiptRule = "For final-result comments, use `--output table` to confirm success without echoing the body. Use `--output json` instead when you need the returned comment ID, attachment details, or other response fields. Gate the cleanup on the post succeeding (`&&`, or an `$LASTEXITCODE` check on Windows): a cleanup command run unconditionally succeeds after a failed post and makes the whole shell call exit 0, and under `--output table` empty stdout alone does not prove success.\n\n"+// writeCommentFormatting emits the cross-platform file-first guardrail.// The Windows branch carries the `$OutputEncoding` rationale: Windows// PowerShell 5.1 defaults $OutputEncoding to ASCII and may replace@@ -388,10 +396,12 @@ func writeIssueBodyFormatting(b *strings.Builder) {func writeCommentFormatting(b *strings.Builder) {b.WriteString("## Comment Formatting\n\n")if runtimeGOOS == "windows" {- b.WriteString("On Windows, **always write the comment body to a UTF-8 file with your file-write tool first, then post it with `--content-file <path>`** — do NOT pipe via `--content-stdin` (Windows PowerShell 5.1's `$OutputEncoding` may replace non-ASCII characters with `?`). Never use inline `--content` for agent-authored comments. Write the file inside your working directory, never `/tmp` or shared paths (MUL-4252). Keep the same `--parent` value from the trigger comment when replying. Delete the temp file (`Remove-Item ./reply.md`) after posting; do not rely on `\\n` escapes.\n\n")+ b.WriteString("On Windows, **always write the comment body to a UTF-8 file with your file-write tool first, then post it with `--content-file <path>`** — do NOT pipe via `--content-stdin` (Windows PowerShell 5.1's `$OutputEncoding` may replace non-ASCII characters with `?`). Never use inline `--content` for agent-authored comments. Write the file inside your working directory, never `/tmp` or shared paths (MUL-4252). Keep the same `--parent` value from the trigger comment when replying. Delete the temp file (`Remove-Item ./reply.md`) only after the post succeeded; do not rely on `\\n` escapes.\n\n")+ b.WriteString(commentReceiptRule)return}- b.WriteString("For issue comments, **always write the comment body to a UTF-8 file with your file-write tool first, then post it with `--content-file <path>`**. Never use inline `--content` for agent-authored comments (MUL-2904); never use `--content-stdin` HEREDOCs alongside other flags (#4182). Write the file inside your working directory, never `/tmp` or shared paths (MUL-4252). Keep the same `--parent` value from the trigger comment when replying; delete the temp file (`rm ./reply.md`) after posting; do not rely on `\\n` escapes.\n\n")+ b.WriteString("For issue comments, **always write the comment body to a UTF-8 file with your file-write tool first, then post it with `--content-file <path>`**. Never use inline `--content` for agent-authored comments (MUL-2904); never use `--content-stdin` HEREDOCs alongside other flags (#4182). Write the file inside your working directory, never `/tmp` or shared paths (MUL-4252). Keep the same `--parent` value from the trigger comment when replying; delete the temp file (`rm ./reply.md`) only after the post succeeded; do not rely on `\\n` escapes.\n\n")+ b.WriteString(commentReceiptRule)}// writeRepositories emits the Repositories section when at least one repo