beads/cmd/bd/setup/cursor.go
Michael Hackner 6829d2418a
feat(cursor): bring Cursor integration to parity with Claude/Codex (#4649)
Cursor support is anemic compared to Claude Code and Codex. It ships
only a static rules file: no agent lifecycle hooks, so `bd prime`
context is never injected at session start and is silently lost after
context compaction, and it has no `bd init` auto-install, no `--global`
scope, no shared agent skill, and no `bd doctor` coverage.

This PR brings Cursor up to the same footing as the tier-1 integrations.

- `bd setup cursor` now installs agent lifecycle hooks
  (`.cursor/hooks.json`) alongside the rules file, wiring
  sessionStart/preCompact/postToolUse to a hidden `bd cursor-hook`
  command so Beads context survives compaction:
  * sessionStart injects full `bd prime` context into new sessions
  * preCompact arms a one-shot refresh marker
  * postToolUse re-injects `bd prime` once after a compaction, then
    no-ops
- `bd init` auto-installs Cursor (rules + skill + hooks) and stages
  `.cursor/`
- `bd setup cursor --global` writes `~/.cursor/hooks.json` +
  `~/.agents/skills/beads`
- Canonical rules: `.cursor/rules/beads.mdc` wraps the shared
  `recipes.Template` instead of a hand-maintained copy
- Shared agent skill (`.agents/skills/beads`), removed only once neither
  Cursor nor Codex still relies on it
- `bd doctor` reports Cursor Integration, Settings Health, and Hook
  Completeness checks with agent-mode enrichment

Shared hook mechanics (prime runner + one-shot refresh marker) are
factored into `cmd/bd/agent_hook.go` and reused by codex-hook.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 13:10:46 -07:00

494 lines
15 KiB
Go

package setup
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/steveyegge/beads/internal/recipes"
)
const (
cursorRulesPath = ".cursor/rules/beads.mdc"
cursorHooksPath = ".cursor/hooks.json"
// cursorHookCommandPrefix identifies hook entries that bd owns, so we can
// upsert/remove them without disturbing a user's own Cursor hooks.
cursorHookCommandPrefix = "bd cursor-hook "
)
// cursorManagedHookEvents is the ordered list of Cursor agent lifecycle events
// bd manages, and the single source of truth for "which events bd installs
// hooks for". cursorManagedHooks derives each command from it, and the doctor
// package consumes it via CursorManagedHookEventNames / CursorManagedHookEvents,
// so the installer and diagnostics can't drift. Order matters for user-facing
// messages (e.g. bd doctor hook completeness).
var cursorManagedHookEvents = []string{"sessionStart", "preCompact", "postToolUse"}
// cursorManagedHooks maps each managed Cursor lifecycle event to the command
// that handles it (the hidden `bd cursor-hook <event>` command), so `bd` must be
// on PATH when Cursor runs them. These events fire in the Cursor IDE and in
// recent cursor-agent CLI builds (verified on the 2026.06 line; early-2026 CLI
// builds only fired shell hooks).
func cursorManagedHooks() map[string]string {
hooks := make(map[string]string, len(cursorManagedHookEvents))
for _, event := range cursorManagedHookEvents {
hooks[event] = cursorHookCommandPrefix + event
}
return hooks
}
// CursorManagedHookEventNames returns the ordered list of Cursor lifecycle
// events bd manages. Exported so the doctor package reports hook completeness
// against the same definition the installer writes.
func CursorManagedHookEventNames() []string {
out := make([]string, len(cursorManagedHookEvents))
copy(out, cursorManagedHookEvents)
return out
}
// CursorManagedHookEvents returns the managed events in a parsed .cursor/hooks.json
// config that have a bd-managed hook entry (a "bd cursor-hook " command). It is
// the single source of truth for detecting bd's Cursor hooks, shared by the
// setup and doctor packages.
func CursorManagedHookEvents(config map[string]interface{}) []string {
hooks, ok := config["hooks"].(map[string]interface{})
if !ok {
return nil
}
var found []string
for _, event := range cursorManagedHookEvents {
for _, entry := range toInterfaceSlice(hooks[event]) {
if cursorHookEntryManaged(entry) {
found = append(found, event)
break
}
}
}
return found
}
// cursorHooksTargetPath resolves where hooks.json lives. Project installs use
// the repo-local .cursor/hooks.json (committed with the project, per Cursor's
// docs); global installs use ~/.cursor/hooks.json, which Cursor documents as the
// user-level hooks location. Note: Cursor has no reliable file-based global
// *rules* location (those live in Cursor Settings), so --global covers hooks
// only.
func cursorHooksTargetPath(global bool) (string, error) {
if !global {
return cursorHooksPath, nil
}
home, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("resolve home directory: %w", err)
}
return filepath.Join(home, ".cursor", "hooks.json"), nil
}
// cursorRulesTemplate is the `.cursor/rules/beads.mdc` content: Cursor `.mdc`
// frontmatter (alwaysApply makes the rule load every conversation) wrapping the
// canonical beads workflow template shared by every file-based recipe. Reusing
// recipes.Template (rather than a Cursor-specific copy) keeps Cursor's rule at
// parity with peers like windsurf/cody and avoids drift. HTML-comment markers
// match the BEGIN/END BEADS INTEGRATION style used in AGENTS.md / CLAUDE.md.
const cursorRulesTemplate = `---
alwaysApply: true
---
<!-- BEGIN BEADS INTEGRATION -->
<!-- Auto-generated by 'bd setup cursor'. Content between these markers is managed by bd. -->
` + recipes.Template + `
<!-- END BEADS INTEGRATION -->
`
// InstallCursor installs Cursor integration. Project scope (default) writes an
// always-applied rules file plus agent lifecycle hooks; global scope writes the
// hooks to ~/.cursor/hooks.json (rules are project-only — see
// cursorHooksTargetPath). The hooks auto-run `bd prime` on session start and
// recover context after compaction.
func InstallCursor(global bool) error {
fmt.Println("Installing Cursor integration...")
if !global {
if err := installCursorRules(); err != nil {
return HandleError("%v", err)
}
}
// The agent skill lives at .agents/skills/beads (project) or
// ~/.agents/skills/beads (global), both of which Cursor loads natively.
// Unlike rules, skills have a real global location, so --global installs it.
skillEnv, err := cursorAgentSkillEnv(global)
if err != nil {
return HandleError("%v", err)
}
if err := installAgentSkill(skillEnv); err != nil {
return HandleError("%v", err)
}
hooksPath, err := cursorHooksTargetPath(global)
if err != nil {
return HandleError("%v", err)
}
if err := installCursorHooks(hooksPath); err != nil {
return HandleError("%v", err)
}
fmt.Printf("\n✓ Cursor integration installed\n")
if !global {
fmt.Printf(" Rules: %s\n", cursorRulesPath)
}
fmt.Printf(" Skill: %s\n", agentSkillPath(skillEnv.projectDir))
fmt.Printf(" Hooks: %s (sessionStart, preCompact, postToolUse)\n", hooksPath)
if global {
fmt.Println("\nGlobal hooks apply to every project. Cursor has no reliable file-based")
fmt.Println("global rules location, so add global rules via Cursor Settings → Rules")
fmt.Println("(or run 'bd setup cursor' per project to install the rules file).")
}
fmt.Println("\nThe hooks invoke `bd cursor-hook`, so make sure `bd` is on PATH for Cursor.")
fmt.Println("Restart Cursor (or start a new cursor-agent session) for changes to take effect.")
return nil
}
// InstallCursorProject installs project-local Cursor integration, returning an
// error instead of exiting. Used by bd init to integrate Cursor setup
// automatically (parallels InstallClaudeProject / InstallCodexProject).
func InstallCursorProject() error {
if err := installCursorRules(); err != nil {
return err
}
skillEnv, err := cursorAgentSkillEnv(false)
if err != nil {
return err
}
if err := installAgentSkill(skillEnv); err != nil {
return err
}
if err := installCursorHooks(cursorHooksPath); err != nil {
return err
}
fmt.Println("✓ Cursor integration installed (rules + skill + hooks)")
return nil
}
// cursorAgentSkillEnv builds the environment for installing/removing the shared
// beads agent skill at .agents/skills/beads (project) or ~/.agents/skills/beads
// (global). This is the same skill Codex installs; Cursor loads .agents/skills/
// natively, so Cursor-only users get it too. See installAgentSkill.
func cursorAgentSkillEnv(global bool) (agentSkillEnv, error) {
base := "."
if global {
home, err := os.UserHomeDir()
if err != nil {
return agentSkillEnv{}, fmt.Errorf("resolve home directory: %w", err)
}
base = home
}
return agentSkillEnv{
stdout: os.Stdout,
stderr: os.Stderr,
projectDir: base,
ensureDir: EnsureDir,
readFile: os.ReadFile,
writeFile: func(path string, data []byte) error {
return atomicWriteFile(path, data)
},
removeFile: os.Remove,
}, nil
}
func installCursorRules() error {
if err := EnsureDir(filepath.Dir(cursorRulesPath), 0o755); err != nil {
return err
}
if err := atomicWriteFile(cursorRulesPath, []byte(cursorRulesTemplate)); err != nil {
return fmt.Errorf("write rules: %w", err)
}
return nil
}
func installCursorHooks(path string) error {
if err := EnsureDir(filepath.Dir(path), 0o755); err != nil {
return err
}
config, err := readCursorHooks(path)
if err != nil {
return err
}
if config == nil {
config = map[string]interface{}{}
}
upsertCursorManagedHooks(config)
return writeCursorHooks(path, config)
}
// CheckCursor reports whether the managed hooks are present. For project scope
// it also verifies the rules file; global rules can't be verified from disk
// (they live in Cursor Settings), so global scope checks hooks only.
func CheckCursor(global bool) error {
missing := false
if !global {
if FileExists(cursorRulesPath) {
fmt.Printf("✓ Cursor rules installed: %s\n", cursorRulesPath)
} else {
fmt.Printf("✗ Cursor rules not installed: %s\n", cursorRulesPath)
missing = true
}
}
hooksPath, err := cursorHooksTargetPath(global)
if err != nil {
return HandleError("%v", err)
}
installed, err := cursorHooksInstalled(hooksPath)
if err != nil {
return HandleError("%v", err)
}
if installed {
fmt.Printf("✓ Cursor hooks installed: %s\n", hooksPath)
} else {
fmt.Printf("✗ Cursor hooks not installed: %s\n", hooksPath)
missing = true
}
setupCmd := "bd setup cursor"
if global {
setupCmd = "bd setup cursor --global"
}
skillEnv, err := cursorAgentSkillEnv(global)
if err != nil {
return HandleError("%v", err)
}
if err := checkAgentSkill(skillEnv, setupCmd); err != nil {
missing = true
}
if missing {
return HandleErrorWithHint("Cursor integration incomplete", "Run: "+setupCmd)
}
return nil
}
// RemoveCursor removes bd-managed hook entries (and, for project scope, the
// rules file), preserving any non-bd hooks the user configured.
func RemoveCursor(global bool) error {
fmt.Println("Removing Cursor integration...")
hooksPath, err := cursorHooksTargetPath(global)
if err != nil {
return HandleError("%v", err)
}
rulesExisted := false
if !global {
rulesExisted = FileExists(cursorRulesPath)
if rulesExisted {
if err := os.Remove(cursorRulesPath); err != nil && !os.IsNotExist(err) {
return HandleError("failed to remove rules: %v", err)
}
// Best-effort: drop the rules dir if it is now empty.
_ = os.Remove(filepath.Dir(cursorRulesPath))
}
}
hooksExisted := FileExists(hooksPath)
if err := removeCursorHooks(hooksPath); err != nil {
return HandleError("%v", err)
}
// The agent skill is shared with Codex (same .agents/skills/beads path).
// Only remove it if Codex isn't still relying on it.
skillEnv, err := cursorAgentSkillEnv(global)
if err != nil {
return HandleError("%v", err)
}
skillExisted := FileExists(agentSkillPath(skillEnv.projectDir))
skillRemoved := false
if codexIntegrationInstalled(global) {
fmt.Println("Keeping Beads agent skill (still used by Codex integration)")
} else if err := removeAgentSkill(skillEnv); err != nil {
return HandleError("%v", err)
} else {
skillRemoved = skillExisted
}
// Only claim removal for what we actually removed. The shared agent skill is
// kept when Codex still relies on it, so a lone kept skill is not a Cursor
// integration and must not report as "removed".
if rulesExisted || hooksExisted || skillRemoved {
fmt.Println("✓ Removed Cursor integration")
} else {
fmt.Println("No Cursor integration found")
}
return nil
}
// cursorBeadsHooksPresent reports whether a parsed hooks.json config contains any
// bd-managed Cursor hook entry (command prefixed with "bd cursor-hook ").
func cursorBeadsHooksPresent(config map[string]interface{}) bool {
return len(CursorManagedHookEvents(config)) > 0
}
// codexIntegrationInstalled reports whether Codex's bd integration is present for
// the given scope (its AGENTS.md managed section or a bd-managed .codex/hooks.json).
// Cursor removal uses this to avoid deleting the shared .agents/skills/beads skill
// while Codex still needs it. Checking both surfaces keeps this symmetric with
// cursorIntegrationInstalledAt, which inspects .cursor/hooks.json and the rules file.
func codexIntegrationInstalled(global bool) bool {
env, err := codexEnvProvider()
if err != nil {
return false
}
if data, err := env.readFile(codexInstructionsPath(env, global)); err == nil {
if _, ok := extractCodexManagedSection(string(data)); ok {
return true
}
}
if data, err := env.readFile(codexHooksPath(env, global)); err == nil {
if config, perr := parseHooksJSON(data); perr == nil && codexBeadsHooksPresent(config) {
return true
}
}
return false
}
// readCursorHooks loads a hooks.json file (project or ~/.cursor). It returns
// (nil, nil) when the file does not exist so callers can distinguish "absent"
// from "empty".
func readCursorHooks(path string) (map[string]interface{}, error) {
data, err := os.ReadFile(path) // #nosec G304 -- fixed .cursor/hooks.json config path (project or home)
if os.IsNotExist(err) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("read %s: %w", path, err)
}
config, err := parseHooksJSON(data)
if err != nil {
return nil, fmt.Errorf("parse %s: %w", path, err)
}
return config, nil
}
func writeCursorHooks(path string, config map[string]interface{}) error {
if _, ok := config["version"]; !ok {
config["version"] = 1
}
data, err := marshalHooksJSON(config)
if err != nil {
return fmt.Errorf("marshal %s: %w", path, err)
}
if err := atomicWriteFile(path, data); err != nil {
return fmt.Errorf("write %s: %w", path, err)
}
return nil
}
func upsertCursorManagedHooks(config map[string]interface{}) {
hooks, ok := config["hooks"].(map[string]interface{})
if !ok {
hooks = map[string]interface{}{}
config["hooks"] = hooks
}
for event, command := range cursorManagedHooks() {
entries := removeCursorManagedEntries(toInterfaceSlice(hooks[event]))
entries = append(entries, map[string]interface{}{"command": command})
hooks[event] = entries
}
}
func removeCursorHooks(path string) error {
config, err := readCursorHooks(path)
if err != nil {
return err
}
if config == nil {
return nil
}
hooks, ok := config["hooks"].(map[string]interface{})
if ok {
for event := range cursorManagedHooks() {
entries := removeCursorManagedEntries(toInterfaceSlice(hooks[event]))
if len(entries) == 0 {
delete(hooks, event)
} else {
hooks[event] = entries
}
}
if len(hooks) == 0 {
delete(config, "hooks")
}
}
// If nothing but the schema version remains, the file was ours; remove it.
if cursorHooksConfigEmpty(config) {
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
return err
}
return nil
}
return writeCursorHooks(path, config)
}
func cursorHooksInstalled(path string) (bool, error) {
config, err := readCursorHooks(path)
if err != nil {
return false, err
}
if config == nil {
return false, nil
}
hooks, ok := config["hooks"].(map[string]interface{})
if !ok {
return false, nil
}
for event, command := range cursorManagedHooks() {
if !cursorHooksHasCommand(toInterfaceSlice(hooks[event]), command) {
return false, nil
}
}
return true, nil
}
func removeCursorManagedEntries(entries []interface{}) []interface{} {
filtered := entries[:0]
for _, entry := range entries {
if !cursorHookEntryManaged(entry) {
filtered = append(filtered, entry)
}
}
return filtered
}
func cursorHookEntryManaged(entry interface{}) bool {
m, ok := entry.(map[string]interface{})
if !ok {
return false
}
command, _ := m["command"].(string)
return strings.HasPrefix(command, cursorHookCommandPrefix)
}
func cursorHooksHasCommand(entries []interface{}, command string) bool {
for _, entry := range entries {
m, ok := entry.(map[string]interface{})
if !ok {
continue
}
if got, _ := m["command"].(string); got == command {
return true
}
}
return false
}
func cursorHooksConfigEmpty(config map[string]interface{}) bool {
for key := range config {
if key != "version" {
return false
}
}
return true
}