beads/cmd/bd/list.go
JennyMink 2704d8a954
fix(list): union repeated --status/--state/--id; refuse repeated --type/--assignee (#5739)
* fix(list): union repeated --status/--state/--id; refuse repeated --type/--assignee

bd list's filter flags were plain pflag strings, so a repeated flag silently
kept only the last value: `--status open --status closed --status pinned`
filtered to pinned alone. A 477-issue census answered over 3 rows and nothing
in the output distinguished the narrowed answer from a correct one — worse for
scripts than humans, since a script pipes the clean-looking count onward. The
--status help text already warned about this, but a doc note does not reach a
script that already ran.

The fix follows what each filter's downstream shape permits:

- --status, --state, --id feed comma-separated OR sets, so repeats now union
  into exactly the comma form: `--status open --status closed` builds
  "open,closed". Single values and the comma form parse byte-identically to
  before.
- --type and --assignee are single-valued all the way down. Joining --type
  would surface as "invalid issue type: bug,epic" (loud but misdirected);
  joining --assignee would exact-match nobody and return an empty result that
  reads as a clean answer — the same defect in a new spelling. A repeat of
  either now refuses at parse time, naming the flag.

Two invariants shape the value types. Setting the empty string fully resets
them, because `bd children` borrows listCmd's status flag with Set("all") and
a deferred Set(""). And gatherListInput clears them after copying values out,
because pflag values persist across in-process Execute() calls (the cmd/bd
test binary, library embedders) and an accumulating value would otherwise
leak one command's filter into the next.

Tests cover the union, the refusal (long and shorthand spellings), the
unchanged single/comma forms, the empty-string reset, and the cross-parse
isolation. All four repeated-flag tests fail against the previous flag
registrations.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(list): dedupe repeated filter values; lower Changed on reset (review follow-ups for #5739)

Two nits from review, both on cmd/bd/list_filter_flags.go:

- unionStringFlag.Set now dedupes per token, so `--status open --status open`
  and `--status open --status open,closed --status closed` both build
  "open,closed" instead of "open,open,closed,closed". Harmless inside the
  IN (...) either way, but the joined value is what --json callers and error
  messages echo back.

- resetListFilterFlags now lowers pflag's Changed bit on the five flags as
  well as clearing the values, so it is a full reset rather than a half one;
  the test helper that cleared Changed by hand is gone. The reset takes the
  flag set as an argument instead of reading listCmd, because listCmd's
  initializer reaches it via runListCore -> gatherListInput and referring
  back would be an initialization cycle.

Tests: TestListRepeatedStatusDedupes and TestResetListFilterFlagsLowersChanged
cover the two changes; the existing eight are unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BDokjpuq569c49NYTwcBPY

* fix(bazel): enumerate list_filter_flags{,_test}.go in cmd/bd srcs

This PR adds cmd/bd/list_filter_flags.go and cmd/bd/list_filter_flags_test.go,
but cmd/bd/BUILD.bazel carries explicit go_library/go_test srcs lists rather
than globs. That file is absent at this branch's merge base and was added on
main during the 177-commit advance, so the contributor's history never had it
to update.

Without the two entries, `bazel build --config=pure //cmd/bd:bd
//cmd/bd:bd_test` fails to compile bd_for_tests.a with six undefined symbols:
list.go:409,410,413,414,422 for the five list*Flag vars and list_input.go:48
for resetListFilterFlags.

Regenerated with `make bazel-sync` (gazelle): +2 srcs lines, no deps churn, and
a second sync is a no-op. `make bazel-sync-check` cannot see this class --
tools/bazel/go_srcs.py --check validates only the go_srcs filegroup globs --
but bazel.yml's sync step diffs the full `make bazel-sync` output and would
report the tree out of sync.

Validated: `bazel build --config=pure //cmd/bd:bd //cmd/bd:bd_test` exits 0
(exits 1 without this change), and //cmd/bd:bd_test runs the PR's 10 new tests
green (test.xml: 10 testcases, 0 failures, 0 errors).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* review: pin the three unpinned flag arms; correct the CHANGELOG claims

Maintainer review fixes for #5739 (review-loop iteration 1). The synthesis was
`approve` with zero blockers and zero majors, so every item here is non-gating;
applied because each is confined to this PR's own files, cheap, and carries no
behaviour change. A new commit rather than an amend: the existing maintainer
commit `21d287f4df` is the pre-review lane's BUILD.bazel drift repair, not a
review fixup.

Test Evidence Quality (minor): three reachable arms of the new registration had
no coverage. Added `TestListStateAndStatusArms` with a subtest each for the
hidden `--state` alias unioning like `--status`; a union containing `all` being
refused downstream rather than narrowed; and `--status` outranking `--state`
when both are given, which is `gatherListInput`'s documented fallback order.
Mutation-proved by making `unionStringFlag.Set` last-wins (the pre-PR
behaviour): the existing `TestListRepeatedStatusUnions` control and the first
two new subtests all red, while `--status outranks --state` stays green because
it pins the fallback order rather than the union - orthogonal, not vacuous.
The `all` arm is the interesting one: under last-wins the repeat kept only
`open`, so the `status "all" cannot be combined` guard was never reachable.

Release Safety (nit): the CHANGELOG's equivalence claim was one-directional and
omitted that third arm. Softened to "accumulate (duplicates collapse) instead of
overwriting" and added the clause that `--status all --status open` is refused
rather than narrowed.

Debuggability (nit), CHANGELOG arm: the quoted refusal was the inner error only.
pflag wraps it, so users actually see `invalid argument "epic" for "-t, --type"
flag: --type given more than once (already "bug"); pass a single value`, which is
now what the entry quotes - probed from a real `ParseFlags` call, not inferred.
Took this arm rather than dropping the `--%s` prefix from the inner error, since
that one changes a user-visible message and the reviewer offered it as the
alternative.

Architectural Consistency (nit): replaced the hand-rolled `slicesContains` with
stdlib `slices.Contains` and deleted the helper; `slices` is already used
elsewhere in this package.

Deliberately not done: the Change Impact minor's sibling-surface sweep, which
the finding itself scopes as "no change in this PR" plus a follow-up bead.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: jwe <otaciaproject@gmail.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-30 21:32:42 -07:00

553 lines
24 KiB
Go

package main
import (
"context"
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/workapi"
)
// 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")
}
// 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()
}
// skipLabelsIssueView wraps IssueWithCounts so the JSON encoder always emits
// `labels: []` regardless of the omitempty tag on Issue.Labels. AD-02 contract:
// with --skip-labels, every issue's labels field is present and empty.
type skipLabelsIssueView struct {
*types.IssueWithCounts
Labels []string `json:"labels"`
}
type skipLabelsListJSONResponse struct {
Issues []skipLabelsIssueView `json:"issues"`
Meta skipLabelsListMeta `json:"meta"`
}
type skipLabelsListMeta struct {
SkipLabels bool `json:"skip_labels"`
Count int `json:"count"`
}
func newSkipLabelsListJSONResponse(issues []*types.IssueWithCounts) skipLabelsListJSONResponse {
views := make([]skipLabelsIssueView, len(issues))
for i, issue := range issues {
views[i] = skipLabelsIssueView{
IssueWithCounts: issue,
Labels: []string{},
}
}
return skipLabelsListJSONResponse{
Issues: views,
Meta: skipLabelsListMeta{
SkipLabels: true,
Count: len(views),
},
}
}
// skipLabelsConflicts returns the names of label-filter flags that conflict
// with --skip-labels. Empty result means no conflict. AD-02 Wireframe 5.
func skipLabelsConflicts(labels, labelsAny []string, labelPattern, labelRegex string, excludeLabels []string, noLabels bool) []string {
var conflicts []string
if len(labels) > 0 {
conflicts = append(conflicts, "--label")
}
if len(labelsAny) > 0 {
conflicts = append(conflicts, "--label-any")
}
if labelPattern != "" {
conflicts = append(conflicts, "--label-pattern")
}
if labelRegex != "" {
conflicts = append(conflicts, "--label-regex")
}
if len(excludeLabels) > 0 {
conflicts = append(conflicts, "--exclude-label")
}
if noLabels {
conflicts = append(conflicts, "--no-labels")
}
return conflicts
}
// skipLabelsFooterText is the AD-02 Wireframe 2 footer note.
// The leading newline keeps the note visually distinct from the table.
func skipLabelsFooterText() string {
return "\nnote: --skip-labels in effect — labels suppressed in output.\n"
}
// printSkipLabelsFooter writes the AD-02 footer to stdout when the flag is set
// and --quiet is not. Used by output paths that don't go through the buffered
// pager (pretty/tree mode).
func printSkipLabelsFooter(skipLabels bool) {
if !skipLabels || isQuiet() {
return
}
fmt.Print(skipLabelsFooterText()) //nolint:forbidigo // Pretty/tree output is outside the --format contract.
}
// formatSkipLabelsConflictError builds the user-facing error message for AD-02
// Wireframe 5. The got: line echoes the conflicting flags so the user can see
// which input to remove without re-reading their command line.
func formatSkipLabelsConflictError(conflicts []string) string {
return fmt.Sprintf(
"error: --skip-labels cannot be combined with --label,\n"+
" --label-any, --label-pattern, --label-regex,\n"+
" --exclude-label, or --no-labels (the filter).\n"+
" (got: --skip-labels %s)\n"+
"reason: --skip-labels suppresses the labels JOIN that those\n"+
" filters depend on.\n\n"+
"To filter by labels: drop --skip-labels.\n"+
"To get a label-free result fast: drop --label flags.\n",
strings.Join(conflicts, " "))
}
// 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)")
},
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("list")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
return runListCore(cmd, args)
},
}
// runListCore runs the list query and rendering without emitting a metrics
// event, so the caller owns emission: `bd list` emits "list" exactly once, and
// the `bd children` alias emits "children" exactly once. children sets listCmd's
// flags and calls this core directly rather than listCmd.RunE, which would emit
// a second "list" event for a single user command.
func runListCore(cmd *cobra.Command, _ []string) error {
in, err := gatherListInput(cmd)
if err != nil {
return err
}
out := cmd.OutOrStdout()
if usesProxiedServer() {
// The cap USED to be rejected here: the proxied query path threaded no
// MaxRows, so honoring it would have been silence. It threads one now
// (internal/storage/domain/db sizes its bound and enforces the cap
// through the same two functions the store seam uses), so this route
// answers *ErrTooManyRows the same way the direct route below does —
// same message, same exit code.
if err := runListProxiedServer(cmd, rootCtx, out, in); err != nil {
if capErr := handleMaxRowsError(err); capErr != nil {
return capErr
}
// An error that already carries an exit code came from a handler
// that has already rendered it (the typed --repo refusal writes
// its JSON to stdout). Re-wrapping would print a second line,
// "Error: exit code 1", after the real message.
if _, rendered := exitCodeFromError(err); rendered {
return err
}
return HandleError("%v", err)
}
return nil
}
if in.Offset > 0 {
return HandleError("--offset is only supported under --proxied-server")
}
// `bd list`'s PAGE is on issueops.Reader. The filter is still built here
// because --watch and the hierarchical --parent tree consume it as a VALUE:
// the poll loop re-runs it on a ticker and the tree walk re-parents a copy
// of it at every level, neither of which a page can express. Building it
// unconditionally also keeps the page query ahead of the tree branch, so
// `--parent --pretty --max-rows N` still refuses on the cap where it did.
cfg, err := workapi.LoadStoreListConfig(rootCtx, store)
if err != nil {
return HandleError("%v", err)
}
filter, err := workapi.BuildListFilter(in.ListRequest, cfg)
if err != nil {
return HandleError("%v", err)
}
ctx := rootCtx
activeStore := store
routedStore, routed, routingRule, err := openRoutedReadStore(ctx, activeStore)
if err != nil {
return HandleError("%v", err)
}
if routed {
defer func() { _ = routedStore.Close() }()
printContributorRoutingNotice(ctx, activeStore, routingRule)
activeStore = routedStore
}
if in.watchMode {
if err := watchIssues(ctx, activeStore, filter, in.ReadyFlag, in.ParentID, in.SortBy, in.Reverse, in.effectiveLimit, in.Status); err != nil {
if capErr := handleMaxRowsError(err); capErr != nil {
return capErr
}
return HandleError("querying issues: %v", err)
}
return nil
}
// The accessor on the ROUTED store, not on the global one: a contributor
// listing is answered from the repository the routing rule picked, and a
// reader taken off `store` would read the wrong database.
reader, err := activeStore.IssueReader()
if err != nil {
return HandleError("%v", err)
}
// --json. The role's List runs the same LoadStoreListConfig, the same
// BuildListFilter and the same workapi.FinishPage this branch ran longhand,
// and the --ready arm is its ReadyFlag, so the page, its order, its trim and
// its has-more verdict are unchanged bytes. The cap still arrives as
// *ErrTooManyRows, which is why handleMaxRowsError still wraps the call.
if jsonOutput {
page, err := reader.List(ctx, in.ListRequest)
if err != nil {
if capErr := handleMaxRowsError(err); capErr != nil {
return capErr
}
return HandleError("%v", err)
}
if in.SkipLabels {
if err := outputJSON(newSkipLabelsListJSONResponse(page.Items)); err != nil {
return err
}
printTruncationHint(page.HasMore, in.effectiveLimit)
return nil
}
if err := outputJSON(page.Items); err != nil {
return err
}
printTruncationHint(page.HasMore, in.effectiveLimit)
return nil
}
// The text renderings print no cardinality, so the request carries SkipCounts
// (issueops.ListRequest.SkipCounts). Without it this would trade a plain scan
// for three aggregate joins on the most-run command in the tree.
textRequest := in.ListRequest
textRequest.SkipCounts = true
// No text rendering prints a comment body, so the per-row comment reads are
// not merely unused here, they are unpayable: SkipCounts above already
// zeroes the count this hydration would key on.
textRequest.IncludeComments = false
page, err := reader.List(ctx, textRequest)
if err != nil {
if capErr := handleMaxRowsError(err); capErr != nil {
return capErr
}
return HandleError("%v", err)
}
issues, truncated := listPageIssues(page)
if in.prettyFormat && !jsonOutput {
if in.ParentID != "" && !in.ReadyFlag {
treeIssues, err := getHierarchicalChildren(ctx, activeStore, "", in.ParentID, filter)
if err != nil {
return HandleError("%v", err)
}
if len(treeIssues) == 0 {
fmt.Printf("Issue '%s' has no children\n", in.ParentID) //nolint:forbidigo // Pretty/tree output is outside the --format contract.
return nil
}
allDeps, depErr := activeStore.GetAllDependencyRecords(ctx)
if depErr != nil && in.depsMode != "" {
return HandleError("loading dependencies for --deps: %v", depErr)
}
// Hierarchical --parent walks use an unlimited per-level query, so the tree is never page-truncated.
displayPrettyListWithDepsMode(treeIssues, false, allDeps, in.depsMode, false, in.ReadyFlag, in.Status, in.SortBy, in.Reverse)
printSkipLabelsFooter(in.SkipLabels)
return nil
}
allDeps, depErr := activeStore.GetAllDependencyRecords(ctx)
if depErr != nil && in.depsMode != "" {
return HandleError("loading dependencies for --deps: %v", depErr)
}
displayPrettyListWithDepsMode(issues, false, allDeps, in.depsMode, truncated, in.ReadyFlag, in.Status, in.SortBy, in.Reverse)
printTruncationHint(truncated, in.effectiveLimit)
printSkipLabelsFooter(in.SkipLabels)
return nil
}
if in.formatStr != "" {
depsByIssueID, _ := activeStore.GetAllDependencyRecords(ctx)
if err := outputFormattedList(out, issues, depsByIssueID, in.formatStr); err != nil {
return HandleError("%v", err)
}
printTruncationHint(truncated, in.effectiveLimit)
return nil
}
maybeShowUpgradeNotification()
issueIDs := make([]string, len(issues))
labelsMap := make(map[string][]string, len(issues))
for i, issue := range issues {
issueIDs[i] = issue.ID
if len(issue.Labels) > 0 {
labelsMap[issue.ID] = issue.Labels
}
}
// The decoration goes through issueops.BlockingAnnotator. Its failure is
// still swallowed: this route has always rendered the page undecorated
// rather than failing on it, while the proxied route fails — a difference
// between the two CALLERS, recorded for the owner in AMBIGUITIES.md
// (A-blk-1) rather than converged here.
blocking := annotateListBlocking(ctx, activeStore, issueIDs)
var buf strings.Builder
if ui.IsAgentMode() {
for _, issue := range issues {
formatAgentIssue(&buf, issue, blocking.blockedBy[issue.ID], blocking.blocks[issue.ID], blocking.parent[issue.ID])
}
fmt.Print(buf.String()) //nolint:forbidigo // Agent output is outside the --format contract.
printTruncationHint(truncated, in.effectiveLimit)
return nil
} else if in.longFormat {
buf.WriteString(fmt.Sprintf("\nFound %d issues:\n\n", len(issues)))
for _, issue := range issues {
labels := labelsMap[issue.ID]
formatIssueLong(&buf, issue, labels, in.SkipLabels)
}
} else {
for _, issue := range issues {
labels := labelsMap[issue.ID]
formatIssueCompact(&buf, issue, labels, blocking.blockedBy[issue.ID], blocking.blocks[issue.ID], blocking.parent[issue.ID])
}
}
if in.SkipLabels && !isQuiet() {
buf.WriteString(skipLabelsFooterText())
}
if err := ui.ToPager(buf.String(), ui.PagerOptions{NoPager: in.noPager}); err != nil {
if _, writeErr := fmt.Fprint(os.Stdout, buf.String()); writeErr != nil { //nolint:forbidigo // Pager fallback is outside the --format contract.
fmt.Fprintf(os.Stderr, "Error writing output: %v\n", writeErr)
}
}
printTruncationHint(truncated, in.effectiveLimit)
maybeShowTip(store)
return nil
}
func init() {
listCmd.Flags().VarP(&listStatusFlag, "status", "s", "Filter by stored status (open, in_progress, blocked, deferred, closed). Comma-separated or repeated for multiple: --status open,in_progress")
listCmd.Flags().Var(&listStateFlag, "state", "Alias for --status")
_ = listCmd.Flags().MarkHidden("state")
registerPriorityFlag(listCmd, "")
listCmd.Flags().VarP(&listAssigneeFlag, "assignee", "a", "Filter by assignee")
listCmd.Flags().VarP(&listTypeFlag, "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().Var(&listIDFlag, "id", "Filter by specific issue IDs (comma-separated or repeated, e.g., bd-1,bd-5,bd-10)")
listCmd.Flags().IntP("limit", "n", workapi.DefaultListLimit, "Limit results (an explicit --limit always wins, 0 meaning unlimited; otherwise --all is unlimited; otherwise a configured list.limit applies; otherwise unlimited when piped, else 20 in agent mode at a terminal, else 50)")
listCmd.Flags().Int("offset", 0, "Skip the first N matching results (0-based). Only supported under --proxied-server.")
listCmd.Flags().String("format", "", "Export the dependency graph of the listed issues: 'digraph' (edge list for golang.org/x/tools/cmd/digraph), 'dot' (Graphviz), or a Go template rendered once per edge over .IssueID, .DependsOnID, .Type, .Issue, .Dependency. 'json' is the exception and does not export the graph: it is equivalent to --json, which also wins when both flags are given. 'digraph' and templates print nothing when no listed issue depends on another; 'dot' still prints the nodes")
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, "Invert the sort field's default direction (created/updated/closed default to newest-first, so --sort updated --reverse is oldest-first)")
// 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)")
listCmd.Flags().String("external-contains", "", "Filter by external ref substring (case-insensitive)")
listCmd.Flags().String("external-ref", "", "Filter by exact external_ref value")
// 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")
// Hydration toggle (AD-02). Distinct from --no-labels (filter).
listCmd.Flags().Bool("skip-labels", false,
"Skip label hydration. The labels field in output will be empty regardless "+
"of actual labels. Use only when the caller does not depend on label data. "+
"Cannot combine with --label, --label-any, --label-pattern, --label-regex, "+
"--exclude-label, or --no-labels.")
// Projection toggle. Like --skip-labels it trades data for bytes, and
// unlike it the dropped fields leave a mark on the row (IsLitePartial).
// Hydration toggle, the list twin of `bd show --include-comments`. Like
// --skip-labels and --brief it changes what is HYDRATED and never which
// rows match. It costs a query per row that has comments, which is why it
// is opt-in on the most-run command in the tree.
listCmd.Flags().Bool("include-comments", false,
"Populate each row's comments field with full comment bodies in JSON output "+
"(--json only; costs one query per row that has comments). Without it, a row "+
"with comments carries comments_omitted=true, so an absent comments field is "+
"never mistaken for having none. Text output is unaffected either way.")
listCmd.Flags().Bool("brief", false,
"Omit the free-form text (description, design, acceptance criteria, notes, "+
"payload, waiters) from each row. Filters that read those fields, such as "+
"--desc-contains, still select on them. An omitted field is"+
" indistinguishable from an empty one in --json; fetch a whole issue"+
" with bd show.")
// 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/role/message by default
listCmd.Flags().Bool("include-infra", false, "Include infrastructure beads (agent/role/message) in output")
// Ephemeral plane: the wisps table is suppressed by default. This is the
// PLANE knob on its own — ListRequest.IncludeEphemeral — as distinct from
// --include-infra, which admits the plane AND lifts the infra-type
// exclusions above. Without it the plane is reachable from the CLI only
// through --include-infra's wider bundle, which leaves --wisp-type below
// with no narrow way to match anything.
listCmd.Flags().Bool("include-ephemeral", false, "Include ephemeral wisp-plane rows in output (normally hidden)")
// 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)")
// --deps annotates the tree with dependency edges and orders siblings by them.
// Bare --deps means "scheduling"; --deps=all also shows knowledge-graph edges.
listCmd.Flags().String("deps", "", "Annotate tree with dependency edges and order siblings by them: 'scheduling' (bare --deps) or 'all'")
if f := listCmd.Flags().Lookup("deps"); f != nil {
f.NoOptDefVal = "scheduling"
}
// 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)")
// Defensive row cap (be-x42v): exits 2 on overage, default disabled.
// ROUTED, not direct-only: both routes thread the cap now.
addRoutedMaxRowsFlag(listCmd)
// Note: --json flag is defined as a persistent flag in main.go, not here
rootCmd.AddCommand(listCmd)
}