Skip to content

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

Go

feat(comments): resolve-aware fold for agent comment reads (MUL-3555) (#4463)

Naiyuan Qingb79777caece6
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.go
index b50939daf1..2fe93d0e5a 100644
--- a/server/cmd/multica/cmd_issue.go
+++ b/server/cmd/multica/cmd_issue.go
@@ -391,6 +391,7 @@ func init() {
issueCommentListCmd.Flags().Int("recent", 0, "Return the N most recently active threads (root + descendants per thread). Use --before/--before-id from the previous response to scroll to older threads.")
issueCommentListCmd.Flags().Bool("roots-only", false, "Only return top-level comments (parent_id is null). Each root also carries reply_count + last_activity_at so you can triage which thread to open.")
issueCommentListCmd.Flags().Bool("summary", false, "Clip each comment's content to a short preview (sets content_truncated) so you can scan a list without pulling full bodies. Composes with any mode.")
+ issueCommentListCmd.Flags().Bool("full", false, "Escape hatch: return every comment in resolved threads verbatim. By default the complete-thread reads (default list, --recent, --thread without --tail) are folded — a resolved thread collapses to its root + conclusion, with the dropped count reported on the root — so you do not pay tokens for settled discussion. Pass --full when you need the folded discussion. No effect on --since/--tail/--roots-only reads, which are never folded.")
issueCommentListCmd.Flags().String("before", "", "Cursor (RFC3339Nano timestamp). With --recent: thread cursor (last_activity_at). With --thread + --tail: reply cursor (reply created_at). Read from the X-Multica-Next-Before response header; must be paired with --before-id.")
issueCommentListCmd.Flags().String("before-id", "", "Cursor UUID. With --recent: thread root UUID. With --thread + --tail: oldest reply UUID. Read from the X-Multica-Next-Before-Id response header; must be paired with --before.")
@@ -1271,6 +1272,7 @@ func runIssueCommentList(cmd *cobra.Command, args []string) error {
tail, _ := cmd.Flags().GetInt("tail")
rootsOnly, _ := cmd.Flags().GetBool("roots-only")
summary, _ := cmd.Flags().GetBool("summary")
+ full, _ := cmd.Flags().GetBool("full")
// Flags().Changed distinguishes "user did not pass --recent" from
// "user explicitly passed --recent 0" (or a negative value). The
// GetInt zero-value collapses both cases, which would otherwise
@@ -1327,6 +1329,18 @@ func runIssueCommentList(cmd *cobra.Command, args []string) error {
if summary {
params.Set("summary", "true")
}
+ // Resolve-aware folding is the default on the complete-thread reads (default
+ // list, --recent, --thread without --tail): a resolved thread collapses to
+ // root + conclusion so an agent does not pay tokens for settled discussion.
+ // --full opts out. The partial-thread reads (--since / --tail) and
+ // --roots-only cannot be folded safely (server rejects fold there), so we
+ // never send fold for them and --full is a harmless no-op. Sending fold only
+ // when eligible keeps every existing read command — including the prompt's
+ // `--thread <id> --tail 30` cold path — working unchanged.
+ foldEligible := !rootsOnly && since == "" && !tailSet
+ if foldEligible && !full {
+ params.Set("fold", "true")
+ }
if thread != "" {
params.Set("thread", thread)
}
diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.go
index 531e214481..8de2af0060 100644
--- a/server/cmd/multica/cmd_issue_test.go
+++ b/server/cmd/multica/cmd_issue_test.go
@@ -1756,6 +1756,7 @@ func newIssueCommentListTestCmd() *cobra.Command {
cmd.Flags().String("since", "", "")
cmd.Flags().Bool("roots-only", false, "")
cmd.Flags().Bool("summary", false, "")
+ cmd.Flags().Bool("full", false, "")
cmd.Flags().String("thread", "", "")
cmd.Flags().Int("recent", 0, "")
cmd.Flags().Int("tail", 0, "")
@@ -2087,6 +2088,82 @@ func TestRunIssueCommentList_SummaryPassesThrough(t *testing.T) {
}
}
+// TestRunIssueCommentList_FoldDefaultAndFullEscape pins the CLI's resolve-aware
+// fold default and its --full escape hatch (MUL-3555):
+//
+// - the complete-thread reads (default list, --recent, untailed --thread) send
+// fold=true by default, so an agent skips settled discussion automatically;
+// - --full suppresses fold so a caller can pull the whole discussion back;
+// - the partial-thread reads (--since, --thread + --tail) and --roots-only
+// never send fold — folding them would be unsafe, and the server rejects it,
+// so the CLI must not add the param there in the first place.
+func TestRunIssueCommentList_FoldDefaultAndFullEscape(t *testing.T) {
+ var gotQuery url.Values
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/api/issues/") && !strings.Contains(r.URL.Path, "/comments") {
+ json.NewEncoder(w).Encode(map[string]any{
+ "id": "issue-1",
+ "identifier": "MUL-1",
+ })
+ return
+ }
+ if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/comments") {
+ gotQuery = r.URL.Query()
+ w.Write([]byte("[]"))
+ return
+ }
+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.String())
+ http.Error(w, "unexpected", http.StatusInternalServerError)
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cases := []struct {
+ name string
+ setup func(c *cobra.Command)
+ wantFold bool
+ }{
+ {name: "default list folds", setup: func(c *cobra.Command) {}, wantFold: true},
+ {name: "recent folds", setup: func(c *cobra.Command) {
+ _ = c.Flags().Set("recent", "10")
+ }, wantFold: true},
+ {name: "untailed thread folds", setup: func(c *cobra.Command) {
+ _ = c.Flags().Set("thread", "00000000-0000-0000-0000-000000000001")
+ }, wantFold: true},
+ {name: "full opts out", setup: func(c *cobra.Command) {
+ _ = c.Flags().Set("full", "true")
+ }, wantFold: false},
+ {name: "since never folds", setup: func(c *cobra.Command) {
+ _ = c.Flags().Set("since", "2026-01-01T00:00:00Z")
+ }, wantFold: false},
+ {name: "thread+tail never folds", setup: func(c *cobra.Command) {
+ _ = c.Flags().Set("thread", "00000000-0000-0000-0000-000000000001")
+ _ = c.Flags().Set("tail", "5")
+ }, wantFold: false},
+ {name: "roots-only never folds", setup: func(c *cobra.Command) {
+ _ = c.Flags().Set("roots-only", "true")
+ }, wantFold: false},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ gotQuery = nil
+ cmd := newIssueCommentListTestCmd()
+ tc.setup(cmd)
+ if err := runIssueCommentList(cmd, []string{"MUL-1"}); err != nil {
+ t.Fatalf("runIssueCommentList: %v", err)
+ }
+ gotFold := gotQuery.Get("fold") == "true"
+ if gotFold != tc.wantFold {
+ t.Errorf("fold query = %q, want fold=%v", gotQuery.Get("fold"), tc.wantFold)
+ }
+ })
+ }
+}
+
// TestRunIssueCommentList_ThreadTailPassesThroughAndPrintsReplyCursor pins
// the positive path for --thread + --tail: the CLI forwards `thread` +
// `tail` query params and, on response, prints "Next reply cursor" (not
diff --git a/server/internal/daemon/execenv/reply_instructions.go b/server/internal/daemon/execenv/reply_instructions.go
index 40ada85375..2bfafd5487 100644
--- a/server/internal/daemon/execenv/reply_instructions.go
+++ b/server/internal/daemon/execenv/reply_instructions.go
@@ -97,7 +97,8 @@ func BuildColdCommentsHint(issueID, triggerCommentID, triggerThreadID string) st
"Read the triggering conversation first: "+
"`multica issue comment list %s --thread %s --tail 30 --output json` "+
"(that thread's root + its 30 newest replies). "+
- "Need cross-thread background? `multica issue comment list %s --recent 10 --output json`.\n\n",
+ "Need cross-thread background? `multica issue comment list %s --recent 10 --output json` "+
+ "(resolved threads come back folded — `--full` to expand).\n\n",
issueID, threadID, issueID,
)
}
diff --git a/server/internal/daemon/execenv/runtime_config.go b/server/internal/daemon/execenv/runtime_config.go
index d1b82a3bb5..1ba188eb7e 100644
--- a/server/internal/daemon/execenv/runtime_config.go
+++ b/server/internal/daemon/execenv/runtime_config.go
@@ -474,7 +474,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` (with or without `--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>] [--full] --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. **Resolve-aware folding is on by default for the complete-thread reads (default list, `--recent`, `--thread` without `--tail`): a resolved thread collapses to its root + conclusion comment (reply-resolved) or its root only (root-resolved), with the dropped count reported on the root as `folded_count` and `thread_resolved: true` — so you skip settled discussion. Pass `--full` to get a folded thread's complete discussion. Folding never applies to `--since`/`--tail`/`--roots-only` reads (they return partial threads), so `--full` is a no-op there.** `--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-file <path> | --description-stdin] [--priority X] [--status X] [--assignee X | --assignee-id <uuid>] [--parent <issue-id>] [--stage N] [--project <project-id>] [--due-date <RFC3339>] [--attachment <path>]` — Create a new issue; `--attachment` may be repeated. `--stage N` (N ≥ 1) groups a sub-issue into an ordered barrier group under its parent so the parent wakes per stage, not per child. For agent-authored long descriptions, prefer `--description-file <path>` — flags after a HEREDOC terminator can be silently swallowed (#4182).\n")
b.WriteString("- `multica issue update <id> [--title X] [--description X | --description-file <path> | --description-stdin] [--priority X] [--status X] [--assignee X | --assignee-id <uuid>] [--parent <issue-id>] [--stage N] [--project <project-id>] [--due-date <RFC3339>]` — Update issue fields; use `--parent \"\"` to clear parent. For agent-authored long descriptions, prefer `--description-file <path>` over stdin (#4182).\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")
@@ -670,7 +670,7 @@ func buildMetaSkillContent(provider string, ctx TaskContextForEnv) string {
} else if cold := BuildColdCommentsHint(ctx.IssueID, ctx.TriggerCommentID, ctx.TriggerThreadID); cold != "" {
b.WriteString("3. " + cold)
} else {
- fmt.Fprintf(&b, "3. Catch up on comments — read with `multica issue comment list %s --recent 10 --output json`.\n", ctx.IssueID)
+ fmt.Fprintf(&b, "3. Catch up on comments — read with `multica issue comment list %s --recent 10 --output json` (resolved threads come back folded — `--full` to expand).\n", ctx.IssueID)
}
fmt.Fprintf(&b, "4. Find the triggering comment (ID: `%s`) and understand what is being asked — do NOT confuse it with previous comments\n", ctx.TriggerCommentID)
if ctx.IsSquadLeader {
@@ -689,7 +689,7 @@ func buildMetaSkillContent(provider string, ctx TaskContextForEnv) string {
b.WriteString("You are responsible for managing the issue status throughout your work, unless your Agent Identity forbids issue status changes.\n\n")
fmt.Fprintf(&b, "1. Run `multica issue get %s --output json` to understand your task\n", ctx.IssueID)
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)
- fmt.Fprintf(&b, "3. Run `multica issue comment list %s --recent 10 --output json` to catch up on recent active comment threads — this is mandatory, not optional. Earlier comments often carry context the issue body lacks (e.g. which repo to work in, the prior agent's findings, the reason the issue was reassigned to you). Skipping this step is the most common cause of agents acting on stale or incomplete instructions. If the recent window shows that older context is needed, page older threads with the stderr `Next thread cursor:` values and the matching `--before` / `--before-id` flags until you have enough history.\n", ctx.IssueID)
+ fmt.Fprintf(&b, "3. Run `multica issue comment list %s --recent 10 --output json` to catch up on recent active comment threads — this is mandatory, not optional. Earlier comments often carry context the issue body lacks (e.g. which repo to work in, the prior agent's findings, the reason the issue was reassigned to you). Skipping this step is the most common cause of agents acting on stale or incomplete instructions. Resolved threads come back folded — `--full` to expand. If the recent window shows that older context is needed, page older threads with the stderr `Next thread cursor:` values and the matching `--before` / `--before-id` flags until you have enough history.\n", ctx.IssueID)
fmt.Fprintf(&b, "4. Run `multica issue status %s in_progress` unless your Agent Identity forbids issue status changes; if it does, skip this step.\n", ctx.IssueID)
b.WriteString("5. Complete the task within your Agent Identity boundaries. Do not investigate, implement, create issues, update issues, or delegate if your Agent Identity forbids that action; if your role is delegation-only, perform the allowed delegation work and stop once that outcome is delivered.\n")
if ctx.IsSquadLeader {
diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.go
index f982eba03f..3ccf8a1641 100644
--- a/server/internal/daemon/prompt.go
+++ b/server/internal/daemon/prompt.go
@@ -38,7 +38,7 @@ func BuildPrompt(task Task, provider string) string {
fmt.Fprintf(&b, "> %s\n\n", task.HandoffNote)
}
fmt.Fprintf(&b, "Start by running `multica issue get %s --output json` to understand your task, then complete it.\n", task.IssueID)
- fmt.Fprintf(&b, "For comment history, follow the rule in your runtime workflow file (assignment-triggered tasks treat the read as mandatory). Start with `multica issue comment list %s --recent 10 --output json` to read the 10 most recently active threads, then page older threads via the stderr `Next thread cursor: ...` line and the matching `--before` / `--before-id` until you have enough history. `--since <RFC3339>` is still available for incremental polling and may combine with `--recent`.\n", task.IssueID)
+ fmt.Fprintf(&b, "For comment history, follow the rule in your runtime workflow file (assignment-triggered tasks treat the read as mandatory). Start with `multica issue comment list %s --recent 10 --output json` to read the 10 most recently active threads, then page older threads via the stderr `Next thread cursor: ...` line and the matching `--before` / `--before-id` until you have enough history. Resolved threads come back folded — `--full` to expand. `--since <RFC3339>` is still available for incremental polling and may combine with `--recent`.\n", task.IssueID)
return b.String()
}
@@ -179,7 +179,7 @@ func buildCommentPrompt(task Task, provider string) string {
} else if cold := execenv.BuildColdCommentsHint(task.IssueID, task.TriggerCommentID, task.TriggerThreadID); cold != "" {
b.WriteString(cold)
} else {
- fmt.Fprintf(&b, "Read the discussion: `multica issue comment list %s --recent 10 --output json`.\n\n", task.IssueID)
+ fmt.Fprintf(&b, "Read the discussion: `multica issue comment list %s --recent 10 --output json` (resolved threads come back folded — `--full` to expand).\n\n", task.IssueID)
}
b.WriteString(execenv.BuildCommentReplyInstructions(provider, task.IssueID, task.TriggerCommentID))
return b.String()
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index 511430dfb5..768fc03236 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -47,6 +47,16 @@ type CommentResponse struct {
// clipped to the summary budget, false when it fit. nil (omitted) means the
// caller did not request a summary projection, so Content is verbatim.
ContentTruncated *bool `json:"content_truncated,omitempty"`
+ // Fold projection fields — populated only under fold=true, and only on the
+ // thread ROOT of a resolved thread (mirrors the human timeline fold; see
+ // foldResolvedThreads). Both are nil/omitted everywhere else: every comment
+ // under an unresolved thread, and every non-root comment. ThreadResolved
+ // marks a thread whose discussion was collapsed to its conclusion;
+ // FoldedCount is how many comments in that thread were dropped from the
+ // response (0 when the thread was already at root + conclusion). The reader
+ // pulls the folded comments back with `comment list --full`.
+ ThreadResolved *bool `json:"thread_resolved,omitempty"`
+ FoldedCount *int `json:"folded_count,omitempty"`
}
func commentToResponse(c db.Comment, reactions []ReactionResponse, attachments []AttachmentResponse) CommentResponse {
@@ -99,6 +109,136 @@ func summarizeContent(content string) (string, bool) {
return content, false
}
+// foldStat is the per-thread fold annotation attached to a resolved thread's
+// root under fold=true. FoldedCount is how many comments in the thread were
+// dropped from the response. See CommentResponse.ThreadResolved / FoldedCount.
+type foldStat struct {
+ FoldedCount int
+}
+
+// foldResolvedThreads collapses every resolved thread in a COMPLETE-thread
+// comment set down to the comments a reader actually needs, mirroring the human
+// timeline fold (deriveThreadResolution in
+// packages/views/issues/components/thread-utils.ts) so agents see what humans
+// see:
+//
+// - unresolved thread → every comment kept, unchanged, no annotation.
+// - reply-resolved thread → keep the thread root + the resolution reply (the
+// conclusion), drop every other reply. Root + conclusion, never conclusion
+// alone: a conclusion is often referential ("go with what we said above")
+// and unreadable without the root question.
+// - root-resolved thread → keep only the root, drop every reply (the whole
+// discussion was a settled dead-end; the root states the topic).
+//
+// The thread root of each resolved thread is annotated (foldStat keyed by the
+// root's id string) so the response can mark it thread_resolved and report how
+// many comments were folded; a reader that needs the dropped discussion pulls
+// it back with `comment list --full`.
+//
+// Resolution is derived exactly as the UI does: the root wins if resolved;
+// otherwise the reply with the latest resolved_at is THE resolution. The single
+// resolved-per-thread invariant (ClearOtherThreadResolutions) normally makes
+// this unambiguous; the latest-wins tiebreak keeps the projection total if an
+// older/concurrent write ever left two.
+//
+// Callers MUST invoke this only on a set containing COMPLETE threads (the
+// default list, --recent, and untailed --thread reads). Partial-thread reads
+// (--since, --tail) are rejected upstream because a fold computed over a partial
+// thread could drop a resolution that was never fetched. As defense in depth,
+// any comment whose thread root is absent from the set is treated as its own
+// root and kept verbatim, so a partial thread degrades to "unchanged" rather
+// than to silent data loss.
+func foldResolvedThreads(comments []db.Comment) ([]db.Comment, map[string]foldStat) {
+ if len(comments) == 0 {
+ return comments, nil
+ }
+
+ byID := make(map[string]db.Comment, len(comments))
+ for _, c := range comments {
+ byID[uuidToString(c.ID)] = c
+ }
+
+ // rootOf walks parent_id up to the thread root within this set. It stops at
+ // the first comment whose parent is absent (in a complete-thread set that is
+ // the real root; in a partial set it is the highest ancestor we hold). The
+ // loop is bounded by len(comments) so an unexpected cycle cannot hang it —
+ // the PK forbids real cycles, but never trust a graph walk over stored data.
+ rootOf := func(c db.Comment) db.Comment {
+ cur := c
+ for i := 0; i < len(comments); i++ {
+ if !cur.ParentID.Valid {
+ return cur
+ }
+ parent, ok := byID[uuidToString(cur.ParentID)]
+ if !ok {
+ return cur
+ }
+ cur = parent
+ }
+ return cur
+ }
+
+ type thread struct {
+ root db.Comment
+ replies []db.Comment // non-root, in input (chronological) order
+ }
+ threads := map[string]*thread{}
+ for _, c := range comments {
+ root := rootOf(c)
+ rid := uuidToString(root.ID)
+ th := threads[rid]
+ if th == nil {
+ th = &thread{root: root}
+ threads[rid] = th
+ }
+ if uuidToString(c.ID) != rid {
+ th.replies = append(th.replies, c)
+ }
+ }
+
+ keep := make(map[string]bool, len(comments))
+ stats := map[string]foldStat{}
+ for rid, th := range threads {
+ // Root-resolved: keep only the root.
+ if th.root.ResolvedAt.Valid {
+ keep[rid] = true
+ stats[rid] = foldStat{FoldedCount: len(th.replies)}
+ continue
+ }
+ // Reply-resolved: the latest-resolved reply is the conclusion.
+ var resolution *db.Comment
+ for i := range th.replies {
+ r := &th.replies[i]
+ if !r.ResolvedAt.Valid {
+ continue
+ }
+ if resolution == nil || r.ResolvedAt.Time.After(resolution.ResolvedAt.Time) {
+ resolution = r
+ }
+ }
+ if resolution == nil {
+ // Unresolved thread: keep everything, no annotation.
+ keep[rid] = true
+ for _, r := range th.replies {
+ keep[uuidToString(r.ID)] = true
+ }
+ continue
+ }
+ keep[rid] = true
+ keep[uuidToString(resolution.ID)] = true
+ // Every reply except the conclusion is folded away.
+ stats[rid] = foldStat{FoldedCount: len(th.replies) - 1}
+ }
+
+ out := make([]db.Comment, 0, len(comments))
+ for _, c := range comments {
+ if keep[uuidToString(c.ID)] {
+ out = append(out, c)
+ }
+ }
+ return out, stats
+}
+
// commentHardCap bounds the comments returned per issue. Sized as a defensive
// safety net rather than a UX paging window: prod p99 is ~30 comments and
// the all-time max observed is ~1.1k, so 2000 leaves ~2x headroom while still
@@ -123,6 +263,15 @@ const commentHardCap = 2000
// agent can scan a list cheaply before pulling a full body. Composes with
// every mode (default, since, thread, recent, roots_only).
//
+// - fold=true — resolve-aware thread projection. Collapses each resolved
+// thread to root + conclusion (reply-resolved) or root only (root-resolved),
+// reusing the human timeline fold so an agent does not pay tokens for
+// settled discussion. The resolved thread's root carries thread_resolved +
+// folded_count; `--full` (no fold param) brings the dropped comments back.
+// Needs whole threads to compute a resolution, so it is rejected with since,
+// tail, and roots_only (partial-thread / reply-less reads) and composes with
+// the default list, recent, untailed thread, and summary.
+//
// - thread=<comment-uuid> — return the root of the thread containing this
// comment plus every descendant. The anchor may be a root or any reply;
// the server walks up to the root via a recursive CTE, so callers do not
@@ -245,7 +394,40 @@ func (h *Handler) ListComments(w http.ResponseWriter, r *http.Request) {
}
}
+ // fold=true is a thread-level projection: it collapses every resolved thread
+ // in the result to root + conclusion (reply-resolved) or root only
+ // (root-resolved), reusing the human timeline's fold semantics so an agent
+ // reading a long issue doesn't pay tokens for settled discussion. Unlike
+ // summary (a per-comment content clip that composes with everything), fold
+ // needs WHOLE threads to compute a resolution, so it is rejected on the
+ // partial-thread reads (since / tail) and on roots_only (which carries no
+ // replies to fold). It composes with summary, the default list, recent, and
+ // untailed thread reads.
+ fold := false
+ if foldStr := q.Get("fold"); foldStr != "" {
+ switch foldStr {
+ case "true":
+ fold = true
+ case "false":
+ default:
+ writeError(w, http.StatusBadRequest, "invalid fold parameter; expected boolean")
+ return
+ }
+ }
+
// --- combination validation ----------------------------------------
+ if fold && sinceTime.Valid {
+ writeError(w, http.StatusBadRequest, "fold and since are mutually exclusive: since returns a partial thread, and a fold over a partial thread could hide a resolution that was not fetched")
+ return
+ }
+ if fold && tailStr != "" {
+ writeError(w, http.StatusBadRequest, "fold and tail are mutually exclusive: tail returns a partial thread, which cannot be folded safely")
+ return
+ }
+ if fold && rootsOnly {
+ writeError(w, http.StatusBadRequest, "fold and roots_only are mutually exclusive: roots_only returns no replies to fold")
+ return
+ }
if rootsOnly && threadStr != "" {
writeError(w, http.StatusBadRequest, "roots_only and thread are mutually exclusive")
return
@@ -365,6 +547,17 @@ func (h *Handler) ListComments(w http.ResponseWriter, r *http.Request) {
}
}
+ // Apply the resolve-aware fold before anything keys off the comment set
+ // (reaction/attachment grouping, the response array): folding drops comments,
+ // and the dropped ones should not pay a reactions/attachments round-trip or
+ // appear in the response. fetchCommentsForList only ever returns complete
+ // threads on the modes fold is allowed with (default, recent, untailed
+ // thread), which is the precondition foldResolvedThreads documents.
+ var foldInfo map[string]foldStat
+ if fold {
+ result.Comments, foldInfo = foldResolvedThreads(result.Comments)
+ }
+
commentIDs := make([]pgtype.UUID, len(result.Comments))
for i, c := range result.Comments {
commentIDs[i] = c.ID
@@ -385,6 +578,14 @@ func (h *Handler) ListComments(w http.ResponseWriter, r *http.Request) {
resp[i].LastActivityAt = &la
}
}
+ // Attach fold annotations on a resolved thread's root (nil map elsewhere;
+ // keyed by root id, so only root comments match).
+ if st, ok := foldInfo[cid]; ok {
+ resolved := true
+ resp[i].ThreadResolved = &resolved
+ fc := st.FoldedCount
+ resp[i].FoldedCount = &fc
+ }
// Apply the summary projection last so it clips whatever content the
// chosen read mode produced, uniformly across every mode.
if summary {
diff --git a/server/internal/handler/comment_fold_test.go b/server/internal/handler/comment_fold_test.go
new file mode 100644
index 0000000000..1fee8da520
--- /dev/null
+++ b/server/internal/handler/comment_fold_test.go
@@ -0,0 +1,249 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "net/url"
+ "testing"
+ "time"
+)
+
+// setCommentResolvedAt stamps resolved_at (and a member resolver) on a comment
+// directly, so a fold test can choose exactly which comment in a thread is the
+// resolution and control the resolved_at ordering. Going through SQL rather
+// than the resolve handler lets a test deliberately leave two resolutions in
+// one thread to exercise the projection's latest-wins tiebreak — the write-side
+// invariant (ClearOtherThreadResolutions) would otherwise collapse them to one.
+func setCommentResolvedAt(t *testing.T, id string, at time.Time) {
+ t.Helper()
+ if _, err := testPool.Exec(context.Background(),
+ `UPDATE comment SET resolved_at = $2, resolved_by_type = 'member', resolved_by_id = $3 WHERE id = $1`,
+ id, at, testUserID,
+ ); err != nil {
+ t.Fatalf("set resolved_at for %s: %v", id, err)
+ }
+}
+
+// byID indexes a response slice for per-comment fold-field assertions.
+func byID(rows []CommentResponse) map[string]CommentResponse {
+ m := make(map[string]CommentResponse, len(rows))
+ for _, r := range rows {
+ m[r.ID] = r
+ }
+ return m
+}
+
+// assertFolded asserts a comment carries the resolved-thread fold annotation
+// with the expected dropped count.
+func assertFolded(t *testing.T, c CommentResponse, wantCount int, ctx string) {
+ t.Helper()
+ if c.ThreadResolved == nil || !*c.ThreadResolved {
+ t.Fatalf("%s: expected thread_resolved=true on %s, got %v", ctx, c.ID, c.ThreadResolved)
+ }
+ if c.FoldedCount == nil {
+ t.Fatalf("%s: expected folded_count on %s, got nil", ctx, c.ID)
+ }
+ if *c.FoldedCount != wantCount {
+ t.Fatalf("%s: folded_count on %s got %d want %d", ctx, c.ID, *c.FoldedCount, wantCount)
+ }
+}
+
+// assertNotFolded asserts a comment carries no fold annotation (every comment
+// outside a resolved thread, and every non-root comment).
+func assertNotFolded(t *testing.T, c CommentResponse, ctx string) {
+ t.Helper()
+ if c.ThreadResolved != nil {
+ t.Fatalf("%s: expected no thread_resolved on %s, got %v", ctx, c.ID, *c.ThreadResolved)
+ }
+ if c.FoldedCount != nil {
+ t.Fatalf("%s: expected no folded_count on %s, got %v", ctx, c.ID, *c.FoldedCount)
+ }
+}
+
+// TestListComments_FoldReplyResolvedKeepsRootAndConclusion pins the core
+// reply-resolved contract: a thread whose CONCLUSION is a reply collapses to
+// root + that reply, dropping every other reply (including ones posted after the
+// conclusion — matches the human timeline's foldedReplies filter). The fixture's
+// thread1 (root1 → r1a, r1b → r1b1) has its conclusion on r1b; r1a and the
+// nested r1b1 fold away. The unresolved thread2 is returned in full.
+func TestListComments_FoldReplyResolvedKeepsRootAndConclusion(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fx := newCommentListFixture(t)
+ setCommentResolvedAt(t, fx.R1b, fx.Base.Add(20*time.Minute))
+
+ _, rows := listComments(t, fx.IssueID, "fold=true")
+ // Order is the chronological default with the folded replies removed.
+ eqIDs(t, ids(rows), []string{fx.Root1, fx.R1b, fx.Root2, fx.R2a, fx.R2b}, "reply-resolved fold")
+
+ m := byID(rows)
+ assertFolded(t, m[fx.Root1], 2, "reply-resolved") // r1a + r1b1 dropped
+ assertNotFolded(t, m[fx.R1b], "conclusion reply is not annotated")
+ assertNotFolded(t, m[fx.Root2], "unresolved thread root")
+ assertNotFolded(t, m[fx.R2a], "unresolved reply")
+}
+
+// TestListComments_FoldRootResolvedKeepsRootOnly pins the root-resolved
+// contract: resolving the ROOT collapses the whole thread to a single line (the
+// root), dropping every reply. thread2's root2 is resolved; r2a and r2b fold
+// away. thread1 stays full.
+func TestListComments_FoldRootResolvedKeepsRootOnly(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fx := newCommentListFixture(t)
+ setCommentResolvedAt(t, fx.Root2, fx.Base.Add(20*time.Minute))
+
+ _, rows := listComments(t, fx.IssueID, "fold=true")
+ eqIDs(t, ids(rows), []string{fx.Root1, fx.R1a, fx.R1b, fx.R1b1, fx.Root2}, "root-resolved fold")
+
+ m := byID(rows)
+ assertFolded(t, m[fx.Root2], 2, "root-resolved") // r2a + r2b dropped
+ for _, id := range []string{fx.Root1, fx.R1a, fx.R1b, fx.R1b1} {
+ assertNotFolded(t, m[id], "unresolved thread1 comment")
+ }
+}
+
+// TestListComments_FoldNoOpWhenNothingResolved guards the cost-saving promise's
+// floor: on an issue with no resolutions, fold=true returns the exact same set
+// as the default list, with no annotations. Folding only ever removes settled
+// discussion; it never changes an active issue's read.
+func TestListComments_FoldNoOpWhenNothingResolved(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fx := newCommentListFixture(t)
+
+ _, rows := listComments(t, fx.IssueID, "fold=true")
+ eqIDs(t, ids(rows),
+ []string{fx.Root1, fx.R1a, fx.R1b, fx.R1b1, fx.Root2, fx.R2a, fx.R2b},
+ "fold no-op")
+ for _, r := range rows {
+ assertNotFolded(t, r, "no resolutions present")
+ }
+}
+
+// TestListComments_FoldLatestReplyWins proves the projection is total even if
+// the single-resolution-per-thread write invariant is ever violated: with both
+// r1a and r1b resolved, the LATEST resolved_at (r1b) is THE conclusion, matching
+// deriveThreadResolution. root1 + r1b survive; r1a (the earlier resolution) and
+// the nested r1b1 fold away.
+func TestListComments_FoldLatestReplyWins(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fx := newCommentListFixture(t)
+ setCommentResolvedAt(t, fx.R1a, fx.Base.Add(5*time.Minute))
+ setCommentResolvedAt(t, fx.R1b, fx.Base.Add(20*time.Minute)) // later → wins
+
+ _, rows := listComments(t, fx.IssueID, "fold=true")
+ eqIDs(t, ids(rows), []string{fx.Root1, fx.R1b, fx.Root2, fx.R2a, fx.R2b}, "latest reply wins")
+ assertFolded(t, byID(rows)[fx.Root1], 2, "latest-wins fold")
+}
+
+// TestListComments_FoldComposesWithRecent confirms fold applies per thread under
+// the --recent grouping (the assignment-entry read the prompt steers agents to).
+// recent returns both threads; the reply-resolved thread1 folds to root1 + r1b
+// while the unresolved thread2 stays full.
+func TestListComments_FoldComposesWithRecent(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fx := newCommentListFixture(t)
+ setCommentResolvedAt(t, fx.R1b, fx.Base.Add(20*time.Minute))
+
+ v := url.Values{}
+ v.Set("fold", "true")
+ v.Set("recent", "10")
+ _, rows := listComments(t, fx.IssueID, v.Encode())
+ eqIDs(t, ids(rows), []string{fx.Root1, fx.R1b, fx.Root2, fx.R2a, fx.R2b}, "fold + recent")
+ assertFolded(t, byID(rows)[fx.Root1], 2, "fold + recent")
+}
+
+// TestListComments_FoldComposesWithSummary confirms the two agent-token
+// projections stack: fold drops the settled replies, then summary's per-comment
+// clip still runs over what remains. The surviving root carries BOTH the fold
+// annotation and the summary's content_truncated marker.
+func TestListComments_FoldComposesWithSummary(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fx := newCommentListFixture(t)
+ setCommentResolvedAt(t, fx.R1b, fx.Base.Add(20*time.Minute))
+
+ v := url.Values{}
+ v.Set("fold", "true")
+ v.Set("summary", "true")
+ _, rows := listComments(t, fx.IssueID, v.Encode())
+ eqIDs(t, ids(rows), []string{fx.Root1, fx.R1b, fx.Root2, fx.R2a, fx.R2b}, "fold + summary")
+
+ root1 := byID(rows)[fx.Root1]
+ assertFolded(t, root1, 2, "fold + summary")
+ if root1.ContentTruncated == nil {
+ t.Fatalf("fold + summary: expected content_truncated marker on root1, got nil")
+ }
+}
+
+// TestListComments_FoldRejectsPartialThreadModes pins the safety boundary: fold
+// needs whole threads to compute a resolution, so it is rejected on the
+// partial-thread reads (since, tail) and on roots_only (no replies to fold).
+// Returning 400 — rather than silently folding a partial thread — is what stops
+// the projection from dropping a resolution that was never fetched.
+func TestListComments_FoldRejectsPartialThreadModes(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fx := newCommentListFixture(t)
+
+ since := fx.Base.Add(5 * time.Minute).UTC().Format(time.RFC3339Nano)
+ for _, tc := range []struct {
+ name string
+ query func() string
+ }{
+ {name: "fold + since", query: func() string {
+ v := url.Values{}
+ v.Set("fold", "true")
+ v.Set("since", since)
+ return v.Encode()
+ }},
+ {name: "fold + tail", query: func() string {
+ v := url.Values{}
+ v.Set("fold", "true")
+ v.Set("thread", fx.Root1)
+ v.Set("tail", "2")
+ return v.Encode()
+ }},
+ {name: "fold + roots_only", query: func() string {
+ v := url.Values{}
+ v.Set("fold", "true")
+ v.Set("roots_only", "true")
+ return v.Encode()
+ }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ w, _ := listComments(t, fx.IssueID, tc.query())
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("%s: expected 400, got %d: %s", tc.name, w.Code, w.Body.String())
+ }
+ })
+ }
+}
+
+// TestListComments_FoldComposesWithThread confirms fold applies to an untailed
+// single-thread read: reading just the reply-resolved thread1 returns root1 +
+// conclusion, dropping the intermediate replies.
+func TestListComments_FoldComposesWithThread(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fx := newCommentListFixture(t)
+ setCommentResolvedAt(t, fx.R1b, fx.Base.Add(20*time.Minute))
+
+ v := url.Values{}
+ v.Set("fold", "true")
+ v.Set("thread", fx.R1a) // anchor on a reply; server resolves to root1
+ _, rows := listComments(t, fx.IssueID, v.Encode())
+ eqIDs(t, ids(rows), []string{fx.Root1, fx.R1b}, "fold + thread")
+ assertFolded(t, byID(rows)[fx.Root1], 2, "fold + thread")
+}