beads/cmd/bd/list.go
Kevin Glynn c5961c4f6f
fix(sort): natural numeric sort for issue IDs with dotted suffixes (GH#3477) (#3486)
Issue IDs like bd-E.10 now sort after bd-E.9 instead of before bd-E.2.
Adds NaturalCompareIDs to internal/utils and replaces string comparison
in list, graph, swarm, todo, and tree display code.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-27 07:04:37 -07:00

1167 lines
40 KiB
Go

package main
import (
"cmp"
"context"
"fmt"
"os"
"os/signal"
"slices"
"strings"
"syscall"
"time"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/utils"
"github.com/steveyegge/beads/internal/validation"
)
// storageExecutor handles operations that need a store connection
type storageExecutor func(store storage.DoltStorage) error
// withStorage executes an operation with either the direct store or a read-only store
func withStorage(ctx context.Context, store storage.DoltStorage, dbPath string, fn storageExecutor) error {
if store != nil {
return fn(store)
} else if dbPath != "" {
// Open read-only connection using repo metadata when available so
// helper paths keep the correct Dolt database and server endpoint.
roStore, err := openReadOnlyStoreForDBPath(ctx, dbPath)
if err != nil {
return err
}
defer func() { _ = roStore.Close() }() // Best effort cleanup
return fn(roStore)
}
return fmt.Errorf("no storage available")
}
func readyWorkFilterFromIssueFilter(filter types.IssueFilter) types.WorkFilter {
wf := types.WorkFilter{
Status: types.StatusOpen,
Limit: filter.Limit,
Labels: filter.Labels,
LabelsAny: filter.LabelsAny,
ExcludeLabels: filter.ExcludeLabels,
LabelPattern: filter.LabelPattern,
LabelRegex: filter.LabelRegex,
ParentID: filter.ParentID,
MolType: filter.MolType,
WispType: filter.WispType,
ExcludeTypes: filter.ExcludeTypes,
MetadataFields: filter.MetadataFields,
HasMetadataKey: filter.HasMetadataKey,
}
if filter.IssueType != nil {
wf.Type = string(*filter.IssueType)
}
if filter.Priority != nil {
wf.Priority = filter.Priority
}
if filter.Assignee != nil {
wf.Assignee = filter.Assignee
}
if filter.NoAssignee {
wf.Unassigned = true
}
if filter.Ephemeral != nil && *filter.Ephemeral {
wf.IncludeEphemeral = true
}
return wf
}
// getHierarchicalChildren handles the --tree --parent combination logic.
// baseFilter carries CLI filters (--type, --status, etc.) through the recursive walk.
func getHierarchicalChildren(ctx context.Context, store storage.DoltStorage, dbPath string, parentID string, baseFilter types.IssueFilter) ([]*types.Issue, error) {
// First verify that the parent issue exists
var parentIssue *types.Issue
err := withStorage(ctx, store, dbPath, func(s storage.DoltStorage) error {
var err error
parentIssue, err = s.GetIssue(ctx, parentID)
return err
})
if err != nil {
return nil, fmt.Errorf("error checking parent issue: %v", err)
}
if parentIssue == nil {
return nil, fmt.Errorf("parent issue '%s' not found", parentID)
}
// Use recursive search to find all descendants using the same logic as --parent filter.
// The parent itself is NOT included in the result set — only actual children and
// their descendants. This matches the behavior of --json and --flat (GH#3349).
allDescendants := make(map[string]*types.Issue)
err = findAllDescendants(ctx, store, dbPath, parentID, baseFilter, allDescendants)
if err != nil {
return nil, fmt.Errorf("error finding descendants: %v", err)
}
if len(allDescendants) == 0 {
return nil, nil
}
// Include the parent as the tree root only when descendants exist,
// so the tree renderer can draw the hierarchy with the parent at the top.
allDescendants[parentID] = parentIssue
treeIssues := make([]*types.Issue, 0, len(allDescendants))
for _, issue := range allDescendants {
treeIssues = append(treeIssues, issue)
}
return treeIssues, nil
}
// findAllDescendants recursively finds all descendants using parent filtering.
// baseFilter carries CLI filters (--type, --status, etc.) so the tree respects them.
func findAllDescendants(ctx context.Context, store storage.DoltStorage, dbPath string, parentID string, baseFilter types.IssueFilter, result map[string]*types.Issue) error {
var children []*types.Issue
err := withStorage(ctx, store, dbPath, func(s storage.DoltStorage) error {
filter := baseFilter
filter.ParentID = &parentID
filter.Limit = 0 // unlimited per level to avoid truncating the tree walk
var err error
children, err = s.SearchIssues(ctx, "", filter)
return err
})
if err != nil {
return err
}
for _, child := range children {
if _, exists := result[child.ID]; !exists {
result[child.ID] = child
err = findAllDescendants(ctx, store, dbPath, child.ID, baseFilter, result)
if err != nil {
return err
}
}
}
return nil
}
// watchIssues polls for changes and re-displays (GH#654)
// Uses polling instead of fsnotify because Dolt stores data in a server-side
// database, not files — file watchers never fire.
type watchListDependencyStore interface {
GetAllDependencyRecords(ctx context.Context) (map[string][]*types.Dependency, error)
}
func loadWatchedIssues(ctx context.Context, store storage.DoltStorage, filter types.IssueFilter, ready bool, parentID string, sortBy string, reverse bool) ([]*types.Issue, error) {
if ready {
issues, err := store.GetReadyWork(ctx, readyWorkFilterFromIssueFilter(filter))
if err != nil {
return nil, err
}
sortIssues(issues, sortBy, reverse)
return issues, nil
}
if parentID != "" {
issues, err := getHierarchicalChildren(ctx, store, "", parentID, filter)
if err != nil {
return nil, err
}
// getHierarchicalChildren builds its result from a map, so normalize the
// slice before snapshot comparison to avoid spurious redraws.
sortIssues(issues, "id", false)
return issues, nil
}
issues, err := store.SearchIssues(ctx, "", filter)
if err != nil {
return nil, err
}
sortIssues(issues, sortBy, reverse)
return issues, nil
}
func displayWatchedIssueList(ctx context.Context, store watchListDependencyStore, issues []*types.Issue) {
var allDeps map[string][]*types.Dependency
if store != nil {
deps, err := store.GetAllDependencyRecords(ctx)
if err == nil {
allDeps = deps
}
}
displayPrettyListWithDeps(issues, true, allDeps)
}
func watchIssues(ctx context.Context, store storage.DoltStorage, filter types.IssueFilter, ready bool, parentID string, sortBy string, reverse bool, effectiveLimit int) {
// Initial display
issues, err := loadWatchedIssues(ctx, store, filter, ready, parentID, sortBy, reverse)
if err != nil {
fmt.Fprintf(os.Stderr, "Error querying issues: %v\n", err)
return
}
truncated := effectiveLimit > 0 && len(issues) > effectiveLimit
if truncated {
issues = issues[:effectiveLimit]
}
displayWatchedIssueList(ctx, store, issues)
printTruncationHint(truncated, effectiveLimit)
lastSnapshot := issueSnapshot(issues)
fmt.Fprintf(os.Stderr, "\nWatching for changes... (Press Ctrl+C to exit)\n")
// Handle Ctrl+C — deferred Stop prevents signal handler leak
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
defer signal.Stop(sigChan)
pollInterval := 2 * time.Second
ticker := time.NewTicker(pollInterval)
defer ticker.Stop()
for {
select {
case <-sigChan:
fmt.Fprintf(os.Stderr, "\nStopped watching.\n")
return
case <-ticker.C:
issues, err := loadWatchedIssues(ctx, store, filter, ready, parentID, sortBy, reverse)
if err != nil {
fmt.Fprintf(os.Stderr, "Error refreshing issues: %v\n", err)
continue
}
truncated := effectiveLimit > 0 && len(issues) > effectiveLimit
if truncated {
issues = issues[:effectiveLimit]
}
snap := issueSnapshot(issues)
if snap != lastSnapshot {
lastSnapshot = snap
displayWatchedIssueList(ctx, store, issues)
printTruncationHint(truncated, effectiveLimit)
fmt.Fprintf(os.Stderr, "\nWatching for changes... (Press Ctrl+C to exit)\n")
}
}
}
}
// issueSnapshot builds a comparable string from issue IDs, statuses, and
// update times so we can detect when the result set has changed.
func issueSnapshot(issues []*types.Issue) string {
var b strings.Builder
for _, issue := range issues {
fmt.Fprintf(&b, "%s:%s:%d;", issue.ID, issue.Status, issue.UpdatedAt.UnixNano())
}
return b.String()
}
// sortIssues sorts a slice of issues by the specified field and direction
func sortIssues(issues []*types.Issue, sortBy string, reverse bool) {
if sortBy == "" {
return
}
slices.SortFunc(issues, func(a, b *types.Issue) int {
var result int
switch sortBy {
case "priority":
// Lower priority numbers come first (P0 > P1 > P2 > P3 > P4)
result = cmp.Compare(a.Priority, b.Priority)
case "created":
// Default: newest first (descending)
result = b.CreatedAt.Compare(a.CreatedAt)
case "updated":
// Default: newest first (descending)
result = b.UpdatedAt.Compare(a.UpdatedAt)
case "closed":
// Default: newest first (descending)
// Handle nil ClosedAt values
if a.ClosedAt == nil && b.ClosedAt == nil {
result = 0
} else if a.ClosedAt == nil {
result = 1 // nil sorts last
} else if b.ClosedAt == nil {
result = -1 // non-nil sorts before nil
} else {
result = b.ClosedAt.Compare(*a.ClosedAt)
}
case "status":
result = cmp.Compare(a.Status, b.Status)
case "id":
result = utils.NaturalCompareIDs(a.ID, b.ID)
case "title":
result = cmp.Compare(strings.ToLower(a.Title), strings.ToLower(b.Title))
case "type":
result = cmp.Compare(a.IssueType, b.IssueType)
case "assignee":
result = cmp.Compare(a.Assignee, b.Assignee)
default:
// Unknown sort field, no sorting
result = 0
}
if reverse {
return -result
}
return result
})
}
// knownListFlags maps bare words that users might pass as positional args
// but are actually flag names. Each maps to a hint for the error message.
var knownListFlags = map[string]string{
"ready": "--ready",
"tree": "--tree",
"flat": "--flat",
"all": "--all",
"long": "--long",
"watch": "--watch",
"pretty": "--pretty",
"pinned": "--pinned",
"overdue": "--overdue",
}
var listCmd = &cobra.Command{
Use: "list",
GroupID: "issues",
Short: "List issues",
Args: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return nil
}
for _, arg := range args {
if hint, ok := knownListFlags[arg]; ok {
return fmt.Errorf("unknown argument %q; did you mean %q or 'bd %s'?", arg, hint, arg)
}
}
return fmt.Errorf("bd list does not accept positional arguments; use flags instead (see bd list --help)")
},
Run: func(cmd *cobra.Command, args []string) {
status, _ := cmd.Flags().GetString("status")
// --state is alias for --status (desire path: bd-9h3w)
if status == "" {
status, _ = cmd.Flags().GetString("state")
}
assignee, _ := cmd.Flags().GetString("assignee")
issueType, _ := cmd.Flags().GetString("type")
issueType = utils.NormalizeIssueType(issueType) // Expand aliases (mr→merge-request, etc.)
limit, _ := cmd.Flags().GetInt("limit")
allFlag, _ := cmd.Flags().GetBool("all")
formatStr, _ := cmd.Flags().GetString("format")
// Handle --format json: the local --format flag shadows the hidden
// persistent --format on rootCmd, so "json" arrives here instead of
// setting jsonOutput via PersistentPreRun. Route it explicitly.
if strings.EqualFold(formatStr, "json") {
jsonOutput = true
formatStr = ""
}
labels, _ := cmd.Flags().GetStringSlice("label")
labelsAny, _ := cmd.Flags().GetStringSlice("label-any")
excludeLabels, _ := cmd.Flags().GetStringSlice("exclude-label")
labelPattern, _ := cmd.Flags().GetString("label-pattern")
labelRegex, _ := cmd.Flags().GetString("label-regex")
titleSearch, _ := cmd.Flags().GetString("title")
specPrefix, _ := cmd.Flags().GetString("spec")
idFilter, _ := cmd.Flags().GetString("id")
longFormat, _ := cmd.Flags().GetBool("long")
sortBy, _ := cmd.Flags().GetString("sort")
reverse, _ := cmd.Flags().GetBool("reverse")
// Pattern matching flags
titleContains, _ := cmd.Flags().GetString("title-contains")
descContains, _ := cmd.Flags().GetString("desc-contains")
notesContains, _ := cmd.Flags().GetString("notes-contains")
// Date range flags
createdAfter, _ := cmd.Flags().GetString("created-after")
createdBefore, _ := cmd.Flags().GetString("created-before")
updatedAfter, _ := cmd.Flags().GetString("updated-after")
updatedBefore, _ := cmd.Flags().GetString("updated-before")
closedAfter, _ := cmd.Flags().GetString("closed-after")
closedBefore, _ := cmd.Flags().GetString("closed-before")
// Empty/null check flags
emptyDesc, _ := cmd.Flags().GetBool("empty-description")
noAssignee, _ := cmd.Flags().GetBool("no-assignee")
noLabels, _ := cmd.Flags().GetBool("no-labels")
// Priority range flags
priorityMinStr, _ := cmd.Flags().GetString("priority-min")
priorityMaxStr, _ := cmd.Flags().GetString("priority-max")
// Pinned filtering flags
pinnedFlag, _ := cmd.Flags().GetBool("pinned")
noPinnedFlag, _ := cmd.Flags().GetBool("no-pinned")
// Template filtering
includeTemplates, _ := cmd.Flags().GetBool("include-templates")
// Gate filtering (bd-7zka.2)
includeGates, _ := cmd.Flags().GetBool("include-gates")
// Infra type filtering: exclude agent/rig/role/message by default
includeInfra, _ := cmd.Flags().GetBool("include-infra")
// Explicit type exclusion (--exclude-type)
excludeTypeStrs, _ := cmd.Flags().GetStringSlice("exclude-type")
// Parent filtering (--filter-parent is alias for --parent)
parentID, _ := cmd.Flags().GetString("parent")
if parentID == "" {
// Flag registered; GetString only errors if flag doesn't exist
parentID, _ = cmd.Flags().GetString("filter-parent")
}
noParent, _ := cmd.Flags().GetBool("no-parent")
// Molecule type filtering
molTypeStr, _ := cmd.Flags().GetString("mol-type")
var molType *types.MolType
if molTypeStr != "" {
mt := types.MolType(molTypeStr)
if !mt.IsValid() {
FatalError("invalid mol-type %q (must be swarm, patrol, or work)", molTypeStr)
}
molType = &mt
}
// Wisp type filtering (TTL-based compaction classification)
wispTypeStr, _ := cmd.Flags().GetString("wisp-type")
var wispType *types.WispType
if wispTypeStr != "" {
wt := types.WispType(wispTypeStr)
if !wt.IsValid() {
FatalError("invalid wisp-type %q (must be heartbeat, ping, patrol, gc_report, recovery, error, or escalation)", wispTypeStr)
}
wispType = &wt
}
// Time-based scheduling filters (GH#820)
deferredFlag, _ := cmd.Flags().GetBool("deferred")
deferAfter, _ := cmd.Flags().GetString("defer-after")
deferBefore, _ := cmd.Flags().GetString("defer-before")
dueAfter, _ := cmd.Flags().GetString("due-after")
dueBefore, _ := cmd.Flags().GetString("due-before")
overdueFlag, _ := cmd.Flags().GetBool("overdue")
// Pretty and watch flags (GH#654)
prettyFormat, _ := cmd.Flags().GetBool("pretty")
treeFormat, _ := cmd.Flags().GetBool("tree")
flatFormat, _ := cmd.Flags().GetBool("flat")
if flatFormat {
treeFormat = false
}
// --tree is alias for --pretty; JSON and explicit --format win
prettyFormat = (prettyFormat || treeFormat) && !jsonOutput && formatStr == ""
watchMode, _ := cmd.Flags().GetBool("watch")
// Pager control (bd-jdz3)
noPager, _ := cmd.Flags().GetBool("no-pager")
// Ready filter (bd-ihu31)
readyFlag, _ := cmd.Flags().GetBool("ready")
// Watch mode implies pretty format
if watchMode {
prettyFormat = true
}
// Use global jsonOutput set by PersistentPreRun
// Normalize labels: trim, dedupe, remove empty
labels = utils.NormalizeLabels(labels)
labelsAny = utils.NormalizeLabels(labelsAny)
excludeLabels = utils.NormalizeLabels(excludeLabels)
// Apply directory-aware label scoping if no labels explicitly provided (GH#541)
if len(labels) == 0 && len(labelsAny) == 0 {
if dirLabels := config.GetDirectoryLabels(); len(dirLabels) > 0 {
labelsAny = dirLabels
}
}
// Resolve effective limit. Priority order:
// 1. Explicit --limit always wins (user intent is clear)
// 2. --all implies unlimited when --limit is not set (GH#1840)
// 3. Agent mode uses a lower default for context efficiency
// 4. Default limit (50) otherwise
limitChanged := cmd.Flags().Changed("limit")
effectiveLimit := limit
switch {
case limitChanged:
effectiveLimit = limit // Explicit value (including --limit 0 for unlimited)
case allFlag:
effectiveLimit = 0 // --all implies unlimited regardless of other flags
case ui.IsAgentMode():
effectiveLimit = 20 // Agent mode default
}
// Validate --sort field (bd-ttno)
if sortBy != "" {
validSortFields := map[string]bool{
"priority": true, "created": true, "updated": true, "closed": true,
"status": true, "id": true, "title": true, "type": true, "assignee": true,
}
if !validSortFields[sortBy] {
FatalError("invalid sort field %q (valid: priority, created, updated, closed, status, id, title, type, assignee)", sortBy)
}
}
// When --sort is specified, don't pass Limit to SQL — the hardcoded
// ORDER BY would truncate before Go-side sorting (GH#1237).
// Instead, apply limit in Go after sortIssues().
sqlLimit := effectiveLimit
if sortBy != "" {
sqlLimit = 0
}
// Fetch one extra row so we can distinguish "exactly N matches" from
// "N+ matches truncated" without running a second count query (GH#3212).
if sqlLimit > 0 {
sqlLimit++
}
filter := types.IssueFilter{
Limit: sqlLimit,
}
// --ready flag: show only open issues (excludes hooked/in_progress/blocked/deferred) (bd-ihu31)
if readyFlag {
s := types.StatusOpen
filter.Status = &s
} else if status != "" && status != "all" {
// Support comma-separated status values (GH#2846)
statusParts := strings.Split(status, ",")
var customStatuses []string
if store != nil {
cs, err := store.GetCustomStatuses(rootCtx)
if err != nil {
if !jsonOutput {
fmt.Fprintf(os.Stderr, "%s Could not load custom statuses from database: %v (falling back to config)\n", ui.RenderWarn("!"), err)
}
} else {
customStatuses = cs
}
}
if len(statusParts) == 1 {
s := types.Status(strings.TrimSpace(statusParts[0]))
if !s.IsValidWithCustom(customStatuses) {
validList := "open, in_progress, blocked, deferred, closed, pinned, hooked"
if len(customStatuses) > 0 {
validList += ", " + strings.Join(customStatuses, ", ")
}
FatalError("invalid status %q (valid: %s)", status, validList)
}
filter.Status = &s
} else {
for _, part := range statusParts {
s := types.Status(strings.TrimSpace(part))
if !s.IsValidWithCustom(customStatuses) {
validList := "open, in_progress, blocked, deferred, closed, pinned, hooked"
if len(customStatuses) > 0 {
validList += ", " + strings.Join(customStatuses, ", ")
}
FatalError("invalid status %q in multi-status filter (valid: %s)", strings.TrimSpace(part), validList)
}
filter.Statuses = append(filter.Statuses, s)
}
}
}
// Default to non-closed/non-pinned issues unless --all, --pinned, or explicit --status (GH#788, bd-uhcg)
// Also exclude custom statuses in done/frozen categories
if status == "" && !allFlag && !readyFlag && !pinnedFlag {
excludeStatuses := []types.Status{types.StatusClosed, types.StatusPinned}
if store != nil {
if detailed, err := store.GetCustomStatusesDetailed(rootCtx); err == nil {
for _, cs := range detailed {
if cs.Category == types.CategoryDone || cs.Category == types.CategoryFrozen {
excludeStatuses = append(excludeStatuses, types.Status(cs.Name))
}
}
}
}
filter.ExcludeStatus = excludeStatuses
}
// Use Changed() to properly handle P0 (priority=0)
if cmd.Flags().Changed("priority") {
priorityStr, _ := cmd.Flags().GetString("priority")
priority, err := validation.ValidatePriority(priorityStr)
if err != nil {
FatalError("%v", err)
}
filter.Priority = &priority
}
if assignee != "" {
filter.Assignee = &assignee
}
if issueType != "" {
t := types.IssueType(issueType)
// Validate --type value (bd-ttno)
var customTypes []string
if store != nil {
ct, _ := store.GetCustomTypes(rootCtx)
customTypes = ct
}
if len(customTypes) == 0 {
customTypes = config.GetCustomTypesFromYAML()
}
if !t.IsValidWithCustom(customTypes) {
validTypes := "bug, feature, task, epic, chore, decision"
if len(customTypes) > 0 {
validTypes += ", " + joinStrings(customTypes, ", ")
}
FatalError("invalid issue type %q (valid: %s)", issueType, validTypes)
}
filter.IssueType = &t
}
if len(labels) > 0 {
filter.Labels = labels
}
if len(labelsAny) > 0 {
filter.LabelsAny = labelsAny
}
if len(excludeLabels) > 0 {
filter.ExcludeLabels = excludeLabels
}
if labelPattern != "" {
filter.LabelPattern = labelPattern
}
if labelRegex != "" {
filter.LabelRegex = labelRegex
}
if titleSearch != "" {
filter.TitleSearch = titleSearch
}
if idFilter != "" {
ids := utils.NormalizeLabels(strings.Split(idFilter, ","))
if len(ids) > 0 {
filter.IDs = ids
}
}
if specPrefix != "" {
filter.SpecIDPrefix = specPrefix
}
// Pattern matching
if titleContains != "" {
filter.TitleContains = titleContains
}
if descContains != "" {
filter.DescriptionContains = descContains
}
if notesContains != "" {
filter.NotesContains = notesContains
}
// Date ranges
if createdAfter != "" {
t, err := parseTimeFlag(createdAfter)
if err != nil {
FatalError("parsing --created-after: %v", err)
}
filter.CreatedAfter = &t
}
if createdBefore != "" {
t, err := parseTimeFlag(createdBefore)
if err != nil {
FatalError("parsing --created-before: %v", err)
}
filter.CreatedBefore = &t
}
if updatedAfter != "" {
t, err := parseTimeFlag(updatedAfter)
if err != nil {
FatalError("parsing --updated-after: %v", err)
}
filter.UpdatedAfter = &t
}
if updatedBefore != "" {
t, err := parseTimeFlag(updatedBefore)
if err != nil {
FatalError("parsing --updated-before: %v", err)
}
filter.UpdatedBefore = &t
}
if closedAfter != "" {
t, err := parseTimeFlag(closedAfter)
if err != nil {
FatalError("parsing --closed-after: %v", err)
}
filter.ClosedAfter = &t
}
if closedBefore != "" {
t, err := parseTimeFlag(closedBefore)
if err != nil {
FatalError("parsing --closed-before: %v", err)
}
filter.ClosedBefore = &t
}
// Empty/null checks
if emptyDesc {
filter.EmptyDescription = true
}
if noAssignee {
filter.NoAssignee = true
}
if noLabels {
filter.NoLabels = true
}
// Priority ranges
if cmd.Flags().Changed("priority-min") {
priorityMin, err := validation.ValidatePriority(priorityMinStr)
if err != nil {
FatalError("parsing --priority-min: %v", err)
}
filter.PriorityMin = &priorityMin
}
if cmd.Flags().Changed("priority-max") {
priorityMax, err := validation.ValidatePriority(priorityMaxStr)
if err != nil {
FatalError("parsing --priority-max: %v", err)
}
filter.PriorityMax = &priorityMax
}
// Pinned filtering: --pinned and --no-pinned are mutually exclusive
if pinnedFlag && noPinnedFlag {
FatalError("--pinned and --no-pinned are mutually exclusive")
}
if pinnedFlag {
pinned := true
filter.Pinned = &pinned
} else if noPinnedFlag || (status != "pinned" && status != "hooked" && !allFlag) {
// Exclude pinned beads by default — they are permanent references,
// not actionable work items. Use --pinned or --all to see them. (bd-uhcg)
// Also skip exclusion for --status=hooked: beads transitioning from
// pinned to hooked retain the legacy pinned=1 column, and excluding
// them breaks gt hook status detection (bd-pr-sheriff bug).
pinned := false
filter.Pinned = &pinned
}
// Template filtering: exclude templates by default
// Use --include-templates to show all issues including templates
if !includeTemplates {
isTemplate := false
filter.IsTemplate = &isTemplate
}
// Gate filtering: exclude gate issues by default (bd-7zka.2)
// Use --include-gates or --type gate to show gate issues
if !includeGates && issueType != "gate" {
filter.ExcludeTypes = append(filter.ExcludeTypes, "gate")
}
// Infra type filtering: exclude configured infra types by default.
// These types live in the wisps table after migration 007.
// Use --include-infra or --type=agent to show infra beads.
infraTypes := storage.DefaultInfraTypes()
if store != nil {
infraSet := store.GetInfraTypes(rootCtx)
infraTypes = make([]string, 0, len(infraSet))
for t := range infraSet {
infraTypes = append(infraTypes, t)
}
}
isInfra := func(t string) bool {
if store != nil {
return store.IsInfraTypeCtx(rootCtx, types.IssueType(t))
}
return storage.IsInfraType(types.IssueType(t))
}
if !includeInfra && !isInfra(issueType) {
for _, t := range infraTypes {
filter.ExcludeTypes = append(filter.ExcludeTypes, types.IssueType(t))
}
}
// Explicit type exclusion from --exclude-type flag.
for _, raw := range excludeTypeStrs {
for _, t := range strings.Split(raw, ",") {
t = strings.TrimSpace(t)
if t != "" {
filter.ExcludeTypes = append(filter.ExcludeTypes, types.IssueType(utils.NormalizeIssueType(t)))
}
}
}
// When explicitly requesting an infra type, search the wisps table
// (where infra beads live after migration 007).
if isInfra(issueType) {
ephemeral := true
filter.Ephemeral = &ephemeral
}
// Parent filtering: filter children by parent issue
if parentID != "" && noParent {
FatalError("--parent and --no-parent are mutually exclusive")
}
if parentID != "" {
filter.ParentID = &parentID
}
if noParent {
filter.NoParent = true
}
// Molecule type filtering
if molType != nil {
filter.MolType = molType
}
// Wisp type filtering
if wispType != nil {
filter.WispType = wispType
}
// Time-based scheduling filters (GH#820)
if deferredFlag {
filter.Deferred = true
}
if deferAfter != "" {
t, err := parseTimeFlag(deferAfter)
if err != nil {
FatalError("parsing --defer-after: %v", err)
}
filter.DeferAfter = &t
}
if deferBefore != "" {
t, err := parseTimeFlag(deferBefore)
if err != nil {
FatalError("parsing --defer-before: %v", err)
}
filter.DeferBefore = &t
}
if dueAfter != "" {
t, err := parseTimeFlag(dueAfter)
if err != nil {
FatalError("parsing --due-after: %v", err)
}
filter.DueAfter = &t
}
if dueBefore != "" {
t, err := parseTimeFlag(dueBefore)
if err != nil {
FatalError("parsing --due-before: %v", err)
}
filter.DueBefore = &t
}
if overdueFlag {
filter.Overdue = true
}
// Metadata filters (GH#1406)
metadataFieldFlags, _ := cmd.Flags().GetStringArray("metadata-field")
if len(metadataFieldFlags) > 0 {
filter.MetadataFields = make(map[string]string, len(metadataFieldFlags))
for _, mf := range metadataFieldFlags {
k, v, ok := strings.Cut(mf, "=")
if !ok || k == "" {
FatalErrorRespectJSON("invalid --metadata-field: expected key=value, got %q", mf)
}
if err := storage.ValidateMetadataKey(k); err != nil {
FatalErrorRespectJSON("invalid --metadata-field key: %v", err)
}
filter.MetadataFields[k] = v
}
}
hasMetadataKey, _ := cmd.Flags().GetString("has-metadata-key")
if hasMetadataKey != "" {
if err := storage.ValidateMetadataKey(hasMetadataKey); err != nil {
FatalErrorRespectJSON("invalid --has-metadata-key: %v", err)
}
filter.HasMetadataKey = hasMetadataKey
}
ctx := rootCtx
activeStore := store
// Contributor auto-routing: read from the same target repo as bd create.
routedStore, routed, err := openRoutedReadStore(ctx, activeStore)
if err != nil {
FatalError("%v", err)
}
if routed {
defer func() { _ = routedStore.Close() }()
activeStore = routedStore
}
// Direct mode
var issues []*types.Issue
if readyFlag {
// Use blocker-aware GetReadyWork semantics (GH#3478).
// This ensures bd list --ready matches bd ready behavior,
// excluding issues with open blocks dependencies.
wf := readyWorkFilterFromIssueFilter(filter)
var err error
issues, err = activeStore.GetReadyWork(ctx, wf)
if err != nil {
FatalError("%v", err)
}
} else {
var err error
issues, err = activeStore.SearchIssues(ctx, "", filter)
if err != nil {
FatalError("%v", err)
}
}
// Apply sorting
sortIssues(issues, sortBy, reverse)
// Detect truncation (GH#3212). We fetched effectiveLimit+1 above, so any
// overflow means more matches exist than we're displaying.
truncated := effectiveLimit > 0 && len(issues) > effectiveLimit
if truncated {
issues = issues[:effectiveLimit]
}
// Handle watch mode (GH#654) - must be before other output modes
if watchMode {
watchIssues(ctx, activeStore, filter, readyFlag, parentID, sortBy, reverse, effectiveLimit)
return
}
// Handle pretty format (GH#654)
// JSON output takes priority over pretty/tree format (bd-list-json-fix, bd-03r)
if prettyFormat && !jsonOutput {
// Special handling for --tree --parent combination (hierarchical descendants)
if parentID != "" && !readyFlag {
treeIssues, err := getHierarchicalChildren(ctx, activeStore, "", parentID, filter)
if err != nil {
FatalError("%v", err)
}
if len(treeIssues) == 0 {
fmt.Printf("Issue '%s' has no children\n", parentID)
return
}
// Load dependencies for tree structure
// Best effort: display gracefully degrades with empty data
allDeps, _ := activeStore.GetAllDependencyRecords(ctx)
displayPrettyListWithDeps(treeIssues, false, allDeps)
return
}
// Regular tree display (no parent filter)
// Load dependencies for tree structure
// Best effort: display gracefully degrades with empty data
allDeps, _ := activeStore.GetAllDependencyRecords(ctx)
displayPrettyListWithDeps(issues, false, allDeps)
printTruncationHint(truncated, effectiveLimit)
return
}
// Handle format flag (non-json presets handled here; json handled earlier)
if formatStr != "" {
if err := outputFormattedList(ctx, activeStore, issues, formatStr); err != nil {
FatalError("%v", err)
}
printTruncationHint(truncated, effectiveLimit)
return
}
if jsonOutput {
// Get labels and dependency counts in bulk (single query instead of N queries)
issueIDs := make([]string, len(issues))
for i, issue := range issues {
issueIDs[i] = issue.ID
}
// Best effort: display gracefully degrades with empty data
labelsMap, _ := activeStore.GetLabelsForIssues(ctx, issueIDs)
depCounts, _ := activeStore.GetDependencyCounts(ctx, issueIDs)
allDeps, _ := activeStore.GetDependencyRecordsForIssues(ctx, issueIDs)
commentCounts, _ := activeStore.GetCommentCounts(ctx, issueIDs)
// Populate labels and dependencies for JSON output
for _, issue := range issues {
issue.Labels = labelsMap[issue.ID]
issue.Dependencies = allDeps[issue.ID]
}
// Build response with counts + computed parent (bd-ym8c)
issuesWithCounts := make([]*types.IssueWithCounts, len(issues))
for i, issue := range issues {
counts := depCounts[issue.ID]
if counts == nil {
counts = &types.DependencyCounts{DependencyCount: 0, DependentCount: 0}
}
// Compute parent from dependency records
var parent *string
for _, dep := range allDeps[issue.ID] {
if dep.Type == types.DepParentChild {
parent = &dep.DependsOnID
break
}
}
issuesWithCounts[i] = &types.IssueWithCounts{
Issue: issue,
DependencyCount: counts.DependencyCount,
DependentCount: counts.DependentCount,
CommentCount: commentCounts[issue.ID],
Parent: parent,
}
}
outputJSON(issuesWithCounts)
printTruncationHint(truncated, effectiveLimit)
return
}
// Show upgrade notification if needed
maybeShowUpgradeNotification()
// Load labels in bulk for display
issueIDs := make([]string, len(issues))
for i, issue := range issues {
issueIDs[i] = issue.ID
}
// Best effort: display gracefully degrades with empty data
labelsMap, _ := activeStore.GetLabelsForIssues(ctx, issueIDs)
// Load blocking info for displayed issues only (bd-7di).
// Previously loaded ALL dependency records which was O(total_issues) and took 2-4s.
// Now scoped to only the displayed issues, making it O(displayed_issues).
// Best effort: display gracefully degrades with empty data
blockedByMap, blocksMap, parentMap, _ := activeStore.GetBlockingInfoForIssues(ctx, issueIDs)
// Build output in buffer for pager support (bd-jdz3)
var buf strings.Builder
if ui.IsAgentMode() {
// Agent mode: ultra-compact, no colors, no pager
for _, issue := range issues {
formatAgentIssue(&buf, issue, blockedByMap[issue.ID], blocksMap[issue.ID], parentMap[issue.ID])
}
fmt.Print(buf.String())
printTruncationHint(truncated, effectiveLimit)
return
} else if longFormat {
// Long format: multi-line with details
buf.WriteString(fmt.Sprintf("\nFound %d issues:\n\n", len(issues)))
for _, issue := range issues {
labels := labelsMap[issue.ID]
formatIssueLong(&buf, issue, labels)
}
} else {
// Compact format: one line per issue
for _, issue := range issues {
labels := labelsMap[issue.ID]
formatIssueCompact(&buf, issue, labels, blockedByMap[issue.ID], blocksMap[issue.ID], parentMap[issue.ID])
}
}
// Output with pager support
if err := ui.ToPager(buf.String(), ui.PagerOptions{NoPager: noPager}); err != nil {
if _, writeErr := fmt.Fprint(os.Stdout, buf.String()); writeErr != nil {
fmt.Fprintf(os.Stderr, "Error writing output: %v\n", writeErr)
}
}
printTruncationHint(truncated, effectiveLimit)
// Show tip after successful list (direct mode only)
maybeShowTip(store)
},
}
func init() {
listCmd.Flags().StringP("status", "s", "", "Filter by stored status (open, in_progress, blocked, deferred, closed). Comma-separated for multiple: --status open,in_progress")
listCmd.Flags().String("state", "", "Alias for --status")
_ = listCmd.Flags().MarkHidden("state")
registerPriorityFlag(listCmd, "")
listCmd.Flags().StringP("assignee", "a", "", "Filter by assignee")
listCmd.Flags().StringP("type", "t", "", "Filter by type (bug, feature, task, epic, chore, decision, merge-request, molecule, gate, convoy). Aliases: mr→merge-request, feat→feature, mol→molecule, dec/adr→decision")
listCmd.Flags().StringSliceP("label", "l", []string{}, "Filter by labels (AND: must have ALL). Can combine with --label-any")
listCmd.Flags().StringSlice("label-any", []string{}, "Filter by labels (OR: must have AT LEAST ONE). Can combine with --label")
listCmd.Flags().StringSlice("exclude-label", []string{}, "Exclude issues that have ANY of these labels")
listCmd.Flags().String("label-pattern", "", "Filter by label glob pattern (e.g., 'tech-*' matches tech-debt, tech-legacy)")
listCmd.Flags().String("label-regex", "", "Filter by label regex pattern (e.g., 'tech-(debt|legacy)')")
listCmd.Flags().String("title", "", "Filter by title text (case-insensitive substring match)")
listCmd.Flags().String("spec", "", "Filter by spec_id prefix")
listCmd.Flags().String("id", "", "Filter by specific issue IDs (comma-separated, e.g., bd-1,bd-5,bd-10)")
listCmd.Flags().IntP("limit", "n", 50, "Limit results (default 50, use 0 for unlimited)")
listCmd.Flags().String("format", "", "Output format: 'digraph' (for golang.org/x/tools/cmd/digraph), 'dot' (Graphviz), or Go template")
listCmd.Flags().Bool("all", false, "Show all issues including closed (overrides default filter)")
listCmd.Flags().Bool("long", false, "Show detailed multi-line output for each issue")
listCmd.Flags().String("sort", "", "Sort by field: priority, created, updated, closed, status, id, title, type, assignee")
listCmd.Flags().BoolP("reverse", "r", false, "Reverse sort order")
// Pattern matching
listCmd.Flags().String("title-contains", "", "Filter by title substring (case-insensitive)")
listCmd.Flags().String("desc-contains", "", "Filter by description substring (case-insensitive)")
listCmd.Flags().String("notes-contains", "", "Filter by notes substring (case-insensitive)")
// Date ranges
listCmd.Flags().String("created-after", "", "Filter issues created after date (YYYY-MM-DD or RFC3339)")
listCmd.Flags().String("created-before", "", "Filter issues created before date (YYYY-MM-DD or RFC3339)")
listCmd.Flags().String("updated-after", "", "Filter issues updated after date (YYYY-MM-DD or RFC3339)")
listCmd.Flags().String("updated-before", "", "Filter issues updated before date (YYYY-MM-DD or RFC3339)")
listCmd.Flags().String("closed-after", "", "Filter issues closed after date (YYYY-MM-DD or RFC3339)")
listCmd.Flags().String("closed-before", "", "Filter issues closed before date (YYYY-MM-DD or RFC3339)")
// Empty/null checks
listCmd.Flags().Bool("empty-description", false, "Filter issues with empty or missing description")
listCmd.Flags().Bool("no-assignee", false, "Filter issues with no assignee")
listCmd.Flags().Bool("no-labels", false, "Filter issues with no labels")
// Priority ranges
listCmd.Flags().String("priority-min", "", "Filter by minimum priority (inclusive, 0-4 or P0-P4)")
listCmd.Flags().String("priority-max", "", "Filter by maximum priority (inclusive, 0-4 or P0-P4)")
// Pinned filtering
listCmd.Flags().Bool("pinned", false, "Show only pinned issues")
listCmd.Flags().Bool("no-pinned", false, "Exclude pinned issues")
// Template filtering: exclude templates by default
listCmd.Flags().Bool("include-templates", false, "Include template molecules in output")
// Gate filtering: exclude gate issues by default (bd-7zka.2)
listCmd.Flags().Bool("include-gates", false, "Include gate issues in output (normally hidden)")
// Infra type filtering: exclude agent/rig/role/message by default
listCmd.Flags().Bool("include-infra", false, "Include infrastructure beads (agent/rig/role/message) in output")
// Explicit type exclusion
listCmd.Flags().StringSlice("exclude-type", nil, "Exclude issue types from results (comma-separated or repeatable, e.g., --exclude-type=convoy,epic)")
// Parent filtering: filter children by parent issue
listCmd.Flags().String("parent", "", "Filter by parent issue ID (shows children of specified issue)")
listCmd.Flags().String("filter-parent", "", "Alias for --parent")
_ = listCmd.Flags().MarkHidden("filter-parent") // Only fails if flag missing (caught in tests)
listCmd.Flags().Bool("no-parent", false, "Exclude child issues (show only top-level issues)")
// Molecule type filtering
listCmd.Flags().String("mol-type", "", "Filter by molecule type: swarm, patrol, or work")
// Wisp type filtering (TTL-based compaction classification)
listCmd.Flags().String("wisp-type", "", "Filter by wisp type: heartbeat, ping, patrol, gc_report, recovery, error, escalation")
// Time-based scheduling filters (GH#820)
listCmd.Flags().Bool("deferred", false, "Show only issues with defer_until set")
listCmd.Flags().String("defer-after", "", "Filter issues deferred after date (supports relative: +6h, tomorrow)")
listCmd.Flags().String("defer-before", "", "Filter issues deferred before date (supports relative: +6h, tomorrow)")
listCmd.Flags().String("due-after", "", "Filter issues due after date (supports relative: +6h, tomorrow)")
listCmd.Flags().String("due-before", "", "Filter issues due before date (supports relative: +6h, tomorrow)")
listCmd.Flags().Bool("overdue", false, "Show only issues with due_at in the past (not closed)")
// Pretty and watch flags (GH#654)
listCmd.Flags().Bool("pretty", false, "Display issues in a tree format with status/priority symbols")
listCmd.Flags().Bool("tree", true, "Hierarchical tree format (default: true; use --flat to disable)")
listCmd.Flags().Bool("flat", false, "Disable tree format and use legacy flat list output")
listCmd.Flags().BoolP("watch", "w", false, "Watch for changes and auto-update display (implies --pretty)")
// Metadata filtering (GH#1406)
listCmd.Flags().StringArray("metadata-field", nil, "Filter by metadata field (key=value, repeatable)")
listCmd.Flags().String("has-metadata-key", "", "Filter issues that have this metadata key set")
// Pager control (bd-jdz3)
listCmd.Flags().Bool("no-pager", false, "Disable pager output")
// Ready filter: show only issues ready to be worked on (bd-ihu31)
listCmd.Flags().Bool("ready", false, "Show only ready issues (no active blockers, same semantics as bd ready)")
// Note: --json flag is defined as a persistent flag in main.go, not here
rootCmd.AddCommand(listCmd)
}