beads/docs/core-concepts/labels.md
Marco Del Pin 63d8cc2522
cmd/bd: bd label rename <old> <new> (stacked on #6007) (#6009)
* storage: add RenameLabel primitive with merge semantics

Add a storage primitive that renames a label across every issue and
wisp that carries it, in one transaction per store. An issue that
already carries the new label is a merge - the stale old-label row is
dropped rather than raising a duplicate-key error - and the call
reports renamed/merged counts plus every touched id.

- internal/storage/issueops/labels.go: RenameLabelInTx sweeps the
  labels and wisp_labels tables (INSERT IGNORE then DELETE, so the
  merge never errors), emitting one EventLabelRenamed plus the usual
  full-snapshot journal row per touched issue/wisp, matching
  AddLabelInTx/RemoveLabelInTx's journal shape. A single batch event
  was considered and rejected: the journal-completeness guard requires
  every touched row to carry its own journal entry.
- internal/storage/storage.go: RenameLabel added to the Storage
  interface, next to AddLabel/RemoveLabel/GetIssuesByLabel.
- internal/storage/dolt, internal/storage/embeddeddolt: direct
  implementations. The dolt commit targets the fixed events/labels
  table pair; doltAddAndCommit's own HasStagedChanges guard skips it
  when the rename touched wisps only (wisp tables are dolt-ignored,
  same as AddLabel/RemoveLabel).
- internal/storage/hook_decorator.go: HookFiringStore.RenameLabel
  fires on_update per touched issue, matching AddLabel/RemoveLabel.
- internal/types/types.go: new EventLabelRenamed event type. Unlike
  EventLabelAdded/EventLabelRemoved, one rename produces exactly one
  of these per touched row, never a paired add+remove.
- internal/jira/tracker_test.go: mock stub for the new interface
  method.

Tests: internal/storage/dolt/label_rename_test.go, against a real
dolt-sql-server container - basic rename, merge, wisp sweep,
zero-carrier no-op, over-length refusal, event assertion. All green.
Also verified TestEveryBeadMutatorJournalsOrIsExempt still passes.

Gates: gofmt clean, go vet ./... clean, CGO_ENABLED=0 go test -tags
gms_pure_go -c -o /dev/null ./cmd/bd clean, go build ./... clean.

* storage: refuse RenameLabel(x, x) instead of wiping the label

RenameLabelInTx's merge branch treats every carrier of oldLabel as
already carrying newLabel when the two names collide (they are the
same string): the batched INSERT IGNORE no-ops on every row, and the
unconditional DELETE FROM <table> WHERE label = ? that follows then
removes every row for that label plane. A self-rename silently wiped
the label instead of leaving it untouched.

Reject oldLabel == newLabel (compared after trimming, case-sensitive)
before any write, returning the new ErrRenameLabelSameName. Verified
red->green: TestRenameLabel_SameNameRefused and
TestRenameLabel_SameNameAfterTrimRefused both fail (GetLabels returns
[] on both the labels and wisp_labels planes) against the pre-fix
code, and pass against the fix. Full TestRenameLabel* suite in
internal/storage/dolt still green.

* telemetry: instrument InstrumentedStorage.RenameLabel

AddLabel and RemoveLabel already get OTel spans/metrics through
InstrumentedStorage; RenameLabel had no override and so fell through
to the embedded storage.DoltStorage passthrough, invisible to
storage.* tracing. Add the override, mirroring the AddLabel/RemoveLabel
shape: span attributes for the old/new label pair (bd.label.old,
bd.label.new, matching the existing bd.dep.from/bd.dep.to pairing
convention), and on success a bd.result.count / bd.merged.count pair
following the SearchIssues-style "set result attributes after a
successful call" pattern already used elsewhere in this file.

* storage: document the O(N) round-trip cost of RenameLabelInTx's event loop

renameLabelInPlane's per-issue loop (InsertDerivedEvent + RecordEventInTx)
is O(len(oldIDs)) SQL round trips inside one transaction, up to four per
touched issue. On a huge label population that lengthens the transaction
and raises the odds an optimistic-concurrency retry has to redo the whole
rename from scratch.

No batching added: InsertDerivedEvent's dedup SELECT is a real
cross-replica convergence check (Protocol v0.1 C2.3), not a redundant one
this transaction could skip, and no batch primitive for this shape exists
anywhere in this package - building one here would be new shared
infrastructure grown for a single caller. AddLabelInTx/RemoveLabelInTx
already pay the identical per-call cost for their one issue; this loop is
that cost repeated once per touched issue. Documented inline as a
disclosed limitation rather than silently left unremarked.

* bda-lbjv: derive rename merge count from rows-affected, not a prior read

renameLabelInPlane computed merged from a snapshot SELECT of newLabel's
carriers taken before the INSERT IGNORE - a check-then-insert whose
result is used. A concurrent AddLabel(issue, newLabel) committing between
snapshot and insert made the reported count schedule-dependent while the
stored data stayed correct (cross-model finding: the Opus panel cleared
A1, codex flipped it to NOT-SAFE on exactly this line).

Now the count is a measurement: INSERT IGNORE reports one affected row
per id actually inserted, so merged = len(oldIDs) - inserted, and the
newLabel pre-read is gone entirely.

Tests: sqlmock scripts the racing schedule (insert sees a row the
snapshot read could not); mutation control confirms the old
implementation fails the new test. Full issueops package + live-store
TestRenameLabel_* green.

* bda-c77s: first-party coverage for EmbeddedDoltStore.RenameLabel

The embedded impl had zero tests while DoltStore.RenameLabel carries a
dedicated suite; AddLabel/RemoveLabel both have parallel embedded
coverage by convention. Four wiring cases (basic, merge, zero-carrier
no-op, same-name refusal) - the deep semantics stay pinned by the shared
issueops suite and the dolt-side tests against the same implementation.

BEADS_TEST_EMBEDDED_DOLT=1: 5 RUN, all green, 2.8s.

* storage: scope the rename delete to the ids the sweep captured

An unrestricted DELETE ... WHERE label = ? makes the sweep's blast radius
engine-dependent: under current-read DELETE semantics a row a concurrent
AddLabel(oldLabel) committed after this transaction's snapshot would be
removed without ever being renamed, counted or journaled. Restricting the
delete to the captured ids touches exactly the rows the INSERT IGNORE above
accounted for on every engine; a concurrent add outside the snapshot now
deterministically SURVIVES the rename - the same observable state as that
add landing after the rename committed, which is the only order-independent
reading of the race.

sqlmock WithArgs pins the id-scoped statement shape; the embedded-Dolt
lifecycle set stays green (5/5).

* cmd/bd: add `bd label rename <old> <new>` with dry-run preview

Wire the storage.RenameLabel primitive (previous commit) into a CLI
command that renames a label everywhere it appears in one call instead
of a per-issue add-then-remove loop.

- cmd/bd/label.go: `bd label rename <old> <new> [--dry-run]`.
  validateLabelRename refuses empty/identical labels and the
  'provides:' reserved prefix before any store call - it is a pure
  function so those rules are testable without a store. --dry-run
  previews the blast radius (count plus the first issues) read-only,
  via a path kept separate from the write path so it can never reach a
  transaction.
- cmd/bd/label_proxied_server.go: the proxied-server route composes
  the existing per-issue LabelUseCase.AddLabel/RemoveLabel (and wisp
  twins) in one uow.RunTx, the same fan-out shape label propagate
  already uses on this route. It journals as an add/remove pair per
  issue rather than the direct route's single EventLabelRenamed,
  because LabelUseCase has no rename-shaped event; the rename
  semantics (merge-on-collision, honest zero-carrier no-op, dry-run
  preview) are identical on both routes.
- docs/core-concepts/labels.md: documents rename, dry-run, and merge
  semantics under Label Management.

Tests: cmd/bd/label_rename_test.go (pure argument-validation table
test, no store needed) plus new subtests in
cmd/bd/label_embedded_test.go covering the full CLI path - basic
rename, merge, dry-run writes nothing, zero-carrier no-op,
identical/empty/reserved-prefix refusals. All green.

Gates: gofmt clean, go vet ./... clean, CGO_ENABLED=0 go test -tags
gms_pure_go -c -o /dev/null ./cmd/bd clean, go build ./... clean.

* cmd/bd,domain: emit label_renamed on the proxied route, not add+remove

runLabelRenameProxiedServer used to fan a rename out into a per-issue
AddLabel-then-RemoveLabel pair, journaling label_added/label_removed
instead of one EventLabelRenamed - a divergence from the direct
DoltStore/EmbeddedDoltStore route the upstream reviewer has already
rejected for another PR touching the same class of proxied/direct
split.

Add domain.LabelUseCase.RenameLabel and domain.LabelSQLRepository.
RenameLabel. The repository method delegates straight to
issueops.RenameLabelInTx (r.runner satisfies issueops.DBTX
structurally), so the proxied route is not merely the same SQL SHAPE
as the direct one, it is the same function: identical merge semantics,
the same ErrRenameLabelSameName refusal, and one EventLabelRenamed per
touched issue. runLabelRenameProxiedServer now just calls
uw.LabelUseCase().RenameLabel(...) inside its existing uow.RunTx.

Declare recordingLabelUC.RenameLabel so the notifying unit of work
records one update per touched issue/wisp (mirroring
HookFiringStore.RenameLabel on the direct route) instead of silently
recording nothing through the embedded interface - caught by the
existing structural parity guard, TestRecordingLabelUseCaseCoversItsSurface,
which fails on any domain.LabelUseCase method neither declared on
recordingLabelUC nor exempted with a reason.

Tests, verified red->green:
  - internal/storage/domain/db: TestLabelUseCase/RenameLabel adds 5
    subtests. EmitsOneRenamedEventPerIssue is the direct regression
    test - reverting RenameLabel to a simulated add-then-remove
    fan-out reproduces exactly the pre-fix event counts (renamed=0,
    added=2, removed=1) it now asserts against (renamed=1, added=1,
    removed=0).
  - cmd/bd/label_proxied_integration_test.go: new "rename" subtest
    exercises `bd label rename` end to end through the real proxied
    server and asserts the same label_renamed/added/removed counts
    directly against the events table.
  - internal/storage/uow: TestRecordingLabelUseCaseCoversItsSurface
    goes red (RenameLabel inherited, records nothing) without the
    recordingLabelUC override and green with it.

Full internal/storage/uow suite (287s) and the new domain/db and
cmd/bd tests all pass.

* cmd/bd: record commandDidWrite before the rename error return

runLabelRename read renamed>0 into commandDidWrite only after the
`if err != nil` early return, so a rename whose SQL side committed but
whose store call also returned an error - the Dolt publication step
failing after the working-set write landed - never marked the command
as having written. The caller's deferred auto-commit would then skip
creating a Dolt commit for a write that, on disk, actually happened.

Move the commandDidWrite.Store(true) check ahead of the error check,
matching applyLabelEdit's existing per-issue marking a few lines above
in the same file.

New test: TestRunLabelRename_CommandDidWriteSetBeforeErrorReturn wraps
a real *dolt.DoltStore in a spy whose RenameLabel reports a publish
failure (renamed>0, err!=nil) after delegating to the real rename, and
asserts commandDidWrite is set despite the returned error. Verified
red->green: reverting the ordering reproduces the exact failure this
guards against.

* bda-bnid: nolint:forbidigo on proxied bulk rename call

The route delegates to domain.LabelUseCase.RenameLabel deliberately: one
EventLabelRenamed per issue with identical merge semantics to the direct
route. Patch.Labels (the lint's suggested remedy) would reintroduce the
per-issue add/remove event divergence this delegation replaced. Matches
the file's own convention (4 sibling nolints, same shape).

Negative control: without the nolint golangci-lint forbidigo reports
exactly this line; with it, 0 issues.

* cmd/bd: address review on label rename (CHANGELOG entry, dry-run caveat, partial-failure count)

Two blocking items from review (bee-ghosttrack, PR #6009):

- Add the CHANGELOG entry for `bd label rename`, in the house voice used
  by the neighboring bd-label entries (bold lead sentence, PR link, dense
  explanatory prose on the merge/dry-run/partial-failure contract).
- The `--dry-run` merged count is a plain snapshot intersection of two
  independent reads - exactly the check-then-count shape
  renameLabelInPlane's own comment documents rejecting for the write
  path, because it is schedule-dependent under a concurrent
  AddLabel/RemoveLabel. That is an acceptable estimate for a preview, but
  nothing said so: the command's Long text, the --dry-run flag help, and
  an inline comment at the computation site now all say the number is
  not authoritative.

One non-blocking nit fixed (the other - hydrating full issue rows in the
direct dry-run just to print 10 titles - is left alone; see below):

- On a partial rename failure (renamed>0, err!=nil - e.g. a Dolt
  publication failure after the SQL side already committed) the command
  now reports how many issues were renamed and merged before the
  failure, instead of only the error. Mirrors the existing shape in
  conflicts.go's ResolveConflictRows handling ("resolved %d of %d
  conflict(s) before failing").

Left alone, and why: the GetIssuesByIDs-hydration nit. GetIssuesByLabel
hydrates every matching issue via GetIssuesByIDs on both the old-label
and new-label reads, which is wasteful on a label carrying 10k issues
when the text-mode preview only prints 10. But the JSON-mode contract
already returns every matching issue's id+title (not capped at the
preview limit), so avoiding hydration only helps the text-mode path and
would branch the two output modes apart for a marginal win on an
uncommon case (a rename dry-run over a 10k-issue label). Not clean
enough to do inline without its own test coverage and a decision about
whether the JSON contract should change too - flagged in the review as
skippable, so skipping it here.

Verification:
- go build ./... - clean
- go vet ./cmd/bd/... - clean
- gofmt -l cmd/bd/label.go - clean
- go test ./cmd/bd/... -run 'Label|LabelRename' - all pass
- BEADS_TEST_EMBEDDED_DOLT=1 go test ./cmd/bd/... -run 'TestEmbeddedLabel$' -v
  - all pass, including label_rename_basic/merge/dry_run_writes_nothing
- BEADS_TEST_PROXIED_SERVER=1 BEADS_TEST_EMBEDDED_DOLT=1 go test ./cmd/bd/...
  -run TestProxiedServerLabel -v - all pass, including the "rename" subtest
- BEADS_TEST_EMBEDDED_DOLT=1 go test ./internal/storage/issueops/... -run Rename -v
- BEADS_TEST_EMBEDDED_DOLT=1 go test ./internal/storage/dolt/... -run Rename -v (live dolt-sql-server)
- BEADS_TEST_EMBEDDED_DOLT=1 go test ./internal/storage/embeddeddolt/... -run Rename -v

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

* cmd/bd: report an upper bound on a failed rename, not a landed count

The partial-failure message asserted that renamed>0 means the SQL side committed. On both routes the counts are assigned inside the transaction closure (label_proxied_server.go RunTx, dolt/labels.go withRetryTx), so a Commit failure or retry exhaustion returns them holding the rolled-back attempt numbers - nothing landed, and the user read 'renamed 6 issue(s) before failing'. Retry exhaustion under a busy server is the likely failure for a bulk rename, so it misreported exactly when it fired. Now reports an upper bound. commandDidWrite keeps the same premise deliberately: it is fail-safe in the other direction.

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

* cmd/bd: pin the partial-failure wording, and hedge the merged count too

Round-3 review: the r2 correction rode unpinned. Nothing in the suite drives
a failing rename with renamed > 0, so the whole TestEmbeddedLabel suite passed
with the hunk reverted - the fix was unfalsifiable, which is the same defect
class the correction itself was about.

Extracts the sentence into labelRenamePartialFailureMessage, a pure function a
test can assert on without inducing a mid-transaction failure, and pins it:
the hedged phrasings must be present AND the two pre-correction phrasings must
be absent. Mutation-checked - restoring the old wording turns it red on three
assertions.

Also the round-3 nit: (%d merged) was the one unhedged clause in a hedged
sentence. It now reads (of which up to %d merged), so no number in the message
asserts a write that may never have landed.

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

* docs: retire the landed-count premise from the CHANGELOG too

Round-4 review, MAJOR: the code retracted a premise and the CHANGELOG kept
publishing it. The entry still said a partway failure 'reports how many issues
were renamed and merged before the failure' - a landed count - while
labelRenamePartialFailureMessage had already become an upper bound.

The sentence carried the premise TWICE and the review named one: besides the
count, its parenthetical offered 'a Dolt publication failure after the SQL side
already committed' as the case, when the whole point of the correction is that
renamed > 0 cannot distinguish that from a rollback. Rewrote both halves: the
bound is explicit, and the two failure shapes are named as indistinguishable
from the count alone.

Also round-4 MINOR: the helper had been inserted between reportLabelRename's
doc comment and its func, so the comment headed the wrong function and
reportLabelRename was left undocumented. Moved back down.

Not done, deliberately: the round-4 NIT that the pin covers the helper and not
the call site. It is marked 'noting, not asking', and an unrequested fix is the
one that ships a defect - this PR already demonstrated that.

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

* CHANGELOG: move this PR's entry under [Unreleased]

The 1.3.0 cut renamed the old [Unreleased] block, so these lines
merged cleanly into a released section (gastownhall/beads#6643).
Moved 31 line(s); the code is unchanged.

* cmd/bd: register label rename in the proxied capability registry

TestProxyCapabilityRegistryCoversCommandTree requires every command path to
carry a proxied-server row. label rename has a proxied route (RunE hands the
rename to runLabelRenameProxiedServer and the --dry-run preview to a proxied
read UOW), so it joins its label siblings in proxyPermittedPaths.

* storage: mint a version for every bead a label rename touches

TestEveryBeadMutatorMintsOrIsExempt (added with #6650) fails on this PR:
RenameLabelInTx writes the labels table but never reached
RecordVersionInTx. A rename changes the label set - part of the durable
snapshot - of every issue that carried oldLabel, whether it gained
newLabel or already had it (merge), so each touched issue now mints one
version row, the same gate AddLabelInTx/RemoveLabelInTx draw on a row
that landed. RecordVersionInTx is already a no-op for wisps and when
versioned history is disabled, and a rename nobody carries touches no
id, so the no-op shape mints nothing.

TestRenameLabelMintsOneVersionPerTouchedBead is the runtime twin of the
static guard: plain rename +1, merge +1, untouched bead +0, a second
rename with no carriers +0, current_revision equal to the row count.

* build(bazel): list this PR's six new test files in their go_test srcs

Generated-artifact drift repair, produced by the repository's own command
(`make bazel-sync`) and inspected before committing, not hand-written.

The PR adds six `_test.go` files and none were listed in their package's
`go_test` srcs, so Bazel compiled each of those packages' test targets without
them - green by omission. That was invisible on the pre-merge head because its
CI predates the Bazel lanes entirely (zero `Bazel /` rows). This merge brings in
e1b2e79484 (#6941), which makes those lanes feed the required gate, so the
omission would now surface as a real red.

Purely additive: 6 insertions, 0 deletions, `go_test` srcs only. No `go_library`
srcs change is needed because every added file is a test, which is also why this
cannot break the build the way a missing production source would.

Verified: `make bazel-sync` is now a no-op against this tree (empty porcelain),
and `bazel build //cmd/bd/... //internal/storage/... //internal/types/...
//internal/telemetry/...` completes successfully - 3429 actions, 0 errors.

---------

Co-authored-by: Marco Del Pin <marco@omniaevo.it>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-29 17:02:35 -07:00

22 KiB

title description
Labels Flexible tagging for cross-cutting concerns, filtering, and caching operational state on issues

Labels provide flexible, multi-dimensional categorization for issues beyond the structured fields (status, priority, type). Use labels for cross-cutting concerns, technical metadata, and contextual tagging without schema changes.

Design Philosophy

When to use labels vs. structured fields:

  • Structured fields (status, priority, type) → Core workflow state

    • Status: Where the issue is in the workflow (open, in_progress, blocked, closed)
    • Priority: How urgent (0-4)
    • Type: What kind of work (bug, feature, task, epic, chore)
  • Labels → Everything else

    • Technical metadata (backend, frontend, api, database)
    • Domain/scope (auth, payments, search, analytics)
    • Effort estimates (small, medium, large)
    • Quality gates (needs-review, needs-tests, breaking-change)
    • Team/ownership (team-infra, team-product)
    • Release tracking (v1.0, v2.0, backport-candidate)

Quick Start

# 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
bd label add bd-42 security
bd label add bd-42 breaking-change

# Add multiple labels at once (comma-separated, no spaces around commas)
bd label add bd-42 security,breaking-change

# List issue labels
bd label list bd-42

# Remove a label
bd label remove bd-42 urgent

# Remove multiple labels at once
bd label remove bd-42 urgent,needs-review

# List all labels in use
bd label list-all

# Filter by labels (AND - must have ALL)
bd list --label backend,auth

# Filter by labels (OR - must have AT LEAST ONE)
bd list --label-any frontend,backend

# Combine filters
bd list --status open --priority 1 --label security

Separating labels, and labels with spaces

Labels are separated by commas, or by repeating the flag:

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:

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

Identify which part of the system:

backend
frontend
api
database
infrastructure
cli
ui
mobile

Example:

bd create "Add GraphQL endpoint" -t feature -p 2 -l backend,api
bd create "Update login form" -t task -p 2 -l frontend,auth,ui

2. Domain/Feature Area

Group by business domain:

auth
payments
search
analytics
billing
notifications
reporting
admin

Example:

bd list --label payments --status open  # All open payment issues
bd list --label-any auth,security       # Security-related work

3. Size/Effort Estimates

Quick effort indicators:

small     # < 1 day
medium    # 1-3 days
large     # > 3 days

Interaction with label inheritance: bd create --parent copies the parent's labels onto the child by default (see GH#2100). If the epic carries a size marker (e.g. large or sp:13) and children have their own estimates, every child will also inherit the epic's size label — so bd list -l large returns the whole tree, not just epic-scale work. For per-child size labels, pass --no-inherit-labels when creating children (team/domain labels you do want shared can still be added explicitly).

Example:

# Find small quick wins
bd ready --json | jq '.[] | select(.labels[] == "small")'

# Child keeps its own size label without inheriting the epic's
bd create "Implement auth endpoints" -p 1 --parent bd-a3f8e9 --no-inherit-labels -l small

4. Quality Gates

Track what's needed before closing:

needs-review
needs-tests
needs-docs
breaking-change

Example:

bd label add bd-42 needs-review
bd list --label needs-review --status in_progress

5. Release Management

Track release targeting:

v1.0
v2.0
backport-candidate
release-blocker

Example:

bd list --label v1.0 --status open    # What's left for v1.0?
bd label add bd-42 release-blocker

6. Team/Ownership

Indicate ownership or interest:

team-infra
team-product
team-mobile
needs-triage
help-wanted

Example:

bd list --assignee alice --label team-infra
bd create "Memory leak in cache" -t bug -p 1 -l team-infra,help-wanted

7. Special Markers

Process or workflow flags:

auto-generated     # Created by automation
discovered-from    # Found during other work (also a dep type)
technical-debt
good-first-issue
duplicate
wontfix

Example:

bd create "TODO: Refactor parser" -t chore -p 3 -l technical-debt,auto-generated

Filtering by Labels

AND Filtering (--label)

All specified labels must be present:

# Issues that are BOTH backend AND urgent
bd list --label backend,urgent

# Open bugs that need review AND tests
bd list --status open --type bug --label needs-review,needs-tests

OR Filtering (--label-any)

At least one specified label must be present:

# Issues in frontend OR backend
bd list --label-any frontend,backend

# Security or auth related
bd list --label-any security,auth

Combining AND/OR

Mix both filters for complex queries:

# Backend issues that are EITHER urgent OR a blocker
bd list --label backend --label-any urgent,release-blocker

# Frontend work that needs BOTH review and tests, but in any component
bd list --label needs-review,needs-tests --label-any frontend,ui,mobile

Workflow Examples

Triage Workflow

# Create untriaged issue
bd create "Crash on login" -t bug -p 1 -l needs-triage

# During triage, add context
bd label add bd-42 auth
bd label add bd-42 backend
bd label add bd-42 urgent
bd label remove bd-42 needs-triage

# Find untriaged issues
bd list --label needs-triage

Quality Gate Workflow

# Start work
bd update bd-42 --claim

# Mark quality requirements
bd label add bd-42 needs-tests
bd label add bd-42 needs-docs

# Before closing, verify
bd label list bd-42
# ... write tests and docs ...
bd label remove bd-42 needs-tests
bd label remove bd-42 needs-docs

# Close when gates satisfied
bd close bd-42

Release Planning

# Tag issues for v1.0
bd label add bd-42 v1.0
bd label add bd-43 v1.0
bd label add bd-44 v1.0

# Track v1.0 progress
bd list --label v1.0 --status closed    # Done
bd list --label v1.0 --status open      # Remaining
bd stats  # Overall progress

# Mark critical items
bd label add bd-45 v1.0
bd label add bd-45 release-blocker

Component-Based Work Distribution

# Backend team picks up work
bd ready --json | jq '.[] | select(.labels[]? == "backend")'

# Frontend team finds small tasks
bd list --status open --label frontend,small

# Find help-wanted items for new contributors
bd list --label help-wanted,good-first-issue

Label Management

Listing Labels

# Labels on a specific issue
bd label list bd-42

# All labels in database with usage counts
bd label list-all

# JSON output for scripting
bd label list-all --json

Output:

[
  {"label": "auth", "count": 5},
  {"label": "backend", "count": 12},
  {"label": "frontend", "count": 8}
]

Renaming Labels

bd label rename fixes a label everywhere it appears, in one command, instead of a per-issue add-then-remove loop:

# Fix a typo or a taxonomy drift across the whole database
bd label rename Backend backend

# Preview the blast radius first - no writes, just a count and the first issues
bd label rename Backend backend --dry-run

If an issue already carries the new label, the rename doesn't error - it drops the stale old label and reports that issue as a merge:

Renamed label 'Backend' to 'backend': 6 issues (2 already had 'backend')

A label nothing carries renames to a clean no-op (No issues found with label 'Backend', exit 0). Rename sweeps both planes: durable issues and wisps.

Bulk Operations

Add labels in batch during creation:

bd create "Issue" -l label1,label2,label3

Script to add label to multiple issues:

# Add "needs-review" to all in_progress issues
bd list --status in_progress --json | jq -r '.[].id' | while read id; do
  bd label add "$id" needs-review
done

Remove label from multiple issues:

# Remove "urgent" from closed issues
bd list --status closed --label urgent --json | jq -r '.[].id' | while read id; do
  bd label remove "$id" urgent
done

Integration with Git Workflow

Labels are stored in the Dolt database and synced automatically with all issue data:

# Make changes
bd create "Fix bug" -l backend,urgent
bd label add bd-42 needs-review

# Changes are committed to Dolt history automatically
# Sync with remotes when ready:
bd dolt push

# After pulling changes:
bd dolt pull
bd list --label backend  # Fresh data including labels

Markdown Import/Export

Labels are preserved when importing from markdown:

# Fix Authentication Bug

### Type
bug

### Priority
1

### Labels
auth, backend, urgent, needs-review

### Description
Users can't log in after recent deployment.
bd create -f issue.md
# Creates issue with all four labels

Best Practices

1. Establish Conventions Early

Document your team's label taxonomy:

# Add to project README or CONTRIBUTING.md
- Use lowercase, hyphen-separated (e.g., `good-first-issue`)
- Prefix team labels (e.g., `team-infra`, `team-product`)
- Use consistent size labels (`small`, `medium`, `large`)

2. Don't Overuse Labels

Labels are flexible, but too many can cause confusion. Prefer:

  • 5-10 core technical labels (backend, frontend, api, etc.)
  • 3-5 domain labels per project
  • Standard process labels (needs-review, needs-tests)
  • Release labels as needed

3. Clean Up Unused Labels

Periodically review:

bd label list-all
# Remove obsolete labels from issues

Labels are for categorization, not free-text search:

  • ✅ Good: backend, auth, urgent
  • ❌ Bad: fix-the-login-bug, john-asked-for-this

5. Combine with Dependencies

Labels + dependencies = powerful organization:

# Epic with labeled subtasks
bd create "Auth system rewrite" -t epic -p 1 -l auth,v2.0
bd create "Implement JWT" -t task -p 1 -l auth,backend --deps parent-child:bd-42
bd create "Update login UI" -t task -p 1 -l auth,frontend --deps parent-child:bd-42

# Find all v2.0 auth work
bd list --label auth,v2.0

AI Agent Usage

Labels are especially useful for AI agents managing complex workflows:

# Auto-label discovered work
bd create "Found TODO in auth.go" -t task -p 2 -l auto-generated,technical-debt

# Filter for agent review
bd list --label needs-review --status in_progress --json

# Track automation metadata
bd label add bd-42 ai-generated
bd label add bd-42 needs-human-review

Example agent workflow:

# Agent discovers issues during refactor
bd create "Extract validateToken function" -t chore -p 2 \
  -l technical-debt,backend,auth,small \
  --deps discovered-from:bd-10

# Agent marks work for review
bd update bd-42 --claim
# ... agent does work ...
bd label add bd-42 needs-review
bd label add bd-42 ai-generated

# Human reviews and approves
bd label remove bd-42 needs-review
bd label add bd-42 approved
bd close bd-42

Labels as State Cache

Labels can cache operational state for fast queries, enabling patterns where beads track both immutable history (events) and current state (labels).

The Pattern

Convention: <dimension>:<value>

Examples:

  • patrol:muted / patrol:active - patrol suppression state
  • mode:degraded / mode:normal - operational mode
  • status:idle / status:working - worker status
  • health:healthy / health:failing - component health

Implementation:

  1. Create an event bead (full context, immutable history)
  2. Update the role bead's labels (current state cache)
# Event: Full record of what happened and why
bd create "Muted patrol: user requested during debugging" -t event \
  -l event-type:patrol-muted,actor:observer,reason:user-request

# State: Update the role bead's label to reflect current state
bd label remove beads/observer patrol:active
bd label add beads/observer patrol:muted

Key principle: Events are the source of truth. Labels are a cache for fast queries.

Why This Pattern?

Fast queries without event scanning:

# Without labels-as-state: scan all events to find current patrol state
bd list --type event | grep "patrol" | tail -1  # Slow, fragile

# With labels-as-state: direct query
bd show beads/observer | grep "patrol:"  # Instant

History preserved:

# When was patrol muted? Why? Who did it?
bd list --label event-type:patrol-muted --type event

State recovery:

# If labels get corrupted, rebuild from events
bd list --type event --label event-type:patrol-muted | tail -1
# Then re-apply the label

Common State Dimensions

Dimension Values Use Case
patrol: active, muted Patrol cycle suppression
mode: normal, degraded, maintenance Operational mode
status: idle, working, blocked Worker activity
health: healthy, warning, failing Component health
lock: unlocked, locked Exclusive access control

State Transitions

Always create an event before changing state labels:

# Function to transition state with audit trail
transition_state() {
  local role="$1"
  local dimension="$2"
  local old_value="$3"
  local new_value="$4"
  local reason="$5"

  # Record the transition
  bd create "State change: $dimension $old_value → $new_value" -t event \
    -l "event-type:state-change,dimension:$dimension,from:$old_value,to:$new_value"

  # Update the cache
  bd label remove "$role" "$dimension:$old_value"
  bd label add "$role" "$dimension:$new_value"
}

# Usage
transition_state beads/observer patrol active muted "User debugging session"

Querying State

# Current state of a role
bd label list beads/observer | grep ":"

# All roles in a specific state
bd list --label patrol:muted

# Roles NOT in expected state
bd list --label-any mode:degraded,health:failing

# History of state changes
bd list --type event --label event-type:state-change

Best Practices

  1. Use namespaced dimensions - Prefix with role type if ambiguous
  2. Keep value sets small - 2-4 values per dimension
  3. Document valid values - List allowed values in role docs
  4. Always create events first - Never update labels without history
  5. Treat labels as ephemeral - Rebuild from events if corrupted

Future Helpers

The pattern suggests helper commands (see bd-7l67):

# Query current state
bd state beads/observer patrol     # → "muted"

# Transition with automatic event creation
bd set-state beads/observer patrol=active --reason "Debugging complete"

Until helpers exist, use the manual pattern above.

Advanced Patterns

Component Matrix

Track issues across multiple dimensions:

# Backend + auth + high priority
bd list --label backend,auth --priority 1

# Any frontend work that's small
bd list --label-any frontend,ui --label small

# Critical issues across all components
bd list --priority 0 --label-any backend,frontend,infrastructure

Sprint Planning

# Label issues for sprint
for id in bd-42 bd-43 bd-44 bd-45; do
  bd label add "$id" sprint-12
done

# Track sprint progress
bd list --label sprint-12 --status closed    # Velocity
bd list --label sprint-12 --status open      # Remaining
bd stats | grep "In Progress"                # Current WIP

Technical Debt Tracking

# Mark debt
bd create "Refactor legacy parser" -t chore -p 3 -l technical-debt,large

# Find debt to tackle
bd list --label technical-debt --label small
bd list --label technical-debt --priority 1  # High-priority debt

Breaking Change Coordination

# Identify breaking changes
bd label add bd-42 breaking-change
bd label add bd-42 v2.0

# Find all breaking changes for next major release
bd list --label breaking-change,v2.0

# Ensure they're documented
bd list --label breaking-change --label needs-docs

Operational State Pattern (Labels as Cache)

For orchestration systems, labels can cache the current operational state of "role beads" (issues representing agents or system components). This enables fast state queries without scanning event history.

Convention: <dimension>:<value>

Use colon-separated labels with a dimension prefix and value suffix:

patrol:muted      patrol:active
mode:degraded     mode:normal
status:idle       status:working
health:healthy    health:failing

The Pattern

  1. Create an event bead with full context (immutable, audit trail)
  2. Update the role bead's labels to reflect current state (fast lookup)
# 1. Record the event (source of truth)
bd create "Muted patrol for agent-abc" -t event \
  --parent agent-abc \
  -d "Reason: investigating stuck worker. Expected duration: 30m"

# 2. Update the cached state label
bd label remove agent-abc patrol:active
bd label add agent-abc patrol:muted

Why This Pattern?

Events are source of truth. Labels are cache.

Approach Events Only Labels as Cache
Query current state Scan all events, find latest bd list --label patrol:muted
Query state history Natural (all events exist) Query events
Audit trail Complete Complete (events still exist)
Performance O(n) events O(1) label lookup

The pattern gives you both: complete history via events, fast queries via labels.

Example: Agent Role States

# Create a role bead for an agent
bd create "witness-alpha" -t role -l patrol:active,mode:normal,health:healthy

# Agent enters degraded mode
bd create "Degraded: high error rate" -t event --parent witness-alpha \
  -d "Error rate exceeded 5%. Reducing poll frequency."
bd label remove witness-alpha mode:normal
bd label add witness-alpha mode:degraded

# Query current state
bd list --label mode:degraded --type role  # All degraded roles

# Agent recovers
bd create "Recovered: error rate normal" -t event --parent witness-alpha
bd label remove witness-alpha mode:degraded
bd label add witness-alpha mode:normal

Common Dimensions

Dimension Values Use Case
patrol active, muted, suspended Agent patrol cycles
mode normal, degraded, maintenance Operational modes
status idle, working, blocked Work state
health healthy, warning, failing Health checks
sync current, stale, syncing Sync state

Best Practices

  1. Always create the event first - Labels are cache; events are truth
  2. Remove old value before adding new - Prevents dimension:value1 + dimension:value2 conflicts
  3. Use consistent dimension names - Establish team conventions early
  4. Keep dimensions orthogonal - patrol and mode are independent concerns

Querying State

# Find all muted patrols
bd list --label patrol:muted

# Find healthy agents in normal mode
bd list --label health:healthy,mode:normal

# Find any non-healthy agents
bd list --label-any health:warning,health:failing

# Get state for a specific role
bd label list witness-alpha
# Output: patrol:active, mode:normal, health:healthy

Helper Commands

For convenience, use these helpers:

# Query a specific dimension
bd state witness-alpha patrol
# Output: active

# List all state dimensions
bd state list witness-alpha
# Output:
#   patrol: active
#   mode: normal
#   health: healthy

# Set state (creates event + updates label atomically)
bd set-state witness-alpha patrol=muted --reason "Investigating issue"

The set-state command atomically:

  1. Creates an event bead with the reason (source of truth)
  2. Removes the old dimension label if present
  3. Adds the new dimension:value label (cache)

See bd set-state for full command reference.

Troubleshooting

Labels Not Showing in List

Labels require explicit fetching. The bd list command shows issues but not labels in human output (only in JSON).

# See labels in JSON
bd list --json | jq '.[] | {id, labels}'

# See labels for specific issue
bd show bd-42 --json | jq '.labels'
bd label list bd-42

Label Filtering Not Working

Check label names for exact matches (case-sensitive):

# These are different labels:
bd label add bd-42 Backend    # Capital B
bd list --label backend       # Won't match

# List all labels to see exact names
bd label list-all

Syncing Labels

Labels are stored in the Dolt database. If labels seem out of sync:

# Pull from Dolt remote
bd dolt pull

# Or run doctor to diagnose
bd doctor

See Also