Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

feat(hooks): add neutral Cursor and Codex hook extension points (#1097)

Shukan Shah90b19ae0626f
diff --git a/CLAUDE.md b/CLAUDE.md
index 47a805ad..7ddfdeb6 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -582,7 +582,7 @@ unpacked through Chrome's developer mode.
- `cli/beacon/internal/pricing` estimates list-price cost for reports: integer-microdollar math over the gen_ai.usage counts (disjoint input/output/cache read/cache write, a one-hour write subset, reasoning inside output), long-context bands only for a single request, and a strict model-name ladder (exact, canonical via `NormalizeModelName`, dotted version, Bedrock route prefix, then stripping a `[1m]` marker, snapshot date or effort suffix) that leaves a model unpriced rather than guess, including when two entries tie with different prices. Its `catalog.json` is embedded, offline and report-time only (hooks never import it); it is generated from LiteLLM's MIT-licensed `model_prices_and_context_window.json` and records the upstream URL, commit and fetch/generation dates. Regenerate with `cd cli/beacon && go run ./internal/pricing/internal/gen` (resolves LiteLLM's main with `git ls-remote` and fetches that commit; `-src`/`-commit` for a local copy) and review the one-model-per-line diff; the generator never runs in builds or tests. Operators price what the catalog cannot (internal models, new releases, gateway aliases, negotiated rates) in a local overrides file, `<BaseDir>/pricing/overrides.json` (`pricing.DefaultOverridesPath`, user or system mode; `--pricing-file` on `beacon token-usage` and `beacon pricing` names another), schema `beacon.pricing.overrides/v1`, documented in `docs/cli/pricing.mdx`. It is offline and Beacon never writes it: the CLI reads it per run, and the dashboard re-reads it per `/api/tokens` request, read-only, falling back to the catalog with `pricing.overrides.error` when it is invalid (the CLI fails instead). Rates are USD per MTok converted exactly to microdollars; zero, negative, quoted, sub-microdollar, absurd, unknown and duplicate keys are refused with the key named. `Pricer.Lookup` runs the same ladder over the file's names first and a row replaces the catalog row whole (omitted cache rates are unpublished, priced by the usual fallbacks); aliases map a reported name to an exact row or catalog key. Reports record `source` (`override`/`catalog`), `alias`, and the file's path and SHA-256. `beacon pricing show|list|info|validate` (`cli/beacon/cmd/pricing.go`) inspects resolution, the catalog, its provenance and the file.
- When adding a new signal, include stable identifiers/counts/hashes alongside any retained raw content, and route raw fields through redaction, sanitization, truncation, and event-size controls.
- Keep the dashboard read-only. It should inspect local status and JSONL events but must not mutate endpoint configuration or telemetry.
-- A few no-op extension points let a separately distributed build compile in files of its own: `claudeExtraHookGroups` and `claudeSettingsChanged` (`cli/beacon/internal/endpoint/hooks/claude.go`), `version.Edition` (both modules; reported by `beacon version`, `endpoint status --json` and the inventory heartbeat only when it is not `community`), and `updatecheck.PublicReleases` (false turns off the startup notice, `beacon version check` and the self-updater). In this repository they stay unset, and with them unset Beacon must behave exactly as before: `TestInstallClaudeSettingsUnchangedWithoutExtensions` compares the written Claude settings to a golden file. Keep them neutral, with no product logic behind them here, and CI refuses any file built only with an `enterprise` tag. The one exception is `beacon endpoint enforcement enable` (`cli/beacon/cmd/endpoint_enforcement.go`), the public installer for the enterprise edition: on an Apple Silicon Mac connected in system mode, with no user-mode Beacon running for the console user, it asks `<dashboard>/api/cli/enforcement/download` for the enterprise package (`internal/endpoint/edition`), installs it with `selfupdate.Applier.InstallPackage` (the self-updater's steps after discovery, with no version gate; the package must match the checksum, be signed by the Apple team pinned in `edition.AppleTeamID`, pass Gatekeeper and report the version and `enterprise` edition once installed, or it is rolled back), then runs the installed binary's own `enable`. A build that carries enforcement sets `activateEnforcement`, which `enable` runs instead, and adds its other subcommands to `endpointEnforcementCmd`. It contains no enforcement logic, never runs from hooks or in the background, and with `activateEnforcement` unset nothing else changes.
+- A few no-op extension points let a separately distributed build compile in files of its own: `claudeExtraHookGroups` and `claudeSettingsChanged` (`cli/beacon/internal/endpoint/hooks/claude.go`), `cursorExtraHooks` and `cursorHooksChanged` (`cursor.go`; an event the map names with no entries is still stripped of Beacon's, which is how a build stops installing a hook there), `codexExtraHookGroups` and `codexHooksChanged` (`codex.go`), `declaredPlatform` in the hook adapter (`cli/beacon-hooks/cmd/helpers.go`: the `--platform` a hook was invoked with, kept when a Cursor payload on a Claude Code hook switches `platformFlag`), `version.Edition` (both modules; reported by `beacon version`, `endpoint status --json` and the inventory heartbeat only when it is not `community`), and `updatecheck.PublicReleases` (false turns off the startup notice, `beacon version check` and the self-updater). In this repository they stay unset, and with them unset Beacon must behave exactly as before: `TestInstallClaudeSettingsUnchangedWithoutExtensions`, `TestCursorHooksGolden` and `TestCodexHooksGolden` compare what the installer writes (and an uninstall leaves) to golden files, with the points cleared by `withoutHookExtensions` so they hold in a build that fills them. Keep them neutral, with no product logic behind them here, and CI refuses any file built only with an `enterprise` tag. The one exception is `beacon endpoint enforcement enable` (`cli/beacon/cmd/endpoint_enforcement.go`), the public installer for the enterprise edition: on an Apple Silicon Mac connected in system mode, with no user-mode Beacon running for the console user, it asks `<dashboard>/api/cli/enforcement/download` for the enterprise package (`internal/endpoint/edition`), installs it with `selfupdate.Applier.InstallPackage` (the self-updater's steps after discovery, with no version gate; the package must match the checksum, be signed by the Apple team pinned in `edition.AppleTeamID`, pass Gatekeeper and report the version and `enterprise` edition once installed, or it is rolled back), then runs the installed binary's own `enable`. A build that carries enforcement sets `activateEnforcement`, which `enable` runs instead, and adds its other subcommands to `endpointEnforcementCmd`. It contains no enforcement logic, never runs from hooks or in the background, and with `activateEnforcement` unset nothing else changes.
- The local trace history (`~/.beacon/endpoint/history.db`, `cli/beacon/internal/endpoint/dashboard/history_*.go`) is opt-in: only `beacon endpoint traces reindex`, a yes to the first-run prompt, or (later) `beacon mcp setup` creates it, and nothing non-interactive is ever prompted. Once it exists, `list`, `search` and `show` must return exactly what the JSONL scan returns for the same log (`TestHistoryAnswersExactlyLikeTheJSONLScan`), so it stores every event and projects it with the same code. A change to the trace projection bumps `historyDerivationVersion`, which rebuilds derived data from the stored lines. The stored lines keep only the raw keys in `historyRawKeys`, and a test fails if the dashboard reads one that is missing. The line dictionary (`historyLineDictionary`) must never change without a new codec.
- The Asymptote device key has exactly one home, `<BaseDir>/asymptote/vector-secrets.json`, read by Vector's `secret` file backend. Never copy it into `config.json`, `vector.toml`, a service unit, an environment variable, a log line, or a `--json` result. Besides Vector, only the root CLI reads it, into memory, to authenticate the one request `beacon endpoint enforcement enable` makes to the platform (and that a build carrying enforcement makes to turn it on or update it); `HasSecretDestinations` is unchanged because the key is not in `config.json`. `internal/auth` is flow-agnostic (PKCE, loopback callback server with an injected exchange function, browser opener, `PostJSON`); new browser flows reuse it rather than adding a second callback server. `connect` must fail before opening a browser when Vector or a service manager is missing, or when Vector rejects the rendered config, so no key is minted or rotated that cannot be used; enrollment rotates a connected device's key in place, so every local check runs ahead of it; the steps that can only fail after the exchange (storing the key, writing the config and unit, starting the service) are covered by the `asymptote/connect-pending` marker, written as soon as the key arrives and removed only when connect finishes, so status reports an incomplete connect instead of the previous connection. A failed first connect stops and removes any partial forwarder before returning, which keeps a later local-only onboarding choice local.
- Keep the release readiness guidance in `README.md` up to date when install, packaging, collector, or dashboard behavior changes.
diff --git a/cli/beacon-hooks/cmd/helpers.go b/cli/beacon-hooks/cmd/helpers.go
index 1879acc7..a33d1e63 100644
--- a/cli/beacon-hooks/cmd/helpers.go
+++ b/cli/beacon-hooks/cmd/helpers.go
@@ -10,8 +10,16 @@ import (
"github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/logging"
)
+// declaredPlatform is the --platform value this hook was invoked with, which names the runtime
+// whose configuration holds the hook entry. readStdinJSON may then switch platformFlag to the
+// runtime the payload came from: Cursor runs Claude Code's user-level hooks with Cursor payloads,
+// so a hook installed for Claude Code can be handling a Cursor event. Nothing in this build reads
+// it; it is there for a build that needs to know where the entry it is running from lives.
+var declaredPlatform string
+
// readStdinJSON decodes JSON from stdin into a map.
func readStdinJSON() (map[string]interface{}, error) {
+ declaredPlatform = platformFlag
var input map[string]interface{}
err := json.NewDecoder(os.Stdin).Decode(&input)
if err == nil {
diff --git a/cli/beacon-hooks/cmd/helpers_test.go b/cli/beacon-hooks/cmd/helpers_test.go
index ba8ccbae..5c403dfd 100644
--- a/cli/beacon-hooks/cmd/helpers_test.go
+++ b/cli/beacon-hooks/cmd/helpers_test.go
@@ -1,9 +1,44 @@
package cmd
import (
+ "os"
"testing"
)
+// Cursor runs Claude Code's user-level hooks with Cursor payloads. readStdinJSON switches
+// platformFlag to the runtime the payload came from and keeps the one the hook was invoked with.
+func TestReadStdinJSONKeepsTheDeclaredPlatform(t *testing.T) {
+ for _, tc := range []struct {
+ name, payload, detected string
+ }{
+ {"cursor payload on a claude hook", `{"hook_event_name":"beforeSubmitPrompt","conversation_id":"c1","prompt":"hi"}`, "cursor"},
+ {"claude payload on a claude hook", `{"hook_event_name":"UserPromptSubmit","session_id":"s1","prompt":"hi"}`, "claude"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ origPlatform, origDeclared, origStdin := platformFlag, declaredPlatform, os.Stdin
+ t.Cleanup(func() { platformFlag, declaredPlatform, os.Stdin = origPlatform, origDeclared, origStdin })
+ r, w, err := os.Pipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := w.WriteString(tc.payload); err != nil {
+ t.Fatal(err)
+ }
+ _ = w.Close()
+ os.Stdin = r
+ platformFlag = "claude"
+
+ if _, err := readStdinJSON(); err != nil {
+ t.Fatal(err)
+ }
+ _ = r.Close()
+ if platformFlag != tc.detected || declaredPlatform != "claude" {
+ t.Fatalf("platformFlag = %q, declaredPlatform = %q; want %q and %q", platformFlag, declaredPlatform, tc.detected, "claude")
+ }
+ })
+ }
+}
+
func TestResolveSessionID_Cursor(t *testing.T) {
tests := []struct {
name string
diff --git a/cli/beacon/cmd/endpoint_enforcement.go b/cli/beacon/cmd/endpoint_enforcement.go
index 1385f650..38688c44 100644
--- a/cli/beacon/cmd/endpoint_enforcement.go
+++ b/cli/beacon/cmd/endpoint_enforcement.go
@@ -25,11 +25,11 @@ import (
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version"
)
-// `beacon endpoint enforcement enable` turns on policy enforcement for Claude Code. Enforcement is
-// part of Beacon's enterprise edition, not this one, so here enable installs that edition on a Mac
-// connected to its organization in system mode, then runs the installed binary's own enable. A
-// build that carries enforcement sets activateEnforcement, which enable runs instead, and adds its
-// other subcommands to endpointEnforcementCmd.
+// `beacon endpoint enforcement enable` turns on policy enforcement for the agents on this machine.
+// Enforcement is part of Beacon's enterprise edition, not this one, so here enable installs that
+// edition on a Mac connected to its organization in system mode, then runs the installed binary's
+// own enable. A build that carries enforcement sets activateEnforcement, which enable runs instead,
+// and adds its other subcommands to endpointEnforcementCmd.
// activateEnforcement turns enforcement on in a build that carries it. Nil in this repository.
var activateEnforcement func(cmd *cobra.Command, dashboardURL string) error
@@ -49,8 +49,8 @@ var endpointEnforcementOpts struct {
var endpointEnforcementCmd = &cobra.Command{
Use: "enforcement",
- Short: "Policy enforcement for Claude Code (enterprise edition)",
- Long: `Policy enforcement for Claude Code, part of Beacon's enterprise edition.
+ Short: "Policy enforcement for AI coding agents (enterprise edition)",
+ Long: `Policy enforcement for AI coding agents, part of Beacon's enterprise edition.
enable installs the enterprise edition on a Mac that is connected to its organization in system
mode (beacon endpoint connect --system), if the organization has enforcement, and turns it on.`,
diff --git a/cli/beacon/internal/endpoint/hooks/codex.go b/cli/beacon/internal/endpoint/hooks/codex.go
index 1ea1181b..e6c3228d 100644
--- a/cli/beacon/internal/endpoint/hooks/codex.go
+++ b/cli/beacon/internal/endpoint/hooks/codex.go
@@ -62,6 +62,22 @@ func codexStatusFromRuntime(status runtimeStatus) CodexStatus {
}
}
+// Extension points for a build of Beacon that compiles in hook subcommands of its own (see
+// version.Edition). Both are nil in this build, which installs exactly the hooks listed in
+// installCodexHooks.
+var (
+ // codexExtraHookGroups returns further hook groups to install for Codex, keyed by event,
+ // given the command prefix Beacon's own hooks use; a group can carry a matcher. Their
+ // commands carry that prefix, so repair, status and uninstall treat them as Beacon's hooks:
+ // a reinstall removes every group Beacon wrote before writing the current ones, and an
+ // uninstall removes them all.
+ codexExtraHookGroups func(prefix string) map[string][]settingsHookGroup
+
+ // codexHooksChanged runs after Beacon has written its hooks into a Codex hooks.json
+ // (installed true) or taken them out (installed false), as whoever ran the install.
+ codexHooksChanged func(hooksPath string, installed bool) error
+)
+
func installCodexHooks(path, binaryPath, logPath, configPath string) error {
prefix := endpointCommandPrefix("codex", binaryPath, logPath, configPath)
// Hooks supply only what Codex's OTLP export lacks: the OS-user session context, and the turn's
@@ -77,11 +93,35 @@ func installCodexHooks(path, binaryPath, logPath, configPath string) error {
{Type: "command", Command: prefix + " codex-assistant-response", Timeout: 10},
}},
}
- return installSettingsEndpointHooks(path, "codex", endpointHooks)
+ groups := make(map[string][]settingsHookGroup, len(endpointHooks))
+ for event, group := range endpointHooks {
+ groups[event] = []settingsHookGroup{group}
+ }
+ if codexExtraHookGroups != nil {
+ for event, extra := range codexExtraHookGroups(prefix) {
+ groups[event] = append(groups[event], extra...)
+ }
+ }
+ if err := installSettingsEndpointHookGroups(path, "codex", groups); err != nil {
+ return err
+ }
+ if codexHooksChanged != nil {
+ return codexHooksChanged(path, true)
+ }
+ return nil
}
func removeCodexEndpointHooks(path string) (bool, error) {
- return removeSettingsEndpointHooks(path, "codex")
+ removed, err := removeSettingsEndpointHooks(path, "codex")
+ if err != nil {
+ return removed, err
+ }
+ if codexHooksChanged != nil {
+ if err := codexHooksChanged(path, false); err != nil {
+ return removed, err
+ }
+ }
+ return removed, nil
}
func isCodexInstalledAt(path string) bool {
diff --git a/cli/beacon/internal/endpoint/hooks/cursor.go b/cli/beacon/internal/endpoint/hooks/cursor.go
index 589b5881..f371002e 100644
--- a/cli/beacon/internal/endpoint/hooks/cursor.go
+++ b/cli/beacon/internal/endpoint/hooks/cursor.go
@@ -48,10 +48,28 @@ var cursorRuntime = hookRuntime{
displayName: "Cursor",
configPath: cursorHooksJSONPath,
install: installCursorHooksJSON,
- uninstall: removeEndpointHooks,
+ uninstall: removeCursorEndpointHooks,
isInstalled: isCursorInstalledAt,
}
+// Extension points for a build of Beacon that compiles in hook subcommands of its own (see
+// version.Edition). Both are nil in this build, which installs exactly the hooks listed in
+// installCursorHooksJSON.
+var (
+ // cursorExtraHooks returns further hook entries to install for Cursor, keyed by event, given
+ // the command prefix Beacon's own hooks use. Their commands carry that prefix, so repair,
+ // status and uninstall treat them as Beacon's hooks. Every event the map names is stripped of
+ // Beacon's entries like the events Beacon installs, then gets Beacon's own entry, if it has
+ // one, followed by these. An event named with no entries is stripped and left with only the
+ // user's, so a build stops installing a hook by naming its event with none: an event left out
+ // of the map keeps whatever Beacon wrote there until an uninstall.
+ cursorExtraHooks func(prefix string) map[string][]HookRef
+
+ // cursorHooksChanged runs after Beacon has written its hooks into a Cursor hooks.json
+ // (installed true) or taken them out (installed false), as whoever ran the install.
+ cursorHooksChanged func(hooksPath string, installed bool) error
+)
+
func InstallCursor(opts CursorOptions) (CursorStatus, error) {
status, err := installRuntimeHooks(cursorRuntime, RuntimeOptions(opts))
if err != nil {
@@ -103,18 +121,51 @@ func installCursorHooksJSON(path, binaryPath, logPath, configPath string) error
"stop": {Command: commandPrefix + " stop"},
"sessionEnd": {Command: commandPrefix + " session-end"},
}
+ entries := make(map[string][]json.RawMessage, len(endpointHooks))
for hookName, ref := range endpointHooks {
entry, err := json.Marshal(ref)
if err != nil {
return err
}
- hooksFile.hooks[hookName] = mergeEndpointHook(hooksFile.hooks[hookName], entry)
+ entries[hookName] = []json.RawMessage{entry}
+ }
+ if cursorExtraHooks != nil {
+ for hookName, refs := range cursorExtraHooks(commandPrefix) {
+ list := entries[hookName]
+ for _, ref := range refs {
+ entry, err := json.Marshal(ref)
+ if err != nil {
+ return err
+ }
+ list = append(list, entry)
+ }
+ entries[hookName] = list
+ }
+ }
+ for hookName, list := range entries {
+ existing := hooksFile.hooks[hookName]
+ merged := mergeEndpointHooks(existing, list)
+ if len(merged) == 0 {
+ // Only an extension's event can end up empty. Drop it when Beacon's entries were
+ // all it held; an event that was already empty is the user's and stays as it was.
+ if len(existing) > 0 {
+ delete(hooksFile.hooks, hookName)
+ }
+ continue
+ }
+ hooksFile.hooks[hookName] = merged
}
data, err := hooksFile.marshal()
if err != nil {
return err
}
- return os.WriteFile(path, data, 0644)
+ if err := os.WriteFile(path, data, 0644); err != nil {
+ return err
+ }
+ if cursorHooksChanged != nil {
+ return cursorHooksChanged(path, true)
+ }
+ return nil
}
func RenderCursorCloudHooks(opts CursorCloudOptions) (string, error) {
@@ -251,14 +302,28 @@ func isEndpointHookEntry(entry json.RawMessage) bool {
return isEndpointHook(cursorHookCommand(entry))
}
-func mergeEndpointHook(existing []json.RawMessage, ref json.RawMessage) []json.RawMessage {
+// mergeEndpointHooks keeps an event's entries that are not Beacon's, in order, and appends refs.
+func mergeEndpointHooks(existing []json.RawMessage, refs []json.RawMessage) []json.RawMessage {
out := make([]json.RawMessage, 0, len(existing))
for _, item := range existing {
if !isEndpointHookEntry(item) {
out = append(out, item)
}
}
- return append(out, ref)
+ return append(out, refs...)
+}
+
+func removeCursorEndpointHooks(path string) (bool, error) {
+ removed, err := removeEndpointHooks(path)
+ if err != nil {
+ return removed, err
+ }
+ if cursorHooksChanged != nil {
+ if err := cursorHooksChanged(path, false); err != nil {
+ return removed, err
+ }
+ }
+ return removed, nil
}
func removeEndpointHooks(path string) (bool, error) {
diff --git a/cli/beacon/internal/endpoint/hooks/hook_extensions_test.go b/cli/beacon/internal/endpoint/hooks/hook_extensions_test.go
new file mode 100644
index 00000000..48ee0c9f
--- /dev/null
+++ b/cli/beacon/internal/endpoint/hooks/hook_extensions_test.go
@@ -0,0 +1,229 @@
+package hooks
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+type hookFileChange struct {
+ path string
+ installed bool
+}
+
+func TestCursorExtraHooksFollowBeaconHooks(t *testing.T) {
+ withoutHookExtensions(t)
+ var changes []hookFileChange
+ enabled := true
+ cursorExtraHooks = func(prefix string) map[string][]HookRef {
+ if !enabled {
+ // Named with no entries: the events are stripped of Beacon's and get nothing new.
+ return map[string][]HookRef{"beforeSubmitPrompt": nil, "beforeMCPExecution": nil}
+ }
+ return map[string][]HookRef{
+ "beforeSubmitPrompt": {{Command: prefix + " extra-prompt", Timeout: 10}},
+ "beforeMCPExecution": {{Command: prefix + " extra-tool", Timeout: 15}},
+ }
+ }
+ cursorHooksChanged = func(path string, installed bool) error {
+ changes = append(changes, hookFileChange{path, installed})
+ return nil
+ }
+
+ path := filepath.Join(t.TempDir(), "hooks.json")
+ existing := `{"version":1,"hooks":{"beforeSubmitPrompt":[{"command":"echo keep"}],"beforeMCPExecution":[{"command":"echo mine","failClosed":true}]}}`
+ if err := os.WriteFile(path, []byte(existing), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ // Installing twice leaves one copy of each entry: the second install strips the first
+ // install's, extra ones included, before writing them again.
+ for i := 0; i < 2; i++ {
+ if err := installCursorHooksJSON(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ commands := cursorCommands(t, path)
+ prompt := commands["beforeSubmitPrompt"]
+ if len(prompt) != 3 || prompt[0] != "echo keep" || !strings.HasSuffix(prompt[1], " prompt-submit") || !strings.HasSuffix(prompt[2], " extra-prompt") {
+ t.Fatalf("beforeSubmitPrompt = %q, want the user's, Beacon's and the extra entry in that order", prompt)
+ }
+ mcp := commands["beforeMCPExecution"]
+ if len(mcp) != 2 || mcp[0] != "echo mine" || !strings.HasSuffix(mcp[1], " extra-tool") {
+ t.Fatalf("beforeMCPExecution = %q, want the user's entry and the extra one", mcp)
+ }
+ if !strings.Contains(readFile(t, path), `"failClosed": true`) {
+ t.Fatalf("the user's entry lost a field Beacon does not model:\n%s", readFile(t, path))
+ }
+ if !isCursorInstalledAt(path) {
+ t.Fatal("status does not see the installed hooks")
+ }
+
+ // A build that stops installing its hooks names their events with none.
+ enabled = false
+ if err := installCursorHooksJSON(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatal(err)
+ }
+ commands = cursorCommands(t, path)
+ if prompt := commands["beforeSubmitPrompt"]; len(prompt) != 2 || !strings.HasSuffix(prompt[1], " prompt-submit") {
+ t.Fatalf("beforeSubmitPrompt after the extension dropped its entry = %q", prompt)
+ }
+ if mcp := commands["beforeMCPExecution"]; !reflect.DeepEqual(mcp, []string{"echo mine"}) {
+ t.Fatalf("beforeMCPExecution after the extension dropped its entry = %q", mcp)
+ }
+
+ // An event that held only Beacon's entries goes away with them.
+ enabled = true
+ if err := os.WriteFile(path, []byte(`{"version":1,"hooks":{}}`), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := installCursorHooksJSON(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatal(err)
+ }
+ enabled = false
+ if err := installCursorHooksJSON(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := cursorCommands(t, path)["beforeMCPExecution"]; ok {
+ t.Fatalf("an event left with nothing was kept:\n%s", readFile(t, path))
+ }
+
+ enabled = true
+ if err := installCursorHooksJSON(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := removeCursorEndpointHooks(path); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatalf("uninstall left a file holding only Beacon's hooks behind: %v", err)
+ }
+
+ want := []hookFileChange{{path, true}, {path, true}, {path, true}, {path, true}, {path, true}, {path, true}, {path, false}}
+ if !reflect.DeepEqual(changes, want) {
+ t.Fatalf("hooks-changed calls = %+v, want %+v", changes, want)
+ }
+}
+
+func TestCursorHooksChangedErrorIsReturned(t *testing.T) {
+ withoutHookExtensions(t)
+ cursorHooksChanged = func(string, bool) error { return os.ErrPermission }
+ path := filepath.Join(t.TempDir(), "hooks.json")
+ if err := installCursorHooksJSON(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != os.ErrPermission {
+ t.Fatalf("install error = %v, want the callback's", err)
+ }
+ if _, err := removeCursorEndpointHooks(path); err != os.ErrPermission {
+ t.Fatalf("uninstall error = %v, want the callback's", err)
+ }
+}
+
+func TestCodexExtraHookGroupsFollowBeaconHooks(t *testing.T) {
+ withoutHookExtensions(t)
+ var changes []hookFileChange
+ enabled := true
+ codexExtraHookGroups = func(prefix string) map[string][]settingsHookGroup {
+ if !enabled {
+ return nil
+ }
+ return map[string][]settingsHookGroup{
+ "SessionStart": {{Hooks: []settingsHookRef{{Type: "command", Command: prefix + " extra-session", Timeout: 15}}}},
+ "UserPromptSubmit": {{Hooks: []settingsHookRef{{Type: "command", Command: prefix + " extra-prompt", Timeout: 10}}}},
+ "PreToolUse": {{Matcher: "^mcp__.*", Hooks: []settingsHookRef{{Type: "command", Command: prefix + " extra-tool", Timeout: 15}}}},
+ }
+ }
+ codexHooksChanged = func(path string, installed bool) error {
+ changes = append(changes, hookFileChange{path, installed})
+ return nil
+ }
+
+ path := filepath.Join(t.TempDir(), "hooks.json")
+ existing := `{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"echo keep"}]}]}}`
+ if err := os.WriteFile(path, []byte(existing), 0600); err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 2; i++ {
+ if err := installCodexHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ settings, err := readSettingsHooks(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pre := settings.hooks["PreToolUse"]
+ if len(pre) != 2 || pre[0].Hooks[0].Command != "echo keep" || pre[1].Matcher != "^mcp__.*" || !strings.HasSuffix(pre[1].Hooks[0].Command, " extra-tool") || pre[1].Hooks[0].Timeout != 15 {
+ t.Fatalf("PreToolUse groups = %+v, want the user's and the extra one", pre)
+ }
+ start := settings.hooks["SessionStart"]
+ if len(start) != 2 || !strings.HasSuffix(start[0].Hooks[0].Command, " codex-session-context") || !strings.HasSuffix(start[1].Hooks[0].Command, " extra-session") {
+ t.Fatalf("SessionStart groups = %+v, want Beacon's then the extra one", start)
+ }
+ if prompt := settings.hooks["UserPromptSubmit"]; len(prompt) != 1 || !strings.HasSuffix(prompt[0].Hooks[0].Command, " extra-prompt") {
+ t.Fatalf("UserPromptSubmit groups = %+v", prompt)
+ }
+
+ // Without the extra groups a reinstall removes them.
+ enabled = false
+ if err := installCodexHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatal(err)
+ }
+ text := readFile(t, path)
+ if strings.Contains(text, "extra-") || strings.Contains(text, "UserPromptSubmit") {
+ t.Fatalf("a reinstall without the extra groups kept them:\n%s", text)
+ }
+ if !strings.Contains(text, "echo keep") || !strings.Contains(text, "codex-session-context") {
+ t.Fatalf("a reinstall lost the user's or Beacon's own hooks:\n%s", text)
+ }
+
+ enabled = true
+ if err := installCodexHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatal(err)
+ }
+ if !isCodexInstalledAt(path) {
+ t.Fatal("status does not see the installed hooks")
+ }
+ if _, err := removeCodexEndpointHooks(path); err != nil {
+ t.Fatal(err)
+ }
+ text = readFile(t, path)
+ if strings.Contains(text, "beacon-hooks") || !strings.Contains(text, "echo keep") {
+ t.Fatalf("uninstall left Beacon's hooks or removed the user's:\n%s", text)
+ }
+
+ want := []hookFileChange{{path, true}, {path, true}, {path, true}, {path, true}, {path, false}}
+ if !reflect.DeepEqual(changes, want) {
+ t.Fatalf("hooks-changed calls = %+v, want %+v", changes, want)
+ }
+}
+
+func TestCodexHooksChangedErrorIsReturned(t *testing.T) {
+ withoutHookExtensions(t)
+ codexHooksChanged = func(string, bool) error { return os.ErrPermission }
+ path := filepath.Join(t.TempDir(), "hooks.json")
+ if err := installCodexHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != os.ErrPermission {
+ t.Fatalf("install error = %v, want the callback's", err)
+ }
+ if _, err := removeCodexEndpointHooks(path); err != os.ErrPermission {
+ t.Fatalf("uninstall error = %v, want the callback's", err)
+ }
+}
+
+func cursorCommands(t *testing.T, path string) map[string][]string {
+ t.Helper()
+ var parsed struct {
+ Hooks map[string][]HookRef `json:"hooks"`
+ }
+ if err := json.Unmarshal([]byte(readFile(t, path)), &parsed); err != nil {
+ t.Fatal(err)
+ }
+ out := make(map[string][]string, len(parsed.Hooks))
+ for event, refs := range parsed.Hooks {
+ for _, ref := range refs {
+ out[event] = append(out[event], ref.Command)
+ }
+ }
+ return out
+}
diff --git a/cli/beacon/internal/endpoint/hooks/hook_goldens_test.go b/cli/beacon/internal/endpoint/hooks/hook_goldens_test.go
index ba740af7..1cbd2ac0 100644
--- a/cli/beacon/internal/endpoint/hooks/hook_goldens_test.go
+++ b/cli/beacon/internal/endpoint/hooks/hook_goldens_test.go
@@ -14,9 +14,15 @@ import (
func withoutHookExtensions(t *testing.T) {
t.Helper()
claudeGroups, claudeChanged := claudeExtraHookGroups, claudeSettingsChanged
+ cursorExtra, cursorChanged := cursorExtraHooks, cursorHooksChanged
+ codexGroups, codexChanged := codexExtraHookGroups, codexHooksChanged
claudeExtraHookGroups, claudeSettingsChanged = nil, nil
+ cursorExtraHooks, cursorHooksChanged = nil, nil
+ codexExtraHookGroups, codexHooksChanged = nil, nil
t.Cleanup(func() {
claudeExtraHookGroups, claudeSettingsChanged = claudeGroups, claudeChanged
+ cursorExtraHooks, cursorHooksChanged = cursorExtra, cursorChanged
+ codexExtraHookGroups, codexHooksChanged = codexGroups, codexChanged
})
}