Add proper hook integration
This commit is contained in:
parent
ce242a8796
commit
e69c53d893
15 changed files with 1070 additions and 5 deletions
179
cmd/bd/codex_hook.go
Normal file
179
cmd/bd/codex_hook.go
Normal file
|
|
@ -0,0 +1,179 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"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) {
|
||||
args := []string{"prime"}
|
||||
if memoriesOnly {
|
||||
args = append(args, "--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
|
||||
}
|
||||
|
||||
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 {
|
||||
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
|
||||
}
|
||||
|
||||
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 {
|
||||
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")
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
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,
|
||||
})
|
||||
}
|
||||
126
cmd/bd/codex_hook_test.go
Normal file
126
cmd/bd/codex_hook_test.go
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func stubCodexHookPrime(t *testing.T, fn func(memoriesOnly bool) (string, error)) {
|
||||
t.Helper()
|
||||
orig := codexHookExecPrime
|
||||
codexHookExecPrime = func(_ context.Context, memoriesOnly bool) (string, error) {
|
||||
return fn(memoriesOnly)
|
||||
}
|
||||
t.Cleanup(func() { codexHookExecPrime = orig })
|
||||
}
|
||||
|
||||
func TestCodexHookSessionStartInjectsPrimeContext(t *testing.T) {
|
||||
stubCodexHookPrime(t, func(memoriesOnly bool) (string, error) {
|
||||
if memoriesOnly {
|
||||
t.Fatal("SessionStart should request full prime output")
|
||||
}
|
||||
return "BEADS PRIME\nbd ready --json\n", nil
|
||||
})
|
||||
|
||||
var out bytes.Buffer
|
||||
input := `{"session_id":"s1","cwd":"/repo","hook_event_name":"SessionStart","source":"startup"}`
|
||||
if err := runCodexHook(context.Background(), codexHookSessionStart, strings.NewReader(input), &out); err != nil {
|
||||
t.Fatalf("runCodexHook: %v", err)
|
||||
}
|
||||
|
||||
var got codexHookResponse
|
||||
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
|
||||
t.Fatalf("parse output: %v\n%s", err, out.String())
|
||||
}
|
||||
if got.HookSpecificOutput.HookEventName != codexHookSessionStart {
|
||||
t.Fatalf("hook event = %q", got.HookSpecificOutput.HookEventName)
|
||||
}
|
||||
if !strings.Contains(got.HookSpecificOutput.AdditionalContext, "bd ready --json") {
|
||||
t.Fatalf("expected prime output in additionalContext: %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodexHookPreCompactWarnsWhenMemoriesUnavailable(t *testing.T) {
|
||||
stubCodexHookPrime(t, func(memoriesOnly bool) (string, error) {
|
||||
if !memoriesOnly {
|
||||
t.Fatal("PreCompact should request memories-only prime output")
|
||||
}
|
||||
return "", errors.New("workspace unavailable")
|
||||
})
|
||||
|
||||
var out bytes.Buffer
|
||||
input := `{"session_id":"s1","cwd":"/repo","hook_event_name":"PreCompact","trigger":"manual"}`
|
||||
if err := runCodexHook(context.Background(), codexHookPreCompact, strings.NewReader(input), &out); err != nil {
|
||||
t.Fatalf("runCodexHook: %v", err)
|
||||
}
|
||||
|
||||
var got codexHookResponse
|
||||
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
|
||||
t.Fatalf("parse output: %v\n%s", err, out.String())
|
||||
}
|
||||
if !strings.Contains(got.SystemMessage, "Beads context check failed") {
|
||||
t.Fatalf("expected warning systemMessage, got %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodexHookPostCompactMarksAndUserPromptRefreshesOnce(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
codexHookMarkerDirOverride = dir
|
||||
t.Cleanup(func() { codexHookMarkerDirOverride = "" })
|
||||
|
||||
calls := 0
|
||||
stubCodexHookPrime(t, func(memoriesOnly bool) (string, error) {
|
||||
calls++
|
||||
if memoriesOnly {
|
||||
t.Fatal("UserPromptSubmit refresh should request full prime output")
|
||||
}
|
||||
return "REFRESHED BEADS CONTEXT\n", nil
|
||||
})
|
||||
|
||||
input := codexHookInput{SessionID: "s1", CWD: filepath.Join("repo", "sub"), HookEventName: codexHookPostCompact}
|
||||
postJSON, _ := json.Marshal(input)
|
||||
if err := runCodexHook(context.Background(), codexHookPostCompact, bytes.NewReader(postJSON), ioDiscard{}); err != nil {
|
||||
t.Fatalf("PostCompact hook: %v", err)
|
||||
}
|
||||
marker := codexHookRefreshMarkerPath(input)
|
||||
if _, err := os.Stat(marker); err != nil {
|
||||
t.Fatalf("expected refresh marker: %v", err)
|
||||
}
|
||||
|
||||
input.HookEventName = codexHookUserPromptSubmit
|
||||
promptJSON, _ := json.Marshal(input)
|
||||
var out bytes.Buffer
|
||||
if err := runCodexHook(context.Background(), codexHookUserPromptSubmit, bytes.NewReader(promptJSON), &out); err != nil {
|
||||
t.Fatalf("UserPromptSubmit hook: %v", err)
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Fatalf("prime calls = %d, want 1", calls)
|
||||
}
|
||||
if _, err := os.Stat(marker); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected refresh marker removed, stat err=%v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "REFRESHED BEADS CONTEXT") {
|
||||
t.Fatalf("expected refreshed context, got %s", out.String())
|
||||
}
|
||||
|
||||
out.Reset()
|
||||
if err := runCodexHook(context.Background(), codexHookUserPromptSubmit, bytes.NewReader(promptJSON), &out); err != nil {
|
||||
t.Fatalf("second UserPromptSubmit hook: %v", err)
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Fatalf("refresh should run once, prime calls = %d", calls)
|
||||
}
|
||||
if out.Len() != 0 {
|
||||
t.Fatalf("expected no second refresh output, got %s", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
type ioDiscard struct{}
|
||||
|
||||
func (ioDiscard) Write(p []byte) (int, error) { return len(p), nil }
|
||||
|
|
@ -711,6 +711,7 @@ var rootCmd = &cobra.Command{
|
|||
"bootstrap",
|
||||
"completion",
|
||||
"context", // reads config files directly, does not need DB open
|
||||
"codex-hook",
|
||||
"doctor",
|
||||
"dolt", // bare "bd dolt" shows help only; subcommands handled below
|
||||
"fish",
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ Automatically detects if MCP server is active and adapts output:
|
|||
- MCP mode: Brief workflow reminders (~50 tokens)
|
||||
- CLI mode: Full command reference (~1-2k tokens)
|
||||
|
||||
Designed for Claude Code hooks (SessionStart, PreCompact) to prevent
|
||||
Designed for Claude Code and Codex hooks to prevent
|
||||
agents from forgetting bd workflow after context compaction.
|
||||
|
||||
Config options:
|
||||
|
|
@ -488,7 +488,7 @@ git push # Push to remote
|
|||
context := primeTruncationDirective + `# Beads Workflow Context
|
||||
|
||||
> **Context Recovery**: Run ` + "`bd prime`" + ` after compaction, clear, or new session
|
||||
> Hooks auto-call this in Claude Code when a beads workspace is resolved
|
||||
> Hooks auto-call this in Claude Code and Codex when a beads workspace is resolved
|
||||
|
||||
` + redirectNotice
|
||||
if memories != "" {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package setup
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
|
@ -17,6 +18,8 @@ const (
|
|||
codexEndMarker = "<!-- END " + codexInstructionMarker + " -->"
|
||||
codexInstructionsFile = "AGENTS.md"
|
||||
codexConfigDir = ".codex"
|
||||
codexConfigFile = "config.toml"
|
||||
codexHooksFile = "hooks.json"
|
||||
codexHomeEnvVar = "CODEX_HOME"
|
||||
)
|
||||
|
||||
|
|
@ -25,6 +28,9 @@ var (
|
|||
errCodexInstructionsMissing = errors.New("codex instructions not installed")
|
||||
errCodexInstructionsStale = errors.New("codex instructions are stale")
|
||||
errCodexInstructionsNoMarker = errors.New("codex instructions section missing")
|
||||
errCodexHooksMissing = errors.New("codex hooks not installed")
|
||||
errCodexHooksStale = errors.New("codex hooks are stale")
|
||||
errCodexFeatureMissing = errors.New("codex hooks feature flag not enabled")
|
||||
)
|
||||
|
||||
type codexEnv struct {
|
||||
|
|
@ -80,6 +86,9 @@ func installCodex(env codexEnv, global bool) error {
|
|||
if err := installAgentSkill(codexAgentSkillEnv(env, global)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := installCodexNativeHooks(env, global); err != nil {
|
||||
return err
|
||||
}
|
||||
return installCodexInstructions(env, global)
|
||||
}
|
||||
|
||||
|
|
@ -100,6 +109,9 @@ func checkCodex(env codexEnv, global bool) error {
|
|||
if err := checkAgentSkill(codexAgentSkillEnv(env, global), codexSetupCommand(global)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := checkCodexNativeHooks(env, global); err != nil {
|
||||
return err
|
||||
}
|
||||
return checkCodexInstructions(env, global)
|
||||
}
|
||||
|
||||
|
|
@ -120,6 +132,9 @@ func removeCodex(env codexEnv, global bool) error {
|
|||
if err := removeAgentSkill(codexAgentSkillEnv(env, global)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := removeCodexNativeHooks(env, global); err != nil {
|
||||
return err
|
||||
}
|
||||
return removeCodexInstructions(env, global)
|
||||
}
|
||||
|
||||
|
|
@ -153,6 +168,21 @@ func codexInstructionsPath(env codexEnv, global bool) string {
|
|||
return filepath.Join(env.projectDir, codexInstructionsFile)
|
||||
}
|
||||
|
||||
func codexConfigRoot(env codexEnv, global bool) string {
|
||||
if global {
|
||||
return codexHomeDir(env)
|
||||
}
|
||||
return filepath.Join(env.projectDir, codexConfigDir)
|
||||
}
|
||||
|
||||
func codexConfigPath(env codexEnv, global bool) string {
|
||||
return filepath.Join(codexConfigRoot(env, global), codexConfigFile)
|
||||
}
|
||||
|
||||
func codexHooksPath(env codexEnv, global bool) string {
|
||||
return filepath.Join(codexConfigRoot(env, global), codexHooksFile)
|
||||
}
|
||||
|
||||
func codexAgentSkillEnv(env codexEnv, global bool) agentSkillEnv {
|
||||
return agentSkillEnv{
|
||||
stdout: env.stdout,
|
||||
|
|
@ -300,3 +330,426 @@ func removeCodexManagedSection(content string) (string, bool) {
|
|||
}
|
||||
return content[:start] + content[end:], true
|
||||
}
|
||||
|
||||
func installCodexNativeHooks(env codexEnv, global bool) error {
|
||||
if global {
|
||||
_, _ = fmt.Fprintln(env.stdout, "Installing Codex native hooks globally...")
|
||||
} else {
|
||||
_, _ = fmt.Fprintln(env.stdout, "Installing Codex native hooks for this project...")
|
||||
}
|
||||
if err := installCodexFeatureFlag(env, global); err != nil {
|
||||
return err
|
||||
}
|
||||
if codexBeadsPluginEnabled(env, global) {
|
||||
_, _ = fmt.Fprintln(env.stdout, "✓ Beads Codex plugin detected — hooks are plugin-managed, skipping hooks.json fallback")
|
||||
return nil
|
||||
}
|
||||
if err := installCodexHooksJSON(env, global); err != nil {
|
||||
return err
|
||||
}
|
||||
_, _ = fmt.Fprintln(env.stdout, "✓ Codex native hooks installed")
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkCodexNativeHooks(env codexEnv, global bool) error {
|
||||
if !codexConfigHasHooksFeature(env, global) {
|
||||
_, _ = fmt.Fprintf(env.stdout, "✗ Codex hooks feature flag not enabled: %s\n", codexConfigPath(env, global))
|
||||
_, _ = fmt.Fprintf(env.stdout, " Run: %s\n", codexSetupCommand(global))
|
||||
return errCodexFeatureMissing
|
||||
}
|
||||
if codexBeadsPluginEnabled(env, global) {
|
||||
_, _ = fmt.Fprintln(env.stdout, "✓ Codex native hooks provided by beads plugin (plugin-managed)")
|
||||
return nil
|
||||
}
|
||||
if !codexHooksJSONCurrent(env, global) {
|
||||
_, _ = fmt.Fprintf(env.stdout, "⚠ Codex hooks missing or stale: %s\n", codexHooksPath(env, global))
|
||||
_, _ = fmt.Fprintf(env.stdout, " Run: %s\n", codexSetupCommand(global))
|
||||
return errCodexHooksStale
|
||||
}
|
||||
_, _ = fmt.Fprintf(env.stdout, "✓ Codex native hooks installed: %s\n", codexHooksPath(env, global))
|
||||
return nil
|
||||
}
|
||||
|
||||
func removeCodexNativeHooks(env codexEnv, global bool) error {
|
||||
if err := removeCodexHooksJSON(env, global); err != nil {
|
||||
return err
|
||||
}
|
||||
return removeCodexFeatureFlag(env, global)
|
||||
}
|
||||
|
||||
func installCodexFeatureFlag(env codexEnv, global bool) error {
|
||||
path := codexConfigPath(env, global)
|
||||
if err := env.ensureDir(filepath.Dir(path), 0o755); err != nil {
|
||||
_, _ = fmt.Fprintf(env.stderr, "Error: %v\n", err)
|
||||
return err
|
||||
}
|
||||
current := ""
|
||||
if data, err := env.readFile(path); err == nil {
|
||||
current = string(data)
|
||||
} else if !os.IsNotExist(err) {
|
||||
_, _ = fmt.Fprintf(env.stderr, "Error: read %s: %v\n", path, err)
|
||||
return err
|
||||
}
|
||||
next := upsertCodexHooksFeature(current)
|
||||
if err := env.writeFile(path, []byte(next)); err != nil {
|
||||
_, _ = fmt.Fprintf(env.stderr, "Error: write %s: %v\n", path, err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func removeCodexFeatureFlag(env codexEnv, global bool) error {
|
||||
path := codexConfigPath(env, global)
|
||||
data, err := env.readFile(path)
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
_, _ = fmt.Fprintf(env.stderr, "Error: read %s: %v\n", path, err)
|
||||
return err
|
||||
}
|
||||
next := removeCodexHooksFeature(string(data))
|
||||
if err := env.writeFile(path, []byte(next)); err != nil {
|
||||
_, _ = fmt.Fprintf(env.stderr, "Error: write %s: %v\n", path, err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func codexConfigHasHooksFeature(env codexEnv, global bool) bool {
|
||||
data, err := env.readFile(codexConfigPath(env, global))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return codexHooksFeatureEnabled(string(data))
|
||||
}
|
||||
|
||||
func codexBeadsPluginEnabled(env codexEnv, global bool) bool {
|
||||
paths := []string{codexConfigPath(env, global)}
|
||||
if !global {
|
||||
paths = append(paths, codexConfigPath(env, true))
|
||||
}
|
||||
for _, path := range paths {
|
||||
data, err := env.readFile(path)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if codexConfigEnablesBeadsPlugin(string(data)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func codexConfigEnablesBeadsPlugin(content string) bool {
|
||||
inBeadsPlugin := false
|
||||
for _, line := range strings.Split(content, "\n") {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]") {
|
||||
table := strings.Trim(trimmed, "[]")
|
||||
inBeadsPlugin = strings.HasPrefix(table, "plugins.") && strings.Contains(strings.ToLower(table), "beads")
|
||||
continue
|
||||
}
|
||||
if inBeadsPlugin && codexConfigLineKey(trimmed) == "enabled" {
|
||||
parts := strings.SplitN(trimmed, "=", 2)
|
||||
return len(parts) == 2 && strings.TrimSpace(parts[1]) == "true"
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func installCodexHooksJSON(env codexEnv, global bool) error {
|
||||
path := codexHooksPath(env, global)
|
||||
if err := env.ensureDir(filepath.Dir(path), 0o755); err != nil {
|
||||
_, _ = fmt.Fprintf(env.stderr, "Error: %v\n", err)
|
||||
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, ¤t); err != nil {
|
||||
_, _ = fmt.Fprintf(env.stderr, "Error: parse %s: %v\n", path, err)
|
||||
return err
|
||||
}
|
||||
} else if err != nil && !os.IsNotExist(err) {
|
||||
_, _ = fmt.Fprintf(env.stderr, "Error: read %s: %v\n", path, err)
|
||||
return err
|
||||
}
|
||||
upsertCodexManagedHooks(current)
|
||||
data, err := json.MarshalIndent(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 {
|
||||
_, _ = fmt.Fprintf(env.stderr, "Error: write %s: %v\n", path, err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func removeCodexHooksJSON(env codexEnv, global bool) error {
|
||||
path := codexHooksPath(env, global)
|
||||
data, err := env.readFile(path)
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
_, _ = 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, ¤t); err != nil {
|
||||
_, _ = fmt.Fprintf(env.stderr, "Error: parse %s: %v\n", path, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
removeCodexManagedHooks(current)
|
||||
if len(current) == 0 {
|
||||
if err := env.removeFile(path); err != nil && !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
next, err := json.MarshalIndent(current, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
next = append(next, '\n')
|
||||
return env.writeFile(path, next)
|
||||
}
|
||||
|
||||
func codexHooksJSONCurrent(env codexEnv, global bool) bool {
|
||||
data, err := env.readFile(codexHooksPath(env, global))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
current := map[string]interface{}{}
|
||||
if err := json.Unmarshal(data, ¤t); err != nil {
|
||||
return false
|
||||
}
|
||||
return codexManagedHooksCurrent(current)
|
||||
}
|
||||
|
||||
func upsertCodexHooksFeature(content string) string {
|
||||
lines := strings.Split(content, "\n")
|
||||
inFeatures := false
|
||||
featuresSeen := false
|
||||
flagSeen := false
|
||||
for i, line := range lines {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]") {
|
||||
inFeatures = trimmed == "[features]"
|
||||
if inFeatures {
|
||||
featuresSeen = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
key := codexConfigLineKey(trimmed)
|
||||
if inFeatures && key == "codex_hooks" {
|
||||
lines[i] = ""
|
||||
continue
|
||||
}
|
||||
if inFeatures && key == "hooks" {
|
||||
lines[i] = "hooks = true"
|
||||
flagSeen = true
|
||||
}
|
||||
}
|
||||
if featuresSeen && !flagSeen {
|
||||
out := make([]string, 0, len(lines)+1)
|
||||
inserted := false
|
||||
inFeatures = false
|
||||
for _, line := range lines {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]") {
|
||||
if inFeatures && !inserted {
|
||||
out = append(out, "hooks = true")
|
||||
inserted = true
|
||||
}
|
||||
inFeatures = trimmed == "[features]"
|
||||
}
|
||||
if strings.TrimSpace(line) != "" {
|
||||
out = append(out, line)
|
||||
}
|
||||
}
|
||||
if inFeatures && !inserted {
|
||||
out = append(out, "hooks = true")
|
||||
}
|
||||
lines = out
|
||||
}
|
||||
next := strings.TrimRight(strings.Join(lines, "\n"), "\n")
|
||||
if !featuresSeen {
|
||||
if strings.TrimSpace(next) != "" {
|
||||
next += "\n\n"
|
||||
}
|
||||
next += "[features]\nhooks = true"
|
||||
}
|
||||
return next + "\n"
|
||||
}
|
||||
|
||||
func removeCodexHooksFeature(content string) string {
|
||||
lines := strings.Split(content, "\n")
|
||||
out := make([]string, 0, len(lines))
|
||||
inFeatures := false
|
||||
for _, line := range lines {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]") {
|
||||
inFeatures = trimmed == "[features]"
|
||||
out = append(out, line)
|
||||
continue
|
||||
}
|
||||
key := codexConfigLineKey(trimmed)
|
||||
if inFeatures && (key == "hooks" || key == "codex_hooks") {
|
||||
continue
|
||||
}
|
||||
out = append(out, line)
|
||||
}
|
||||
return strings.TrimRight(strings.Join(out, "\n"), "\n") + "\n"
|
||||
}
|
||||
|
||||
func codexHooksFeatureEnabled(content string) bool {
|
||||
inFeatures := false
|
||||
for _, line := range strings.Split(content, "\n") {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]") {
|
||||
inFeatures = trimmed == "[features]"
|
||||
continue
|
||||
}
|
||||
if inFeatures && codexConfigLineKey(trimmed) == "hooks" {
|
||||
parts := strings.SplitN(trimmed, "=", 2)
|
||||
return len(parts) == 2 && strings.TrimSpace(parts[1]) == "true"
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func codexConfigLineKey(trimmed string) string {
|
||||
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
|
||||
return ""
|
||||
}
|
||||
parts := strings.SplitN(trimmed, "=", 2)
|
||||
if len(parts) != 2 {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(parts[0])
|
||||
}
|
||||
|
||||
func codexManagedHooks() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"SessionStart": []interface{}{codexHookEntry("startup|resume|clear", "bd codex-hook SessionStart", "Loading Beads context")},
|
||||
"PreCompact": []interface{}{codexHookEntry("manual|auto", "bd codex-hook PreCompact", "Checking Beads context")},
|
||||
"PostCompact": []interface{}{codexHookEntry("manual|auto", "bd codex-hook PostCompact", "Scheduling Beads context refresh")},
|
||||
"UserPromptSubmit": []interface{}{codexHookEntry("", "bd codex-hook UserPromptSubmit", "Refreshing Beads context")},
|
||||
}
|
||||
}
|
||||
|
||||
func codexHookEntry(matcher, command, status string) map[string]interface{} {
|
||||
entry := map[string]interface{}{
|
||||
"hooks": []interface{}{
|
||||
map[string]interface{}{
|
||||
"type": "command",
|
||||
"command": command,
|
||||
"statusMessage": status,
|
||||
},
|
||||
},
|
||||
}
|
||||
if matcher != "" {
|
||||
entry["matcher"] = matcher
|
||||
}
|
||||
return entry
|
||||
}
|
||||
|
||||
func upsertCodexManagedHooks(config map[string]interface{}) {
|
||||
hooks, ok := config["hooks"].(map[string]interface{})
|
||||
if !ok {
|
||||
hooks = map[string]interface{}{}
|
||||
config["hooks"] = hooks
|
||||
}
|
||||
for event, entries := range codexManagedHooks() {
|
||||
removeCodexManagedHookEvent(hooks, event)
|
||||
hooks[event] = append(toInterfaceSlice(hooks[event]), entries.([]interface{})...)
|
||||
}
|
||||
}
|
||||
|
||||
func removeCodexManagedHooks(config map[string]interface{}) {
|
||||
hooks, ok := config["hooks"].(map[string]interface{})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
for event := range codexManagedHooks() {
|
||||
removeCodexManagedHookEvent(hooks, event)
|
||||
}
|
||||
if len(hooks) == 0 {
|
||||
delete(config, "hooks")
|
||||
}
|
||||
}
|
||||
|
||||
func codexManagedHooksCurrent(config map[string]interface{}) bool {
|
||||
hooks, ok := config["hooks"].(map[string]interface{})
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
for event, wantEntries := range codexManagedHooks() {
|
||||
want, _ := wantEntries.([]interface{})
|
||||
for _, wantEntry := range want {
|
||||
if !codexHookEntriesContain(toInterfaceSlice(hooks[event]), wantEntry) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func removeCodexManagedHookEvent(hooks map[string]interface{}, event string) {
|
||||
entries := toInterfaceSlice(hooks[event])
|
||||
filtered := entries[:0]
|
||||
for _, entry := range entries {
|
||||
if !codexHookEntryManaged(entry) {
|
||||
filtered = append(filtered, entry)
|
||||
}
|
||||
}
|
||||
if len(filtered) == 0 {
|
||||
delete(hooks, event)
|
||||
} else {
|
||||
hooks[event] = filtered
|
||||
}
|
||||
}
|
||||
|
||||
func codexHookEntriesContain(entries []interface{}, want interface{}) bool {
|
||||
wantJSON, _ := json.Marshal(want)
|
||||
for _, entry := range entries {
|
||||
gotJSON, _ := json.Marshal(entry)
|
||||
if string(gotJSON) == string(wantJSON) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func codexHookEntryManaged(entry interface{}) bool {
|
||||
entryMap, ok := entry.(map[string]interface{})
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
commands := toInterfaceSlice(entryMap["hooks"])
|
||||
for _, command := range commands {
|
||||
commandMap, ok := command.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if commandString, _ := commandMap["command"].(string); strings.HasPrefix(commandString, "bd codex-hook ") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func toInterfaceSlice(value interface{}) []interface{} {
|
||||
switch typed := value.(type) {
|
||||
case []interface{}:
|
||||
return typed
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -80,6 +80,16 @@ func TestInstallCodexCreatesProjectSkillAndInstructions(t *testing.T) {
|
|||
if instructionsPath != filepath.Join(env.projectDir, "AGENTS.md") {
|
||||
t.Fatalf("project instructions path = %s, want root AGENTS.md", instructionsPath)
|
||||
}
|
||||
configData, err := os.ReadFile(codexConfigPath(env, false))
|
||||
if err != nil {
|
||||
t.Fatalf("read Codex config: %v", err)
|
||||
}
|
||||
if !codexHooksFeatureEnabled(string(configData)) {
|
||||
t.Fatalf("expected hooks feature enabled in %s", codexConfigPath(env, false))
|
||||
}
|
||||
if !codexHooksJSONCurrent(env, false) {
|
||||
t.Fatalf("expected managed Codex hooks in %s", codexHooksPath(env, false))
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallCodexGlobalCreatesGlobalSkillAndInstructions(t *testing.T) {
|
||||
|
|
@ -93,6 +103,12 @@ func TestInstallCodexGlobalCreatesGlobalSkillAndInstructions(t *testing.T) {
|
|||
if _, err := os.Stat(codexInstructionsPath(env, true)); err != nil {
|
||||
t.Fatalf("expected global Codex instructions: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(codexConfigPath(env, true)); err != nil {
|
||||
t.Fatalf("expected global Codex config: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(codexHooksPath(env, true)); err != nil {
|
||||
t.Fatalf("expected global Codex hooks: %v", err)
|
||||
}
|
||||
if got, want := codexInstructionsPath(env, true), filepath.Join(env.homeDir, ".codex", "AGENTS.md"); got != want {
|
||||
t.Fatalf("global instructions path = %s, want %s", got, want)
|
||||
}
|
||||
|
|
@ -122,6 +138,12 @@ func TestInstallCodexGlobalRespectsCodexHome(t *testing.T) {
|
|||
if _, err := os.Stat(filepath.Join(codexHome, "AGENTS.md")); err != nil {
|
||||
t.Fatalf("expected CODEX_HOME instructions: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(codexHome, "config.toml")); err != nil {
|
||||
t.Fatalf("expected CODEX_HOME config: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(codexHome, "hooks.json")); err != nil {
|
||||
t.Fatalf("expected CODEX_HOME hooks: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(env.homeDir, ".codex", "AGENTS.md")); !os.IsNotExist(err) {
|
||||
t.Fatal("global setup should not write ~/.codex/AGENTS.md when CODEX_HOME is set")
|
||||
}
|
||||
|
|
@ -170,11 +192,33 @@ func TestCheckCodexMissingPieces(t *testing.T) {
|
|||
t.Fatalf("install skill: %v", err)
|
||||
}
|
||||
err = checkCodex(env, false)
|
||||
if !errors.Is(err, errCodexFeatureMissing) {
|
||||
t.Fatalf("expected errCodexFeatureMissing, got %v", err)
|
||||
}
|
||||
|
||||
if err := installCodexNativeHooks(env, false); err != nil {
|
||||
t.Fatalf("install native hooks: %v", err)
|
||||
}
|
||||
err = checkCodex(env, false)
|
||||
if !errors.Is(err, errCodexInstructionsMissing) {
|
||||
t.Fatalf("expected errCodexInstructionsMissing, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckCodexDetectsStaleHooks(t *testing.T) {
|
||||
env, _, _ := newCodexTestEnv(t)
|
||||
if err := installCodex(env, false); err != nil {
|
||||
t.Fatalf("installCodex returned error: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(codexHooksPath(env, false), []byte(`{"hooks":{"SessionStart":[]}}`), 0o644); err != nil {
|
||||
t.Fatalf("write stale hooks: %v", err)
|
||||
}
|
||||
err := checkCodex(env, false)
|
||||
if !errors.Is(err, errCodexHooksStale) {
|
||||
t.Fatalf("expected errCodexHooksStale, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckCodexDetectsStaleInstructions(t *testing.T) {
|
||||
env, _, _ := newCodexTestEnv(t)
|
||||
if err := installCodex(env, false); err != nil {
|
||||
|
|
@ -214,4 +258,93 @@ func TestRemoveCodexRemovesSkillAndInstructionsSection(t *testing.T) {
|
|||
if strings.Contains(string(data), codexBeginMarker) {
|
||||
t.Fatal("expected managed Codex section removed")
|
||||
}
|
||||
if _, err := os.Stat(codexHooksPath(env, false)); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected managed Codex hooks removed, stat err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodexHooksConfigMergeIsIdempotent(t *testing.T) {
|
||||
env, _, _ := newCodexTestEnv(t)
|
||||
configPath := codexConfigPath(env, false)
|
||||
hooksPath := codexHooksPath(env, false)
|
||||
if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
|
||||
t.Fatalf("mkdir config: %v", err)
|
||||
}
|
||||
seedConfig := "[model]\nname = \"gpt-test\"\n\n[features]\nother = true\n"
|
||||
if err := os.WriteFile(configPath, []byte(seedConfig), 0o644); err != nil {
|
||||
t.Fatalf("write seed config: %v", err)
|
||||
}
|
||||
seedHooks := `{"hooks":{"SessionStart":[{"matcher":"startup","hooks":[{"type":"command","command":"echo keep"}]}]}}`
|
||||
if err := os.WriteFile(hooksPath, []byte(seedHooks), 0o644); err != nil {
|
||||
t.Fatalf("write seed hooks: %v", err)
|
||||
}
|
||||
|
||||
if err := installCodexNativeHooks(env, false); err != nil {
|
||||
t.Fatalf("install hooks first time: %v", err)
|
||||
}
|
||||
firstConfig, _ := os.ReadFile(configPath)
|
||||
firstHooks, _ := os.ReadFile(hooksPath)
|
||||
if err := installCodexNativeHooks(env, false); err != nil {
|
||||
t.Fatalf("install hooks second time: %v", err)
|
||||
}
|
||||
secondConfig, _ := os.ReadFile(configPath)
|
||||
secondHooks, _ := os.ReadFile(hooksPath)
|
||||
if string(firstConfig) != string(secondConfig) {
|
||||
t.Fatal("expected idempotent config merge")
|
||||
}
|
||||
if string(firstHooks) != string(secondHooks) {
|
||||
t.Fatal("expected idempotent hook merge")
|
||||
}
|
||||
if !strings.Contains(string(secondConfig), "other = true") || !strings.Contains(string(secondConfig), "hooks = true") {
|
||||
t.Fatalf("expected existing feature and hooks flag preserved:\n%s", string(secondConfig))
|
||||
}
|
||||
if !strings.Contains(string(secondHooks), "echo keep") || !strings.Contains(string(secondHooks), "bd codex-hook SessionStart") {
|
||||
t.Fatalf("expected existing and managed hooks preserved:\n%s", string(secondHooks))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodexHooksFeatureMigratesDeprecatedKey(t *testing.T) {
|
||||
input := "[features]\ncodex_hooks = true\nother = true\n"
|
||||
|
||||
output := upsertCodexHooksFeature(input)
|
||||
|
||||
if strings.Contains(output, "codex_hooks") {
|
||||
t.Fatalf("expected deprecated codex_hooks key removed:\n%s", output)
|
||||
}
|
||||
if !strings.Contains(output, "hooks = true") {
|
||||
t.Fatalf("expected hooks feature enabled:\n%s", output)
|
||||
}
|
||||
if !strings.Contains(output, "other = true") {
|
||||
t.Fatalf("expected unrelated feature preserved:\n%s", output)
|
||||
}
|
||||
if !codexHooksFeatureEnabled(output) {
|
||||
t.Fatalf("expected migrated config to enable hooks:\n%s", output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallCodexNativeHooksSkipsFallbackWhenPluginEnabled(t *testing.T) {
|
||||
env, stdout, _ := newCodexTestEnv(t)
|
||||
configPath := codexConfigPath(env, false)
|
||||
if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
|
||||
t.Fatalf("mkdir config: %v", err)
|
||||
}
|
||||
seedConfig := "[plugins.\"beads@local\"]\nenabled = true\n"
|
||||
if err := os.WriteFile(configPath, []byte(seedConfig), 0o644); err != nil {
|
||||
t.Fatalf("write seed config: %v", err)
|
||||
}
|
||||
if err := installCodexNativeHooks(env, false); err != nil {
|
||||
t.Fatalf("install native hooks: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(codexHooksPath(env, false)); !os.IsNotExist(err) {
|
||||
t.Fatalf("plugin-managed setup should not write fallback hooks, stat err=%v", err)
|
||||
}
|
||||
if !strings.Contains(stdout.String(), "plugin-managed") {
|
||||
t.Fatalf("expected plugin-managed message, got %s", stdout.String())
|
||||
}
|
||||
if !codexConfigHasHooksFeature(env, false) {
|
||||
t.Fatal("expected hooks feature enabled even when hooks are plugin-managed")
|
||||
}
|
||||
if err := checkCodexNativeHooks(env, false); err != nil {
|
||||
t.Fatalf("plugin-managed check should pass: %v", err)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,16 +41,21 @@ func TestPluginLayoutUsesSharedBeadsRoot(t *testing.T) {
|
|||
|
||||
var codexManifest struct {
|
||||
Skills string `json:"skills"`
|
||||
Hooks string `json:"hooks"`
|
||||
}
|
||||
readJSONFile(t, filepath.Join(root, "plugins", "beads", ".codex-plugin", "plugin.json"), &codexManifest)
|
||||
if codexManifest.Skills != "./skills/" {
|
||||
t.Fatalf("Codex manifest skills path = %q, want ./skills/", codexManifest.Skills)
|
||||
}
|
||||
if codexManifest.Hooks != "./hooks/hooks.json" {
|
||||
t.Fatalf("Codex manifest hooks path = %q, want ./hooks/hooks.json", codexManifest.Hooks)
|
||||
}
|
||||
|
||||
requireRepoFile(t, root, "plugins", "beads", "skills", "beads", "SKILL.md")
|
||||
requireRepoFile(t, root, "plugins", "beads", "skills", "beads", "agents", "openai.yaml")
|
||||
requireRepoFile(t, root, "plugins", "beads", "agents", "task-agent.md")
|
||||
requireRepoFile(t, root, "plugins", "beads", "skills", "beads", "commands", "ready.md")
|
||||
requireRepoFile(t, root, "plugins", "beads", "hooks", "hooks.json")
|
||||
}
|
||||
|
||||
func readJSONFile(t *testing.T, path string, dest interface{}) {
|
||||
|
|
|
|||
74
docs/CODEX_INTEGRATION.md
Normal file
74
docs/CODEX_INTEGRATION.md
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
# Codex Integration
|
||||
|
||||
Beads supports Codex through the shared `beads` skill, `AGENTS.md` guidance, and native Codex lifecycle hooks.
|
||||
|
||||
## Quick Setup
|
||||
|
||||
```bash
|
||||
bd setup codex
|
||||
```
|
||||
|
||||
Project setup writes:
|
||||
|
||||
- `.agents/skills/beads/` for the Beads skill.
|
||||
- `AGENTS.md` with a managed Beads section.
|
||||
- `.codex/config.toml` with `[features].hooks = true`.
|
||||
- `.codex/hooks.json` with the Beads hook fallback.
|
||||
|
||||
Global setup uses `bd setup codex --global` and writes under `$CODEX_HOME` when set, otherwise `~/.codex`.
|
||||
|
||||
## Plugin-Managed Hooks
|
||||
|
||||
The bundled Codex plugin declares `"hooks": "./hooks/hooks.json"` in `plugins/beads/.codex-plugin/plugin.json`. On Codex 0.129.0+, use `/hooks` to inspect or toggle these handlers.
|
||||
|
||||
The plugin and `bd setup codex` fallback install the same lifecycle:
|
||||
|
||||
- `SessionStart` with matcher `startup|resume|clear`: injects full `bd prime` output as developer context.
|
||||
- `PreCompact` with matcher `manual|auto`: checks `bd prime --memories-only` and surfaces a warning if Beads context is unavailable.
|
||||
- `PostCompact` with matcher `manual|auto`: records that the Codex session needs a Beads refresh.
|
||||
- `UserPromptSubmit`: if a refresh marker exists, injects full `bd prime` output once and clears the marker.
|
||||
|
||||
`PreCompact` cannot preserve Beads context by printing text; compact hook plain stdout is ignored by Codex. Beads therefore uses `PostCompact` plus the next `UserPromptSubmit` to recover context after successful manual or automatic compaction.
|
||||
|
||||
Refresh markers are stored in a user cache/temp directory keyed by Codex `session_id` and workspace path. They are not written to tracked files or to the Beads database.
|
||||
|
||||
## Manual Fallback
|
||||
|
||||
If you do not use the plugin, `bd setup codex` manages `.codex/hooks.json` directly. The equivalent manual shape is:
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{
|
||||
"matcher": "startup|resume|clear",
|
||||
"hooks": [{ "type": "command", "command": "bd codex-hook SessionStart" }]
|
||||
}
|
||||
],
|
||||
"PreCompact": [
|
||||
{
|
||||
"matcher": "manual|auto",
|
||||
"hooks": [{ "type": "command", "command": "bd codex-hook PreCompact" }]
|
||||
}
|
||||
],
|
||||
"PostCompact": [
|
||||
{
|
||||
"matcher": "manual|auto",
|
||||
"hooks": [{ "type": "command", "command": "bd codex-hook PostCompact" }]
|
||||
}
|
||||
],
|
||||
"UserPromptSubmit": [
|
||||
{
|
||||
"hooks": [{ "type": "command", "command": "bd codex-hook UserPromptSubmit" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Ensure `config.toml` enables:
|
||||
|
||||
```toml
|
||||
[features]
|
||||
hooks = true
|
||||
```
|
||||
|
|
@ -280,7 +280,7 @@ bd init --quiet
|
|||
bd setup claude # Claude Code - installs SessionStart/PreCompact hooks
|
||||
bd setup cursor # Cursor IDE - creates .cursor/rules/beads.mdc
|
||||
bd setup aider # Aider - creates .aider.conf.yml
|
||||
bd setup codex # Codex CLI - installs Beads skill + AGENTS.md guidance
|
||||
bd setup codex # Codex CLI - installs Beads skill, AGENTS.md guidance, and native hooks
|
||||
bd setup factory # Factory.ai Droid - creates/updates AGENTS.md
|
||||
bd setup mux # Mux - creates/updates AGENTS.md
|
||||
```
|
||||
|
|
@ -288,6 +288,7 @@ bd setup mux # Mux - creates/updates AGENTS.md
|
|||
**How it works:**
|
||||
- `bd init` creates or updates `AGENTS.md` by default unless you use `--skip-agents` or `--stealth`
|
||||
- Editor hooks/rules inject `bd prime` automatically on session start
|
||||
- Codex 0.129.0+ uses native `/hooks`: SessionStart injects `bd prime`, compact hooks mark context stale, and the next prompt after compaction refreshes Beads context once
|
||||
- `bd prime` provides ~1-2k tokens of workflow context
|
||||
- You use `bd` CLI commands directly
|
||||
- Git hooks (installed by `bd init`) auto-sync the database
|
||||
|
|
|
|||
|
|
@ -15,5 +15,5 @@ bd prime # Refresh Beads context
|
|||
### Rules
|
||||
|
||||
- Use `bd` for all task tracking; do not create markdown TODO lists.
|
||||
- Run `bd prime` when Beads context is missing or stale.
|
||||
- Run `bd prime` when Beads context is missing or stale. Codex 0.129.0+ can load Beads context automatically through native hooks; use `/hooks` to inspect or toggle them.
|
||||
- Keep persistent project memory in Beads via `bd remember`; do not create ad hoc memory files.
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@
|
|||
"agent-memory"
|
||||
],
|
||||
"skills": "./skills/",
|
||||
"hooks": "./hooks/hooks.json",
|
||||
"interface": {
|
||||
"displayName": "Beads",
|
||||
"shortDescription": "Project task tracking with bd",
|
||||
|
|
|
|||
|
|
@ -7,8 +7,21 @@ This is the shared Claude/Codex plugin package for Beads. Claude and Codex use s
|
|||
- `.codex-plugin/plugin.json` describes the Codex plugin.
|
||||
- `.claude-plugin/plugin.json` describes the Claude plugin.
|
||||
- `skills/beads/` contains the plugin-owned Beads skill.
|
||||
- `hooks/hooks.json` contains Codex native lifecycle hooks for startup and compaction-aware context refresh.
|
||||
- The Claude marketplace entry lives at `.claude-plugin/marketplace.json`.
|
||||
|
||||
## Codex Hooks
|
||||
|
||||
The Codex plugin exposes native hooks through `.codex-plugin/plugin.json`.
|
||||
With Codex 0.129.0+, `/hooks` shows these lifecycle handlers:
|
||||
|
||||
- `SessionStart` runs `bd codex-hook SessionStart` for `startup|resume|clear` and injects full `bd prime` output.
|
||||
- `PreCompact` runs `bd codex-hook PreCompact` for `manual|auto` and warns if `bd prime --memories-only` cannot run.
|
||||
- `PostCompact` runs `bd codex-hook PostCompact` for `manual|auto` and records a one-shot refresh marker in the user cache/temp directory.
|
||||
- `UserPromptSubmit` runs `bd codex-hook UserPromptSubmit` and, when a refresh marker exists, injects full `bd prime` output once before clearing it.
|
||||
|
||||
If the plugin is not installed, `bd setup codex` writes an equivalent `.codex/hooks.json` fallback and enables `[features].hooks = true`.
|
||||
|
||||
## Local Development
|
||||
|
||||
Claude Code uses `.claude-plugin/marketplace.json`, which points at this shared package root.
|
||||
|
|
|
|||
51
plugins/beads/hooks/hooks.json
Normal file
51
plugins/beads/hooks/hooks.json
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
{
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{
|
||||
"matcher": "startup|resume|clear",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "bd codex-hook SessionStart",
|
||||
"statusMessage": "Loading Beads context"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PreCompact": [
|
||||
{
|
||||
"matcher": "manual|auto",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "bd codex-hook PreCompact",
|
||||
"statusMessage": "Checking Beads context"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PostCompact": [
|
||||
{
|
||||
"matcher": "manual|auto",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "bd codex-hook PostCompact",
|
||||
"statusMessage": "Scheduling Beads context refresh"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"UserPromptSubmit": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "bd codex-hook UserPromptSubmit",
|
||||
"statusMessage": "Refreshing Beads context"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -152,7 +152,7 @@ bd init --quiet
|
|||
bd setup claude # Claude Code - installs SessionStart/PreCompact hooks
|
||||
bd setup cursor # Cursor IDE - creates .cursor/rules/beads.mdc
|
||||
bd setup aider # Aider - creates .aider.conf.yml
|
||||
bd setup codex # Codex CLI - creates/updates AGENTS.md
|
||||
bd setup codex # Codex CLI - installs Beads skill, AGENTS.md guidance, and native hooks
|
||||
bd setup factory # Factory.ai Droid - creates/updates AGENTS.md
|
||||
bd setup mux # Mux - creates/updates AGENTS.md
|
||||
```
|
||||
|
|
@ -160,6 +160,7 @@ bd setup mux # Mux - creates/updates AGENTS.md
|
|||
**How it works:**
|
||||
- `bd init` creates or updates `AGENTS.md` by default unless you use `--skip-agents` or `--stealth`
|
||||
- Editor hooks/rules inject `bd prime` automatically on session start
|
||||
- Codex 0.129.0+ uses native `/hooks` for startup and compaction-aware context refresh
|
||||
- `bd prime` provides ~1-2k tokens of workflow context
|
||||
- You use `bd` CLI commands directly
|
||||
- Git hooks (installed by `bd init`) auto-sync the database
|
||||
|
|
|
|||
27
website/docs/integrations/codex.md
Normal file
27
website/docs/integrations/codex.md
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
---
|
||||
id: codex
|
||||
title: Codex
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Codex Integration
|
||||
|
||||
Use Beads with Codex through the `beads` skill, managed `AGENTS.md` guidance, and native Codex hooks.
|
||||
|
||||
```bash
|
||||
bd setup codex
|
||||
bd setup codex --check
|
||||
```
|
||||
|
||||
Codex 0.129.0+ supports `/hooks`, compact lifecycle hooks, and hook-provided developer context. Beads uses that lifecycle to inject `bd prime` on session start and recover context after compaction.
|
||||
|
||||
## Hook Lifecycle
|
||||
|
||||
- `SessionStart` (`startup|resume|clear`) injects full `bd prime` output.
|
||||
- `PreCompact` (`manual|auto`) checks `bd prime --memories-only` and warns if Beads context is unavailable.
|
||||
- `PostCompact` (`manual|auto`) records that the session needs a Beads refresh.
|
||||
- `UserPromptSubmit` injects full `bd prime` once after compaction, then clears the refresh marker.
|
||||
|
||||
`PreCompact` alone does not inject context because Codex ignores plain stdout from compact hooks. The post-compact marker plus first-prompt refresh is the reliable recovery path.
|
||||
|
||||
The Beads Codex plugin declares `"hooks": "./hooks/hooks.json"`. Without the plugin, `bd setup codex` installs the same hook config in `.codex/hooks.json` and enables `[features].hooks = true`.
|
||||
Loading…
Add table
Add a link
Reference in a new issue