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

File diff suppressed because one or more lines are too long

3
.gitignore vendored
View File

@@ -85,6 +85,9 @@ npm-package/package-lock.json
.beads/beads.db?*
bd-original
mcp_agent_mail/
bd-test
bd-fixed
.cursor/
# Python cache files
__pycache__/

View File

@@ -25,6 +25,12 @@ func FindDatabasePath() string {
return beads.FindDatabasePath()
}
// FindBeadsDir finds the .beads/ directory in the current directory tree
// Returns empty string if not found. Supports both database and JSONL-only mode.
func FindBeadsDir() string {
return beads.FindBeadsDir()
}
// FindJSONLPath finds the JSONL file corresponding to a database path
func FindJSONLPath(dbPath string) string {
return beads.FindJSONLPath(dbPath)

View File

@@ -14,6 +14,7 @@ import (
"github.com/fatih/color"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/cmd/bd/doctor"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/daemon"
@@ -156,10 +157,10 @@ func runDiagnostics(path string) doctorResult {
result.OverallOK = false
}
// Check 6: Multiple JSONL files
multiJSONLCheck := checkMultipleJSONLFiles(path)
result.Checks = append(result.Checks, multiJSONLCheck)
if multiJSONLCheck.Status == statusWarning || multiJSONLCheck.Status == statusError {
// Check 6: Legacy JSONL filename (issues.jsonl vs beads.jsonl)
jsonlCheck := convertDoctorCheck(doctor.CheckLegacyJSONLFilename(path))
result.Checks = append(result.Checks, jsonlCheck)
if jsonlCheck.Status == statusWarning || jsonlCheck.Status == statusError {
result.OverallOK = false
}
@@ -191,9 +192,30 @@ func runDiagnostics(path string) doctorResult {
result.OverallOK = false
}
// Check 11: Claude integration
claudeCheck := convertDoctorCheck(doctor.CheckClaude())
result.Checks = append(result.Checks, claudeCheck)
// Don't fail overall check for missing Claude integration, just warn
// Check 12: Legacy beads slash commands in documentation
legacyDocsCheck := convertDoctorCheck(doctor.CheckLegacyBeadsSlashCommands(path))
result.Checks = append(result.Checks, legacyDocsCheck)
// Don't fail overall check for legacy docs, just warn
return result
}
// convertDoctorCheck converts doctor package check to main package check
func convertDoctorCheck(dc doctor.DoctorCheck) doctorCheck {
return doctorCheck{
Name: dc.Name,
Status: dc.Status,
Message: dc.Message,
Detail: dc.Detail,
Fix: dc.Fix,
}
}
func checkInstallation(path string) doctorCheck {
beadsDir := filepath.Join(path, ".beads")
if _, err := os.Stat(beadsDir); os.IsNotExist(err) {
@@ -231,8 +253,20 @@ func checkDatabaseVersion(path string) doctorCheck {
// Check if database file exists
if _, err := os.Stat(dbPath); os.IsNotExist(err) {
// Check if JSONL exists (--no-db mode)
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
if _, err := os.Stat(jsonlPath); err == nil {
// Check both canonical (beads.jsonl) and legacy (issues.jsonl) names
beadsJSONL := filepath.Join(beadsDir, "beads.jsonl")
issuesJSONL := filepath.Join(beadsDir, "issues.jsonl")
if _, err := os.Stat(beadsJSONL); err == nil {
return doctorCheck{
Name: "Database",
Status: statusOK,
Message: "JSONL-only mode",
Detail: "Using beads.jsonl (no SQLite database)",
}
}
if _, err := os.Stat(issuesJSONL); err == nil {
return doctorCheck{
Name: "Database",
Status: statusOK,
@@ -626,42 +660,6 @@ func checkMultipleDatabases(path string) doctorCheck {
}
}
func checkMultipleJSONLFiles(path string) doctorCheck {
beadsDir := filepath.Join(path, ".beads")
var jsonlFiles []string
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 len(jsonlFiles) == 0 {
return doctorCheck{
Name: "JSONL Files",
Status: statusOK,
Message: "No JSONL files found (database-only mode)",
}
}
if len(jsonlFiles) == 1 {
return doctorCheck{
Name: "JSONL Files",
Status: statusOK,
Message: fmt.Sprintf("Using %s", jsonlFiles[0]),
}
}
// Multiple JSONL files found
return doctorCheck{
Name: "JSONL Files",
Status: statusWarning,
Message: fmt.Sprintf("Multiple JSONL files found: %s", strings.Join(jsonlFiles, ", ")),
Fix: "Standardize on one JSONL file (issues.jsonl recommended). Delete or rename the other.",
}
}
func checkDaemonStatus(path string) doctorCheck {
// Normalize path for reliable comparison (handles symlinks)
wsNorm, err := filepath.EvalSymlinks(path)

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)",
}
}

View File

@@ -241,68 +241,6 @@ func TestCheckMultipleDatabases(t *testing.T) {
}
}
func TestCheckMultipleJSONLFiles(t *testing.T) {
tests := []struct {
name string
jsonlFiles []string
expectedStatus string
expectWarning bool
}{
{
name: "no JSONL files",
jsonlFiles: []string{},
expectedStatus: statusOK,
expectWarning: false,
},
{
name: "single issues.jsonl",
jsonlFiles: []string{"issues.jsonl"},
expectedStatus: statusOK,
expectWarning: false,
},
{
name: "single beads.jsonl",
jsonlFiles: []string{"beads.jsonl"},
expectedStatus: statusOK,
expectWarning: false,
},
{
name: "both JSONL files",
jsonlFiles: []string{"issues.jsonl", "beads.jsonl"},
expectedStatus: statusWarning,
expectWarning: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.Mkdir(beadsDir, 0750); err != nil {
t.Fatal(err)
}
// Create test JSONL files
for _, jsonlFile := range tc.jsonlFiles {
path := filepath.Join(beadsDir, jsonlFile)
if err := os.WriteFile(path, []byte{}, 0644); err != nil {
t.Fatal(err)
}
}
check := checkMultipleJSONLFiles(tmpDir)
if check.Status != tc.expectedStatus {
t.Errorf("Expected status %s, got %s", tc.expectedStatus, check.Status)
}
if tc.expectWarning && check.Fix == "" {
t.Error("Expected fix message for warning status")
}
})
}
}
func TestCheckPermissions(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")

View File

@@ -142,7 +142,22 @@ var rootCmd = &cobra.Command{
}
// Skip database initialization for commands that don't need a database
noDbCommands := []string{"init", cmdDaemon, "help", "version", "quickstart", "doctor", "merge", "completion", "bash", "zsh", "fish", "powershell"}
noDbCommands := []string{
cmdDaemon,
"bash",
"completion",
"doctor",
"fish",
"help",
"init",
"merge",
"powershell",
"prime",
"quickstart",
"setup",
"version",
"zsh",
}
if slices.Contains(noDbCommands, cmd.Name()) {
return
}

191
cmd/bd/prime.go Normal file
View File

@@ -0,0 +1,191 @@
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/spf13/cobra"
"github.com/steveyegge/beads"
)
var (
primeFullMode bool
primeMCPMode bool
)
var primeCmd = &cobra.Command{
Use: "prime",
Short: "Output AI-optimized workflow context",
Long: `Output essential Beads workflow context in AI-optimized markdown format.
Automatically detects if MCP server is active and adapts output:
- MCP mode: Brief workflow reminders (~50 tokens)
- CLI mode: Full command reference (~1-2k tokens)
Designed for Claude Code hooks (SessionStart, PreCompact) to prevent
agents from forgetting bd workflow after context compaction.`,
Run: func(cmd *cobra.Command, args []string) {
// Find .beads/ directory (supports both database and JSONL-only mode)
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
// Not in a beads project - silent exit with success
// CRITICAL: No stderr output, exit 0
// This enables cross-platform hook integration
os.Exit(0)
}
// Detect MCP mode (unless overridden by flags)
mcpMode := isMCPActive()
if primeFullMode {
mcpMode = false
}
if primeMCPMode {
mcpMode = true
}
// Output workflow context (adaptive based on MCP)
if err := outputPrimeContext(mcpMode); err != nil {
// Suppress all errors - silent exit with success
// Never write to stderr (breaks Windows compatibility)
os.Exit(0)
}
},
}
func init() {
primeCmd.Flags().BoolVar(&primeFullMode, "full", false, "Force full CLI output (ignore MCP detection)")
primeCmd.Flags().BoolVar(&primeMCPMode, "mcp", false, "Force MCP mode (minimal output)")
rootCmd.AddCommand(primeCmd)
}
// isMCPActive detects if MCP server is currently active
func isMCPActive() bool {
// Get home directory with fallback
home, err := os.UserHomeDir()
if err != nil {
// Fallback to HOME environment variable
home = os.Getenv("HOME")
if home == "" {
// Can't determine home directory, assume no MCP
return false
}
}
settingsPath := filepath.Join(home, ".claude/settings.json")
data, err := os.ReadFile(settingsPath)
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
}
// outputPrimeContext outputs workflow context in markdown format
func outputPrimeContext(mcpMode bool) error {
if mcpMode {
return outputMCPContext()
}
return outputCLIContext()
}
// outputMCPContext outputs minimal context for MCP users
func outputMCPContext() error {
context := `# Beads Issue Tracker Active
## Core Rules
- Track ALL work in beads (no TodoWrite tool, no markdown TODOs)
- Use bd MCP tools (mcp__plugin_beads_beads__*), not TodoWrite or markdown
Start: Check ` + "`ready`" + ` tool for available work.
`
fmt.Print(context)
return nil
}
// outputCLIContext outputs full CLI reference for non-MCP users
func outputCLIContext() error {
context := `# Beads Workflow Context
> **Context Recovery**: Run ` + "`bd prime`" + ` after compaction, clear, or new session
> Hooks auto-call this in Claude Code when .beads/ detected
## Core Rules
- Track ALL work in beads (no TodoWrite tool, no markdown TODOs)
- Use ` + "`bd create`" + ` to create issues, not TodoWrite tool
- Git workflow: hooks auto-sync, run ` + "`bd sync`" + ` at session end
- Session management: check ` + "`bd ready`" + ` for available work
## Essential Commands
### Finding Work
- ` + "`bd ready`" + ` - Show issues ready to work (no blockers)
- ` + "`bd list --status=open`" + ` - All open issues
- ` + "`bd list --status=in_progress`" + ` - Your active work
- ` + "`bd show <id>`" + ` - Detailed issue view with dependencies
### Creating & Updating
- ` + "`bd create --title=\"...\" --type=task|bug|feature`" + ` - New issue
- ` + "`bd update <id> --status=in_progress`" + ` - Claim work
- ` + "`bd update <id> --assignee=username`" + ` - Assign to someone
- ` + "`bd close <id>`" + ` - Mark complete
- ` + "`bd close <id> --reason=\"explanation\"`" + ` - Close with reason
### Dependencies & Blocking
- ` + "`bd dep <from> <to>`" + ` - Add blocker dependency (from blocks to)
- ` + "`bd blocked`" + ` - Show all blocked issues
- ` + "`bd show <id>`" + ` - See what's blocking/blocked by this issue
### Sync & Collaboration
- ` + "`bd sync`" + ` - Sync with git remote (run at session end)
- ` + "`bd sync --status`" + ` - Check sync status without syncing
### Project Health
- ` + "`bd stats`" + ` - Project statistics (open/closed/blocked counts)
- ` + "`bd doctor`" + ` - Check for issues (sync problems, missing hooks)
## Common Workflows
**Starting work:**
` + "```bash" + `
bd ready # Find available work
bd show <id> # Review issue details
bd update <id> --status=in_progress # Claim it
` + "```" + `
**Completing work:**
` + "```bash" + `
bd close <id> # Mark done
bd sync # Push to remote
` + "```" + `
**Creating dependent work:**
` + "```bash" + `
bd create --title="Implement feature X" --type=feature
bd create --title="Write tests for X" --type=task
bd dep beads-xxx beads-yyy # Feature blocks tests
` + "```" + `
`
fmt.Print(context)
return nil
}

78
cmd/bd/setup.go Normal file
View File

@@ -0,0 +1,78 @@
package main
import (
"github.com/spf13/cobra"
"github.com/steveyegge/beads/cmd/bd/setup"
)
var (
setupProject bool
setupCheck bool
setupRemove bool
)
var setupCmd = &cobra.Command{
Use: "setup",
Short: "Setup integration with AI editors",
Long: `Setup integration files for AI editors like Claude Code and Cursor.`,
}
var setupCursorCmd = &cobra.Command{
Use: "cursor",
Short: "Setup Cursor IDE integration",
Long: `Install Beads workflow rules for Cursor IDE.
Creates .cursor/rules/beads.mdc with bd workflow context.
Uses BEGIN/END markers for safe idempotent updates.`,
Run: func(cmd *cobra.Command, args []string) {
if setupCheck {
setup.CheckCursor()
return
}
if setupRemove {
setup.RemoveCursor()
return
}
setup.InstallCursor()
},
}
var setupClaudeCmd = &cobra.Command{
Use: "claude",
Short: "Setup Claude Code integration",
Long: `Install Claude Code hooks that auto-inject bd workflow context.
By default, installs hooks globally (~/.claude/settings.json).
Use --project flag to install only for this project.
Hooks call 'bd prime' on SessionStart and PreCompact events to prevent
agents from forgetting bd workflow after context compaction.`,
Run: func(cmd *cobra.Command, args []string) {
if setupCheck {
setup.CheckClaude()
return
}
if setupRemove {
setup.RemoveClaude(setupProject)
return
}
setup.InstallClaude(setupProject)
},
}
func init() {
setupClaudeCmd.Flags().BoolVar(&setupProject, "project", false, "Install for this project only (not globally)")
setupClaudeCmd.Flags().BoolVar(&setupCheck, "check", false, "Check if Claude integration is installed")
setupClaudeCmd.Flags().BoolVar(&setupRemove, "remove", false, "Remove bd hooks from Claude settings")
setupCursorCmd.Flags().BoolVar(&setupCheck, "check", false, "Check if Cursor integration is installed")
setupCursorCmd.Flags().BoolVar(&setupRemove, "remove", false, "Remove bd rules from Cursor")
setupCmd.AddCommand(setupClaudeCmd)
setupCmd.AddCommand(setupCursorCmd)
rootCmd.AddCommand(setupCmd)
}

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
}

7
commands/prime.md Normal file
View File

@@ -0,0 +1,7 @@
Load AI-optimized workflow context for beads issue tracking.
Outputs essential beads workflow rules and command reference to help agents remember to use bd instead of markdown TODOs after context compaction.
```bash
bd prime
```

View File

@@ -192,6 +192,34 @@ func FindDatabasePath() string {
return ""
}
// FindBeadsDir finds the .beads/ directory in the current directory tree
// Returns empty string if not found. Supports both database and JSONL-only mode.
// This is useful for commands that need to detect beads projects without requiring a database.
func FindBeadsDir() string {
// 1. Check BEADS_DIR environment variable (preferred)
if beadsDir := os.Getenv("BEADS_DIR"); beadsDir != "" {
absBeadsDir := utils.CanonicalizePath(beadsDir)
if info, err := os.Stat(absBeadsDir); err == nil && info.IsDir() {
return absBeadsDir
}
}
// 2. Search for .beads/ in current directory and ancestors
cwd, err := os.Getwd()
if err != nil {
return ""
}
for dir := cwd; dir != "/" && dir != "."; dir = filepath.Dir(dir) {
beadsDir := filepath.Join(dir, ".beads")
if info, err := os.Stat(beadsDir); err == nil && info.IsDir() {
return beadsDir
}
}
return ""
}
// FindJSONLPath returns the expected JSONL file path for the given database path.
// It searches for existing *.jsonl files in the database directory and returns
// the first one found, or defaults to "issues.jsonl".