Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(comments): preserve direct parent on replies (#3579)
Naiyuan Qing4ae4722ef080
diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.goindex aeb5e44866..bcaf2c6a20 100644--- a/server/internal/daemon/execenv/execenv_test.go+++ b/server/internal/daemon/execenv/execenv_test.go@@ -3442,8 +3442,9 @@ func TestInjectRuntimeConfigCommentTriggerResumedNoDeltaRead(t *testing.T) {for _, want := range []string{"triggering comment is already included above","No other new comments on this issue since your last run",- "Do not re-read comment history by default",- "Only if the resumed session is missing thread context",+ "triggering comment ID / thread anchor",+ "If your reply depends on thread context",+ "do not rely only on resumed session memory","multica issue comment list " + issueID + " --thread " + triggerID + " --tail 30 --output json",} {if !strings.Contains(s, want) {diff --git a/server/internal/daemon/execenv/reply_instructions.go b/server/internal/daemon/execenv/reply_instructions.goindex 20283d7957..67a2d1e614 100644--- a/server/internal/daemon/execenv/reply_instructions.go+++ b/server/internal/daemon/execenv/reply_instructions.go@@ -54,10 +54,10 @@ func BuildNewCommentsHint(issueID, triggerCommentID, newCommentsSince string, ne// no-delta path: the daemon is resuming a prior provider session and the// triggering comment body has already been injected into the per-turn prompt.// newCommentCount == 0 here means no new comments arrived issue-wide since the-// last run (beyond the injected trigger and the agent's own replies), so-// re-reading comment history is duplicate work by default. Keep the bounded-// triggering-thread read as an explicit fallback for missing context instead of-// making it the first action.+// last run (beyond the injected trigger and the agent's own replies). Keep the+// read bounded and conditional, but make it explicit that context-dependent+// replies should refresh the triggering conversation rather than trusting+// resumed memory alone.func BuildResumedCommentsHint(issueID, triggerCommentID string) string {if issueID == "" || triggerCommentID == "" {return ""@@ -65,10 +65,11 @@ func BuildResumedCommentsHint(issueID, triggerCommentID string) string {return fmt.Sprintf("You're resuming the prior session, and the triggering comment is already included above. "+"No other new comments on this issue since your last run. "+- "Do not re-read comment history by default. "+- "Only if the resumed session is missing thread context, pull the triggering conversation: "++ "Use the triggering comment ID / thread anchor: `%s`. "++ "If your reply depends on thread context, do not rely only on resumed session memory — "++ "first pull the triggering conversation with: "+"`multica issue comment list %s --thread %s --tail 30 --output json`.\n\n",- issueID, triggerCommentID,+ triggerCommentID, issueID, triggerCommentID,)}diff --git a/server/internal/daemon/execenv/runtime_config_test.go b/server/internal/daemon/execenv/runtime_config_test.goindex a45ea8a360..38cff217d2 100644--- a/server/internal/daemon/execenv/runtime_config_test.go+++ b/server/internal/daemon/execenv/runtime_config_test.go@@ -237,8 +237,9 @@ func TestCommentTriggeredBriefResumedNoDeltaSkipsDefaultThreadRead(t *testing.T)for _, want := range []string{"triggering comment is already included above","No other new comments on this issue since your last run",- "Do not re-read comment history by default",- "Only if the resumed session is missing thread context",+ "triggering comment ID / thread anchor",+ "If your reply depends on thread context",+ "do not rely only on resumed session memory","multica issue comment list " + issueID + " --thread trigger-1 --tail 30 --output json",} {if !strings.Contains(out, want) {diff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.goindex de667d5740..825c0ab5e7 100644--- a/server/internal/daemon/prompt_test.go+++ b/server/internal/daemon/prompt_test.go@@ -385,8 +385,9 @@ func TestBuildPromptResumedNoDeltaDoesNotForceThreadRead(t *testing.T) {for _, want := range []string{"triggering comment is already included above","No other new comments on this issue since your last run",- "Do not re-read comment history by default",- "Only if the resumed session is missing thread context",+ "triggering comment ID / thread anchor",+ "If your reply depends on thread context",+ "do not rely only on resumed session memory","multica issue comment list " + issueID + " --thread trigger-1 --tail 30 --output json",} {if !strings.Contains(out, want) {diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex b5d7dacde2..6694869e54 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -871,20 +871,17 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {// entity-encode Markdown syntax characters (>, ", &, <) and corrupt the// source. See issue #1303 / discussion in MUL-1119, MUL-1125.- // Collapse parent_id to the thread root before storing so the comment tree- // never exceeds depth 1 (the 2-level model the product and UI assume — see- // GetThreadRoot). The agent-drift guard above already compared the *raw*- // parent_id to the task's trigger comment, so normalization happens only- // here, after that check. We also repoint parentComment at the root so the- // downstream thread-aware steps (AutoUnresolveThreadOnReply,- // isReplyToMemberThread) act on the thread root, not an interior reply.+ // parent_id stores the exact comment being replied to. Thread-level behavior+ // (for example auto-unresolving a resolved thread) resolves the root+ // separately so storing a reply-to-reply does not destroy the direct-parent+ // signal used by trigger decisions.+ var rootComment *db.Commentif parentID.Valid {if root, err := h.Queries.GetThreadRoot(r.Context(), db.GetThreadRootParams{CommentID: parentID,WorkspaceID: issue.WorkspaceID,}); err == nil {- parentID = root.ID- parentComment = &root+ rootComment = &root}}@@ -924,7 +921,7 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {// so the reply is visible regardless of the unresolve outcome. Shared with// the agent task path (TaskService.createAgentComment) — both reply paths// must keep the resolved root in sync.- h.TaskService.AutoUnresolveThreadOnReply(r.Context(), parentComment, uuidToString(issue.WorkspaceID), authorType, authorID)+ h.TaskService.AutoUnresolveThreadOnReply(r.Context(), rootComment, uuidToString(issue.WorkspaceID), authorType, authorID)h.triggerTasksForComment(r.Context(), issue, comment, parentComment, authorType, authorID)diff --git a/server/internal/handler/comment_list_test.go b/server/internal/handler/comment_list_test.goindex 4c2b948135..9cc404efd2 100644--- a/server/internal/handler/comment_list_test.go+++ b/server/internal/handler/comment_list_test.go@@ -1376,13 +1376,11 @@ func TestCountNewCommentsSince_IssueWideExcludesAgentOwnAndTrigger(t *testing.T)}}-// TestCreateCommentNormalizesParentToThreadRoot pins the write-boundary-// invariant: a reply created through CreateComment is always stored with its-// parent_id pointing at the THREAD ROOT, never at an interior reply. This keeps-// the comment tree at depth 1 (the 2-level model the product/UI assume), so-// readers can treat a reply's parent_id AS its thread root. We post a reply to a-// reply and assert the stored parent collapses to the root, not the middle row.-func TestCreateCommentNormalizesParentToThreadRoot(t *testing.T) {+// TestCreateCommentPreservesDirectParent pins the write-boundary invariant:+// parent_id stores the exact comment being replied to. Thread readers discover+// the root separately via recursive queries, so storing a reply-to-reply must+// not destroy the direct-parent signal that trigger logic needs.+func TestCreateCommentPreservesDirectParent(t *testing.T) {if testHandler == nil || testPool == nil {t.Skip("requires DB")}@@ -1393,7 +1391,7 @@ func TestCreateCommentNormalizesParentToThreadRoot(t *testing.T) {INSERT INTO issue (workspace_id, creator_type, creator_id, title)VALUES ($1, 'member', $2, $3)RETURNING id- `, testWorkspaceID, testUserID, "parent normalization fixture").Scan(&issueID); err != nil {+ `, testWorkspaceID, testUserID, "direct parent fixture").Scan(&issueID); err != nil {t.Fatalf("create issue: %v", err)}t.Cleanup(func() {@@ -1431,10 +1429,11 @@ func TestCreateCommentNormalizesParentToThreadRoot(t *testing.T) {t.Fatalf("direct reply parent_id: want root %s, got %v", root.ID, reply.ParentID)}- // A reply whose parent is itself a reply must collapse to the thread root,- // NOT stay pointed at the interior reply — this is the write-boundary fix.+ // A reply whose parent is itself a reply must keep that direct parent. The+ // thread root is recoverable through recursive thread reads; the direct+ // parent is not recoverable once overwritten.nested := create(reply.ID, "nested")- if nested.ParentID == nil || *nested.ParentID != root.ID {- t.Fatalf("reply-to-reply parent_id: want collapsed to root %s, got %v (must not be the interior reply %s)", root.ID, nested.ParentID, reply.ID)+ if nested.ParentID == nil || *nested.ParentID != reply.ID {+ t.Fatalf("reply-to-reply parent_id: want direct parent %s, got %v (root was %s)", reply.ID, nested.ParentID, root.ID)}}diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.goindex c4ea6d8da9..e81f503ae9 100644--- a/server/internal/handler/handler_test.go+++ b/server/internal/handler/handler_test.go@@ -3210,6 +3210,196 @@ func TestMemberReplyToAgentRootDoesNotInheritParentMentions(t *testing.T) {}}+// TestNestedMemberReplyUsesDirectParentForMentionInheritance is the regression+// for parent-root write normalization leaking root mentions into plain nested+// replies. Stored parent_id keeps the direct parent, and trigger logic evaluates+// that direct parent rather than the thread root.+func TestNestedMemberReplyUsesDirectParentForMentionInheritance(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ assigneeAgent := createHandlerTestAgent(t, "Nested Mention Assignee", nil)+ mentionedAgent := createHandlerTestAgent(t, "Nested Mention Target", nil)++ var number int+ if err := testPool.QueryRow(ctx, `+ UPDATE workspace+ SET issue_counter = GREATEST(issue_counter, (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)) + 1+ WHERE id = $1 RETURNING issue_counter+ `, testWorkspaceID).Scan(&number); err != nil {+ t.Fatalf("next issue number: %v", err)+ }++ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, creator_type, creator_id, title, assignee_type, assignee_id, number)+ VALUES ($1, 'member', $2, $3, 'agent', $4, $5)+ RETURNING id+ `, testWorkspaceID, testUserID, "nested mention inheritance regression", assigneeAgent, number).Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)+ testPool.Exec(context.Background(), `DELETE FROM comment WHERE issue_id = $1`, issueID)+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)+ })++ countQueued := func(agentID string) int {+ t.Helper()+ var n int+ if err := testPool.QueryRow(ctx, `+ SELECT count(*) FROM agent_task_queue+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'+ `, issueID, agentID).Scan(&n); err != nil {+ t.Fatalf("count queued tasks: %v", err)+ }+ return n+ }+ postMemberComment := func(body map[string]any) CommentResponse {+ t.Helper()+ w := httptest.NewRecorder()+ r := newRequest("POST", "/api/issues/"+issueID+"/comments", body)+ r = withURLParam(r, "id", issueID)+ testHandler.CreateComment(w, r)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateComment: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var resp CommentResponse+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode comment response: %v", err)+ }+ return resp+ }++ root := postMemberComment(map[string]any{+ "content": fmt.Sprintf("[@Mentioned](mention://agent/%s) please look", mentionedAgent),+ })+ if got := countQueued(mentionedAgent); got != 1 {+ t.Fatalf("expected root mention to queue mentioned agent once, got %d", got)+ }+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'cancelled' WHERE issue_id = $1`, issueID); err != nil {+ t.Fatalf("cancel root mention task: %v", err)+ }++ var directParentID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content, parent_id)+ VALUES ($1, $2, 'agent', $3, $4, $5)+ RETURNING id+ `, testWorkspaceID, issueID, mentionedAgent, "looks like redirect config", root.ID).Scan(&directParentID); err != nil {+ t.Fatalf("insert direct parent reply: %v", err)+ }++ nested := postMemberComment(map[string]any{+ "content": "can you also check session expiry?",+ "parent_id": directParentID,+ })+ if nested.ParentID == nil || *nested.ParentID != directParentID {+ t.Fatalf("stored nested reply parent_id should keep direct parent %s, got %v", directParentID, nested.ParentID)+ }+ if got := countQueued(mentionedAgent); got != 0 {+ t.Fatalf("plain nested reply must not inherit root mention from non-direct parent; got %d queued tasks", got)+ }+}++// TestNestedMemberReplyUsesDirectParentForAssigneeParticipation is the+// regression for treating any prior agent reply in the root thread as direct+// participation in a nested human sub-thread.+func TestNestedMemberReplyUsesDirectParentForAssigneeParticipation(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ assigneeAgent := createHandlerTestAgent(t, "Nested Participation Assignee", nil)++ var number int+ if err := testPool.QueryRow(ctx, `+ UPDATE workspace+ SET issue_counter = GREATEST(issue_counter, (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)) + 1+ WHERE id = $1 RETURNING issue_counter+ `, testWorkspaceID).Scan(&number); err != nil {+ t.Fatalf("next issue number: %v", err)+ }++ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, creator_type, creator_id, title, assignee_type, assignee_id, number)+ VALUES ($1, 'member', $2, $3, 'agent', $4, $5)+ RETURNING id+ `, testWorkspaceID, testUserID, "nested participation regression", assigneeAgent, number).Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)+ testPool.Exec(context.Background(), `DELETE FROM comment WHERE issue_id = $1`, issueID)+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)+ })++ countAssigneeQueued := func() int {+ t.Helper()+ var n int+ if err := testPool.QueryRow(ctx, `+ SELECT count(*) FROM agent_task_queue+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'+ `, issueID, assigneeAgent).Scan(&n); err != nil {+ t.Fatalf("count queued tasks: %v", err)+ }+ return n+ }+ postMemberComment := func(body map[string]any) CommentResponse {+ t.Helper()+ w := httptest.NewRecorder()+ r := newRequest("POST", "/api/issues/"+issueID+"/comments", body)+ r = withURLParam(r, "id", issueID)+ testHandler.CreateComment(w, r)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateComment: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var resp CommentResponse+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode comment response: %v", err)+ }+ return resp+ }++ var rootID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content)+ VALUES ($1, $2, 'member', $3, 'this cache question is for humans')+ RETURNING id+ `, testWorkspaceID, issueID, testUserID).Scan(&rootID); err != nil {+ t.Fatalf("insert root comment: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content, parent_id)+ VALUES ($1, $2, 'agent', $3, 'expiration policy is the issue', $4)+ `, testWorkspaceID, issueID, assigneeAgent, rootID); err != nil {+ t.Fatalf("insert assignee reply: %v", err)+ }+ var humanParentID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content, parent_id)+ VALUES ($1, $2, 'member', $3, 'I have seen this too', $4)+ RETURNING id+ `, testWorkspaceID, issueID, testUserID, rootID).Scan(&humanParentID); err != nil {+ t.Fatalf("insert human direct parent: %v", err)+ }++ nested := postMemberComment(map[string]any{+ "content": "what should the expiration be?",+ "parent_id": humanParentID,+ })+ if nested.ParentID == nil || *nested.ParentID != humanParentID {+ t.Fatalf("stored nested reply parent_id should keep direct parent %s, got %v", humanParentID, nested.ParentID)+ }+ if got := countAssigneeQueued(); got != 0 {+ t.Fatalf("plain nested human reply must not wake assignee just because assignee replied elsewhere under root; got %d queued tasks", got)+ }+}+// TestAgentExplicitMentionStillTriggers documents the boundary the structural// fix preserves: suppressing implicit parent-mention inheritance for agent// authors does NOT block deliberate handoffs. An agent that explicitlydiff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 158770855b..6ccfa4c5e2 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -1926,12 +1926,9 @@ func (s *TaskService) createAgentComment(ctx context.Context, issueID, agentID pif err != nil {return}- // Resolve thread root: collapse parentID to the top-level thread root so the- // comment tree never exceeds depth 1 (the 2-level model the product and UI- // assume — see GetThreadRoot). GetThreadRoot walks parent_id all the way to- // the root, so this stays correct even if a reply-to-a-reply ever reached the- // store. rootComment captures the root row so we can auto-unresolve it after- // the reply is committed (see AutoUnresolveThreadOnReply).+ // Resolve the thread root for thread-level side effects without overwriting+ // parentID. The stored parent_id must remain the exact comment being replied+ // to; recursive thread reads recover the root when needed.var rootComment *db.Commentif parentID.Valid {if root, err := s.Queries.GetThreadRoot(ctx, db.GetThreadRootParams{@@ -1939,7 +1936,6 @@ func (s *TaskService) createAgentComment(ctx context.Context, issueID, agentID pWorkspaceID: issue.WorkspaceID,}); err == nil {rootComment = &root- parentID = root.ID}}// Expand bare issue identifiers (e.g. MUL-117) into mention links.diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.goindex 449b154589..2785792c08 100644--- a/server/pkg/db/generated/comment.sql.go+++ b/server/pkg/db/generated/comment.sql.go@@ -204,12 +204,9 @@ type GetThreadRootParams struct {// Returns the thread-root comment for @comment_id by walking parent_id up to// the row whose parent_id IS NULL. For a root comment it returns that comment-// itself. Used at the write boundary to flatten replies: every new reply stores-// the thread root as its parent_id, so the comment tree never exceeds depth 1.-// This enforces the 2-level threading model the product and UI already assume-// (a root + a flat list of replies, like Linear/Slack) at insert time, so every-// reader can treat a reply's parent_id AS its thread root without re-walking the-// tree. Cycle-safe under the PK constraint (a comment cannot be its own ancestor).+// itself. Used when callers need thread-level behavior while parent_id remains+// the exact direct parent of a reply. Cycle-safe under the PK constraint (a+// comment cannot be its own ancestor).func (q *Queries) GetThreadRoot(ctx context.Context, arg GetThreadRootParams) (Comment, error) {row := q.db.QueryRow(ctx, getThreadRoot, arg.CommentID, arg.WorkspaceID)var i Comment@@ -806,10 +803,9 @@ type ListThreadCommentsForIssueRow struct {}// Returns the root of the thread containing @anchor_id plus every descendant-// (recursive — defends against any future deeper nesting; today's data is two-// layers because the CreateComment path collapses replies to root, but the-// schema does not enforce that). @anchor_id may itself be a root or a reply.-// Output is chronological so it can be fed straight to the agent.+// (recursive — supports real reply-to-reply nesting). @anchor_id may itself be+// a root or any reply in the thread. Output is chronological so it can be fed+// straight to the agent.func (q *Queries) ListThreadCommentsForIssue(ctx context.Context, arg ListThreadCommentsForIssueParams) ([]ListThreadCommentsForIssueRow, error) {rows, err := q.db.Query(ctx, listThreadCommentsForIssue,arg.RowLimit,diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sqlindex 9be748092c..15362cc621 100644--- a/server/pkg/db/queries/comment.sql+++ b/server/pkg/db/queries/comment.sql@@ -113,10 +113,9 @@ ORDER BY c.created_at ASC, c.id ASC;-- name: ListThreadCommentsForIssue :many-- Returns the root of the thread containing @anchor_id plus every descendant--- (recursive — defends against any future deeper nesting; today's data is two--- layers because the CreateComment path collapses replies to root, but the--- schema does not enforce that). @anchor_id may itself be a root or a reply.--- Output is chronological so it can be fed straight to the agent.+-- (recursive — supports real reply-to-reply nesting). @anchor_id may itself be+-- a root or any reply in the thread. Output is chronological so it can be fed+-- straight to the agent.WITH RECURSIVE root_of AS (-- Walk up from the anchor until parent_id IS NULL.SELECT c.id, c.parent_id@@ -324,12 +323,9 @@ WHERE id = $1 AND workspace_id = $2;-- name: GetThreadRoot :one-- Returns the thread-root comment for @comment_id by walking parent_id up to-- the row whose parent_id IS NULL. For a root comment it returns that comment--- itself. Used at the write boundary to flatten replies: every new reply stores--- the thread root as its parent_id, so the comment tree never exceeds depth 1.--- This enforces the 2-level threading model the product and UI already assume--- (a root + a flat list of replies, like Linear/Slack) at insert time, so every--- reader can treat a reply's parent_id AS its thread root without re-walking the--- tree. Cycle-safe under the PK constraint (a comment cannot be its own ancestor).+-- itself. Used when callers need thread-level behavior while parent_id remains+-- the exact direct parent of a reply. Cycle-safe under the PK constraint (a+-- comment cannot be its own ancestor).WITH RECURSIVE root_of AS (SELECT c.id, c.parent_idFROM comment c