beads/cmd/bd/setup/agents.go
Julian Knutsen 1de9b59324
fix(setup): bd setup claude --global manages the section in ~/.claude/CLAUDE.md, not the current directory (#7696)
* fix(setup): keep bd setup claude --global's section in ~/.claude/CLAUDE.md

bd setup claude --global put its hook in ~/.claude/settings.json but wrote
the managed beads section into the current directory's CLAUDE.md, and
--remove --global stripped it from there. Run from $HOME it created
~/CLAUDE.md with project scaffolding, which stops Claude Code reading
AGENTS.md in projects below it; run inside a project it removed the
section that project's own install had written, leaving its hooks.

A global install and removal now manage the section in Claude Code's
user-level ~/.claude/CLAUDE.md (created holding only the section, no
project scaffolding), with hints naming bd setup claude --global. With
global or plugin hooks, --check reports that file when the project's
instructions have no beads section; a project install is still judged
on the project's file alone. Project installs are unchanged.

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): render the user-level CLAUDE.md section independently of the project

~/.claude/CLAUDE.md is shared by every project, but bd setup claude --global
rendered and --check judged its section with the current directory's beads
config (sync.remote, sync.git-remote, no-push). From a project with a remote
and one without, --check called the other's install stale and its hint
flipped the file back. The user-level file now always renders with the
default options, so install and --check agree across projects.

Also pin --check's fallback to the project's file and project hint when
neither file has a section, tell existing --global users to re-run it, and
name ~/.claude/CLAUDE.md in the ide-setup recipe table.

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): judge the user-level Claude files from $HOME and ~/.claude

Run from the home directory, the project's .claude/settings.json is the
global one, so bd setup claude --check reported a global install as project
hooks and judged ~/CLAUDE.md; its "Run: bd setup claude" hint then created
the ~/CLAUDE.md a global install exists to avoid. Run from ~/.claude, the
project's CLAUDE.md is the user-level file, and --check judged it with that
directory's render options and the project hint.

--check now reports hooks as global from $HOME and judges the user-level
file there and from ~/.claude with the fixed options and the --global hint.
With user-level hooks and no section in either file it names --global
unless the project has its own CLAUDE.md. A --remove run from $HOME, which
removes the global hooks, also removes the user-level section.

The init agent-artifact test ran bd setup claude with HOME at the project,
so its checks would now see a home directory; it gets a separate HOME and
its goldens are unchanged.

Rebase note (maintainer): rebased onto main after #7678 merged; main's
agent-artifact harness already runs bd with a separate HOME, so this
commit's harness edits to cmd/bd/agent_artifacts_embedded_test.go were
dropped.

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>

* test(setup): pin --check's user-level choice beside project instructions

With global hooks, --check judges ~/.claude/CLAUDE.md when the project's
own CLAUDE.md has no beads section but the user-level file has one, and
when run from the home directory whose ~/CLAUDE.md has no section. Nothing
exercised either half of that condition: replacing it with false left the
suite and goldens green. Add a subtest for each; each now fails when its
half of the condition is dropped.

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): name --global when --check finds no hooks from $HOME

From the home directory --check with no hooks said 'Run: bd setup claude'.
Following it runs a project install there, which creates ~/CLAUDE.md with
project scaffolding, the file that stops Claude Code reading AGENTS.md in
the projects below it. The missing-section hint at home already names
--global; make the missing-hooks hint match, with a subtest.

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>

* docs(setup): qualify the --global CHANGELOG entry; watch ~/.claude/CLAUDE.md

The CHANGELOG said --check from the home directory judges the user-level
files, but a beads section still in ~/CLAUDE.md is judged instead, and
the --global hint for a missing section applies only when the project has
no CLAUDE.md of its own. Say both, mention the new missing-hooks hint at
home, and re-wrap the paragraph.

The embedded agent-artifact harness comment said a global install writes
$HOME/CLAUDE.md; it now writes $HOME/.claude/CLAUDE.md. Track that path
too and reword the comment. The bd init goldens do not change.

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): word the user-level CLAUDE.md section for repositories that use beads

bd setup claude --global writes its section to ~/.claude/CLAUDE.md, which
Claude Code loads in every project, but rendered it with the project
wording: "This project uses bd (beads)" and "Use bd for ALL task tracking —
do NOT use TodoWrite". In a repository without beads that told the agent to
give up its own task tools and pointed it at bd, whose answer there is
"run 'bd init'", while the global hook, bd prime, stays silent outside a
workspace.

RenderOpts.UserLevel rewords the opening line and the task-tracking rules of
both profiles so they apply only in beads repositories. The global env fixes
it through agents.UserLevelRenderOpts, so install, in-place update and
--check agree on the hash from every directory, and a project-worded section
left in ~/.claude/CLAUDE.md reads as stale and is reworded by --global. The
new minimal-user and full-user variants are pinned by golden and hash; the
project rendering is unchanged.

Also pin sameDir's symlink following: --check from a symlink to $HOME or to
~/.claude still judges the user-level files.

Refreshed onto main past #7692, whose --remove takes the blank lines
around the section with it and whose setup appends a section after one
blank line: claude-setup-global-beside-project-install.golden no longer
records the old hole (an extra blank line before the appended section,
two left behind by --remove --global).

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>
2026-10-19 12:22:04 +00:00

431 lines
15 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package setup
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/templates/agents"
)
// readFileBytesImpl is used in tests; avoids import cycle.
var readFileBytesImpl = os.ReadFile
// AGENTS.md integration markers for beads section
const (
agentsBeginMarker = "<!-- BEGIN BEADS INTEGRATION -->"
agentsEndMarker = "<!-- END BEADS INTEGRATION -->"
)
var (
errAgentsFileMissing = errors.New("agents file not found")
errBeadsSectionMissing = errors.New("beads section missing")
errBeadsSectionStale = errors.New("beads section is stale")
)
const muxAgentInstructionsURL = "https://mux.coder.com/AGENTS.md"
type agentsEnv struct {
agentsPath string
stdout io.Writer
stderr io.Writer
skipped *bool
// sectionOnly creates a missing or empty file holding only the managed
// section, without the project scaffolding createNewAgentsFileWithOpts
// adds. For user-level files, which apply to every project.
sectionOnly bool
// renderOpts, when set, fixes the render options instead of detecting
// them from the current directory's beads config. For user-level files,
// which every project shares, so install and --check agree everywhere.
renderOpts func() agents.RenderOpts
}
func (env agentsEnv) resolveRenderOpts() agents.RenderOpts {
if env.renderOpts != nil {
return env.renderOpts()
}
return detectRenderOpts()
}
type agentsIntegration struct {
name string
setupCommand string
readHint string
docsURL string
profile agents.Profile // "full" or "minimal"; empty defaults to "full"
}
func defaultAgentsEnv() agentsEnv {
return agentsEnv{
agentsPath: config.SafeAgentsFile(),
stdout: os.Stdout,
stderr: os.Stderr,
}
}
// detectRenderOptsImpl checks whether a Dolt sync remote is configured and returns
// appropriate RenderOpts. When no remote is configured, the rendered template
// omits "bd dolt push" from session-completion instructions.
// Exposed as a variable so tests can override.
var detectRenderOptsImpl = func() agents.RenderOpts {
return agents.RenderOpts{
HasRemote: config.GetString("sync.remote") != "" || config.GetString("sync.git-remote") != "",
NoPush: config.GetBool("no-push"),
}
}
func detectRenderOpts() agents.RenderOpts {
return detectRenderOptsImpl()
}
// containsBeadsMarker returns true if content contains a BEGIN BEADS INTEGRATION marker
// (either legacy or new format with metadata).
func containsBeadsMarker(content string) bool {
return strings.Contains(content, "<!-- BEGIN BEADS INTEGRATION")
}
// resolveProfile returns the integration's profile, defaulting to full.
func resolveProfile(integration agentsIntegration) agents.Profile {
if integration.profile != "" {
return integration.profile
}
return agents.ProfileFull
}
func agentsFileName(path string) string {
base := filepath.Base(path)
if base == "" || base == "." {
return path
}
return base
}
func (env agentsEnv) markSkipped() {
if env.skipped != nil {
*env.skipped = true
}
}
func installAgents(env agentsEnv, integration agentsIntegration) error {
_, _ = fmt.Fprintf(env.stdout, "Installing %s integration...\n", integration.name)
agentsFile := agentsFileName(env.agentsPath)
// Never inject managed sections through symlinks. Following symlink targets
// can unexpectedly mutate other instruction files and, in some workflows,
// corrupt tracked symlink entries.
if info, err := os.Lstat(env.agentsPath); err == nil && info.Mode()&os.ModeSymlink != 0 {
target, readErr := os.Readlink(env.agentsPath)
targetHint := ""
if readErr == nil && target != "" {
targetHint = fmt.Sprintf(" to %s", target)
}
_, _ = fmt.Fprintf(env.stderr, "Warning: %s is a symlink%s; skipping managed section injection to preserve link mode/content. Update the target file directly, or replace the symlink with a regular file and re-run '%s'.\n", agentsFile, targetHint, integration.setupCommand)
env.markSkipped()
return nil
} else if err != nil && !os.IsNotExist(err) {
_, _ = fmt.Fprintf(env.stderr, "Error: failed to inspect %s: %v\n", env.agentsPath, err)
return err
}
profile := resolveProfile(integration)
opts := env.resolveRenderOpts()
var currentContent string
data, err := os.ReadFile(env.agentsPath) // #nosec G304 -- env.agentsPath is trusted setup destination
if err == nil {
currentContent = string(data)
} else if !os.IsNotExist(err) {
_, _ = fmt.Fprintf(env.stderr, "Error: failed to read %s: %v\n", env.agentsPath, err)
return err
}
// Profile precedence: if the file already has a full profile and we're
// requesting minimal, preserve full to avoid information loss (e.g. when
// CLAUDE.md is a symlink to AGENTS.md and both Claude and Codex target it).
if currentContent != "" && containsBeadsMarker(currentContent) {
existingProfile := existingBeadsProfile(currentContent)
if existingProfile == agents.ProfileFull && profile == agents.ProfileMinimal {
_, _ = fmt.Fprintf(env.stdout, " ℹ File already has full profile; preserving (higher-information) content\n")
profile = agents.ProfileFull
}
}
beadsSection := agents.RenderSectionWithOpts(profile, opts)
if currentContent != "" {
if containsBeadsMarker(currentContent) {
// 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)
}
} else {
// 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
}
_, _ = fmt.Fprintf(env.stdout, "✓ Added beads section to existing %s\n", agentsFile)
}
} else {
newContent := createNewAgentsFileWithOpts(profile, opts)
if env.sectionOnly {
newContent = beadsSection
}
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, "✓ Created new %s with beads integration\n", agentsFile)
}
_, _ = fmt.Fprintf(env.stdout, "\n✓ %s integration installed\n", integration.name)
_, _ = fmt.Fprintf(env.stdout, " File: %s\n", env.agentsPath)
if integration.readHint != "" {
_, _ = fmt.Fprintf(env.stdout, "\n%s\n", integration.readHint)
}
if integration.docsURL != "" {
_, _ = fmt.Fprintf(env.stdout, "Review guide: %s\n", integration.docsURL)
}
_, _ = fmt.Fprintln(env.stdout, "No additional configuration needed!")
return nil
}
func checkAgents(env agentsEnv, integration agentsIntegration) error {
agentsFile := agentsFileName(env.agentsPath)
data, err := os.ReadFile(env.agentsPath)
if os.IsNotExist(err) {
_, _ = fmt.Fprintf(env.stdout, "✗ %s not found\n", agentsFile)
_, _ = fmt.Fprintf(env.stdout, " Run: %s\n", integration.setupCommand)
return errAgentsFileMissing
} else if err != nil {
_, _ = fmt.Fprintf(env.stderr, "Error: failed to read %s: %v\n", env.agentsPath, err)
return err
}
content := string(data)
if !containsBeadsMarker(content) {
_, _ = fmt.Fprintf(env.stdout, "⚠ %s exists but no beads section found\n", agentsFile)
_, _ = fmt.Fprintf(env.stdout, " Run: %s (to add beads section)\n", integration.setupCommand)
return errBeadsSectionMissing
}
// Section exists — check freshness via profile and hash
profile := resolveProfile(integration)
existingProf := existingBeadsProfile(content)
// Extract hash from marker
idx := findBeginMarker(content)
line := content[idx:]
if nl := strings.Index(line, "\n"); nl != -1 {
line = line[:nl]
}
meta := agents.ParseMarker(line)
checkProfile := profile
if profile == agents.ProfileMinimal && existingProf == agents.ProfileFull {
// Accept full profile as current when a minimal integration targets the same
// file (typically via symlinks like CLAUDE.md -> AGENTS.md).
checkProfile = agents.ProfileFull
}
currentHash := agents.CurrentHashWithOpts(checkProfile, env.resolveRenderOpts())
if meta != nil && meta.Hash == currentHash && existingProf == checkProfile {
_, _ = fmt.Fprintf(env.stdout, "✓ %s integration installed: %s (current)\n", integration.name, env.agentsPath)
return nil
}
// Stale or legacy section
_, _ = fmt.Fprintf(env.stdout, "⚠ %s integration installed but stale: %s\n", integration.name, env.agentsPath)
_, _ = fmt.Fprintf(env.stdout, " Run: %s (to update)\n", integration.setupCommand)
return errBeadsSectionStale
}
func removeAgents(env agentsEnv, integration agentsIntegration) error {
_, _ = fmt.Fprintf(env.stdout, "Removing %s integration...\n", integration.name)
agentsFile := agentsFileName(env.agentsPath)
data, err := os.ReadFile(env.agentsPath)
if os.IsNotExist(err) {
_, _ = fmt.Fprintf(env.stdout, "No %s file found\n", agentsFile)
return nil
} else if err != nil {
_, _ = fmt.Fprintf(env.stderr, "Error: failed to read %s: %v\n", env.agentsPath, err)
return err
}
content := string(data)
if !containsBeadsMarker(content) {
_, _ = fmt.Fprintf(env.stdout, "No beads section found in %s\n", agentsFile)
return nil
}
newContent := removeBeadsSection(content)
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, "✓ Removed beads section from %s\n", agentsFile)
return nil
}
// updateBeadsSection replaces the beads section in existing content using the full profile.
// Kept for backward compatibility with existing callers and tests.
func updateBeadsSection(content string) string {
return updateBeadsSectionWithProfile(content, agents.ProfileFull)
}
// updateBeadsSectionWithProfile replaces the beads section with the given profile.
// 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())
}
// updateBeadsSectionWithOpts replaces the beads section with the given profile and render opts.
func updateBeadsSectionWithOpts(content string, profile agents.Profile, opts agents.RenderOpts) string {
replaced, _, err := agents.ReplaceSectionWithOpts(content, profile, opts)
if err != nil {
return content
}
return replaced
}
// 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)
if start == -1 || end == -1 || start > end {
return content
}
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")
}
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,
// matching both legacy (exact) and new (with metadata) formats via prefix match.
// Returns -1 if not found.
func findBeginMarker(content string) int {
return strings.Index(content, "<!-- BEGIN BEADS INTEGRATION")
}
// existingBeadsProfile extracts the profile from an existing beads section's
// begin marker. Returns ProfileFull if the marker contains "profile:full" or
// if it's a legacy marker (legacy sections contain full content).
// Returns ProfileMinimal only if explicitly marked as such.
func existingBeadsProfile(content string) agents.Profile {
idx := findBeginMarker(content)
if idx == -1 {
return agents.ProfileFull
}
line := content[idx:]
if nl := strings.Index(line, "\n"); nl != -1 {
line = line[:nl]
}
meta := agents.ParseMarker(line)
if meta == nil || meta.Profile == "" {
// Legacy marker — assume full (it contains all the content)
return agents.ProfileFull
}
return meta.Profile
}
// createNewAgentsFile creates a new AGENTS.md with a basic template using the full profile.
func createNewAgentsFile() string {
return createNewAgentsFileWithProfile(agents.ProfileFull)
}
// createNewAgentsFileWithProfile creates a new AGENTS.md with the given profile.
func createNewAgentsFileWithProfile(profile agents.Profile) string {
return createNewAgentsFileWithOpts(profile, agents.DefaultRenderOpts())
}
// createNewAgentsFileWithOpts creates a new AGENTS.md with the given profile and render opts.
func createNewAgentsFileWithOpts(profile agents.Profile, opts agents.RenderOpts) string {
beadsSection := agents.RenderSectionWithOpts(profile, opts)
return `# Project Instructions for AI Agents
This file provides instructions and context for AI coding agents working on this project.
` + beadsSection + `
## Build & Test
_Add your build and test commands here_
` + "```bash" + `
# Example:
# npm install
# npm test
` + "```" + `
## Architecture Overview
_Add a brief overview of your project architecture_
## Conventions & Patterns
_Add your project-specific conventions here_
`
}