Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(comments): roots-only thread stats + summary projection for comment list (MUL-2809) (#3505)
Bohan Jiang75b5be3f8ede
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.goindex aa85b27556..ebe0013cee 100644--- a/server/cmd/multica/cmd_issue.go+++ b/server/cmd/multica/cmd_issue.go@@ -315,7 +315,8 @@ func init() {issueCommentListCmd.Flags().String("thread", "", "Comment UUID — return the thread containing this comment (root + every descendant). May be a root or a reply id.")issueCommentListCmd.Flags().Int("tail", 0, "Only valid with --thread. Cap reply count to the N most recent replies; the thread root is always included (even with --tail 0). Use --before/--before-id to scroll to older replies.")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)")+ 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().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.")@@ -942,6 +943,7 @@ func runIssueCommentList(cmd *cobra.Command, args []string) error {recent, _ := cmd.Flags().GetInt("recent")tail, _ := cmd.Flags().GetInt("tail")rootsOnly, _ := cmd.Flags().GetBool("roots-only")+ summary, _ := cmd.Flags().GetBool("summary")// 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@@ -995,6 +997,9 @@ func runIssueCommentList(cmd *cobra.Command, args []string) error {if rootsOnly {params.Set("roots_only", "true")}+ if summary {+ params.Set("summary", "true")+ }if thread != "" {params.Set("thread", thread)}diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.goindex 3ecd6f933c..cc94ca4a41 100644--- a/server/cmd/multica/cmd_issue_test.go+++ b/server/cmd/multica/cmd_issue_test.go@@ -1553,6 +1553,7 @@ func newIssueCommentListTestCmd() *cobra.Command {cmd.Flags().String("output", "json", "")cmd.Flags().String("since", "", "")cmd.Flags().Bool("roots-only", false, "")+ cmd.Flags().Bool("summary", false, "")cmd.Flags().String("thread", "", "")cmd.Flags().Int("recent", 0, "")cmd.Flags().Int("tail", 0, "")@@ -1760,6 +1761,53 @@ func TestRunIssueCommentList_RootsOnlyPassesThroughWithSince(t *testing.T) {}}+// TestRunIssueCommentList_SummaryPassesThrough pins the CLI side of the summary+// projection: --summary must forward summary=true, and it must compose with+// --roots-only (the orientation read it pairs with most often) rather than+// being rejected as an incompatible combination.+func TestRunIssueCommentList_SummaryPassesThrough(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")++ cmd := newIssueCommentListTestCmd()+ if err := cmd.Flags().Set("summary", "true"); err != nil {+ t.Fatalf("set summary: %v", err)+ }+ if err := cmd.Flags().Set("roots-only", "true"); err != nil {+ t.Fatalf("set roots-only: %v", err)+ }+ if err := runIssueCommentList(cmd, []string{"MUL-1"}); err != nil {+ t.Fatalf("runIssueCommentList: %v", err)+ }++ if got := gotQuery.Get("summary"); got != "true" {+ t.Errorf("summary query = %q, want true", got)+ }+ if got := gotQuery.Get("roots_only"); got != "true" {+ t.Errorf("roots_only query = %q, want true", got)+ }+}+// TestRunIssueCommentList_ThreadTailPassesThroughAndPrintsReplyCursor pins// the positive path for --thread + --tail: the CLI forwards `thread` +// `tail` query params and, on response, prints "Next reply cursor" (notdiff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex a1db5c89ec..b5d7dacde2 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -33,6 +33,18 @@ type CommentResponse struct {ResolvedByID *string `json:"resolved_by_id"`Reactions []ReactionResponse `json:"reactions"`Attachments []AttachmentResponse `json:"attachments"`+ // Orientation stats — populated only on the roots_only path and omitted in+ // every other mode, so the default response shape stays byte-identical for+ // existing callers. ReplyCount is the number of descendants in the thread;+ // LastActivityAt is the MAX(created_at) across the whole subtree. Together+ // they let an agent triage which thread to drill into without fetching any+ // replies.+ ReplyCount *int `json:"reply_count,omitempty"`+ LastActivityAt *string `json:"last_activity_at,omitempty"`+ // ContentTruncated is set only under summary=true: true when Content was+ // 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"`}func commentToResponse(c db.Comment, reactions []ReactionResponse, attachments []AttachmentResponse) CommentResponse {@@ -60,6 +72,30 @@ func commentToResponse(c db.Comment, reactions []ReactionResponse, attachments [}}+// summaryContentRunes bounds comment content under summary=true. 200 runes is+// enough to tell what a comment is about (its opening) while cutting the bulk+// of a long body out of an agent's context budget. Counted in runes, not bytes,+// so multi-byte (e.g. CJK) content is clipped on a character boundary.+const summaryContentRunes = 200++// summarizeContent clips content to summaryContentRunes for the summary+// projection. Returns the (possibly clipped) content and whether it was+// truncated. An ellipsis marks a clip so the reader knows more text exists.+//+// It scans by rune and stops at the (budget+1)th rune rather than allocating a+// full []rune for the whole body — so a pathologically long comment costs only+// the budget, not its full length, under summary mode.+func summarizeContent(content string) (string, bool) {+ count := 0+ for byteOffset := range content { // range over a string yields rune start offsets+ if count == summaryContentRunes {+ return content[:byteOffset] + "…", true+ }+ count+++ }+ return content, false+}+// 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@@ -73,10 +109,16 @@ const commentHardCap = 2000// agent-style readers bounded views that scale to long issues without dragging// every prior reply into context://-// - roots_only=true — return only top-level comments (parent_id IS NULL).-// May combine with since for incremental polling of newly created roots,-// but is exclusive with thread/recent/tail/cursor modes because those-// have their own grouping or pagination semantics.+// - roots_only=true — return only top-level comments (parent_id IS NULL),+// each annotated with reply_count + last_activity_at so the caller can+// triage which thread to drill into. May combine with since for incremental+// polling of newly created roots, but is exclusive with thread/recent/tail/+// cursor modes because those have their own grouping or pagination semantics.+//+// - summary=true — orthogonal content projection. Clips each returned+// comment's content to a fixed budget and sets content_truncated, so an+// agent can scan a list cheaply before pulling a full body. Composes with+// every mode (default, since, thread, recent, roots_only).//// - thread=<comment-uuid> — return the root of the thread containing this// comment plus every descendant. The anchor may be a root or any reply;@@ -183,6 +225,23 @@ func (h *Handler) ListComments(w http.ResponseWriter, r *http.Request) {}}+ // summary=true is an orthogonal content projection: it clips each comment's+ // content to a fixed budget so an agent can scan a list without pulling full+ // bodies into context. It is intentionally NOT mutually exclusive with any+ // mode — it composes with the default list, since, thread, recent, and+ // roots_only alike.+ summary := false+ if summaryStr := q.Get("summary"); summaryStr != "" {+ switch summaryStr {+ case "true":+ summary = true+ case "false":+ default:+ writeError(w, http.StatusBadRequest, "invalid summary parameter; expected boolean")+ return+ }+ }+// --- combination validation ----------------------------------------if rootsOnly && threadStr != "" {writeError(w, http.StatusBadRequest, "roots_only and thread are mutually exclusive")@@ -314,6 +373,22 @@ func (h *Handler) ListComments(w http.ResponseWriter, r *http.Request) {for i, c := range result.Comments {cid := uuidToString(c.ID)resp[i] = commentToResponse(c, grouped[cid], groupedAtt[cid])+ // Attach roots_only orientation stats when present (nil map elsewhere).+ if st, ok := result.RootStats[cid]; ok {+ rc := st.ReplyCount+ resp[i].ReplyCount = &rc+ if st.LastActivityAt.Valid {+ la := timestampToString(st.LastActivityAt)+ resp[i].LastActivityAt = &la+ }+ }+ // Apply the summary projection last so it clips whatever content the+ // chosen read mode produced, uniformly across every mode.+ if summary {+ clipped, truncated := summarizeContent(resp[i].Content)+ resp[i].Content = clipped+ resp[i].ContentTruncated = &truncated+ }}// Emit the next cursor as response headers when the page is likely not@@ -360,6 +435,16 @@ type fetchCommentsResult struct {Comments []db.CommentNextBefore stringNextBeforeID string+ // RootStats carries per-root orientation stats keyed by comment id string.+ // Populated only on the roots_only path; nil for every other mode.+ RootStats map[string]rootStat+}++// rootStat is the per-thread orientation metadata attached to each root comment+// on the roots_only path. See CommentResponse.ReplyCount / LastActivityAt.+type rootStat struct {+ ReplyCount int+ LastActivityAt pgtype.Timestamptz}var (@@ -614,23 +699,51 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr// Root-only read for issue-level orientation. This intentionally// stays separate from thread/recent modes: callers get the global// top-level discussion first, then fetch a specific thread only when- // they need reply context.+ // they need reply context. Each root carries reply_count ++ // last_activity_at so the reader can triage which thread to drill into.+ stats := map[string]rootStat{}if args.Since.Valid {- comments, err := h.Queries.ListRootCommentsSinceForIssue(ctx, db.ListRootCommentsSinceForIssueParams{+ rows, err := h.Queries.ListRootCommentsSinceForIssue(ctx, db.ListRootCommentsSinceForIssueParams{IssueID: issue.ID,WorkspaceID: issue.WorkspaceID,- CreatedAt: args.Since,- Limit: commentHardCap,+ Since: args.Since,+ RowLimit: commentHardCap,})- return fetchCommentsResult{Comments: comments}, err+ if err != nil {+ return fetchCommentsResult{}, err+ }+ comments := make([]db.Comment, len(rows))+ for i, r := range rows {+ comments[i] = db.Comment{+ ID: r.ID, IssueID: r.IssueID, AuthorType: r.AuthorType, AuthorID: r.AuthorID,+ Content: r.Content, Type: r.Type, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt,+ ParentID: r.ParentID, WorkspaceID: r.WorkspaceID, ResolvedAt: r.ResolvedAt,+ ResolvedByType: r.ResolvedByType, ResolvedByID: r.ResolvedByID,+ }+ stats[uuidToString(r.ID)] = rootStat{ReplyCount: int(r.ReplyCount), LastActivityAt: r.LastActivityAt}+ }+ return fetchCommentsResult{Comments: comments, RootStats: stats}, nil}- comments, err := h.Queries.ListRootCommentsForIssue(ctx, db.ListRootCommentsForIssueParams{+ rows, err := h.Queries.ListRootCommentsForIssue(ctx, db.ListRootCommentsForIssueParams{IssueID: issue.ID,WorkspaceID: issue.WorkspaceID,- Limit: commentHardCap,+ RowLimit: commentHardCap,})- return fetchCommentsResult{Comments: comments}, err+ if err != nil {+ return fetchCommentsResult{}, err+ }+ comments := make([]db.Comment, len(rows))+ for i, r := range rows {+ comments[i] = db.Comment{+ ID: r.ID, IssueID: r.IssueID, AuthorType: r.AuthorType, AuthorID: r.AuthorID,+ Content: r.Content, Type: r.Type, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt,+ ParentID: r.ParentID, WorkspaceID: r.WorkspaceID, ResolvedAt: r.ResolvedAt,+ ResolvedByType: r.ResolvedByType, ResolvedByID: r.ResolvedByID,+ }+ stats[uuidToString(r.ID)] = rootStat{ReplyCount: int(r.ReplyCount), LastActivityAt: r.LastActivityAt}+ }+ return fetchCommentsResult{Comments: comments, RootStats: stats}, nil}// Default + since paths preserved verbatim (no behavioural change fordiff --git a/server/internal/handler/comment_list_test.go b/server/internal/handler/comment_list_test.goindex ae68016e75..7e820ff138 100644--- a/server/internal/handler/comment_list_test.go+++ b/server/internal/handler/comment_list_test.go@@ -7,8 +7,10 @@ import ("net/http/httptest""net/url""strconv"+ "strings""testing""time"+ "unicode/utf8""github.com/google/uuid""github.com/jackc/pgx/v5/pgtype"@@ -227,6 +229,206 @@ func TestListComments_RootsOnlyWithSinceReturnsNewTopLevelComments(t *testing.T)}}+// TestListComments_RootsOnlyReturnsThreadStats pins the orientation metadata:+// each root returned by roots_only carries reply_count (recursive descendant+// count) and last_activity_at (MAX created_at over the subtree), so an agent+// can triage which thread to open without fetching any replies. The fixture's+// root1 has a nested reply (r1b1 → r1b → root1), proving the count walks deeper+// than one level. Stats are roots-only — the default list must not carry them.+func TestListComments_RootsOnlyReturnsThreadStats(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ fx := newCommentListFixture(t)++ _, rows := listComments(t, fx.IssueID, "roots_only=true")+ eqIDs(t, ids(rows), []string{fx.Root1, fx.Root2}, "roots stats order")++ byID := map[string]CommentResponse{}+ for _, r := range rows {+ byID[r.ID] = r+ }+ // root1: r1a, r1b, r1b1 (nested) → 3 replies; newest activity is r1b1 at +3m.+ assertRootStat(t, byID[fx.Root1], "root1", 3, fx.Base.Add(3*time.Minute))+ // root2: r2a, r2b → 2 replies; newest activity is r2b at +12m.+ assertRootStat(t, byID[fx.Root2], "root2", 2, fx.Base.Add(12*time.Minute))++ // The default (non-roots) list must NOT leak the roots-only stats.+ _, all := listComments(t, fx.IssueID, "")+ for _, r := range all {+ if r.ReplyCount != nil || r.LastActivityAt != nil {+ t.Fatalf("default list leaked roots-only stats on %s (reply_count=%v last_activity=%v)", r.ID, r.ReplyCount, r.LastActivityAt)+ }+ }+}++func assertRootStat(t *testing.T, c CommentResponse, label string, wantReplies int, wantLastActivity time.Time) {+ t.Helper()+ if c.ReplyCount == nil {+ t.Fatalf("%s: reply_count missing", label)+ }+ if *c.ReplyCount != wantReplies {+ t.Fatalf("%s: reply_count got=%d want=%d", label, *c.ReplyCount, wantReplies)+ }+ if c.LastActivityAt == nil {+ t.Fatalf("%s: last_activity_at missing", label)+ }+ got, err := time.Parse(time.RFC3339, *c.LastActivityAt)+ if err != nil {+ t.Fatalf("%s: last_activity_at parse %q: %v", label, *c.LastActivityAt, err)+ }+ if !got.Equal(wantLastActivity) {+ t.Fatalf("%s: last_activity_at got=%s want=%s", label, got.UTC(), wantLastActivity.UTC())+ }+}++// TestListComments_SummaryClipsContent pins the summary projection: with+// summary=true a long body is clipped to summaryContentRunes (+ellipsis) and+// flagged content_truncated=true, a short body is returned verbatim with+// content_truncated=false, and without summary the field is omitted entirely so+// the default response shape is unchanged.+func TestListComments_SummaryClipsContent(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, creator_type, creator_id, title)+ VALUES ($1, 'member', $2, $3)+ RETURNING id+ `, testWorkspaceID, testUserID, "summary fixture").Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)+ })++ base := time.Now().UTC().Add(-time.Hour).Truncate(time.Second)+ insert := func(body string, offset time.Duration) string {+ t.Helper()+ var id string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)+ VALUES ($1, $2, 'member', $3, $4, 'comment', $5)+ RETURNING id+ `, issueID, testWorkspaceID, testUserID, body, base.Add(offset)).Scan(&id); err != nil {+ t.Fatalf("insert comment: %v", err)+ }+ return id+ }+ longID := insert(strings.Repeat("x", 500), 0)+ shortID := insert("short", time.Minute)+ // Multi-byte body: clipping must land on a rune boundary, never mid-rune.+ cjkID := insert(strings.Repeat("你", 300), 2*time.Minute)++ // Baseline: no summary → full content, content_truncated omitted.+ _, full := listComments(t, issueID, "")+ for _, c := range full {+ if c.ContentTruncated != nil {+ t.Fatalf("baseline: content_truncated should be nil, got %v on %s", *c.ContentTruncated, c.ID)+ }+ if c.ID == longID && utf8.RuneCountInString(c.Content) != 500 {+ t.Fatalf("baseline: long content len got=%d want=500", utf8.RuneCountInString(c.Content))+ }+ }++ // summary=true → long clipped + truncated true; short verbatim + false.+ _, sum := listComments(t, issueID, "summary=true")+ byID := map[string]CommentResponse{}+ for _, c := range sum {+ byID[c.ID] = c+ }+ long := byID[longID]+ if long.ContentTruncated == nil || !*long.ContentTruncated {+ t.Fatalf("summary: long comment should be truncated, got %v", long.ContentTruncated)+ }+ if rc := utf8.RuneCountInString(long.Content); rc != summaryContentRunes+1 { // +1 for the ellipsis+ t.Fatalf("summary: long content rune count got=%d want=%d", rc, summaryContentRunes+1)+ }+ if !strings.HasSuffix(long.Content, "…") {+ t.Fatalf("summary: long content should end with ellipsis, got %q", long.Content)+ }+ short := byID[shortID]+ if short.ContentTruncated == nil || *short.ContentTruncated {+ t.Fatalf("summary: short comment should be untruncated (false), got %v", short.ContentTruncated)+ }+ if short.Content != "short" {+ t.Fatalf("summary: short content got=%q want=short", short.Content)+ }+ cjk := byID[cjkID]+ if cjk.ContentTruncated == nil || !*cjk.ContentTruncated {+ t.Fatalf("summary: cjk comment should be truncated, got %v", cjk.ContentTruncated)+ }+ if !utf8.ValidString(cjk.Content) {+ t.Fatalf("summary: cjk content was clipped mid-rune (invalid UTF-8): %q", cjk.Content)+ }+ if rc := utf8.RuneCountInString(cjk.Content); rc != summaryContentRunes+1 { // 200 CJK runes + ellipsis+ t.Fatalf("summary: cjk content rune count got=%d want=%d", rc, summaryContentRunes+1)+ }+ if !strings.HasSuffix(cjk.Content, "你…") {+ t.Fatalf("summary: cjk content should be whole 你-runes then ellipsis, got %q", cjk.Content)+ }+}++// TestListComments_RootsOnlySummaryComposes pins the spec's headline+// "table of contents" read: --roots-only --summary together must (a) clip each+// root's content and flag content_truncated, AND (b) still carry the roots-only+// orientation stats (reply_count over the full subtree, last_activity_at). The+// summary projection composes with roots_only rather than replacing its stats;+// a future refactor that moved the clip into a per-mode branch would silently+// break this composition, so both halves are asserted on the same response.+func TestListComments_RootsOnlySummaryComposes(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, creator_type, creator_id, title)+ VALUES ($1, 'member', $2, $3)+ RETURNING id+ `, testWorkspaceID, testUserID, "roots+summary fixture").Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)+ })++ base := time.Now().UTC().Add(-time.Hour).Truncate(time.Second)+ insert := func(parent *string, body string, offset time.Duration) string {+ t.Helper()+ var id string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, created_at)+ VALUES ($1, $2, 'member', $3, $4, 'comment', $5, $6)+ RETURNING id+ `, issueID, testWorkspaceID, testUserID, body, parent, base.Add(offset)).Scan(&id); err != nil {+ t.Fatalf("insert comment: %v", err)+ }+ return id+ }+ rootID := insert(nil, strings.Repeat("x", 500), 0)+ insert(&rootID, "a reply", 5*time.Minute) // pushes last_activity past the root's own time++ _, rows := listComments(t, issueID, "roots_only=true&summary=true")+ eqIDs(t, ids(rows), []string{rootID}, "roots_only+summary returns only the root")++ root := rows[0]+ // Summary half: the long root content is clipped + flagged.+ if root.ContentTruncated == nil || !*root.ContentTruncated {+ t.Fatalf("roots+summary: root should be truncated, got %v", root.ContentTruncated)+ }+ if rc := utf8.RuneCountInString(root.Content); rc != summaryContentRunes+1 { // +1 for the ellipsis+ t.Fatalf("roots+summary: clipped content rune count got=%d want=%d", rc, summaryContentRunes+1)+ }+ // Stats half: orientation metadata survives the summary projection. The+ // reply (1 descendant, +5m) drives both reply_count and last_activity_at.+ assertRootStat(t, root, "root", 1, base.Add(5*time.Minute))+}+// TestListComments_ThreadResolvesFromAnyAnchor proves Elon's point 2:// regardless of whether the anchor is a root, a direct reply, or a nested// reply (parent_id points at another reply), the server walks up to the@@ -608,6 +810,11 @@ func TestListComments_FlagCombinationRules(t *testing.T) {query: "roots_only=yes",status: http.StatusBadRequest,},+ {+ name: "non-boolean summary rejected",+ query: "summary=yes",+ status: http.StatusBadRequest,+ },{name: "roots_only + thread rejected",query: "roots_only=true&thread=" + fx.Root1,diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.goindex f68957f183..677cf66e49 100644--- a/server/pkg/db/generated/comment.sql.go+++ b/server/pkg/db/generated/comment.sql.go@@ -513,30 +513,90 @@ func (q *Queries) ListRecentThreadCommentsForIssue(ctx context.Context, arg List}const listRootCommentsForIssue = `-- name: ListRootCommentsForIssue :many-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id FROM comment-WHERE issue_id = $1 AND workspace_id = $2 AND parent_id IS NULL-ORDER BY created_at ASC, id ASC-LIMIT $3+WITH RECURSIVE selected_roots AS (+ SELECT c.id, c.created_at+ FROM comment c+ WHERE c.issue_id = $1+ AND c.workspace_id = $2+ AND c.parent_id IS NULL+ ORDER BY c.created_at ASC, c.id ASC+ LIMIT $3+),+membership(id, root_id, comment_created_at) AS (+ SELECT sr.id, sr.id AS root_id, sr.created_at+ FROM selected_roots sr+ UNION ALL+ SELECT c.id, m.root_id, c.created_at+ FROM comment c+ JOIN membership m ON c.parent_id = m.id+ WHERE c.issue_id = $1+ AND c.workspace_id = $2+),+thread_stats AS (+ SELECT root_id,+ (COUNT(*) - 1)::int AS reply_count,+ MAX(comment_created_at)::timestamptz AS last_activity_at+ FROM membership+ GROUP BY root_id+)+SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,+ c.created_at, c.updated_at, c.parent_id, c.workspace_id,+ c.resolved_at, c.resolved_by_type, c.resolved_by_id,+ ts.reply_count AS reply_count,+ ts.last_activity_at AS last_activity_at+FROM selected_roots sr+JOIN comment c ON c.id = sr.id+JOIN thread_stats ts ON ts.root_id = sr.id+ORDER BY c.created_at ASC, c.id ASC`type ListRootCommentsForIssueParams struct {IssueID pgtype.UUID `json:"issue_id"`WorkspaceID pgtype.UUID `json:"workspace_id"`- Limit int32 `json:"limit"`+ RowLimit int32 `json:"row_limit"`+}++type ListRootCommentsForIssueRow struct {+ ID pgtype.UUID `json:"id"`+ IssueID pgtype.UUID `json:"issue_id"`+ AuthorType string `json:"author_type"`+ AuthorID pgtype.UUID `json:"author_id"`+ Content string `json:"content"`+ Type string `json:"type"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ ParentID pgtype.UUID `json:"parent_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ResolvedAt pgtype.Timestamptz `json:"resolved_at"`+ ResolvedByType pgtype.Text `json:"resolved_by_type"`+ ResolvedByID pgtype.UUID `json:"resolved_by_id"`+ ReplyCount int32 `json:"reply_count"`+ LastActivityAt pgtype.Timestamptz `json:"last_activity_at"`}-// Top-level comments only, in issue chronological order. This powers-// `comment list --roots-only` so agents can orient around the global issue-// discussion before fetching any specific reply thread.-func (q *Queries) ListRootCommentsForIssue(ctx context.Context, arg ListRootCommentsForIssueParams) ([]Comment, error) {- rows, err := q.db.Query(ctx, listRootCommentsForIssue, arg.IssueID, arg.WorkspaceID, arg.Limit)+// Top-level comments only, in issue chronological order, each annotated with+// per-thread orientation stats: reply_count (number of descendants) and+// last_activity_at (MAX(created_at) over the whole subtree). This powers+// `comment list --roots-only` so agents can not only orient around the global+// discussion but also triage which thread to drill into (biggest / most+// recently active) before fetching any specific reply thread.+//+// `selected_roots` picks the roots we will actually return first (the chrono+// page of size @row_limit), so the recursive `membership` walk only expands+// those threads' subtrees instead of every thread in the issue. membership+// labels each comment with its thread root by walking down from the selected+// roots, so the counts stay correct even if the schema ever allows+// reply-of-reply (the write path collapses to root today, but does not enforce+// it). Mirrors ListRecentThreadCommentsForIssue's stats CTE.+func (q *Queries) ListRootCommentsForIssue(ctx context.Context, arg ListRootCommentsForIssueParams) ([]ListRootCommentsForIssueRow, error) {+ rows, err := q.db.Query(ctx, listRootCommentsForIssue, arg.IssueID, arg.WorkspaceID, arg.RowLimit)if err != nil {return nil, err}defer rows.Close()- items := []Comment{}+ items := []ListRootCommentsForIssueRow{}for rows.Next() {- var i Comment+ var i ListRootCommentsForIssueRowif err := rows.Scan(&i.ID,&i.IssueID,@@ -551,6 +611,8 @@ func (q *Queries) ListRootCommentsForIssue(ctx context.Context, arg ListRootComm&i.ResolvedAt,&i.ResolvedByType,&i.ResolvedByID,+ &i.ReplyCount,+ &i.LastActivityAt,); err != nil {return nil, err}@@ -563,35 +625,90 @@ func (q *Queries) ListRootCommentsForIssue(ctx context.Context, arg ListRootComm}const listRootCommentsSinceForIssue = `-- name: ListRootCommentsSinceForIssue :many-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id FROM comment-WHERE issue_id = $1 AND workspace_id = $2 AND parent_id IS NULL AND created_at > $3-ORDER BY created_at ASC, id ASC-LIMIT $4+WITH RECURSIVE selected_roots AS (+ SELECT c.id, c.created_at+ FROM comment c+ WHERE c.issue_id = $1+ AND c.workspace_id = $2+ AND c.parent_id IS NULL+ AND c.created_at > $3+ ORDER BY c.created_at ASC, c.id ASC+ LIMIT $4+),+membership(id, root_id, comment_created_at) AS (+ SELECT sr.id, sr.id AS root_id, sr.created_at+ FROM selected_roots sr+ UNION ALL+ SELECT c.id, m.root_id, c.created_at+ FROM comment c+ JOIN membership m ON c.parent_id = m.id+ WHERE c.issue_id = $1+ AND c.workspace_id = $2+),+thread_stats AS (+ SELECT root_id,+ (COUNT(*) - 1)::int AS reply_count,+ MAX(comment_created_at)::timestamptz AS last_activity_at+ FROM membership+ GROUP BY root_id+)+SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,+ c.created_at, c.updated_at, c.parent_id, c.workspace_id,+ c.resolved_at, c.resolved_by_type, c.resolved_by_id,+ ts.reply_count AS reply_count,+ ts.last_activity_at AS last_activity_at+FROM selected_roots sr+JOIN comment c ON c.id = sr.id+JOIN thread_stats ts ON ts.root_id = sr.id+ORDER BY c.created_at ASC, c.id ASC`type ListRootCommentsSinceForIssueParams struct {IssueID pgtype.UUID `json:"issue_id"`WorkspaceID pgtype.UUID `json:"workspace_id"`- CreatedAt pgtype.Timestamptz `json:"created_at"`- Limit int32 `json:"limit"`+ Since pgtype.Timestamptz `json:"since"`+ RowLimit int32 `json:"row_limit"`+}++type ListRootCommentsSinceForIssueRow struct {+ ID pgtype.UUID `json:"id"`+ IssueID pgtype.UUID `json:"issue_id"`+ AuthorType string `json:"author_type"`+ AuthorID pgtype.UUID `json:"author_id"`+ Content string `json:"content"`+ Type string `json:"type"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ ParentID pgtype.UUID `json:"parent_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ResolvedAt pgtype.Timestamptz `json:"resolved_at"`+ ResolvedByType pgtype.Text `json:"resolved_by_type"`+ ResolvedByID pgtype.UUID `json:"resolved_by_id"`+ ReplyCount int32 `json:"reply_count"`+ LastActivityAt pgtype.Timestamptz `json:"last_activity_at"`}-// Top-level comments created strictly after $3. Same semantics as-// ListCommentsSinceForIssue, narrowed to thread roots.-func (q *Queries) ListRootCommentsSinceForIssue(ctx context.Context, arg ListRootCommentsSinceForIssueParams) ([]Comment, error) {+// Top-level comments created strictly after @since, each annotated with the+// same reply_count / last_activity_at stats as ListRootCommentsForIssue. The+// @since filter narrows which roots are returned; the stats are still computed+// over each selected thread's full subtree (so a freshly created root with no+// replies reports reply_count 0 and last_activity_at = its own created_at).+// selected_roots applies the @since + @row_limit cut up front so the recursive+// membership walk only touches the subtrees of the roots we actually return.+func (q *Queries) ListRootCommentsSinceForIssue(ctx context.Context, arg ListRootCommentsSinceForIssueParams) ([]ListRootCommentsSinceForIssueRow, error) {rows, err := q.db.Query(ctx, listRootCommentsSinceForIssue,arg.IssueID,arg.WorkspaceID,- arg.CreatedAt,- arg.Limit,+ arg.Since,+ arg.RowLimit,)if err != nil {return nil, err}defer rows.Close()- items := []Comment{}+ items := []ListRootCommentsSinceForIssueRow{}for rows.Next() {- var i Comment+ var i ListRootCommentsSinceForIssueRowif err := rows.Scan(&i.ID,&i.IssueID,@@ -606,6 +723,8 @@ func (q *Queries) ListRootCommentsSinceForIssue(ctx context.Context, arg ListRoo&i.ResolvedAt,&i.ResolvedByType,&i.ResolvedByID,+ &i.ReplyCount,+ &i.LastActivityAt,); err != nil {return nil, err}diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sqlindex 5e7ef2a5a6..ef073fcf93 100644--- a/server/pkg/db/queries/comment.sql+++ b/server/pkg/db/queries/comment.sql@@ -16,21 +16,100 @@ ORDER BY created_at ASC, id ASCLIMIT $4;-- name: ListRootCommentsForIssue :many--- Top-level comments only, in issue chronological order. This powers--- `comment list --roots-only` so agents can orient around the global issue--- discussion before fetching any specific reply thread.-SELECT * FROM comment-WHERE issue_id = $1 AND workspace_id = $2 AND parent_id IS NULL-ORDER BY created_at ASC, id ASC-LIMIT $3;+-- Top-level comments only, in issue chronological order, each annotated with+-- per-thread orientation stats: reply_count (number of descendants) and+-- last_activity_at (MAX(created_at) over the whole subtree). This powers+-- `comment list --roots-only` so agents can not only orient around the global+-- discussion but also triage which thread to drill into (biggest / most+-- recently active) before fetching any specific reply thread.+--+-- `selected_roots` picks the roots we will actually return first (the chrono+-- page of size @row_limit), so the recursive `membership` walk only expands+-- those threads' subtrees instead of every thread in the issue. membership+-- labels each comment with its thread root by walking down from the selected+-- roots, so the counts stay correct even if the schema ever allows+-- reply-of-reply (the write path collapses to root today, but does not enforce+-- it). Mirrors ListRecentThreadCommentsForIssue's stats CTE.+WITH RECURSIVE selected_roots AS (+ SELECT c.id, c.created_at+ FROM comment c+ WHERE c.issue_id = @issue_id+ AND c.workspace_id = @workspace_id+ AND c.parent_id IS NULL+ ORDER BY c.created_at ASC, c.id ASC+ LIMIT @row_limit+),+membership(id, root_id, comment_created_at) AS (+ SELECT sr.id, sr.id AS root_id, sr.created_at+ FROM selected_roots sr+ UNION ALL+ SELECT c.id, m.root_id, c.created_at+ FROM comment c+ JOIN membership m ON c.parent_id = m.id+ WHERE c.issue_id = @issue_id+ AND c.workspace_id = @workspace_id+),+thread_stats AS (+ SELECT root_id,+ (COUNT(*) - 1)::int AS reply_count,+ MAX(comment_created_at)::timestamptz AS last_activity_at+ FROM membership+ GROUP BY root_id+)+SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,+ c.created_at, c.updated_at, c.parent_id, c.workspace_id,+ c.resolved_at, c.resolved_by_type, c.resolved_by_id,+ ts.reply_count AS reply_count,+ ts.last_activity_at AS last_activity_at+FROM selected_roots sr+JOIN comment c ON c.id = sr.id+JOIN thread_stats ts ON ts.root_id = sr.id+ORDER BY c.created_at ASC, c.id ASC;-- name: ListRootCommentsSinceForIssue :many--- Top-level comments created strictly after $3. Same semantics as--- ListCommentsSinceForIssue, narrowed to thread roots.-SELECT * FROM comment-WHERE issue_id = $1 AND workspace_id = $2 AND parent_id IS NULL AND created_at > $3-ORDER BY created_at ASC, id ASC-LIMIT $4;+-- Top-level comments created strictly after @since, each annotated with the+-- same reply_count / last_activity_at stats as ListRootCommentsForIssue. The+-- @since filter narrows which roots are returned; the stats are still computed+-- over each selected thread's full subtree (so a freshly created root with no+-- replies reports reply_count 0 and last_activity_at = its own created_at).+-- selected_roots applies the @since + @row_limit cut up front so the recursive+-- membership walk only touches the subtrees of the roots we actually return.+WITH RECURSIVE selected_roots AS (+ SELECT c.id, c.created_at+ FROM comment c+ WHERE c.issue_id = @issue_id+ AND c.workspace_id = @workspace_id+ AND c.parent_id IS NULL+ AND c.created_at > @since+ ORDER BY c.created_at ASC, c.id ASC+ LIMIT @row_limit+),+membership(id, root_id, comment_created_at) AS (+ SELECT sr.id, sr.id AS root_id, sr.created_at+ FROM selected_roots sr+ UNION ALL+ SELECT c.id, m.root_id, c.created_at+ FROM comment c+ JOIN membership m ON c.parent_id = m.id+ WHERE c.issue_id = @issue_id+ AND c.workspace_id = @workspace_id+),+thread_stats AS (+ SELECT root_id,+ (COUNT(*) - 1)::int AS reply_count,+ MAX(comment_created_at)::timestamptz AS last_activity_at+ FROM membership+ GROUP BY root_id+)+SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,+ c.created_at, c.updated_at, c.parent_id, c.workspace_id,+ c.resolved_at, c.resolved_by_type, c.resolved_by_id,+ ts.reply_count AS reply_count,+ ts.last_activity_at AS last_activity_at+FROM selected_roots sr+JOIN comment c ON c.id = sr.id+JOIN thread_stats ts ON ts.root_id = sr.id+ORDER BY c.created_at ASC, c.id ASC;-- name: ListThreadCommentsForIssue :many-- Returns the root of the thread containing @anchor_id plus every descendant