fix(rename-prefix): do not double IDs already on the target prefix (#5135)

* fix(rename-prefix): do not double IDs already on the target prefix

When config.issue_prefix is stale (e.g. still "global") but issue IDs
were already rewritten to "atlas-*", rename-prefix atlas did:

  TrimPrefix("atlas-1", "global-") → "atlas-1"
  newID = "atlas-" + "atlas-1" → "atlas-atlas-1"

Detect IDs that already use the destination prefix and leave them
alone, then still update the config cell (GH#4827).

Fixes #4827

* fix(rename-prefix): use the detected row prefix, not the config cell, to drive ID rewrites

PR #5135 review (maphew, 2026-07-29): rewriteIssueID's "already on
target prefix" guard ran before the old-prefix match, so it also
matched the first hyphen-boundary segment of a multi-part prefix.
Shortening beads-vscode- -> beads- silently skipped every row (they
all start with "beads-"), leaving the config cell and IDs out of
sync — the exact GH#4827 state, now produced by the fix for it.

Restructure so the caller threads the prefix actually detected on
the rows (detectPrefixes), not the possibly-stale issue_prefix
config cell, into rewriteIssueID/renamePrefixInDB:

- detected == newPrefix: config-only repair (GH#4827 half-migrated
  DB) — SetConfig, no ID rewrites, distinct success/dry-run message.
- otherwise: rewrite detected-* -> newPrefix-* as before.

rewriteIssueID collapses to a single oldPrefix check; the newPrefix
guard is gone, since the caller now guarantees oldPrefix reflects
reality instead of a cell that may have drifted.

Also from the same review, three cheap correctness fixes:
- dry-run no longer claims "(all N issue IDs already use prefix X)"
  on a zero-rewrite run when the rows are on an unrelated prefix —
  that message only fires now for the genuine config-only-repair case.
- the success/JSON path reports issues_count: 0 (not len(issues)) and
  a distinct message when only the config was repaired.
- dry-run's "... and more" restores the exact "... and N more issues"
  count.

Left out of scope (per review): the #4175 SetConfig no-op textual-
conflict note, and the PR title's leading "# " (already fixed).

Added: a failing-first unit test for the shortening regression
(TestRewriteIssueID_PrefixShortening), an end-to-end embedded-CLI
subtest for the same case, and a DB-level test pinning the GH#4827
config-only-repair path (TestRenamePrefixInDB_HalfMigratedConfigNotDoubled).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(rename-prefix): assert the rewritten prefix, not a sequential ID

bd create mints hash IDs (beads-cyc), never sequential ones, so
Contains("beads-1") only passed when a hash happened to start with 1 --
a flaky assertion that fails deterministically for most runs. Assert the
"beads-" prefix instead; the existing !Contains("beads-vscode-") check
is what actually pins the shortening fix. Mirrors rename_basic, which
asserts "new-" for the same reason.

Reported by maphew on PR #5135.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Vishnu J 2026-07-31 01:45:43 -07:00 • committed by GitHub
commit 38b6f9ac42
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 241 additions and 19 deletions

View file

@ -136,34 +136,76 @@ NOTE: This is a rare operation. Most users never need this command.`,
return nil
}
if dryRun {
fmt.Printf("DRY RUN: Would rename %d issues from prefix '%s' to '%s'\n\n", len(issues), oldPrefix, newPrefix)
fmt.Printf("Sample changes:\n")
for i, issue := range issues {
if i >= 5 {
fmt.Printf("... and %d more issues\n", len(issues)-5)
break
// The prefix actually on the rows is the ground truth for ID rewriting,
// not the (possibly stale) issue_prefix config cell — see #5135 review.
// detectPrefixes already established this is a single, consistent
// prefix (the len(prefixes) > 1 case returned above).
detected := oldPrefix
if len(prefixes) == 1 {
for p := range prefixes {
detected = p
}
}
// detected == newPrefix means every row is already correctly prefixed
// and only the config cell is stale (GH#4827 half-migrated database).
// Repair the config without touching any IDs.
if detected == newPrefix {
if dryRun {
fmt.Printf("DRY RUN: config prefix disagrees with issue IDs — would repair config only: '%s' -> '%s' (%d issue IDs already correct)\n", oldPrefix, newPrefix, len(issues))
return nil
}
if err := store.SetConfig(ctx, "issue_prefix", newPrefix); err != nil {
return HandleError("failed to update prefix: %v", err)
}
commandDidWrite.Store(true)
fmt.Printf("%s Repaired config prefix: '%s' -> '%s' (%d issue IDs already correct, none rewritten)\n", ui.RenderPass("✓"), ui.RenderAccent(oldPrefix), ui.RenderAccent(newPrefix), len(issues))
if jsonOutput {
result := map[string]interface{}{
"old_prefix": oldPrefix,
"new_prefix": newPrefix,
"issues_count": 0,
"config_repaired": true,
}
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
if eerr := enc.Encode(result); eerr != nil {
return eerr
}
oldID := fmt.Sprintf("%s-%s", oldPrefix, strings.TrimPrefix(issue.ID, oldPrefix+"-"))
newID := fmt.Sprintf("%s-%s", newPrefix, strings.TrimPrefix(issue.ID, oldPrefix+"-"))
fmt.Printf(" %s -> %s\n", ui.RenderAccent(oldID), ui.RenderAccent(newID))
}
return nil
}
fmt.Printf("Renaming %d issues from prefix '%s' to '%s'...\n", len(issues), oldPrefix, newPrefix)
if dryRun {
fmt.Printf("DRY RUN: Would rename issues from prefix '%s' to '%s'\n\n", detected, newPrefix)
fmt.Printf("Sample changes:\n")
shown := 0
for _, issue := range issues {
newID := rewriteIssueID(detected, newPrefix, issue.ID)
if shown < 5 {
fmt.Printf(" %s -> %s\n", ui.RenderAccent(issue.ID), ui.RenderAccent(newID))
shown++
}
}
if remaining := len(issues) - shown; remaining > 0 {
fmt.Printf("... and %d more issues\n", remaining)
}
return nil
}
if err := renamePrefixInDB(ctx, oldPrefix, newPrefix, issues); err != nil {
fmt.Printf("Renaming issues from prefix '%s' to '%s'...\n", detected, newPrefix)
if err := renamePrefixInDB(ctx, detected, newPrefix, issues); err != nil {
return HandleError("failed to rename prefix: %v", err)
}
commandDidWrite.Store(true)
fmt.Printf("%s Successfully renamed prefix from %s to %s\n", ui.RenderPass("✓"), ui.RenderAccent(oldPrefix), ui.RenderAccent(newPrefix))
fmt.Printf("%s Successfully renamed prefix from %s to %s\n", ui.RenderPass("✓"), ui.RenderAccent(detected), ui.RenderAccent(newPrefix))
if jsonOutput {
result := map[string]interface{}{
"old_prefix": oldPrefix,
"old_prefix": detected,
"new_prefix": newPrefix,
"issues_count": len(issues),
}
@ -355,24 +397,45 @@ func repairPrefixes(ctx context.Context, st storage.DoltStorage, actorName strin
return nil
}
// rewriteIssueID maps oldID from oldPrefix to newPrefix. oldPrefix must be
// the prefix actually detected on the issue rows (see detectPrefixes), not
// the possibly-stale issue_prefix config cell — see PR #5135 review (maphew,
// 2026-07-29): using the config cell here made the "already on target
// prefix" check ambiguous with genuine prefix-shortening renames (e.g.
// "beads-vscode-" -> "beads-" would leave "beads-vscode-1" unchanged,
// because it also starts with "beads-"). The GH#4827 half-migrated-config
// case is now handled by the caller comparing the detected prefix to
// newPrefix directly and skipping ID rewrites entirely (config-only
// repair), so this function no longer needs — or has — a newPrefix guard.
func rewriteIssueID(oldPrefix, newPrefix, oldID string) string {
oldP := strings.TrimRight(oldPrefix, "-")
newP := strings.TrimRight(newPrefix, "-")
if oldP == "" || newP == "" {
return oldID
}
if strings.HasPrefix(oldID, oldP+"-") {
return newP + "-" + strings.TrimPrefix(oldID, oldP+"-")
}
return oldID
}
func renamePrefixInDB(ctx context.Context, oldPrefix, newPrefix string, issues []*types.Issue) error {
// NOTE: Each issue is updated in its own transaction. A failure mid-way could leave
// the database in a mixed state with some issues renamed and others not.
// For production use, consider implementing a single atomic RenamePrefix() method
// in the storage layer that wraps all updates in one transaction.
oldPrefixPattern := regexp.MustCompile(`\b` + regexp.QuoteMeta(oldPrefix) + `-(\d+)\b`)
oldP := strings.TrimRight(oldPrefix, "-")
newP := strings.TrimRight(newPrefix, "-")
oldPrefixPattern := regexp.MustCompile(`\b` + regexp.QuoteMeta(oldP) + `-(\d+)\b`)
replaceFunc := func(match string) string {
return strings.Replace(match, oldPrefix+"-", newPrefix+"-", 1)
return strings.Replace(match, oldP+"-", newP+"-", 1)
}
for _, issue := range issues {
oldID := issue.ID
numPart := strings.TrimPrefix(oldID, oldPrefix+"-")
newID := fmt.Sprintf("%s-%s", newPrefix, numPart)
issue.ID = newID
newID := rewriteIssueID(oldP, newP, oldID)
issue.Title = oldPrefixPattern.ReplaceAllStringFunc(issue.Title, replaceFunc)
issue.Description = oldPrefixPattern.ReplaceAllStringFunc(issue.Description, replaceFunc)
@ -386,12 +449,19 @@ func renamePrefixInDB(ctx context.Context, oldPrefix, newPrefix string, issues [
issue.Notes = oldPrefixPattern.ReplaceAllStringFunc(issue.Notes, replaceFunc)
}
// ID already on the target prefix (stale config cell only): skip UpdateIssueID
// so we never produce atlas-atlas-* (GH#4827).
if newID == oldID {
continue
}
issue.ID = newID
if err := store.UpdateIssueID(ctx, oldID, newID, issue, actor); err != nil {
return fmt.Errorf("failed to update issue %s: %w", oldID, err)
}
}
if err := store.SetConfig(ctx, "issue_prefix", newPrefix); err != nil {
if err := store.SetConfig(ctx, "issue_prefix", newP); err != nil {
return fmt.Errorf("failed to update config: %w", err)
}

View file

@ -130,6 +130,41 @@ func TestEmbeddedRenamePrefix(t *testing.T) {
t.Errorf("expected 'No issues' message: %s", out)
}
})
// ===== Prefix Shortening (PR #5135 review blocker B1) =====
// Shortening a multi-part prefix to one of its own leading segments
// (e.g. "beads-vscode-" -> "beads-") must still rewrite every row —
// "beads-vscode-1" starting with "beads-" is not the same thing as it
// already being on the target prefix.
t.Run("rename_prefix_shortening", func(t *testing.T) {
dir, _, _ := bdInit(t, bd, "--prefix", "beads-vscode")
bdCreate(t, bd, dir, "Shortening test 1", "--type", "task")
bdCreate(t, bd, dir, "Shortening test 2", "--type", "task")
out := bdRenamePrefix(t, bd, dir, "beads")
if !strings.Contains(out, "Successfully renamed") {
t.Errorf("expected 'Successfully renamed' in output: %s", out)
}
cmd := exec.Command(bd, "list")
cmd.Dir = dir
cmd.Env = bdEnv(dir)
stdout, stderr, err := runCommandBuffers(t, cmd)
if err != nil {
t.Fatalf("bd list after rename failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
}
// bd create mints hash IDs (beads-cyc), never sequential ones, so assert the
// rewritten prefix rather than a number — the beads-vscode- check below is what
// carries the real weight. Mirrors rename_basic, which asserts "new-" for the
// same reason.
if !strings.Contains(stdout.String(), "beads-") {
t.Errorf("expected shortened 'beads-' prefix in list output: %s", stdout.String())
}
if strings.Contains(stdout.String(), "beads-vscode-") {
t.Errorf("regression: 'beads-vscode-' IDs were left unrewritten: %s", stdout.String())
}
})
}
// TestEmbeddedRenamePrefixConcurrent exercises rename-prefix --dry-run concurrently.

View file

@ -0,0 +1,53 @@
package main
import "testing"
func TestRewriteIssueID_NoDoublePrefix(t *testing.T) {
t.Parallel()
// GH#4827: config still "global" but rows already "atlas-*"
got := rewriteIssueID("global", "atlas", "atlas-1")
if got != "atlas-1" {
t.Fatalf("got %q, want atlas-1 (must not double)", got)
}
got = rewriteIssueID("global-", "atlas-", "atlas-99")
if got != "atlas-99" {
t.Fatalf("got %q, want atlas-99", got)
}
}
func TestRewriteIssueID_NormalRename(t *testing.T) {
t.Parallel()
got := rewriteIssueID("global", "atlas", "global-1")
if got != "atlas-1" {
t.Fatalf("got %q, want atlas-1", got)
}
got = rewriteIssueID("old-", "new-", "old-abc")
if got != "new-abc" {
t.Fatalf("got %q, want new-abc", got)
}
}
func TestRewriteIssueID_UnrelatedPrefixUnchanged(t *testing.T) {
t.Parallel()
got := rewriteIssueID("global", "atlas", "other-1")
if got != "other-1" {
t.Fatalf("got %q, want other-1", got)
}
}
// TestRewriteIssueID_PrefixShortening pins PR #5135 review blocker B1
// (maphew, 2026-07-29): the "already on target prefix" guard was checked
// before the old-prefix match, so shortening a multi-part prefix to one of
// its own leading segments (e.g. "beads-vscode-" -> "beads-") silently
// skipped every ID, because "beads-vscode-1" also starts with "beads-".
func TestRewriteIssueID_PrefixShortening(t *testing.T) {
t.Parallel()
got := rewriteIssueID("beads-vscode", "beads", "beads-vscode-1")
if got != "beads-1" {
t.Fatalf("got %q, want beads-1 (shortening regression)", got)
}
got = rewriteIssueID("kw-team", "kw", "kw-team-42")
if got != "kw-42" {
t.Fatalf("got %q, want kw-42 (shortening regression)", got)
}
}

View file

@ -221,3 +221,67 @@ func TestRenamePrefixInDB(t *testing.T) {
t.Errorf("Expected ID 'new-1', got %q", newIssue.ID)
}
}
// TestRenamePrefixInDB_HalfMigratedConfigNotDoubled pins the actual GH#4827
// recovery path at the DB layer: config says "global" but the row is
// already "atlas-1" (a half-migrated database). renamePrefixInDB must leave
// the row alone — not produce "atlas-atlas-1" — while still repairing the
// config cell. See PR #5135 review (maphew, 2026-07-29).
func TestRenamePrefixInDB_HalfMigratedConfigNotDoubled(t *testing.T) {
tmpDir := t.TempDir()
dbPath := filepath.Join(tmpDir, "test.db")
testStore, err := dolt.New(context.Background(), &dolt.Config{Path: dbPath})
if err != nil {
t.Skipf("skipping: Dolt server not available: %v", err)
}
t.Cleanup(func() {
testStore.Close()
os.Remove(dbPath)
})
ctx := context.Background()
store = testStore
actor = "test-actor"
if err := testStore.SetConfig(ctx, "issue_prefix", "global"); err != nil {
t.Fatalf("Failed to set config: %v", err)
}
issue1 := &types.Issue{
ID: "atlas-1",
Title: "Already migrated",
Description: "Row is on the target prefix; config cell is stale",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
if err := testStore.CreateIssue(ctx, issue1, "test"); err != nil {
t.Fatalf("Failed to create issue: %v", err)
}
issues := []*types.Issue{issue1}
if err := renamePrefixInDB(ctx, "global", "atlas", issues); err != nil {
t.Fatalf("renamePrefixInDB failed: %v", err)
}
newPrefix, err := testStore.GetConfig(ctx, "issue_prefix")
if err != nil {
t.Fatalf("Failed to get new prefix: %v", err)
}
if newPrefix != "atlas" {
t.Errorf("Expected config prefix 'atlas', got %q", newPrefix)
}
survivingIssue, err := testStore.GetIssue(ctx, "atlas-1")
if err != nil {
t.Fatalf("Expected atlas-1 to survive unchanged, got error: %v", err)
}
if survivingIssue.ID != "atlas-1" {
t.Errorf("Expected surviving ID 'atlas-1', got %q", survivingIssue.ID)
}
if doubled, err := testStore.GetIssue(ctx, "atlas-atlas-1"); err == nil && doubled != nil {
t.Errorf("regression: found doubled ID 'atlas-atlas-1': %+v", doubled)
}
}