From ee441fdc73086eff7758c37fc17e0e08be7dc69d Mon Sep 17 00:00:00 2001 From: Julian Knutsen Date: Mon, 19 Oct 2026 08:28:18 +0000 Subject: [PATCH] fix(setup): stop leaving a blank-line hole on --remove (#7692) `bd setup claude --remove` (and the factory, mux, opencode and gemini recipes that share removeBeadsSection) cut exactly the managed section and kept the blank lines that set it off, leaving a 3-line hole in the CLAUDE.md bd init writes. installAgents then appended a re-added section after two blank lines, so every remove/re-add cycle grew the file. removeBeadsSection now drops the line breaks next to the section (never text): the surrounding text is rejoined with one blank line, or none if the section had none; a section at the top leaves no leading blank lines and one at the bottom leaves a single final line break. CRLF is preserved, and a marker sharing its line with text is still cut exactly. installAgents appends like bd init's updateAgentFile: ensure a final newline, then one blank line. remove(add(x)) == x for a file ending in a newline, and after the first remove, setup and --remove toggle between the same two files; a re-added section goes at the end. Goldens regenerated with BD_UPDATE_GOLDEN=1. Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-authored-by: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 8 ++ cmd/bd/setup/agents.go | 59 +++++++++---- cmd/bd/setup/agents_marker_test.go | 87 +++++++++++++++++++ cmd/bd/setup/factory_test.go | 36 +++++++- .../claude-setup-agents-import-stub.golden | 1 - .../claude-setup-existing-user-files.golden | 3 - .../setup/testdata/claude-setup-global.golden | 2 - .../claude-setup-legacy-local-settings.golden | 2 - .../claude-setup-project-stealth.golden | 2 - .../testdata/claude-setup-project.golden | 2 - .../agent_artifacts/init-default.golden | 5 -- docs/getting-started/ide-setup.md | 2 +- 12 files changed, 170 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e6bb0aee1..57c1c56ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -804,6 +804,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 with no `.local_version` witness. A pre-1.0 witness, or a `.beads/dolt` that holds anything, is still refused, and commands other than `bd init` are decided as before. +- **`bd setup claude --remove` no longer leaves a blank-line hole.** Removing + the beads section from `CLAUDE.md` (or, with the other setup recipes, from + `AGENTS.md` or `GEMINI.md`) left the blank lines around it behind, three in + the `CLAUDE.md` `bd init` writes, and setup then re-added the section after + two more, so every remove and re-add grew the file. `--remove` now takes + those blank lines with the section, and setup appends a section after one + blank line, so removing and re-adding it toggles between the same two files. + A re-added section goes at the end of the file. - **`bd show --as-of` exits 1 when it reads no issue.** A ref the Dolt AS OF read does not take (an instant, a versioned-history address), a ref that does not exist, or an issue that did not exist at the ref was reported on diff --git a/cmd/bd/setup/agents.go b/cmd/bd/setup/agents.go index 6c4ac09f4..f4ba12508 100644 --- a/cmd/bd/setup/agents.go +++ b/cmd/bd/setup/agents.go @@ -150,7 +150,14 @@ func installAgents(env agentsEnv, integration agentsIntegration) error { } _, _ = fmt.Fprintf(env.stdout, "✓ Updated existing beads section in %s\n", agentsFile) } else { - newContent := currentContent + "\n\n" + beadsSection + // Set the section off with one blank line, as bd init's + // updateAgentFile does, so that removeBeadsSection gives the + // file back as it was. + newContent := currentContent + if !strings.HasSuffix(newContent, "\n") { + newContent += "\n" + } + newContent += "\n" + beadsSection if err := atomicWriteFile(env.agentsPath, []byte(newContent)); err != nil { _, _ = fmt.Fprintf(env.stderr, "Error: write %s: %v\n", env.agentsPath, err) return err @@ -279,7 +286,17 @@ func updateBeadsSectionWithOpts(content string, profile agents.Profile, opts age return replaced } -// removeBeadsSection removes the beads section from content +// removeBeadsSection removes the beads section from content together with the +// blank lines that set it off, so removing it leaves no hole. Only line breaks +// next to the section are dropped, never text: the text before and after it is +// rejoined with one blank line if the section was set off by any (with none if +// it was not), a section at the top of the file leaves no leading blank lines, +// and one at the bottom leaves the file ending in a single line break. This +// undoes installAgents' append, so adding the section to a file and removing it +// gives the file back. +// +// A marker that shares its line with other text is cut out exactly, with the +// line break after the END marker, and nothing around it is touched. func removeBeadsSection(content string) string { start := findBeginMarker(content) end := strings.Index(content, agentsEndMarker) @@ -288,23 +305,31 @@ func removeBeadsSection(content string) string { return content } - // Remove exactly the managed section, including a single trailing newline - // immediately after the end marker if present. We intentionally do NOT trim - // surrounding whitespace or unrelated content to keep user file content intact. - endOfEndMarker := end + len(agentsEndMarker) - if endOfEndMarker < len(content) { - switch content[endOfEndMarker] { - case '\r': - endOfEndMarker++ - if endOfEndMarker < len(content) && content[endOfEndMarker] == '\n' { - endOfEndMarker++ - } - case '\n': - endOfEndMarker++ - } + before := content[:start] + after := content[end+len(agentsEndMarker):] + head := strings.TrimRight(before, "\r\n") + tail := strings.TrimLeft(after, "\r\n") + if (head != "" && head == before) || (tail != "" && tail == after) { + after = strings.TrimPrefix(after, "\r") + return before + strings.TrimPrefix(after, "\n") } - return content[:start] + content[endOfEndMarker:] + eol := "\n" + if strings.HasPrefix(before[len(head):], "\r\n") { + eol = "\r\n" + } + switch { + case head == "": + return tail + case tail == "": + return head + eol + case strings.Count(before[len(head):], "\n")+strings.Count(after[:len(after)-len(tail)], "\n") > 2: + // Besides the line break ending the line before the section and the + // one ending the END marker's line, there was a blank line. + return head + eol + eol + tail + default: + return head + eol + tail + } } // findBeginMarker returns the index of the BEGIN BEADS INTEGRATION marker in content, diff --git a/cmd/bd/setup/agents_marker_test.go b/cmd/bd/setup/agents_marker_test.go index 44bd699ad..f098dc75d 100644 --- a/cmd/bd/setup/agents_marker_test.go +++ b/cmd/bd/setup/agents_marker_test.go @@ -170,6 +170,93 @@ func TestInstallAgentsDefaultsToFullProfile(t *testing.T) { } } +// TestAgentsSectionRemoveReaddIsStable pins what --remove and a later setup +// leave behind: removing the section leaves no blank-line hole, setup appends +// it again after one blank line, and from then on each --remove and each setup +// leaves the same bytes, however often they alternate. A file the user wrote +// gets back what it held before setup added the section. +func TestAgentsSectionRemoveReaddIsStable(t *testing.T) { + stubDetectRenderOpts(t) + integration := agentsIntegration{ + name: "TestAgent", + setupCommand: "bd setup testagent", + profile: agents.ProfileMinimal, + } + section := agents.RenderSection(agents.ProfileMinimal) + scaffold := createNewAgentsFileWithProfile(agents.ProfileMinimal) + + tests := []struct { + name string + seed string // "" means setup creates the file + wantRemoved string + }{ + { + name: "file setup created", + wantRemoved: strings.Replace(scaffold, section+"\n\n", "", 1), + }, + { + name: "user file", + seed: "# My Project\n\nHouse rules live here.\n", + wantRemoved: "# My Project\n\nHouse rules live here.\n", + }, + { + name: "user file without a final newline", + seed: "# My Project", + wantRemoved: "# My Project\n", + }, + { + name: "user file ending in blank lines", + seed: "# My Project\n\n\n", + wantRemoved: "# My Project\n", + }, + { + name: "CRLF user file", + seed: "# My Project\r\n\r\nHouse rules live here.\r\n", + wantRemoved: "# My Project\r\n\r\nHouse rules live here.\r\n", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + env, _, _ := newFactoryTestEnv(t) + if tt.seed != "" { + if err := os.WriteFile(env.agentsPath, []byte(tt.seed), 0o644); err != nil { + t.Fatalf("seed: %v", err) + } + } + step := func(name string, run func(agentsEnv, agentsIntegration) error) string { + t.Helper() + if err := run(env, integration); err != nil { + t.Fatalf("%s: %v", name, err) + } + data, err := os.ReadFile(env.agentsPath) + if err != nil { + t.Fatalf("read after %s: %v", name, err) + } + return string(data) + } + + step("setup", installAgents) + removed := step("remove", removeAgents) + if removed != tt.wantRemoved { + t.Fatalf("after remove:\ngot: %q\nwant: %q", removed, tt.wantRemoved) + } + readded := step("setup again", installAgents) + if want := removed + "\n" + section; readded != want { + t.Fatalf("after setup again:\ngot: %q\nwant: %q", readded, want) + } + for cycle := 2; cycle <= 3; cycle++ { + if got := step("remove", removeAgents); got != removed { + t.Fatalf("remove #%d changed the result:\ngot: %q\nwant: %q", cycle, got, removed) + } + if got := step("setup", installAgents); got != readded { + t.Fatalf("setup #%d changed the result:\ngot: %q\nwant: %q", cycle+1, got, readded) + } + } + }) + } +} + // readFileBytes is a test helper to read file content func readFileBytes(path string) ([]byte, error) { return readFileBytesImpl(path) diff --git a/cmd/bd/setup/factory_test.go b/cmd/bd/setup/factory_test.go index 2af6c84b0..6c868750f 100644 --- a/cmd/bd/setup/factory_test.go +++ b/cmd/bd/setup/factory_test.go @@ -82,7 +82,6 @@ Beads content More content`, expected: `# My Project - More content`, }, { @@ -97,7 +96,6 @@ Beads content expected: `# My Project Content - `, }, { @@ -111,9 +109,39 @@ Content expected: "# My Project\n\nContent", }, { - name: "preserve surrounding whitespace and unrelated content", + name: "rejoin surrounding content with one blank line", content: "Header\n\n" + agents.EmbeddedBeadsSection() + "\n\nFooter\n", - expected: "Header\n\n\n\nFooter\n", + expected: "Header\n\nFooter\n", + }, + { + name: "remove section at top", + content: agents.EmbeddedBeadsSection() + "\n# My Project\n", + expected: "# My Project\n", + }, + { + name: "remove section from a new agents file", + content: createNewAgentsFile(), + expected: strings.Replace(createNewAgentsFile(), agents.RenderSection(agents.ProfileFull)+"\n\n", "", 1), + }, + { + name: "CRLF line endings", + content: "Header\r\n\r\n\r\nBeads content\r\n\r\n\r\nFooter\r\n", + expected: "Header\r\n\r\nFooter\r\n", + }, + { + name: "no blank line added where the section had none", + content: "Header\n\nBeads content\n\nFooter\n", + expected: "Header\nFooter\n", + }, + { + name: "marker sharing a line with text is cut exactly", + content: "Intro \nBeads content\n\n\nFooter\n", + expected: "Intro \nFooter\n", + }, + { + name: "file holding only the section becomes empty", + content: agents.EmbeddedBeadsSection(), + expected: "", }, } diff --git a/cmd/bd/setup/testdata/claude-setup-agents-import-stub.golden b/cmd/bd/setup/testdata/claude-setup-agents-import-stub.golden index 9b4337a80..68c99593c 100644 --- a/cmd/bd/setup/testdata/claude-setup-agents-import-stub.golden +++ b/cmd/bd/setup/testdata/claude-setup-agents-import-stub.golden @@ -46,7 +46,6 @@ Restart Claude Code for changes to take effect. Shared by every agent. - [managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal.md] diff --git a/cmd/bd/setup/testdata/claude-setup-existing-user-files.golden b/cmd/bd/setup/testdata/claude-setup-existing-user-files.golden index d81091fb8..a799c799f 100644 --- a/cmd/bd/setup/testdata/claude-setup-existing-user-files.golden +++ b/cmd/bd/setup/testdata/claude-setup-existing-user-files.golden @@ -101,7 +101,6 @@ Restart Claude Code for changes to take effect. House rules live here. - [managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal.md] @@ -162,8 +161,6 @@ Removing Claude Code integration... House rules live here. - - === bd setup claude --check result: error: claude hooks not installed --- stdout diff --git a/cmd/bd/setup/testdata/claude-setup-global.golden b/cmd/bd/setup/testdata/claude-setup-global.golden index da63d077c..c82e8df06 100644 --- a/cmd/bd/setup/testdata/claude-setup-global.golden +++ b/cmd/bd/setup/testdata/claude-setup-global.golden @@ -92,8 +92,6 @@ Removing Claude Code integration... This file provides instructions and context for AI coding agents working on this project. - - ## Build & Test _Add your build and test commands here_ diff --git a/cmd/bd/setup/testdata/claude-setup-legacy-local-settings.golden b/cmd/bd/setup/testdata/claude-setup-legacy-local-settings.golden index 1e17ea55a..96d9a5530 100644 --- a/cmd/bd/setup/testdata/claude-setup-legacy-local-settings.golden +++ b/cmd/bd/setup/testdata/claude-setup-legacy-local-settings.golden @@ -136,8 +136,6 @@ Removing Claude Code integration... This file provides instructions and context for AI coding agents working on this project. - - ## Build & Test _Add your build and test commands here_ diff --git a/cmd/bd/setup/testdata/claude-setup-project-stealth.golden b/cmd/bd/setup/testdata/claude-setup-project-stealth.golden index 71d62d8e6..6912f2bde 100644 --- a/cmd/bd/setup/testdata/claude-setup-project-stealth.golden +++ b/cmd/bd/setup/testdata/claude-setup-project-stealth.golden @@ -92,8 +92,6 @@ Removing Claude Code integration... This file provides instructions and context for AI coding agents working on this project. - - ## Build & Test _Add your build and test commands here_ diff --git a/cmd/bd/setup/testdata/claude-setup-project.golden b/cmd/bd/setup/testdata/claude-setup-project.golden index aa307d08f..90c7edbdc 100644 --- a/cmd/bd/setup/testdata/claude-setup-project.golden +++ b/cmd/bd/setup/testdata/claude-setup-project.golden @@ -112,8 +112,6 @@ Removing Claude Code integration... This file provides instructions and context for AI coding agents working on this project. - - ## Build & Test _Add your build and test commands here_ diff --git a/cmd/bd/testdata/agent_artifacts/init-default.golden b/cmd/bd/testdata/agent_artifacts/init-default.golden index 6d3929882..fa77b054b 100644 --- a/cmd/bd/testdata/agent_artifacts/init-default.golden +++ b/cmd/bd/testdata/agent_artifacts/init-default.golden @@ -171,8 +171,6 @@ Removing Claude Code integration... This file provides instructions and context for AI coding agents working on this project. - - ## Build & Test _Add your build and test commands here_ @@ -239,8 +237,6 @@ Restart Claude Code for changes to take effect. This file provides instructions and context for AI coding agents working on this project. - - ## Build & Test _Add your build and test commands here_ @@ -259,7 +255,6 @@ _Add a brief overview of your project architecture_ _Add your project-specific conventions here_ - [managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal-no-remote.md] diff --git a/docs/getting-started/ide-setup.md b/docs/getting-started/ide-setup.md index 4eea8a09e..bbd5b8ec4 100644 --- a/docs/getting-started/ide-setup.md +++ b/docs/getting-started/ide-setup.md @@ -78,7 +78,7 @@ BD_AGENT_PROFILE=team-maintainer bd prime ### Managed Sections -`bd setup factory`, `bd setup mux`, and `bd setup opencode` append a beads section to `AGENTS.md`, wrapped in `BEGIN/END BEADS INTEGRATION` HTML-comment markers. The begin marker carries version, profile, and hash metadata (e.g. ``) so `--check` can report `missing`, `stale`, or `current`; legacy markers without metadata are auto-upgraded on the next install or update. Re-running setup updates the existing section in place (idempotent), and `--remove` deletes only the managed section — the rest of your `AGENTS.md` is untouched. +`bd setup factory`, `bd setup mux`, and `bd setup opencode` append a beads section to `AGENTS.md`, wrapped in `BEGIN/END BEADS INTEGRATION` HTML-comment markers. The begin marker carries version, profile, and hash metadata (e.g. ``) so `--check` can report `missing`, `stale`, or `current`; legacy markers without metadata are auto-upgraded on the next install or update. Re-running setup updates the existing section in place (idempotent), and `--remove` deletes only the managed section and the blank lines that set it off — the rest of your `AGENTS.md` is untouched. Running setup again after `--remove` appends the section to the end of the file after one blank line, so removing and re-adding it toggles between the same two files. The section `bd setup claude` and `bd setup gemini` manage in `CLAUDE.md` and `GEMINI.md` behaves the same way. `bd setup codex` uses its own marker pair (`BEGIN/END BEADS CODEX SETUP`). Running it alongside `bd setup factory` or `bd setup mux` against the same `AGENTS.md` leaves two managed sections side by side; each recipe's `--check` inspects only its own section, and each `--remove` removes only its own section.