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>
This commit is contained in:
Michael Hackner 2026-07-10 13:10:46 -07:00 • committed by GitHub
commit 6829d2418a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
25 changed files with 1918 additions and 147 deletions

View file

@ -13,6 +13,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`BD_ALLOW_REMOTE_MIGRATE=1` for bypassing the remote-migrate gate (#4259)
as the single designated migrator; process-local so it cannot leak into
child processes (git hooks, dolt subprocesses).
- **Cursor agent hooks.** `bd setup cursor` now installs `.cursor/hooks.json`
alongside the existing rules file, wiring three Cursor lifecycle events to a
new hidden `bd cursor-hook` command:
- `sessionStart` injects full `bd prime` context into every new agent session.
- `preCompact` arms a one-shot refresh marker (and notifies the user).
- `postToolUse` re-injects `bd prime` exactly once after a compaction, then
no-ops.
This brings Cursor (IDE and recent `cursor-agent` CLI builds — verified on the
2026.06 line; early-2026 CLI builds only fired shell hooks) to parity with
the Claude Code / Codex hook integrations, so Beads context survives context
compaction instead of being forgotten. Existing user hooks in
`.cursor/hooks.json` are preserved, and `bd setup cursor --remove` only
removes the Beads-managed entries.
The integration now matches Claude/Codex on several more fronts:
- **`bd init` auto-installs Cursor** (rules + skill + hooks) the same way it
auto-sets up Claude Code and Codex, and stages `.cursor/` for commit.
- **`bd setup cursor --global`** writes hooks to `~/.cursor/hooks.json` (and the
agent skill to `~/.agents/skills/beads`) so they apply to every project.
(Global scope is hooks + skill only; Cursor has no reliable file-based global
*rules* location — those live in Cursor Settings.)
- **Canonical rules content.** `.cursor/rules/beads.mdc` now wraps the shared
`recipes.Template` (the same content every other file-based recipe uses)
instead of a hand-maintained copy, so it no longer drifts or omits the Issue
Types / Priorities / git-authority sections.
- **Agent skill.** `bd setup cursor` installs the shared
`.agents/skills/beads/SKILL.md` (which Cursor loads natively), so Cursor-only
users get the same progressive-disclosure skill Codex installs. The skill is
shared with Codex and is only removed once no integration still relies on it.
- **`bd doctor`** reports `Cursor Integration`, `Cursor Settings Health`
(malformed `.cursor/hooks.json` → error), and `Cursor Hook Completeness`
(all three lifecycle events present) checks — with agent-mode enrichment —
paralleling the Claude integration checks.
### Changed

68
cmd/bd/agent_hook.go Normal file
View file

@ -0,0 +1,68 @@
package main
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
// Shared helpers for the agent lifecycle hook commands (codex-hook, cursor-hook).
// Each agent keeps its own event names, input/output schemas, and test stubs, but
// the prime-runner and one-shot refresh-marker mechanics are identical and live
// here to avoid divergence.
// runBdPrime shells out to `bd prime [args...]` and returns its combined output.
// The hooks exec a subprocess (rather than calling prime in process) to avoid
// re-entrant store initialization.
func runBdPrime(ctx context.Context, args ...string) (string, error) {
cmdArgs := append([]string{"prime"}, args...)
// #nosec G702 - os.Args[0] is this bd binary re-invoking itself; cmdArgs is the
// fixed "prime" subcommand plus internal flags, never attacker-controlled input.
cmd := exec.CommandContext(ctx, os.Args[0], cmdArgs...)
out, err := cmd.CombinedOutput()
if err != nil {
return "", fmt.Errorf("bd %s: %w: %s", strings.Join(cmdArgs, " "), err, strings.TrimSpace(string(out)))
}
return string(out), nil
}
// agentHookMarkerBaseDir returns the cache directory for one-shot
// post-compaction refresh markers for a given agent (subdir e.g. "codex-hooks").
// override redirects the location for tests.
func agentHookMarkerBaseDir(subdir, override string) string {
if override != "" {
return override
}
if dir, err := os.UserCacheDir(); err == nil && dir != "" {
return filepath.Join(dir, "beads", subdir)
}
return filepath.Join(os.TempDir(), "beads-"+subdir)
}
// agentHookMarkerPath derives a per-session, per-workspace marker file under
// base so concurrent agent sessions don't clobber each other's state. Empty
// keys fall back to stable placeholders.
func agentHookMarkerPath(base, sessionKey, workspaceKey string) string {
if sessionKey == "" {
sessionKey = "unknown-session"
}
if workspaceKey == "" {
workspaceKey = "unknown-workspace"
}
sum := sha256.Sum256([]byte(sessionKey + "\x00" + filepath.Clean(workspaceKey)))
return filepath.Join(base, hex.EncodeToString(sum[:])+".refresh")
}
// writeAgentHookMarker creates the marker directory and writes the one-shot
// refresh marker file.
func writeAgentHookMarker(path string) error {
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return err
}
return os.WriteFile(path, []byte("1\n"), 0o600) // #nosec G306 -- user-private cache marker
}

View file

@ -2,14 +2,10 @@ package main
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
@ -26,16 +22,10 @@ const (
var codexHookMarkerDirOverride string
var codexHookExecPrime = func(ctx context.Context, memoriesOnly bool) (string, error) {
args := []string{"prime"}
if memoriesOnly {
args = append(args, "--memories-only")
return runBdPrime(ctx, "--memories-only")
}
cmd := exec.CommandContext(ctx, os.Args[0], args...)
out, err := cmd.CombinedOutput()
if err != nil {
return "", fmt.Errorf("bd %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out)))
}
return string(out), nil
return runBdPrime(ctx)
}
type codexHookInput struct {
@ -114,11 +104,7 @@ func codexHookPreCompactCheck(ctx context.Context, stdout io.Writer) error {
}
func codexHookMarkNeedsRefresh(input codexHookInput) error {
path := codexHookRefreshMarkerPath(input)
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return nil
}
return os.WriteFile(path, []byte("1\n"), 0o600) // #nosec G306 -- user-private cache marker
return writeAgentHookMarker(codexHookRefreshMarkerPath(input))
}
func codexHookMaybeRefresh(ctx context.Context, input codexHookInput, stdout io.Writer) error {
@ -138,27 +124,11 @@ func codexHookMaybeRefresh(ctx context.Context, input codexHookInput, stdout io.
}
func codexHookRefreshMarkerPath(input codexHookInput) string {
base := codexHookMarkerBaseDir()
sessionID := input.SessionID
if sessionID == "" {
sessionID = "unknown-session"
}
workspace := input.CWD
if workspace == "" {
workspace = "unknown-workspace"
}
sum := sha256.Sum256([]byte(sessionID + "\x00" + filepath.Clean(workspace)))
return filepath.Join(base, hex.EncodeToString(sum[:])+".refresh")
return agentHookMarkerPath(codexHookMarkerBaseDir(), input.SessionID, input.CWD)
}
func codexHookMarkerBaseDir() string {
if codexHookMarkerDirOverride != "" {
return codexHookMarkerDirOverride
}
if dir, err := os.UserCacheDir(); err == nil && dir != "" {
return filepath.Join(dir, "beads", "codex-hooks")
}
return filepath.Join(os.TempDir(), "beads-codex-hooks")
return agentHookMarkerBaseDir("codex-hooks", codexHookMarkerDirOverride)
}
func writeCodexHookAdditionalContext(stdout io.Writer, event, context string) error {

170
cmd/bd/cursor_hook.go Normal file
View file

@ -0,0 +1,170 @@
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/spf13/cobra"
)
// Cursor agent hook event names. These match the keys used in
// .cursor/hooks.json and the "hook_event_name" field Cursor sends on stdin.
// See https://cursor.com/docs/hooks for the full lifecycle.
const (
cursorHookSessionStart = "sessionStart"
cursorHookPreCompact = "preCompact"
cursorHookPostToolUse = "postToolUse"
)
// cursorHookMarkerDirOverride lets tests redirect the refresh-marker location.
var cursorHookMarkerDirOverride string
// cursorHookExecPrime runs `bd prime` and returns its output. It is a package
// variable so tests can stub it; it delegates to the shared runBdPrime used by
// codex-hook.
var cursorHookExecPrime = func(ctx context.Context) (string, error) {
return runBdPrime(ctx)
}
// cursorHookInput captures the subset of Cursor's hook payload we use. Cursor
// sends a common base (conversation_id, hook_event_name, workspace_roots, ...)
// plus event-specific fields. Unknown fields are ignored by the decoder.
type cursorHookInput struct {
ConversationID string `json:"conversation_id"`
SessionID string `json:"session_id"`
HookEventName string `json:"hook_event_name"`
WorkspaceRoots []string `json:"workspace_roots"`
CWD string `json:"cwd"`
Trigger string `json:"trigger"`
ToolName string `json:"tool_name"`
}
// cursorHookResponse is the JSON we write to stdout. All fields are optional;
// an empty struct encodes to "{}", which is the correct no-op response for a
// command hook (e.g. postToolUse when no refresh is pending).
type cursorHookResponse struct {
Continue *bool `json:"continue,omitempty"`
AdditionalContext string `json:"additional_context,omitempty"`
UserMessage string `json:"user_message,omitempty"`
}
var cursorHookCmd = &cobra.Command{
Use: "cursor-hook <event>",
Hidden: true,
Short: "Run an internal Cursor agent lifecycle hook",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return runCursorHook(cmd.Context(), args[0], os.Stdin, os.Stdout)
},
}
func init() {
rootCmd.AddCommand(cursorHookCmd)
}
func runCursorHook(ctx context.Context, event string, stdin io.Reader, stdout io.Writer) error {
var input cursorHookInput
if err := json.NewDecoder(stdin).Decode(&input); err != nil && err != io.EOF {
return err
}
// Cursor sends the canonical event name on stdin; prefer it over the arg so
// a single misconfigured hooks.json entry can't mislabel the event.
if input.HookEventName != "" {
event = input.HookEventName
}
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
switch event {
case cursorHookSessionStart:
return cursorHookHandleSessionStart(ctx, input, stdout)
case cursorHookPreCompact:
return cursorHookHandlePreCompact(input, stdout)
case cursorHookPostToolUse:
return cursorHookHandlePostToolUse(ctx, input, stdout)
default:
return fmt.Errorf("unsupported Cursor hook event %q", event)
}
}
// cursorHookHandleSessionStart injects full `bd prime` output into the new
// session and clears any stale post-compaction refresh marker.
func cursorHookHandleSessionStart(ctx context.Context, input cursorHookInput, stdout io.Writer) error {
_ = os.Remove(cursorHookRefreshMarkerPath(input)) // best-effort: drop stale marker
cont := true
resp := cursorHookResponse{Continue: &cont}
out, err := cursorHookExecPrime(ctx)
if err == nil {
resp.AdditionalContext = strings.TrimRight(out, "\n")
}
return json.NewEncoder(stdout).Encode(resp)
}
// cursorHookHandlePreCompact arms a one-shot marker so the next postToolUse
// re-injects context, and surfaces a short note to the user. Cursor's
// preCompact cannot inject model context directly, so the marker + postToolUse
// pair is how we recover after compaction.
func cursorHookHandlePreCompact(input cursorHookInput, stdout io.Writer) error {
_ = writeAgentHookMarker(cursorHookRefreshMarkerPath(input)) // best-effort: arm recovery
return json.NewEncoder(stdout).Encode(cursorHookResponse{
UserMessage: "Beads: context compacting — bd workflow context will be re-injected on the next tool call (or run `bd prime`).",
})
}
// cursorHookHandlePostToolUse is a fast no-op on every tool call unless a
// compaction just happened (marker present), in which case it re-injects
// `bd prime` exactly once and clears the marker.
func cursorHookHandlePostToolUse(ctx context.Context, input cursorHookInput, stdout io.Writer) error {
path := cursorHookRefreshMarkerPath(input)
if _, err := os.Stat(path); err != nil {
return json.NewEncoder(stdout).Encode(cursorHookResponse{})
}
out, err := cursorHookExecPrime(ctx)
if err != nil || strings.TrimSpace(out) == "" {
// Leave the marker in place so a later tool call can retry the refresh.
return json.NewEncoder(stdout).Encode(cursorHookResponse{})
}
_ = os.Remove(path)
// Set continue=true alongside the injected context, mirroring sessionStart's
// context-injection response. (The no-op paths above stay as a bare "{}",
// the documented no-op for a command hook.)
cont := true
restored := "[Beads] Context was compacted. Restored bd workflow context below.\n\n" + strings.TrimRight(out, "\n")
return json.NewEncoder(stdout).Encode(cursorHookResponse{Continue: &cont, AdditionalContext: restored})
}
// cursorHookRefreshMarkerPath derives a per-conversation, per-workspace marker
// path so concurrent Cursor sessions don't clobber each other's state. Cursor
// keys on conversation_id (falling back to session_id) and the first workspace
// root (falling back to cwd); the empty→placeholder fallbacks live in
// agentHookMarkerPath.
func cursorHookRefreshMarkerPath(input cursorHookInput) string {
conv := input.ConversationID
if conv == "" {
conv = input.SessionID
}
workspace := ""
if len(input.WorkspaceRoots) > 0 {
workspace = input.WorkspaceRoots[0]
}
if workspace == "" {
workspace = input.CWD
}
return agentHookMarkerPath(cursorHookMarkerBaseDir(), conv, workspace)
}
func cursorHookMarkerBaseDir() string {
return agentHookMarkerBaseDir("cursor-hooks", cursorHookMarkerDirOverride)
}

199
cmd/bd/cursor_hook_test.go Normal file
View file

@ -0,0 +1,199 @@
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"os"
"strings"
"testing"
)
func stubCursorHookPrime(t *testing.T, fn func() (string, error)) {
t.Helper()
orig := cursorHookExecPrime
cursorHookExecPrime = func(_ context.Context) (string, error) { return fn() }
t.Cleanup(func() { cursorHookExecPrime = orig })
}
func TestCursorHookSessionStartInjectsPrime(t *testing.T) {
cursorHookMarkerDirOverride = t.TempDir()
t.Cleanup(func() { cursorHookMarkerDirOverride = "" })
stubCursorHookPrime(t, func() (string, error) {
return "BEADS PRIME\nbd ready --json\n", nil
})
var out bytes.Buffer
input := `{"session_id":"s1","conversation_id":"s1","hook_event_name":"sessionStart","composer_mode":"agent","workspace_roots":["/repo"]}`
if err := runCursorHook(context.Background(), cursorHookSessionStart, strings.NewReader(input), &out); err != nil {
t.Fatalf("runCursorHook: %v", err)
}
var got cursorHookResponse
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
t.Fatalf("parse output: %v\n%s", err, out.String())
}
if got.Continue == nil || !*got.Continue {
t.Fatalf("expected continue=true, got %#v", got)
}
if !strings.Contains(got.AdditionalContext, "bd ready --json") {
t.Fatalf("expected prime output in additional_context: %#v", got)
}
}
func TestCursorHookSessionStartEmptyPrimeStillValid(t *testing.T) {
cursorHookMarkerDirOverride = t.TempDir()
t.Cleanup(func() { cursorHookMarkerDirOverride = "" })
stubCursorHookPrime(t, func() (string, error) { return "", nil })
var out bytes.Buffer
input := `{"session_id":"s1","hook_event_name":"sessionStart"}`
if err := runCursorHook(context.Background(), cursorHookSessionStart, strings.NewReader(input), &out); err != nil {
t.Fatalf("runCursorHook: %v", err)
}
var got cursorHookResponse
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
t.Fatalf("parse output: %v\n%s", err, out.String())
}
if got.Continue == nil || !*got.Continue {
t.Fatalf("expected continue=true even when prime empty: %#v", got)
}
if got.AdditionalContext != "" {
t.Fatalf("expected empty additional_context, got %q", got.AdditionalContext)
}
}
func TestCursorHookSessionStartPrimeErrorStillContinues(t *testing.T) {
cursorHookMarkerDirOverride = t.TempDir()
t.Cleanup(func() { cursorHookMarkerDirOverride = "" })
stubCursorHookPrime(t, func() (string, error) { return "", errors.New("workspace unavailable") })
var out bytes.Buffer
input := `{"hook_event_name":"sessionStart","session_id":"s9"}`
if err := runCursorHook(context.Background(), cursorHookSessionStart, strings.NewReader(input), &out); err != nil {
t.Fatalf("runCursorHook: %v", err)
}
var got cursorHookResponse
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
t.Fatalf("parse output: %v", err)
}
if got.Continue == nil || !*got.Continue {
t.Fatalf("expected continue=true on prime error, got %#v", got)
}
}
func TestCursorHookPreCompactThenPostToolRefreshesOnce(t *testing.T) {
cursorHookMarkerDirOverride = t.TempDir()
t.Cleanup(func() { cursorHookMarkerDirOverride = "" })
calls := 0
stubCursorHookPrime(t, func() (string, error) {
calls++
return "REFRESHED BEADS CONTEXT\n", nil
})
// preCompact arms the one-shot marker and emits a user message.
preInput := `{"hook_event_name":"preCompact","conversation_id":"c1","workspace_roots":["/repo"],"trigger":"auto"}`
var preOut bytes.Buffer
if err := runCursorHook(context.Background(), cursorHookPreCompact, strings.NewReader(preInput), &preOut); err != nil {
t.Fatalf("preCompact: %v", err)
}
var preResp cursorHookResponse
if err := json.Unmarshal(preOut.Bytes(), &preResp); err != nil {
t.Fatalf("parse preCompact: %v", err)
}
if preResp.UserMessage == "" {
t.Fatalf("expected preCompact user_message, got %#v", preResp)
}
marker := cursorHookRefreshMarkerPath(cursorHookInput{ConversationID: "c1", WorkspaceRoots: []string{"/repo"}})
if _, err := os.Stat(marker); err != nil {
t.Fatalf("expected refresh marker after preCompact: %v", err)
}
// First postToolUse after compaction re-injects context and clears marker.
toolInput := `{"hook_event_name":"postToolUse","conversation_id":"c1","workspace_roots":["/repo"],"tool_name":"Shell"}`
var toolOut bytes.Buffer
if err := runCursorHook(context.Background(), cursorHookPostToolUse, strings.NewReader(toolInput), &toolOut); err != nil {
t.Fatalf("postToolUse: %v", err)
}
var toolResp cursorHookResponse
if err := json.Unmarshal(toolOut.Bytes(), &toolResp); err != nil {
t.Fatalf("parse postToolUse: %v", err)
}
if !strings.Contains(toolResp.AdditionalContext, "REFRESHED BEADS CONTEXT") {
t.Fatalf("expected refreshed context in additional_context, got %#v", toolResp)
}
if toolResp.Continue == nil || !*toolResp.Continue {
t.Fatalf("expected continue=true on post-compaction refresh, got %#v", toolResp)
}
if calls != 1 {
t.Fatalf("prime calls = %d, want 1", calls)
}
if _, err := os.Stat(marker); !os.IsNotExist(err) {
t.Fatalf("expected marker removed after refresh, stat err=%v", err)
}
// Second postToolUse is a no-op.
toolOut.Reset()
if err := runCursorHook(context.Background(), cursorHookPostToolUse, strings.NewReader(toolInput), &toolOut); err != nil {
t.Fatalf("second postToolUse: %v", err)
}
if calls != 1 {
t.Fatalf("refresh should run once, prime calls = %d", calls)
}
if strings.TrimSpace(toolOut.String()) != "{}" {
t.Fatalf("expected {} no-op on second postToolUse, got %q", toolOut.String())
}
}
func TestCursorHookPostToolUseNoMarkerIsNoop(t *testing.T) {
cursorHookMarkerDirOverride = t.TempDir()
t.Cleanup(func() { cursorHookMarkerDirOverride = "" })
stubCursorHookPrime(t, func() (string, error) {
t.Fatal("prime must not run without an armed marker")
return "", nil
})
var out bytes.Buffer
input := `{"hook_event_name":"postToolUse","conversation_id":"c2","workspace_roots":["/repo"],"tool_name":"Read"}`
if err := runCursorHook(context.Background(), cursorHookPostToolUse, strings.NewReader(input), &out); err != nil {
t.Fatalf("postToolUse: %v", err)
}
if strings.TrimSpace(out.String()) != "{}" {
t.Fatalf("expected {} no-op, got %q", out.String())
}
}
func TestCursorHookSessionStartClearsStaleMarker(t *testing.T) {
cursorHookMarkerDirOverride = t.TempDir()
t.Cleanup(func() { cursorHookMarkerDirOverride = "" })
stubCursorHookPrime(t, func() (string, error) { return "ctx", nil })
// Arm a marker via preCompact, then a new sessionStart for the same
// conversation should clear it so we don't double-inject.
in := `{"conversation_id":"c3","workspace_roots":["/repo"]}`
if err := runCursorHook(context.Background(), cursorHookPreCompact, strings.NewReader(in), &bytes.Buffer{}); err != nil {
t.Fatalf("preCompact: %v", err)
}
marker := cursorHookRefreshMarkerPath(cursorHookInput{ConversationID: "c3", WorkspaceRoots: []string{"/repo"}})
if _, err := os.Stat(marker); err != nil {
t.Fatalf("expected marker: %v", err)
}
start := `{"hook_event_name":"sessionStart","session_id":"c3","conversation_id":"c3","workspace_roots":["/repo"]}`
if err := runCursorHook(context.Background(), cursorHookSessionStart, strings.NewReader(start), &bytes.Buffer{}); err != nil {
t.Fatalf("sessionStart: %v", err)
}
if _, err := os.Stat(marker); !os.IsNotExist(err) {
t.Fatalf("expected sessionStart to clear stale marker, stat err=%v", err)
}
}
func TestCursorHookUnsupportedEvent(t *testing.T) {
var out bytes.Buffer
input := `{"hook_event_name":"sessionEnd"}`
if err := runCursorHook(context.Background(), "sessionEnd", strings.NewReader(input), &out); err == nil {
t.Fatal("expected error for unsupported event")
}
}

View file

@ -651,7 +651,24 @@ func runDiagnostics(path string) doctorResult {
result.Checks = append(result.Checks, bdPathCheck)
// Don't fail overall check for missing bd in PATH, just warn
// Check 11e: Documentation bd prime references match installed version
// Check 11e: Cursor integration (agent hooks)
cursorCheck := convertWithCategory(doctor.CheckCursor(path), doctor.CategoryIntegration)
result.Checks = append(result.Checks, cursorCheck)
// Don't fail overall check for missing Cursor integration, just warn
// Check 11f: Cursor hooks file health (malformed JSON detection)
cursorSettingsCheck := convertWithCategory(doctor.CheckCursorSettingsHealth(path), doctor.CategoryIntegration)
result.Checks = append(result.Checks, cursorSettingsCheck)
if cursorSettingsCheck.Status == statusError {
result.OverallOK = false // Malformed hooks.json is a real problem
}
// Check 11g: Cursor hook completeness (all three lifecycle events)
cursorHookCheck := convertWithCategory(doctor.CheckCursorHookCompleteness(path), doctor.CategoryIntegration)
result.Checks = append(result.Checks, cursorHookCheck)
// Don't fail overall check for incomplete hooks, just warn
// Check 11h: Documentation bd prime references match installed version
bdPrimeDocsCheck := convertWithCategory(doctor.CheckDocumentationBdPrimeReference(path), doctor.CategoryIntegration)
result.Checks = append(result.Checks, bdPrimeDocsCheck)
// Don't fail overall check for doc mismatch, just warn

View file

@ -127,6 +127,9 @@ var agentEnrichers = map[string]enricher{
"Claude Settings Health": enrichClaudeSettings,
"Claude Hook Completeness": enrichClaudeHooks,
"Claude Plugin": enrichClaudePlugin,
"Cursor Integration": enrichCursor,
"Cursor Settings Health": enrichCursorSettings,
"Cursor Hook Completeness": enrichCursorHooks,
"bd prime Output": enrichBdPrimeOutput,
"CLI Availability": enrichBdInPath,
"Repo Fingerprint": enrichRepoFingerprint,
@ -566,6 +569,39 @@ func enrichClaudePlugin(dc DoctorCheck) agentEnrichment {
}
}
func enrichCursor(dc DoctorCheck) agentEnrichment {
return agentEnrichment{
severity: "advisory",
explanation: fmt.Sprintf("Cursor integration: %s. Beads integrates with Cursor via agent hooks in .cursor/hooks.json (or ~/.cursor/hooks.json) that run 'bd cursor-hook' to inject bd prime on sessionStart and recover context after compaction.", dc.Message),
observed: dc.Message + "\n" + dc.Detail,
expected: "Cursor hooks configured for beads (bd cursor-hook on sessionStart/preCompact/postToolUse)",
commands: []string{"bd setup cursor"},
sourceFiles: []string{"cmd/bd/doctor/cursor.go:CheckCursor"},
}
}
func enrichCursorSettings(dc DoctorCheck) agentEnrichment {
return agentEnrichment{
severity: "blocking",
explanation: fmt.Sprintf("Cursor hooks file is malformed: %s. A corrupted .cursor/hooks.json prevents Cursor from loading any hooks, which silently breaks beads context injection and post-compaction recovery.", dc.Message),
observed: dc.Message + "\n" + dc.Detail,
expected: ".cursor/hooks.json (and ~/.cursor/hooks.json) are valid JSON",
commands: []string{"cat .cursor/hooks.json | python3 -m json.tool", "bd setup cursor"},
sourceFiles: []string{"cmd/bd/doctor/cursor.go:CheckCursorSettingsHealth"},
}
}
func enrichCursorHooks(dc DoctorCheck) agentEnrichment {
return agentEnrichment{
severity: "advisory",
explanation: fmt.Sprintf("Cursor hook completeness: %s. Beads recovers context across compaction in Cursor using three hooks: sessionStart, preCompact, and postToolUse. A partial install degrades recovery.", dc.Message),
observed: dc.Message + "\n" + dc.Detail,
expected: "sessionStart, preCompact, and postToolUse hooks all configured for beads",
commands: []string{"bd setup cursor"},
sourceFiles: []string{"cmd/bd/doctor/cursor.go:CheckCursorHookCompleteness"},
}
}
func enrichBdPrimeOutput(dc DoctorCheck) agentEnrichment {
return agentEnrichment{
severity: "advisory",

208
cmd/bd/doctor/cursor.go Normal file
View file

@ -0,0 +1,208 @@
package doctor
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/steveyegge/beads/cmd/bd/setup"
)
// CheckCursor reports whether beads-managed Cursor agent hooks are installed.
// It mirrors CheckClaude: Go observes and reports; the agent/user decides. The
// hooks (sessionStart/preCompact/postToolUse calling `bd cursor-hook`) are what
// keep beads context alive across compaction in Cursor.
// repoPath is the project root directory.
func CheckCursor(repoPath string) DoctorCheck {
projectHooks := filepath.Join(repoPath, ".cursor", "hooks.json")
hasProject := hasBeadsCursorHooks(projectHooks)
hasGlobal := false
if home, err := os.UserHomeDir(); err == nil {
hasGlobal = hasBeadsCursorHooks(filepath.Join(home, ".cursor", "hooks.json"))
}
if hasProject || hasGlobal {
loc := ".cursor/hooks.json"
if !hasProject && hasGlobal {
loc = "~/.cursor/hooks.json"
}
return DoctorCheck{
Name: "Cursor Integration",
Status: StatusOK,
Message: "Hooks installed",
Detail: "bd prime auto-injected on sessionStart and recovered after compaction (" + loc + ")",
}
}
// Only nudge when Cursor is actually in use; otherwise stay quiet so
// non-Cursor users don't see spurious warnings.
if !isCursorPresent(repoPath) {
return DoctorCheck{
Name: "Cursor Integration",
Status: StatusOK,
Message: "N/A (Cursor not detected)",
}
}
return DoctorCheck{
Name: "Cursor Integration",
Status: StatusWarning,
Message: "Hooks not installed",
Detail: "Cursor will only see the static rule (if any) and won't auto-recover\n" +
" beads context after a context compaction.",
Fix: "Run 'bd setup cursor' to install sessionStart/preCompact/postToolUse hooks\n" +
" (or 'bd setup cursor --global' for ~/.cursor/hooks.json across all projects).",
}
}
// hasBeadsCursorHooks reports whether a hooks.json contains a bd-managed hook
// (a command starting with "bd cursor-hook") for any managed event.
func hasBeadsCursorHooks(path string) bool {
return len(cursorBeadsHookEvents(path)) > 0
}
// cursorBeadsHookEvents returns the managed events in a hooks.json that have a
// bd-managed hook (a "bd cursor-hook " command). It returns nil if the file is
// absent or malformed (see CheckCursorSettingsHealth for that case). Detection
// delegates to the setup package so the installer and doctor agree on which
// events bd manages and what a bd-managed entry looks like.
func cursorBeadsHookEvents(path string) []string {
data, err := os.ReadFile(path) // #nosec G304 -- path is constructed from known safe locations (repo root / home .cursor), not user input
if err != nil {
return nil
}
var config map[string]interface{}
if err := json.Unmarshal(data, &config); err != nil {
return nil
}
return setup.CursorManagedHookEvents(config)
}
// CheckCursorSettingsHealth reports malformed .cursor/hooks.json files. A broken
// hooks.json silently disables every Cursor hook, so this is an error (mirrors
// CheckClaudeSettingsHealth). repoPath is the project root directory.
func CheckCursorSettingsHealth(repoPath string) DoctorCheck {
files := []struct{ path, label string }{
{filepath.Join(repoPath, ".cursor", "hooks.json"), ".cursor/hooks.json"},
}
if home, err := os.UserHomeDir(); err == nil {
files = append(files, struct{ path, label string }{
filepath.Join(home, ".cursor", "hooks.json"), "~/.cursor/hooks.json",
})
}
var malformed []string
var checked int
for _, f := range files {
data, err := os.ReadFile(f.path) // #nosec G304 -- known safe .cursor locations, not user input
if err != nil {
continue
}
checked++
var parsed map[string]interface{}
if err := json.Unmarshal(data, &parsed); err != nil {
malformed = append(malformed, fmt.Sprintf("%s: %v", f.label, err))
}
}
if checked == 0 {
return DoctorCheck{
Name: "Cursor Settings Health",
Status: StatusOK,
Message: "No Cursor hooks files found",
}
}
if len(malformed) > 0 {
return DoctorCheck{
Name: "Cursor Settings Health",
Status: StatusError,
Message: fmt.Sprintf("%d malformed hooks file(s)", len(malformed)),
Detail: strings.Join(malformed, "\n"),
Fix: "Fix the JSON syntax in the listed file(s). A malformed hooks.json silently disables all Cursor hooks.",
}
}
return DoctorCheck{
Name: "Cursor Settings Health",
Status: StatusOK,
Message: fmt.Sprintf("%d hooks file(s) valid", checked),
}
}
// CheckCursorHookCompleteness verifies that when bd-managed Cursor hooks are
// installed, all three lifecycle events are present. bd's compaction recovery
// needs sessionStart (prime on start/after compaction), preCompact (arm
// recovery), and postToolUse (re-inject after compaction); a partial install
// (e.g. a hand-edited hooks.json) silently degrades recovery. Mirrors
// CheckClaudeHookCompleteness. repoPath is the project root directory.
func CheckCursorHookCompleteness(repoPath string) DoctorCheck {
paths := []string{filepath.Join(repoPath, ".cursor", "hooks.json")}
if home, err := os.UserHomeDir(); err == nil {
paths = append(paths, filepath.Join(home, ".cursor", "hooks.json"))
}
present := map[string]bool{}
for _, p := range paths {
for _, ev := range cursorBeadsHookEvents(p) {
present[ev] = true
}
}
if len(present) == 0 {
return DoctorCheck{
Name: "Cursor Hook Completeness",
Status: StatusOK,
Message: "N/A (no hooks installed)",
}
}
var missing []string
for _, ev := range setup.CursorManagedHookEventNames() {
if !present[ev] {
missing = append(missing, ev)
}
}
if len(missing) == 0 {
return DoctorCheck{
Name: "Cursor Hook Completeness",
Status: StatusOK,
Message: "All recovery hooks present (sessionStart, preCompact, postToolUse)",
}
}
return DoctorCheck{
Name: "Cursor Hook Completeness",
Status: StatusWarning,
Message: "Missing hook event(s): " + strings.Join(missing, ", "),
Detail: "sessionStart primes context; preCompact + postToolUse recover beads context after a compaction.",
Fix: "Run 'bd setup cursor' to reinstall the full hook set.",
}
}
// isCursorPresent returns true when Cursor appears to be in use: running inside
// a Cursor hook/agent, the cursor CLI is on PATH, a project .cursor/ dir exists,
// or the user has a ~/.cursor/ directory.
func isCursorPresent(repoPath string) bool {
// Set by Cursor when running hooks/agents (see Cursor hooks env vars).
if os.Getenv("CURSOR_PROJECT_DIR") != "" || os.Getenv("CURSOR_TRACE_ID") != "" {
return true
}
for _, bin := range []string{"cursor-agent", "cursor"} {
if _, err := exec.LookPath(bin); err == nil {
return true
}
}
if info, err := os.Stat(filepath.Join(repoPath, ".cursor")); err == nil && info.IsDir() {
return true
}
if home, err := os.UserHomeDir(); err == nil {
if info, err := os.Stat(filepath.Join(home, ".cursor")); err == nil && info.IsDir() {
return true
}
}
return false
}

View file

@ -0,0 +1,154 @@
package doctor
import (
"os"
"path/filepath"
"testing"
)
func writeCursorHooksFile(t *testing.T, repoDir, body string) {
t.Helper()
if err := os.MkdirAll(filepath.Join(repoDir, ".cursor"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(repoDir, ".cursor", "hooks.json"), []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
func TestCheckCursor_HooksInstalled(t *testing.T) {
repo := t.TempDir()
t.Setenv("HOME", t.TempDir()) // isolate any real ~/.cursor
t.Setenv("USERPROFILE", t.TempDir())
writeCursorHooksFile(t, repo, `{"version":1,"hooks":{"sessionStart":[{"command":"bd cursor-hook sessionStart"}]}}`)
dc := CheckCursor(repo)
if dc.Status != StatusOK {
t.Fatalf("status = %q, want ok (%#v)", dc.Status, dc)
}
if dc.Message != "Hooks installed" {
t.Errorf("message = %q, want %q", dc.Message, "Hooks installed")
}
}
func TestCheckCursor_PresentButNoHooks(t *testing.T) {
repo := t.TempDir()
t.Setenv("HOME", t.TempDir()) // ensure no global bd hooks
t.Setenv("USERPROFILE", t.TempDir())
// A .cursor/ dir signals Cursor is in use, but no bd hooks are installed.
if err := os.MkdirAll(filepath.Join(repo, ".cursor", "rules"), 0o755); err != nil {
t.Fatal(err)
}
dc := CheckCursor(repo)
if dc.Status != StatusWarning {
t.Fatalf("status = %q, want warning (%#v)", dc.Status, dc)
}
}
func TestCheckCursorSettingsHealth(t *testing.T) {
t.Run("malformed is error", func(t *testing.T) {
repo := t.TempDir()
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", t.TempDir())
writeCursorHooksFile(t, repo, `{not valid json`)
dc := CheckCursorSettingsHealth(repo)
if dc.Status != StatusError {
t.Fatalf("status = %q, want error (%#v)", dc.Status, dc)
}
})
t.Run("valid is ok", func(t *testing.T) {
repo := t.TempDir()
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", t.TempDir())
writeCursorHooksFile(t, repo, `{"version":1,"hooks":{"sessionStart":[{"command":"bd cursor-hook sessionStart"}]}}`)
dc := CheckCursorSettingsHealth(repo)
if dc.Status != StatusOK {
t.Fatalf("status = %q, want ok (%#v)", dc.Status, dc)
}
})
t.Run("absent is ok", func(t *testing.T) {
repo := t.TempDir()
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", t.TempDir())
dc := CheckCursorSettingsHealth(repo)
if dc.Status != StatusOK {
t.Fatalf("status = %q, want ok (%#v)", dc.Status, dc)
}
})
}
func TestCheckCursorHookCompleteness(t *testing.T) {
t.Run("all events present is ok", func(t *testing.T) {
repo := t.TempDir()
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", t.TempDir())
writeCursorHooksFile(t, repo, `{"version":1,"hooks":{
"sessionStart":[{"command":"bd cursor-hook sessionStart"}],
"preCompact":[{"command":"bd cursor-hook preCompact"}],
"postToolUse":[{"command":"bd cursor-hook postToolUse"}]
}}`)
dc := CheckCursorHookCompleteness(repo)
if dc.Status != StatusOK {
t.Fatalf("status = %q, want ok (%#v)", dc.Status, dc)
}
})
t.Run("partial install warns", func(t *testing.T) {
repo := t.TempDir()
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", t.TempDir())
// sessionStart only — recovery hooks missing.
writeCursorHooksFile(t, repo, `{"version":1,"hooks":{"sessionStart":[{"command":"bd cursor-hook sessionStart"}]}}`)
dc := CheckCursorHookCompleteness(repo)
if dc.Status != StatusWarning {
t.Fatalf("status = %q, want warning (%#v)", dc.Status, dc)
}
})
t.Run("no hooks is N/A ok", func(t *testing.T) {
repo := t.TempDir()
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", t.TempDir())
dc := CheckCursorHookCompleteness(repo)
if dc.Status != StatusOK {
t.Fatalf("status = %q, want ok (%#v)", dc.Status, dc)
}
})
}
func TestHasBeadsCursorHooks(t *testing.T) {
dir := t.TempDir()
hooks := filepath.Join(dir, "hooks.json")
cases := []struct {
name string
body string
want bool
}{
{"managed sessionStart", `{"hooks":{"sessionStart":[{"command":"bd cursor-hook sessionStart"}]}}`, true},
{"managed postToolUse", `{"hooks":{"postToolUse":[{"command":"bd cursor-hook postToolUse"}]}}`, true},
{"user hook only", `{"hooks":{"afterFileEdit":[{"command":"./format.sh"}]}}`, false},
{"empty", `{"version":1}`, false},
{"malformed", `{not json`, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if err := os.WriteFile(hooks, []byte(tc.body), 0o644); err != nil {
t.Fatal(err)
}
if got := hasBeadsCursorHooks(hooks); got != tc.want {
t.Errorf("hasBeadsCursorHooks = %v, want %v", got, tc.want)
}
})
}
}

View file

@ -1666,8 +1666,8 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
}
}
// Auto-setup Claude hooks and Codex project integration. Skip in stealth
// mode or when agents are skipped.
// Auto-setup Claude hooks, Codex, and Cursor project integration. Skip in
// stealth mode or when agents are skipped.
if !stealth && !skipAgents && !isBareGitRepo() {
if err := setup.InstallClaudeProject(stealth); err != nil {
if !quiet {
@ -1681,6 +1681,12 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
}
// Non-fatal - continue with init
}
if err := setup.InstallCursorProject(); err != nil {
if !quiet {
fmt.Fprintf(os.Stderr, "Warning: failed to setup Cursor integration: %v\n", err)
}
// Non-fatal - continue with init
}
}
// Auto-stage and commit beads files so bd doctor doesn't warn about
@ -1706,8 +1712,10 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
claudeMdCmd := exec.Command("git", "add", "CLAUDE.md")
_ = claudeMdCmd.Run()
}
// Also stage Codex project integration files if created by setup
for _, path := range []string{".agents", ".codex"} {
// Also stage Codex and Cursor project integration files if created
// by setup. Cursor project hooks/rules are meant to be committed
// (a no-op git add if .cursor/ is gitignored in this repo).
for _, path := range []string{".agents", ".codex", ".cursor"} {
if _, statErr := os.Stat(path); statErr == nil {
codexCmd := exec.Command("git", "add", path)
_ = codexCmd.Run()
@ -2123,7 +2131,7 @@ func init() {
initCmd.Flags().Bool("stealth", false, "Enable stealth mode: global gitattributes and gitignore, no local repo tracking")
initCmd.Flags().Bool("setup-exclude", false, "Configure .git/info/exclude to keep beads files local (for forks)")
initCmd.Flags().Bool("skip-hooks", false, "Skip git hooks installation")
initCmd.Flags().Bool("skip-agents", false, "Skip AGENTS.md and Claude/Codex setup generation")
initCmd.Flags().Bool("skip-agents", false, "Skip AGENTS.md and Claude/Codex/Cursor setup generation")
initCmd.Flags().Bool("force", false, "Deprecated alias for --reinit-local. Bypasses only the LOCAL data-safety guard; does NOT authorize remote divergence (see 'bd help init-safety').")
initCmd.Flags().Bool("reinit-local", false, "Re-initialize local .beads/ over existing local data. Does NOT authorize remote divergence; see --discard-remote.")
initCmd.Flags().Bool("discard-remote", false, "Authorize discarding the configured remote's Dolt history when re-initializing. Requires --destroy-token in non-interactive mode; see 'bd help init-safety'.")

View file

@ -1469,6 +1469,9 @@ func TestEmbeddedInit(t *testing.T) {
requireFile(t, filepath.Join(dir, ".agents", "skills", "beads", "agents", "openai.yaml"))
requireFile(t, filepath.Join(dir, ".codex", "config.toml"))
requireFile(t, filepath.Join(dir, ".codex", "hooks.json"))
// Cursor integration is auto-installed by bd init too (rules + hooks).
requireFile(t, filepath.Join(dir, ".cursor", "rules", "beads.mdc"))
requireFile(t, filepath.Join(dir, ".cursor", "hooks.json"))
content, err := os.ReadFile(filepath.Join(beadsDir, ".gitignore"))
if err != nil {

View file

@ -846,6 +846,7 @@ var rootCmd = &cobra.Command{
"completion",
"context", // reads config files directly, does not need DB open
"codex-hook",
"cursor-hook", // shells out to `bd prime`; never opens the store itself
"doctor",
"dolt", // bare "bd dolt" shows help only; subcommands handled below
"fish",

View file

@ -36,7 +36,8 @@ Recipes define where beads workflow instructions are written. Built-in recipes
include cursor, claude, copilot, gemini, aider, factory, codex, mux, opencode, junie, windsurf, cody, and kilocode.
Examples:
bd setup cursor # Install Cursor IDE integration
bd setup cursor # Install Cursor IDE integration (rules + agent hooks)
bd setup cursor --global # Install global Cursor hooks (~/.cursor/hooks.json)
bd setup codex # Install Codex skill + AGENTS.md guidance + native hooks
bd setup codex --global # Install global Codex skill + guidance + native hooks
bd setup copilot # Install Copilot CLI plugin + repository instructions
@ -319,11 +320,11 @@ func translateSetupError(err error) error {
func runCursorRecipe() error {
switch {
case setupCheck:
return translateSetupError(setup.CheckCursor())
return translateSetupError(setup.CheckCursor(setupGlobal))
case setupRemove:
return translateSetupError(setup.RemoveCursor())
return translateSetupError(setup.RemoveCursor(setupGlobal))
default:
return translateSetupError(setup.InstallCursor())
return translateSetupError(setup.InstallCursor(setupGlobal))
}
}
@ -426,7 +427,7 @@ func init() {
setupCmd.Flags().BoolVar(&setupCheck, "check", false, "Check if integration is installed")
setupCmd.Flags().BoolVar(&setupRemove, "remove", false, "Remove the integration")
setupCmd.Flags().BoolVar(&setupProject, "project", false, "Install for this project only (gemini/mux)")
setupCmd.Flags().BoolVar(&setupGlobal, "global", false, "Install globally (claude/codex/mux; writes to ~/.claude/settings.json, $CODEX_HOME/AGENTS.md or ~/.codex/AGENTS.md, or ~/.mux/AGENTS.md)")
setupCmd.Flags().BoolVar(&setupGlobal, "global", false, "Install globally (claude/codex/cursor/mux; writes to ~/.claude/settings.json, $CODEX_HOME/AGENTS.md or ~/.codex/AGENTS.md, ~/.cursor/hooks.json, or ~/.mux/AGENTS.md)")
setupCmd.Flags().BoolVar(&setupStealth, "stealth", false, "Use stealth mode (claude/gemini)")
rootCmd.AddCommand(setupCmd)

View file

@ -125,7 +125,11 @@ func RemoveCodex(global bool) error {
}
func removeCodex(env codexEnv, global bool) error {
if err := removeAgentSkill(codexAgentSkillEnv(env, global)); err != nil {
// The agent skill is shared with Cursor (same .agents/skills/beads path).
// Only remove it if Cursor isn't still relying on it.
if cursorIntegrationInstalledAt(env.readFile, codexRootDir(env, global), global) {
_, _ = fmt.Fprintln(env.stdout, "Keeping Beads agent skill (still used by Cursor integration)")
} else if err := removeAgentSkill(codexAgentSkillEnv(env, global)); err != nil {
return err
}
if err := removeCodexNativeHooks(env, global); err != nil {
@ -134,6 +138,25 @@ func removeCodex(env codexEnv, global bool) error {
return removeCodexInstructions(env, global)
}
// cursorIntegrationInstalledAt reports whether Cursor's bd integration exists
// under root (projectDir for project scope, homeDir for global scope), using the
// provided readFile so the check stays hermetic in tests. Both Cursor and Codex
// install the shared .agents/skills/beads skill, so removing one must not delete
// the skill while the other still relies on it.
func cursorIntegrationInstalledAt(readFile func(string) ([]byte, error), root string, global bool) bool {
if data, err := readFile(filepath.Join(root, ".cursor", "hooks.json")); err == nil {
if config, perr := parseHooksJSON(data); perr == nil && cursorBeadsHooksPresent(config) {
return true
}
}
if !global {
if _, err := readFile(filepath.Join(root, cursorRulesPath)); err == nil {
return true
}
}
return false
}
func codexSetupCommand(global bool) string {
if global {
return "bd setup codex --global"
@ -470,23 +493,24 @@ func installCodexHooksJSON(env codexEnv, global bool) error {
return err
}
current := map[string]interface{}{}
if data, err := env.readFile(path); err == nil && len(strings.TrimSpace(string(data))) > 0 {
if err := json.Unmarshal(data, &current); err != nil {
_, _ = fmt.Fprintf(env.stderr, "Error: parse %s: %v\n", path, err)
return err
}
} else if err != nil && !os.IsNotExist(err) {
data, err := env.readFile(path)
if err != nil && !os.IsNotExist(err) {
_, _ = fmt.Fprintf(env.stderr, "Error: read %s: %v\n", path, err)
return err
}
if err == nil {
if current, err = parseHooksJSON(data); err != nil {
_, _ = fmt.Fprintf(env.stderr, "Error: parse %s: %v\n", path, err)
return err
}
}
upsertCodexManagedHooks(current)
data, err := json.MarshalIndent(current, "", " ")
out, err := marshalHooksJSON(current)
if err != nil {
_, _ = fmt.Fprintf(env.stderr, "Error: marshal %s: %v\n", path, err)
return err
}
data = append(data, '\n')
if err := env.writeFile(path, data); err != nil {
if err := env.writeFile(path, out); err != nil {
_, _ = fmt.Fprintf(env.stderr, "Error: write %s: %v\n", path, err)
return err
}
@ -503,12 +527,10 @@ func removeCodexHooksJSON(env codexEnv, global bool) error {
_, _ = fmt.Fprintf(env.stderr, "Error: read %s: %v\n", path, err)
return err
}
current := map[string]interface{}{}
if len(strings.TrimSpace(string(data))) > 0 {
if err := json.Unmarshal(data, &current); err != nil {
_, _ = fmt.Fprintf(env.stderr, "Error: parse %s: %v\n", path, err)
return err
}
current, err := parseHooksJSON(data)
if err != nil {
_, _ = fmt.Fprintf(env.stderr, "Error: parse %s: %v\n", path, err)
return err
}
removeCodexManagedHooks(current)
if len(current) == 0 {
@ -517,11 +539,10 @@ func removeCodexHooksJSON(env codexEnv, global bool) error {
}
return nil
}
next, err := json.MarshalIndent(current, "", " ")
next, err := marshalHooksJSON(current)
if err != nil {
return err
}
next = append(next, '\n')
return env.writeFile(path, next)
}
@ -530,8 +551,8 @@ func codexHooksJSONCurrent(env codexEnv, global bool) bool {
if err != nil {
return false
}
current := map[string]interface{}{}
if err := json.Unmarshal(data, &current); err != nil {
current, err := parseHooksJSON(data)
if err != nil {
return false
}
return codexManagedHooksCurrent(current)
@ -706,6 +727,26 @@ func codexManagedHooksCurrent(config map[string]interface{}) bool {
return true
}
// codexBeadsHooksPresent reports whether a parsed hooks.json config contains any
// bd-managed Codex hook entry ("bd codex-hook " command). It mirrors
// cursorBeadsHooksPresent so codexIntegrationInstalled can detect a hooks-only
// Codex install (no AGENTS.md section) the same way cursorIntegrationInstalledAt
// detects a hooks-only Cursor install.
func codexBeadsHooksPresent(config map[string]interface{}) bool {
hooks, ok := config["hooks"].(map[string]interface{})
if !ok {
return false
}
for event := range codexManagedHooks() {
for _, entry := range toInterfaceSlice(hooks[event]) {
if codexHookEntryManaged(entry) {
return true
}
}
}
return false
}
func removeCodexManagedHookEvent(hooks map[string]interface{}, event string) {
entries := toInterfaceSlice(hooks[event])
filtered := entries[:0]

View file

@ -263,6 +263,32 @@ func TestRemoveCodexRemovesSkillAndInstructionsSection(t *testing.T) {
}
}
func TestRemoveCodexKeepsSkillWhenCursorPresent(t *testing.T) {
env, _, _ := newCodexTestEnv(t)
if err := installCodex(env, false); err != nil {
t.Fatalf("installCodex returned error: %v", err)
}
// Simulate a Cursor install that shares the .agents/skills/beads skill by
// writing a bd-managed cursor hooks file under the same root.
cursorDir := filepath.Join(env.projectDir, ".cursor")
if err := os.MkdirAll(cursorDir, 0o755); err != nil {
t.Fatalf("mkdir .cursor: %v", err)
}
hooks := `{"version":1,"hooks":{"sessionStart":[{"command":"bd cursor-hook sessionStart"}]}}`
if err := os.WriteFile(filepath.Join(cursorDir, "hooks.json"), []byte(hooks), 0o644); err != nil {
t.Fatalf("write cursor hooks: %v", err)
}
if err := removeCodex(env, false); err != nil {
t.Fatalf("removeCodex returned error: %v", err)
}
if _, err := os.Stat(agentSkillPath(env.projectDir)); err != nil {
t.Errorf("skill should be kept while Cursor integration is present: %v", err)
}
}
func TestCodexHooksConfigMergeIsIdempotent(t *testing.T) {
env, _, _ := newCodexTestEnv(t)
configPath := codexConfigPath(env, false)

View file

@ -4,96 +4,491 @@ 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
---
# Beads Issue Tracking
# Auto-generated by 'bd setup cursor' - do not remove these markers
# BEGIN BEADS INTEGRATION
<!-- BEGIN BEADS INTEGRATION -->
<!-- Auto-generated by 'bd setup cursor'. Content between these markers is managed by bd. -->
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 dolt push`" + ` at end of session to sync with the Dolt remote
- Git hooks refresh exports and legacy fallbacks; Dolt remotes handle sync
## 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> --claim # Claim work atomically
bd unclaim <id> # Release stuck issue (agent crashed)
bd close <id> # Mark complete
bd dep add <issue> <depends-on> # Add dependency (issue depends on depends-on)
bd dolt push # Sync with Dolt remote
` + "```" + `
## Workflow
1. Check for ready work: ` + "`bd ready`" + `
2. Claim an issue atomically: ` + "`bd update <id> --claim`" + `
3. Do the work
4. Mark complete: ` + "`bd close <id>`" + `
5. Sync: ` + "`bd dolt push`" + `
## 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
` + recipes.Template + `
<!-- END BEADS INTEGRATION -->
`
func InstallCursor() error {
rulesPath := ".cursor/rules/beads.mdc"
// 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 err := EnsureDir(filepath.Dir(rulesPath), 0755); err != nil {
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)
}
if err := atomicWriteFile(rulesPath, []byte(cursorRulesTemplate)); err != nil {
return HandleError("write rules: %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")
fmt.Printf(" Rules: %s\n", rulesPath)
fmt.Println("\nRestart Cursor for changes to take effect.")
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
}
func CheckCursor() error {
rulesPath := ".cursor/rules/beads.mdc"
// 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
}
if !FileExists(rulesPath) {
return HandleErrorWithHint("Cursor integration not installed", "Run: bd setup cursor")
// 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
}
}
fmt.Println("✓ Cursor integration installed:", rulesPath)
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
}
func RemoveCursor() error {
rulesPath := ".cursor/rules/beads.mdc"
// 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...")
if err := os.Remove(rulesPath); err != nil {
if os.IsNotExist(err) {
fmt.Println("No rules file found")
return nil
}
return HandleError("failed to remove file: %v", err)
hooksPath, err := cursorHooksTargetPath(global)
if err != nil {
return HandleError("%v", err)
}
fmt.Println("✓ Removed Cursor integration")
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
}

View file

@ -1,12 +1,233 @@
package setup
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/templates"
)
// inTempDir chdir's into a fresh temp directory for the duration of the test.
func inTempDir(t *testing.T) {
t.Helper()
origDir, err := os.Getwd()
if err != nil {
t.Fatalf("getwd: %v", err)
}
if err := os.Chdir(t.TempDir()); err != nil {
t.Fatalf("chdir: %v", err)
}
t.Cleanup(func() {
if err := os.Chdir(origDir); err != nil {
t.Fatalf("restore wd: %v", err)
}
})
}
func readCursorHooksFile(t *testing.T) map[string]interface{} {
t.Helper()
data, err := os.ReadFile(cursorHooksPath)
if err != nil {
t.Fatalf("read hooks: %v", err)
}
var cfg map[string]interface{}
if err := json.Unmarshal(data, &cfg); err != nil {
t.Fatalf("parse hooks: %v", err)
}
return cfg
}
func cursorHookCommandsForEvent(t *testing.T, cfg map[string]interface{}, event string) []string {
t.Helper()
hooks, _ := cfg["hooks"].(map[string]interface{})
entries, _ := hooks[event].([]interface{})
var cmds []string
for _, e := range entries {
if m, ok := e.(map[string]interface{}); ok {
if c, ok := m["command"].(string); ok {
cmds = append(cmds, c)
}
}
}
return cmds
}
func TestInstallCursorInstallsHooks(t *testing.T) {
inTempDir(t)
InstallCursor(false)
if !FileExists(cursorHooksPath) {
t.Fatalf("hooks file %s not created", cursorHooksPath)
}
cfg := readCursorHooksFile(t)
for event, want := range cursorManagedHooks() {
cmds := cursorHookCommandsForEvent(t, cfg, event)
found := false
for _, c := range cmds {
if c == want {
found = true
}
}
if !found {
t.Errorf("event %q missing command %q (got %v)", event, want, cmds)
}
}
ok, err := cursorHooksInstalled(cursorHooksPath)
if err != nil || !ok {
t.Errorf("cursorHooksInstalled = %v, %v; want true, nil", ok, err)
}
}
func TestInstallCursorInstallsSkill(t *testing.T) {
inTempDir(t)
InstallCursor(false)
skillPath := agentSkillPath(".")
if !FileExists(skillPath) {
t.Fatalf("agent skill not installed at %s", skillPath)
}
data, err := os.ReadFile(skillPath)
if err != nil {
t.Fatalf("read skill: %v", err)
}
if string(data) != templates.BeadsAgentSkill() {
t.Error("installed skill content does not match managed template")
}
}
func TestRemoveCursorRemovesSkillWhenCodexAbsent(t *testing.T) {
inTempDir(t)
InstallCursor(false)
if !FileExists(agentSkillPath(".")) {
t.Fatal("precondition: skill should exist after install")
}
RemoveCursor(false)
if FileExists(agentSkillPath(".")) {
t.Error("skill should be removed when no other integration relies on it")
}
}
func TestRemoveCursorKeepsSkillWhenCodexPresent(t *testing.T) {
inTempDir(t)
InstallCursor(false)
// Simulate a Codex install that shares the .agents/skills/beads skill by
// writing its managed AGENTS.md section.
if err := os.WriteFile(codexInstructionsFile, []byte(codexManagedSection()+"\n"), 0o644); err != nil {
t.Fatal(err)
}
RemoveCursor(false)
if !FileExists(agentSkillPath(".")) {
t.Error("skill should be kept while Codex integration is present")
}
}
func TestRemoveCursorKeepsSkillWhenCodexHooksPresent(t *testing.T) {
inTempDir(t)
InstallCursor(false)
// Simulate a Codex install that shares the .agents/skills/beads skill but is
// visible only via .codex/hooks.json (no AGENTS.md section). codexIntegrationInstalled
// must detect this too, symmetric with cursorIntegrationInstalledAt's hooks check.
if err := os.MkdirAll(codexConfigDir, 0o755); err != nil {
t.Fatal(err)
}
codexHooks := `{"version":1,"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"bd codex-hook SessionStart"}]}]}}`
if err := os.WriteFile(filepath.Join(codexConfigDir, codexHooksFile), []byte(codexHooks), 0o644); err != nil {
t.Fatal(err)
}
RemoveCursor(false)
if !FileExists(agentSkillPath(".")) {
t.Error("skill should be kept while a bd-managed .codex/hooks.json is present")
}
}
func TestInstallCursorHooksIdempotent(t *testing.T) {
inTempDir(t)
InstallCursor(false)
InstallCursor(false)
cfg := readCursorHooksFile(t)
for event := range cursorManagedHooks() {
cmds := cursorHookCommandsForEvent(t, cfg, event)
if len(cmds) != 1 {
t.Errorf("event %q has %d commands after double install, want 1: %v", event, len(cmds), cmds)
}
}
}
func TestInstallCursorHooksPreservesUserHooks(t *testing.T) {
inTempDir(t)
if err := os.MkdirAll(".cursor", 0o755); err != nil {
t.Fatal(err)
}
existing := `{"version":1,"hooks":{"afterFileEdit":[{"command":"./format.sh"}]}}`
if err := os.WriteFile(cursorHooksPath, []byte(existing), 0o644); err != nil {
t.Fatal(err)
}
InstallCursor(false)
cfg := readCursorHooksFile(t)
edits := cursorHookCommandsForEvent(t, cfg, "afterFileEdit")
if len(edits) != 1 || edits[0] != "./format.sh" {
t.Errorf("user afterFileEdit hook not preserved: %v", edits)
}
if cmds := cursorHookCommandsForEvent(t, cfg, "sessionStart"); len(cmds) != 1 {
t.Errorf("sessionStart hook not installed alongside user hook: %v", cmds)
}
}
func TestRemoveCursorRemovesManagedHooks(t *testing.T) {
inTempDir(t)
InstallCursor(false)
RemoveCursor(false)
if FileExists(cursorHooksPath) {
t.Errorf("hooks file should be removed when only bd hooks were present")
}
if FileExists(cursorRulesPath) {
t.Errorf("rules file should be removed")
}
}
func TestRemoveCursorPreservesUserHooks(t *testing.T) {
inTempDir(t)
if err := os.MkdirAll(".cursor", 0o755); err != nil {
t.Fatal(err)
}
existing := `{"version":1,"hooks":{"afterFileEdit":[{"command":"./format.sh"}]}}`
if err := os.WriteFile(cursorHooksPath, []byte(existing), 0o644); err != nil {
t.Fatal(err)
}
InstallCursor(false)
RemoveCursor(false)
if !FileExists(cursorHooksPath) {
t.Fatalf("hooks file should remain because a user hook is present")
}
cfg := readCursorHooksFile(t)
edits := cursorHookCommandsForEvent(t, cfg, "afterFileEdit")
if len(edits) != 1 || edits[0] != "./format.sh" {
t.Errorf("user hook not preserved after remove: %v", edits)
}
for event := range cursorManagedHooks() {
if cmds := cursorHookCommandsForEvent(t, cfg, event); len(cmds) != 0 {
t.Errorf("managed event %q should be removed: %v", event, cmds)
}
}
}
func TestCursorRulesTemplate(t *testing.T) {
// Verify template contains required content
requiredContent := []string{
@ -51,7 +272,7 @@ func TestInstallCursor(t *testing.T) {
}
}()
InstallCursor()
InstallCursor(false)
// Verify file was created
rulesPath := ".cursor/rules/beads.mdc"
@ -92,7 +313,7 @@ func TestInstallCursor_ExistingDirectory(t *testing.T) {
}
// Should not fail
InstallCursor()
InstallCursor(false)
// Verify file was created
if !FileExists(".cursor/rules/beads.mdc") {
@ -125,7 +346,7 @@ func TestInstallCursor_OverwriteExisting(t *testing.T) {
t.Fatalf("failed to create old file: %v", err)
}
InstallCursor()
InstallCursor(false)
// Verify content was overwritten
data, err := os.ReadFile(rulesPath)
@ -158,10 +379,10 @@ func TestInstallCursorIdempotent(t *testing.T) {
}()
// Run twice
InstallCursor()
InstallCursor(false)
firstData, _ := os.ReadFile(".cursor/rules/beads.mdc")
InstallCursor()
InstallCursor(false)
secondData, _ := os.ReadFile(".cursor/rules/beads.mdc")
if string(firstData) != string(secondData) {
@ -186,7 +407,7 @@ func TestRemoveCursor(t *testing.T) {
}()
// Install first
InstallCursor()
InstallCursor(false)
// Verify file exists
rulesPath := ".cursor/rules/beads.mdc"
@ -195,7 +416,7 @@ func TestRemoveCursor(t *testing.T) {
}
// Remove
RemoveCursor()
RemoveCursor(false)
// Verify file is gone
if FileExists(rulesPath) {
@ -220,7 +441,7 @@ func TestRemoveCursor_NoFile(t *testing.T) {
}()
// Should not panic when file doesn't exist
RemoveCursor()
RemoveCursor(false)
}
func TestCheckCursor_NotInstalled(t *testing.T) {
@ -239,7 +460,7 @@ func TestCheckCursor_NotInstalled(t *testing.T) {
}
}()
if err := CheckCursor(); err == nil {
if err := CheckCursor(false); err == nil {
t.Fatal("CheckCursor should return error when not installed")
}
}
@ -261,10 +482,10 @@ func TestCheckCursor_Installed(t *testing.T) {
}()
// Install first
InstallCursor()
InstallCursor(false)
// Should not panic or exit
CheckCursor()
CheckCursor(false)
}
func TestCursorRulesPath(t *testing.T) {
@ -287,7 +508,7 @@ func TestCursorRulesPath(t *testing.T) {
}
}()
InstallCursor()
InstallCursor(false)
// Verify the file was created at the expected path
if !FileExists(expectedPath) {
@ -295,6 +516,62 @@ func TestCursorRulesPath(t *testing.T) {
}
}
func TestInstallCursorProject(t *testing.T) {
inTempDir(t)
if err := InstallCursorProject(); err != nil {
t.Fatalf("InstallCursorProject: %v", err)
}
if !FileExists(cursorRulesPath) {
t.Errorf("project rules not installed")
}
ok, err := cursorHooksInstalled(cursorHooksPath)
if err != nil || !ok {
t.Errorf("project hooks not installed: ok=%v err=%v", ok, err)
}
}
func TestInstallCursorGlobalHooksOnly(t *testing.T) {
inTempDir(t)
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
InstallCursor(true)
globalHooks := filepath.Join(home, ".cursor", "hooks.json")
if !FileExists(globalHooks) {
t.Fatalf("global hooks file not created at %s", globalHooks)
}
// Global scope must not write a project rules file.
if FileExists(cursorRulesPath) {
t.Errorf("global install should not create a project rules file")
}
// Skills do have a global location (~/.agents/skills/), so --global installs one.
if !FileExists(agentSkillPath(home)) {
t.Errorf("global agent skill not installed at %s", agentSkillPath(home))
}
ok, err := cursorHooksInstalled(globalHooks)
if err != nil || !ok {
t.Errorf("global cursorHooksInstalled = %v, %v; want true, nil", ok, err)
}
}
func TestRemoveCursorGlobal(t *testing.T) {
inTempDir(t)
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
InstallCursor(true)
RemoveCursor(true)
globalHooks := filepath.Join(home, ".cursor", "hooks.json")
if FileExists(globalHooks) {
t.Errorf("global hooks file should be removed when only bd hooks present")
}
}
func TestCursorTemplateFormatting(t *testing.T) {
// Verify template is well-formed
template := cursorRulesTemplate

View file

@ -0,0 +1,32 @@
package setup
import (
"encoding/json"
"strings"
)
// parseHooksJSON unmarshals an agent hooks.json body into a generic map. Empty
// or whitespace-only input yields an empty (non-nil) map with no error, matching
// how both the Codex and Cursor installers treat a missing/blank file. File I/O
// (and absent-file handling) stays with the caller so each agent keeps its own
// read mechanism.
func parseHooksJSON(data []byte) (map[string]interface{}, error) {
config := map[string]interface{}{}
if len(strings.TrimSpace(string(data))) > 0 {
if err := json.Unmarshal(data, &config); err != nil {
return nil, err
}
}
return config, nil
}
// marshalHooksJSON renders an agent hooks.json config with two-space indent and
// a trailing newline (the on-disk format shared by the Codex and Cursor
// installers).
func marshalHooksJSON(config map[string]interface{}) ([]byte, error) {
data, err := json.MarshalIndent(config, "", " ")
if err != nil {
return nil, err
}
return append(data, '\n'), nil
}

View file

@ -3569,7 +3569,7 @@ bd init [flags]
--server-user string Dolt server MySQL user (default: root)
--setup-exclude Configure .git/info/exclude to keep beads files local (for forks)
--shared-server Enable shared Dolt server mode (all projects share one server at ~/.beads/shared-server/)
--skip-agents Skip AGENTS.md and Claude/Codex setup generation
--skip-agents Skip AGENTS.md and Claude/Codex/Cursor setup generation
--skip-hooks Skip git hooks installation
--sqlite-path string SQLite database file (with --backend=sqlite; relative to the beads dir, default beads.db)
--stealth Enable stealth mode: global gitattributes and gitignore, no local repo tracking
@ -3817,7 +3817,8 @@ Recipes define where beads workflow instructions are written. Built-in recipes
include cursor, claude, copilot, gemini, aider, factory, codex, mux, opencode, junie, windsurf, cody, and kilocode.
Examples:
bd setup cursor # Install Cursor IDE integration
bd setup cursor # Install Cursor IDE integration (rules + agent hooks)
bd setup cursor --global # Install global Cursor hooks (~/.cursor/hooks.json)
bd setup codex # Install Codex skill + AGENTS.md guidance + native hooks
bd setup codex --global # Install global Codex skill + guidance + native hooks
bd setup copilot # Install Copilot CLI plugin + repository instructions
@ -3841,7 +3842,7 @@ bd setup [recipe] [flags]
```
--add string Add a custom recipe with given name
--check Check if integration is installed
--global Install globally (claude/codex/mux; writes to ~/.claude/settings.json, $CODEX_HOME/AGENTS.md or ~/.codex/AGENTS.md, or ~/.mux/AGENTS.md)
--global Install globally (claude/codex/cursor/mux; writes to ~/.claude/settings.json, $CODEX_HOME/AGENTS.md or ~/.codex/AGENTS.md, ~/.cursor/hooks.json, or ~/.mux/AGENTS.md)
--list List all available recipes
-o, --output string Write template to custom path
--print Print the template to stdout

View file

@ -47,7 +47,7 @@ var BuiltinRecipes = map[string]Recipe{
Name: "Cursor IDE",
Path: ".cursor/rules/beads.mdc",
Type: TypeFile,
Description: "Cursor IDE rules file",
Description: "Cursor IDE rules file + agent hooks (prime on session start, restore after compaction)",
},
"windsurf": {
Name: "Windsurf",

View file

@ -25,6 +25,7 @@ bd ready # Show issues ready to work (no blockers)
bd list --status=open # List all open issues
bd create "title" -t task -p 2 # Create new issue
bd update <id> --claim # Claim work atomically
bd unclaim <id> # Release stuck issue (agent crashed)
bd close <id> # Mark complete
bd dep add <issue> <depends-on> # Add dependency
bd dolt push # Sync with remote when authorized

View file

@ -96,7 +96,7 @@ bd init [flags]
--server-user string Dolt server MySQL user (default: root)
--setup-exclude Configure .git/info/exclude to keep beads files local (for forks)
--shared-server Enable shared Dolt server mode (all projects share one server at ~/.beads/shared-server/)
--skip-agents Skip AGENTS.md and Claude/Codex setup generation
--skip-agents Skip AGENTS.md and Claude/Codex/Cursor setup generation
--skip-hooks Skip git hooks installation
--sqlite-path string SQLite database file (with --backend=sqlite; relative to the beads dir, default beads.db)
--stealth Enable stealth mode: global gitattributes and gitignore, no local repo tracking

View file

@ -16,7 +16,8 @@ Recipes define where beads workflow instructions are written. Built-in recipes
include cursor, claude, copilot, gemini, aider, factory, codex, mux, opencode, junie, windsurf, cody, and kilocode.
Examples:
bd setup cursor # Install Cursor IDE integration
bd setup cursor # Install Cursor IDE integration (rules + agent hooks)
bd setup cursor --global # Install global Cursor hooks (~/.cursor/hooks.json)
bd setup codex # Install Codex skill + AGENTS.md guidance + native hooks
bd setup codex --global # Install global Codex skill + guidance + native hooks
bd setup copilot # Install Copilot CLI plugin + repository instructions
@ -40,7 +41,7 @@ bd setup [recipe] [flags]
```
--add string Add a custom recipe with given name
--check Check if integration is installed
--global Install globally (claude/codex/mux; writes to ~/.claude/settings.json, $CODEX_HOME/AGENTS.md or ~/.codex/AGENTS.md, or ~/.mux/AGENTS.md)
--global Install globally (claude/codex/cursor/mux; writes to ~/.claude/settings.json, $CODEX_HOME/AGENTS.md or ~/.codex/AGENTS.md, ~/.cursor/hooks.json, or ~/.mux/AGENTS.md)
--list List all available recipes
-o, --output string Write template to custom path
--print Print the template to stdout

View file

@ -5,17 +5,145 @@ title: Cursor
# Cursor Integration
Use Beads with Cursor through a project rules file.
Use Beads with Cursor through a project rules file **and** agent lifecycle hooks.
The hooks are what keep Beads context alive across compaction — without them,
Cursor only sees the static rules file and the agent must remember to run
`bd prime` itself (which it often forgets after a context compaction).
```bash
bd setup cursor
bd setup cursor --check
```
The setup command creates `.cursor/rules/beads.mdc` with Beads workflow guidance and quick `bd` command references. Restart Cursor after setup so the rules file is loaded into new agent sessions.
`bd setup cursor` installs three things:
- **`.cursor/rules/beads.mdc`** — an always-applied rule with the canonical Beads
workflow guidance (the same content every other editor integration uses), so it
stays in sync as the workflow evolves. Because it is always applied, Cursor
re-includes it every turn, including after a compaction.
- **`.agents/skills/beads/SKILL.md`** — the Beads agent skill, which Cursor loads
natively from `.agents/skills/` (the same skill the Codex integration installs).
It gives the agent an on-demand, progressive-disclosure reference for `bd`.
- **`.cursor/hooks.json`** — agent hooks that run the hidden `bd cursor-hook`
command at key points in the session. Existing (non-Beads) hooks in this file
are preserved.
The managed hooks are:
| Event | What it does |
|-------|--------------|
| `sessionStart` | Injects full `bd prime` output so the agent starts every session already knowing the workflow, ready work, and project memories. |
| `preCompact` | Arms a one-shot marker and shows a short reminder that context will be restored. |
| `postToolUse` | After a compaction, re-injects `bd prime` exactly once on the next tool call, then no-ops. |
:::note Requirements
Hooks run 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). After setup,
restart Cursor or start a **new** `cursor-agent` session so the hooks load.
The hook entries call `bd cursor-hook`, which Cursor resolves on `PATH` — exactly
like the Claude Code and Codex hooks. **But that `PATH` is not your shell's:**
Cursor rebuilds it for hook subprocesses and prepends its own directories, so a
stale `bd` earlier in *that* order silently wins and every hook fails with no
visible error. The classic case is an old Homebrew `bd` (without the
`cursor-hook` command) shadowing a newer build. Make sure the first `bd` Cursor
finds is current — `~/.local/bin` and `~/go/bin` sort ahead of Homebrew in
Cursor's PATH, so installing or symlinking `bd` there is a reliable way to win
resolution.
In the CLI, the workspace must also be **trusted** — hooks do not run in an
untrusted workspace.
:::
:::tip Auto-installed by `bd init`
You usually don't need to run `bd setup cursor` by hand. `bd init` installs the
Cursor integration automatically (the same way it sets up Claude Code and
Codex), and stages `.cursor/` so the rules + hooks are committed with your repo.
Run `bd setup cursor` only to (re)install into an existing project or to repair
drift.
:::
## Global install (all projects)
To wire the hooks once for every project instead of per-repo:
```bash
bd setup cursor --global # writes ~/.cursor/hooks.json
bd setup cursor --check --global
bd setup cursor --remove --global
```
Global scope installs the **hooks and the agent skill** (`~/.agents/skills/beads`),
but not a rules file. Cursor has no reliable file-based global *rules* location —
global rules belong in **Cursor Settings → Rules** — so `.cursor/rules/beads.mdc`
is project-scoped. This is fine in practice: the global `sessionStart` hook
already injects the full `bd prime` context into every project, which supersedes
the static rule.
## Why these specific hooks
The Claude Code / Codex integrations recover from compaction with a dedicated
post-compaction event plus a prompt-submission hook. Cursor's
[hook API](https://cursor.com/docs/hooks) doesn't offer equivalents, so the
recovery is built from what Cursor *can* do:
- Cursor has **no post-compaction hook** — only `preCompact`, which is
observational and "cannot block or modify the compaction behavior" (its only
output is `user_message`). So `preCompact` just arms a one-shot marker and
notifies you.
- Only **two** hooks can inject model-visible context (`additional_context`):
`sessionStart` and `postToolUse`. `sessionStart` fires only when a new
conversation is created — not after a compaction, and not when resuming with
`cursor-agent --continue`. `preCompact` and `postToolUse` *do* fire in resumed
sessions, so compaction recovery still works under `--continue`; only the
one-time start-of-session injection is skipped (the resumed conversation
already contains it).
- That makes `postToolUse` the only place to re-inject `bd prime` after a
compaction — which the docs explicitly support ("Useful for ... injecting
context").
:::caution Limitation
Post-compaction recovery fires on the **next tool call**. If you have a
purely conversational turn right after a compaction (no tool use), the refresh
waits until the next tool runs — no Cursor hook can inject context on a bare
prompt. Agent sessions call tools often, so in practice this is quick. You can
always run `bd prime` manually to force a refresh.
:::
## Verifying it works (CLI, no hooks pane)
The `cursor-agent` CLI has no hooks output pane, so verify the hooks directly:
```bash
# sessionStart should return {"continue": true, "additional_context": "...bd prime..."}
echo '{"hook_event_name":"sessionStart","workspace_roots":["'"$PWD"'"]}' \
| bd cursor-hook sessionStart | jq .
# In a real session, the agent should know your bd workflow without being told,
# and should recover it after a compaction without you running `bd prime`.
```
If `additional_context` is empty, the directory is not a Beads workspace yet
(run `bd init`) or `bd` is not on Cursor's `PATH`. Note this command runs *your
shell's* `bd`; Cursor may resolve a different one for hooks (see Requirements
above), so a passing check here doesn't guarantee Cursor runs the same build.
`bd doctor` also reports three Cursor checks (under integration diagnostics),
paralleling the Claude checks:
- **Cursor Integration** — flags when Cursor is in use but the hooks aren't installed.
- **Cursor Settings Health** — errors if `.cursor/hooks.json` is malformed JSON
(which would silently disable every hook).
- **Cursor Hook Completeness** — warns if only some of the three managed events
are installed (e.g. after a hand-edit), since recovery needs all three.
## Remove
```bash
bd setup cursor --remove
```
This removes the rules file and the Beads-managed hook entries while leaving any
of your own hooks in `.cursor/hooks.json` intact. The shared agent skill
(`.agents/skills/beads`) is removed too — unless the Codex integration is still
installed, in which case it is kept because both integrations use it.

View file

@ -25,7 +25,7 @@ bd setup --list
| `claude` | [Claude Code](/integrations/claude-code) | Claude hooks and `CLAUDE.md` |
| `codex` | [Codex](/integrations/codex) | Beads skill, `AGENTS.md`, and Codex hooks |
| `cody` | [Sourcegraph Cody](/integrations/cody) | `.cody/rules/beads.md` |
| `cursor` | [Cursor](/integrations/cursor) | `.cursor/rules/beads.mdc` |
| `cursor` | [Cursor](/integrations/cursor) | `.cursor/rules/beads.mdc` + `.cursor/hooks.json` |
| `factory` | [Factory.ai Droid](/integrations/factory) | `AGENTS.md` |
| `gemini` | [Gemini CLI](/integrations/gemini) | Gemini hooks and `GEMINI.md` |
| `junie` | [Junie](/integrations/junie) | `.junie/guidelines.md` and MCP config |