diff --git a/CHANGELOG.md b/CHANGELOG.md index edf3746fd..4fa31bb90 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -211,6 +211,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 instead of the message followed by `Error: exit code 1` and the full usage text. Exit statuses are unchanged; this applies on every topology. +- **`bd label remove` and `bd label add` no longer claim a no-op edit** + ([#5988](https://github.com/gastownhall/beads/issues/5988)). Removing a + label the issue never had printed `✓ Removed label 'x' from `, and + adding one it already had printed `✓ Added label`, so a real edit could not + be told from a no-op. Such a label is now reported as + `• Label 'x' was not on ` / `• already has label 'x'`, with JSON + status `unchanged` instead of `removed`/`added`; a multi-label edit reports + each label by what actually happened to it. The exit code is still 0, so + idempotent callers are unaffected. + - **Proxied `--repo` and row-cap refusals are typed again** ([#6293](https://github.com/gastownhall/beads/pull/6293)). `bd create --repo` under `--proxied-server` answers `--json` with the stable diff --git a/cmd/bd/label.go b/cmd/bd/label.go index 6e76c5646..86af49bc9 100644 --- a/cmd/bd/label.go +++ b/cmd/bd/label.go @@ -127,12 +127,48 @@ func applyLabelEdit(ctx context.Context, issueIDs []string, labels []string, ope } else { patch.Labels.Add = labels } + // WHICH LABELS ACTUALLY MOVED is what the report has to say (GH#5988). + // UpdateResult.Changed is one flag per issue, which answers it exactly + // for a single label; a multi-label edit that changed something also + // needs the pre-edit set to tell its moved labels from its no-ops, so + // only that case pays for a read. + // + // THAT PRE-EDIT SET IS READ OUTSIDE THE WRITE TRANSACTION, so per-label + // attribution on the multi-label path is best-effort: a concurrent edit + // landing between the read and the Update can misattribute one label's + // line. What it cannot do is write the wrong thing — the target set is + // recomputed from current.Labels inside the write transaction + // (issueops.ApplyLabelPatch), so the stored labels, the JSON shape and + // the exit code stay correct and the state converges. A single-label + // edit is immune by construction, deriving its outcome from the write's + // own transaction. The batch shape named above closes the window + // structurally by collapsing the read and the write into one + // transaction; it is not worth a second read protocol before then. + var reader issueops.Reader + if len(labels) > 1 { + if reader, err = openIssueReader(); err != nil { + return HandleErrorRespectJSON("%v", err) + } + } + outcomes := make([]labelEditOutcome, 0, len(issueIDs)) for _, issueID := range issueIDs { - if _, uerr := lifecycle.Update(ctx, issueops.UpdateRequest{ + var before map[string]bool + if reader != nil { + details, gerr := reader.Get(ctx, issueops.GetRequest{ID: issueID}) + if gerr != nil { + return HandleErrorRespectJSON("label %s: reading labels on %s: %v", operation, issueID, gerr) + } + before = make(map[string]bool, len(details.Labels)) + for _, label := range details.Labels { + before[label] = true + } + } + result, uerr := lifecycle.Update(ctx, issueops.UpdateRequest{ Actor: actor, IssueID: issueID, Patch: patch, - }); uerr != nil { + }) + if uerr != nil { return HandleErrorRespectJSON("label %s: %s label '%s' on %s: %v", operation, operation, strings.Join(labels, "', '"), issueID, uerr) } @@ -140,29 +176,60 @@ func applyLabelEdit(ctx context.Context, issueIDs []string, labels []string, ope // call at a time, so a request that failed on its third id has still // written its first two and the deferred commit has to know about them. commandDidWrite.Store(true) + outcome := labelEditOutcome{issueID: issueID, changed: make([]bool, len(labels))} + for i, label := range labels { + switch { + case !result.Changed: + // The role wrote nothing, so no label of this edit moved. + case before == nil: + outcome.changed[i] = true + case operation == labelOperationRemoved: + outcome.changed[i] = before[label] + default: + outcome.changed[i] = !before[label] + } + } + outcomes = append(outcomes, outcome) } - return reportLabelEdit(issueIDs, labels, operation, jsonOutput) + return reportLabelEdit(outcomes, labels, operation, jsonOutput) } // The two label edits this command performs, spelled once. They are the words // the JSON "status" member and the human line both carry, so they are constants -// rather than two string literals that have to agree. +// rather than two string literals that have to agree. labelStatusUnchanged is +// the status of a label the edit left as it was: an add of a label the issue +// already had, or a remove of one it never had. const ( labelOperationAdded = "added" labelOperationRemoved = "removed" + labelStatusUnchanged = "unchanged" ) +// labelEditOutcome is what one issue's edit did: changed[i] reports whether +// the edit's i-th label actually moved. +type labelEditOutcome struct { + issueID string + changed []bool +} + // reportLabelEdit prints what landed, in the shape both routes have always // printed it: one JSON row per (issue, label) pair, or one human line per issue -// naming every label at once. -func reportLabelEdit(issueIDs []string, labels []string, operation string, jsonOut bool) error { +// naming every label that moved. A label the edit left as it was is reported +// as such — status "unchanged", and a line of its own — rather than as the +// operation, so a no-op cannot be read as a confirmation (GH#5988). It is +// still not an error: the exit code stays 0 so idempotent callers keep working. +func reportLabelEdit(outcomes []labelEditOutcome, labels []string, operation string, jsonOut bool) error { if jsonOut { - results := make([]map[string]interface{}, 0, len(issueIDs)*len(labels)) - for _, issueID := range issueIDs { - for _, label := range labels { + results := make([]map[string]interface{}, 0, len(outcomes)*len(labels)) + for _, outcome := range outcomes { + for i, label := range labels { + status := operation + if !outcome.changed[i] { + status = labelStatusUnchanged + } results = append(results, map[string]interface{}{ - "status": operation, - "issue_id": issueID, + "status": status, + "issue_id": outcome.issueID, "label": label, }) } @@ -173,17 +240,42 @@ func reportLabelEdit(issueIDs []string, labels []string, operation string, jsonO if operation == labelOperationRemoved { verb, prep = "Removed", "from" } - noun := "label" - if len(labels) > 1 { - noun = "labels" - } - labelDesc := strings.Join(labels, "', '") - for _, issueID := range issueIDs { - fmt.Printf("%s %s %s '%s' %s %s\n", ui.RenderPass("✓"), verb, noun, labelDesc, prep, issueID) + for _, outcome := range outcomes { + var moved, unmoved []string + for i, label := range labels { + if outcome.changed[i] { + moved = append(moved, label) + } else { + unmoved = append(unmoved, label) + } + } + if len(moved) > 0 { + fmt.Printf("%s %s %s '%s' %s %s\n", ui.RenderPass("✓"), verb, + labelNoun(moved, "label", "labels"), strings.Join(moved, "', '"), prep, outcome.issueID) + } + if len(unmoved) == 0 { + continue + } + unmovedDesc := strings.Join(unmoved, "', '") + if operation == labelOperationRemoved { + fmt.Printf("%s %s '%s' %s not on %s\n", ui.RenderAccent("•"), + labelNoun(unmoved, "Label", "Labels"), unmovedDesc, labelNoun(unmoved, "was", "were"), outcome.issueID) + } else { + fmt.Printf("%s %s already has %s '%s'\n", ui.RenderAccent("•"), + outcome.issueID, labelNoun(unmoved, "label", "labels"), unmovedDesc) + } } return nil } +// labelNoun picks the singular or plural word for a list of labels. +func labelNoun(labels []string, singular, plural string) string { + if len(labels) > 1 { + return plural + } + return singular +} + // parseLabelArgs splits positional args into issue IDs and labels. The final // arg is the label spec; commas separate multiple labels ("label1,label2"). func parseLabelArgs(args []string) (issueIDs []string, labels []string) { diff --git a/cmd/bd/label_embedded_test.go b/cmd/bd/label_embedded_test.go index 9f8b52aeb..8f91d5acf 100644 --- a/cmd/bd/label_embedded_test.go +++ b/cmd/bd/label_embedded_test.go @@ -40,6 +40,21 @@ func bdLabelJSONOutput(t *testing.T, bd, dir string, args ...string) string { return stdout.String() } +// bdLabelEditJSON runs "bd label ... --json" and returns its result rows. +func bdLabelEditJSON(t *testing.T, bd, dir, op string, args ...string) []map[string]interface{} { + t.Helper() + s := strings.TrimSpace(bdLabelJSONOutput(t, bd, dir, append(append([]string{op}, args...), "--json")...)) + start := strings.Index(s, "[") + if start < 0 { + t.Fatalf("no JSON array in label %s output: %s", op, s) + } + var rows []map[string]interface{} + if err := json.Unmarshal([]byte(s[start:]), &rows); err != nil { + t.Fatalf("parse label %s JSON: %v\nstdout: %s", op, err, s) + } + return rows +} + // bdLabelFail runs "bd label" expecting failure. func bdLabelFail(t *testing.T, bd, dir string, args ...string) string { t.Helper() @@ -245,6 +260,114 @@ func TestEmbeddedLabel(t *testing.T) { } }) + // ===== No-op edits (GH#5988) ===== + // + // A label edit that leaves the set as it was used to print the same + // "✓ Removed"/"✓ Added" line and JSON status as a real one. It still exits + // 0 (bdLabel fails the test otherwise), but it now says so. + + t.Run("label_remove_absent_reports_noop", func(t *testing.T) { + issue := bdCreate(t, bd, dir, "Remove absent", "--type", "task", "--label", "present") + out := bdLabel(t, bd, dir, "remove", issue.ID, "never-applied") + if strings.Contains(out, "Removed") { + t.Errorf("remove of an absent label claimed a removal: %s", out) + } + if want := "Label 'never-applied' was not on " + issue.ID; !strings.Contains(out, want) { + t.Errorf("expected %q in output: %s", want, out) + } + rows := bdLabelEditJSON(t, bd, dir, "remove", issue.ID, "never-applied") + if len(rows) != 1 || rows[0]["status"] != "unchanged" || rows[0]["label"] != "never-applied" || rows[0]["issue_id"] != issue.ID { + t.Errorf("remove of an absent label JSON = %v, want one unchanged row", rows) + } + }) + + t.Run("label_add_present_reports_noop", func(t *testing.T) { + issue := bdCreate(t, bd, dir, "Add present", "--type", "task", "--label", "present") + out := bdLabel(t, bd, dir, "add", issue.ID, "present") + if strings.Contains(out, "Added") { + t.Errorf("add of a present label claimed an addition: %s", out) + } + if want := issue.ID + " already has label 'present'"; !strings.Contains(out, want) { + t.Errorf("expected %q in output: %s", want, out) + } + rows := bdLabelEditJSON(t, bd, dir, "add", issue.ID, "present") + if len(rows) != 1 || rows[0]["status"] != "unchanged" || rows[0]["label"] != "present" || rows[0]["issue_id"] != issue.ID { + t.Errorf("add of a present label JSON = %v, want one unchanged row", rows) + } + }) + + t.Run("label_edit_real_change_still_reported", func(t *testing.T) { + issue := bdCreate(t, bd, dir, "Real edit", "--type", "task") + if rows := bdLabelEditJSON(t, bd, dir, "add", issue.ID, "real"); len(rows) != 1 || rows[0]["status"] != "added" { + t.Errorf("real add JSON = %v, want one added row", rows) + } + if rows := bdLabelEditJSON(t, bd, dir, "remove", issue.ID, "real"); len(rows) != 1 || rows[0]["status"] != "removed" { + t.Errorf("real remove JSON = %v, want one removed row", rows) + } + if out := bdLabel(t, bd, dir, "add", issue.ID, "real"); !strings.Contains(out, "Added label 'real' to "+issue.ID) { + t.Errorf("real add text = %s", out) + } + if out := bdLabel(t, bd, dir, "remove", issue.ID, "real"); !strings.Contains(out, "Removed label 'real' from "+issue.ID) { + t.Errorf("real remove text = %s", out) + } + }) + + t.Run("label_edit_mixed_reports_each_label", func(t *testing.T) { + issue := bdCreate(t, bd, dir, "Mixed edit", "--type", "task", "--label", "have") + out := bdLabel(t, bd, dir, "add", issue.ID, "have,fresh") + if !strings.Contains(out, "Added label 'fresh' to "+issue.ID) || !strings.Contains(out, issue.ID+" already has label 'have'") { + t.Errorf("mixed add text = %s", out) + } + rows := bdLabelEditJSON(t, bd, dir, "remove", issue.ID, "have,ghost") + got := map[interface{}]interface{}{} + for _, r := range rows { + got[r["label"]] = r["status"] + } + if len(rows) != 2 || got["have"] != "removed" || got["ghost"] != "unchanged" { + t.Errorf("mixed remove JSON = %v, want have=removed ghost=unchanged", rows) + } + }) + + // One label, two issues, only one of which has it: the divergence is + // BETWEEN the issues, so this pins the per-issue derivation the way + // label_edit_mixed_reports_each_label pins the per-label one. The outcome + // is built inside the id loop from that id's own UpdateResult, and a + // refactor that hoisted it out — or reused the last result for every id — + // would print one identical line per issue again, which is what the + // pre-GH#5988 code did. Every other subtest here edits a single issue and + // so would pass such a refactor. + t.Run("label_edit_divergent_multi_issue", func(t *testing.T) { + fresh := bdCreate(t, bd, dir, "Divergent JSON fresh", "--type", "task") + holder := bdCreate(t, bd, dir, "Divergent JSON holder", "--type", "task", "--label", "shared") + rows := bdLabelEditJSON(t, bd, dir, "add", fresh.ID, holder.ID, "shared") + got := map[interface{}]interface{}{} + for _, r := range rows { + if r["label"] != "shared" { + t.Errorf("unexpected label in row %v", r) + } + got[r["issue_id"]] = r["status"] + } + if len(rows) != 2 || got[fresh.ID] != "added" || got[holder.ID] != "unchanged" { + t.Errorf("divergent multi-issue add JSON = %v, want %s=added %s=unchanged", + rows, fresh.ID, holder.ID) + } + + // Same shape in the text report: one line per issue, each naming its + // own id, and the no-op issue must not be claimed as an edit. + freshText := bdCreate(t, bd, dir, "Divergent text fresh", "--type", "task") + holderText := bdCreate(t, bd, dir, "Divergent text holder", "--type", "task", "--label", "shared") + out := bdLabel(t, bd, dir, "add", freshText.ID, holderText.ID, "shared") + if want := "Added label 'shared' to " + freshText.ID; !strings.Contains(out, want) { + t.Errorf("expected %q in output: %s", want, out) + } + if want := holderText.ID + " already has label 'shared'"; !strings.Contains(out, want) { + t.Errorf("expected %q in output: %s", want, out) + } + if claim := "Added label 'shared' to " + holderText.ID; strings.Contains(out, claim) { + t.Errorf("add claimed an edit on the issue that already had the label: %s", out) + } + }) + // ===== Label List ===== t.Run("label_list", func(t *testing.T) { diff --git a/cmd/bd/label_proxied_integration_test.go b/cmd/bd/label_proxied_integration_test.go index ffdd460d8..b85bdf156 100644 --- a/cmd/bd/label_proxied_integration_test.go +++ b/cmd/bd/label_proxied_integration_test.go @@ -243,6 +243,40 @@ func TestProxiedServerLabel(t *testing.T) { } }) + // GH#5988: a no-op edit reports itself on this route exactly as on the + // direct one, text and JSON, and still exits 0. + t.Run("noop_edit_reports_unchanged", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "no") + issue := bdProxiedCreate(t, bd, p.dir, "No-op label") + bdProxiedLabel(t, bd, p.dir, "add", issue.ID, "have") + + if out := bdProxiedLabel(t, bd, p.dir, "remove", issue.ID, "never"); !strings.Contains(out, "Label 'never' was not on "+issue.ID) { + t.Errorf("remove of an absent label text = %s", out) + } + if out := bdProxiedLabel(t, bd, p.dir, "add", issue.ID, "have"); !strings.Contains(out, issue.ID+" already has label 'have'") { + t.Errorf("add of a present label text = %s", out) + } + stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "label", "remove", issue.ID, "have,never", "--json") + if err != nil { + t.Fatalf("label remove --json failed: %v\nstderr:\n%s", err, stderr) + } + start := strings.Index(stdout, "[") + if start < 0 { + t.Fatalf("no JSON array in remove output:\n%s", stdout) + } + var rows []struct { + Status string `json:"status"` + Label string `json:"label"` + } + if err := json.Unmarshal([]byte(stdout[start:]), &rows); err != nil { + t.Fatalf("parse remove JSON: %v\nraw: %s", err, stdout[start:]) + } + if len(rows) != 2 || rows[0].Label != "have" || rows[0].Status != "removed" || rows[1].Label != "never" || rows[1].Status != "unchanged" { + t.Fatalf("mixed remove rows = %+v, want have=removed never=unchanged", rows) + } + }) + t.Run("remove_comma_separated_multi", func(t *testing.T) { t.Parallel() p := newSharedProxiedProject(t, bd, "rm") diff --git a/tests/regression/DISCOVERY.md b/tests/regression/DISCOVERY.md index 98952784b..b60f2eca9 100644 --- a/tests/regression/DISCOVERY.md +++ b/tests/regression/DISCOVERY.md @@ -96,8 +96,8 @@ actionable — some are by-design tradeoffs. The audit column tracks triage. | BUG-67 | **PROTOCOL** | PASS (correct) | — | | BUG-68 | **PROTOCOL** | PASS (correct) | — | | BUG-69 | **BUG** | OPEN (not PR'd yet) | — | -| BUG-70 | **BUG** | OPEN (not PR'd yet) | — | -| BUG-71 | **BUG** | OPEN (not PR'd yet) | — | +| BUG-70 | **FIX PR** | **PR OPEN** | PR #6742 | +| BUG-71 | **FIX PR** | **PR OPEN** | PR #6742 | | BUG-72 | **PROTOCOL** | PASS (correct) | — | ### Shipped fix PRs (all include protocol tests) @@ -1169,6 +1169,7 @@ exist." Same class of bug as BUG-59 (children nonexistent parent). ### BUG-70: `bd label remove` on nonexistent label reports success (NEW — session 8c) **Severity: LOW** — False positive confirmation (same class as BUG-42) +**Status: FIXED — PR #6742** (GH#5988) **Discovered:** Session 8c discovery, test **File:** `cmd/bd/label.go` (no existence check before remove) **Test:** `TestDiscovery_LabelRemoveNonexistentSilentSuccess` @@ -1181,6 +1182,7 @@ was never on the issue. Same pattern as BUG-42 (dep rm nonexistent says "Removed ### BUG-71: `bd label add` duplicate reports "Added" when already exists (NEW — session 8c) **Severity: LOW** — Misleading success message +**Status: FIXED — PR #6742** (GH#5988) **Discovered:** Session 8c discovery, test **File:** `cmd/bd/label.go:99-102` (no existence check before add) **Test:** `TestDiscovery_LabelAddDuplicateReportsAdded` diff --git a/tests/regression/discovery_test.go b/tests/regression/discovery_test.go index ce1d32146..8c3a3b936 100644 --- a/tests/regression/discovery_test.go +++ b/tests/regression/discovery_test.go @@ -2784,8 +2784,18 @@ func TestDiscovery_BlockedNonexistentParentSilentEmpty(t *testing.T) { } // TestDiscovery_LabelRemoveNonexistentSilentSuccess verifies that -// bd label remove reports success. -// BUG-65: Same pattern as BUG-42 (dep rm nonexistent says "Removed"). +// bd label remove does not claim a removal. +// +// FIXED (PR #6742, GH#5988): the command used to print "✓ Removed label" +// for a label the issue never had. It now reports the no-op ("Label 'x' was +// not on ") and still exits 0, since a no-op edit is not an error. This +// test's assertions describe the fixed behavior and stay as a discovery-suite +// regression check — this file is `//go:build regression && discovery` and no +// CI lane passes the discovery tag, so the CI lock for the fix is +// TestEmbeddedLabel/TestProxiedServerLabel in cmd/bd, not this test. Same +// class as BUG-42 (dep rm nonexistent says "Removed"). +// +// Classification: BUG (fixed) — false positive confirmation. func TestDiscovery_LabelRemoveNonexistentSilentSuccess(t *testing.T) { w := newCandidateWorkspace(t) @@ -2799,23 +2809,35 @@ func TestDiscovery_LabelRemoveNonexistentSilentSuccess(t *testing.T) { t.Fatalf("expected 1 label, got %d", len(labels)) } - // Bug: removing a nonexistent label should error, not report success - _, err := w.tryRun("label", "remove", a, "never-existed-label") - if err == nil { - // Command succeeded — verify the real label is still there - data = parseJSON(t, w.run("show", a, "--json")) - labels, _ = data[0]["labels"].([]any) - if len(labels) == 1 { - t.Errorf("DISCOVERY: bd label remove %s 'never-existed-label' reported success — "+ - "label didn't exist. Same pattern as BUG-42 (dep rm false positive). "+ - "File: cmd/bd/label.go (no existence check before remove).", a) - } + out, err := w.tryRun("label", "remove", a, "never-existed-label") + if err != nil { + t.Fatalf("bd label remove of an absent label should still exit 0: %v\n%s", err, out) + } + if strings.Contains(out, "Removed") { + t.Errorf("DISCOVERY: bd label remove %s 'never-existed-label' claimed a removal — "+ + "the label was never on the issue. File: cmd/bd/label.go.\n%s", a, out) + } + if !strings.Contains(out, "was not on") { + t.Errorf("bd label remove of an absent label should say so, got:\n%s", out) + } + data = parseJSON(t, w.run("show", a, "--json")) + labels, _ = data[0]["labels"].([]any) + if len(labels) != 1 { + t.Errorf("the real label should be untouched, got %d labels", len(labels)) } } // TestDiscovery_LabelAddDuplicateReportsAdded verifies that adding an -// already-existing label reports "Added" even though it's a no-op. -// BUG-66: label.go doesn't check if label already exists before adding. +// already-existing label does not report "Added". +// +// FIXED (PR #6742, GH#5988): the command used to print "✓ Added label" for a +// label the issue already had. The storage layer was always idempotent (no +// duplicate row); the message now says " already has label 'x'" and the +// command still exits 0. Like the test above this stays as a discovery-suite +// regression check and is not a CI gate; the CI lock is +// TestEmbeddedLabel/TestProxiedServerLabel in cmd/bd. +// +// Classification: BUG (fixed) — misleading success message. func TestDiscovery_LabelAddDuplicateReportsAdded(t *testing.T) { w := newCandidateWorkspace(t) @@ -2829,21 +2851,21 @@ func TestDiscovery_LabelAddDuplicateReportsAdded(t *testing.T) { t.Fatalf("expected 1 label, got %d", len(labels)) } - // Bug: adding the same label again should either warn or be rejected - _, err := w.tryRun("label", "add", a, "my-label") - if err == nil { - // Succeeded — check if the label count changed (duplicate created?) - data = parseJSON(t, w.run("show", a, "--json")) - labels, _ = data[0]["labels"].([]any) - if len(labels) == 1 { - // Idempotent (correct at storage level) but misleading "Added" message - t.Errorf("DISCOVERY: bd label add %s 'my-label' reported 'Added' when label already existed — "+ - "idempotent no-op but misleading success message. Should warn 'label already exists'. "+ - "File: cmd/bd/label.go:99-102.", a) - } else if len(labels) > 1 { - t.Errorf("DISCOVERY: bd label add %s 'my-label' created DUPLICATE label — "+ - "now has %d copies. File: cmd/bd/label.go.", a, len(labels)) - } + out, err := w.tryRun("label", "add", a, "my-label") + if err != nil { + t.Fatalf("bd label add of a present label should still exit 0: %v\n%s", err, out) + } + if strings.Contains(out, "Added") { + t.Errorf("DISCOVERY: bd label add %s 'my-label' reported 'Added' when the label already existed. "+ + "File: cmd/bd/label.go.\n%s", a, out) + } + if !strings.Contains(out, "already has label") { + t.Errorf("bd label add of a present label should say so, got:\n%s", out) + } + data = parseJSON(t, w.run("show", a, "--json")) + labels, _ = data[0]["labels"].([]any) + if len(labels) != 1 { + t.Errorf("bd label add %s 'my-label' created a DUPLICATE label — now has %d copies", a, len(labels)) } }