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

254
cmd/bd/doctor/claude.go Normal file
View File

@@ -0,0 +1,254 @@
package doctor
import (
"encoding/json"
"os"
"os/exec"
"path/filepath"
"strings"
)
// DoctorCheck represents a single diagnostic check result
type DoctorCheck struct {
Name string `json:"name"`
Status string `json:"status"` // "ok", "warning", or "error"
Message string `json:"message"`
Detail string `json:"detail,omitempty"`
Fix string `json:"fix,omitempty"`
}
// CheckClaude returns Claude integration verification as a DoctorCheck
func CheckClaude() DoctorCheck {
// Check what's installed
hasPlugin := isBeadsPluginInstalled()
hasMCP := isMCPServerInstalled()
hasHooks := hasClaudeHooks()
// Plugin provides slash commands and MCP server
if hasPlugin && hasHooks {
return DoctorCheck{
Name: "Claude Integration",
Status: "ok",
Message: "Plugin and hooks installed",
Detail: "Slash commands and workflow reminders enabled",
}
} else if hasPlugin && !hasHooks {
return DoctorCheck{
Name: "Claude Integration",
Status: "warning",
Message: "Plugin installed but hooks missing",
Fix: "Run: bd setup claude",
}
} else if hasMCP && hasHooks {
return DoctorCheck{
Name: "Claude Integration",
Status: "ok",
Message: "MCP server and hooks installed",
Detail: "Workflow reminders enabled (legacy MCP mode)",
}
} else if !hasMCP && !hasPlugin && hasHooks {
return DoctorCheck{
Name: "Claude Integration",
Status: "ok",
Message: "Hooks installed (CLI mode)",
Detail: "Plugin not detected - install for slash commands",
}
} else if hasMCP && !hasHooks {
return DoctorCheck{
Name: "Claude Integration",
Status: "warning",
Message: "MCP server installed but hooks missing",
Fix: "Run: bd setup claude",
}
} else {
return DoctorCheck{
Name: "Claude Integration",
Status: "warning",
Message: "Not configured",
Fix: "Run: bd setup claude (and install beads plugin for slash commands)",
}
}
}
// isBeadsPluginInstalled checks if beads plugin is enabled in Claude Code
func isBeadsPluginInstalled() bool {
home, err := os.UserHomeDir()
if err != nil {
return false
}
settingsPath := filepath.Join(home, ".claude/settings.json")
data, err := os.ReadFile(settingsPath) // #nosec G304 -- settingsPath is constructed from user home dir, not user input
if err != nil {
return false
}
var settings map[string]interface{}
if err := json.Unmarshal(data, &settings); err != nil {
return false
}
// Check enabledPlugins section for beads
enabledPlugins, ok := settings["enabledPlugins"].(map[string]interface{})
if !ok {
return false
}
// Look for beads@beads-marketplace plugin
for key, value := range enabledPlugins {
if strings.Contains(strings.ToLower(key), "beads") {
// Check if it's enabled (value should be true)
if enabled, ok := value.(bool); ok && enabled {
return true
}
}
}
return false
}
// isMCPServerInstalled checks if MCP server is configured
func isMCPServerInstalled() bool {
home, err := os.UserHomeDir()
if err != nil {
return false
}
settingsPath := filepath.Join(home, ".claude/settings.json")
data, err := os.ReadFile(settingsPath) // #nosec G304 -- settingsPath is constructed from user home dir, not user input
if err != nil {
return false
}
var settings map[string]interface{}
if err := json.Unmarshal(data, &settings); err != nil {
return false
}
// Check mcpServers section for beads
mcpServers, ok := settings["mcpServers"].(map[string]interface{})
if !ok {
return false
}
// Look for beads server (any key containing "beads")
for key := range mcpServers {
if strings.Contains(strings.ToLower(key), "beads") {
return true
}
}
return false
}
// hasClaudeHooks checks if Claude hooks are installed
func hasClaudeHooks() bool {
home, err := os.UserHomeDir()
if err != nil {
return false
}
globalSettings := filepath.Join(home, ".claude/settings.json")
projectSettings := ".claude/settings.local.json"
return hasBeadsHooks(globalSettings) || hasBeadsHooks(projectSettings)
}
// 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
}
// verifyPrimeOutput checks if bd prime command works and adapts correctly
// Returns a check result
func VerifyPrimeOutput() DoctorCheck {
cmd := exec.Command("bd", "prime")
output, err := cmd.CombinedOutput()
if err != nil {
return DoctorCheck{
Name: "bd prime Command",
Status: "error",
Message: "Command failed to execute",
Fix: "Ensure bd is installed and in PATH",
}
}
if len(output) == 0 {
return DoctorCheck{
Name: "bd prime Command",
Status: "error",
Message: "No output produced",
Detail: "Expected workflow context markdown",
}
}
// Check if output adapts to MCP mode
hasMCP := isMCPServerInstalled()
outputStr := string(output)
if hasMCP && strings.Contains(outputStr, "mcp__plugin_beads_beads__") {
return DoctorCheck{
Name: "bd prime Output",
Status: "ok",
Message: "MCP mode detected",
Detail: "Outputting workflow reminders",
}
} else if !hasMCP && strings.Contains(outputStr, "bd ready") {
return DoctorCheck{
Name: "bd prime Output",
Status: "ok",
Message: "CLI mode detected",
Detail: "Outputting full command reference",
}
} else {
return DoctorCheck{
Name: "bd prime Output",
Status: "warning",
Message: "Output may not be adapting to environment",
}
}
}

67
cmd/bd/doctor/claude.md Normal file
View File

@@ -0,0 +1,67 @@
# Claude Code Integration Design
This document explains design decisions for Claude Code integration in beads.
## Integration Approach
Beads uses a simple, universal approach to Claude Code integration:
- `bd prime` command for context injection
- Hooks (SessionStart/PreCompact) for automatic context refresh
- Optional: Plugin for slash commands and enhanced UX
- Optional: MCP server for native tool access (legacy)
## Why Not Claude Skills?
**Decision: Beads does NOT use or require Claude Skills (.claude/skills/)**
### Reasons
1. **Redundant with bd prime**
- `bd prime` already provides workflow context (~1-2k tokens)
- Skills would duplicate this information
- More systems = more complexity
2. **Simplicity is core to beads**
- Workflow fits in simple command set: ready → create → update → close → sync
- Already well-documented in ~1-2k tokens
- Complex workflow orchestration not needed
3. **Editor agnostic**
- Skills are Claude-specific
- Breaks beads' editor-agnostic philosophy
- Cursor, Windsurf, Zed, etc. wouldn't benefit
4. **Maintenance burden**
- Another system to document and test
- Another thing that can drift out of sync
- Another migration path when things change
### If Skills were needed...
They should be:
- Provided by the beads plugin (not bd core tool)
- Complementary (not replacing) bd prime
- Optional power-user workflows only
- Opt-in, never required
### Current approach is better
-`bd prime` - Universal context injection
- ✅ Hooks - Automatic context refresh
- ✅ Plugin - Optional Claude-specific enhancements
- ✅ MCP - Optional native tool access (legacy)
- ❌ Skills - Unnecessary complexity
Users who want custom Skills can create their own, but beads doesn't ship with or require them.
## Related Files
- `cmd/bd/prime.go` - Context generation
- `cmd/bd/setup/claude.go` - Hook installation
- `cmd/bd/doctor/claude.go` - Integration verification
- `docs/CLAUDE.md` - General project guidance for Claude
## References
- [Claude Skills Documentation](https://support.claude.com/en/articles/12580051-teach-claude-your-way-of-working-using-skills)
- [Claude Skills Best Practices](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/best-practices)

108
cmd/bd/doctor/legacy.go Normal file
View File

@@ -0,0 +1,108 @@
package doctor
import (
"fmt"
"os"
"path/filepath"
"strings"
)
// CheckLegacyBeadsSlashCommands detects old /beads:* slash commands in documentation
// and recommends migration to bd prime hooks for better token efficiency.
//
// Old pattern: /beads:quickstart, /beads:ready (~10.5k tokens per session)
// New pattern: bd prime hooks (~50-2k tokens per session)
func CheckLegacyBeadsSlashCommands(repoPath string) DoctorCheck {
docFiles := []string{
filepath.Join(repoPath, "AGENTS.md"),
filepath.Join(repoPath, "CLAUDE.md"),
filepath.Join(repoPath, ".claude", "CLAUDE.md"),
}
var filesWithLegacyCommands []string
legacyPattern := "/beads:"
for _, docFile := range docFiles {
content, err := os.ReadFile(docFile) // #nosec G304 - controlled paths from repoPath
if err != nil {
continue // File doesn't exist or can't be read
}
if strings.Contains(string(content), legacyPattern) {
filesWithLegacyCommands = append(filesWithLegacyCommands, filepath.Base(docFile))
}
}
if len(filesWithLegacyCommands) == 0 {
return DoctorCheck{
Name: "Documentation",
Status: "ok",
Message: "No legacy beads slash commands detected",
}
}
return DoctorCheck{
Name: "Documentation",
Status: "warning",
Message: fmt.Sprintf("Legacy /beads:* slash commands found in: %s", strings.Join(filesWithLegacyCommands, ", ")),
Detail: "Old pattern: /beads:quickstart, /beads:ready (~10.5k tokens)",
Fix: "Migration steps:\n" +
" 1. Run 'bd setup claude' (or 'bd setup cursor') to install bd prime hooks\n" +
" 2. Remove /beads:* slash commands from AGENTS.md/CLAUDE.md\n" +
" 3. Add this to AGENTS.md/CLAUDE.md for team members without hooks:\n" +
" \"This project uses bd (beads) for issue tracking. Run 'bd prime' at session start for workflow context.\"\n" +
" Token savings: ~10.5k → ~50-2k tokens per session",
}
}
// CheckLegacyJSONLFilename detects if project is using legacy issues.jsonl
// instead of the canonical beads.jsonl filename.
func CheckLegacyJSONLFilename(repoPath string) DoctorCheck {
beadsDir := filepath.Join(repoPath, ".beads")
var jsonlFiles []string
hasIssuesJSON := false
for _, name := range []string{"issues.jsonl", "beads.jsonl"} {
jsonlPath := filepath.Join(beadsDir, name)
if _, err := os.Stat(jsonlPath); err == nil {
jsonlFiles = append(jsonlFiles, name)
if name == "issues.jsonl" {
hasIssuesJSON = true
}
}
}
if len(jsonlFiles) == 0 {
return DoctorCheck{
Name: "JSONL Files",
Status: "ok",
Message: "No JSONL files found (database-only mode)",
}
}
if len(jsonlFiles) == 1 {
// Single JSONL file - check if it's the legacy name
if hasIssuesJSON {
return DoctorCheck{
Name: "JSONL Files",
Status: "warning",
Message: "Using legacy JSONL filename: issues.jsonl",
Fix: "Run 'git mv .beads/issues.jsonl .beads/beads.jsonl' to use canonical name (matches beads.db)",
}
}
return DoctorCheck{
Name: "JSONL Files",
Status: "ok",
Message: fmt.Sprintf("Using %s", jsonlFiles[0]),
}
}
// Multiple JSONL files found
return DoctorCheck{
Name: "JSONL Files",
Status: "warning",
Message: fmt.Sprintf("Multiple JSONL files found: %s", strings.Join(jsonlFiles, ", ")),
Fix: "Run 'git rm .beads/issues.jsonl' to standardize on beads.jsonl (canonical name)",
}
}