diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a2730931..a359da061 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -894,6 +894,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 driver sends a `time.Time` as its wall clock with no zone, so a library caller paging with a cursor in another zone was answered from the wrong position there (server Dolt was unaffected). +- **`bd setup claude --global` keeps its beads section in `~/.claude/CLAUDE.md`.** + It wrote the section into the current directory's `CLAUDE.md`: run from your + home directory it created `~/CLAUDE.md`, which by default stops Claude Code + reading `AGENTS.md` in the projects below it, and `--remove --global` + stripped the section a project's own install had put in its `CLAUDE.md` + while leaving that project's hooks in place. A global install and removal now + use only the user-level files beside `~/.claude/settings.json`. A new + `~/.claude/CLAUDE.md` holds just the section, rendered the same whichever + project you run from. Claude Code loads that file in every project, so its + section, task-tracking rules included, applies only in repositories that use + beads. With global or plugin hooks `--check` accepts it when the project's + instructions have none, or names `--global` when it is missing and the + project has no `CLAUDE.md` of its own. Run from `~/.claude`, + or from your home directory unless `~/CLAUDE.md` still holds a section an + earlier run left there, `--check` judges the user-level files, and from your + home directory it names `--global` when no hooks are installed. From your + home directory, whose `.claude/settings.json` is the global one, `--remove` + removes the user-level section with the hooks. If you ran `--global` before, + re-run `bd setup claude --global` to add the section to `~/.claude/CLAUDE.md`. + A section an earlier `--global` run left in a directory's `CLAUDE.md` stays + there; delete it by hand if you don't want it. - **`bd blocked --label`, `--label-any` and `--exclude-label` apply to a row blocked only by an unsatisfied `external:` dependency.** The external-dependency policy lists such a row itself, after the label query diff --git a/cmd/bd/agent_artifacts_embedded_test.go b/cmd/bd/agent_artifacts_embedded_test.go index 9636f9429..3b7d1c8a4 100644 --- a/cmd/bd/agent_artifacts_embedded_test.go +++ b/cmd/bd/agent_artifacts_embedded_test.go @@ -118,14 +118,16 @@ func TestEmbeddedInitAgentArtifactsGolden(t *testing.T) { } // agentArtifactPaths are the Claude agent artifacts bd init and bd setup -// claude write in a project ($PROJECT), and the two a global install writes -// in the home directory ($HOME) instead. +// claude write in a project ($PROJECT), and those in the home directory +// ($HOME): the $HOME/.claude/ files a global install writes, and the +// $HOME/CLAUDE.md an older --global run from $HOME wrote. var agentArtifactPaths = []string{ "$PROJECT/.claude/settings.json", "$PROJECT/.claude/settings.local.json", "$PROJECT/AGENTS.md", "$PROJECT/CLAUDE.md", "$HOME/.claude/settings.json", + "$HOME/.claude/CLAUDE.md", "$HOME/CLAUDE.md", } @@ -138,8 +140,10 @@ var agentArtifactManagedSections = []struct { }{ {golden: "managed-section-minimal.md", profile: agents.ProfileMinimal, opts: agents.RenderOpts{HasRemote: true}}, {golden: "managed-section-minimal-no-remote.md", profile: agents.ProfileMinimal, opts: agents.RenderOpts{}}, + {golden: "managed-section-minimal-user.md", profile: agents.ProfileMinimal, opts: agents.UserLevelRenderOpts()}, {golden: "managed-section-full.md", profile: agents.ProfileFull, opts: agents.RenderOpts{HasRemote: true}}, {golden: "managed-section-full-no-remote.md", profile: agents.ProfileFull, opts: agents.RenderOpts{}}, + {golden: "managed-section-full-user.md", profile: agents.ProfileFull, opts: agents.UserLevelRenderOpts()}, } // elideAgentArtifactManagedSection replaces the body of a managed section diff --git a/cmd/bd/setup/agents.go b/cmd/bd/setup/agents.go index 55bb29a6a..b11061967 100644 --- a/cmd/bd/setup/agents.go +++ b/cmd/bd/setup/agents.go @@ -34,6 +34,21 @@ type agentsEnv struct { 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 { @@ -117,7 +132,7 @@ func installAgents(env agentsEnv, integration agentsIntegration) error { } profile := resolveProfile(integration) - opts := detectRenderOpts() + opts := env.resolveRenderOpts() var currentContent string data, err := os.ReadFile(env.agentsPath) // #nosec G304 -- env.agentsPath is trusted setup destination @@ -176,6 +191,9 @@ func installAgents(env agentsEnv, integration agentsIntegration) error { } } 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 @@ -234,7 +252,7 @@ func checkAgents(env agentsEnv, integration agentsIntegration) error { checkProfile = agents.ProfileFull } - currentHash := agents.CurrentHashWithOpts(checkProfile, detectRenderOpts()) + 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 diff --git a/cmd/bd/setup/claude.go b/cmd/bd/setup/claude.go index 01190bd88..832d68a20 100644 --- a/cmd/bd/setup/claude.go +++ b/cmd/bd/setup/claude.go @@ -27,6 +27,14 @@ var claudeAgentsIntegration = agentsIntegration{ 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 @@ -71,6 +79,13 @@ 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. @@ -131,6 +146,80 @@ func claudeAgentsEnvRedirect(env claudeEnv) (agentsEnv, bool) { }, 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 @@ -342,10 +431,10 @@ func installClaude(env claudeEnv, global bool, stealth bool) error { // Install minimal beads section in CLAUDE.md. // Hooks handle the heavy lifting via bd prime; CLAUDE.md just needs a pointer. - agentsEnv, redirected := claudeAgentsEnvRedirect(env) + agentsEnv, integration, redirected := claudeInstructionsEnv(env, global) agentsSkipped := false agentsEnv.skipped = &agentsSkipped - agentsErr := installAgents(agentsEnv, claudeAgentsIntegration) + 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) @@ -447,24 +536,37 @@ func checkClaude(env claudeEnv) error { 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 hasBeadsHooks(projectSettings): + 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") - _, _ = fmt.Fprintln(env.stdout, " Run: bd setup claude") + 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 } - return checkAgents(claudeAgentsEnv(env), claudeAgentsIntegration) + agentsEnv, integration := claudeCheckAgentsEnv(env, userLevelHooks) + return checkAgents(agentsEnv, integration) } func RemoveClaude(global bool) error { @@ -536,7 +638,7 @@ func removeClaude(env claudeEnv, global bool) error { } } - agentsEnv, redirected := claudeAgentsEnvRedirect(env) + 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 @@ -547,12 +649,23 @@ func removeClaude(env claudeEnv, global bool) error { _, _ = fmt.Fprintf(env.stderr, "Warning: failed to clean stale beads block from %s: %v\n", claudeInstructionsFile, err) } } else { - if err := removeAgents(agentsEnv, claudeAgentsIntegration); err != nil { + 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 } diff --git a/cmd/bd/setup/claude_artifacts_golden_test.go b/cmd/bd/setup/claude_artifacts_golden_test.go index 1d35a33c1..710d49423 100644 --- a/cmd/bd/setup/claude_artifacts_golden_test.go +++ b/cmd/bd/setup/claude_artifacts_golden_test.go @@ -35,6 +35,7 @@ import ( // claudeArtifactPaths are the files bd setup claude can create, change or // delete, relative to the root holding the test's project and home dirs. var claudeArtifactPaths = []string{ + "home/.claude/CLAUDE.md", "home/.claude/settings.json", "project/.claude/settings.json", "project/.claude/settings.local.json", @@ -51,8 +52,10 @@ var managedSectionGoldens = []struct { }{ {golden: "managed-section-minimal.md", profile: agents.ProfileMinimal, opts: agents.RenderOpts{HasRemote: true}}, {golden: "managed-section-minimal-no-remote.md", profile: agents.ProfileMinimal, opts: agents.RenderOpts{}}, + {golden: "managed-section-minimal-user.md", profile: agents.ProfileMinimal, opts: agents.UserLevelRenderOpts()}, {golden: "managed-section-full.md", profile: agents.ProfileFull, opts: agents.RenderOpts{HasRemote: true}}, {golden: "managed-section-full-no-remote.md", profile: agents.ProfileFull, opts: agents.RenderOpts{}}, + {golden: "managed-section-full-user.md", profile: agents.ProfileFull, opts: agents.UserLevelRenderOpts()}, } // elideManagedSection replaces the body of a managed section that is @@ -227,6 +230,24 @@ func TestClaudeSetupArtifactsGolden(t *testing.T) { claudeCheckStep(), }, }, + { + // A global install and removal run inside a project that has its + // own install, as bd init leaves it: the global steps use the + // user-level files under home/.claude only, and the project's + // hooks and section stay in place and current throughout. + name: "global-beside-project-install", + seed: map[string]string{ + "home/.claude/CLAUDE.md": "# My preferences\n\nAnswer tersely.\n", + "project/.claude/settings.json": installedSettings, + "project/CLAUDE.md": "# My Project\n\n" + agents.RenderSectionWithOpts(agents.ProfileMinimal, agents.DefaultRenderOpts()), + }, + steps: []claudeArtifactStep{ + claudeInstallStep(true, false), + claudeCheckStep(), + claudeRemoveStep(true), + claudeCheckStep(), + }, + }, { // User-owned settings and instructions: install merges into // them and --remove takes back only what bd added. diff --git a/cmd/bd/setup/claude_test.go b/cmd/bd/setup/claude_test.go index bcb565a15..78f99f6c9 100644 --- a/cmd/bd/setup/claude_test.go +++ b/cmd/bd/setup/claude_test.go @@ -66,6 +66,12 @@ func writeSettings(t *testing.T, path string, settings map[string]interface{}) { } } +// userLevelSection is the managed section a global install writes to +// ~/.claude/CLAUDE.md. +func userLevelSection() string { + return agents.RenderSectionWithOpts(agents.ProfileMinimal, agents.UserLevelRenderOpts()) +} + func TestAddHookCommand(t *testing.T) { tests := []struct { name string @@ -793,15 +799,110 @@ func TestInstallClaudeGlobalStealth(t *testing.T) { if !strings.Contains(string(data), "bd prime --stealth") { t.Error("expected stealth command in settings") } - instructionsPath := filepath.Join(env.projectDir, claudeInstructionsFile) - if _, err := os.Stat(instructionsPath); err != nil { - t.Fatalf("expected %s to be created: %v", claudeInstructionsFile, err) + // The managed section goes to Claude Code's user-level instructions file, + // beside the global settings, holding only the section, worded for a file + // every project loads: none of the project scaffolding a new project + // CLAUDE.md gets. + instructions, err := os.ReadFile(globalClaudeInstructionsPath(env.homeDir)) + if err != nil { + t.Fatalf("expected user-level %s to be created: %v", claudeInstructionsFile, err) + } + if want := userLevelSection(); string(instructions) != want { + t.Errorf("user-level %s should hold only the managed section:\ngot:\n%s\nwant:\n%s", claudeInstructionsFile, instructions, want) + } + // A global install must not touch the current directory's files. + if _, err := os.Stat(filepath.Join(env.projectDir, claudeInstructionsFile)); !os.IsNotExist(err) { + t.Errorf("global install should not create the project's %s (stat err: %v)", claudeInstructionsFile, err) } if !strings.Contains(stdout.String(), "globally") { t.Error("expected global installation message") } } +// The user-level ~/.claude/CLAUDE.md is shared by every project, so a global +// install renders and checks it the same way whatever beads config the +// current directory has: otherwise --check from one project calls the section +// another project wrote stale, and following its hint flips it back. +func TestClaudeGlobalSectionIgnoresProjectConfig(t *testing.T) { + configs := []struct { + name string + opts agents.RenderOpts + }{ + {"remote", agents.RenderOpts{HasRemote: true}}, + {"no remote", agents.RenderOpts{HasRemote: false}}, + {"no push", agents.RenderOpts{HasRemote: true, NoPush: true}}, + } + wantHash := agents.CurrentHashWithOpts(agents.ProfileMinimal, agents.UserLevelRenderOpts()) + orig := detectRenderOptsImpl + t.Cleanup(func() { detectRenderOptsImpl = orig }) + for _, install := range configs { + for _, check := range configs { + t.Run(install.name+" install, "+check.name+" check", func(t *testing.T) { + env, stdout, _ := newClaudeTestEnv(t) + installOpts := install.opts + detectRenderOptsImpl = func() agents.RenderOpts { return installOpts } + if err := installClaude(env, true, false); err != nil { + t.Fatalf("installClaude: %v", err) + } + globalInstructions := globalClaudeInstructionsPath(env.homeDir) + data, err := os.ReadFile(globalInstructions) + if err != nil { + t.Fatalf("read user-level %s: %v", claudeInstructionsFile, err) + } + if !strings.Contains(string(data), "hash:"+wantHash) { + t.Errorf("expected hash %s regardless of project config, got:\n%s", wantHash, data) + } + checkOpts := check.opts + detectRenderOptsImpl = func() agents.RenderOpts { return checkOpts } + stdout.Reset() + if err := checkClaude(env); err != nil { + t.Fatalf("checkClaude: %v\n%s", err, stdout.String()) + } + if !strings.Contains(stdout.String(), globalInstructions+" (current)") { + t.Errorf("expected the user-level file reported current, got:\n%s", stdout.String()) + } + }) + } + } +} + +// A section worded for a project, such as a project install run from +// ~/.claude leaves there, is stale in the user-level file: --check names the +// global install, which rewords the section in place and keeps the user's +// own text. +func TestInstallClaudeGlobalRewordsProjectSection(t *testing.T) { + stubDetectRenderOpts(t) + env, stdout, _ := newClaudeTestEnv(t) + if err := installClaude(env, true, false); err != nil { + t.Fatalf("installClaude: %v", err) + } + globalInstructions := globalClaudeInstructionsPath(env.homeDir) + if err := os.WriteFile(globalInstructions, []byte("# Mine\n\n"+agents.RenderSection(agents.ProfileMinimal)), 0o644); err != nil { + t.Fatalf("write user-level %s: %v", claudeInstructionsFile, err) + } + stdout.Reset() + if err := checkClaude(env); !errors.Is(err, errBeadsSectionStale) { + t.Fatalf("expected errBeadsSectionStale, got %v\n%s", err, stdout.String()) + } + if !strings.Contains(stdout.String(), "Run: bd setup claude --global (to update)") { + t.Errorf("expected the global setup hint, got:\n%s", stdout.String()) + } + if err := installClaude(env, true, false); err != nil { + t.Fatalf("installClaude: %v", err) + } + data, err := os.ReadFile(globalInstructions) + if err != nil { + t.Fatalf("read user-level %s: %v", claudeInstructionsFile, err) + } + if want := "# Mine\n\n" + userLevelSection(); string(data) != want { + t.Errorf("user-level %s after the global install:\ngot:\n%s\nwant:\n%s", claudeInstructionsFile, data, want) + } + stdout.Reset() + if err := checkClaude(env); err != nil { + t.Fatalf("checkClaude: %v\n%s", err, stdout.String()) + } +} + func TestInstallClaudeErrors(t *testing.T) { t.Run("invalid json", func(t *testing.T) { env, _, stderr := newClaudeTestEnv(t) @@ -894,6 +995,19 @@ func TestCheckClaudeScenarios(t *testing.T) { } }) + // From the home directory a project install would create ~/CLAUDE.md, + // so the hint names the global install. + t.Run("missing hooks checked from home", func(t *testing.T) { + env, stdout, _ := newClaudeTestEnv(t) + env.projectDir = env.homeDir + if err := checkClaude(env); !errors.Is(err, errClaudeHooksMissing) { + t.Fatalf("expected errClaudeHooksMissing, got %v", err) + } + if !strings.Contains(stdout.String(), "Run: bd setup claude --global\n") { + t.Errorf("expected the global setup hint, got:\n%s", stdout.String()) + } + }) + t.Run("missing instructions", func(t *testing.T) { env, stdout, _ := newClaudeTestEnv(t) writeSettings(t, globalSettingsPath(env.homeDir), map[string]interface{}{ @@ -914,10 +1028,298 @@ func TestCheckClaudeScenarios(t *testing.T) { if !strings.Contains(stdout.String(), claudeInstructionsFile+" not found") { t.Fatalf("expected missing %s message, got: %s", claudeInstructionsFile, stdout.String()) } + // With global hooks and no instructions file in the project, the + // missing section is the user-level one the global install writes. + if !strings.Contains(stdout.String(), "Run: bd setup claude --global\n") { + t.Errorf("expected the global setup hint, got:\n%s", stdout.String()) + } }) + + // A project CLAUDE.md without a section is still reported as the + // project's: adding the section there is one way to finish the setup. + t.Run("project instructions without a section", func(t *testing.T) { + env, stdout, _ := newClaudeTestEnv(t) + writeSettings(t, globalSettingsPath(env.homeDir), map[string]interface{}{ + "hooks": map[string]interface{}{ + "SessionStart": []interface{}{ + map[string]interface{}{ + "matcher": "", + "hooks": []interface{}{ + map[string]interface{}{"type": "command", "command": "bd prime --hook-json"}, + }, + }, + }, + }, + }) + if err := os.WriteFile(filepath.Join(env.projectDir, claudeInstructionsFile), []byte("# Mine\n"), 0o644); err != nil { + t.Fatalf("write project %s: %v", claudeInstructionsFile, err) + } + if err := checkClaude(env); !errors.Is(err, errBeadsSectionMissing) { + t.Fatalf("expected errBeadsSectionMissing, got %v\n%s", err, stdout.String()) + } + if !strings.Contains(stdout.String(), "Run: bd setup claude (to add beads section)") { + t.Errorf("expected the project setup hint, got:\n%s", stdout.String()) + } + }) + + primeHookSettings := map[string]interface{}{ + "hooks": map[string]interface{}{ + "SessionStart": []interface{}{ + map[string]interface{}{ + "matcher": "", + "hooks": []interface{}{ + map[string]interface{}{"type": "command", "command": "bd prime --hook-json"}, + }, + }, + }, + }, + } + + // A global install is checked from any directory: with no beads section + // in the project, the one in ~/.claude/CLAUDE.md is the one Claude loads. + t.Run("global install from another directory", func(t *testing.T) { + env, stdout, _ := newClaudeTestEnv(t) + writeSettings(t, globalSettingsPath(env.homeDir), primeHookSettings) + globalInstructions := globalClaudeInstructionsPath(env.homeDir) + if err := os.WriteFile(globalInstructions, []byte(userLevelSection()), 0o644); err != nil { + t.Fatalf("write user-level %s: %v", claudeInstructionsFile, err) + } + if err := checkClaude(env); err != nil { + t.Fatalf("checkClaude: %v\n%s", err, stdout.String()) + } + if !strings.Contains(stdout.String(), globalInstructions+" (current)") { + t.Errorf("expected the user-level file reported current, got:\n%s", stdout.String()) + } + }) + + // The common global case: the project has its own CLAUDE.md with no + // beads section, and the user-level file carries the section. + t.Run("global install beside project instructions without a section", func(t *testing.T) { + env, stdout, _ := newClaudeTestEnv(t) + writeSettings(t, globalSettingsPath(env.homeDir), primeHookSettings) + globalInstructions := globalClaudeInstructionsPath(env.homeDir) + if err := os.WriteFile(globalInstructions, []byte(userLevelSection()), 0o644); err != nil { + t.Fatalf("write user-level %s: %v", claudeInstructionsFile, err) + } + if err := os.WriteFile(filepath.Join(env.projectDir, claudeInstructionsFile), []byte("# Mine\n"), 0o644); err != nil { + t.Fatalf("write project %s: %v", claudeInstructionsFile, err) + } + if err := checkClaude(env); err != nil { + t.Fatalf("checkClaude: %v\n%s", err, stdout.String()) + } + if !strings.Contains(stdout.String(), globalInstructions+" (current)") { + t.Errorf("expected the user-level file reported current, got:\n%s", stdout.String()) + } + }) + + // From the home directory a ~/CLAUDE.md without a section is not the + // file to fix: the project hint would add the section there. + t.Run("home instructions without a section checked from home", func(t *testing.T) { + env, stdout, _ := newClaudeTestEnv(t) + env.projectDir = env.homeDir + writeSettings(t, globalSettingsPath(env.homeDir), primeHookSettings) + if err := os.WriteFile(filepath.Join(env.homeDir, claudeInstructionsFile), []byte("# Mine\n"), 0o644); err != nil { + t.Fatalf("write home %s: %v", claudeInstructionsFile, err) + } + if err := checkClaude(env); !errors.Is(err, errAgentsFileMissing) { + t.Fatalf("expected errAgentsFileMissing, got %v\n%s", err, stdout.String()) + } + if !strings.Contains(stdout.String(), "Run: bd setup claude --global\n") { + t.Errorf("expected the global setup hint, got:\n%s", stdout.String()) + } + }) + + t.Run("stale user-level section", func(t *testing.T) { + env, stdout, _ := newClaudeTestEnv(t) + writeSettings(t, globalSettingsPath(env.homeDir), primeHookSettings) + stale := "\nOld.\n\n" + if err := os.WriteFile(globalClaudeInstructionsPath(env.homeDir), []byte(stale), 0o644); err != nil { + t.Fatalf("write user-level %s: %v", claudeInstructionsFile, err) + } + if err := checkClaude(env); !errors.Is(err, errBeadsSectionStale) { + t.Fatalf("expected errBeadsSectionStale, got %v", err) + } + if !strings.Contains(stdout.String(), "Run: bd setup claude --global (to update)") { + t.Errorf("expected the global setup hint, got:\n%s", stdout.String()) + } + }) + + // The plugin's hooks are user-level too, so --global can supply the section. + t.Run("plugin hooks with user-level section", func(t *testing.T) { + env, stdout, _ := newClaudeTestEnv(t) + writeSettings(t, globalSettingsPath(env.homeDir), settingsWithPlugin()) + globalInstructions := globalClaudeInstructionsPath(env.homeDir) + if err := os.WriteFile(globalInstructions, []byte(userLevelSection()), 0o644); err != nil { + t.Fatalf("write user-level %s: %v", claudeInstructionsFile, err) + } + if err := checkClaude(env); err != nil { + t.Fatalf("checkClaude: %v\n%s", err, stdout.String()) + } + if !strings.Contains(stdout.String(), globalInstructions+" (current)") { + t.Errorf("expected the user-level file reported current, got:\n%s", stdout.String()) + } + }) + + // A project install is judged on the project's file alone: the + // user-level section does not stand in for a missing project one. + t.Run("project hooks ignore the user-level section", func(t *testing.T) { + env, stdout, _ := newClaudeTestEnv(t) + writeSettings(t, projectSettingsPath(env.projectDir), primeHookSettings) + if err := os.MkdirAll(filepath.Dir(globalClaudeInstructionsPath(env.homeDir)), 0o755); err != nil { + t.Fatalf("mkdir user-level dir: %v", err) + } + if err := os.WriteFile(globalClaudeInstructionsPath(env.homeDir), []byte(userLevelSection()), 0o644); err != nil { + t.Fatalf("write user-level %s: %v", claudeInstructionsFile, err) + } + if err := checkClaude(env); !errors.Is(err, errAgentsFileMissing) { + t.Fatalf("expected errAgentsFileMissing, got %v\n%s", err, stdout.String()) + } + }) + + // With global hooks the project's own section still wins over the + // user-level one, as project hooks win over global ones. + t.Run("project section preferred", func(t *testing.T) { + env, stdout, _ := newClaudeTestEnv(t) + writeSettings(t, globalSettingsPath(env.homeDir), primeHookSettings) + stale := "\nOld.\n\n" + if err := os.WriteFile(globalClaudeInstructionsPath(env.homeDir), []byte(stale), 0o644); err != nil { + t.Fatalf("write user-level %s: %v", claudeInstructionsFile, err) + } + projectInstructions := filepath.Join(env.projectDir, claudeInstructionsFile) + if err := os.WriteFile(projectInstructions, []byte(agents.RenderSection(agents.ProfileMinimal)), 0o644); err != nil { + t.Fatalf("write project %s: %v", claudeInstructionsFile, err) + } + if err := checkClaude(env); err != nil { + t.Fatalf("checkClaude: %v\n%s", err, stdout.String()) + } + if !strings.Contains(stdout.String(), projectInstructions+" (current)") { + t.Errorf("expected the project file reported, got:\n%s", stdout.String()) + } + }) + + // From the home directory the project's settings are the global ones and + // its CLAUDE.md is ~/CLAUDE.md, so a global install must still be judged + // on the user-level files. + t.Run("global install checked from home", func(t *testing.T) { + env, _, _ := newClaudeTestEnv(t) + env.projectDir = env.homeDir + if err := installClaude(env, true, false); err != nil { + t.Fatalf("installClaude: %v", err) + } + stdout := &bytes.Buffer{} + env.stdout = stdout + if err := checkClaude(env); err != nil { + t.Fatalf("checkClaude: %v\n%s", err, stdout.String()) + } + if !strings.Contains(stdout.String(), "Global hooks installed") { + t.Errorf("expected global hooks reported, got:\n%s", stdout.String()) + } + if !strings.Contains(stdout.String(), globalClaudeInstructionsPath(env.homeDir)+" (current)") { + t.Errorf("expected the user-level file reported current, got:\n%s", stdout.String()) + } + }) + + // The project hint would create ~/CLAUDE.md from the home directory. + t.Run("missing section checked from home", func(t *testing.T) { + env, stdout, _ := newClaudeTestEnv(t) + env.projectDir = env.homeDir + writeSettings(t, globalSettingsPath(env.homeDir), primeHookSettings) + if err := checkClaude(env); !errors.Is(err, errAgentsFileMissing) { + t.Fatalf("expected errAgentsFileMissing, got %v\n%s", err, stdout.String()) + } + if !strings.Contains(stdout.String(), "Global hooks installed") { + t.Errorf("expected global hooks reported, got:\n%s", stdout.String()) + } + if !strings.Contains(stdout.String(), "Run: bd setup claude --global\n") { + t.Errorf("expected the global setup hint, got:\n%s", stdout.String()) + } + }) + + // From ~/.claude the project's CLAUDE.md is the user-level file: it is + // judged with the fixed global render options, not this directory's. + t.Run("global install checked from the user-level directory", func(t *testing.T) { + env, _, _ := newClaudeTestEnv(t) + if err := installClaude(env, true, false); err != nil { + t.Fatalf("installClaude: %v", err) + } + orig := detectRenderOptsImpl + t.Cleanup(func() { detectRenderOptsImpl = orig }) + detectRenderOptsImpl = func() agents.RenderOpts { return agents.RenderOpts{HasRemote: false} } + env.projectDir = filepath.Dir(globalClaudeInstructionsPath(env.homeDir)) + stdout := &bytes.Buffer{} + env.stdout = stdout + if err := checkClaude(env); err != nil { + t.Fatalf("checkClaude: %v\n%s", err, stdout.String()) + } + if !strings.Contains(stdout.String(), globalClaudeInstructionsPath(env.homeDir)+" (current)") { + t.Errorf("expected the user-level file reported current, got:\n%s", stdout.String()) + } + }) + + // The home directory and ~/.claude are recognized when reached through a + // symlink too (a symlinked /home, a linked checkout): sameDir compares + // the directories, not their path strings. + for _, link := range []struct { + name string + target func(home string) string + }{ + {"home", func(home string) string { return home }}, + {"the user-level directory", func(home string) string { return filepath.Dir(globalClaudeInstructionsPath(home)) }}, + } { + t.Run("global install checked from a symlink to "+link.name, func(t *testing.T) { + env, _, _ := newClaudeTestEnv(t) + if err := installClaude(env, true, false); err != nil { + t.Fatalf("installClaude: %v", err) + } + linkDir := filepath.Join(t.TempDir(), "link") + if err := os.Symlink(link.target(env.homeDir), linkDir); err != nil { + t.Skipf("symlink: %v", err) + } + env.projectDir = linkDir + stdout := &bytes.Buffer{} + env.stdout = stdout + if err := checkClaude(env); err != nil { + t.Fatalf("checkClaude: %v\n%s", err, stdout.String()) + } + if !strings.Contains(stdout.String(), "✓ Global hooks installed") { + t.Errorf("expected global hooks reported, got:\n%s", stdout.String()) + } + if !strings.Contains(stdout.String(), globalClaudeInstructionsPath(env.homeDir)+" (current)") { + t.Errorf("expected the user-level file reported current, got:\n%s", stdout.String()) + } + }) + } } func TestRemoveClaudeScenarios(t *testing.T) { + // From the home directory a project removal removes the global hooks, + // whose settings file is the same, so it removes their user-level + // section too. + t.Run("remove from home", func(t *testing.T) { + env, stdout, _ := newClaudeTestEnv(t) + env.projectDir = env.homeDir + if err := installClaude(env, true, false); err != nil { + t.Fatalf("installClaude: %v", err) + } + if err := removeClaude(env, false); err != nil { + t.Fatalf("removeClaude: %v", err) + } + data, err := os.ReadFile(globalSettingsPath(env.homeDir)) + if err != nil { + t.Fatalf("read global settings: %v", err) + } + if strings.Contains(string(data), "bd prime") { + t.Error("expected bd prime hooks removed") + } + instructions, err := os.ReadFile(globalClaudeInstructionsPath(env.homeDir)) + if err != nil { + t.Fatalf("read user-level %s: %v", claudeInstructionsFile, err) + } + if containsBeadsMarker(string(instructions)) { + t.Errorf("expected the user-level section removed, got:\n%s\nstdout:\n%s", instructions, stdout.String()) + } + }) + t.Run("remove global hooks", func(t *testing.T) { env, stdout, _ := newClaudeTestEnv(t) path := globalSettingsPath(env.homeDir) @@ -934,9 +1336,16 @@ func TestRemoveClaudeScenarios(t *testing.T) { }, }, }) - instructionsPath := filepath.Join(env.projectDir, claudeInstructionsFile) - if err := os.WriteFile(instructionsPath, []byte(agents.RenderSection(agents.ProfileMinimal)), 0o644); err != nil { - t.Fatalf("seed %s: %v", claudeInstructionsFile, err) + section := agents.RenderSection(agents.ProfileMinimal) + globalInstructions := globalClaudeInstructionsPath(env.homeDir) + if err := os.WriteFile(globalInstructions, []byte("# Mine\n\n"+section), 0o644); err != nil { + t.Fatalf("seed user-level %s: %v", claudeInstructionsFile, err) + } + // The project's own section, as bd init leaves it, belongs to the + // project install: a global removal must leave it alone. + projectInstructions := filepath.Join(env.projectDir, claudeInstructionsFile) + if err := os.WriteFile(projectInstructions, []byte(section), 0o644); err != nil { + t.Fatalf("seed project %s: %v", claudeInstructionsFile, err) } // global=true → remove from global settings if err := removeClaude(env, true); err != nil { @@ -949,12 +1358,19 @@ func TestRemoveClaudeScenarios(t *testing.T) { if strings.Contains(string(data), "bd prime") { t.Error("expected bd prime hooks removed") } - instructions, err := os.ReadFile(instructionsPath) + instructions, err := os.ReadFile(globalInstructions) if err != nil { - t.Fatalf("read %s: %v", claudeInstructionsFile, err) + t.Fatalf("read user-level %s: %v", claudeInstructionsFile, err) } - if strings.Contains(string(instructions), "BEGIN BEADS INTEGRATION") { - t.Fatalf("expected beads section removed from %s", claudeInstructionsFile) + if strings.Contains(string(instructions), "BEGIN BEADS INTEGRATION") || !strings.HasPrefix(string(instructions), "# Mine\n") { + t.Errorf("expected only the beads section removed from user-level %s, got:\n%s", claudeInstructionsFile, instructions) + } + project, err := os.ReadFile(projectInstructions) + if err != nil { + t.Fatalf("read project %s: %v", claudeInstructionsFile, err) + } + if string(project) != section { + t.Errorf("global removal changed the project's %s:\n%s", claudeInstructionsFile, project) } if !strings.Contains(stdout.String(), "hooks removed") { t.Error("expected success message") diff --git a/cmd/bd/setup/testdata/claude-setup-global-beside-project-install.golden b/cmd/bd/setup/testdata/claude-setup-global-beside-project-install.golden new file mode 100644 index 000000000..e6f628d1a --- /dev/null +++ b/cmd/bd/setup/testdata/claude-setup-global-beside-project-install.golden @@ -0,0 +1,108 @@ +# bd setup claude artifact transcript: global-beside-project-install +# Regenerate with BD_UPDATE_GOLDEN=1 go test ./cmd/bd/setup/ -run TestClaudeSetupArtifactsGolden +--- seed: created $ROOT/home/.claude/CLAUDE.md +# My preferences + +Answer tersely. +--- seed: created $ROOT/project/.claude/settings.json +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "command": "bd prime --hook-json", + "type": "command" + } + ], + "matcher": "" + } + ] + } +} +--- seed: created $ROOT/project/CLAUDE.md +# My Project + + +[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal.md] + + +=== bd setup claude --global +result: ok +--- stdout +Installing Claude hooks globally... +✓ Registered SessionStart hook +Installing Claude Code integration... +✓ Added beads section to existing CLAUDE.md + +✓ Claude Code integration installed + File: $ROOT/home/.claude/CLAUDE.md +No additional configuration needed! + +✓ Claude Code integration installed + Settings: $ROOT/home/.claude/settings.json + +Restart Claude Code for changes to take effect. +--- stderr +(empty) +--- files: modified $ROOT/home/.claude/CLAUDE.md +# My preferences + +Answer tersely. + + +[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal-user.md] + +--- files: created $ROOT/home/.claude/settings.json +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "command": "bd prime --hook-json", + "type": "command" + } + ], + "matcher": "" + } + ] + } +} + +=== bd setup claude --check +result: ok +--- stdout +✓ Project hooks installed: $ROOT/project/.claude/settings.json +✓ Claude Code integration installed: $ROOT/project/CLAUDE.md (current) +--- stderr +(empty) +--- files: unchanged + +=== bd setup claude --remove --global +result: ok +--- stdout +Removing Claude hooks globally... +✓ Removed SessionStart hook +Removing Claude Code integration... +✓ Removed beads section from CLAUDE.md +✓ Claude hooks removed +--- stderr +(empty) +--- files: modified $ROOT/home/.claude/CLAUDE.md +# My preferences + +Answer tersely. +--- files: modified $ROOT/home/.claude/settings.json +{ + "hooks": {} +} + +=== bd setup claude --check +result: ok +--- stdout +✓ Project hooks installed: $ROOT/project/.claude/settings.json +✓ Claude Code integration installed: $ROOT/project/CLAUDE.md (current) +--- stderr +(empty) +--- files: unchanged diff --git a/cmd/bd/setup/testdata/claude-setup-global.golden b/cmd/bd/setup/testdata/claude-setup-global.golden index c82e8df06..0cfbfea4f 100644 --- a/cmd/bd/setup/testdata/claude-setup-global.golden +++ b/cmd/bd/setup/testdata/claude-setup-global.golden @@ -11,7 +11,7 @@ Installing Claude Code integration... ✓ Created new CLAUDE.md with beads integration ✓ Claude Code integration installed - File: $ROOT/project/CLAUDE.md + File: $ROOT/home/.claude/CLAUDE.md No additional configuration needed! ✓ Claude Code integration installed @@ -20,6 +20,10 @@ No additional configuration needed! Restart Claude Code for changes to take effect. --- stderr (empty) +--- files: created $ROOT/home/.claude/CLAUDE.md + +[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal-user.md] + --- files: created $ROOT/home/.claude/settings.json { "hooks": { @@ -36,39 +40,12 @@ Restart Claude Code for changes to take effect. ] } } ---- files: created $ROOT/project/CLAUDE.md -# Project Instructions for AI Agents - -This file provides instructions and context for AI coding agents working on this project. - - -[managed section body: byte-identical to internal/templates/agents/testdata/managed-section-minimal.md] - - - -## 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_ === bd setup claude --check result: ok --- stdout ✓ Global hooks installed: $ROOT/home/.claude/settings.json -✓ Claude Code integration installed: $ROOT/project/CLAUDE.md (current) +✓ Claude Code integration installed: $ROOT/home/.claude/CLAUDE.md (current) --- stderr (empty) --- files: unchanged @@ -83,32 +60,12 @@ Removing Claude Code integration... ✓ Claude hooks removed --- stderr (empty) +--- files: modified $ROOT/home/.claude/CLAUDE.md +(empty) --- files: modified $ROOT/home/.claude/settings.json { "hooks": {} } ---- files: modified $ROOT/project/CLAUDE.md -# Project Instructions for AI Agents - -This file provides instructions and context for AI coding agents working on this project. - -## 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_ === bd setup claude --check result: error: claude hooks not installed diff --git a/docs/getting-started/ide-setup.md b/docs/getting-started/ide-setup.md index bbd5b8ec4..a2523e7f2 100644 --- a/docs/getting-started/ide-setup.md +++ b/docs/getting-started/ide-setup.md @@ -22,7 +22,7 @@ bd setup claude --remove # Uninstall | Recipe | Files written | Details | |--------|---------------|---------| -| `claude` | `.claude/settings.json` (or `~/.claude/settings.json` with `--global`) + `CLAUDE.md` section | [Claude Code](/integrations/claude-code) | +| `claude` | `.claude/settings.json` + `CLAUDE.md` section (or `~/.claude/settings.json` + `~/.claude/CLAUDE.md` with `--global`) | [Claude Code](/integrations/claude-code) | | `cursor` | `.cursor/rules/beads.mdc` + `.agents/skills/beads/` + `.cursor/hooks.json` (with `--global`: `~/.cursor/hooks.json` + `~/.agents/skills/beads/`, no rules file) | [Cursor](/integrations/cursor) | | `gemini` | `~/.gemini/settings.json` (or `.gemini/settings.json` with `--project`) + `GEMINI.md` section | [Gemini CLI](/integrations/gemini) | | `copilot` | `.copilot-plugin/plugin.json` + `.github/copilot-instructions.md` | [Copilot CLI](/integrations/copilot-cli) | @@ -90,12 +90,12 @@ The recommended approach for Claude Code: ```bash bd setup claude # Project install: .claude/settings.json -bd setup claude --global # Global install: ~/.claude/settings.json +bd setup claude --global # Global install: ~/.claude/settings.json + ~/.claude/CLAUDE.md ``` This installs: - **SessionStart hook** - Runs `bd prime --hook-json`, which wraps the workflow context in the JSON envelope Claude Code expects. SessionStart fires when a session starts, resumes, or clears, and again after context compaction — no separate compaction hook is needed. -- **Minimal beads section in `CLAUDE.md`** - A pointer to `bd prime`, managed with hash/version markers for safe updates and `--check` freshness detection. If `CLAUDE.md` is a thin stub that imports `AGENTS.md` (an `@AGENTS.md` line of its own), the section is written to `AGENTS.md` instead, and a stale beads block left in the stub by an older bd is removed. +- **Minimal beads section in `CLAUDE.md`** - A pointer to `bd prime`, managed with hash/version markers for safe updates and `--check` freshness detection. If `CLAUDE.md` is a thin stub that imports `AGENTS.md` (an `@AGENTS.md` line of its own), the section is written to `AGENTS.md` instead, and a stale beads block left in the stub by an older bd is removed. A `--global` install writes the section to your user-level `~/.claude/CLAUDE.md` and leaves the current directory's files alone. Claude Code loads that file in every project, so there the section applies only in repositories that use beads. If the [beads Claude Code plugin](/integrations/claude-code-plugin) is installed, hooks are plugin-managed and `bd setup claude` skips writing them, so `bd prime` doesn't fire twice per session. @@ -111,7 +111,7 @@ If the [beads Claude Code plugin](/integrations/claude-code-plugin) is installed |------|-------------| | `--check` | Check both hooks and the managed `CLAUDE.md` beads section | | `--remove` | Remove beads hooks and the managed `CLAUDE.md` beads section | -| `--global` | Install to `~/.claude/settings.json` instead of the project | +| `--global` | Install to `~/.claude/settings.json` and `~/.claude/CLAUDE.md` instead of the project | | `--stealth` | Use `bd prime --stealth --hook-json` (flush only, no git operations) — useful in CI/CD where git operations might fail | Restart Claude Code after installation for the hooks to take effect. diff --git a/docs/integrations/claude-code.md b/docs/integrations/claude-code.md index 1678215b5..433876715 100644 --- a/docs/integrations/claude-code.md +++ b/docs/integrations/claude-code.md @@ -15,12 +15,12 @@ bd setup claude This installs: - **SessionStart hook** - Runs `bd prime --hook-json` when a session starts. SessionStart also fires after context compaction, so the same hook refreshes context automatically. -- **CLAUDE.md pointer** - A minimal beads section in your project's `CLAUDE.md` (skipped if `CLAUDE.md` is a symlink). +- **CLAUDE.md pointer** - A minimal beads section in your project's `CLAUDE.md`, or with `--global` in your user-level `~/.claude/CLAUDE.md`, where it applies only in repositories that use beads (skipped if that file is a symlink). By default the hook is written to the project's `.claude/settings.json`. Variants: ```bash -bd setup claude --global # Install to ~/.claude/settings.json instead +bd setup claude --global # Install to ~/.claude/settings.json and ~/.claude/CLAUDE.md instead bd setup claude --stealth # Stealth mode: flush only, no git operations bd setup claude --remove # Remove the hook and the CLAUDE.md section ``` diff --git a/internal/templates/agents/golden_test.go b/internal/templates/agents/golden_test.go index e49b0acf8..924753f5b 100644 --- a/internal/templates/agents/golden_test.go +++ b/internal/templates/agents/golden_test.go @@ -32,13 +32,16 @@ type managedSectionVariant struct { // managedSectionVariants lists every managed section bd renders: both // profiles, each with and without the `bd dolt push` lines that depend on a -// configured Dolt remote. NoPush renders the no-remote bytes +// configured Dolt remote, and each worded for a user-level file +// (UserLevelRenderOpts). NoPush renders the no-remote bytes // (TestManagedSectionNoPushMatchesNoRemote), so it needs no variant of its own. var managedSectionVariants = []managedSectionVariant{ {name: "minimal", profile: ProfileMinimal, opts: RenderOpts{HasRemote: true}}, {name: "minimal-no-remote", profile: ProfileMinimal, opts: RenderOpts{}}, + {name: "minimal-user", profile: ProfileMinimal, opts: UserLevelRenderOpts()}, {name: "full", profile: ProfileFull, opts: RenderOpts{HasRemote: true}}, {name: "full-no-remote", profile: ProfileFull, opts: RenderOpts{}}, + {name: "full-user", profile: ProfileFull, opts: UserLevelRenderOpts()}, } // TestManagedSectionGolden pins each managed section byte for byte, markers @@ -60,8 +63,10 @@ func TestManagedSectionHashes(t *testing.T) { want := map[string]string{ "minimal": "6ffdf896", "minimal-no-remote": "cdcea925", + "minimal-user": "52c58e00", "full": "bacef91e", "full-no-remote": "9c890b20", + "full-user": "0d9cad1f", } for _, v := range managedSectionVariants { got := CurrentHashWithOpts(v.profile, v.opts) diff --git a/internal/templates/agents/render.go b/internal/templates/agents/render.go index ee4d1c129..108bf9227 100644 --- a/internal/templates/agents/render.go +++ b/internal/templates/agents/render.go @@ -52,6 +52,11 @@ type RenderOpts struct { // NoPush indicates the rig is declared local-only (no-push: true in config). // When true, "bd dolt push" is omitted regardless of HasRemote. NoPush bool + // UserLevel words the section for a user-level instructions file, such as + // ~/.claude/CLAUDE.md, that the agent loads in every repository: instead + // of stating that the current project uses bd, it applies only in + // repositories that do, and so do its task-tracking rules. + UserLevel bool } // omitsDoltPush reports whether rendered instructions leave out "bd dolt push": @@ -67,6 +72,13 @@ func DefaultRenderOpts() RenderOpts { return RenderOpts{HasRemote: true} } +// UserLevelRenderOpts returns the fixed opts for a user-level instructions +// file. No one repository's beads config applies to it, so it assumes a +// remote, as DefaultRenderOpts does. +func UserLevelRenderOpts() RenderOpts { + return RenderOpts{HasRemote: true, UserLevel: true} +} + // RenderSection returns the beads integration section for the given profile, // wrapped in markers that include version, profile, and hash metadata for freshness detection. // Assumes a Dolt remote is configured (backward-compatible). Use RenderSectionWithOpts @@ -224,10 +236,33 @@ func templateBodyWithOpts(profile Profile, opts RenderOpts) string { if opts.omitsDoltPush() { body = stripDoltPushReferences(body) } + if opts.UserLevel { + body = userLevelWording.Replace(body) + } return body } +// userLevelScope opens a user-level section: the agent loads that file in +// every repository, including ones that do not use beads. +const userLevelScope = "This Beads block applies only in beads repositories: repositories that use **bd (beads)** for issue tracking, with a `.beads/` directory. Ignore it in any other repository." + +// userLevelWording rewords the lines of both profiles' bodies that state the +// current project uses bd, or that set a task-tracking rule with no condition, +// so they apply only in beads repositories (RenderOpts.UserLevel). +var userLevelWording = strings.NewReplacer( + "This project uses **bd (beads)** for issue tracking. Run `bd prime`", + userLevelScope+" In a beads repository, run `bd prime`", + "- Use `bd` for ALL task tracking", + "- In a beads repository, use `bd` for ALL task tracking", + "- Use `bd remember` for durable project facts", + "- In a beads repository, use `bd remember` for durable project facts", + "**IMPORTANT**: This project uses **bd (beads)** for ALL issue tracking.", + userLevelScope+"\n\n**IMPORTANT**: In a beads repository, use **bd (beads)** for ALL issue tracking.", + "- ✅ Use bd for ALL task tracking", + "- ✅ In a beads repository, use bd for ALL task tracking", +) + func normalizeEmbeddedMarkdown(content string) string { return strings.TrimRight(strings.ReplaceAll(content, "\r\n", "\n"), "\n") } diff --git a/internal/templates/agents/render_test.go b/internal/templates/agents/render_test.go index 6df83564c..c0bd12d4a 100644 --- a/internal/templates/agents/render_test.go +++ b/internal/templates/agents/render_test.go @@ -541,3 +541,37 @@ func TestReplaceSectionWithOptsDetectsRemoteChange(t *testing.T) { t.Error("replaced content should not contain 'bd dolt push' with HasRemote=false") } } + +// A user-level section loads in every repository, so it must not say the +// current one uses bd, and its task-tracking rules hold only in repositories +// that do. The wording is matched against the templates' text, so a template +// edit that the rewording no longer finds fails here. +func TestRenderSectionUserLevelAppliesOnlyInBeadsRepositories(t *testing.T) { + for _, profile := range []Profile{ProfileMinimal, ProfileFull} { + section := RenderSectionWithOpts(profile, UserLevelRenderOpts()) + if strings.Contains(section, "This project uses") { + t.Errorf("%s user-level section says the current project uses bd:\n%s", profile, section) + } + if n := strings.Count(section, userLevelScope); n != 1 { + t.Errorf("%s user-level section states its scope %d times, want 1", profile, n) + } + } + rules := map[Profile][]string{ + ProfileMinimal: { + "- In a beads repository, use `bd` for ALL task tracking — do NOT use TodoWrite", + "- In a beads repository, use `bd remember` for durable project facts", + }, + ProfileFull: { + "**IMPORTANT**: In a beads repository, use **bd (beads)** for ALL issue tracking.", + "- ✅ In a beads repository, use bd for ALL task tracking", + }, + } + for profile, want := range rules { + section := RenderSectionWithOpts(profile, UserLevelRenderOpts()) + for _, rule := range want { + if !strings.Contains(section, rule) { + t.Errorf("%s user-level section lacks the scoped rule %q", profile, rule) + } + } + } +} diff --git a/internal/templates/agents/testdata/managed-section-full-user.md b/internal/templates/agents/testdata/managed-section-full-user.md new file mode 100644 index 000000000..56e8785fc --- /dev/null +++ b/internal/templates/agents/testdata/managed-section-full-user.md @@ -0,0 +1,133 @@ + +## Issue Tracking with bd (beads) + +This Beads block applies only in beads repositories: repositories that use **bd (beads)** for issue tracking, with a `.beads/` directory. Ignore it in any other repository. + +**IMPORTANT**: In a beads repository, use **bd (beads)** for ALL issue tracking. Do NOT use markdown TODOs, task lists, or other tracking methods. + +### Why bd? + +- Dependency-aware: Track blockers and relationships between issues +- Git-friendly: Dolt-powered version control with native sync +- Agent-optimized: JSON output, ready work detection, discovered-from links +- Prevents duplicate tracking systems and confusion + +### Quick Start + +**Check for ready work:** + +```bash +bd ready --json +``` + +**Create new issues:** + +```bash +bd create "Issue title" --description="Detailed context" -t bug|feature|task -p 0-4 --json +bd create "Issue title" --description="What this issue is about" -p 1 --deps discovered-from:bd-123 --json +``` + +**Claim and update:** + +```bash +bd update --claim --json +bd update bd-42 --priority 1 --json +``` + +**Complete work:** + +```bash +bd close bd-42 --reason "Completed" --json +``` + +### Issue Types + +- `bug` - Something broken +- `feature` - New functionality +- `task` - Work item (tests, docs, refactoring) +- `epic` - Large feature with subtasks +- `chore` - Maintenance (dependencies, tooling) + +### Priorities + +- `0` - Critical (security, data loss, broken builds) +- `1` - High (major features, important bugs) +- `2` - Medium (default, nice-to-have) +- `3` - Low (polish, optimization) +- `4` - Backlog (future ideas) + +### Workflow for AI Agents + +1. **Check ready work**: `bd ready` shows unblocked issues +2. **Claim your task atomically**: `bd update --claim` +3. **Work on it**: Implement, test, document +4. **Discover new work?** Create linked issue: + - `bd create "Found bug" --description="Details about what was found" -p 1 --deps discovered-from:` +5. **Complete**: `bd close --reason "Done"` + +### Quality +- Use `--acceptance` and `--design` fields when creating issues +- Use `--validate` to check description completeness + +### Lifecycle +- `bd defer ` / `bd supersede ` for issue management +- `bd stale` / `bd orphans` / `bd lint` for hygiene +- `bd human ` to flag for human decisions +- `bd formula list` / `bd mol pour ` for structured workflows + +### Sync + +bd stores issue history in Dolt: + +- Each write auto-commits to Dolt history +- Use `bd dolt push`/`bd dolt pull` for remote sync +- Do not treat `.beads/issues.jsonl` as the sync protocol + +**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md for details and anti-patterns. + +### Important Rules + +- ✅ In a beads repository, use bd for ALL task tracking +- ✅ Always use `--json` flag for programmatic use +- ✅ Link discovered work with `discovered-from` dependencies +- ✅ Check `bd ready` before asking "what should I work on?" +- ❌ Do NOT create markdown TODO lists +- ❌ Do NOT use external issue trackers +- ❌ Do NOT duplicate tracking systems + +For more details, see README.md and https://github.com/gastownhall/beads/blob/main/docs/getting-started/quickstart.md. + +## Agent Context Profiles + +The managed Beads block is task-tracking guidance, not permission to override repository, user, or orchestrator instructions. + +- **Conservative (default)**: Use `bd` for task tracking. Do not run git commits, git pushes, or Dolt remote sync unless explicitly asked. At handoff, report changed files, validation, and suggested next commands. +- **Minimal**: Keep tool instruction files as pointers to `bd prime`; use the same conservative git policy unless active instructions say otherwise. +- **Team-maintainer**: Only when the repository explicitly opts in, agents may close beads, run quality gates, commit, and push as part of session close. A current "do not commit" or "do not push" instruction still wins. + +## Session Completion + +This protocol applies when ending a Beads implementation workflow. It is subordinate to explicit user, repository, and orchestrator instructions. + +1. **File issues for remaining work** - Create beads for anything that needs follow-up +2. **Run quality gates** (if code changed) - Tests, linters, builds +3. **Update issue status** - Close finished work, update in-progress items +4. **Handle git/sync by active profile**: + ```bash + # Conservative/minimal/default: report status and proposed commands; wait for approval. + git status + + # Team-maintainer opt-in only, unless current instructions forbid it: + git pull --rebase + bd dolt push + git push + git status + ``` +5. **Hand off** - Summarize changes, validation, issue status, and any blocked sync/commit/push step + +**Critical rules:** +- Explicit user or orchestrator instructions override this Beads block. +- Do not commit or push without clear authority from the active profile or the current user request. +- If a required sync or push is blocked, stop and report the exact command and error. + + diff --git a/internal/templates/agents/testdata/managed-section-minimal-user.md b/internal/templates/agents/testdata/managed-section-minimal-user.md new file mode 100644 index 000000000..5c51e2c14 --- /dev/null +++ b/internal/templates/agents/testdata/managed-section-minimal-user.md @@ -0,0 +1,55 @@ + +## Beads Issue Tracker + +This Beads block applies only in beads repositories: repositories that use **bd (beads)** for issue tracking, with a `.beads/` directory. Ignore it in any other repository. In a beads repository, run `bd prime` to see full workflow context and commands. + +### Quick Reference + +```bash +bd ready # Find available work +bd show # View issue details +bd update --claim # Claim work +bd close # Complete work +``` + +### Rules + +- In a beads repository, use `bd` for ALL task tracking — do NOT use TodoWrite, TaskCreate, or markdown TODO lists +- Run `bd prime` for detailed command reference and session close protocol +- In a beads repository, use `bd remember` for durable project facts — not per-tool memory files, which fragment across accounts; keep per-operator preferences in your harness's own memory + +**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md for details and anti-patterns. + +## Agent Context Profiles + +The managed Beads block is task-tracking guidance, not permission to override repository, user, or orchestrator instructions. + +- **Conservative (default)**: Use `bd` for task tracking. Do not run git commits, git pushes, or Dolt remote sync unless explicitly asked. At handoff, report changed files, validation, and suggested next commands. +- **Minimal**: Keep tool instruction files as pointers to `bd prime`; use the same conservative git policy unless active instructions say otherwise. +- **Team-maintainer**: Only when the repository explicitly opts in, agents may close beads, run quality gates, commit, and push as part of session close. A current "do not commit" or "do not push" instruction still wins. + +## Session Completion + +This protocol applies when ending a Beads implementation workflow. It is subordinate to explicit user, repository, and orchestrator instructions. + +1. **File issues for remaining work** - Create beads for anything that needs follow-up +2. **Run quality gates** (if code changed) - Tests, linters, builds +3. **Update issue status** - Close finished work, update in-progress items +4. **Handle git/sync by active profile**: + ```bash + # Conservative/minimal/default: report status and proposed commands; wait for approval. + git status + + # Team-maintainer opt-in only, unless current instructions forbid it: + git pull --rebase + bd dolt push + git push + git status + ``` +5. **Hand off** - Summarize changes, validation, issue status, and any blocked sync/commit/push step + +**Critical rules:** +- Explicit user or orchestrator instructions override this Beads block. +- Do not commit or push without clear authority from the active profile or the current user request. +- If a required sync or push is blocked, stop and report the exact command and error. +