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>
This commit is contained in:
JennyMink 2026-09-30 21:32:42 -07:00 • committed by GitHub
commit 2704d8a954
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 366 additions and 5 deletions

View file

@ -9,6 +9,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- **`bd list` no longer silently drops all but the last repeated filter flag.**
`--status`, `--state`, and `--id` were plain string flags, so
`bd list --status open --status closed --status pinned` kept only `pinned` —
a census over 477 issues quietly answered over 3, with nothing in the output
to distinguish the narrowed answer from a correct one. Repeats of those three
flags now accumulate (duplicates collapse) instead of overwriting, so
`--status open --status closed` selects the same set as
`--status open,closed`. The one repeat that does not simply accumulate is one
involving `--status all`: `all` cannot be combined with other statuses, so
`--status all --status open` is now refused rather than narrowed to `open`.
`--type` and `--assignee` are single-valued all the way down — unioning would
fail type validation or exact-match nobody — so a repeat of either now refuses
loudly instead of silently keeping the last value:
`invalid argument "epic" for "-t, --type" flag: --type given more than once
(already "bug"); pass a single value`.
Single-flag and comma-form spellings behave exactly as before.
- **`bd init --force` can no longer silently recreate a missing server-side
database as empty** (be-5up5). `--force` is an alias for `--reinit-local`,
which skips the existing-data guard entirely, and the reinit path's own typed

View file

@ -179,6 +179,7 @@ go_library(
"lint.go",
"lint_proxied_server.go",
"list.go",
"list_filter_flags.go",
"list_format.go",
"list_input.go",
"list_output.go",
@ -849,6 +850,7 @@ go_test(
"list_comments_embedded_test.go",
"list_comments_proxied_integration_test.go",
"list_embedded_test.go",
"list_filter_flags_test.go",
"list_footer_counts_test.go",
"list_format_json_test.go",
"list_helpers_test.go",

View file

@ -406,12 +406,12 @@ func runListCore(cmd *cobra.Command, _ []string) error {
}
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. Note: repeating -s/--status silently overwrites the previous value — always use the comma-separated form for multi-status filters.")
listCmd.Flags().String("state", "", "Alias for --status")
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().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().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")
@ -419,7 +419,7 @@ func init() {
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().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")

101
cmd/bd/list_filter_flags.go Normal file
View file

@ -0,0 +1,101 @@
package main
import (
"fmt"
"slices"
"strings"
"github.com/spf13/pflag"
)
// unionStringFlag accumulates repeated flag occurrences into a comma-joined
// set: `--status open --status closed` means the same union as
// `--status open,closed`. Setting the empty string clears it — `bd children`
// resets listCmd's flags that way after borrowing them, and gatherListInput
// resets after each read so in-process callers that Execute() more than once
// do not inherit the previous command's filter.
type unionStringFlag struct {
value string
}
func (f *unionStringFlag) Set(s string) error {
switch {
case s == "":
f.value = ""
case f.value == "":
f.value = s
default:
for _, tok := range strings.Split(s, ",") {
if !slices.Contains(strings.Split(f.value, ","), tok) {
f.value += "," + tok
}
}
}
return nil
}
func (f *unionStringFlag) String() string { return f.value }
// Type reports "string" so cmd.Flags().GetString keeps working on flags
// registered with this value.
func (f *unionStringFlag) Type() string { return "string" }
// onceStringFlag refuses a repeated occurrence outright. It belongs on
// filters that are single-valued all the way down (--type, --assignee),
// where comma-joining would either fail type validation on the joined value
// or exact-match nothing and return an empty result that reads as a clean
// answer. Empty-string reset semantics match unionStringFlag.
type onceStringFlag struct {
name string
value string
set bool
}
func (f *onceStringFlag) Set(s string) error {
if s == "" {
f.value = ""
f.set = false
return nil
}
if f.set {
return fmt.Errorf("--%s given more than once (already %q); pass a single value", f.name, f.value)
}
f.set = true
f.value = s
return nil
}
func (f *onceStringFlag) String() string { return f.value }
func (f *onceStringFlag) Type() string { return "string" }
var (
listStatusFlag unionStringFlag
listStateFlag unionStringFlag
listIDFlag unionStringFlag
listTypeFlag = onceStringFlag{name: "type"}
listAssigneeFlag = onceStringFlag{name: "assignee"}
)
// resetListFilterFlags returns listCmd's five filter flags to their unparsed
// state: the values are cleared AND pflag's Changed bit is lowered on the
// given flag set, so an in-process caller that Execute()s listCmd twice sees
// neither the previous filter nor a stale "the user passed --status" signal.
// It takes the flag set as an argument rather than reading listCmd so that
// listCmd's initializer (via runListCore -> gatherListInput) does not refer
// back to itself.
func resetListFilterFlags(flags *pflag.FlagSet) {
_ = listStatusFlag.Set("")
_ = listStateFlag.Set("")
_ = listIDFlag.Set("")
_ = listTypeFlag.Set("")
_ = listAssigneeFlag.Set("")
if flags == nil {
return
}
for _, name := range []string{"status", "state", "type", "assignee", "id"} {
if fl := flags.Lookup(name); fl != nil {
fl.Changed = false
}
}
}

View file

@ -0,0 +1,237 @@
package main
import (
"strings"
"testing"
"github.com/steveyegge/beads/internal/workapi"
)
// resetListFilterFlagState restores listCmd's filter flags to their unparsed
// state so these tests leave nothing behind for the rest of the package.
func resetListFilterFlagState(t *testing.T) {
t.Helper()
t.Cleanup(func() { resetListFilterFlags(listCmd.Flags()) })
}
func TestListRepeatedStatusUnions(t *testing.T) {
resetListFilterFlagState(t)
if err := listCmd.ParseFlags([]string{"--status", "open", "--status", "closed", "-s", "pinned"}); err != nil {
t.Fatalf("ParseFlags: %v", err)
}
got, err := listCmd.Flags().GetString("status")
if err != nil {
t.Fatalf("GetString(status): %v", err)
}
if got != "open,closed,pinned" {
t.Fatalf("repeated --status = %q, want union %q", got, "open,closed,pinned")
}
}
func TestListSingleAndCommaStatusUnchanged(t *testing.T) {
resetListFilterFlagState(t)
if err := listCmd.ParseFlags([]string{"--status", "open"}); err != nil {
t.Fatalf("ParseFlags: %v", err)
}
if got, _ := listCmd.Flags().GetString("status"); got != "open" {
t.Fatalf("single --status = %q, want %q", got, "open")
}
resetListFilterFlags(listCmd.Flags())
if err := listCmd.ParseFlags([]string{"--status", "open,in_progress"}); err != nil {
t.Fatalf("ParseFlags: %v", err)
}
if got, _ := listCmd.Flags().GetString("status"); got != "open,in_progress" {
t.Fatalf("comma --status = %q, want %q", got, "open,in_progress")
}
}
func TestListRepeatedIDUnions(t *testing.T) {
resetListFilterFlagState(t)
if err := listCmd.ParseFlags([]string{"--id", "bd-1", "--id", "bd-2,bd-3"}); err != nil {
t.Fatalf("ParseFlags: %v", err)
}
if got, _ := listCmd.Flags().GetString("id"); got != "bd-1,bd-2,bd-3" {
t.Fatalf("repeated --id = %q, want %q", got, "bd-1,bd-2,bd-3")
}
}
func TestListRepeatedTypeRefused(t *testing.T) {
resetListFilterFlagState(t)
for _, args := range [][]string{
{"--type", "bug", "--type", "epic"},
{"-t", "bug", "-t", "epic"},
} {
resetListFilterFlags(listCmd.Flags())
err := listCmd.ParseFlags(args)
if err == nil {
t.Fatalf("ParseFlags(%v) accepted a repeated --type", args)
}
if !strings.Contains(err.Error(), "type") || !strings.Contains(err.Error(), "more than once") {
t.Fatalf("ParseFlags(%v) error %q does not name the repeated flag", args, err)
}
}
}
func TestListRepeatedAssigneeRefused(t *testing.T) {
resetListFilterFlagState(t)
err := listCmd.ParseFlags([]string{"--assignee", "alice", "--assignee", "bob"})
if err == nil {
t.Fatal("ParseFlags accepted a repeated --assignee")
}
if !strings.Contains(err.Error(), "assignee") || !strings.Contains(err.Error(), "more than once") {
t.Fatalf("error %q does not name the repeated flag", err)
}
}
func TestListSingleTypeAndAssigneeUnchanged(t *testing.T) {
resetListFilterFlagState(t)
if err := listCmd.ParseFlags([]string{"--type", "bug", "--assignee", "alice"}); err != nil {
t.Fatalf("ParseFlags: %v", err)
}
if got, _ := listCmd.Flags().GetString("type"); got != "bug" {
t.Fatalf("single --type = %q, want %q", got, "bug")
}
if got, _ := listCmd.Flags().GetString("assignee"); got != "alice" {
t.Fatalf("single --assignee = %q, want %q", got, "alice")
}
}
// bd children borrows listCmd's status flag with Set("all") and a deferred
// Set(""); an empty Set must fully reset both value kinds.
func TestEmptySetResetsFilterFlags(t *testing.T) {
resetListFilterFlagState(t)
fl := listCmd.Flags()
_ = fl.Set("status", "all")
_ = fl.Set("status", "")
_ = fl.Set("status", "open")
if got, _ := fl.GetString("status"); got != "open" {
t.Fatalf("status after reset = %q, want %q", got, "open")
}
_ = fl.Set("type", "bug")
_ = fl.Set("type", "")
if err := fl.Set("type", "epic"); err != nil {
t.Fatalf("Set(type) after reset refused: %v", err)
}
if got, _ := fl.GetString("type"); got != "epic" {
t.Fatalf("type after reset = %q, want %q", got, "epic")
}
}
// Two parses in one process must not bleed into each other once
// resetListFilterFlags has run between them, the way gatherListInput does.
func TestFilterFlagsDoNotLeakAcrossParses(t *testing.T) {
resetListFilterFlagState(t)
if err := listCmd.ParseFlags([]string{"--status", "open", "--status", "closed"}); err != nil {
t.Fatalf("ParseFlags: %v", err)
}
resetListFilterFlags(listCmd.Flags())
if err := listCmd.ParseFlags([]string{"--status", "pinned"}); err != nil {
t.Fatalf("ParseFlags: %v", err)
}
if got, _ := listCmd.Flags().GetString("status"); got != "pinned" {
t.Fatalf("status after second parse = %q, want %q (leaked prior parse)", got, "pinned")
}
}
func TestListRepeatedStatusDedupes(t *testing.T) {
resetListFilterFlagState(t)
if err := listCmd.ParseFlags([]string{"--status", "open", "--status", "open,closed", "--status", "closed"}); err != nil {
t.Fatalf("ParseFlags: %v", err)
}
got, err := listCmd.Flags().GetString("status")
if err != nil {
t.Fatalf("GetString(status): %v", err)
}
if got != "open,closed" {
t.Fatalf("repeated --status with duplicates = %q, want %q", got, "open,closed")
}
}
func TestResetListFilterFlagsLowersChanged(t *testing.T) {
resetListFilterFlagState(t)
if err := listCmd.ParseFlags([]string{"--status", "open", "--type", "bug"}); err != nil {
t.Fatalf("ParseFlags: %v", err)
}
for _, name := range []string{"status", "type"} {
if !listCmd.Flags().Changed(name) {
t.Fatalf("precondition: --%s should read as Changed after parse", name)
}
}
resetListFilterFlags(listCmd.Flags())
for _, name := range []string{"status", "state", "type", "assignee", "id"} {
if listCmd.Flags().Changed(name) {
t.Fatalf("--%s still reads as Changed after resetListFilterFlags", name)
}
}
}
// TestListStateAndStatusArms pins the three reachable arms of the new flag
// registration that the existing cases do not reach: the hidden --state alias
// unions like --status, a union that includes "all" is refused downstream
// rather than silently narrowing, and --status wins over --state when both are
// given (gatherListInput only consults --state when --status is empty).
func TestListStateAndStatusArms(t *testing.T) {
t.Run("repeated --state unions", func(t *testing.T) {
resetListFilterFlagState(t)
if err := listCmd.ParseFlags([]string{"--state", "open", "--state", "closed"}); err != nil {
t.Fatalf("ParseFlags: %v", err)
}
got, err := listCmd.Flags().GetString("state")
if err != nil {
t.Fatalf("GetString(state): %v", err)
}
if got != "open,closed" {
t.Fatalf("repeated --state = %q, want union %q", got, "open,closed")
}
})
t.Run("union including all is refused, not narrowed", func(t *testing.T) {
resetListFilterFlagState(t)
if err := listCmd.ParseFlags([]string{"--status", "all", "--status", "open"}); err != nil {
t.Fatalf("ParseFlags: %v", err)
}
in, err := gatherListInput(listCmd)
if err != nil {
t.Fatalf("gatherListInput: %v", err)
}
if in.Status != "all,open" {
t.Fatalf("unioned status = %q, want %q", in.Status, "all,open")
}
// The union is what makes this reachable: before this PR the repeat
// kept only "open" and the combination never reached the guard.
if _, err := workapi.BuildListFilter(in.ListRequest, workapi.ListConfig{}); err == nil {
t.Fatal("BuildListFilter accepted a union containing \"all\", want a refusal")
} else if !strings.Contains(err.Error(), "cannot be combined") {
t.Fatalf("BuildListFilter error = %v, want a \"cannot be combined\" refusal", err)
}
})
t.Run("--status outranks --state", func(t *testing.T) {
resetListFilterFlagState(t)
if err := listCmd.ParseFlags([]string{"--status", "open", "--state", "closed"}); err != nil {
t.Fatalf("ParseFlags: %v", err)
}
in, err := gatherListInput(listCmd)
if err != nil {
t.Fatalf("gatherListInput: %v", err)
}
if in.Status != "open" {
t.Fatalf("in.Status = %q, want %q (--state must not merge into a non-empty --status)", in.Status, "open")
}
})
}

View file

@ -43,6 +43,10 @@ type listInput struct {
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")