beads/cmd/bd/label_whitespace_warn_test.go
Robin Carswell 543e44aef8
fix(labels): normalize labels on write, and warn when one contains a space (#5812) (#5813)
* fix(labels): normalize labels on write, as read paths already do (#5812)

bd applies utils.NormalizeLabels (trim, drop empty, dedupe) to every label
FILTER path -- list, search, ready, orphans, count and the workapi
equivalents -- but to no label WRITE path.

That asymmetry stores labels no filter can match:

    bd create "T" --labels 'theme:a, theme:b'   # stores "theme:a", " theme:b"
    bd list --label theme:b                     # filter trims -- no match

--labels 'a, b' is the comma-space form most people type, and pflag's CSV
split leaves the leading space on the second element, so the split looks
like it worked. A filtered list that is silently short is
indistinguishable from a complete one.

Two more everyday inputs corrupt just as quietly: --labels 'a,,b' stores
an empty label, and --labels 'a,a' stores the same label twice.

Apply the existing helper on the write paths so write and read agree:
create (--labels and its --label alias, normalized after merging the two
so dedupe spans both), quick, and update (--add-label, --remove-label,
--set-labels). --remove-label matters as much as the additive flags: an
untrimmed ' theme:a' fails to match the stored label and silently removes
nothing. The --set-labels '' clear-all signal is preserved -- it is gated
on pointer identity, not slice length.

Also add a warn-only 'Label Whitespace' doctor check, since the write-path
fix does nothing for labels already stored and nothing else surfaces them.
It reports leading/trailing and blank labels only. A label whose trimmed
form still contains whitespace is deliberately not reported: that turns on
what a space between labels should mean, which this change does not
settle, and "good first issue" is a legitimate multi-word label.

Not auto-fixable by design -- trimming a damaged label can collide with a
correct label already on the same issue, which needs a human decision.

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

* feat(labels): warn when a stored label contains a space (#5812)

A label containing a space is almost always a comma that was meant and
missed. That is the failure behind #5812's evidence: 150 corrupt label
rows across 111 issues, found months later only because theme-by-theme
counts failed to reconcile.

The issue proposed splitting labels on whitespace as well as commas. This
deliberately does NOT do that, and the reasoning is worth recording.

A shell has exactly one mechanism for "is this one word or two", and it is
already unambiguous. All three of these send ONE argument:

    bd create T --labels 'one two'
    bd create T --labels "one two"
    bd create T --labels one\ two

They are byte-identical by the time bd sees them: quoting and backslash-
escaping are consumed by the shell, which reports only the resulting word
boundaries. It is the same mechanism that makes 'cd my\ dir' work.

Splitting on whitespace would therefore override a boundary the caller has
already explicitly set, making labels the one place on the command line
where quoting does not mean what it means everywhere else. It is also
undoable: with splitting there is no way left to ask for a label containing
a space except a second, nested layer of quotes. And it cannot deliver what
it appears to promise, since 'one two' and "one two" are indistinguishable
by the time any code could act on them.

So honor the shell's boundaries, which bd already does, and warn instead:

    ⚠ Stored "theme:a theme:b" as ONE label — it contains a space.
      If you meant several labels, separate them with commas (a,b) or
      repeat the flag.

The 150 rows would have produced 150 warnings at the keystroke, while
--labels 'good first issue' still does exactly what it says. A warning
rather than an error, because a space-containing label is a legitimate
thing to ask for and the shell has just been used to ask for it; --quiet
silences it. No command changes meaning.

Applied to the paths that write labels: create, q, --add-label and
--set-labels. Deliberately not --remove-label, because removing a
space-containing label is how the damage gets repaired and warning on the
repair is noise.

The Label Whitespace doctor check gains a matching third class so an
existing database can find the ones already in it. It is reported
separately from the untrimmed/blank classes and is not called corruption:
bd cannot tell "good first issue" from a missed comma, so it surfaces them
and a human decides.

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

* fix(labels): close the last raw label write, bd tag (#5812)

Review feedback on #5813. `bd tag` describes itself as "Shorthand for
'bd update <id> --add-label <label>'" and was not: update normalizes and warns,
tag passed the positional straight to AddLabel, and the proxied route passed it
to ApplyLabelPatch, which drops "" but does not trim.

Verified on a scratch DB against binaries built either side of this commit:

  before: bd tag t-fap ' theme:spaced' -> stored " theme:spaced"
          bd list --label theme:spaced -> 0 rows
  after:  bd tag t-wjz ' theme:spaced' -> stored "theme:spaced"
          bd list --label theme:spaced -> 1 row

That is the unfilterable class this PR set out to close, written by the command
whose help text promises equivalence with the one that already closed it.

Normalization happens in tag.go BEFORE the route split, so the direct and
proxied paths cannot diverge on it; runTagProxiedServer now takes the resolved
id and label rather than raw args, which removes the second entry point.

A whitespace-only label is refused (exit 1) rather than dropped. The plural
flags can discard an empty element and still honor the rest of the request;
bd tag has exactly one label to add, so dropping it would report success having
written nothing.

Also here, both from the same review:

- `bd label add` now warns too. splitLabelArg already trimmed, so it never
  stored the untrimmed class, but it could not tell a caller that
  `bd label add bd-1 'theme:a theme:b'` is ONE label. Verified firing.
- docs/core-concepts/labels.md: says plainly that import and batch ingest are
  deliberately NOT normalized (round-trip fidelity; the doctor check is what
  finds legacy damage), so the next reader does not "fix" it. Also notes that
  bare `bd doctor` is not yet supported in embedded mode (GH#3794), so the new
  Label Whitespace check reaches classic and server-mode databases only --
  "run bd doctor" was overselling to embedded users.
- CHANGELOG entries under Fixed and Added.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Steve Yegge <steve.yegge@gmail.com>
2026-08-20 08:08:24 -07:00

96 lines
3.3 KiB
Go

package main
import (
"strings"
"testing"
"github.com/spf13/cobra"
)
// bd honors the shell's word boundaries: a quoted or backslash-escaped space
// makes ONE label, exactly as it makes one filename. That is correct, and also
// indistinguishable from a comma someone meant to type — so it warns.
func TestWarnLabelsContainingWhitespace(t *testing.T) {
tests := []struct {
name string
labels []string
wantWarn bool
}{
{"plain slugs stay silent", []string{"theme:a", "theme:b"}, false},
{"no labels stay silent", nil, false},
{"space-containing label warns", []string{"theme:a theme:b"}, true},
{"tab-containing label warns", []string{"theme:a\ttheme:b"}, true},
{"a deliberate multi-word label also warns", []string{"good first issue"}, true},
{"one bad among good still warns", []string{"theme:a", "b c"}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
out := captureStderr(t, func() {
warnLabelsContainingWhitespace(tt.labels)
})
if got := out != ""; got != tt.wantWarn {
t.Fatalf("warned=%v, want %v (stderr: %q)", got, tt.wantWarn, out)
}
if tt.wantWarn {
if !strings.Contains(out, "ONE label") {
t.Errorf("warning should say the label was stored whole, got: %q", out)
}
if !strings.Contains(out, "commas") {
t.Errorf("warning should point at the comma form, got: %q", out)
}
}
})
}
}
// The warning names every offending label, so a bulk write does not hide one
// behind another, but prints the remedy once.
func TestWarnLabelsContainingWhitespaceNamesEachLabelOnce(t *testing.T) {
out := captureStderr(t, func() {
warnLabelsContainingWhitespace([]string{"a b", "c d", "fine"})
})
if !strings.Contains(out, `"a b"`) || !strings.Contains(out, `"c d"`) {
t.Fatalf("expected both offending labels named, got: %q", out)
}
if strings.Contains(out, `"fine"`) {
t.Fatalf("a clean label must not be named, got: %q", out)
}
if n := strings.Count(out, "separate them with commas"); n != 1 {
t.Fatalf("expected the remedy line once, got %d: %q", n, out)
}
}
// The warning fires through the real create path, not just in isolation.
func TestGatherCreateInputWarnsOnSpaceContainingLabel(t *testing.T) {
out := captureStderr(t, func() {
cmd := newCreateFlagsCommand(t, "--title", "Title", "--labels", "theme:a theme:b")
if _, err := gatherCreateInput(cmd, nil); err != nil {
t.Errorf("gatherCreateInput: %v", err)
}
})
if !strings.Contains(out, "ONE label") {
t.Fatalf("expected create to warn on a space-containing label, got: %q", out)
}
}
// Removing a space-containing label is how the damage gets repaired, so the
// repair must not be warned at.
func TestGatherUpdateInputDoesNotWarnOnRemoveLabel(t *testing.T) {
out := captureStderr(t, func() {
cmd := &cobra.Command{Use: "update"}
cmd.Flags().StringSlice("add-label", nil, "")
cmd.Flags().StringSlice("remove-label", nil, "")
cmd.Flags().StringSlice("set-labels", nil, "")
if err := cmd.ParseFlags([]string{"--remove-label", "theme:a theme:b"}); err != nil {
t.Errorf("parse update flags: %v", err)
return
}
if _, err := gatherUpdateInput(t.Context(), cmd); err != nil {
t.Errorf("gatherUpdateInput: %v", err)
}
})
if out != "" {
t.Fatalf("removing a space-containing label must not warn, got: %q", out)
}
}