beads/cmd/bd/list_input.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

436 lines
16 KiB
Go

package main
import (
"fmt"
"os"
"strings"
"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"
"github.com/steveyegge/beads/internal/workapi"
"github.com/steveyegge/beads/issueops"
)
// listInput is everything `bd list` parsed off the command line: the
// frontend-independent query knobs (issueops.ListRequest, the request the
// reader role takes and the filter is built from) plus the presentation
// choices that never leave the CLI.
type listInput struct {
issueops.ListRequest
longFormat bool
prettyFormat bool
flatFormat bool
depsMode string
watchMode bool
noPager bool
formatStr string
jsonOutput bool
limitChanged bool
effectiveLimit int
repoOverride string
repoOverrideSet bool
}
func gatherListInput(cmd *cobra.Command) (listInput, error) {
in := listInput{}
// The custom filter values persist across in-process Execute() calls;
// clear them once this read has copied them out.
defer resetListFilterFlags(cmd.Flags())
in.Status, _ = cmd.Flags().GetString("status")
if in.Status == "" {
in.Status, _ = cmd.Flags().GetString("state")
}
in.Assignee, _ = cmd.Flags().GetString("assignee")
rawType, _ := cmd.Flags().GetString("type")
in.IssueType = utils.NormalizeIssueType(rawType)
limit, _ := cmd.Flags().GetInt("limit")
in.limitChanged = cmd.Flags().Changed("limit")
listLimitConfigured := false
if !in.limitChanged {
listLimitConfigured = config.GetValueSource("list.limit") != config.SourceDefault
limit = config.GetInt("list.limit")
}
in.AllFlag, _ = cmd.Flags().GetBool("all")
in.formatStr, _ = cmd.Flags().GetString("format")
if strings.EqualFold(in.formatStr, "json") {
jsonOutput = true
in.formatStr = ""
} else if in.formatStr != "" && cmd.Flags().Changed("format") && !commandJSONFlagChanged(cmd) {
// A --format the caller typed outranks a json default from config or
// the environment (GH#6278). The root pre-run promotes `json: true`
// into jsonOutput unless the ROOT --format changed, but this command's
// own --format shadows the root one, so that check never sees it and
// the JSON branch would replace the requested graph or template. An
// explicit --json still wins (the !commandJSONFlagChanged conjunct
// above is what preserves it); note no flag's help text states that
// precedence, so this comment is its only record.
jsonOutput = false
}
in.jsonOutput = jsonOutput
in.Labels, _ = cmd.Flags().GetStringSlice("label")
in.LabelsAny, _ = cmd.Flags().GetStringSlice("label-any")
in.ExcludeLabels, _ = cmd.Flags().GetStringSlice("exclude-label")
in.LabelPattern, _ = cmd.Flags().GetString("label-pattern")
in.LabelRegex, _ = cmd.Flags().GetString("label-regex")
in.TitleSearch, _ = cmd.Flags().GetString("title")
in.SpecPrefix, _ = cmd.Flags().GetString("spec")
in.IDFilter, _ = cmd.Flags().GetString("id")
in.longFormat, _ = cmd.Flags().GetBool("long")
in.SortBy, _ = cmd.Flags().GetString("sort")
in.Reverse, _ = cmd.Flags().GetBool("reverse")
in.TitleContains, _ = cmd.Flags().GetString("title-contains")
in.DescContains, _ = cmd.Flags().GetString("desc-contains")
in.NotesContains, _ = cmd.Flags().GetString("notes-contains")
in.ExternalContains, _ = cmd.Flags().GetString("external-contains")
in.ExternalRef, _ = cmd.Flags().GetString("external-ref")
in.EmptyDesc, _ = cmd.Flags().GetBool("empty-description")
in.NoAssignee, _ = cmd.Flags().GetBool("no-assignee")
in.NoLabels, _ = cmd.Flags().GetBool("no-labels")
in.Brief, _ = cmd.Flags().GetBool("brief")
in.IncludeComments, _ = cmd.Flags().GetBool("include-comments")
in.SkipLabels, _ = cmd.Flags().GetBool("skip-labels")
if in.SkipLabels {
conflicts := skipLabelsConflicts(in.Labels, in.LabelsAny, in.LabelPattern, in.LabelRegex, in.ExcludeLabels, in.NoLabels)
if len(conflicts) > 0 {
fmt.Fprint(os.Stderr, formatSkipLabelsConflictError(conflicts))
return in, &exitError{Code: 2}
}
}
if cmd.Flags().Changed("priority") {
priorityStr, _ := cmd.Flags().GetString("priority")
p, err := validation.ValidatePriority(priorityStr)
if err != nil {
return in, HandleError("%v", err)
}
in.Priority = &p
}
if cmd.Flags().Changed("priority-min") {
s, _ := cmd.Flags().GetString("priority-min")
p, err := validation.ValidatePriority(s)
if err != nil {
return in, HandleError("parsing --priority-min: %v", err)
}
in.PriorityMin = &p
}
if cmd.Flags().Changed("priority-max") {
s, _ := cmd.Flags().GetString("priority-max")
p, err := validation.ValidatePriority(s)
if err != nil {
return in, HandleError("parsing --priority-max: %v", err)
}
in.PriorityMax = &p
}
in.PinnedFlag, _ = cmd.Flags().GetBool("pinned")
in.NoPinnedFlag, _ = cmd.Flags().GetBool("no-pinned")
if in.PinnedFlag && in.NoPinnedFlag {
return in, HandleError("--pinned and --no-pinned are mutually exclusive")
}
in.IncludeTemplates, _ = cmd.Flags().GetBool("include-templates")
in.IncludeGates, _ = cmd.Flags().GetBool("include-gates")
in.IncludeInfra, _ = cmd.Flags().GetBool("include-infra")
in.IncludeEphemeral, _ = cmd.Flags().GetBool("include-ephemeral")
in.ExcludeTypes, _ = cmd.Flags().GetStringSlice("exclude-type")
in.ParentID, _ = cmd.Flags().GetString("parent")
if in.ParentID == "" {
in.ParentID, _ = cmd.Flags().GetString("filter-parent")
}
in.NoParent, _ = cmd.Flags().GetBool("no-parent")
if in.ParentID != "" && in.NoParent {
return in, HandleError("--parent and --no-parent are mutually exclusive")
}
if s, _ := cmd.Flags().GetString("mol-type"); s != "" {
mt := types.MolType(s)
if !mt.IsValid() {
return in, HandleError("invalid mol-type %q (must be %s)", s, types.ValidMolTypeNames())
}
in.MolType = &mt
}
if s, _ := cmd.Flags().GetString("wisp-type"); s != "" {
wt := types.WispType(s)
if !wt.IsValid() {
return in, HandleError("invalid wisp-type %q (must be %s)", s, types.ValidWispTypeNames())
}
in.WispType = &wt
// wisp_type is a PREDICATE, not a plane selector (see
// issueops.ListRequest.WispType): it narrows whatever the rest of the
// request admitted. On a default listing that is the durable rows,
// which carry no classification — so this request cannot match a row
// for ANY input, and would report an empty listing rather than the
// unread plane that actually holds the answer.
//
// The request stays LAWFUL at the API layer, where composing to empty
// is the pinned contract. Refusing it belongs HERE, at the CLI, where
// the only thing a human can have meant is the combination that
// answers with rows.
//
// An explicit --type is left alone: an infra type routes to the plane
// by itself, so the request may be satisfiable and this cannot tell
// without the workspace's infra vocabulary, which this layer does not
// load.
if !in.IncludeEphemeral && !in.IncludeInfra && in.IssueType == "" {
return in, HandleErrorWithHint(
fmt.Sprintf("--wisp-type %s cannot match anything here: it filters the wisp_type column, and this listing admits only durable rows, which never carry one", s),
"add --include-ephemeral to admit the ephemeral plane (or --include-infra, which admits it as part of a wider bundle)")
}
}
in.DeferredFlag, _ = cmd.Flags().GetBool("deferred")
in.OverdueFlag, _ = cmd.Flags().GetBool("overdue")
var err error
if in.CreatedAfter, err = parseListTimeFlag(cmd, "created-after"); err != nil {
return in, err
}
if in.CreatedBefore, err = parseListTimeFlag(cmd, "created-before"); err != nil {
return in, err
}
if in.UpdatedAfter, err = parseListTimeFlag(cmd, "updated-after"); err != nil {
return in, err
}
if in.UpdatedBefore, err = parseListTimeFlag(cmd, "updated-before"); err != nil {
return in, err
}
if in.ClosedAfter, err = parseListTimeFlag(cmd, "closed-after"); err != nil {
return in, err
}
if in.ClosedBefore, err = parseListTimeFlag(cmd, "closed-before"); err != nil {
return in, err
}
if in.DeferAfter, err = parseListTimeFlag(cmd, "defer-after"); err != nil {
return in, err
}
if in.DeferBefore, err = parseListTimeFlag(cmd, "defer-before"); err != nil {
return in, err
}
if in.DueAfter, err = parseListTimeFlag(cmd, "due-after"); err != nil {
return in, err
}
if in.DueBefore, err = parseListTimeFlag(cmd, "due-before"); err != nil {
return in, err
}
metadataFieldFlags, _ := cmd.Flags().GetStringArray("metadata-field")
if len(metadataFieldFlags) > 0 {
in.MetadataFields = make(map[string]string, len(metadataFieldFlags))
for _, mf := range metadataFieldFlags {
k, v, ok := strings.Cut(mf, "=")
if !ok || k == "" {
return in, HandleErrorRespectJSON("invalid --metadata-field: expected key=value, got %q", mf)
}
if err := storage.ValidateMetadataKey(k); err != nil {
return in, HandleErrorRespectJSON("invalid --metadata-field key: %v", err)
}
in.MetadataFields[k] = v
}
}
if k, _ := cmd.Flags().GetString("has-metadata-key"); k != "" {
if err := storage.ValidateMetadataKey(k); err != nil {
return in, HandleErrorRespectJSON("invalid --has-metadata-key: %v", err)
}
in.HasMetadataKey = k
}
prettyFormat, _ := cmd.Flags().GetBool("pretty")
treeFormat, _ := cmd.Flags().GetBool("tree")
in.flatFormat, _ = cmd.Flags().GetBool("flat")
if in.flatFormat {
treeFormat = false
}
in.prettyFormat = (prettyFormat || treeFormat) && !in.jsonOutput && in.formatStr == ""
in.watchMode, _ = cmd.Flags().GetBool("watch")
if in.watchMode {
// --watch re-renders the pretty listing on every tick, so a --format
// template would be dropped without a word (GH#6277). Refused here,
// ahead of the route split, so the direct and proxied routes answer
// the same way.
if in.formatStr != "" {
return in, HandleError("--format cannot be combined with --watch; --watch always renders the pretty listing")
}
in.prettyFormat = true
}
in.noPager, _ = cmd.Flags().GetBool("no-pager")
in.ReadyFlag, _ = cmd.Flags().GetBool("ready")
// REFUSED WHERE IT CANNOT BE HONORED OR CANNOT BE SEEN. The page routes,
// direct and proxied, JSON and text, all hand this request to
// issueops.Reader.List, whose query reads types.IssueFilter.Lite; the three
// below leave that query.
//
// --watch re-queries on a ticker through loadWatchedIssues, whose --ready
// arm calls the bare GetReadyWork and whose --parent arm walks the tree;
// neither reads Lite.
//
// --parent with --pretty is that same tree walk, an unlimited per-level
// query rather than a page.
//
// --format hands the whole issue to a caller-written template, so
// `--brief --format '{{.Issue.Description}}'` would print an empty string
// with nothing to say it had been dropped. The long format prints one
// omitted field and says so; a template can print any of the six and
// cannot be annotated.
if in.Brief {
switch {
case in.watchMode:
return in, HandleError("--watch cannot be combined with --brief")
case in.formatStr != "":
return in, HandleError("--format cannot be combined with --brief; a template can print a field --brief omits, with nothing to mark it")
case in.ParentID != "" && in.prettyFormat:
return in, HandleError("--parent with --pretty cannot be combined with --brief; the hierarchical walk is a different query")
}
}
in.depsMode, _ = cmd.Flags().GetString("deps")
if in.depsMode != "" {
if in.depsMode != "scheduling" && in.depsMode != "all" {
return in, HandleErrorRespectJSON("invalid --deps value %q (valid: scheduling, all)", in.depsMode)
}
// --deps annotates and orders the parent-child tree, so it is meaningful
// only in the tree view. Reject the non-tree output modes rather than
// accept the flag and silently ignore it, then imply the tree view so a
// bare `--deps` renders as intended (mirrors --watch implying --pretty).
switch {
case in.jsonOutput:
return in, HandleErrorRespectJSON("--deps is not supported with --json output")
case in.formatStr != "":
return in, HandleErrorRespectJSON("--deps is not supported with --format output")
case in.flatFormat:
return in, HandleErrorRespectJSON("--deps requires the tree view and cannot be combined with --flat")
case in.watchMode:
return in, HandleErrorRespectJSON("--deps is not supported with --watch")
}
in.prettyFormat = true
}
if in.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[in.SortBy] {
return in, HandleError("invalid sort field %q (valid: priority, created, updated, closed, status, id, title, type, assignee)", in.SortBy)
}
}
in.Labels = utils.NormalizeLabels(in.Labels)
in.LabelsAny = utils.NormalizeLabels(in.LabelsAny)
in.ExcludeLabels = utils.NormalizeLabels(in.ExcludeLabels)
if !in.SkipLabels && len(in.Labels) == 0 && len(in.LabelsAny) == 0 {
if dirLabels := config.GetDirectoryLabels(); len(dirLabels) > 0 {
in.LabelsAny = dirLabels
}
}
in.effectiveLimit = limit
switch {
case in.limitChanged:
in.effectiveLimit = limit
case in.AllFlag:
in.effectiveLimit = 0
case listLimitConfigured:
in.effectiveLimit = limit
default:
in.effectiveLimit = unflaggedLimit(limit)
}
// The request carries the limit the caller receives. Which row limit that
// implies for the query - a sort SQL cannot express fetches everything and
// trims client-side - is workapi.SQLLimit's decision, made once, inside the
// builder, for every frontend.
pageLimit := in.effectiveLimit
in.Limit = &pageLimit
if cmd.Flags().Changed("offset") {
offset, _ := cmd.Flags().GetInt("offset")
if offset < 0 {
return in, HandleError("--offset must be >= 0")
}
// --offset only makes sense when pagination happens in SQL. Sorts
// that fall back to Go-side (currently --sort id) fetch everything
// regardless, so combining them with --offset is misleading — the
// caller would think they're paging when they're really pulling
// the whole result set.
if offset > 0 && workapi.SQLLimit(in.ListRequest) == 0 && in.SortBy == "id" {
return in, HandleError("--offset is not supported with --sort %s (sort requires fetching the full result set)", in.SortBy)
}
in.Offset = offset
}
// The defensive cap is part of the REQUEST, not something stamped onto the
// filter after the builder has produced it (issueops.ListRequest.MaxRows).
//
// Resolving it HERE also means it is resolved exactly once per invocation.
// resolveMaxRowsEnvOnly warns on a malformed BEADS_MAX_ROWS every time it
// runs, so a second resolve downstream would warn twice.
maxRows, maxRowsSource, err := resolveMaxRows(cmd)
if err != nil {
return in, err
}
in.MaxRows = maxRows
in.MaxRowsSource = maxRowsSource
in.repoOverride, _ = cmd.Flags().GetString("repo")
in.repoOverrideSet = cmd.Flags().Changed("repo")
return in, nil
}
func parseListTimeFlag(cmd *cobra.Command, name string) (*time.Time, error) {
s, _ := cmd.Flags().GetString(name)
if s == "" {
return nil, nil
}
t, err := parseTimeFlag(s)
if err != nil {
return nil, HandleError("parsing --%s: %v", name, err)
}
return &t, nil
}
// agentModeLimit is the page size an unflagged listing gets in agent mode on a
// terminal: ultra-compact output for an LLM context window.
const agentModeLimit = 20
// unflaggedLimit is the limit a listing command uses when the caller named
// none: the part of the policy `bd list` and `bd query` share, so the two
// cannot drift (GH#6229). Each command resolves its own earlier branches first
// (an explicit --limit, `bd list`'s --all and list.limit) and hands its own
// default here as fallback.
func unflaggedLimit(fallback int) int {
return resolveUnflaggedLimit(fallback, ui.IsTerminal(), ui.IsAgentMode())
}
// resolveUnflaggedLimit is unflaggedLimit with the environment passed in, so
// the terminal and agent-mode branches are testable from a piped `go test`.
func resolveUnflaggedLimit(fallback int, stdoutIsTerminal, agentMode bool) int {
switch {
case !stdoutIsTerminal:
return 0 // Piped stdout should not truncate (GH#4094)
case agentMode:
return agentModeLimit
}
return fallback
}