beads/docs/core-concepts
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
..
adaptive-ids.md docs: apply PR #4722 review feedback to user docs 2026-07-12 11:06:57 -07:00
dependencies.md docs: supersedes is a replacement link, not a version chain (#6212) 2026-09-12 06:41:33 -07:00
graph-links.md docs: supersedes is a replacement link, not a version chain (#6212) 2026-09-12 06:41:33 -07:00
hash-ids.md docs: apply PR #4722 review feedback to user docs 2026-07-12 11:06:57 -07:00
index.md Rename the reserved "graph" mermaid node id so diagrams render (#4958) 2026-07-23 17:14:09 -07:00
issues.md docs: align user docs and CLI reference with the v1.1.0 release (#4874) 2026-07-17 14:17:28 -07:00
labels.md cmd/bd: bd label rename <old> <new> (stacked on #6007) (#6009) 2026-09-29 17:02:35 -07:00
metadata.md docs: apply PR #4722 review feedback to user docs 2026-07-12 11:06:57 -07:00
sync-concepts.md docs: apply PR #4722 review feedback to user docs 2026-07-12 11:06:57 -07:00