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) <noreply@anthropic.com>
This commit is contained in:
Julian Knutsen 2026-10-19 08:28:18 +00:00 • committed by GitHub
commit ee441fdc73
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 170 additions and 39 deletions

View file

@ -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

View file

@ -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,

View file

@ -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)

View file

@ -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<!-- BEGIN BEADS INTEGRATION -->\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<!-- BEGIN BEADS INTEGRATION -->\r\nBeads content\r\n<!-- END BEADS INTEGRATION -->\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<!-- BEGIN BEADS INTEGRATION -->\nBeads content\n<!-- END BEADS INTEGRATION -->\nFooter\n",
expected: "Header\nFooter\n",
},
{
name: "marker sharing a line with text is cut exactly",
content: "Intro <!-- BEGIN BEADS INTEGRATION -->\nBeads content\n<!-- END BEADS INTEGRATION -->\n\nFooter\n",
expected: "Intro \nFooter\n",
},
{
name: "file holding only the section becomes empty",
content: agents.EmbeddedBeadsSection(),
expected: "",
},
}

View file

@ -46,7 +46,6 @@ Restart Claude Code for changes to take effect.
Shared by every agent.
<!-- BEGIN BEADS INTEGRATION v:1 profile:minimal hash:6ffdf896 -->
[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal.md]
<!-- END BEADS INTEGRATION -->

View file

@ -101,7 +101,6 @@ Restart Claude Code for changes to take effect.
House rules live here.
<!-- BEGIN BEADS INTEGRATION v:1 profile:minimal hash:6ffdf896 -->
[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal.md]
<!-- END BEADS INTEGRATION -->
@ -162,8 +161,6 @@ Removing Claude Code integration...
House rules live here.
=== bd setup claude --check
result: error: claude hooks not installed
--- stdout

View file

@ -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_

View file

@ -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_

View file

@ -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_

View file

@ -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_

View file

@ -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_
<!-- BEGIN BEADS INTEGRATION v:1 profile:minimal hash:cdcea925 -->
[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal-no-remote.md]
<!-- END BEADS INTEGRATION -->

View file

@ -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. `<!-- BEGIN BEADS INTEGRATION v:1 profile:full hash:19cc25d9 -->`) 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. `<!-- BEGIN BEADS INTEGRATION v:1 profile:full hash:19cc25d9 -->`) 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.