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>
This commit is contained in:
Robin Carswell 2026-08-20 16:08:24 +01:00 • committed by GitHub
commit 543e44aef8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 794 additions and 12 deletions

View file

@ -7,6 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
- **`bd` warns when it stores a label containing a space**
([#5813](https://github.com/gastownhall/beads/pull/5813)). Such a label is a
legitimate thing to ask for — `-l 'good first issue'` — and bd stores it as
asked rather than re-splitting a boundary the shell already decided. But it is
also exactly what a missed comma looks like, and that case cannot be told
apart from the deliberate one at the point of writing. A line on stderr
catches it at the keystroke instead of months later: `⚠ Stored "auth backend"
as ONE label — it contains a space.` It is advice, not an error; stdout is
untouched, so `--silent` still prints just the ID, and `--quiet` silences it.
Not emitted for `--remove-label`, since removing such a label is how the
damage gets repaired.
- **`bd doctor` gains a `Label Whitespace` check** for finding damage already in
a database ([#5813](https://github.com/gastownhall/beads/pull/5813)). It
reports labels that contain whitespace or differ from their trimmed form, and
`bd doctor --fix` repairs them. The check is warn-only: a database with legacy
damage still exits 0. As with the rest of bare `bd doctor`, it does not yet
run in embedded mode (GH#3794).
### Changed
- **`bd show` labels `created_by` as `Created by:`, not `Owner:`** (be-ss66).
@ -128,6 +149,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`Nothing to commit` (`committed: false` in JSON) instead of attributing an
unchanged HEAD to a new commit.
- **Every CLI label write now normalizes its input, as every label filter
already did** ([#5813](https://github.com/gastownhall/beads/pull/5813),
fixes [#5812](https://github.com/gastownhall/beads/issues/5812)).
`utils.NormalizeLabels` (trim, drop empty, dedupe) was applied to `list`,
`search`, `ready`, `orphans`, `count` and workapi — and to no write path at
all. The filter trimmed its input and the store did not, so a label could not
match its own filter: `bd create --labels 'theme:a, theme:b'` stored
`theme:b` with pflag's leading space intact, and `bd list --label theme:b`
then returned nothing. The failure is silent in the worst way — a filtered
list quietly short of rows is indistinguishable from a complete one. One real
database had 150 such rows across 111 issues, found months later only because
theme-by-theme counts refused to reconcile. `create`, `quick`, `update`
(`--add-label`, `--remove-label`, `--set-labels`) and `tag` now normalize on
the way in. `--remove-label` matters as much as the additive flags: an
untrimmed `' theme:a'` silently removed nothing.
**`bd tag` is included deliberately.** Its help calls it "Shorthand for
`bd update <id> --add-label <label>`", and it was the last CLI door still
storing a positional verbatim. Normalization happens before the direct/proxied
route split, so the two routes cannot disagree. A label that is only
whitespace is now refused rather than dropped: the plural flags can discard an
empty element and still honor the rest of the request, but `bd tag` has one
label to add, so dropping it would report success having written nothing.
**Import and batch ingest are deliberately excluded** and keep round-trip
fidelity: what was exported is what is restored.
- **`bd show` no longer corrupts shell globs and other quoted wildcards in a
description or notes**
([#5799](https://github.com/gastownhall/beads/pull/5799)). CommonMark lets a

View file

@ -23,6 +23,7 @@ import (
"github.com/steveyegge/beads/internal/timeparsing"
"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/issueops"
)
@ -179,6 +180,8 @@ var createCmd = &cobra.Command{
if len(labelAlias) > 0 {
labels = append(labels, labelAlias...)
}
labels = utils.NormalizeLabels(labels)
warnLabelsContainingWhitespace(labels)
explicitID, _ := cmd.Flags().GetString("id")
parentID, _ := cmd.Flags().GetString("parent")

View file

@ -13,6 +13,7 @@ import (
"github.com/steveyegge/beads/internal/timeparsing"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/utils"
"github.com/steveyegge/beads/internal/validation"
)
@ -197,6 +198,12 @@ func gatherCreateInput(cmd *cobra.Command, args []string) (createInput, error) {
if len(labelAlias) > 0 {
in.labels = append(in.labels, labelAlias...)
}
// Normalize after merging the alias so dedupe spans both flags. Read paths
// (list, search, ready, orphans) already do this; without it here, `--labels
// 'a, b'` stores " b" with pflag's leading space and can never match its own
// filter.
in.labels = utils.NormalizeLabels(in.labels)
warnLabelsContainingWhitespace(in.labels)
in.deps, _ = cmd.Flags().GetStringSlice("deps")
in.repoOverride, _ = cmd.Flags().GetString("repo")

View file

@ -734,6 +734,15 @@ func runDiagnostics(path string) doctorResult {
blockedConsistencyCheck := convertWithCategory(doctor.CheckBlockedConsistencyWithStore(sharedStore), doctor.CategoryData)
result.Checks = append(result.Checks, blockedConsistencyCheck)
// Check 10d: label whitespace damage (#5812) — labels written by a bd that
// normalized on read but not on write, which no filter can match.
// Warn-only (does not fail OverallOK), same reasoning as the check above:
// this ships into databases that already carry the damage, and turning
// doctor red on pre-existing data across the fleet would be worse than
// surfacing it as actionable.
labelWhitespaceCheck := convertWithCategory(doctor.CheckLabelWhitespaceWithStore(sharedStore), doctor.CategoryData)
result.Checks = append(result.Checks, labelWhitespaceCheck)
// Check 11: Claude integration
claudeCheck := convertWithCategory(doctor.CheckClaude(path), doctor.CategoryIntegration)
result.Checks = append(result.Checks, claudeCheck)

View file

@ -0,0 +1,161 @@
package fix
import (
"context"
"database/sql"
"fmt"
"sort"
"strings"
"unicode"
)
// labelTables are the label tables scanned for whitespace damage, mirroring
// issueops.WispTableRouting.
var labelTables = []string{"labels", "wisp_labels"}
// LabelWhitespaceAnomalies summarizes one table's labels carrying whitespace
// damage (#5812).
//
// Untrimmed and Blank are unambiguous corruption: bd normalizes labels on every
// FILTER path but historically did not on any WRITE path, so a stored " a" can
// never match its own `--label a` filter and a filtered list is silently short.
//
// Internal — a trimmed label that still contains a space — is reported
// SEPARATELY and is not called corruption. bd honors the shell's word
// boundaries, so `--labels 'one two'` legitimately means one label, exactly as
// it means one filename. But it is also what someone typed when they meant a
// comma, which is how #5812's 150 corrupt rows were made. New writes now warn
// at the keystroke; this class is how a database finds the ones already in it,
// and a human decides which were meant.
type LabelWhitespaceAnomalies struct {
Table string
Untrimmed []LabelRow // label differs from its trimmed form
Blank []LabelRow // label is empty or whitespace-only
Internal []LabelRow // trimmed label still contains whitespace
}
// LabelRow identifies one damaged label by the issue carrying it.
type LabelRow struct {
IssueID string
Label string
}
// LabelWhitespaceClass is how ScanLabelWhitespace classifies a single label.
type LabelWhitespaceClass int
const (
// LabelClean is matchable by its own filter.
LabelClean LabelWhitespaceClass = iota
// LabelBlank is empty or whitespace-only.
LabelBlank
// LabelUntrimmed has leading or trailing whitespace.
LabelUntrimmed
// LabelInternalSpace is trimmed but still contains whitespace.
LabelInternalSpace
)
// ClassifyLabelWhitespace reports which class of whitespace a label carries,
// using strings.TrimSpace so that tabs, newlines and Unicode spaces are treated
// exactly as utils.NormalizeLabels treats them.
//
// A label is reported under one class only: leading/trailing whitespace is the
// actionable finding for an untrimmed label, so it is not also counted as an
// internal space.
func ClassifyLabelWhitespace(label string) LabelWhitespaceClass {
trimmed := strings.TrimSpace(label)
switch {
case trimmed == "":
return LabelBlank
case trimmed != label:
return LabelUntrimmed
case strings.ContainsFunc(trimmed, unicode.IsSpace):
return LabelInternalSpace
default:
return LabelClean
}
}
// Total returns the number of flagged rows across all three classes.
func (a LabelWhitespaceAnomalies) Total() int {
return len(a.Untrimmed) + len(a.Blank) + len(a.Internal)
}
// ScanLabelWhitespace reports labels carrying whitespace damage in both label
// tables. Tables absent from the schema are skipped; only tables with anomalies
// appear in the result.
//
// Classification happens in Go rather than SQL so that tabs, newlines and
// Unicode spaces are caught the same way strings.TrimSpace catches them —
// a TRIM()-based predicate would silently miss them.
func ScanLabelWhitespace(ctx context.Context, db *sql.DB) ([]LabelWhitespaceAnomalies, error) {
var out []LabelWhitespaceAnomalies
for _, table := range labelTables {
exists, err := labelTableExists(ctx, db, table)
if err != nil {
return nil, fmt.Errorf("%s: %w", table, err)
}
if !exists {
continue
}
a := LabelWhitespaceAnomalies{Table: table}
//nolint:gosec // G201: table is a hardcoded constant, never user input.
rows, err := db.QueryContext(ctx, fmt.Sprintf(`SELECT issue_id, label FROM %s`, table))
if err != nil {
return nil, fmt.Errorf("%s: %w", table, err)
}
for rows.Next() {
var issueID string
var label sql.NullString
if err := rows.Scan(&issueID, &label); err != nil {
_ = rows.Close()
return nil, fmt.Errorf("%s: %w", table, err)
}
if !label.Valid {
continue
}
row := LabelRow{IssueID: issueID, Label: label.String}
switch ClassifyLabelWhitespace(label.String) {
case LabelBlank:
a.Blank = append(a.Blank, row)
case LabelUntrimmed:
a.Untrimmed = append(a.Untrimmed, row)
case LabelInternalSpace:
a.Internal = append(a.Internal, row)
}
}
_ = rows.Close()
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("%s: %w", table, err)
}
if a.Total() > 0 {
sortLabelRows(a.Untrimmed)
sortLabelRows(a.Blank)
sortLabelRows(a.Internal)
out = append(out, a)
}
}
return out, nil
}
// sortLabelRows gives the scan a stable order so doctor output does not churn
// between runs on an unchanged database.
func sortLabelRows(rows []LabelRow) {
sort.SliceStable(rows, func(i, j int) bool {
if rows[i].IssueID != rows[j].IssueID {
return rows[i].IssueID < rows[j].IssueID
}
return rows[i].Label < rows[j].Label
})
}
func labelTableExists(ctx context.Context, db *sql.DB, table string) (bool, error) {
var count int
if err := db.QueryRowContext(ctx,
`SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?`,
table).Scan(&count); err != nil {
return false, err
}
return count > 0, nil
}

View file

@ -0,0 +1,48 @@
package fix
import "testing"
// The classifier is the load-bearing part of the #5812 doctor check: it decides
// which stored labels bd can no longer filter for. The SQL around it is a plain
// table scan.
func TestClassifyLabelWhitespace(t *testing.T) {
tests := []struct {
name string
label string
want LabelWhitespaceClass
}{
{"plain slug", "theme:a", LabelClean},
{"empty", "", LabelBlank},
{"spaces only", " ", LabelBlank},
{"tab only", "\t", LabelBlank},
// The shape pflag's CSV split produces from `--labels 'a, b'`.
{"leading space", " theme:b", LabelUntrimmed},
{"trailing space", "theme:b ", LabelUntrimmed},
{"trailing newline", "theme:b\n", LabelUntrimmed},
// A space-containing label is legal — the shell said one word — but it is
// also what a missed comma looks like, so it is surfaced for review
// rather than called corruption.
{"internal space", "theme:a theme:b", LabelInternalSpace},
{"internal tab", "theme:a\ttheme:b", LabelInternalSpace},
{"multi-word github label", "good first issue", LabelInternalSpace},
// Outer whitespace is the finding even when the label also has an
// internal space — the trimmed form is what a filter would match.
{"untrimmed with internal space", " theme:a theme:b ", LabelUntrimmed},
// TrimSpace is Unicode-aware, so the check must be too: a non-breaking
// space is invisible in a terminal and would otherwise slip through.
{"unicode nbsp leading", "\u00a0theme:a", LabelUntrimmed},
{"unicode nbsp trailing", "theme:a\u00a0", LabelUntrimmed},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := ClassifyLabelWhitespace(tt.label); got != tt.want {
t.Errorf("ClassifyLabelWhitespace(%q) = %v, want %v", tt.label, got, tt.want)
}
})
}
}

View file

@ -0,0 +1,97 @@
package doctor
import (
"context"
"fmt"
"strings"
"github.com/steveyegge/beads/cmd/bd/doctor/fix"
"github.com/steveyegge/beads/internal/storage/dolt"
)
// maxLabelExamples caps how many damaged labels the detail line names, so a
// database with thousands of them stays readable.
const maxLabelExamples = 5
// CheckLabelWhitespaceWithStore reports labels carrying whitespace damage
// (#5812): labels with leading/trailing whitespace, blank labels, and labels
// containing a space.
//
// bd normalizes labels on every filter path but historically did not on any
// write path, so `--labels 'a, b'` stored " b" — a label that can never match
// its own filter. Databases written by an older bd still carry that damage
// after the write paths are fixed, and nothing surfaces it: a filtered list
// that is silently short is indistinguishable from a complete one.
func CheckLabelWhitespaceWithStore(ss *SharedStore) DoctorCheck {
store := ss.Store()
if store == nil {
return DoctorCheck{
Name: "Label Whitespace",
Status: StatusOK,
Message: "No database yet",
}
}
return checkLabelWhitespaceWithStore(store)
}
func checkLabelWhitespaceWithStore(store *dolt.DoltStore) DoctorCheck {
anomalies, err := fix.ScanLabelWhitespace(context.Background(), store.UnderlyingDB())
if err != nil {
return DoctorCheck{
Name: "Label Whitespace",
Status: StatusWarning,
Message: "Unable to scan labels",
Detail: err.Error(),
}
}
if len(anomalies) == 0 {
return DoctorCheck{
Name: "Label Whitespace",
Status: StatusOK,
Message: "No labels carry whitespace damage",
}
}
var untrimmed, blank, internal int
var examples []string
for _, a := range anomalies {
untrimmed += len(a.Untrimmed)
blank += len(a.Blank)
internal += len(a.Internal)
for _, group := range [][]fix.LabelRow{a.Untrimmed, a.Blank, a.Internal} {
for _, row := range group {
if len(examples) < maxLabelExamples {
examples = append(examples, fmt.Sprintf("%s: %q", row.IssueID, row.Label))
}
}
}
}
var parts []string
if untrimmed > 0 {
parts = append(parts, fmt.Sprintf("%d with leading/trailing whitespace", untrimmed))
}
if blank > 0 {
parts = append(parts, fmt.Sprintf("%d blank", blank))
}
if internal > 0 {
parts = append(parts, fmt.Sprintf("%d containing a space", internal))
}
detail := strings.Join(examples, "; ")
if total := untrimmed + blank + internal; total > len(examples) {
detail += fmt.Sprintf(" (+%d more)", total-len(examples))
}
// Deliberately not auto-fixable. Trimming a damaged label can collide with a
// correct label already on the same issue, and a label containing a space may
// have been meant — bd cannot tell "good first issue" from a missed comma.
// Both need a human.
return DoctorCheck{
Name: "Label Whitespace",
Status: StatusWarning,
Message: fmt.Sprintf("%s — these may not match the filters meant to find them", strings.Join(parts, ", ")),
Detail: detail,
Fix: "Repair with: bd update <id> --remove-label '<damaged>' --add-label <replacement>. A label containing a space is often a missed comma; bd now warns when one is written.",
}
}

View file

@ -501,6 +501,12 @@ func runLabelAdd(ctx context.Context, args []string) error {
return HandleErrorRespectJSON("'provides:' labels are reserved for cross-project capabilities. Hint: use 'bd ship %s' instead", strings.TrimPrefix(label, "provides:"))
}
}
// splitLabelArg already trims and drops empties, so this route never stored
// the untrimmed class. What it could not tell a caller is that
// `bd label add bd-1 'theme:a theme:b'` is ONE label — the same silent
// miscount #5812 is about, reached by a different command. Warning here
// keeps the whole CLI saying the same thing about the same input.
warnLabelsContainingWhitespace(labels)
issueIDs, err := resolveLabelIssueIDs(ctx, "add", issueIDs)
if err != nil {
return HandleErrorRespectJSON("%v", err)

View file

@ -0,0 +1,161 @@
package main
import (
"context"
"fmt"
"testing"
"github.com/spf13/cobra"
)
// Write paths must normalize labels the same way read paths already do.
//
// bd applies utils.NormalizeLabels (trim, drop empty, dedupe) to every label
// FILTER path (list, search, ready, orphans, count, workapi) but to no label
// WRITE path. The asymmetry means `--labels 'a, b'` stores " b" with a leading
// space, while `--label ' b'` on a filter is trimmed to "b" — so the stored
// label can never match its own filter and a filtered list is silently short.
func TestGatherCreateInputNormalizesLabels(t *testing.T) {
tests := []struct {
name string
args []string
want []string
}{
{
// The comma-space form most people type. pflag's CSV split keeps
// the leading space, and the split looks like it worked.
name: "comma space separated",
args: []string{"--labels", "theme:a, theme:b"},
want: []string{"theme:a", "theme:b"},
},
{
name: "surrounding whitespace trimmed",
args: []string{"--labels", " theme:a "},
want: []string{"theme:a"},
},
{
name: "empty elements dropped",
args: []string{"--labels", "theme:a,,theme:b"},
want: []string{"theme:a", "theme:b"},
},
{
name: "duplicates collapsed",
args: []string{"--labels", "theme:a,theme:a"},
want: []string{"theme:a"},
},
{
// --label is documented as an alias for --labels, so it must
// normalize identically rather than bypass the cleanup.
name: "label alias normalized",
args: []string{"--label", " theme:a , theme:b"},
want: []string{"theme:a", "theme:b"},
},
{
// The alias appends to --labels; dedupe must span both flags.
name: "alias and labels deduped together",
args: []string{"--labels", "theme:a", "--label", " theme:a"},
want: []string{"theme:a"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
args := append([]string{"--title", "Title"}, tt.args...)
cmd := newCreateFlagsCommand(t, args...)
in, err := gatherCreateInput(cmd, nil)
if err != nil {
t.Fatalf("gatherCreateInput: %v", err)
}
assertLabels(t, in.labels, tt.want)
})
}
}
// The update write paths carry the same gap on --add-label, --remove-label and
// --set-labels.
func TestGatherUpdateInputNormalizesLabels(t *testing.T) {
// gatherUpdateInput reads flags through Flags().Changed, which reports
// false for anything unregistered, so the three label flags are all this
// case needs. ctx is consulted only for --status validation.
cmd := &cobra.Command{Use: "update"}
cmd.Flags().StringSlice("add-label", nil, "Add labels (repeatable)")
cmd.Flags().StringSlice("remove-label", nil, "Remove labels (repeatable)")
cmd.Flags().StringSlice("set-labels", nil, "Set labels, replacing all existing (repeatable)")
args := []string{
"--add-label", "theme:a, theme:b",
"--remove-label", " theme:c ",
"--set-labels", "theme:d,,theme:d",
}
if err := cmd.ParseFlags(args); err != nil {
t.Fatalf("parse update flags: %v", err)
}
in, err := gatherUpdateInput(context.Background(), cmd)
if err != nil {
t.Fatalf("gatherUpdateInput: %v", err)
}
assertLabels(t, in.addLabels, []string{"theme:a", "theme:b"})
assertLabels(t, in.removeLabels, []string{"theme:c"})
if in.setLabels == nil {
t.Fatal("expected --set-labels to be captured")
}
assertLabels(t, *in.setLabels, []string{"theme:d"})
}
// `bd tag` calls itself "Shorthand for 'bd update <id> --add-label <label>'",
// so it must normalize identically. It took the positional verbatim, which made
// it the one CLI label write that could still store an unfilterable label.
//
// normalizeLabelForTag is called before the direct/proxied route split, so one
// test covers both routes.
func TestNormalizeLabelForTag(t *testing.T) {
for _, tt := range []struct {
name string
raw string
want string
}{
{"leading space trimmed", " theme:a", "theme:a"},
{"surrounding whitespace trimmed", " theme:a\t", "theme:a"},
{"already clean is untouched", "theme:a", "theme:a"},
// A label containing a space is legitimate and is stored as asked;
// warnLabelsContainingWhitespace is what flags it.
{"internal space preserved", "good first issue", "good first issue"},
} {
t.Run(tt.name, func(t *testing.T) {
got, err := normalizeLabelForTag(tt.raw)
if err != nil {
t.Fatalf("normalizeLabelForTag(%q): %v", tt.raw, err)
}
if got != tt.want {
t.Fatalf("normalizeLabelForTag(%q) = %q, want %q", tt.raw, got, tt.want)
}
})
}
// The plural flags can drop an empty element and still honor the rest of
// the request. `bd tag` has one label to add, so dropping it would report
// success having written nothing.
for _, raw := range []string{"", " ", "\t"} {
t.Run("rejects empty "+fmt.Sprintf("%q", raw), func(t *testing.T) {
if _, err := normalizeLabelForTag(raw); err == nil {
t.Fatalf("normalizeLabelForTag(%q) = nil error, want a refusal", raw)
}
})
}
}
func assertLabels(t *testing.T, got, want []string) {
t.Helper()
if len(got) != len(want) {
t.Fatalf("labels = %q, want %q", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("labels = %q, want %q", got, want)
}
}
}

View file

@ -0,0 +1,51 @@
package main
import (
"fmt"
"os"
"strings"
"unicode"
"github.com/steveyegge/beads/internal/debug"
"github.com/steveyegge/beads/internal/ui"
)
// warnLabelsContainingWhitespace warns when a label being written contains a
// space, which is almost always a comma that was meant and missed (#5812).
//
// It is a WARNING and not an error, because a label containing a space is a
// legitimate thing to ask for and the shell already has the vocabulary to ask:
// `--labels 'one two'`, `--labels "one two"` and `--labels one\ two` all send
// one argument, exactly as they do for a filename containing a space. bd honors
// that boundary rather than re-splitting it — a caller who quoted or escaped
// has already said where the word ends, and overriding that would make labels
// the one place on the command line where quoting does not mean what it means
// everywhere else.
//
// What that leaves is the case the quoting cannot distinguish: someone typing
// `--labels 'theme:a theme:b'` who meant two labels gets one, silently. This is
// the whole failure mode behind #5812 — 150 corrupt rows across 111 issues,
// found months later only because theme counts failed to reconcile. A line on
// stderr is enough to catch it at the keystroke, and costs the deliberate user
// nothing but a line they can silence with --quiet.
//
// Deliberately not called for --remove-label: removing a space-containing label
// is how the damage gets repaired, and warning on the repair is noise.
func warnLabelsContainingWhitespace(labels []string) {
if debug.IsQuiet() {
return
}
var flagged []string
for _, l := range labels {
if strings.ContainsFunc(l, unicode.IsSpace) {
flagged = append(flagged, l)
}
}
if len(flagged) == 0 {
return
}
for _, l := range flagged {
fmt.Fprintf(os.Stderr, "%s Stored %q as ONE label — it contains a space.\n", ui.RenderWarn("⚠"), l)
}
fmt.Fprintf(os.Stderr, " If you meant several labels, separate them with commas (a,b) or repeat the flag.\n")
}

View file

@ -0,0 +1,96 @@
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)
}
}

View file

@ -149,10 +149,9 @@ func runNoteProxiedServer(ctx context.Context, id, noteText string) error {
// issueops.Reader.Get supplies the issue the template guard needs — the roles
// have no opinion about templates, and the direct route refuses one — and the
// role takes an exact id by contract, which Get's issue-then-wisp lookup is.
func runTagProxiedServer(ctx context.Context, args []string) error {
id := args[0]
label := args[1]
// The label arrives already normalized: tag.go does that before choosing a
// route, so this path and the direct one cannot disagree about what was stored.
func runTagProxiedServer(ctx context.Context, id, label string) error {
reader, err := openIssueReader()
if err != nil {
return HandleErrorRespectJSON("tag %s: %v", id, err)

View file

@ -9,6 +9,7 @@ import (
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/utils"
"github.com/steveyegge/beads/internal/validation"
)
@ -49,6 +50,8 @@ Example:
priorityStr, _ := cmd.Flags().GetString("priority")
issueType, _ := cmd.Flags().GetString("type")
labels, _ := cmd.Flags().GetStringSlice("labels")
labels = utils.NormalizeLabels(labels)
warnLabelsContainingWhitespace(labels)
parentID, _ := cmd.Flags().GetString("parent")
priority, err := validation.ValidatePriority(priorityStr)

View file

@ -10,6 +10,7 @@ import (
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/storage/uow"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/utils"
"github.com/steveyegge/beads/internal/validation"
)
@ -19,6 +20,8 @@ func runQuickProxiedServer(cmd *cobra.Command, ctx context.Context, args []strin
priorityStr, _ := cmd.Flags().GetString("priority")
issueType, _ := cmd.Flags().GetString("type")
labels, _ := cmd.Flags().GetStringSlice("labels")
labels = utils.NormalizeLabels(labels)
warnLabelsContainingWhitespace(labels)
parentID, _ := cmd.Flags().GetString("parent")
priority, err := validation.ValidatePriority(priorityStr)

View file

@ -6,6 +6,7 @@ import (
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/utils"
)
var tagCmd = &cobra.Command{
@ -32,12 +33,16 @@ Examples:
}
}()
label, err := normalizeLabelForTag(args[1])
if err != nil {
return HandleErrorRespectJSON("tag %s: %v", args[0], err)
}
if usesProxiedServer() {
return runTagProxiedServer(rootCtx, args)
return runTagProxiedServer(rootCtx, args[0], label)
}
id := args[0]
label := args[1]
ctx := rootCtx
@ -90,6 +95,29 @@ Examples:
},
}
// normalizeLabelForTag applies to `bd tag` the normalization every other CLI
// label write performs, and it is deliberately called BEFORE the route split so
// the direct and proxied paths cannot diverge on it.
//
// `bd tag` describes itself as "Shorthand for 'bd update <id> --add-label
// <label>'". Without this it was not: update trims and warns, tag stored the
// positional verbatim, so `bd tag bd-1 ' theme:a'` wrote a label that no
// `--label theme:a` filter can ever match — the exact unfilterable class #5812
// is about, written by the command whose help text promises equivalence.
//
// A label that is only whitespace is rejected rather than silently dropped.
// The plural flags can drop an empty element and still honor the rest of the
// request; `bd tag` has exactly one label to add, so dropping it would leave a
// command that reported success having done nothing.
func normalizeLabelForTag(raw string) (string, error) {
labels := utils.NormalizeLabels([]string{raw})
if len(labels) == 0 {
return "", fmt.Errorf("label %q is empty after trimming whitespace", raw)
}
warnLabelsContainingWhitespace(labels)
return labels[0], nil
}
func init() {
tagCmd.ValidArgsFunction = issueIDCompletion
rootCmd.AddCommand(tagCmd)

View file

@ -253,15 +253,19 @@ pointless).`,
}
if cmd.Flags().Changed("add-label") {
addLabels, _ := cmd.Flags().GetStringSlice("add-label")
updates["add_labels"] = addLabels
added := utils.NormalizeLabels(addLabels)
warnLabelsContainingWhitespace(added)
updates["add_labels"] = added
}
if cmd.Flags().Changed("remove-label") {
removeLabels, _ := cmd.Flags().GetStringSlice("remove-label")
updates["remove_labels"] = removeLabels
updates["remove_labels"] = utils.NormalizeLabels(removeLabels)
}
if cmd.Flags().Changed("set-labels") {
setLabels, _ := cmd.Flags().GetStringSlice("set-labels")
updates["set_labels"] = setLabels
set := utils.NormalizeLabels(setLabels)
warnLabelsContainingWhitespace(set)
updates["set_labels"] = set
}
if cmd.Flags().Changed("parent") {
parent, _ := cmd.Flags().GetString("parent")

View file

@ -140,14 +140,25 @@ func gatherUpdateInput(ctx context.Context, cmd *cobra.Command) (*updateInput, e
issueType, _ := cmd.Flags().GetString("type")
in.fields["issue_type"] = utils.NormalizeIssueType(issueType)
}
// Normalize on the way in, as the read paths do. --remove-label matters as
// much as the additive flags: an untrimmed " theme:a" would fail to match
// the stored label and silently remove nothing.
if cmd.Flags().Changed("add-label") {
in.addLabels, _ = cmd.Flags().GetStringSlice("add-label")
addLabels, _ := cmd.Flags().GetStringSlice("add-label")
in.addLabels = utils.NormalizeLabels(addLabels)
warnLabelsContainingWhitespace(in.addLabels)
}
if cmd.Flags().Changed("remove-label") {
in.removeLabels, _ = cmd.Flags().GetStringSlice("remove-label")
removeLabels, _ := cmd.Flags().GetStringSlice("remove-label")
in.removeLabels = utils.NormalizeLabels(removeLabels)
}
if cmd.Flags().Changed("set-labels") {
labels, _ := cmd.Flags().GetStringSlice("set-labels")
// Preserve the explicit "clear all labels" signal: --set-labels ''
// normalizes to empty, and a nil slice here would still be a non-nil
// pointer to an empty slice, which is the clear instruction.
labels = utils.NormalizeLabels(labels)
warnLabelsContainingWhitespace(labels)
in.setLabels = &labels
}
if cmd.Flags().Changed("parent") {

View file

@ -25,7 +25,7 @@ Labels provide flexible, multi-dimensional categorization for issues beyond the
## Quick Start
```bash
# Add labels when creating issues
# Add labels when creating issues (comma-separated)
bd create "Fix auth bug" -t bug -p 1 -l auth,backend,urgent
# Add labels to existing issues
@ -57,6 +57,53 @@ bd list --label-any frontend,backend
bd list --status open --priority 1 --label security
```
## Separating labels, and labels with spaces
Labels are separated by **commas**, or by repeating the flag:
```bash
bd create "Fix auth bug" -l auth,backend
bd create "Fix auth bug" -l auth -l backend
```
A space does **not** separate labels. bd honours the word boundaries your shell
already decided, exactly as it does for a filename containing a space — so all
three of these create the single label `good first issue`:
```bash
bd create "Starter task" -l 'good first issue'
bd create "Starter task" -l "good first issue"
bd create "Starter task" -l good\ first\ issue
```
Because that is also what a missed comma looks like, bd warns when it stores a
label containing a space:
```
⚠ Stored "auth backend" as ONE label — it contains a space.
If you meant several labels, separate them with commas (a,b) or repeat the flag.
```
The warning is advice, not an error — the label is stored as asked. Silence it
with `--quiet`.
To find labels already stored this way in an existing database, run `bd doctor`
and look at the `Label Whitespace` check. It reports and never fails the run, so
a database with legacy damage still exits 0. Note that `bd doctor` is not yet
supported in embedded mode (GH#3794 enables embedded checks one at a time), so
this check currently reaches classic and server-mode databases only.
**Import and batch ingest are deliberately left alone.** They do not normalize,
do not warn, and this is intended rather than an oversight: an import must round
trip — what was exported is what is restored — and quietly rewriting a label on
the way in would make a JSONL file and the database it came from disagree.
Repair is a separate, deliberate act, which is what the `bd doctor` check above
is for.
Note that an *unquoted* space is not a label separator either — it ends the
flag's value, so `-l auth backend` leaves `backend` as a stray positional
argument and the command fails.
## Common Label Patterns
### 1. Technical Component Labels