beads/cmd/bd/codex_hook.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

149 lines
4.2 KiB
Go

package main
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/spf13/cobra"
)
const (
codexHookSessionStart = "SessionStart"
codexHookPreCompact = "PreCompact"
codexHookPostCompact = "PostCompact"
codexHookUserPromptSubmit = "UserPromptSubmit"
)
var codexHookMarkerDirOverride string
var codexHookExecPrime = func(ctx context.Context, memoriesOnly bool) (string, error) {
if memoriesOnly {
return runBdPrime(ctx, "--memories-only")
}
return runBdPrime(ctx)
}
type codexHookInput struct {
SessionID string `json:"session_id"`
TranscriptPath string `json:"transcript_path"`
CWD string `json:"cwd"`
HookEventName string `json:"hook_event_name"`
Model string `json:"model"`
Trigger string `json:"trigger"`
}
type codexHookResponse struct {
Continue bool `json:"continue,omitempty"`
SystemMessage string `json:"systemMessage,omitempty"`
HookSpecificOutput codexHookSpecificOutput `json:"hookSpecificOutput,omitempty"`
}
type codexHookSpecificOutput struct {
HookEventName string `json:"hookEventName,omitempty"`
AdditionalContext string `json:"additionalContext,omitempty"`
}
var codexHookCmd = &cobra.Command{
Use: "codex-hook <event>",
Hidden: true,
Short: "Run an internal Codex lifecycle hook",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return runCodexHook(cmd.Context(), args[0], os.Stdin, os.Stdout)
},
}
func init() {
rootCmd.AddCommand(codexHookCmd)
}
func runCodexHook(ctx context.Context, event string, stdin io.Reader, stdout io.Writer) error {
var input codexHookInput
if err := json.NewDecoder(stdin).Decode(&input); err != nil && err != io.EOF {
return err
}
if input.HookEventName != "" {
event = input.HookEventName
}
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
switch event {
case codexHookSessionStart:
return codexHookInjectPrime(ctx, stdout, codexHookSessionStart)
case codexHookPreCompact:
return codexHookPreCompactCheck(ctx, stdout)
case codexHookPostCompact:
return codexHookMarkNeedsRefresh(input)
case codexHookUserPromptSubmit:
return codexHookMaybeRefresh(ctx, input, stdout)
default:
return fmt.Errorf("unsupported Codex hook event %q", event)
}
}
func codexHookInjectPrime(ctx context.Context, stdout io.Writer, event string) error {
out, err := codexHookExecPrime(ctx, false)
if err != nil || strings.TrimSpace(out) == "" {
return nil
}
return writeCodexHookAdditionalContext(stdout, event, out)
}
func codexHookPreCompactCheck(ctx context.Context, stdout io.Writer) error {
if _, err := codexHookExecPrime(ctx, true); err != nil {
return writeCodexHookSystemMessage(stdout, fmt.Sprintf("Beads context check failed before compaction: %v", err))
}
return nil
}
func codexHookMarkNeedsRefresh(input codexHookInput) error {
return writeAgentHookMarker(codexHookRefreshMarkerPath(input))
}
func codexHookMaybeRefresh(ctx context.Context, input codexHookInput, stdout io.Writer) error {
path := codexHookRefreshMarkerPath(input)
if _, err := os.Stat(path); err != nil {
return nil
}
out, err := codexHookExecPrime(ctx, false)
if err != nil {
return writeCodexHookSystemMessage(stdout, fmt.Sprintf("Beads context refresh after compaction failed: %v", err))
}
_ = os.Remove(path)
if strings.TrimSpace(out) == "" {
return nil
}
return writeCodexHookAdditionalContext(stdout, codexHookUserPromptSubmit, out)
}
func codexHookRefreshMarkerPath(input codexHookInput) string {
return agentHookMarkerPath(codexHookMarkerBaseDir(), input.SessionID, input.CWD)
}
func codexHookMarkerBaseDir() string {
return agentHookMarkerBaseDir("codex-hooks", codexHookMarkerDirOverride)
}
func writeCodexHookAdditionalContext(stdout io.Writer, event, context string) error {
return json.NewEncoder(stdout).Encode(codexHookResponse{
Continue: true,
HookSpecificOutput: codexHookSpecificOutput{
HookEventName: event,
AdditionalContext: context,
},
})
}
func writeCodexHookSystemMessage(stdout io.Writer, message string) error {
return json.NewEncoder(stdout).Encode(codexHookResponse{
Continue: true,
SystemMessage: message,
})
}