Skip to content

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

Go

MUL-2785: optimize resumed comment reads (#3509)

Multica Eve9616d78e4786
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 1b2edd51de..28c473992d 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -2490,6 +2490,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
TriggerCommentID: task.TriggerCommentID,
NewCommentCount: task.NewCommentCount,
NewCommentsSince: task.NewCommentsSince,
+ PriorSessionResumed: task.PriorSessionID != "",
AgentID: agentID,
AgentName: agentName,
AgentInstructions: instructions,
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index 0fcf25be4e..c0148139b3 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -59,8 +59,9 @@ type PrepareParams struct {
type TaskContextForEnv struct {
IssueID string
TriggerCommentID string // comment that triggered this task (empty for on_assign)
- NewCommentCount int // comments created since this agent's last run on the issue (excludes its own)
+ NewCommentCount int // non-injected comments in the trigger thread since this agent's last run (excludes its own)
NewCommentsSince string // RFC3339 anchor (last run's started_at) the count is measured from; empty on cold start
+ PriorSessionResumed bool // true when the daemon will resume an existing provider session for this task
AgentID string // unique ID of the dispatched agent
AgentName string
AgentInstructions string // agent identity/persona instructions, injected into CLAUDE.md
diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.go
index c2f7efc6e4..8efc6a6d11 100644
--- a/server/internal/daemon/execenv/execenv_test.go
+++ b/server/internal/daemon/execenv/execenv_test.go
@@ -3412,6 +3412,48 @@ func TestInjectRuntimeConfigCommentTriggerColdStartRead(t *testing.T) {
}
}
+// TestInjectRuntimeConfigCommentTriggerResumedNoDeltaRead checks the
+// comment-triggered Workflow when the daemon is resuming a prior session and no
+// since-delta hint is present. In that shape, the agent already has session
+// context and the trigger body is injected in the per-turn prompt, so the
+// runtime brief must not force a duplicate thread read.
+func TestInjectRuntimeConfigCommentTriggerResumedNoDeltaRead(t *testing.T) {
+ t.Parallel()
+
+ const (
+ issueID = "issue-resumed-1"
+ triggerID = "trigger-comment-1"
+ )
+ dir := t.TempDir()
+ ctx := TaskContextForEnv{
+ IssueID: issueID,
+ TriggerCommentID: triggerID,
+ PriorSessionResumed: true,
+ }
+ if _, err := InjectRuntimeConfig(dir, "claude", ctx); err != nil {
+ t.Fatalf("InjectRuntimeConfig failed: %v", err)
+ }
+ data, err := os.ReadFile(filepath.Join(dir, "CLAUDE.md"))
+ if err != nil {
+ t.Fatalf("read CLAUDE.md: %v", err)
+ }
+ s := string(data)
+
+ for _, want := range []string{
+ "triggering comment is already included above",
+ "Do not re-read comment history by default",
+ "Only if the resumed session is missing thread context",
+ "multica issue comment list " + issueID + " --thread " + triggerID + " --tail 30 --output json",
+ } {
+ if !strings.Contains(s, want) {
+ t.Errorf("comment-triggered resumed Workflow missing %q\n---\n%s", want, s)
+ }
+ }
+ if strings.Contains(s, "Read the triggering conversation first") {
+ t.Errorf("resumed workflow must not force the cold-start thread read\n---\n%s", s)
+ }
+}
+
// TestInjectRuntimeConfigAssignmentTriggerMentionsRecent pins that the
// assignment-triggered Workflow keeps full-history reading as the mandatory
// default (the agent must still ingest earlier comments — that rule was
diff --git a/server/internal/daemon/execenv/reply_instructions.go b/server/internal/daemon/execenv/reply_instructions.go
index 3c37284203..3948d6412d 100644
--- a/server/internal/daemon/execenv/reply_instructions.go
+++ b/server/internal/daemon/execenv/reply_instructions.go
@@ -3,44 +3,61 @@ package execenv
import "fmt"
// BuildNewCommentsHint returns the comment-reading pointer for the WARM path —
-// the agent ran on this issue before, so there is a since-anchor. It tells the
-// agent how many comments arrived since its last run and the exact `--since`
-// invocation to fetch just those. It ships only the COUNT and the cursor — never
-// the comment bodies — so the server stays cheap and the agent pulls details on
-// demand.
+// the agent ran on this issue before, so there is a since-anchor. The server
+// count is scoped to the triggering thread and excludes the triggering comment
+// itself because that body is already injected into the prompt. It ships only
+// the COUNT and the cursor — never the comment bodies — so the server stays
+// cheap and the agent pulls details on demand.
//
// Both the per-turn prompt (daemon.buildCommentPrompt) and the CLAUDE.md
// workflow (InjectRuntimeConfig) call this so the two surfaces cannot drift
// (hard requirement from PR #2816).
//
// Renders nothing on cold start (no prior run → newCommentsSince empty) or when
-// there are no new comments (newCommentCount <= 0) or issueID is empty. In those
-// cases the caller falls back to BuildColdCommentsHint.
+// there are no additional thread comments (newCommentCount <= 0) or required
+// IDs are empty. In those cases the caller falls back to BuildResumedCommentsHint
+// (when a prior session is active) or BuildColdCommentsHint.
func BuildNewCommentsHint(issueID, triggerCommentID, newCommentsSince string, newCommentCount int) string {
- if newCommentCount <= 0 || newCommentsSince == "" || issueID == "" {
+ if newCommentCount <= 0 || newCommentsSince == "" || issueID == "" || triggerCommentID == "" {
return ""
}
hint := fmt.Sprintf(
- "%d new comment(s) since your last run. Catch up: "+
- "`multica issue comment list %s --since %s --output json`.\n\n",
- newCommentCount, issueID, newCommentsSince,
+ "%d other new comment(s) in this thread since your last run. "+
+ "The triggering comment is already included above. "+
+ "To inspect the raw thread delta (which may include the injected trigger and agent-authored rows), run: "+
+ "`multica issue comment list %s --thread %s --since %s --output json`.\n\n",
+ newCommentCount, issueID, triggerCommentID, newCommentsSince,
+ )
+ // --thread + --since is still only a delta: it covers new rows in the
+ // triggering thread, not older pre-anchor context. Keep a bounded fallback
+ // when the older conversation context is missing.
+ hint += fmt.Sprintf(
+ "If older thread context before %s is missing, pull the triggering conversation: "+
+ "`multica issue comment list %s --thread %s --tail 30 --output json`.\n\n",
+ newCommentsSince, issueID, triggerCommentID,
)
- // --since is a pure TIME delta: it covers comments newer than the anchor, not
- // the topic. If the triggering comment is a reply in a thread whose earlier
- // history predates the anchor (a thread this run never loaded), --since won't
- // include that context and the resumed session may not hold it either. Point
- // the agent at the full triggering thread so it can pull the conversation
- // behind the trigger on demand.
- if triggerCommentID != "" {
- hint += fmt.Sprintf(
- "If the triggering comment belongs to a thread you haven't read this run, "+
- "pull it in full: `multica issue comment list %s --thread %s --tail 30 --output json`.\n\n",
- issueID, triggerCommentID,
- )
- }
return hint
}
+// BuildResumedCommentsHint returns the comment-reading pointer for the WARM
+// 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.
+// In that shape, reading the triggering thread's last 30 replies is duplicate
+// context by default. Keep the bounded thread read as an explicit fallback for
+// missing context instead of making it the first action.
+func BuildResumedCommentsHint(issueID, triggerCommentID string) string {
+ if issueID == "" || triggerCommentID == "" {
+ return ""
+ }
+ return fmt.Sprintf(
+ "You're resuming the prior session, and the triggering comment is already included above. "+
+ "Do not re-read comment history by default. "+
+ "Only if the resumed session is missing thread context, pull the triggering conversation: "+
+ "`multica issue comment list %s --thread %s --tail 30 --output json`.\n\n",
+ issueID, triggerCommentID,
+ )
+}
+
// BuildColdCommentsHint returns the comment-reading pointer for the COLD path —
// the agent has no prior run on this issue, so there is no since-anchor and
// BuildNewCommentsHint renders nothing. Instead of dumping the whole flat
diff --git a/server/internal/daemon/execenv/runtime_config.go b/server/internal/daemon/execenv/runtime_config.go
index 5d62cebc81..78d30d2df4 100644
--- a/server/internal/daemon/execenv/runtime_config.go
+++ b/server/internal/daemon/execenv/runtime_config.go
@@ -427,7 +427,7 @@ func buildMetaSkillContent(provider string, ctx TaskContextForEnv) string {
b.WriteString("The default brief includes the commands needed for the core agent loop and common issue create/update tasks. For everything else, run `multica --help`, `multica <command> --help`, or `multica <command> <subcommand> --help`; prefer `--output json` when the command supports it.\n\n")
b.WriteString("### Core\n")
b.WriteString("- `multica issue get <id> --output json` — Get full issue details.\n")
- b.WriteString("- `multica issue comment list <issue-id> [--thread <comment-id> [--tail N] | --recent N] [--before <ts> --before-id <uuid>] [--since <RFC3339>] --output json` — List comments on an issue. Default returns the full flat timeline (server cap 2000). On busy issues prefer the thread-aware reads: `--thread <comment-id>` returns one conversation (root + every reply); `--thread <id> --tail N` caps replies to the N most recent (root is always included, even at `--tail 0`); `--recent N` returns the N most recently active threads. `--before` / `--before-id` walks older replies under `--thread --tail` (stderr label: `Next reply cursor`) or older threads under `--recent` (stderr label: `Next thread cursor`). `--since` is for incremental polling and may combine with `--thread --tail` or `--recent`.\n")
+ b.WriteString("- `multica issue comment list <issue-id> [--thread <comment-id> [--tail N] | --recent N] [--before <ts> --before-id <uuid>] [--since <RFC3339>] --output json` — List comments on an issue. Default returns the full flat timeline (server cap 2000). On busy issues prefer the thread-aware reads: `--thread <comment-id>` returns one conversation (root + every reply); `--thread <id> --tail N` caps replies to the N most recent (root is always included, even at `--tail 0`); `--recent N` returns the N most recently active threads. `--before` / `--before-id` walks older replies under `--thread --tail` (stderr label: `Next reply cursor`) or older threads under `--recent` (stderr label: `Next thread cursor`). `--since` is for incremental polling and may combine with `--thread` (with or without `--tail`) or `--recent`.\n")
b.WriteString("- `multica issue create --title \"...\" [--description \"...\" | --description-stdin | --description-file <path>] [--priority X] [--status X] [--assignee X | --assignee-id <uuid>] [--parent <issue-id>] [--project <project-id>] [--due-date <RFC3339>] [--attachment <path>]` — Create a new issue; `--attachment` may be repeated.\n")
b.WriteString("- `multica issue update <id> [--title X] [--description X | --description-stdin | --description-file <path>] [--priority X] [--status X] [--assignee X | --assignee-id <uuid>] [--parent <issue-id>] [--project <project-id>] [--due-date <RFC3339>]` — Update issue fields; use `--parent \"\"` to clear parent.\n")
b.WriteString("- `multica repo checkout <url> [--ref <branch-or-sha>]` — Check out a repository into the working directory (creates a git worktree with a dedicated branch; use `--ref` for review/QA on a specific branch, tag, or commit)\n")
@@ -576,6 +576,8 @@ func buildMetaSkillContent(provider string, ctx TaskContextForEnv) string {
fmt.Fprintf(&b, "2. Run `multica issue metadata list %s --output json` to see what prior agents pinned — best-effort, empty `{}` and CLI failures are normal. See the `## Issue Metadata` section above for what to look for.\n", ctx.IssueID)
if hint := BuildNewCommentsHint(ctx.IssueID, ctx.TriggerCommentID, ctx.NewCommentsSince, ctx.NewCommentCount); hint != "" {
b.WriteString("3. " + hint)
+ } else if ctx.PriorSessionResumed {
+ b.WriteString("3. " + BuildResumedCommentsHint(ctx.IssueID, ctx.TriggerCommentID))
} else if cold := BuildColdCommentsHint(ctx.IssueID, ctx.TriggerCommentID); cold != "" {
b.WriteString("3. " + cold)
} else {
diff --git a/server/internal/daemon/execenv/runtime_config_test.go b/server/internal/daemon/execenv/runtime_config_test.go
index a034215dcc..b3854bcc45 100644
--- a/server/internal/daemon/execenv/runtime_config_test.go
+++ b/server/internal/daemon/execenv/runtime_config_test.go
@@ -156,9 +156,9 @@ func TestCommentTriggeredProtocolDoesNotForceInReview(t *testing.T) {
}
}
-// The CLAUDE.md workflow surface must carry the same since-delta new-comment
-// hint as the per-turn prompt. PR #2816 requires the two surfaces stay in sync,
-// so this pins the count-driven `--since` hint into the comment-triggered brief.
+// The CLAUDE.md workflow surface must carry the same thread-scoped since-delta
+// new-comment hint as the per-turn prompt. PR #2816 requires the two surfaces
+// stay in sync.
func TestCommentTriggeredBriefCarriesNewCommentsHint(t *testing.T) {
t.Parallel()
const (
@@ -173,14 +173,20 @@ func TestCommentTriggeredBriefCarriesNewCommentsHint(t *testing.T) {
}
out := buildMetaSkillContent("claude", ctx)
- if !strings.Contains(out, "4 new comment(s) since your last run") {
+ if !strings.Contains(out, "4 other new comment(s) in this thread since your last run") {
t.Errorf("comment brief must report the new-comment count, got:\n%s", out)
}
- if !strings.Contains(out, "--since "+since+" --output json") {
- t.Errorf("comment brief must point at the --since catch-up read, got:\n%s", out)
+ if !strings.Contains(out, "--thread reply-abc --since "+since+" --output json") {
+ t.Errorf("comment brief must point at the thread-scoped --since catch-up read, got:\n%s", out)
}
- // Warm path also keeps a --thread pointer for the triggering thread's
- // pre-anchor history that --since cannot cover.
+ if !strings.Contains(out, "raw thread delta") {
+ t.Errorf("comment brief must not imply the CLI output exactly matches the count, got:\n%s", out)
+ }
+ if strings.Contains(out, "resumed session is missing older thread context") {
+ t.Errorf("comment brief warm fallback wording must not assume a resumed session, got:\n%s", out)
+ }
+ // Warm path also keeps a bounded full-thread pointer for the triggering
+ // thread's pre-anchor history that --since cannot cover.
if !strings.Contains(out, "--thread reply-abc --tail 30 --output json") {
t.Errorf("warm brief must also point at the triggering thread, got:\n%s", out)
}
@@ -211,6 +217,37 @@ func TestCommentTriggeredBriefColdStartThreadRead(t *testing.T) {
}
}
+// A resumed comment session with no since-delta should not fall back to the
+// cold-start "read the triggering conversation first" instruction. The trigger
+// body is already embedded in the per-turn prompt and the resumed session should
+// carry prior thread context, so the thread read is only a fallback.
+func TestCommentTriggeredBriefResumedNoDeltaSkipsDefaultThreadRead(t *testing.T) {
+ t.Parallel()
+ const issueID = "55555555-6666-7777-8888-999999999999"
+ ctx := TaskContextForEnv{
+ IssueID: issueID,
+ TriggerCommentID: "trigger-1",
+ PriorSessionResumed: true,
+ NewCommentCount: 0,
+ NewCommentsSince: "",
+ }
+ out := buildMetaSkillContent("claude", ctx)
+
+ for _, want := range []string{
+ "triggering comment is already included above",
+ "Do not re-read comment history by default",
+ "Only if the resumed session is missing thread context",
+ "multica issue comment list " + issueID + " --thread trigger-1 --tail 30 --output json",
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("resumed/no-delta brief missing %q\n--- output ---\n%s", want, out)
+ }
+ }
+ if strings.Contains(out, "Read the triggering conversation first") {
+ t.Errorf("resumed/no-delta brief must not use the cold-start forced-read wording, got:\n%s", out)
+ }
+}
+
// Assignment-triggered briefs are the inverse boundary: when the agent
// owns the issue lifecycle, the brief AS A WHOLE must still tell it to
// flip to in_review on completion. The flip lives in the
diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.go
index 8a7ee6e5cc..d1092bd6f3 100644
--- a/server/internal/daemon/prompt.go
+++ b/server/internal/daemon/prompt.go
@@ -159,11 +159,15 @@ func buildCommentPrompt(task Task, provider string) string {
}
}
fmt.Fprintf(&b, "Start by running `multica issue get %s --output json` to understand your task, then decide how to proceed.\n\n", task.IssueID)
- // Comment-reading pointer. Warm path (agent ran here before): since-delta.
- // Cold path (no prior run): read the triggering thread, not the flat timeline.
- // Final fallback (no trigger id, shouldn't happen on this path): plain read.
+ // Comment-reading pointer. Warm path with additional thread comments:
+ // thread-scoped since-delta. Warm resumed path with no additional thread
+ // comments: the trigger is already injected, so don't force a duplicate
+ // thread read. Cold path: read the triggering thread, not the flat timeline.
+ // Final fallback (no trigger id, shouldn't happen here): plain read.
if hint := execenv.BuildNewCommentsHint(task.IssueID, task.TriggerCommentID, task.NewCommentsSince, task.NewCommentCount); hint != "" {
b.WriteString(hint)
+ } else if task.PriorSessionID != "" {
+ b.WriteString(execenv.BuildResumedCommentsHint(task.IssueID, task.TriggerCommentID))
} else if cold := execenv.BuildColdCommentsHint(task.IssueID, task.TriggerCommentID); cold != "" {
b.WriteString(cold)
} else {
diff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.go
index 3f269d6dfa..41605792be 100644
--- a/server/internal/daemon/prompt_test.go
+++ b/server/internal/daemon/prompt_test.go
@@ -299,9 +299,8 @@ func TestBuildPromptNonSquadLeaderNoRule(t *testing.T) {
// TestBuildPromptNewCommentsHint pins that a comment-triggered task whose agent
// ran before on this issue (NewCommentsSince set, NewCommentCount > 0) gets the
-// one-line since-delta hint pointing at `--since`, so the agent catches up on
-// exactly the comments that arrived since its last run instead of re-reading
-// everything or walking threads blind.
+// since-delta hint scoped to the triggering thread, so the agent does not pull
+// unrelated thread updates by default.
func TestBuildPromptNewCommentsHint(t *testing.T) {
const (
issueID = "issue-new-1"
@@ -317,15 +316,20 @@ func TestBuildPromptNewCommentsHint(t *testing.T) {
}
out := BuildPrompt(task, "claude")
- if !strings.Contains(out, "3 new comment(s) since your last run") {
+ if !strings.Contains(out, "3 other new comment(s) in this thread since your last run") {
t.Errorf("hint must report the new-comment count, got:\n%s", out)
}
- if !strings.Contains(out, "multica issue comment list "+issueID+" --since "+since+" --output json") {
- t.Errorf("hint must point at the --since catch-up read, got:\n%s", out)
+ if !strings.Contains(out, "multica issue comment list "+issueID+" --thread trigger-1 --since "+since+" --output json") {
+ t.Errorf("hint must point at the thread-scoped --since catch-up read, got:\n%s", out)
}
- // Warm path also keeps a --thread pointer: --since is a time delta and can
- // miss the triggering thread's pre-anchor history, so the agent is told it can
- // pull that thread in full when needed.
+ if !strings.Contains(out, "raw thread delta") {
+ t.Errorf("hint must not imply the CLI output exactly matches the count, got:\n%s", out)
+ }
+ if strings.Contains(out, "resumed session is missing older thread context") {
+ t.Errorf("warm delta fallback wording must not assume a resumed session, got:\n%s", out)
+ }
+ // Warm path also keeps a bounded full-thread pointer: thread-scoped --since
+ // can still miss the triggering thread's pre-anchor history.
if !strings.Contains(out, "multica issue comment list "+issueID+" --thread trigger-1 --tail 30 --output json") {
t.Errorf("warm hint must also point at the triggering thread, got:\n%s", out)
}
@@ -357,3 +361,35 @@ func TestBuildPromptColdStartThreadRead(t *testing.T) {
t.Errorf("cold start must point at the triggering thread read, got:\n%s", out)
}
}
+
+// TestBuildPromptResumedNoDeltaDoesNotForceThreadRead pins the warm/no-delta
+// path: when a prior provider session is actually being resumed, the triggering
+// comment is already embedded in the per-turn prompt, so the agent should not
+// be told to re-read the triggering thread's latest 30 replies by default.
+func TestBuildPromptResumedNoDeltaDoesNotForceThreadRead(t *testing.T) {
+ const issueID = "issue-resumed-1"
+ task := Task{
+ IssueID: issueID,
+ TriggerCommentID: "trigger-1",
+ TriggerCommentContent: "hi again",
+ TriggerAuthorType: "member",
+ PriorSessionID: "session-123",
+ NewCommentCount: 0,
+ NewCommentsSince: "",
+ }
+ out := BuildPrompt(task, "claude")
+
+ for _, want := range []string{
+ "triggering comment is already included above",
+ "Do not re-read comment history by default",
+ "Only if the resumed session is missing thread context",
+ "multica issue comment list " + issueID + " --thread trigger-1 --tail 30 --output json",
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("resumed/no-delta prompt missing %q\n--- output ---\n%s", want, out)
+ }
+ }
+ if strings.Contains(out, "Read the triggering conversation first") {
+ t.Errorf("resumed/no-delta prompt must not use the cold-start forced-read wording, got:\n%s", out)
+ }
+}
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index 5b6ea3c205..f5e3e996b8 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -55,7 +55,7 @@ type Task struct {
TriggerCommentContent string `json:"trigger_comment_content,omitempty"` // content of the triggering comment
TriggerAuthorType string `json:"trigger_author_type,omitempty"` // "agent" or "member" — author kind for the triggering comment
TriggerAuthorName string `json:"trigger_author_name,omitempty"` // display name of the triggering comment author
- NewCommentCount int `json:"new_comment_count,omitempty"` // comments on the issue created since this agent's last run (excludes its own); 0/omitted for old daemons or cold start
+ NewCommentCount int `json:"new_comment_count,omitempty"` // non-injected comments in the trigger thread since this agent's last run (excludes its own); 0/omitted for old daemons or cold start
NewCommentsSince string `json:"new_comments_since,omitempty"` // RFC3339 anchor (last run's started_at) the count is measured from; empty on cold start
ChatSessionID string `json:"chat_session_id,omitempty"` // non-empty for chat tasks
ChatMessage string `json:"chat_message,omitempty"` // user message content for chat tasks
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 82aaad9f5b..d8be7e5c21 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -203,7 +203,7 @@ type AgentTaskResponse struct {
TriggerSummary *string `json:"trigger_summary,omitempty"` // canonical short description snapshot — comment text / autopilot title — taken at task creation; survives source edits/deletes
TriggerAuthorType string `json:"trigger_author_type,omitempty"` // "agent" or "member" — author kind of the triggering comment
TriggerAuthorName string `json:"trigger_author_name,omitempty"` // display name of the triggering comment author
- NewCommentCount int `json:"new_comment_count,omitempty"` // comments created since this agent's last run on the issue (excludes its own); omitempty so old daemons ignore it
+ NewCommentCount int `json:"new_comment_count,omitempty"` // trigger-thread comments since last run; excludes injected trigger + own comments; omitempty so old daemons ignore it
NewCommentsSince string `json:"new_comments_since,omitempty"` // RFC3339 anchor (last run's started_at) the count is measured from; omitempty so old daemons ignore it
ChatSessionID string `json:"chat_session_id,omitempty"` // non-empty for chat tasks
ChatMessage string `json:"chat_message,omitempty"` // user message for chat tasks
diff --git a/server/internal/handler/comment_list_test.go b/server/internal/handler/comment_list_test.go
index 7e820ff138..e3c6762d03 100644
--- a/server/internal/handler/comment_list_test.go
+++ b/server/internal/handler/comment_list_test.go
@@ -1320,44 +1320,47 @@ func resolveCommentRow(t *testing.T, commentID string) {
}
}
-// TestCountNewCommentsSince_ExcludesAgentOwn pins the claim-side count query: it
-// counts comments created after the given anchor and excludes the agent's own,
-// so a chatty agent does not inflate its own new-comment count.
-func TestCountNewCommentsSince_ExcludesAgentOwn(t *testing.T) {
+// TestCountNewCommentsSince_ThreadScopedExcludesAgentOwnAndTrigger pins the
+// claim-side count query: it counts comments created after the given anchor only
+// within the triggering thread, excludes the triggering comment because it is
+// injected into the prompt, and excludes the agent's own comments so a chatty
+// agent does not inflate its own new-comment count.
+func TestCountNewCommentsSince_ThreadScopedExcludesAgentOwnAndTrigger(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
}
fx := newCommentListFixture(t)
agentID := createHandlerTestAgent(t, "count-agent", []byte("[]"))
- // Two agent-authored comments — must NOT be counted.
- for _, body := range []string{"agent reply 1", "agent reply 2"} {
- if _, err := testPool.Exec(context.Background(), `
- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id)
- VALUES ($1, $2, 'agent', $3, $4, 'comment', $5)
- `, fx.IssueID, testWorkspaceID, agentID, body, fx.Root2); err != nil {
- t.Fatalf("insert agent comment: %v", err)
- }
+ if _, err := testPool.Exec(context.Background(), `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, created_at)
+ VALUES ($1, $2, 'agent', $3, 'agent reply', 'comment', $4, $5)
+ `, fx.IssueID, testWorkspaceID, agentID, fx.Root1, fx.Base.Add(4*time.Minute)); err != nil {
+ t.Fatalf("insert agent comment: %v", err)
}
ctx := context.Background()
- // Anchor in the far past: all 7 member comments are newer; agent's 2 excluded.
+ // Anchor after r1a: root1/r1a are stale, r1b is the only non-trigger,
+ // non-agent comment in the triggering thread. r1b1 is the trigger and root2's
+ // whole thread is unrelated noise.
got, err := testHandler.Queries.CountNewCommentsSince(ctx, db.CountNewCommentsSinceParams{
+ AnchorID: parseUUID(fx.R1b1),
IssueID: parseUUID(fx.IssueID),
WorkspaceID: parseUUID(testWorkspaceID),
- Since: pgtype.Timestamptz{Time: time.Unix(0, 0), Valid: true},
+ Since: pgtype.Timestamptz{Time: fx.Base.Add(90 * time.Second), Valid: true},
AuthorID: parseUUID(agentID),
})
if err != nil {
- t.Fatalf("count new since epoch: %v", err)
+ t.Fatalf("count new since anchor: %v", err)
}
- if got != 7 {
- t.Fatalf("expected 7 new member comments since epoch (agent's own excluded), got %d", got)
+ if got != 1 {
+ t.Fatalf("expected only r1b to count, got %d", got)
}
// Anchor in the future: nothing is newer.
got, err = testHandler.Queries.CountNewCommentsSince(ctx, db.CountNewCommentsSinceParams{
+ AnchorID: parseUUID(fx.R1b1),
IssueID: parseUUID(fx.IssueID),
WorkspaceID: parseUUID(testWorkspaceID),
Since: pgtype.Timestamptz{Time: time.Now().Add(time.Hour), Valid: true},
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 6591baa279..a023163af6 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1269,18 +1269,21 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
}
}
}
- // Count comments that arrived since this agent's last run on the
- // issue, so the daemon can tell it up front instead of relying on
- // it to self-fetch. Anchor = the prior task's started_at (never
- // completed_at: a long run would miss comments posted while it
- // ran). Cold start (no prior task) → no anchor → no hint.
- // Excludes the agent's own comments. Best-effort: any DB error or
- // zero count leaves the hint suppressed.
+ // Count non-injected comments that arrived in the triggering
+ // thread since this agent's last run, so the daemon can tell it up
+ // front instead of forcing an issue-wide catch-up. Anchor = the
+ // prior task's started_at (never completed_at: a long run would
+ // miss comments posted while it ran). Cold start (no prior task) →
+ // no anchor → no hint. Excludes the agent's own comments and the
+ // triggering comment itself because that body is already injected
+ // into the prompt. Best-effort: any DB error or zero count leaves
+ // the hint suppressed.
if startedAt, err := h.Queries.GetLastTaskStartedAtForIssueAndAgent(r.Context(), db.GetLastTaskStartedAtForIssueAndAgentParams{
AgentID: task.AgentID,
IssueID: comment.IssueID,
}); err == nil && startedAt.Valid {
if cnt, err := h.Queries.CountNewCommentsSince(r.Context(), db.CountNewCommentsSinceParams{
+ AnchorID: task.TriggerCommentID,
IssueID: comment.IssueID,
WorkspaceID: comment.WorkspaceID,
Since: startedAt,
diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.go
index d734b789f7..8b325bc099 100644
--- a/server/internal/handler/daemon_test.go
+++ b/server/internal/handler/daemon_test.go
@@ -3497,11 +3497,12 @@ func claimCommentTask(t *testing.T, runtimeID, daemonID string) claimCommentTask
return resp
}
-// TestClaimTaskByRuntime_CommentTaskPopulatesNewCommentCount verifies the claim
-// response carries new_comment_count + new_comments_since for a comment task
-// when the agent ran on this issue before: the count is comments created after
-// the prior run's started_at, and the since anchor is that started_at.
-func TestClaimTaskByRuntime_CommentTaskPopulatesNewCommentCount(t *testing.T) {
+// TestClaimTaskByRuntime_CommentTaskPopulatesThreadScopedNewCommentCount
+// verifies the claim response carries new_comment_count + new_comments_since for
+// a comment task when the agent ran before: the count is scoped to the
+// triggering thread, excludes the injected trigger comment, excludes the
+// agent's own comments, and the since anchor is the prior run's started_at.
+func TestClaimTaskByRuntime_CommentTaskPopulatesThreadScopedNewCommentCount(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
}
@@ -3520,8 +3521,39 @@ func TestClaimTaskByRuntime_CommentTaskPopulatesNewCommentCount(t *testing.T) {
}
t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, priorTaskID) })
- // The trigger comment (member-authored, created now) lands after the anchor.
- _, triggerID := createCommentTriggeredClaimTask(t, ctx, agentID, runtimeID, issueID, nil)
+ var threadRootID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type)
+ VALUES ($1, $2, 'member', $3, 'same-thread context', 'comment')
+ RETURNING id
+ `, issueID, testWorkspaceID, testUserID).Scan(&threadRootID); err != nil {
+ t.Fatalf("insert trigger thread root: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM comment WHERE id = $1`, threadRootID) })
+
+ var unrelatedRootID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type)
+ VALUES ($1, $2, 'member', $3, 'unrelated thread context', 'comment')
+ RETURNING id
+ `, issueID, testWorkspaceID, testUserID).Scan(&unrelatedRootID); err != nil {
+ t.Fatalf("insert unrelated thread root: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM comment WHERE id = $1`, unrelatedRootID) })
+
+ var agentOwnID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id)
+ VALUES ($1, $2, 'agent', $3, 'agent self reply', 'comment', $4)
+ RETURNING id
+ `, issueID, testWorkspaceID, agentID, threadRootID).Scan(&agentOwnID); err != nil {
+ t.Fatalf("insert agent self reply: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM comment WHERE id = $1`, agentOwnID) })
+
+ // The trigger comment (member-authored, created now) lands after the anchor
+ // but is injected into the prompt, so it should not be counted.
+ _, triggerID := createCommentTriggeredClaimTask(t, ctx, agentID, runtimeID, issueID, &threadRootID)
resp := claimCommentTask(t, runtimeID, "comment-newcount-claim")
if resp.Task.TriggerCommentID != triggerID {
@@ -3530,8 +3562,40 @@ func TestClaimTaskByRuntime_CommentTaskPopulatesNewCommentCount(t *testing.T) {
if resp.Task.NewCommentsSince == "" {
t.Errorf("new_comments_since must be set when a prior run exists, got empty")
}
- if resp.Task.NewCommentCount < 1 {
- t.Errorf("new_comment_count = %d, want >= 1 (the trigger comment is newer than the anchor)", resp.Task.NewCommentCount)
+ if resp.Task.NewCommentCount != 1 {
+ t.Errorf("new_comment_count = %d, want 1 (same-thread context only)", resp.Task.NewCommentCount)
+ }
+}
+
+func TestClaimTaskByRuntime_CommentTaskOmitsDeltaWhenOnlyTriggerIsNew(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Comment trigger-only runtime")
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Comment trigger-only agent")
+
+ var priorTaskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at, completed_at)
+ VALUES ($1, $2, $3, 'completed', 0, now() - interval '1 hour', now() - interval '50 minutes')
+ RETURNING id
+ `, agentID, runtimeID, issueID).Scan(&priorTaskID); err != nil {
+ t.Fatalf("insert prior task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, priorTaskID) })
+
+ _, triggerID := createCommentTriggeredClaimTask(t, ctx, agentID, runtimeID, issueID, nil)
+
+ resp := claimCommentTask(t, runtimeID, "comment-trigger-only-claim")
+ if resp.Task.TriggerCommentID != triggerID {
+ t.Fatalf("trigger_comment_id = %s, want %s", resp.Task.TriggerCommentID, triggerID)
+ }
+ if resp.Task.NewCommentCount != 0 {
+ t.Errorf("new_comment_count = %d, want 0 when only the injected trigger is new", resp.Task.NewCommentCount)
+ }
+ if resp.Task.NewCommentsSince != "" {
+ t.Errorf("new_comments_since = %q, want empty when only the injected trigger is new", resp.Task.NewCommentsSince)
}
}
diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.go
index 677cf66e49..2cbd946bae 100644
--- a/server/pkg/db/generated/comment.sql.go
+++ b/server/pkg/db/generated/comment.sql.go
@@ -29,26 +29,51 @@ func (q *Queries) CountComments(ctx context.Context, arg CountCommentsParams) (i
}
const countNewCommentsSince = `-- name: CountNewCommentsSince :one
-SELECT count(*) FROM comment
-WHERE issue_id = $1
- AND workspace_id = $2
- AND created_at > $3
- AND NOT (author_type = 'agent' AND author_id = $4)
+WITH RECURSIVE root_of AS (
+ SELECT c.id, c.parent_id
+ FROM comment c
+ WHERE c.id = $1 AND c.issue_id = $2 AND c.workspace_id = $3
+ UNION ALL
+ SELECT p.id, p.parent_id
+ FROM comment p
+ JOIN root_of r ON p.id = r.parent_id
+ WHERE p.issue_id = $2 AND p.workspace_id = $3
+),
+thread_root AS (
+ SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1
+),
+descendants AS (
+ SELECT c.id, c.created_at, c.author_type, c.author_id
+ FROM comment c
+ JOIN thread_root tr ON c.id = tr.id
+ UNION
+ SELECT c.id, c.created_at, c.author_type, c.author_id
+ FROM comment c
+ JOIN descendants d ON c.parent_id = d.id
+ WHERE c.issue_id = $2 AND c.workspace_id = $3
+)
+SELECT count(*) FROM descendants
+WHERE created_at > $4
+ AND id <> $1
+ AND NOT (author_type = 'agent' AND author_id = $5)
`
type CountNewCommentsSinceParams struct {
+ AnchorID pgtype.UUID `json:"anchor_id"`
IssueID pgtype.UUID `json:"issue_id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
Since pgtype.Timestamptz `json:"since"`
AuthorID pgtype.UUID `json:"author_id"`
}
-// Counts comments on an issue created strictly after @since, excluding any
-// authored by the given agent (@author_id). Feeds the daemon claim response so
-// a comment-triggered task can tell the agent how many comments arrived since
-// its last run on this issue, without shipping their bodies.
+// Counts non-injected comments in the thread containing @anchor_id created
+// strictly after @since, excluding any authored by the given agent
+// (@author_id). The triggering comment body is already injected into the
+// prompt, so @anchor_id itself is excluded from the count. Feeds the daemon
+// claim response without shipping comment bodies.
func (q *Queries) CountNewCommentsSince(ctx context.Context, arg CountNewCommentsSinceParams) (int64, error) {
row := q.db.QueryRow(ctx, countNewCommentsSince,
+ arg.AnchorID,
arg.IssueID,
arg.WorkspaceID,
arg.Since,
diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sql
index ef073fcf93..fb7f39acc4 100644
--- a/server/pkg/db/queries/comment.sql
+++ b/server/pkg/db/queries/comment.sql
@@ -298,14 +298,40 @@ SELECT count(*) FROM comment
WHERE issue_id = $1 AND workspace_id = $2;
-- name: CountNewCommentsSince :one
--- Counts comments on an issue created strictly after @since, excluding any
--- authored by the given agent (@author_id). Feeds the daemon claim response so
--- a comment-triggered task can tell the agent how many comments arrived since
--- its last run on this issue, without shipping their bodies.
-SELECT count(*) FROM comment
-WHERE issue_id = @issue_id
- AND workspace_id = @workspace_id
- AND created_at > @since
+-- Counts non-injected comments in the thread containing @anchor_id created
+-- strictly after @since, excluding any authored by the given agent
+-- (@author_id). The triggering comment body is already injected into the
+-- prompt, so @anchor_id itself is excluded from the count. Feeds the daemon
+-- claim response without shipping comment bodies.
+WITH RECURSIVE root_of AS (
+ -- Scope is enforced on both the anchor seed and recursive walk-up; keep
+ -- these predicates together so future parent/thread changes cannot cross
+ -- issue or workspace boundaries.
+ SELECT c.id, c.parent_id
+ FROM comment c
+ WHERE c.id = @anchor_id AND c.issue_id = @issue_id AND c.workspace_id = @workspace_id
+ UNION ALL
+ SELECT p.id, p.parent_id
+ FROM comment p
+ JOIN root_of r ON p.id = r.parent_id
+ WHERE p.issue_id = @issue_id AND p.workspace_id = @workspace_id
+),
+thread_root AS (
+ SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1
+),
+descendants AS (
+ SELECT c.id, c.created_at, c.author_type, c.author_id
+ FROM comment c
+ JOIN thread_root tr ON c.id = tr.id
+ UNION
+ SELECT c.id, c.created_at, c.author_type, c.author_id
+ FROM comment c
+ JOIN descendants d ON c.parent_id = d.id
+ WHERE c.issue_id = @issue_id AND c.workspace_id = @workspace_id
+)
+SELECT count(*) FROM descendants
+WHERE created_at > @since
+ AND id <> @anchor_id
AND NOT (author_type = 'agent' AND author_id = @author_id);
-- name: GetComment :one