beads/cmd/bd/list_format.go
Stephanie Jarmak 0954be4166
feat(list,ready,httpapi): reach the Brief projection from both front doors (#5586)
* feat(list,ready,httpapi): reach the Brief projection from both front doors

Application half of #5546, stacked on the storage half. `--brief` on `bd list`
and `bd ready`, `brief` on `GET /v0/beads/issues` and `GET /v0/beads/ready`.
Defaults to false everywhere, so no payload changes for a caller that does not
ask; #4122 objects to default payload changes and #5078 records what the last
one cost.

ONE REGISTRATION PER COMMAND REACHES BOTH OF ITS ROUTES, because the two
gatherers are shared. `bd list` hands `in.ListRequest` to issueops.Reader.List
verbatim on the direct and the proxied route. `bd ready` uses the Reader role on
NEITHER: both routes pass the filter that gatherReadyInput built through
workapi.BuildReadyFilter, so `types.WorkFilter.Lite` is what has to carry it
there, and the CLI-hop tests assert the filter rather than the request for that
reason. The HTTP handlers build both requests independently of the CLI, so they
are wired separately.

REFUSED WHEREVER IT CANNOT BE HONORED, rather than accepted and dropped, which
is the silent no-op the storage half was written to close. `Lite` reaches a
driver through exactly two queries: the bare SearchIssuesInTx (#3906) and the
counts mega-query (the storage half). `GetReadyWork` and the by-ID hydration
behind the tree walk read neither, so:

  - `bd ready --brief` requires --json, and is refused with --claim, --gated,
    --mol and --explain. `bd ready` runs the counts query for --json alone; the
    text routes call the bare GetReadyWork and the three specialized modes
    answer with shapes of their own. The direct route dispatches those modes
    BEFORE gathering, so each check appears in cmd/bd/ready.go as well as in
    the gatherer, exactly as the --claim conflicts beside them already do.
  - `bd list --brief` works in text mode too, since all of its page routes reach
    Reader.List, and is refused with --watch, with --format, and with --parent
    in the tree view. --tree defaults to true, so a bare --parent in text mode
    is that same walk without the flag being typed.

--claim is refused for a stronger reason than the rest: no route can serve it.
ClaimNext refetches its winning row whole and returns ErrValidation for a
projected request. Catching it in the gatherer keeps the message about the two
flags the user typed, and leaves readyRoleRequest free to carry Brief for the
COUNT, which needs it.

--format is refused rather than annotated because a caller's template can print
any of the six dropped fields and there is nothing to hang a marker on.
`bd list --long` is the one built-in text rendering that prints one of them, and
it is allowed because it CAN say so: it now prints
"Description: (omitted by --brief)". That keys off types.Issue.IsLitePartial
rather than off the flag, so a row that arrived projected reads the same
whichever door set it.

THE JSON PAYLOAD CARRIES NO MARKER, and the flag help and both OpenAPI
descriptions say so plainly. types.Issue.IsLitePartial is `json:"-"` and
documented as internal-only by #3906, so an omitted field is indistinguishable
from an empty one on the wire; only the caller that sent the flag knows. #5549
deferred exactly this marker for brief_deps as its own change, and this follows
that, rather than changing a shared type's wire form on the way past.

`brief` is decoded in handleListReadyWork and NOT in readyFilters, the
vocabulary the ready listing shares with :count and :claimNext, because it
projects fields rather than selecting rows and neither of those returns rows to
project. That made TestClaimNextAdmitsExactlyTheListingsFilters fail, correctly:
its single hardcoded `limit` exception is now a `pageKnobs` table of the
listing's two page knobs, each still asserted ABSENT from claimNext, since a
documented parameter that is always a 400 is a trap. Both branches of that
assertion were verified by sabotage.

RED BEFORE GREEN on all nine new assertions, each verified and reverted: the two
request hops, the seven refusals, the long-format marker, and both branches of
the parity table.

Gates: go build ./..., go vet ./..., gofmt, cmd/bd, internal/httpapi,
internal/workapi, backend/conformance, internal/storage/issueops, issueops,
make api-check, ./scripts/generate-cli-docs.sh --check.

Refs: #5546, #3906

* fix(ready,changelog): close the review findings on #5586

THE THREE DIRECT-ROUTE REFUSALS WERE UNTESTED, and the review's mutation
proved it: deleting the --gated check left `go test ./cmd/bd/` entirely green
while `bd ready --gated --brief` silently ignored the flag on the direct route.
Nothing in the package drives readyCmd's RunE, so the gatherer's tested copies
were only ever guarding the proxied route. The PR body's "seven refusals, red
before green" covered five.

Taking the second of the two suggested fixes, since it removes the duplication
rather than testing it. The per-mode copies in ready.go are deleted. Their body
moves to briefModeConflict, which gatherReadyInput now calls, and RunE calls
once through briefModeConflictFromFlags, hoisted ABOVE the mode dispatch and
above the proxied branch so it is the single place a --brief conflict is
decided for this command on either route.

TestReadyCmdRefusesBriefBeforeItDispatches drives RunE directly, which is
reachable because that check now precedes every store access. Verified by
reproducing the review's own mutation: deleting the hoisted call fails the
--gated, --mol and --explain cases.

THE CHANGELOG ENTRY CONTRADICTED ITSELF, claiming --brief "marks each row
is_lite_partial" and then, in the same paragraph, that the response carries no
marker. The first half was written before the wire form was checked;
types.Issue.IsLitePartial is `json:"-"` and never serialized, so an agent
following that sentence would have grepped its JSON for the field and concluded
the feature was broken. The no-marker fact is now its own paragraph, and the
only marker the entry claims is the text one `bd list --long --brief` prints.
The entry cites #5554 and #5586 alongside #5546, matching the sibling
brief-deps entry.

Gates: go build ./..., go vet ./..., gofmt, cmd/bd, internal/httpapi,
internal/workapi, backend/conformance, internal/storage/issueops, issueops,
make api-check, ./scripts/generate-cli-docs.sh --check.

---------

Co-authored-by: sjarmak <t@t.co>
2026-08-10 13:05:00 -07:00

295 lines
11 KiB
Go

package main
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/timeparsing"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
)
// parseTimeFlag parses time strings using the layered time parsing architecture.
// Supports compact durations (+6h, -1d), natural language (tomorrow, next monday),
// and absolute formats (2006-01-02, RFC3339).
func parseTimeFlag(s string) (time.Time, error) {
return timeparsing.ParseRelativeTime(s, time.Now())
}
// pinIndicator returns a pushpin emoji prefix for pinned issues
func pinIndicator(issue *types.Issue) string {
if issue.Pinned {
return "📌 "
}
return ""
}
// Priority tags for pretty output - simple text, semantic colors applied via ui package
// Design principle: only P0/P1 get color for attention, P2-P4 are neutral
func renderPriorityTag(priority int) string {
return ui.RenderPriority(priority)
}
// renderStatusIcon returns the status icon with semantic coloring applied
// Delegates to the shared ui.RenderStatusIcon for consistency across commands
func renderStatusIcon(status types.Status) string {
return ui.RenderStatusIcon(string(status))
}
// formatPrettyIssue formats a single issue for pretty output
// Uses semantic colors: status icon colored, priority P0/P1 colored, rest neutral
func formatPrettyIssue(issue *types.Issue) string {
// Use shared helpers from ui package
statusIcon := ui.RenderStatusIcon(string(issue.Status))
priorityTag := renderPriorityTag(issue.Priority)
// Type badge - only show for notable types
typeBadge := ""
switch issue.IssueType {
case "epic":
typeBadge = ui.TypeEpicStyle.Render("[epic]") + " "
case "bug":
typeBadge = ui.TypeBugStyle.Render("[bug]") + " "
}
// Format: STATUS_ICON ID PRIORITY [Type] Title
// Closed issues: entire line is muted
if issue.Status == types.StatusClosed {
return fmt.Sprintf("%s %s %s %s%s",
statusIcon,
ui.RenderMuted(issue.ID),
ui.RenderMuted(fmt.Sprintf("P%d", issue.Priority)),
ui.RenderMuted(string(issue.IssueType)),
ui.RenderMuted(" "+issue.Title))
}
return fmt.Sprintf("%s %s %s %s%s", statusIcon, issue.ID, priorityTag, typeBadge, issue.Title)
}
// formatPrettyIssueWithContext formats an issue with optional parent epic annotation
func formatPrettyIssueWithContext(issue *types.Issue, parentEpic string) string {
base := formatPrettyIssue(issue)
if parentEpic == "" {
return base
}
return base + " " + ui.RenderMuted("← "+parentEpic)
}
// formatIssueLong formats a single issue in long format to a buffer.
// When labelsSkipped is true (AD-02 --skip-labels), the Labels: line shows
// "(suppressed by --skip-labels)" instead of the (empty) hydration result.
func formatIssueLong(buf *strings.Builder, issue *types.Issue, labels []string, labelsSkipped bool) {
status := string(issue.Status)
if status == "closed" {
line := fmt.Sprintf("%s%s [P%d] [%s] %s\n %s",
pinIndicator(issue), issue.ID, issue.Priority,
issue.IssueType, status, issue.Title)
buf.WriteString(ui.RenderClosedLine(line))
buf.WriteString("\n")
} else {
buf.WriteString(fmt.Sprintf("%s%s [%s] [%s] %s\n",
pinIndicator(issue),
ui.RenderID(issue.ID),
ui.RenderPriority(issue.Priority),
ui.RenderType(string(issue.IssueType)),
ui.RenderStatus(status)))
buf.WriteString(fmt.Sprintf(" %s\n", issue.Title))
}
if issue.Assignee != "" {
buf.WriteString(fmt.Sprintf(" Assignee: %s\n", issue.Assignee))
}
// This is the one text rendering in the tree that prints a field --brief
// drops, so it is the one that has to say so. Keyed off the ROW, not off
// the flag: IsLitePartial travels with the issue, so a row that arrived
// projected reads the same here whichever door set it. Without this the
// listing is indistinguishable from one whose issues have no description,
// which is the ambiguity the flag is otherwise careful to avoid.
if issue.IsLitePartial {
buf.WriteString(" Description: (omitted by --brief)\n")
} else if desc := strings.TrimSpace(issue.Description); desc != "" {
buf.WriteString(" Description:\n")
for _, line := range strings.Split(desc, "\n") {
buf.WriteString(fmt.Sprintf(" %s\n", line))
}
}
if labelsSkipped {
buf.WriteString(" Labels: (suppressed by --skip-labels)\n")
} else if len(labels) > 0 {
buf.WriteString(fmt.Sprintf(" Labels: %v\n", labels))
}
if hasCustomMetadata(issue) {
if n := countMetadataKeys(issue); n > 0 {
buf.WriteString(fmt.Sprintf(" Metadata: %d keys\n", n))
} else {
buf.WriteString(" Metadata: set\n")
}
}
buf.WriteString("\n")
}
// formatAgentIssue formats a single issue in ultra-compact agent mode format
// Output: "ID: Title" with optional dependency info "(parent: X, blocked by: Y, blocks: Z)"
func formatAgentIssue(buf *strings.Builder, issue *types.Issue, blockedBy, blocks []string, parent string) {
depInfo := formatDependencyInfo(blockedBy, blocks, parent)
if depInfo != "" {
buf.WriteString(fmt.Sprintf("%s: %s %s\n", issue.ID, issue.Title, depInfo))
} else {
buf.WriteString(fmt.Sprintf("%s: %s\n", issue.ID, issue.Title))
}
}
// formatDependencyInfo formats dependency info for list output.
// Parent-child deps are shown as "parent: X" (structural), separate from "blocked by" (blocking). (bd-hcxu)
// Returns "(parent: X, blocked by: Y, blocks: Z)" or "" if no dependencies.
func formatDependencyInfo(blockedBy, blocks []string, parent string) string {
if len(blockedBy) == 0 && len(blocks) == 0 && parent == "" {
return ""
}
var parts []string
if parent != "" {
parts = append(parts, fmt.Sprintf("parent: %s", parent))
}
if len(blockedBy) > 0 {
parts = append(parts, fmt.Sprintf("blocked by: %s", strings.Join(blockedBy, ", ")))
}
if len(blocks) > 0 {
parts = append(parts, fmt.Sprintf("blocks: %s", strings.Join(blocks, ", ")))
}
return "(" + strings.Join(parts, ", ") + ")"
}
// buildBlockingMaps builds maps of blocking dependencies from dependency records.
// Returns three maps: blockedByMap[issueID] = []IDs that block this issue,
// blocksMap[issueID] = []IDs that this issue blocks (excluding parent-child),
// and childrenMap[issueID] = []IDs that are children of this issue.
// Only includes dependencies where AffectsReadyWork() is true (blocks, parent-child, etc.)
//
// closedIDs is an optional set of issue IDs known to be closed. When provided,
// closed blockers are excluded from blockedByMap so that "blocked by" annotations
// only show active (open) blockers. This prevents stale annotations like
// "(blocked by: X)" when X has already been closed.
func buildBlockingMaps(allDeps map[string][]*types.Dependency, closedIDs map[string]bool) (blockedByMap, blocksMap, childrenMap map[string][]string) {
blockedByMap = make(map[string][]string)
blocksMap = make(map[string][]string)
childrenMap = make(map[string][]string)
for issueID, deps := range allDeps {
for _, dep := range deps {
// Only include blocking dependencies
if !dep.Type.AffectsReadyWork() {
continue
}
// Skip closed blockers in "blocked by" annotations — the dependency
// record is preserved, but a closed blocker no longer blocks work.
isClosed := closedIDs != nil && closedIDs[dep.DependsOnID]
if !isClosed {
blockedByMap[issueID] = append(blockedByMap[issueID], dep.DependsOnID)
}
// Separate parent-child from blocking relationships
if dep.Type == types.DepParentChild {
childrenMap[dep.DependsOnID] = append(childrenMap[dep.DependsOnID], issueID)
} else if !isClosed {
blocksMap[dep.DependsOnID] = append(blocksMap[dep.DependsOnID], issueID)
}
}
}
return blockedByMap, blocksMap, childrenMap
}
// getClosedBlockerIDs collects all unique blocker IDs from dependency records
// and returns the subset that are closed or unreachable. This is used to filter
// stale "blocked by" annotations in bd list output.
func getClosedBlockerIDs(ctx context.Context, s storage.DoltStorage, allDeps map[string][]*types.Dependency) map[string]bool {
// Collect unique blocker IDs
blockerIDs := make(map[string]bool)
for _, deps := range allDeps {
for _, dep := range deps {
if dep.Type.AffectsReadyWork() {
blockerIDs[dep.DependsOnID] = true
}
}
}
closedIDs := make(map[string]bool)
for id := range blockerIDs {
issue, err := s.GetIssue(ctx, id)
if err != nil || issue == nil {
// Treat missing or unreachable blockers as resolved — a blocker
// that cannot be fetched cannot block work, matching the behavior
// of computeBlockedIDs which only considers active issues.
closedIDs[id] = true
continue
}
if issue.Status == types.StatusClosed {
closedIDs[id] = true
}
}
return closedIDs
}
// formatIssueCompact formats a single issue in compact format to a buffer
// Uses status icons for better scanability - consistent with bd graph
// Format: [icon] [pin] ID [Priority] [Type] @assignee [labels] - Title (parent: X, blocked by: Y, blocks: Z)
func formatIssueCompact(buf *strings.Builder, issue *types.Issue, labels []string, blockedBy, blocks []string, parent string) {
labelsStr := ""
if len(labels) > 0 {
labelsStr = fmt.Sprintf(" %v", labels)
}
assigneeStr := ""
if issue.Assignee != "" {
assigneeStr = fmt.Sprintf(" @%s", issue.Assignee)
}
// Format dependency info
depInfo := formatDependencyInfo(blockedBy, blocks, parent)
if depInfo != "" {
depInfo = " " + depInfo
}
// Get styled status icon — override to blocked when issue has open blockers (GH#2858)
statusIcon := renderStatusIcon(issue.Status)
if len(blockedBy) > 0 && issue.Status == types.StatusOpen {
statusIcon = renderStatusIcon(types.StatusBlocked)
}
if issue.Status == types.StatusClosed {
// Closed issues: entire line muted (fades visually)
line := fmt.Sprintf("%s %s%s [P%d] [%s]%s%s - %s%s",
statusIcon, pinIndicator(issue), issue.ID, issue.Priority,
issue.IssueType, assigneeStr, labelsStr, issue.Title, depInfo)
buf.WriteString(ui.RenderClosedLine(line))
buf.WriteString("\n")
} else {
// Active issues: status icon + semantic colors for priority/type
buf.WriteString(fmt.Sprintf("%s %s%s [%s] [%s]%s%s - %s%s\n",
statusIcon,
pinIndicator(issue),
ui.RenderID(issue.ID),
ui.RenderPriority(issue.Priority),
ui.RenderType(string(issue.IssueType)),
assigneeStr, labelsStr, issue.Title, depInfo))
}
}
// hasCustomMetadata returns true if the issue has non-empty custom metadata.
func hasCustomMetadata(issue *types.Issue) bool {
if len(issue.Metadata) == 0 {
return false
}
trimmed := strings.TrimSpace(string(issue.Metadata))
return trimmed != "{}" && trimmed != "null"
}
// countMetadataKeys returns the number of top-level keys in the issue's metadata JSON.
func countMetadataKeys(issue *types.Issue) int {
var data map[string]json.RawMessage
if err := json.Unmarshal(issue.Metadata, &data); err != nil {
return 0
}
return len(data)
}