beads/cmd/bd/setup/claude.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

879 lines
29 KiB
Go

package setup
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/templates/agents"
)
var (
claudeEnvProvider = defaultClaudeEnv
errClaudeHooksMissing = errors.New("claude hooks not installed")
)
const claudeInstructionsFile = "CLAUDE.md"
var claudeAgentsIntegration = agentsIntegration{
name: "Claude Code",
setupCommand: "bd setup claude",
profile: agents.ProfileMinimal,
}
// claudeGlobalAgentsIntegration is claudeAgentsIntegration for the user-level
// instructions file, so its hints name the command that maintains that file.
var claudeGlobalAgentsIntegration = agentsIntegration{
name: "Claude Code",
setupCommand: "bd setup claude --global",
profile: agents.ProfileMinimal,
}
type claudeEnv struct {
stdout io.Writer
stderr io.Writer
homeDir string
projectDir string
ensureDir func(string, os.FileMode) error
readFile func(string) ([]byte, error)
writeFile func(string, []byte) error
}
func defaultClaudeEnv() (claudeEnv, error) {
home, err := os.UserHomeDir()
if err != nil {
return claudeEnv{}, fmt.Errorf("home directory: %w", err)
}
workDir, err := os.Getwd()
if err != nil {
return claudeEnv{}, fmt.Errorf("working directory: %w", err)
}
return claudeEnv{
stdout: os.Stdout,
stderr: os.Stderr,
homeDir: home,
projectDir: workDir,
ensureDir: EnsureDir,
readFile: os.ReadFile,
writeFile: func(path string, data []byte) error {
return atomicWriteFile(path, data)
},
}, nil
}
func projectSettingsPath(base string) string {
return filepath.Join(base, ".claude", "settings.json")
}
func legacyProjectSettingsPath(base string) string {
return filepath.Join(base, ".claude", "settings.local.json")
}
func globalSettingsPath(home string) string {
return filepath.Join(home, ".claude", "settings.json")
}
// globalClaudeInstructionsPath is Claude Code's user-level instructions file,
// which it loads in every project. A global install keeps its managed beads
// section there, beside the ~/.claude/settings.json its hook goes in.
func globalClaudeInstructionsPath(home string) string {
return filepath.Join(home, ".claude", claudeInstructionsFile)
}
// marshalSettings renders a Claude settings map as two-space-indented JSON
// with the trailing newline json.MarshalIndent omits, so the file stays
// POSIX-clean and byte-stable across runs.
func marshalSettings(settings map[string]interface{}) ([]byte, error) {
data, err := json.MarshalIndent(settings, "", " ")
if err != nil {
return nil, err
}
return append(data, '\n'), nil
}
// writeSettingsIfChanged writes data to path only when it differs from what is
// already on disk. GH#5693: bd init / bd setup claude marshaled and wrote
// settings.json on every run, so a no-op run still churned the file's mtime
// and — because MarshalIndent emits no trailing newline — silently stripped it.
func writeSettingsIfChanged(env claudeEnv, path string, data []byte) error {
if existing, err := env.readFile(path); err == nil && bytes.Equal(existing, data) {
return nil
}
return env.writeFile(path, data)
}
func claudeAgentsEnv(env claudeEnv) agentsEnv {
ae, _ := claudeAgentsEnvRedirect(env)
return ae
}
// claudeAgentsEnvRedirect is claudeAgentsEnv plus a bool reporting whether the
// AGENTS.md redirect activated, so callers that need to clean up a stale
// CLAUDE.md block (installClaude, removeClaude) can tell the redirected case
// apart from the plain CLAUDE.md-is-authoritative case.
func claudeAgentsEnvRedirect(env claudeEnv) (agentsEnv, bool) {
claudePath := filepath.Join(env.projectDir, claudeInstructionsFile)
// If CLAUDE.md is a thin stub that imports AGENTS.md via the @-include
// convention (Claude Code expands @-imports), redirect the managed beads
// section to AGENTS.md instead of duplicating it in the stub. This matches
// the shared-authoritative-file pattern used by repos that keep AGENTS.md
// as the single source of agent instructions.
agentsFile := config.SafeAgentsFile()
agentsPath := filepath.Join(env.projectDir, agentsFile)
if data, err := env.readFile(claudePath); err == nil {
if isAgentsImportStub(string(data), agentsFile) {
if _, err := env.readFile(agentsPath); err == nil {
return agentsEnv{
agentsPath: agentsPath,
stdout: env.stdout,
stderr: env.stderr,
}, true
}
}
}
return agentsEnv{
agentsPath: claudePath,
stdout: env.stdout,
stderr: env.stderr,
}, false
}
// claudeInstructionsEnv resolves the file an install or removal manages the
// beads section in, with the integration whose hints name its command. A
// global install uses the user-level ~/.claude/CLAUDE.md and leaves the
// current directory's files alone. It renders that file with fixed options:
// every project shares it, so it must not follow one project's config, and
// Claude Code loads it in projects that do not use beads too, so its section
// applies only in those that do. A project install uses the project's
// CLAUDE.md, or AGENTS.md when the bool reports the claudeAgentsEnvRedirect
// redirect.
func claudeInstructionsEnv(env claudeEnv, global bool) (agentsEnv, agentsIntegration, bool) {
if !global {
ae, redirected := claudeAgentsEnvRedirect(env)
return ae, claudeAgentsIntegration, redirected
}
return agentsEnv{
agentsPath: globalClaudeInstructionsPath(env.homeDir),
stdout: env.stdout,
stderr: env.stderr,
sectionOnly: true,
renderOpts: agents.UserLevelRenderOpts,
}, claudeGlobalAgentsIntegration, false
}
// claudeCheckAgentsEnv picks the instructions file --check reports on. Run
// from ~/.claude, the project's CLAUDE.md is the user-level file, so it is
// judged as one. Otherwise it is the project's file, unless the hooks are
// user-level (a global install's, or the plugin's) and the project's file has
// no beads section. Then it is the ~/.claude/CLAUDE.md a global install
// writes, which Claude Code loads alongside the project's own instructions,
// if that has a section, if the project's file does not exist, or if the
// project is the home directory: there a project install's hint would create
// the ~/CLAUDE.md a global install exists to avoid. A project install with
// project hooks is judged on the project's file alone; one whose hooks the
// plugin manages has no project hooks, so it is treated as user-level.
func claudeCheckAgentsEnv(env claudeEnv, userLevelHooks bool) (agentsEnv, agentsIntegration) {
globalEnv, globalIntegration, _ := claudeInstructionsEnv(env, true)
if sameDir(env.projectDir, filepath.Dir(globalEnv.agentsPath)) {
return globalEnv, globalIntegration
}
projectEnv := claudeAgentsEnv(env)
if !userLevelHooks || claudeFileHasBeadsSection(env, projectEnv.agentsPath) {
return projectEnv, claudeAgentsIntegration
}
if claudeFileHasBeadsSection(env, globalEnv.agentsPath) || claudeProjectIsHome(env) {
return globalEnv, globalIntegration
}
if _, err := env.readFile(projectEnv.agentsPath); err != nil {
return globalEnv, globalIntegration
}
return projectEnv, claudeAgentsIntegration
}
// claudeProjectIsHome reports whether the current directory is the home
// directory, where the project's .claude/settings.json is the global one.
func claudeProjectIsHome(env claudeEnv) bool {
return sameDir(env.projectDir, env.homeDir)
}
// sameDir reports whether a and b are the same directory, following
// symlinks; it compares cleaned paths when either cannot be stat'd.
func sameDir(a, b string) bool {
ai, errA := os.Stat(a)
bi, errB := os.Stat(b)
if errA == nil && errB == nil {
return os.SameFile(ai, bi)
}
return filepath.Clean(a) == filepath.Clean(b)
}
func claudeFileHasBeadsSection(env claudeEnv, path string) bool {
data, err := env.readFile(path)
return err == nil && containsBeadsMarker(string(data))
}
// stripStaleClaudeBlock removes a beads-managed block left behind in CLAUDE.md
// by an older bd version, once the AGENTS.md redirect is active. Older bd
// releases wrote the managed block directly into CLAUDE.md; a project that has
// since adopted the "@AGENTS.md" import-stub pattern would otherwise carry a
// stale duplicate of that block alongside the one now maintained in AGENTS.md.
func stripStaleClaudeBlock(env claudeEnv) error {
claudePath := filepath.Join(env.projectDir, claudeInstructionsFile)
data, err := env.readFile(claudePath)
if err != nil {
return nil
}
content := string(data)
if !containsBeadsMarker(content) {
return nil
}
newContent := removeBeadsSection(content)
if err := env.writeFile(claudePath, []byte(newContent)); err != nil {
return err
}
_, _ = fmt.Fprintf(env.stdout, "✓ Removed stale beads block from %s (now redirected to %s)\n", claudeInstructionsFile, config.SafeAgentsFile())
return nil
}
// isAgentsImportStub reports whether content contains an @-include directive
// for the given agents file (e.g. "@AGENTS.md" on its own line), indicating
// the file is a thin stub that imports shared agent instructions from the
// agents file rather than carrying its own content.
//
// Directives inside fenced code blocks do not count. Claude Code does not expand
// an @-import that is shown as code, so a file that merely documents the pattern
// is not a stub — and treating it as one is not a cosmetic misread: the caller
// redirects the managed block to AGENTS.md and then stripStaleClaudeBlock deletes
// the block that was in CLAUDE.md. A fenced example would silently relocate
// content out of the file that was, in fact, authoritative.
//
// Only fences are skipped, not four-space-indented blocks. An indented line is
// ambiguous in a way a fence is not — it is equally the continuation of a list
// item, which is a plausible place to put a real directive — so treating
// indentation as code would trade this false positive for a false negative.
func isAgentsImportStub(content, agentsFile string) bool {
directives := []string{"@" + agentsFile, "@./" + agentsFile}
fence := ""
for _, line := range strings.Split(content, "\n") {
trimmed := strings.TrimSpace(line)
if marker := codeFenceMarker(trimmed); marker != "" {
switch {
case fence == "":
fence = marker
case marker == fence:
// A closing fence must match the character the block opened
// with, so ``` inside a ~~~ block does not end it.
fence = ""
}
continue
}
if fence != "" {
continue
}
for _, directive := range directives {
if trimmed == directive {
return true
}
}
}
return false
}
// codeFenceMarker returns the fence character ("`" or "~") if the already-trimmed
// line opens or closes a fenced code block, and "" otherwise. CommonMark requires
// at least three of the same character; an info string ("```go") may follow.
func codeFenceMarker(trimmed string) string {
for _, ch := range []string{"`", "~"} {
if strings.HasPrefix(trimmed, strings.Repeat(ch, 3)) {
return ch
}
}
return ""
}
func InstallClaude(global bool, stealth bool) error {
env, err := claudeEnvProvider()
if err != nil {
return HandleError("%v", err)
}
return installClaude(env, global, stealth)
}
// InstallClaudeProject installs project-local Claude hooks, returning an error
// instead of exiting. Used by bd init to integrate Claude setup automatically.
func InstallClaudeProject(stealth bool) error {
return InstallClaudeProjectTo(stealth, ProjectInstallOutput{})
}
// InstallClaudeProjectTo is InstallClaudeProject reporting to out.
func InstallClaudeProjectTo(stealth bool, out ProjectInstallOutput) error {
env, err := claudeEnvProvider()
if err != nil {
return err
}
env.stdout, env.stderr = out.stdout(), out.stderr()
return installClaude(env, false, stealth)
}
func installClaude(env claudeEnv, global bool, stealth bool) error {
var settingsPath string
if global {
settingsPath = globalSettingsPath(env.homeDir)
_, _ = fmt.Fprintln(env.stdout, "Installing Claude hooks globally...")
} else {
settingsPath = projectSettingsPath(env.projectDir)
_, _ = fmt.Fprintln(env.stdout, "Installing Claude hooks for this project...")
}
if err := env.ensureDir(filepath.Dir(settingsPath), 0o755); err != nil {
_, _ = fmt.Fprintf(env.stderr, "Error: %v\n", err)
return err
}
settings := make(map[string]interface{})
if data, err := env.readFile(settingsPath); err == nil {
if err := json.Unmarshal(data, &settings); err != nil {
_, _ = fmt.Fprintf(env.stderr, "Error: failed to parse settings.json: %v\n", err)
return err
}
}
hooks, ok := settings["hooks"].(map[string]interface{})
if !ok {
hooks = make(map[string]interface{})
settings["hooks"] = hooks
}
// GH#955: Clean up any null values left by previous buggy removal
// Claude Code expects arrays, not null values
for key, val := range hooks {
if val == nil {
delete(hooks, key)
}
}
command := "bd prime --hook-json"
if stealth {
command = "bd prime --stealth --hook-json"
}
// Migration sweep: remove bare "bd prime" variants registered by older
// installations. Claude Code's current context-injection contract uses
// the SessionStart JSON envelope; SessionStart also fires after compaction
// with source=compact, so PreCompact no longer needs a bd prime hook.
legacyBareVariants := []string{"bd prime", "bd prime --stealth"}
for _, legacy := range legacyBareVariants {
if legacy == command {
continue
}
removeHookCommand(env.stdout, hooks, "SessionStart", legacy)
removeHookCommand(env.stdout, hooks, "PreCompact", legacy)
}
removeHookCommand(env.stdout, hooks, "PreCompact", "bd prime --hook-json")
removeHookCommand(env.stdout, hooks, "PreCompact", "bd prime --stealth --hook-json")
// GH#3192: Skip writing hooks if the beads plugin is already providing them,
// so project-level hooks don't fire bd prime twice per session.
pluginManaged := hasBeadsPlugin(env)
if pluginManaged {
_, _ = fmt.Fprintln(env.stdout, "✓ Beads plugin detected — hooks are plugin-managed, skipping")
} else {
if addHookCommand(hooks, "SessionStart", command) {
_, _ = fmt.Fprintln(env.stdout, "✓ Registered SessionStart hook")
}
}
data, err := marshalSettings(settings)
if err != nil {
_, _ = fmt.Fprintf(env.stderr, "Error: marshal settings: %v\n", err)
return err
}
if err := writeSettingsIfChanged(env, settingsPath, data); err != nil {
_, _ = fmt.Fprintf(env.stderr, "Error: write settings: %v\n", err)
return err
}
// Migrate legacy hooks: remove beads hooks from settings.local.json if present
if !global {
legacyPath := legacyProjectSettingsPath(env.projectDir)
if hasBeadsHooks(legacyPath) {
if legacyData, readErr := env.readFile(legacyPath); readErr == nil {
var legacySettings map[string]interface{}
if json.Unmarshal(legacyData, &legacySettings) == nil {
if legacyHooks, ok := legacySettings["hooks"].(map[string]interface{}); ok {
for _, v := range []string{"bd prime", "bd prime --stealth", "bd prime --hook-json", "bd prime --stealth --hook-json"} {
removeHookCommand(env.stdout, legacyHooks, "SessionStart", v)
removeHookCommand(env.stdout, legacyHooks, "PreCompact", v)
}
if migrated, marshalErr := marshalSettings(legacySettings); marshalErr == nil {
if writeErr := writeSettingsIfChanged(env, legacyPath, migrated); writeErr == nil {
_, _ = fmt.Fprintf(env.stdout, "✓ Migrated hooks from %s\n", legacyPath)
}
}
}
}
}
}
}
// Install minimal beads section in CLAUDE.md.
// Hooks handle the heavy lifting via bd prime; CLAUDE.md just needs a pointer.
agentsEnv, integration, redirected := claudeInstructionsEnv(env, global)
agentsSkipped := false
agentsEnv.skipped = &agentsSkipped
agentsErr := installAgents(agentsEnv, integration)
if agentsErr != nil {
// Non-fatal: hooks are already installed
_, _ = fmt.Fprintf(env.stderr, "Warning: failed to update %s: %v\n", agentsFileName(agentsEnv.agentsPath), agentsErr)
}
// 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)
}
}
if agentsSkipped {
_, _ = fmt.Fprintln(env.stdout, "\n✓ Claude Code hooks installed")
_, _ = fmt.Fprintf(env.stdout, " Agent instructions skipped: %s is a symlink\n", claudeInstructionsFile)
} else {
_, _ = fmt.Fprintln(env.stdout, "\n✓ Claude Code integration installed")
}
_, _ = fmt.Fprintf(env.stdout, " Settings: %s\n", settingsPath)
_, _ = fmt.Fprintln(env.stdout, "\nRestart Claude Code for changes to take effect.")
return nil
}
// claudeSettingsUsesRemovedSyncCommand reports whether any hook command references
// bd sync (removed as a real command; GH#3546).
func claudeSettingsUsesRemovedSyncCommand(data []byte) bool {
var settings map[string]interface{}
if err := json.Unmarshal(data, &settings); err != nil {
return false
}
hooks, ok := settings["hooks"].(map[string]interface{})
if !ok {
return false
}
for _, raw := range hooks {
eventHooks, ok := raw.([]interface{})
if !ok {
continue
}
for _, hook := range eventHooks {
hookMap, ok := hook.(map[string]interface{})
if !ok {
continue
}
cmds, ok := hookMap["hooks"].([]interface{})
if !ok {
continue
}
for _, c := range cmds {
cmdMap, ok := c.(map[string]interface{})
if !ok {
continue
}
command, _ := cmdMap["command"].(string)
if strings.Contains(command, "bd sync") {
return true
}
}
}
}
return false
}
func warnIfClaudeHooksUseRemovedSync(env claudeEnv) {
paths := []string{
projectSettingsPath(env.projectDir),
globalSettingsPath(env.homeDir),
legacyProjectSettingsPath(env.projectDir),
}
for _, p := range paths {
data, err := env.readFile(p)
if err != nil {
continue
}
if !claudeSettingsUsesRemovedSyncCommand(data) {
continue
}
_, _ = fmt.Fprintf(env.stderr, "Warning: %s contains a hook using removed \"bd sync\". Run bd setup claude to refresh hooks (bd prime / bd dolt push), or edit settings manually.\n", p)
}
}
func CheckClaude() error {
env, err := claudeEnvProvider()
if err != nil {
return HandleError("%v", err)
}
return checkClaude(env)
}
func checkClaude(env claudeEnv) error {
warnIfClaudeHooksUseRemovedSync(env)
projectSettings := projectSettingsPath(env.projectDir)
globalSettings := globalSettingsPath(env.homeDir)
legacySettings := legacyProjectSettingsPath(env.projectDir)
// From the home directory the project's settings are the global ones,
// so hooks there are user-level and reported as global.
atHome := claudeProjectIsHome(env)
userLevelHooks := false
switch {
case !atHome && hasBeadsHooks(projectSettings):
_, _ = fmt.Fprintf(env.stdout, "✓ Project hooks installed: %s\n", projectSettings)
case hasBeadsHooks(globalSettings):
_, _ = fmt.Fprintf(env.stdout, "✓ Global hooks installed: %s\n", globalSettings)
userLevelHooks = true
case hasBeadsHooks(legacySettings):
_, _ = fmt.Fprintf(env.stdout, "✓ Project hooks installed (legacy): %s\n", legacySettings)
_, _ = fmt.Fprintf(env.stdout, " Consider running 'bd setup claude' to migrate to .claude/settings.json\n")
case hasBeadsPlugin(env):
// GH#3192: Plugin provides hooks via plugin.json — no project-level hooks needed
_, _ = fmt.Fprintln(env.stdout, "✓ Hooks provided by beads plugin (plugin-managed)")
userLevelHooks = true
default:
_, _ = fmt.Fprintln(env.stdout, "✗ No hooks installed")
if atHome {
// A project install here would create the ~/CLAUDE.md a global
// install exists to avoid.
_, _ = fmt.Fprintln(env.stdout, " Run: bd setup claude --global")
} else {
_, _ = fmt.Fprintln(env.stdout, " Run: bd setup claude")
}
return errClaudeHooksMissing
}
agentsEnv, integration := claudeCheckAgentsEnv(env, userLevelHooks)
return checkAgents(agentsEnv, integration)
}
func RemoveClaude(global bool) error {
env, err := claudeEnvProvider()
if err != nil {
return HandleError("%v", err)
}
return removeClaude(env, global)
}
func removeClaude(env claudeEnv, global bool) error {
var settingsPath string
if global {
settingsPath = globalSettingsPath(env.homeDir)
_, _ = fmt.Fprintln(env.stdout, "Removing Claude hooks globally...")
} else {
settingsPath = projectSettingsPath(env.projectDir)
_, _ = fmt.Fprintln(env.stdout, "Removing Claude hooks from project...")
}
data, err := env.readFile(settingsPath)
if err != nil {
_, _ = fmt.Fprintln(env.stdout, "No settings file found")
} else {
var settings map[string]interface{}
if err := json.Unmarshal(data, &settings); err != nil {
_, _ = fmt.Fprintf(env.stderr, "Error: failed to parse settings.json: %v\n", err)
return err
}
hooks, ok := settings["hooks"].(map[string]interface{})
if !ok {
_, _ = fmt.Fprintln(env.stdout, "No hooks found")
} else {
for _, v := range []string{"bd prime", "bd prime --stealth", "bd prime --hook-json", "bd prime --stealth --hook-json"} {
removeHookCommand(env.stdout, hooks, "SessionStart", v)
removeHookCommand(env.stdout, hooks, "PreCompact", v)
}
data, err = marshalSettings(settings)
if err != nil {
_, _ = fmt.Fprintf(env.stderr, "Error: marshal settings: %v\n", err)
return err
}
if err := writeSettingsIfChanged(env, settingsPath, data); err != nil {
_, _ = fmt.Fprintf(env.stderr, "Error: write settings: %v\n", err)
return err
}
}
}
// Also clean legacy settings.local.json when removing project hooks
if !global {
legacyPath := legacyProjectSettingsPath(env.projectDir)
if legacyData, readErr := env.readFile(legacyPath); readErr == nil {
var legacySettings map[string]interface{}
if json.Unmarshal(legacyData, &legacySettings) == nil {
if legacyHooks, ok := legacySettings["hooks"].(map[string]interface{}); ok {
for _, v := range []string{"bd prime", "bd prime --stealth", "bd prime --hook-json", "bd prime --stealth --hook-json"} {
removeHookCommand(env.stdout, legacyHooks, "SessionStart", v)
removeHookCommand(env.stdout, legacyHooks, "PreCompact", v)
}
if migrated, marshalErr := marshalSettings(legacySettings); marshalErr == nil {
_ = writeSettingsIfChanged(env, legacyPath, migrated)
}
}
}
}
}
agentsEnv, integration, redirected := claudeInstructionsEnv(env, global)
if redirected {
// When redirected, AGENTS.md carries the project-authoritative shared
// beads section (created by `bd init` or another agent's setup), not a
// Claude-specific one. Removing Claude integration must not delete it;
// only clean up any stale block left directly in CLAUDE.md.
_, _ = fmt.Fprintf(env.stdout, " Leaving shared beads section in %s untouched (project-authoritative, not Claude-specific)\n", config.SafeAgentsFile())
if err := stripStaleClaudeBlock(env); err != nil {
_, _ = fmt.Fprintf(env.stderr, "Warning: failed to clean stale beads block from %s: %v\n", claudeInstructionsFile, err)
}
} else {
if err := removeAgents(agentsEnv, integration); err != nil {
// Non-fatal
_, _ = fmt.Fprintf(env.stderr, "Warning: failed to update %s: %v\n", claudeInstructionsFile, err)
}
}
// From the home directory a project removal has just removed the global
// hooks, since the settings files are the same; remove the user-level
// section a global install paired with them too.
if !global && claudeProjectIsHome(env) {
globalEnv, globalIntegration, _ := claudeInstructionsEnv(env, true)
if err := removeAgents(globalEnv, globalIntegration); err != nil {
// Non-fatal
_, _ = fmt.Fprintf(env.stderr, "Warning: failed to update %s: %v\n", globalEnv.agentsPath, err)
}
}
_, _ = fmt.Fprintln(env.stdout, "✓ Claude hooks removed")
return nil
}
// addHookCommand adds a hook command to an event if not already present
// Returns true if hook was added, false if already exists
func addHookCommand(hooks map[string]interface{}, event, command string) bool {
// Get or create event array
eventHooks, ok := hooks[event].([]interface{})
if !ok {
eventHooks = []interface{}{}
}
// Check if bd hook already registered
for _, hook := range eventHooks {
hookMap, ok := hook.(map[string]interface{})
if !ok {
continue
}
commands, ok := hookMap["hooks"].([]interface{})
if !ok {
continue
}
for _, cmd := range commands {
cmdMap, ok := cmd.(map[string]interface{})
if !ok {
continue
}
if cmdMap["command"] == command {
fmt.Printf("✓ Hook already registered: %s\n", event)
return false
}
}
}
// Add bd hook to array
newHook := map[string]interface{}{
"matcher": "",
"hooks": []interface{}{
map[string]interface{}{
"type": "command",
"command": command,
},
},
}
eventHooks = append(eventHooks, newHook)
hooks[event] = eventHooks
return true
}
// removeHookCommand removes a specific command from an event's hook entries.
// Only the matching command object is removed; sibling commands in the same
// hook entry are preserved. A hook entry is dropped only when its command list
// becomes empty after filtering. Each removal is reported to w, the caller's
// stdout: bd init --quiet hands the installers a discarding writer, so a
// print to the process stdout here would escape it.
func removeHookCommand(w io.Writer, hooks map[string]interface{}, event, command string) {
eventHooks, ok := hooks[event].([]interface{})
if !ok {
return
}
// Initialize as empty slice (not nil) to avoid JSON null serialization.
filtered := make([]interface{}, 0, len(eventHooks))
for _, hook := range eventHooks {
hookMap, ok := hook.(map[string]interface{})
if !ok {
filtered = append(filtered, hook)
continue
}
commands, ok := hookMap["hooks"].([]interface{})
if !ok {
filtered = append(filtered, hook)
continue
}
// Filter only the matching command; preserve any siblings.
remaining := make([]interface{}, 0, len(commands))
removed := false
for _, cmd := range commands {
cmdMap, ok := cmd.(map[string]interface{})
if !ok {
remaining = append(remaining, cmd)
continue
}
if cmdMap["command"] == command {
removed = true
continue
}
remaining = append(remaining, cmd)
}
if removed {
_, _ = fmt.Fprintf(w, "✓ Removed %s hook\n", event)
}
// Drop the hook entry only when it has no commands left.
if len(remaining) > 0 {
hookMap["hooks"] = remaining
filtered = append(filtered, hookMap)
}
}
// GH#955: Delete the key entirely if no hooks remain, rather than
// leaving an empty array. This is cleaner and avoids potential
// issues with empty arrays in settings.
if len(filtered) == 0 {
delete(hooks, event)
} else {
hooks[event] = filtered
}
}
// hasBeadsPlugin checks if the beads Claude Code plugin is enabled in any
// settings file. The plugin declares its own SessionStart hooks in plugin.json,
// so project-level hooks from bd setup claude would duplicate them.
func hasBeadsPlugin(env claudeEnv) bool {
paths := []string{
projectSettingsPath(env.projectDir),
globalSettingsPath(env.homeDir),
legacyProjectSettingsPath(env.projectDir),
}
for _, p := range paths {
if checkBeadsPluginInFile(env.readFile, p) {
return true
}
}
return false
}
// checkBeadsPluginInFile checks if the beads plugin is enabled in a single settings file.
func checkBeadsPluginInFile(readFile func(string) ([]byte, error), path string) bool {
data, err := readFile(path)
if err != nil {
return false
}
var settings map[string]interface{}
if err := json.Unmarshal(data, &settings); err != nil {
return false
}
enabledPlugins, ok := settings["enabledPlugins"].(map[string]interface{})
if !ok {
return false
}
for key, value := range enabledPlugins {
// enabledPlugins keys are "<pluginName>@<marketplace>". Match the
// plugin-name segment exactly: a substring test (GH#4244) mistakes any
// "*beads*" plugin (e.g. design-to-beads) for the beads hook plugin and
// wrongly skips the SessionStart hook write.
name, _, _ := strings.Cut(strings.ToLower(key), "@")
if name == "beads" {
if enabled, ok := value.(bool); ok && enabled {
return true
}
}
}
return false
}
// hasBeadsHooks checks if a settings file has bd prime hooks
func hasBeadsHooks(settingsPath string) bool {
data, err := os.ReadFile(settingsPath) // #nosec G304 -- settingsPath is constructed from known safe locations (user home/.claude), not user input
if err != nil {
return false
}
var settings map[string]interface{}
if err := json.Unmarshal(data, &settings); err != nil {
return false
}
hooks, ok := settings["hooks"].(map[string]interface{})
if !ok {
return false
}
// Check SessionStart and PreCompact for "bd prime"
for _, event := range []string{"SessionStart", "PreCompact"} {
eventHooks, ok := hooks[event].([]interface{})
if !ok {
continue
}
for _, hook := range eventHooks {
hookMap, ok := hook.(map[string]interface{})
if !ok {
continue
}
commands, ok := hookMap["hooks"].([]interface{})
if !ok {
continue
}
for _, cmd := range commands {
cmdMap, ok := cmd.(map[string]interface{})
if !ok {
continue
}
// Recognize both current (--hook-json) and legacy bare variants.
switch cmdMap["command"] {
case "bd prime", "bd prime --stealth",
"bd prime --hook-json", "bd prime --stealth --hook-json":
return true
}
}
}
}
return false
}