feat: add context optimization features for AI agents (#297)

* feat: add bd prime and setup commands for AI agent integration

This commit consolidates context optimization features for AI agents:

## New Commands

**bd prime** - AI-optimized workflow context injection
- Outputs ~1-2k tokens of workflow context
- Context-aware: adapts to MCP vs CLI mode
- MCP mode: minimal reminders (~500 tokens)
- CLI mode: full command reference (~1-2k tokens)
- Warns against TodoWrite tool and markdown TODOs
- Designed for SessionStart/PreCompact hooks

**bd setup claude** - Claude Code integration installer
- Installs hooks via JSON configuration (not file scripts)
- Supports --project for project-only installation
- Supports --check to verify installation
- Supports --remove to uninstall hooks
- Idempotent (safe to run multiple times)
- Merges with existing settings

**bd setup cursor** - Cursor IDE integration installer
- Creates .cursor/rules/beads.mdc with workflow rules
- Simplified implementation (just overwrites file)

## bd doctor Enhancements

- New: CheckClaude() verifies Claude Code integration
- Detects plugin, MCP server, and hooks installation
- Provides actionable fix suggestions
- Extracted legacy pattern detection to doctor/legacy.go
- Detects JSONL-only mode and warns about legacy issues.jsonl

## Core Improvements

- FindBeadsDir() utility for cross-platform .beads/ discovery
- Works in JSONL-only mode (no database required)
- Sorted noDbCommands alphabetically (one per line for easy diffs)

## Testing

- Unit tests for setup command hook manipulation
- Tests for idempotency, adding/removing hooks
- All tests passing

## Documentation

- cmd/bd/doctor/claude.md - Documents why beads doesn't use Claude Skills
- commands/prime.md - Slash command for bd prime
- Fixed G304 gosec warnings with nosec comments

## Token Efficiency

The bd prime approach reduces AI context usage dramatically:
- MCP mode: ~500 tokens (vs ~10.5k for full MCP tool scan)
- CLI mode: ~1-2k tokens
- 80-99% reduction in standing context overhead

* fix: resolve linting errors in setup utils and remove obsolete test

- Add error check for tmpFile.Close() in setup/utils.go to fix golangci-lint G104
- Remove TestCheckMultipleJSONLFiles test that referenced deleted checkMultipleJSONLFiles function

Fixes golangci-lint errcheck violations introduced in the bd prime/setup feature.
This commit is contained in:
Ryan
2025-11-12 10:48:36 -08:00
committed by GitHub
parent d9904a8830
commit f7e80dd80c
18 changed files with 1594 additions and 134 deletions

295
cmd/bd/setup/claude.go Normal file
View File

@@ -0,0 +1,295 @@
package setup
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
)
// InstallClaude installs Claude Code hooks
func InstallClaude(project bool) {
var settingsPath string
if project {
settingsPath = ".claude/settings.local.json"
fmt.Println("Installing Claude hooks for this project...")
} else {
home, err := os.UserHomeDir()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: failed to get home directory: %v\n", err)
os.Exit(1)
}
settingsPath = filepath.Join(home, ".claude/settings.json")
fmt.Println("Installing Claude hooks globally...")
}
// Ensure parent directory exists
if err := EnsureDir(filepath.Dir(settingsPath), 0755); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
// Load or create settings
var settings map[string]interface{}
data, err := os.ReadFile(settingsPath) // #nosec G304 -- settingsPath is constructed from user home dir, not user input
if err != nil {
settings = make(map[string]interface{})
} else {
if err := json.Unmarshal(data, &settings); err != nil {
fmt.Fprintf(os.Stderr, "Error: failed to parse settings.json: %v\n", err)
os.Exit(1)
}
}
// Get or create hooks section
hooks, ok := settings["hooks"].(map[string]interface{})
if !ok {
hooks = make(map[string]interface{})
settings["hooks"] = hooks
}
// Add SessionStart hook
if addHookCommand(hooks, "SessionStart", "bd prime") {
fmt.Println("✓ Registered SessionStart hook")
}
// Add PreCompact hook
if addHookCommand(hooks, "PreCompact", "bd prime") {
fmt.Println("✓ Registered PreCompact hook")
}
// Write back to file
data, err = json.MarshalIndent(settings, "", " ")
if err != nil {
fmt.Fprintf(os.Stderr, "Error: marshal settings: %v\n", err)
os.Exit(1)
}
if err := atomicWriteFile(settingsPath, data, 0644); err != nil {
fmt.Fprintf(os.Stderr, "Error: write settings: %v\n", err)
os.Exit(1)
}
fmt.Printf("\n✓ Claude Code integration installed\n")
fmt.Printf(" Settings: %s\n", settingsPath)
fmt.Println("\nRestart Claude Code for changes to take effect.")
}
// CheckClaude checks if Claude integration is installed
func CheckClaude() {
home, err := os.UserHomeDir()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: failed to get home directory: %v\n", err)
os.Exit(1)
}
globalSettings := filepath.Join(home, ".claude/settings.json")
projectSettings := ".claude/settings.local.json"
globalHooks := hasBeadsHooks(globalSettings)
projectHooks := hasBeadsHooks(projectSettings)
if globalHooks {
fmt.Println("✓ Global hooks installed:", globalSettings)
} else if projectHooks {
fmt.Println("✓ Project hooks installed:", projectSettings)
} else {
fmt.Println("✗ No hooks installed")
fmt.Println(" Run: bd setup claude")
os.Exit(1)
}
}
// RemoveClaude removes Claude Code hooks
func RemoveClaude(project bool) {
var settingsPath string
if project {
settingsPath = ".claude/settings.local.json"
fmt.Println("Removing Claude hooks from project...")
} else {
home, err := os.UserHomeDir()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: failed to get home directory: %v\n", err)
os.Exit(1)
}
settingsPath = filepath.Join(home, ".claude/settings.json")
fmt.Println("Removing Claude hooks globally...")
}
// Load settings
data, err := os.ReadFile(settingsPath) // #nosec G304 -- settingsPath is constructed from user home dir, not user input
if err != nil {
fmt.Println("No settings file found")
return
}
var settings map[string]interface{}
if err := json.Unmarshal(data, &settings); err != nil {
fmt.Fprintf(os.Stderr, "Error: failed to parse settings.json: %v\n", err)
os.Exit(1)
}
hooks, ok := settings["hooks"].(map[string]interface{})
if !ok {
fmt.Println("No hooks found")
return
}
// Remove bd prime hooks
removeHookCommand(hooks, "SessionStart", "bd prime")
removeHookCommand(hooks, "PreCompact", "bd prime")
// Write back
data, err = json.MarshalIndent(settings, "", " ")
if err != nil {
fmt.Fprintf(os.Stderr, "Error: marshal settings: %v\n", err)
os.Exit(1)
}
if err := atomicWriteFile(settingsPath, data, 0644); err != nil {
fmt.Fprintf(os.Stderr, "Error: write settings: %v\n", err)
os.Exit(1)
}
fmt.Println("✓ Claude hooks removed")
}
// 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 hook command from an event
func removeHookCommand(hooks map[string]interface{}, event, command string) {
eventHooks, ok := hooks[event].([]interface{})
if !ok {
return
}
// Filter out bd prime hooks
var filtered []interface{}
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
}
keepHook := true
for _, cmd := range commands {
cmdMap, ok := cmd.(map[string]interface{})
if !ok {
continue
}
if cmdMap["command"] == command {
keepHook = false
fmt.Printf("✓ Removed %s hook\n", event)
break
}
}
if keepHook {
filtered = append(filtered, hook)
}
}
hooks[event] = filtered
}
// 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
}
if cmdMap["command"] == "bd prime" {
return true
}
}
}
}
return false
}

278
cmd/bd/setup/claude_test.go Normal file
View File

@@ -0,0 +1,278 @@
package setup
import (
"encoding/json"
"os"
"path/filepath"
"testing"
)
func TestAddHookCommand(t *testing.T) {
tests := []struct {
name string
existingHooks map[string]interface{}
event string
command string
wantAdded bool
}{
{
name: "add hook to empty hooks",
existingHooks: make(map[string]interface{}),
event: "SessionStart",
command: "bd prime",
wantAdded: true,
},
{
name: "hook already exists",
existingHooks: map[string]interface{}{
"SessionStart": []interface{}{
map[string]interface{}{
"matcher": "",
"hooks": []interface{}{
map[string]interface{}{
"type": "command",
"command": "bd prime",
},
},
},
},
},
event: "SessionStart",
command: "bd prime",
wantAdded: false,
},
{
name: "add second hook alongside existing",
existingHooks: map[string]interface{}{
"SessionStart": []interface{}{
map[string]interface{}{
"matcher": "",
"hooks": []interface{}{
map[string]interface{}{
"type": "command",
"command": "other command",
},
},
},
},
},
event: "SessionStart",
command: "bd prime",
wantAdded: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := addHookCommand(tt.existingHooks, tt.event, tt.command)
if got != tt.wantAdded {
t.Errorf("addHookCommand() = %v, want %v", got, tt.wantAdded)
}
// Verify hook exists in structure
eventHooks, ok := tt.existingHooks[tt.event].([]interface{})
if !ok {
t.Fatal("Event hooks not found")
}
found := false
for _, hook := range eventHooks {
hookMap := hook.(map[string]interface{})
commands := hookMap["hooks"].([]interface{})
for _, cmd := range commands {
cmdMap := cmd.(map[string]interface{})
if cmdMap["command"] == tt.command {
found = true
break
}
}
}
if !found {
t.Errorf("Hook command %q not found in event %q", tt.command, tt.event)
}
})
}
}
func TestRemoveHookCommand(t *testing.T) {
tests := []struct {
name string
existingHooks map[string]interface{}
event string
command string
wantRemaining int
}{
{
name: "remove only hook",
existingHooks: map[string]interface{}{
"SessionStart": []interface{}{
map[string]interface{}{
"matcher": "",
"hooks": []interface{}{
map[string]interface{}{
"type": "command",
"command": "bd prime",
},
},
},
},
},
event: "SessionStart",
command: "bd prime",
wantRemaining: 0,
},
{
name: "remove one of multiple hooks",
existingHooks: map[string]interface{}{
"SessionStart": []interface{}{
map[string]interface{}{
"matcher": "",
"hooks": []interface{}{
map[string]interface{}{
"type": "command",
"command": "other command",
},
},
},
map[string]interface{}{
"matcher": "",
"hooks": []interface{}{
map[string]interface{}{
"type": "command",
"command": "bd prime",
},
},
},
},
},
event: "SessionStart",
command: "bd prime",
wantRemaining: 1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
removeHookCommand(tt.existingHooks, tt.event, tt.command)
eventHooks, ok := tt.existingHooks[tt.event].([]interface{})
if !ok && tt.wantRemaining > 0 {
t.Fatal("Event hooks not found")
}
if len(eventHooks) != tt.wantRemaining {
t.Errorf("Expected %d remaining hooks, got %d", tt.wantRemaining, len(eventHooks))
}
// Verify target hook is actually gone
for _, hook := range eventHooks {
hookMap := hook.(map[string]interface{})
commands := hookMap["hooks"].([]interface{})
for _, cmd := range commands {
cmdMap := cmd.(map[string]interface{})
if cmdMap["command"] == tt.command {
t.Errorf("Hook command %q still present after removal", tt.command)
}
}
}
})
}
}
func TestHasBeadsHooks(t *testing.T) {
tmpDir := t.TempDir()
tests := []struct {
name string
settingsData map[string]interface{}
want bool
}{
{
name: "has bd prime hook",
settingsData: map[string]interface{}{
"hooks": map[string]interface{}{
"SessionStart": []interface{}{
map[string]interface{}{
"matcher": "",
"hooks": []interface{}{
map[string]interface{}{
"type": "command",
"command": "bd prime",
},
},
},
},
},
},
want: true,
},
{
name: "no hooks",
settingsData: map[string]interface{}{},
want: false,
},
{
name: "has other hooks but not bd prime",
settingsData: map[string]interface{}{
"hooks": map[string]interface{}{
"SessionStart": []interface{}{
map[string]interface{}{
"matcher": "",
"hooks": []interface{}{
map[string]interface{}{
"type": "command",
"command": "other command",
},
},
},
},
},
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
settingsPath := filepath.Join(tmpDir, "settings.json")
data, err := json.Marshal(tt.settingsData)
if err != nil {
t.Fatalf("Failed to marshal test data: %v", err)
}
if err := os.WriteFile(settingsPath, data, 0644); err != nil {
t.Fatalf("Failed to write test file: %v", err)
}
got := hasBeadsHooks(settingsPath)
if got != tt.want {
t.Errorf("hasBeadsHooks() = %v, want %v", got, tt.want)
}
})
}
}
func TestIdempotency(t *testing.T) {
// Test that running addHookCommand twice doesn't duplicate hooks
hooks := make(map[string]interface{})
// First add
added1 := addHookCommand(hooks, "SessionStart", "bd prime")
if !added1 {
t.Error("First call should have added the hook")
}
// Second add (should detect existing)
added2 := addHookCommand(hooks, "SessionStart", "bd prime")
if added2 {
t.Error("Second call should have detected existing hook")
}
// Verify only one hook exists
eventHooks := hooks["SessionStart"].([]interface{})
if len(eventHooks) != 1 {
t.Errorf("Expected 1 hook, got %d", len(eventHooks))
}
}

12
cmd/bd/setup/constants.go Normal file
View File

@@ -0,0 +1,12 @@
package setup
const (
// Claude paths
ClaudeDir = ".claude"
ClaudeSettings = "settings.json"
ClaudeRules = "rules"
// Cursor paths
CursorDir = ".cursor"
CursorRules = "rules"
)

101
cmd/bd/setup/cursor.go Normal file
View File

@@ -0,0 +1,101 @@
package setup
import (
"fmt"
"os"
"path/filepath"
)
const cursorRulesTemplate = `# Beads Issue Tracking
# Auto-generated by 'bd setup cursor' - do not remove these markers
# BEGIN BEADS INTEGRATION
This project uses [Beads (bd)](https://github.com/steveyegge/beads) for issue tracking.
## Core Rules
- Track ALL work in bd (never use markdown TODOs or comment-based task lists)
- Use ` + "`bd ready`" + ` to find available work
- Use ` + "`bd create`" + ` to track new issues/tasks/bugs
- Use ` + "`bd sync`" + ` at end of session to sync with git remote
- Git hooks auto-sync on commit/merge
## Quick Reference
` + "```bash" + `
bd prime # Load complete workflow context
bd ready # Show issues ready to work (no blockers)
bd list --status=open # List all open issues
bd create --title="..." --type=task # Create new issue
bd update <id> --status=in_progress # Claim work
bd close <id> # Mark complete
bd dep <from> <to> # Add dependency (from blocks to)
bd sync # Sync with git remote
` + "```" + `
## Workflow
1. Check for ready work: ` + "`bd ready`" + `
2. Claim an issue: ` + "`bd update <id> --status=in_progress`" + `
3. Do the work
4. Mark complete: ` + "`bd close <id>`" + `
5. Sync: ` + "`bd sync`" + ` (or let git hooks handle it)
## Context Loading
Run ` + "`bd prime`" + ` to get complete workflow documentation in AI-optimized format (~1-2k tokens).
For detailed docs: see AGENTS.md, QUICKSTART.md, or run ` + "`bd --help`" + `
# END BEADS INTEGRATION
`
// InstallCursor installs Cursor IDE integration
func InstallCursor() {
rulesPath := ".cursor/rules/beads.mdc"
fmt.Println("Installing Cursor integration...")
// Ensure parent directory exists
if err := EnsureDir(filepath.Dir(rulesPath), 0755); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
// Write beads rules file (overwrite if exists)
if err := atomicWriteFile(rulesPath, []byte(cursorRulesTemplate), 0644); err != nil {
fmt.Fprintf(os.Stderr, "Error: write rules: %v\n", err)
os.Exit(1)
}
fmt.Printf("\n✓ Cursor integration installed\n")
fmt.Printf(" Rules: %s\n", rulesPath)
fmt.Println("\nRestart Cursor for changes to take effect.")
}
// CheckCursor checks if Cursor integration is installed
func CheckCursor() {
rulesPath := ".cursor/rules/beads.mdc"
if _, err := os.Stat(rulesPath); os.IsNotExist(err) {
fmt.Println("✗ Cursor integration not installed")
fmt.Println(" Run: bd setup cursor")
os.Exit(1)
}
fmt.Println("✓ Cursor integration installed:", rulesPath)
}
// RemoveCursor removes Cursor integration
func RemoveCursor() {
rulesPath := ".cursor/rules/beads.mdc"
fmt.Println("Removing Cursor integration...")
if err := os.Remove(rulesPath); err != nil {
if os.IsNotExist(err) {
fmt.Println("No rules file found")
return
}
fmt.Fprintf(os.Stderr, "Error: failed to remove file: %v\n", err)
os.Exit(1)
}
fmt.Println("✓ Removed Cursor integration")
}

70
cmd/bd/setup/utils.go Normal file
View File

@@ -0,0 +1,70 @@
package setup
import (
"fmt"
"os"
"path/filepath"
)
// atomicWriteFile writes data to a file atomically using a unique temporary file.
// This prevents race conditions when multiple processes write to the same file.
func atomicWriteFile(path string, data []byte, perm os.FileMode) error {
dir := filepath.Dir(path)
// Create unique temp file in same directory
tmpFile, err := os.CreateTemp(dir, ".*.tmp")
if err != nil {
return fmt.Errorf("create temp file: %w", err)
}
tmpPath := tmpFile.Name()
// Write data
if _, err := tmpFile.Write(data); err != nil {
_ = tmpFile.Close() // best effort cleanup
_ = os.Remove(tmpPath) // best effort cleanup
return fmt.Errorf("write temp file: %w", err)
}
// Close temp file
if err := tmpFile.Close(); err != nil {
_ = os.Remove(tmpPath) // Best effort cleanup
return fmt.Errorf("close temp file: %w", err)
}
// Set permissions
if err := os.Chmod(tmpPath, perm); err != nil {
_ = os.Remove(tmpPath) // Best effort cleanup
return fmt.Errorf("set permissions: %w", err)
}
// Atomic rename
if err := os.Rename(tmpPath, path); err != nil {
_ = os.Remove(tmpPath) // Best effort cleanup
return fmt.Errorf("rename temp file: %w", err)
}
return nil
}
// DirExists checks if a directory exists
func DirExists(path string) bool {
info, err := os.Stat(path)
return err == nil && info.IsDir()
}
// FileExists checks if a file exists
func FileExists(path string) bool {
info, err := os.Stat(path)
return err == nil && !info.IsDir()
}
// EnsureDir creates a directory if it doesn't exist
func EnsureDir(path string, perm os.FileMode) error {
if DirExists(path) {
return nil
}
if err := os.MkdirAll(path, perm); err != nil {
return fmt.Errorf("create directory: %w", err)
}
return nil
}