fix(setup): leave a current agents-file beads section untouched (#7693)

* fix(setup): leave a current agents-file beads section untouched

installAgents rewrote the instructions file whenever it found a beads
marker, discarding ReplaceSectionWithOpts' changed flag and error. A rerun
of `bd setup claude` (and `bd init`, which runs it) replaced a byte-identical
CLAUDE.md with a new file (new inode, fresh mtime, mode reset to 0644) and
reported "Updated existing beads section", while bd init's updateAgentFile
reported AGENTS.md current in the same run. A section whose END marker was
lost or came before BEGIN was likewise "updated" without change.

Mirror updateAgentFile: write only when the section changes, report
"<file> already has the current beads section" otherwise, and return
ErrMalformedMarkers instead of rewriting. claude/gemini warn and continue;
factory/opencode/mux fail (mux before installing its .mux hooks), per their
existing error policies. Tests pin inode, mode and mtime of the untouched
file and the claude/mux policies for both malformed-marker shapes. Goldens
updated for the new rerun message.

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>

* fix(setup): keep CLAUDE.md's beads block when the AGENTS.md update fails

When CLAUDE.md is an @AGENTS.md stub that still holds a beads block,
installClaude strips that block once the redirect is active, gated only on
installAgents not having skipped a symlinked AGENTS.md. It ignored
installAgents' error, so now that installAgents returns ErrMalformedMarkers
instead of writing a malformed AGENTS.md back, the strip deleted the stub's
block while AGENTS.md kept no usable section, and the warning named
CLAUDE.md. Base had the same end state behind a false "Updated" report; the
new error is what makes the failure detectable, so the gate belongs here.

Gate the strip on a nil installAgents error too, so it runs only once
AGENTS.md holds the current section (written now or already current), and
name the file that failed in the warning (AGENTS.md when redirected). A
redirect subtest in TestInstallClaudeWarnsOnMalformedMarkers pins both, for
both malformed shapes: dropping the gate reds it on CLAUDE.md's content,
inode, mtime and mode, and naming CLAUDE.md again reds it on the warning.

Also correct updateBeadsSectionWithProfile's doc comment, which claimed an
error string it never returned: it returns the content unchanged when the
section cannot be replaced. The CHANGELOG entry notes the redirect case.

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>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
This commit is contained in:
Julian Knutsen 2026-10-19 08:45:04 +00:00 • committed by GitHub
commit 9893f9020d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 251 additions and 15 deletions

View file

@ -826,6 +826,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
older bd registered. The hooks are still migrated to the SessionStart
`bd prime --hook-json` hook; the removal lines now go to the installer's own
output, which `--quiet` discards, instead of straight to stdout.
- **`bd setup claude` no longer rewrites a CLAUDE.md whose beads section is
already current.** A rerun (and `bd init`, which runs it) wrote the same
bytes back as a new file, resetting its mode to 0644 and its mtime, and
reported "Updated existing beads section"; it now leaves the file alone and
reports the section current (the report `bd init` already gives a current
AGENTS.md). `bd setup factory`, `opencode`, `mux` and `gemini` share the
fix. A section whose END marker is missing or comes before BEGIN, which was
also reported as updated while nothing changed, is now reported as an error:
`bd setup factory`, `opencode` and `mux` exit 1 (`mux` before installing its
`.mux` hooks), while `claude` and `gemini` warn and carry on. When CLAUDE.md
is an `@AGENTS.md` stub and it is AGENTS.md that cannot be updated, `claude`
now names AGENTS.md in the warning and keeps the beads block left in the
stub, which it used to delete although AGENTS.md was never updated.
- **Time-bound filters and the keyset cursor compare the same instant on every
engine, whatever zone they are given in.** The storage filter builder binds
every time bound (`created_*`, `updated_*`, `closed_*`, `started_*`,

View file

@ -143,12 +143,22 @@ func installAgents(env agentsEnv, integration agentsIntegration) error {
if currentContent != "" {
if containsBeadsMarker(currentContent) {
newContent := updateBeadsSectionWithOpts(currentContent, profile, opts)
if err := atomicWriteFile(env.agentsPath, []byte(newContent)); err != nil {
_, _ = fmt.Fprintf(env.stderr, "Error: write %s: %v\n", env.agentsPath, err)
// Like bd init's updateAgentFile: write only when the section
// actually changes, so a rerun leaves a current file alone.
newContent, changed, err := agents.ReplaceSectionWithOpts(currentContent, profile, opts)
switch {
case err != nil:
_, _ = fmt.Fprintf(env.stderr, "Error: failed to update beads section in %s: %v\n", env.agentsPath, err)
return err
case !changed:
_, _ = fmt.Fprintf(env.stdout, "✓ %s already has the current beads section\n", agentsFile)
default:
if err := atomicWriteFile(env.agentsPath, []byte(newContent)); err != nil {
_, _ = fmt.Fprintf(env.stderr, "Error: write %s: %v\n", env.agentsPath, err)
return err
}
_, _ = fmt.Fprintf(env.stdout, "✓ Updated existing beads section in %s\n", agentsFile)
}
_, _ = fmt.Fprintf(env.stdout, "✓ Updated existing beads section in %s\n", agentsFile)
} else {
// Set the section off with one blank line, as bd init's
// updateAgentFile does, so that removeBeadsSection gives the
@ -271,8 +281,10 @@ func updateBeadsSection(content string) string {
}
// updateBeadsSectionWithProfile replaces the beads section with the given profile.
// Delegates to the canonical agents.ReplaceSection. Returns an error string on
// malformed markers (logged by callers) instead of silently appending.
// Delegates to the canonical agents.ReplaceSection. When the section cannot be
// replaced (no BEGIN marker, or malformed markers) it returns content unchanged
// and reports nothing; a caller that must report that calls
// agents.ReplaceSectionWithOpts directly, as installAgents does.
func updateBeadsSectionWithProfile(content string, profile agents.Profile) string {
return updateBeadsSectionWithOpts(content, profile, agents.DefaultRenderOpts())
}

View file

@ -5,8 +5,10 @@ import (
"errors"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/templates/agents"
)
@ -528,3 +530,210 @@ func TestLegacyToNewMigrationViaInstall(t *testing.T) {
t.Error("surrounding content should be preserved")
}
}
// seedAgentsFileWithOldMtime writes content to path with mode 0600 and
// backdates it, so a test can tell whether installAgents rewrote it:
// atomicWriteFile replaces the file with a new one (new inode, fresh mtime,
// mode 0644).
func seedAgentsFileWithOldMtime(t *testing.T, path, content string) os.FileInfo {
t.Helper()
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatalf("seed %s: %v", path, err)
}
if err := os.Chmod(path, 0o600); err != nil {
t.Fatalf("chmod %s: %v", path, err)
}
old := time.Date(2001, 2, 3, 4, 5, 6, 0, time.UTC)
if err := os.Chtimes(path, old, old); err != nil {
t.Fatalf("backdate %s: %v", path, err)
}
info, err := os.Stat(path)
if err != nil {
t.Fatalf("stat %s: %v", path, err)
}
return info
}
// assertAgentsFileUntouched fails if path no longer holds content, or was
// rewritten since seedAgentsFileWithOldMtime returned seed: replaced by a new
// file, given a new mtime, or had its mode reset.
func assertAgentsFileUntouched(t *testing.T, path, content string, seed os.FileInfo) {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
if string(data) != content {
t.Errorf("%s changed:\n got: %q\nwant: %q", path, data, content)
}
info, err := os.Stat(path)
if err != nil {
t.Fatalf("stat %s: %v", path, err)
}
if !os.SameFile(seed, info) {
t.Errorf("%s was replaced by a new file (inode changed)", path)
}
if !info.ModTime().Equal(seed.ModTime()) {
t.Errorf("%s was rewritten: mtime %v, want %v", path, info.ModTime(), seed.ModTime())
}
if runtime.GOOS != "windows" && info.Mode().Perm() != 0o600 {
t.Errorf("%s mode = %o, want 0600", path, info.Mode().Perm())
}
}
// A rerun of bd setup on a file whose beads section is already current must
// leave the file alone and say so, as bd init's updateAgentFile does. It used
// to write the same bytes back (fresh mtime, new inode, mode reset to 0644)
// and report "Updated existing beads section".
func TestInstallAgentsLeavesCurrentSectionUntouched(t *testing.T) {
stubDetectRenderOpts(t)
tests := []struct {
name string
installed agents.Profile
requested agents.Profile
}{
{name: "same profile", installed: agents.ProfileMinimal, requested: agents.ProfileMinimal},
{name: "full profile kept for a minimal integration", installed: agents.ProfileFull, requested: agents.ProfileMinimal},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
env, stdout, stderr := newFactoryTestEnv(t)
content := "# My Project\n\n" + agents.RenderSection(tt.installed) + "\n## Notes\n"
seed := seedAgentsFileWithOldMtime(t, env.agentsPath, content)
integration := agentsIntegration{name: "TestAgent", setupCommand: "bd setup testagent", profile: tt.requested}
if err := installAgents(env, integration); err != nil {
t.Fatalf("installAgents: %v", err)
}
assertAgentsFileUntouched(t, env.agentsPath, content, seed)
out := stdout.String()
if !strings.Contains(out, "✓ AGENTS.md already has the current beads section\n") {
t.Errorf("expected the section to be reported current, got:\n%s", out)
}
if strings.Contains(out, "Updated existing beads section") {
t.Errorf("reported an update to a file it left unchanged:\n%s", out)
}
if stderr.Len() != 0 {
t.Errorf("unexpected stderr: %s", stderr.String())
}
})
}
}
// malformedMarkerContents are agents-file contents whose beads section cannot
// be replaced: the END marker is missing, or comes before BEGIN.
var malformedMarkerContents = []struct {
name string
content string
}{
{
name: "missing END marker",
content: "# My Project\n\n<!-- BEGIN BEADS INTEGRATION v:1 profile:full hash:00000000 -->\nOlder guidance; its END marker was lost.\n",
},
{
name: "END before BEGIN",
content: "# My Project\n\n<!-- END BEADS INTEGRATION -->\nStray text.\n<!-- BEGIN BEADS INTEGRATION v:1 profile:full hash:00000000 -->\nOlder guidance.\n",
},
}
// A section with malformed markers cannot be replaced. installAgents used to
// write the file back unchanged and report "Updated existing beads section";
// like bd init's updateAgentFile it now leaves the file alone and returns the
// error.
func TestInstallAgentsReportsMalformedMarkers(t *testing.T) {
stubDetectRenderOpts(t)
for _, tt := range malformedMarkerContents {
t.Run(tt.name, func(t *testing.T) {
env, stdout, stderr := newFactoryTestEnv(t)
seed := seedAgentsFileWithOldMtime(t, env.agentsPath, tt.content)
integration := agentsIntegration{name: "TestAgent", setupCommand: "bd setup testagent", profile: agents.ProfileFull}
err := installAgents(env, integration)
if !errors.Is(err, agents.ErrMalformedMarkers) {
t.Fatalf("installAgents error = %v, want %v", err, agents.ErrMalformedMarkers)
}
assertAgentsFileUntouched(t, env.agentsPath, tt.content, seed)
if strings.Contains(stdout.String(), "Updated existing beads section") {
t.Errorf("reported an update to a file it could not update:\n%s", stdout.String())
}
if !strings.Contains(stderr.String(), "malformed beads section markers") {
t.Errorf("expected the malformed markers on stderr, got: %q", stderr.String())
}
})
}
}
// bd setup claude treats a CLAUDE.md it cannot update as non-fatal: hooks are
// already installed, so it warns and returns nil, leaving the file alone.
// When CLAUDE.md is an @AGENTS.md stub, the file it cannot update is AGENTS.md,
// and the beads block still in the stub must stay: stripping it is safe only
// once AGENTS.md holds the current section.
func TestInstallClaudeWarnsOnMalformedMarkers(t *testing.T) {
stubDetectRenderOpts(t)
for _, tt := range malformedMarkerContents {
t.Run(tt.name, func(t *testing.T) {
env, stdout, stderr := newClaudeTestEnv(t)
claudePath := filepath.Join(env.projectDir, claudeInstructionsFile)
seed := seedAgentsFileWithOldMtime(t, claudePath, tt.content)
if err := installClaude(env, false, false); err != nil {
t.Fatalf("installClaude returned error: %v", err)
}
assertAgentsFileUntouched(t, claudePath, tt.content, seed)
if strings.Contains(stdout.String(), "Updated existing beads section") {
t.Errorf("reported an update to a file it could not update:\n%s", stdout.String())
}
if !strings.Contains(stderr.String(), "Warning: failed to update "+claudeInstructionsFile) {
t.Errorf("expected a non-fatal warning on stderr, got: %q", stderr.String())
}
})
t.Run(tt.name+" in the redirected AGENTS.md", func(t *testing.T) {
env, stdout, stderr := newClaudeTestEnv(t)
claudePath := filepath.Join(env.projectDir, claudeInstructionsFile)
claudeContent := staleClaudeStubWithBlock()
claudeSeed := seedAgentsFileWithOldMtime(t, claudePath, claudeContent)
agentsPath := filepath.Join(env.projectDir, "AGENTS.md")
agentsSeed := seedAgentsFileWithOldMtime(t, agentsPath, tt.content)
if err := installClaude(env, false, false); err != nil {
t.Fatalf("installClaude returned error: %v", err)
}
assertAgentsFileUntouched(t, agentsPath, tt.content, agentsSeed)
// AGENTS.md was not updated, so the stub's block is the only
// well-formed beads section the project has.
assertAgentsFileUntouched(t, claudePath, claudeContent, claudeSeed)
if strings.Contains(stdout.String(), "Removed stale beads block") {
t.Errorf("reported stripping %s although AGENTS.md was not updated:\n%s", claudeInstructionsFile, stdout.String())
}
if !strings.Contains(stderr.String(), "Warning: failed to update AGENTS.md") {
t.Errorf("expected the warning to name AGENTS.md, the file that failed, got: %q", stderr.String())
}
})
}
}
// bd setup mux fails on an AGENTS.md it cannot update, before installing its
// .mux hooks.
func TestInstallMuxFailsOnMalformedMarkers(t *testing.T) {
stubDetectRenderOpts(t)
for _, tt := range malformedMarkerContents {
t.Run(tt.name, func(t *testing.T) {
env, _, _ := newFactoryTestEnv(t)
seed := seedAgentsFileWithOldMtime(t, env.agentsPath, tt.content)
err := installMux(env, false, false)
if !errors.Is(err, agents.ErrMalformedMarkers) {
t.Fatalf("installMux error = %v, want %v", err, agents.ErrMalformedMarkers)
}
assertAgentsFileUntouched(t, env.agentsPath, tt.content, seed)
if _, statErr := os.Stat(muxProjectDir(env.agentsPath)); !os.IsNotExist(statErr) {
t.Errorf("expected no .mux hooks directory, stat err = %v", statErr)
}
})
}
}

View file

@ -345,16 +345,18 @@ func installClaude(env claudeEnv, global bool, stealth bool) error {
agentsEnv, redirected := claudeAgentsEnvRedirect(env)
agentsSkipped := false
agentsEnv.skipped = &agentsSkipped
if err := installAgents(agentsEnv, claudeAgentsIntegration); err != nil {
agentsErr := installAgents(agentsEnv, claudeAgentsIntegration)
if agentsErr != nil {
// Non-fatal: hooks are already installed
_, _ = fmt.Fprintf(env.stderr, "Warning: failed to update %s: %v\n", claudeInstructionsFile, err)
_, _ = fmt.Fprintf(env.stderr, "Warning: failed to update %s: %v\n", agentsFileName(agentsEnv.agentsPath), agentsErr)
}
// Only strip the stale CLAUDE.md block once the redirect has actually
// written the replacement to AGENTS.md. If installAgents skipped injection
// (e.g. AGENTS.md is a symlink), stripping here would delete-before-write
// and leave the project with no beads section anywhere.
if redirected && !agentsSkipped {
// Only strip the stale CLAUDE.md block once AGENTS.md holds the current
// section (written now or already current). If installAgents skipped
// injection (e.g. AGENTS.md is a symlink) or failed (e.g. its markers are
// malformed), stripping here would delete-before-write and leave the
// project with no beads section anywhere.
if redirected && agentsErr == nil && !agentsSkipped {
if err := stripStaleClaudeBlock(env); err != nil {
// Non-fatal: the redirect itself already succeeded above
_, _ = fmt.Fprintf(env.stderr, "Warning: failed to clean stale beads block from %s: %v\n", claudeInstructionsFile, err)

View file

@ -79,7 +79,7 @@ result: ok
Installing Claude hooks for this project...
✓ Hook already registered: SessionStart
Installing Claude Code integration...
✓ Updated existing beads section in CLAUDE.md
✓ CLAUDE.md already has the current beads section
✓ Claude Code integration installed
File: $ROOT/project/CLAUDE.md

View file

@ -138,7 +138,7 @@ exit: 0
Installing Claude hooks for this project...
✓ Hook already registered: SessionStart
Installing Claude Code integration...
✓ Updated existing beads section in CLAUDE.md
✓ CLAUDE.md already has the current beads section
✓ Claude Code integration installed
File: $PROJECT/CLAUDE.md