Skip to content

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

refactor(hooks): one hook-command recogniser for installer and Cursor dedupe (#1140)

kyle-elliott-asymptotee25f324b42e2
diff --git a/cli/beacon-hooks/cmd/cursor_compat.go b/cli/beacon-hooks/cmd/cursor_compat.go
index c21ed3f0..5837bfe2 100644
--- a/cli/beacon-hooks/cmd/cursor_compat.go
+++ b/cli/beacon-hooks/cmd/cursor_compat.go
@@ -6,6 +6,8 @@ import (
"path/filepath"
"regexp"
"strings"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
)
// cursorUserHooksPath locates the user-level Cursor hooks file, where `beacon endpoint install`
@@ -18,27 +20,6 @@ var cursorUserHooksPath = func() string {
return filepath.Join(home, ".cursor", "hooks.json")
}
-// cursorEventsForCommand names the Cursor hooks.json event(s) Beacon's own installer
-// (installCursorHooksJSON, cli/beacon/internal/endpoint/hooks/cursor.go) wires each telemetry
-// subcommand to. It mirrors that function's base endpointHooks map and nothing else: an
-// enterprise build's cursorExtraHooks can add more events, but never for these subcommands.
-//
-// cursorRecordsThisHook only trusts an entry under one of these events. An entry elsewhere in the
-// file -- a stale one from a hand edit, or one the matcher check below would otherwise take at face
-// value -- cannot claim a subcommand it was never wired to run for.
-//
-// TestCursorEventsForCommandMatchesTheInstaller pins this against the installer's own map.
-var cursorEventsForCommand = map[string][]string{
- "session-start": {"sessionStart"},
- "prompt-submit": {"beforeSubmitPrompt"},
- "pre-tool": {"preToolUse"},
- "agent-thought": {"afterAgentThought"},
- "agent-response": {"afterAgentResponse"},
- "post-tool": {"afterFileEdit", "postToolUse", "postToolUseFailure"},
- "stop": {"stop"},
- "session-end": {"sessionEnd"},
-}
-
// cursorRecordsThisHook reports whether Beacon's own Cursor hooks run command for this payload, so
// that a run of Beacon's Claude Code hook carrying a Cursor payload is a second recording of the
// same event.
@@ -46,8 +27,10 @@ var cursorEventsForCommand = map[string][]string{
// The Cursor IDE runs the hooks in the user-level ~/.claude/settings.json alongside its own
// hooks.json, giving them Cursor payloads. With Beacon installed for both, every session start,
// prompt and stop was written twice, and every tool call that both pre-tool matchers name. The
-// Claude copy steps aside only where, under an event Beacon's installer actually wires that
-// subcommand to, a Beacon Cursor entry's matcher selects the payload's tool. The two installers'
+// Claude copy steps aside only where, under an event Beacon's installer wires that subcommand to
+// (hookcmd.CursorEvents), a Beacon Cursor entry's matcher selects the payload's tool. An entry
+// elsewhere in the file -- a stale one from a hand edit -- cannot claim a subcommand it was never
+// wired to run for. The two installers'
// pre-tool matchers differ (Claude's names Read, Grep and Glob; Cursor's names Shell and MCP), so
// a call only Claude's matcher selects still has the Claude copy as its one recorder and policy
// check. So does any command Beacon's Cursor hooks don't run (subagent events, permission
@@ -55,7 +38,7 @@ var cursorEventsForCommand = map[string][]string{
//
// It is one read of a small file, made only when a Claude Code hook receives a Cursor payload.
func cursorRecordsThisHook(command string, input map[string]interface{}) bool {
- events := cursorEventsForCommand[command]
+ events := hookcmd.CursorEvents[command]
if len(events) == 0 {
return false
}
@@ -79,7 +62,7 @@ func cursorRecordsThisHook(command string, input map[string]interface{}) bool {
tool := getFirstStr(input, "tool_name", "toolName")
for _, event := range events {
for _, entry := range file.Hooks[event] {
- if isBeaconCursorHookCommand(entry.Command, command) && cursorMatcherSelects(entry.Matcher, tool) {
+ if hookcmd.Runs(entry.Command, "cursor", command) && cursorMatcherSelects(entry.Matcher, tool) {
return true
}
}
@@ -105,25 +88,3 @@ func cursorMatcherSelects(matcher, tool string) bool {
}
return pattern.MatchString(tool)
}
-
-// isBeaconCursorHookCommand reports whether line is a beacon-hooks command for Cursor that runs
-// command. Beacon writes `'<dir>/beacon-hooks' --platform cursor [--log ... --config ...] <command>`,
-// and older versions put endpoint settings in front as `VAR=value` words; both end with the command.
-func isBeaconCursorHookCommand(line, command string) bool {
- fields := strings.Fields(line)
- if len(fields) == 0 || strings.Trim(fields[len(fields)-1], `'"`) != command {
- return false
- }
- binary, cursor := false, false
- for i, field := range fields {
- word := strings.Trim(field, `'"`)
- name := strings.TrimSuffix(filepath.Base(strings.ReplaceAll(word, `\`, "/")), ".exe")
- if name == "beacon-hooks" {
- binary = true
- }
- if word == "--platform=cursor" || (word == "--platform" && i+1 < len(fields) && strings.Trim(fields[i+1], `'"`) == "cursor") {
- cursor = true
- }
- }
- return binary && cursor
-}
diff --git a/cli/beacon-hooks/cmd/cursor_compat_test.go b/cli/beacon-hooks/cmd/cursor_compat_test.go
index 952c42b7..653afd98 100644
--- a/cli/beacon-hooks/cmd/cursor_compat_test.go
+++ b/cli/beacon-hooks/cmd/cursor_compat_test.go
@@ -6,7 +6,6 @@ import (
"os"
"path/filepath"
"reflect"
- "sort"
"strings"
"testing"
@@ -302,31 +301,6 @@ func TestDuplicateCursorRunDoesNotAskThePolicyProvider(t *testing.T) {
}
}
-func TestIsBeaconCursorHookCommand(t *testing.T) {
- cases := []struct {
- name string
- line string
- command string
- want bool
- }{
- {"current form", beaconCursorHook("pre-tool"), "pre-tool", true},
- {"older env-prefix form", "BEACON_ENDPOINT_MODE=1 BEACON_ENDPOINT_LOG='/tmp/r.jsonl' '/home/dev/.beacon/endpoint/hooks/beacon-hooks' --platform cursor stop", "stop", true},
- {"windows binary", `'C:\Users\dev\.beacon\endpoint\hooks\beacon-hooks.exe' --platform cursor session-start`, "session-start", true},
- {"equals flag", "/opt/beacon/bin/beacon-hooks --platform=cursor prompt-submit", "prompt-submit", true},
- {"another command", beaconCursorHook("pre-tool"), "post-tool", false},
- {"claude entry", "'/Users/dev/.beacon/endpoint/hooks/beacon-hooks' --platform claude prompt-submit", "prompt-submit", false},
- {"someone else's binary", "/usr/local/bin/audit --platform cursor prompt-submit", "prompt-submit", false},
- {"empty", "", "prompt-submit", false},
- }
- for _, tc := range cases {
- t.Run(tc.name, func(t *testing.T) {
- if got := isBeaconCursorHookCommand(tc.line, tc.command); got != tc.want {
- t.Fatalf("isBeaconCursorHookCommand(%q, %q) = %v, want %v", tc.line, tc.command, got, tc.want)
- }
- })
- }
-}
-
func TestCursorRecordsThisHookToleratesBadFiles(t *testing.T) {
path := filepath.Join(t.TempDir(), "hooks.json")
original := cursorUserHooksPath
@@ -346,34 +320,3 @@ func TestCursorRecordsThisHookToleratesBadFiles(t *testing.T) {
t.Fatal("an unknown command matched")
}
}
-
-// TestCursorEventsForCommandMatchesTheInstaller pins cursorEventsForCommand against
-// installCursorHooksJSON's own endpointHooks map (cli/beacon/internal/endpoint/hooks/cursor.go,
-// read here as cli/beacon/internal/endpoint/hooks/testdata/cursor_hooks_golden.json, which that
-// package's own golden test keeps matching the installer). The two files are different Go
-// modules, so this cannot import the installer directly; cursor.go carries a matching comment
-// pointing back here.
-func TestCursorEventsForCommandMatchesTheInstaller(t *testing.T) {
- want := map[string][]string{
- "session-start": {"sessionStart"},
- "prompt-submit": {"beforeSubmitPrompt"},
- "pre-tool": {"preToolUse"},
- "agent-thought": {"afterAgentThought"},
- "agent-response": {"afterAgentResponse"},
- "post-tool": {"afterFileEdit", "postToolUse", "postToolUseFailure"},
- "stop": {"stop"},
- "session-end": {"sessionEnd"},
- }
- if len(cursorEventsForCommand) != len(want) {
- t.Fatalf("cursorEventsForCommand has %d commands, want %d", len(cursorEventsForCommand), len(want))
- }
- for command, wantEvents := range want {
- gotEvents := append([]string(nil), cursorEventsForCommand[command]...)
- sort.Strings(gotEvents)
- sortedWant := append([]string(nil), wantEvents...)
- sort.Strings(sortedWant)
- if !reflect.DeepEqual(gotEvents, sortedWant) {
- t.Errorf("cursorEventsForCommand[%q] = %v, want %v", command, cursorEventsForCommand[command], wantEvents)
- }
- }
-}
diff --git a/cli/beacon/internal/endpoint/harness/harness.go b/cli/beacon/internal/endpoint/harness/harness.go
index fee150e4..7e9737af 100644
--- a/cli/beacon/internal/endpoint/harness/harness.go
+++ b/cli/beacon/internal/endpoint/harness/harness.go
@@ -18,6 +18,7 @@ import (
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/integrations/cowork"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/hermessession"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/tomledit"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
"gopkg.in/yaml.v3"
)
@@ -637,7 +638,7 @@ func hasBeaconDevinHooks(data []byte, platforms ...string) (bool, error) {
for _, group := range groups {
for _, hook := range group.Hooks {
for _, platform := range platforms {
- if hooks.IsEndpointHookCommand(hook.Command, platform) {
+ if hookcmd.IsEndpointHook(hook.Command, platform) {
return true, nil
}
}
@@ -671,7 +672,7 @@ func hasBeaconWindsurfHooks(data []byte, platform string) (bool, error) {
}
for _, refs := range root.Hooks {
for _, hook := range refs {
- if hooks.IsEndpointHookCommand(hook.Command, platform) {
+ if hookcmd.IsEndpointHook(hook.Command, platform) {
return true, nil
}
}
@@ -708,7 +709,7 @@ func hasBeaconHermesHooks(data []byte) (bool, error) {
}
for _, refs := range root.Hooks {
for _, ref := range refs {
- if hooks.IsEndpointHookCommand(ref.Command, "hermes") {
+ if hookcmd.IsEndpointHook(ref.Command, "hermes") {
return true, nil
}
}
diff --git a/cli/beacon/internal/endpoint/hooks/antigravity.go b/cli/beacon/internal/endpoint/hooks/antigravity.go
index 9f37966f..bbc89784 100644
--- a/cli/beacon/internal/endpoint/hooks/antigravity.go
+++ b/cli/beacon/internal/endpoint/hooks/antigravity.go
@@ -5,6 +5,8 @@ import (
"fmt"
"os"
"path/filepath"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
)
const antigravityBeaconHookName = "beacon-endpoint"
@@ -197,7 +199,7 @@ func hasAntigravityEndpointHook(raw json.RawMessage) bool {
} {
for _, group := range groups {
for _, hook := range group.Hooks {
- if isEndpointHookCommand(hook.Command, "antigravity") {
+ if hookcmd.IsEndpointHook(hook.Command, "antigravity") {
return true
}
}
diff --git a/cli/beacon/internal/endpoint/hooks/command_parse_test.go b/cli/beacon/internal/endpoint/hooks/command_parse_test.go
index 3aa22343..dd30ff81 100644
--- a/cli/beacon/internal/endpoint/hooks/command_parse_test.go
+++ b/cli/beacon/internal/endpoint/hooks/command_parse_test.go
@@ -1,125 +1,11 @@
package hooks
import (
- "reflect"
"strings"
"testing"
-)
-
-// TestCommandFieldsKeepsQuotedPathsWhole is the reason this parser exists.
-//
-// strings.Fields was enough while every path was POSIX. The default Windows install locations are
-// under %ProgramFiles% and a user profile, both of which routinely contain a space, so a quoted path
-// splits into fragments and every token comparison after it is made against half a path.
-func TestCommandFieldsKeepsQuotedPathsWhole(t *testing.T) {
- cases := []struct {
- name string
- command string
- want []string
- }{
- {
- name: "the Windows form",
- command: `"C:\Program Files\Beacon\hooks\beacon-hooks.exe" pre-tool --platform cursor`,
- want: []string{`C:\Program Files\Beacon\hooks\beacon-hooks.exe`, "pre-tool", "--platform", "cursor"},
- },
- {
- name: "the POSIX form, single quotes and an env prefix",
- command: `BEACON_ENDPOINT_MODE=1 BEACON_ENDPOINT_LOG='/var/log/beacon-agent/runtime.jsonl' '/opt/beacon/hooks/beacon-hooks' --platform cursor`,
- want: []string{
- "BEACON_ENDPOINT_MODE=1",
- "BEACON_ENDPOINT_LOG=/var/log/beacon-agent/runtime.jsonl",
- "/opt/beacon/hooks/beacon-hooks",
- "--platform", "cursor",
- },
- },
- {
- // A dropped empty argument would shift every token after it left by one, which is how a
- // value gets read as a flag name.
- name: "an empty quoted value is still an argument",
- command: `beacon-hooks --platform "" --log x`,
- want: []string{"beacon-hooks", "--platform", "", "--log", "x"},
- },
- {
- name: "runs of whitespace and tabs collapse",
- command: "beacon-hooks\t--platform cursor ",
- want: []string{"beacon-hooks", "--platform", "cursor"},
- },
- {
- // A backslash is a path separator here, not an escape. Treating it as one would corrupt
- // every Windows path this parses.
- name: "backslashes survive",
- command: `C:\beacon\beacon-hooks.exe --log C:\logs\runtime.jsonl`,
- want: []string{`C:\beacon\beacon-hooks.exe`, "--log", `C:\logs\runtime.jsonl`},
- },
- {
- // hookCommandQuote writes a single quote inside a value as \' between two quoted runs.
- name: "a single quote escaped the way hookCommandQuote writes it",
- command: `'C:\Users\O'\''Brien\hooks\beacon-hooks.exe' --platform claude`,
- want: []string{`C:\Users\O'Brien\hooks\beacon-hooks.exe`, "--platform", "claude"},
- },
- {
- name: "empty",
- command: " ",
- want: nil,
- },
- }
-
- for _, tc := range cases {
- t.Run(tc.name, func(t *testing.T) {
- if got := commandFields(tc.command); !reflect.DeepEqual(got, tc.want) {
- t.Fatalf("commandFields = %#v, want %#v", got, tc.want)
- }
- })
- }
-}
-
-// TestFlagsFormIsRecognizedAsAnEndpointHook covers the regression that motivated this change.
-//
-// The flags form carries no BEACON_ENDPOINT_MODE=1 prefix and does name a platform, so it fell past
-// both branches of isEndpointHookCommand and reported false. Every runtime's repair would have added
-// a duplicate hook beside the one Beacon had just written, and uninstall would have left it behind --
-// with nothing failing anywhere to say so.
-func TestFlagsFormIsRecognizedAsAnEndpointHook(t *testing.T) {
- command := `"C:\Program Files\Beacon\hooks\beacon-hooks.exe" --platform cursor` +
- ` --log "C:\ProgramData\Beacon\Endpoint\logs\runtime.jsonl"` +
- ` --config "C:\ProgramData\Beacon\Endpoint\config.json"`
-
- if !isEndpointHookCommand(command, "cursor") {
- t.Fatal("the flags form is not recognized as an endpoint hook; repair would duplicate it")
- }
- // Still scoped to its own runtime: matching another platform is the direction that rewrites
- // somebody else's hook.
- if isEndpointHookCommand(command, "vscode") {
- t.Fatal("a cursor hook matched when asked about vscode")
- }
-}
-
-// TestAPlatformNamedWithAnEqualsSignCountsAsNamingOne closes a false positive.
-//
-// The old check asked whether the command contained "--platform " with a trailing space, which missed
-// `--platform=cursor`. A command naming no platform is treated as an any-platform install, so that
-// spelling made a hook match when asked about *every* runtime -- and repair rewrites what it matches.
-//
-// Both halves are asserted, because the fix is only safe if it did not also stop recognizing Beacon's
-// own hooks written that way.
-func TestAPlatformNamedWithAnEqualsSignCountsAsNamingOne(t *testing.T) {
- // No endpoint settings, so this belongs to whoever wrote it -- and must not be claimed for a
- // runtime it does not name. Before the fix, it was claimed for all of them.
- foreign := `/opt/beacon/hooks/beacon-hooks --platform=grok`
- if isEndpointHookCommand(foreign, "cursor") {
- t.Fatal("--platform=grok was claimed when asked about cursor; repair would rewrite it")
- }
- // With endpoint settings it is Beacon's, and the equals spelling must still resolve to the
- // platform it names.
- own := `/opt/beacon/hooks/beacon-hooks --platform=cursor --log=/var/log/beacon-agent/runtime.jsonl`
- if !isEndpointHookCommand(own, "cursor") {
- t.Fatal("an endpoint hook written with --platform=cursor is not matched for cursor")
- }
- if isEndpointHookCommand(own, "vscode") {
- t.Fatal("--platform=cursor matched when asked about vscode")
- }
-}
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
+)
// A profile directory with an apostrophe (C:\Users\O'Brien) puts \' between two quoted runs in every
// path of the command. Read as an unterminated quote, it swallowed --platform, and the hook matched
@@ -128,74 +14,15 @@ func TestAHookUnderAnApostrophePathKeepsItsPlatform(t *testing.T) {
for _, home := range []string{`C:\Users\O'Brien`, `/home/o'brien`} {
command := endpointCommandPrefix("claude", home+`/.beacon/endpoint/hooks/beacon-hooks`,
home+`/.beacon/endpoint/logs/runtime.jsonl`, home+`/.beacon/endpoint/config.json`)
- if !isEndpointHookCommand(command, "claude") {
+ if !hookcmd.IsEndpointHook(command, "claude") {
t.Errorf("%s: not matched for claude", command)
}
- if isEndpointHookCommand(command, "cursor") {
+ if hookcmd.IsEndpointHook(command, "cursor") {
t.Errorf("%s: a claude hook matched when asked about cursor", command)
}
}
}
-func TestAPlatformlessBeaconHookStillMatchesAnyRuntime(t *testing.T) {
- // Written before --platform existed. Repair has to keep finding these or it will leave two.
- if !isEndpointHookCommand(`/opt/beacon/hooks/beacon-hooks pre-tool`, "cursor") {
- t.Fatal("a hook naming no platform should match any runtime")
- }
-}
-
-func TestCommandHasPlatformReadsQuotedAndSeparatedValues(t *testing.T) {
- cases := []struct {
- command string
- platform string
- want bool
- }{
- {`beacon-hooks --platform cursor`, "cursor", true},
- {`beacon-hooks --platform "cursor"`, "cursor", true},
- {`beacon-hooks --platform=cursor`, "cursor", true},
- {`beacon-hooks --platform cursor`, "vscode", false},
- // The path contains a space and the platform follows it. With whitespace splitting the path
- // becomes two tokens; the flag still has to be found after them.
- {`"C:\Program Files\Beacon\beacon-hooks.exe" --platform vscode`, "vscode", true},
- // Nothing to compare against.
- {`beacon-hooks --platform`, "cursor", false},
- {`beacon-hooks`, "cursor", false},
- }
- for _, tc := range cases {
- if got := commandHasPlatform(tc.command, tc.platform); got != tc.want {
- t.Fatalf("commandHasPlatform(%q, %q) = %v, want %v", tc.command, tc.platform, got, tc.want)
- }
- }
-}
-
-func TestCommandCarriesEndpointSettingsRecognizesBothSpellings(t *testing.T) {
- carries := []string{
- `BEACON_ENDPOINT_MODE=1 beacon-hooks --platform cursor`,
- `beacon-hooks --platform cursor --log /var/log/beacon-agent/runtime.jsonl`,
- `beacon-hooks --platform cursor --config /etc/beacon/endpoint/config.json`,
- `beacon-hooks --platform cursor --cli /opt/beacon/bin/beacon`,
- `beacon-hooks --platform cursor --log=/var/log/beacon-agent/runtime.jsonl`,
- }
- for _, command := range carries {
- if !commandCarriesEndpointSettings(command) {
- t.Fatalf("endpoint settings not detected in %q", command)
- }
- }
-
- // A path that merely contains the text of a flag is not that flag. This is what token comparison
- // buys over a substring search, and why the quoted path has to stay whole.
- notCarries := []string{
- `beacon-hooks --platform cursor`,
- `"C:\tools\--log\beacon-hooks.exe" --platform cursor`,
- `beacon-hooks --platform cursor --logfile /tmp/x`,
- }
- for _, command := range notCarries {
- if commandCarriesEndpointSettings(command) {
- t.Fatalf("endpoint settings falsely detected in %q", command)
- }
- }
-}
-
// The two builders of a hook invocation must stay in step.
//
// endpointCommandPrefix writes a command line for runtimes that hand a string to a shell;
@@ -222,7 +49,7 @@ func TestEndpointCommandArgsMatchPrefix(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
prefix := endpointCommandPrefix("cline", tc.binaryPath, tc.logPath, tc.configPath)
args := endpointCommandArgs("cline", tc.binaryPath, tc.logPath, tc.configPath)
- tokens := commandFields(prefix)
+ tokens := hookcmd.Fields(prefix)
if len(tokens) != len(args) {
t.Fatalf("prefix tokens %v do not match argv %v", tokens, args)
}
@@ -247,7 +74,7 @@ func TestEndpointCommandBuildersNoLongerEmitCLI(t *testing.T) {
t.Fatal("argv must not carry --cli")
}
}
- if !commandCarriesEndpointSettings("beacon-hooks --platform claude --cli /opt/beacon/bin/beacon session-start") {
+ if !hookcmd.CarriesEndpointSettings("beacon-hooks --platform claude --cli /opt/beacon/bin/beacon session-start") {
t.Fatal("a hook written by an older version, carrying only --cli, must still be recognized")
}
}
diff --git a/cli/beacon/internal/endpoint/hooks/cursor.go b/cli/beacon/internal/endpoint/hooks/cursor.go
index a67498dd..72280601 100644
--- a/cli/beacon/internal/endpoint/hooks/cursor.go
+++ b/cli/beacon/internal/endpoint/hooks/cursor.go
@@ -5,6 +5,8 @@ import (
"fmt"
"os"
"path/filepath"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
)
type Level string
@@ -109,30 +111,24 @@ func installCursorHooksJSON(path, binaryPath, logPath, configPath string) error
return err
}
commandPrefix := endpointCommandPrefix("cursor", binaryPath, logPath, configPath)
- // Keep this event-to-subcommand wiring in step with cursorEventsForCommand in
- // cli/beacon-hooks/cmd/cursor_compat.go: it decides, from the subcommand alone, which Cursor
- // event a Claude Code hook running the same subcommand may trust Beacon's own Cursor entry to
- // also be covering, and a mismatch either suppresses an event this map no longer records or
- // keeps recording one it does.
- endpointHooks := map[string]HookRef{
- "sessionStart": {Command: commandPrefix + " session-start"},
- "beforeSubmitPrompt": {Command: commandPrefix + " prompt-submit", Timeout: 30},
- "preToolUse": {Command: commandPrefix + " pre-tool", Matcher: "Write|Edit|MultiEdit|Shell|MCP"},
- "afterAgentThought": {Command: commandPrefix + " agent-thought"},
- "afterAgentResponse": {Command: commandPrefix + " agent-response"},
- "afterFileEdit": {Command: commandPrefix + " post-tool"},
- "postToolUse": {Command: commandPrefix + " post-tool"},
- "postToolUseFailure": {Command: commandPrefix + " post-tool"},
- "stop": {Command: commandPrefix + " stop"},
- "sessionEnd": {Command: commandPrefix + " session-end"},
- }
- entries := make(map[string][]json.RawMessage, len(endpointHooks))
- for hookName, ref := range endpointHooks {
+ // The subcommand-to-event wiring is hookcmd.CursorEvents, which the hooks binary also reads to
+ // decide which Cursor entries a Claude Code hook running the same subcommand may defer to.
+ entries := make(map[string][]json.RawMessage)
+ for subcommand, events := range hookcmd.CursorEvents {
+ ref := HookRef{Command: commandPrefix + " " + subcommand}
+ switch subcommand {
+ case "prompt-submit":
+ ref.Timeout = 30
+ case "pre-tool":
+ ref.Matcher = "Write|Edit|MultiEdit|Shell|MCP"
+ }
entry, err := json.Marshal(ref)
if err != nil {
return err
}
- entries[hookName] = []json.RawMessage{entry}
+ for _, event := range events {
+ entries[event] = []json.RawMessage{entry}
+ }
}
if cursorExtraHooks != nil {
for hookName, refs := range cursorExtraHooks(commandPrefix) {
@@ -372,7 +368,7 @@ func removeEndpointHooks(path string) (bool, error) {
}
func isEndpointHook(command string) bool {
- return isEndpointHookCommand(command, "cursor")
+ return hookcmd.IsEndpointHook(command, "cursor")
}
func isCursorInstalledAt(path string) bool {
diff --git a/cli/beacon/internal/endpoint/hooks/cursor_test.go b/cli/beacon/internal/endpoint/hooks/cursor_test.go
index 634044fe..3e3aa6b9 100644
--- a/cli/beacon/internal/endpoint/hooks/cursor_test.go
+++ b/cli/beacon/internal/endpoint/hooks/cursor_test.go
@@ -2,14 +2,62 @@ package hooks
import (
"encoding/json"
- "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
"os"
"path/filepath"
"reflect"
+ "slices"
"strings"
"testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
)
+// The hooks binary decides which Cursor entries cover a subcommand from hookcmd.CursorEvents and
+// hookcmd.Runs. Read back from what the installer actually writes, every Beacon entry must be one
+// of those pairs and every pair must be written; otherwise the Claude Code copy of an event is
+// dropped with no Cursor hook recording it, or recorded twice.
+func TestInstalledCursorHooksRoundTripThroughCursorEvents(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "hooks.json")
+ if err := installCursorHooksJSON(path, "/opt/beacon hooks/beacon-hooks", "/var/log/beacon/runtime.jsonl", "/etc/beacon/config.json"); err != nil {
+ t.Fatal(err)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var file struct {
+ Hooks map[string][]struct {
+ Command string `json:"command"`
+ } `json:"hooks"`
+ }
+ if err := json.Unmarshal(data, &file); err != nil {
+ t.Fatal(err)
+ }
+ written := map[string][]string{}
+ for event, entries := range file.Hooks {
+ for _, entry := range entries {
+ fields := hookcmd.Fields(entry.Command)
+ subcommand := fields[len(fields)-1]
+ if !hookcmd.Runs(entry.Command, "cursor", subcommand) {
+ t.Fatalf("%s: installed command %q is not recognised as Beacon's", event, entry.Command)
+ }
+ written[subcommand] = append(written[subcommand], event)
+ }
+ }
+ want := map[string][]string{}
+ for subcommand, events := range hookcmd.CursorEvents {
+ want[subcommand] = append([]string(nil), events...)
+ slices.Sort(want[subcommand])
+ }
+ for subcommand := range written {
+ slices.Sort(written[subcommand])
+ }
+ if !reflect.DeepEqual(written, want) {
+ t.Fatalf("installed subcommand->events = %v, want hookcmd.CursorEvents %v", written, want)
+ }
+}
+
func TestInstallCursorHooksJSONPreservesNonBeaconHooks(t *testing.T) {
path := filepath.Join(t.TempDir(), "hooks.json")
existing := `{"version":1,"hooks":{"sessionStart":[{"command":"echo keep"}]}}`
diff --git a/cli/beacon/internal/endpoint/hooks/devin.go b/cli/beacon/internal/endpoint/hooks/devin.go
index 14a33eb6..c402d787 100644
--- a/cli/beacon/internal/endpoint/hooks/devin.go
+++ b/cli/beacon/internal/endpoint/hooks/devin.go
@@ -5,6 +5,8 @@ import (
"fmt"
"os"
"path/filepath"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
)
type DevinOptions struct {
@@ -449,7 +451,7 @@ func isDevinEndpointHookCommand(command string, platforms ...string) bool {
platforms = []string{"devin"}
}
for _, platform := range platforms {
- if isEndpointHookCommand(command, platform) {
+ if hookcmd.IsEndpointHook(command, platform) {
return true
}
}
@@ -457,7 +459,7 @@ func isDevinEndpointHookCommand(command string, platforms ...string) bool {
}
func isWindsurfEndpointHookCommand(command, platform string) bool {
- return isEndpointHookCommand(command, platform)
+ return hookcmd.IsEndpointHook(command, platform)
}
func devinConfigPath(level Level) (string, error) {
diff --git a/cli/beacon/internal/endpoint/hooks/dsh.go b/cli/beacon/internal/endpoint/hooks/dsh.go
index 854e8a9e..b6aaab2f 100644
--- a/cli/beacon/internal/endpoint/hooks/dsh.go
+++ b/cli/beacon/internal/endpoint/hooks/dsh.go
@@ -6,6 +6,8 @@ import (
"os"
"path/filepath"
"strings"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
)
// DeepSeek Harness is the one supported runtime where installing hooks takes two files, because
@@ -399,7 +401,7 @@ func dshHasEndpointHooks(path string) bool {
for _, groups := range file {
for _, group := range groups {
for _, hook := range group.Hooks {
- if isEndpointHookCommand(hook.Command, "dsh") {
+ if hookcmd.IsEndpointHook(hook.Command, "dsh") {
return true
}
}
@@ -425,7 +427,7 @@ func dshHookFileIsBeacons(path string) error {
for event, groups := range file {
for _, group := range groups {
for _, hook := range group.Hooks {
- if !isEndpointHookCommand(hook.Command, "dsh") {
+ if !hookcmd.IsEndpointHook(hook.Command, "dsh") {
return fmt.Errorf(
"%s already defines a %s hook Beacon did not write (%q); Beacon owns that "+
"filename, so it will not overwrite it. Point the bridge at your own "+
diff --git a/cli/beacon/internal/endpoint/hooks/dsh_test.go b/cli/beacon/internal/endpoint/hooks/dsh_test.go
index a1caeb90..ec9aafd8 100644
--- a/cli/beacon/internal/endpoint/hooks/dsh_test.go
+++ b/cli/beacon/internal/endpoint/hooks/dsh_test.go
@@ -193,7 +193,7 @@ func TestDshReinstallReplacesTheHooksFileWholesale(t *testing.T) {
// A stale Beacon event from an imagined earlier version.
file["PreCompact"] = []dshHookGroup{{Hooks: []dshHookRef{{
Type: "command",
- // Spelled the way the installer spells one: isEndpointHookCommand recognizes a Beacon
+ // Spelled the way the installer spells one: hookcmd.IsEndpointHook recognizes a Beacon
// command by its binary AND its endpoint settings, so a fixture missing --log and --config
// is not one Beacon would be asked to replace.
Command: "'/opt/beacon/bin/beacon-hooks' --platform dsh --log '/var/log/beacon/runtime.jsonl' --config '/etc/beacon/config.json' pre-compact",
diff --git a/cli/beacon/internal/endpoint/hooks/grok.go b/cli/beacon/internal/endpoint/hooks/grok.go
index 823ba2dc..52939e9c 100644
--- a/cli/beacon/internal/endpoint/hooks/grok.go
+++ b/cli/beacon/internal/endpoint/hooks/grok.go
@@ -6,6 +6,8 @@ import (
"os"
"path/filepath"
"strings"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
)
const (
@@ -142,7 +144,7 @@ func isGrokManagedHookFile(data []byte) bool {
for _, groups := range hooks.Hooks {
for _, group := range groups {
for _, hook := range group.Hooks {
- if isEndpointHookCommand(hook.Command, "grok") {
+ if hookcmd.IsEndpointHook(hook.Command, "grok") {
return true
}
}
diff --git a/cli/beacon/internal/endpoint/hooks/hermes.go b/cli/beacon/internal/endpoint/hooks/hermes.go
index 4e36b788..6eb1331f 100644
--- a/cli/beacon/internal/endpoint/hooks/hermes.go
+++ b/cli/beacon/internal/endpoint/hooks/hermes.go
@@ -8,6 +8,7 @@ import (
"gopkg.in/yaml.v3"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/hermessession"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
)
type HermesOptions struct {
@@ -163,7 +164,7 @@ func writeHermesConfig(path string, config hermesConfig) error {
func mergeHermesEndpointHook(existing []hermesHookRef, ref hermesHookRef) []hermesHookRef {
out := make([]hermesHookRef, 0, len(existing)+1)
for _, item := range existing {
- if !isEndpointHookCommand(item.Command, "hermes") {
+ if !hookcmd.IsEndpointHook(item.Command, "hermes") {
out = append(out, item)
}
}
@@ -182,7 +183,7 @@ func removeHermesEndpointHooks(path string) (bool, error) {
for eventName, refs := range config.hooks {
filtered := refs[:0]
for _, ref := range refs {
- if isEndpointHookCommand(ref.Command, "hermes") {
+ if hookcmd.IsEndpointHook(ref.Command, "hermes") {
changed = true
continue
}
@@ -213,7 +214,7 @@ func isHermesInstalledAt(path string) bool {
}
for _, refs := range config.hooks {
for _, ref := range refs {
- if isEndpointHookCommand(ref.Command, "hermes") {
+ if hookcmd.IsEndpointHook(ref.Command, "hermes") {
return true
}
}
diff --git a/cli/beacon/internal/endpoint/hooks/kimi.go b/cli/beacon/internal/endpoint/hooks/kimi.go
index dc7ddce5..a61a59ab 100644
--- a/cli/beacon/internal/endpoint/hooks/kimi.go
+++ b/cli/beacon/internal/endpoint/hooks/kimi.go
@@ -11,6 +11,7 @@ import (
"github.com/pelletier/go-toml/v2"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/tomledit"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
)
// Kimi Code is the one supported runtime whose hook registration lives inside a file that also
@@ -233,7 +234,7 @@ func kimiStatusFromRuntime(status runtimeStatus) KimiStatus {
// There is no command-line escape for it, and the alternative -- leaving the path unquoted --
// fails on the far more common space.
//
-// The detection side needs no matching change: commandFields already accepts both quote
+// The detection side needs no matching change: hookcmd.Fields already accepts both quote
// characters, precisely so a command written for either shell can be recognized.
func kimiCommandPrefix(binaryPath, logPath, configPath string) string {
if runtime.GOOS != "windows" {
@@ -390,7 +391,7 @@ func isKimiInstalledAt(path string) bool {
// comment.
func kimiConfigHasEndpointHooks(parsed map[string]interface{}) bool {
for _, entry := range kimiHookEntries(parsed) {
- if isEndpointHookCommand(entry.Command, "kimi") {
+ if hookcmd.IsEndpointHook(entry.Command, "kimi") {
return true
}
}
@@ -502,7 +503,7 @@ func stripKimiHooks(text string) (string, []kimiHookEntry) {
}
block := lines[index:end]
entry := kimiEntryFromBlock(block)
- if !isEndpointHookCommand(entry.Command, "kimi") {
+ if !hookcmd.IsEndpointHook(entry.Command, "kimi") {
kept = append(kept, block...)
keptEntries = append(keptEntries, entry)
index = end - 1
diff --git a/cli/beacon/internal/endpoint/hooks/kimi_test.go b/cli/beacon/internal/endpoint/hooks/kimi_test.go
index c7bce1ef..b8eb7f1d 100644
--- a/cli/beacon/internal/endpoint/hooks/kimi_test.go
+++ b/cli/beacon/internal/endpoint/hooks/kimi_test.go
@@ -8,6 +8,7 @@ import (
"testing"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
"github.com/pelletier/go-toml/v2"
)
@@ -581,11 +582,11 @@ func TestKimiCommandIsRecognizedInBothQuotingForms(t *testing.T) {
"windows": `"C:\Program Files\Beacon\beacon-hooks.exe" --platform kimi --log "C:\ProgramData\Beacon\runtime.jsonl" pre-tool`,
} {
t.Run(name, func(t *testing.T) {
- if !isEndpointHookCommand(command, "kimi") {
- t.Fatalf("isEndpointHookCommand(%q) = false", command)
+ if !hookcmd.IsEndpointHook(command, "kimi") {
+ t.Fatalf("hookcmd.IsEndpointHook(%q) = false", command)
}
// And it must not claim another runtime's hook.
- if isEndpointHookCommand(strings.Replace(command, "--platform kimi", "--platform claude", 1), "kimi") {
+ if hookcmd.IsEndpointHook(strings.Replace(command, "--platform kimi", "--platform claude", 1), "kimi") {
t.Fatal("a Claude Code hook was claimed as Kimi Code's")
}
})
diff --git a/cli/beacon/internal/endpoint/hooks/kiro.go b/cli/beacon/internal/endpoint/hooks/kiro.go
index 3b122bdf..4372850a 100644
--- a/cli/beacon/internal/endpoint/hooks/kiro.go
+++ b/cli/beacon/internal/endpoint/hooks/kiro.go
@@ -6,6 +6,8 @@ import (
"os"
"path/filepath"
"strings"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
)
// Kiro registers hooks as standalone JSON files in a directory it scans -- `.kiro/hooks/` in a
@@ -260,7 +262,7 @@ func kiroHookFileIsBeacons(path string) error {
return nil
}
for _, hook := range file.Hooks {
- if !isEndpointHookCommand(hook.Action.Command, "kiro") {
+ if !hookcmd.IsEndpointHook(hook.Action.Command, "kiro") {
return fmt.Errorf(
"%s already defines a hook Beacon did not write (%q); Beacon owns that filename, "+
"so it will not overwrite it. Move that hook to another file in the same "+
@@ -322,7 +324,7 @@ func isKiroInstalledAt(path string) bool {
return false
}
for _, hook := range file.Hooks {
- if isEndpointHookCommand(hook.Action.Command, "kiro") {
+ if hookcmd.IsEndpointHook(hook.Action.Command, "kiro") {
return true
}
}
diff --git a/cli/beacon/internal/endpoint/hooks/muse.go b/cli/beacon/internal/endpoint/hooks/muse.go
index f08e96c5..e64e44b9 100644
--- a/cli/beacon/internal/endpoint/hooks/muse.go
+++ b/cli/beacon/internal/endpoint/hooks/muse.go
@@ -5,6 +5,8 @@ import (
"fmt"
"os"
"path/filepath"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
)
const (
@@ -358,7 +360,7 @@ func isMuseManagedHookFile(data []byte) bool {
for _, groups := range hooks.Hooks {
for _, group := range groups {
for _, hook := range group.Hooks {
- if isEndpointHookCommand(hook.Command, "muse") {
+ if hookcmd.IsEndpointHook(hook.Command, "muse") {
return true
}
}
diff --git a/cli/beacon/internal/endpoint/hooks/openhands.go b/cli/beacon/internal/endpoint/hooks/openhands.go
index ab76a723..0c6f4f6d 100644
--- a/cli/beacon/internal/endpoint/hooks/openhands.go
+++ b/cli/beacon/internal/endpoint/hooks/openhands.go
@@ -7,6 +7,8 @@ import (
"path/filepath"
"sort"
"strings"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
)
// OpenHands registers hooks in one file, `.openhands/hooks.json`, which the runtime reads directly
@@ -359,7 +361,7 @@ func isOpenHandsEndpointHook(raw json.RawMessage) bool {
if err := json.Unmarshal(raw, &ref); err != nil {
return false
}
- return isEndpointHookCommand(ref.Command, "openhands")
+ return hookcmd.IsEndpointHook(ref.Command, "openhands")
}
// removeOpenHandsHooks takes Beacon's hooks back out and leaves the user's in place.
diff --git a/cli/beacon/internal/endpoint/hooks/openhands_test.go b/cli/beacon/internal/endpoint/hooks/openhands_test.go
index 059e8fcb..514d5955 100644
--- a/cli/beacon/internal/endpoint/hooks/openhands_test.go
+++ b/cli/beacon/internal/endpoint/hooks/openhands_test.go
@@ -8,6 +8,7 @@ import (
"testing"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
)
// OpenHands is silent about a hooks.json it does not like: a file that fails validation is dropped
@@ -548,7 +549,7 @@ func openHandsHasCommand(commands []string, want string) bool {
func openHandsHasBeaconCommand(commands []string) bool {
for _, command := range commands {
- if isEndpointHookCommand(command, "openhands") {
+ if hookcmd.IsEndpointHook(command, "openhands") {
return true
}
}
diff --git a/cli/beacon/internal/endpoint/hooks/runtime.go b/cli/beacon/internal/endpoint/hooks/runtime.go
index 7af13b10..83e5bff7 100644
--- a/cli/beacon/internal/endpoint/hooks/runtime.go
+++ b/cli/beacon/internal/endpoint/hooks/runtime.go
@@ -10,6 +10,7 @@ import (
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/embedded"
endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
"gopkg.in/yaml.v3"
)
@@ -175,36 +176,8 @@ func hookCommandQuote(value string) string {
return "'" + strings.ReplaceAll(value, "'", `'\''`) + "'"
}
-// isEndpointHookCommand decides whether a command already in a runtime's config is one Beacon wrote.
-//
-// This is the detection surface for status, repair and uninstall across every runtime, so both
-// directions are costly. A false negative makes repair add a second hook beside the first and leaves
-// uninstall's behind; a false positive rewrites or deletes a hook somebody else installed.
-func isEndpointHookCommand(command, platform string) bool {
- hasPlatform := platform == "" || commandHasPlatform(command, platform)
- namesPlatform := commandNamesPlatform(command)
- hasBeaconBinary := strings.Contains(command, embedded.BinaryStem)
- hasLegacyBinary := strings.Contains(command, "asym-hooks")
-
- if commandCarriesEndpointSettings(command) && hasBeaconBinary {
- return hasPlatform || !namesPlatform
- }
- if hasBeaconBinary && !namesPlatform {
- return true
- }
- return hasLegacyBinary && hasPlatform
-}
-
-// IsEndpointHookCommand reports whether command is a hook an endpoint install wrote for platform
-// ("" for any platform). Status, doctor and inventory use it so they recognize exactly the hooks
-// install writes, repairs and removes, in both spellings described at
-// commandCarriesEndpointSettings.
-func IsEndpointHookCommand(command, platform string) bool {
- return isEndpointHookCommand(command, platform)
-}
-
// ConfigHasEndpointHook reports whether a runtime's JSON or YAML hooks config holds a command
-// IsEndpointHookCommand accepts for platform. Every string under a "command" key is checked,
+// hookcmd.IsEndpointHook accepts for platform. Every string under a "command" key is checked,
// wherever the runtime nests it. The error is the document's parse error.
func ConfigHasEndpointHook(data []byte, platform string) (bool, error) {
var doc any
@@ -224,7 +197,7 @@ func hasEndpointCommand(node any, platform string) bool {
switch typed := node.(type) {
case map[string]any:
for key, value := range typed {
- if command, ok := value.(string); ok && key == "command" && isEndpointHookCommand(command, platform) {
+ if command, ok := value.(string); ok && key == "command" && hookcmd.IsEndpointHook(command, platform) {
return true
}
if hasEndpointCommand(value, platform) {
@@ -241,121 +214,6 @@ func hasEndpointCommand(node any, platform string) bool {
return false
}
-// commandCarriesEndpointSettings reports whether a command was written by an endpoint install, as
-// opposed to being some other invocation of the same binary.
-//
-// Two spellings, because the values moved from the environment to flags. An inline
-// `BEACON_ENDPOINT_MODE=1 ...` prefix is a POSIX shell construct that neither Windows shell accepts,
-// so a Windows hook carries `--log`/`--config`/`--cli` instead. Both must be recognized: already
-// installed POSIX hooks use the prefix, and until a repair rewrites them one machine has both.
-//
-// Recognizing only the prefix is what made this worth extracting. A flags-form command matched
-// nothing -- it has no prefix, and it does name a platform, so it fell past both branches above and
-// reported false. Every runtime's repair would have added a duplicate hook next to the one Beacon
-// had just written, and uninstall would have left it in place.
-func commandCarriesEndpointSettings(command string) bool {
- for _, field := range commandFields(command) {
- if field == "BEACON_ENDPOINT_MODE=1" {
- return true
- }
- // --cli is no longer written (inventory comes from the scheduled job, not the hook), but
- // it is still recognized so hooks installed by older versions are repaired and removed.
- for _, name := range []string{"--log", "--config", "--cli"} {
- if field == name || strings.HasPrefix(field, name+"=") {
- return true
- }
- }
- }
- return false
-}
-
-// commandNamesPlatform reports whether a command specifies a platform at all.
-//
-// A command that names none is treated as an any-platform install, which is how hooks written before
-// the flag existed are still recognized. Asked as a token rather than by searching for the substring
-// "--platform " with a trailing space: that spelling missed `--platform=cursor`, so such a hook was
-// treated as platform-less and matched when asked about *any* runtime -- the false-positive direction,
-// where repair rewrites somebody else's hook.
-func commandNamesPlatform(command string) bool {
- for _, field := range commandFields(command) {
- if field == "--platform" || strings.HasPrefix(field, "--platform=") {
- return true
- }
- }
- return false
-}
-
-func commandHasPlatform(command, platform string) bool {
- fields := commandFields(command)
- for i, field := range fields {
- if field == "--platform" {
- return i+1 < len(fields) && fields[i+1] == platform
- }
- if value, found := strings.CutPrefix(field, "--platform="); found {
- return value == platform
- }
- }
- return false
-}
-
-// commandFields splits a hook command into argv-like tokens, keeping quoted runs together.
-//
-// strings.Fields is not enough once paths are Windows paths. The default install location is under
-// %ProgramFiles% or a user profile, both of which routinely contain a space, so a quoted path splits
-// into fragments and any token comparison after it is being made against half a path. Quoting is
-// stripped rather than preserved because callers compare against bare values like "cursor".
-//
-// Both quote characters, because the command may have been written for either shell -- POSIX hooks
-// are single-quoted and Windows ones double-quoted -- and this function only has to recover tokens,
-// not to reproduce a particular shell's semantics. It deliberately does not handle backslash escapes:
-// on Windows a backslash is a path separator, and treating it as an escape would corrupt every path
-// this parses. The one exception is \' outside quotes: hookCommandQuote writes a single quote in a
-// value by closing the quoted run, writing \' and reopening it.
-func commandFields(command string) []string {
- var (
- fields []string
- current strings.Builder
- quote rune
- started bool
- )
- flush := func() {
- if started {
- fields = append(fields, current.String())
- current.Reset()
- started = false
- }
- }
- runes := []rune(command)
- for i := 0; i < len(runes); i++ {
- r := runes[i]
- switch {
- case quote != 0:
- if r == quote {
- quote = 0
- break
- }
- current.WriteRune(r)
- case r == '\\' && i+1 < len(runes) && runes[i+1] == '\'':
- current.WriteRune('\'')
- started = true
- i++
- case r == '"' || r == '\'':
- // Marks the token as started even if the quotes turn out to be empty, so `--platform ""`
- // yields an empty value rather than dropping the argument and shifting every token after
- // it left by one.
- quote = r
- started = true
- case r == ' ' || r == '\t':
- flush()
- default:
- current.WriteRune(r)
- started = true
- }
- }
- flush()
- return fields
-}
-
func writeEndpointHookBinary(userMode bool) (string, error) {
path, err := endpointHookBinaryPath(userMode)
if err != nil {
diff --git a/cli/beacon/internal/endpoint/hooks/scope_test.go b/cli/beacon/internal/endpoint/hooks/scope_test.go
index d4f4f2bf..4101d84e 100644
--- a/cli/beacon/internal/endpoint/hooks/scope_test.go
+++ b/cli/beacon/internal/endpoint/hooks/scope_test.go
@@ -6,6 +6,7 @@ import (
"testing"
endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
)
// A hook writing to a machine-wide log is feeding a system-mode endpoint and must read the system
@@ -80,7 +81,7 @@ func TestHookDetectionRecognizesBothBinarySpellings(t *testing.T) {
`BEACON_ENDPOINT_MODE=1 '/home/u/.beacon/endpoint/hooks/beacon-hooks' --platform cursor`,
`BEACON_ENDPOINT_MODE=1 'C:\Users\u\.beacon\endpoint\hooks\beacon-hooks.exe' --platform cursor`,
} {
- if !isEndpointHookCommand(command, "cursor") {
+ if !hookcmd.IsEndpointHook(command, "cursor") {
t.Errorf("command not recognized as a Beacon hook: %s", command)
}
}
@@ -90,7 +91,7 @@ func TestHookDetectionRecognizesBothBinarySpellings(t *testing.T) {
`echo keep`,
`/usr/local/bin/some-other-tool --platform cursor`,
} {
- if isEndpointHookCommand(command, "cursor") {
+ if hookcmd.IsEndpointHook(command, "cursor") {
t.Errorf("unrelated command was claimed as a Beacon hook: %s", command)
}
}
diff --git a/cli/beacon/internal/endpoint/hooks/settings_hooks.go b/cli/beacon/internal/endpoint/hooks/settings_hooks.go
index ad37b211..08360b2d 100644
--- a/cli/beacon/internal/endpoint/hooks/settings_hooks.go
+++ b/cli/beacon/internal/endpoint/hooks/settings_hooks.go
@@ -4,6 +4,8 @@ import (
"bytes"
"encoding/json"
"os"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
)
// settingsHookGroup and settingsHookRef model the shape Beacon writes into a runtime's shared
@@ -308,10 +310,10 @@ func isSettingsEndpointHookGroup(group settingsHookGroup, platform string) bool
}
func isSettingsEndpointHookCommand(command, platform string) bool {
- if platform != "" && !commandHasPlatform(command, platform) {
+ if platform != "" && !hookcmd.HasPlatform(command, platform) {
return false
}
- return isEndpointHookCommand(command, platform)
+ return hookcmd.IsEndpointHook(command, platform)
}
func isSettingsEndpointInstalledAt(path, platform string) bool {
diff --git a/cli/beacon/internal/endpoint/hooks/vscode.go b/cli/beacon/internal/endpoint/hooks/vscode.go
index fbb40322..5197f8f7 100644
--- a/cli/beacon/internal/endpoint/hooks/vscode.go
+++ b/cli/beacon/internal/endpoint/hooks/vscode.go
@@ -5,6 +5,8 @@ import (
"fmt"
"os"
"path/filepath"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/hookcmd"
)
type VSCodeOptions struct {
@@ -111,7 +113,7 @@ func readVSCodeHooks(path string) (vscodeHooksFile, error) {
func mergeVSCodeEndpointHook(existing []vscodeHookRef, ref vscodeHookRef) []vscodeHookRef {
out := make([]vscodeHookRef, 0, len(existing)+1)
for _, item := range existing {
- if !isEndpointHookCommand(item.Command, "vscode") {
+ if !hookcmd.IsEndpointHook(item.Command, "vscode") {
out = append(out, item)
}
}
@@ -130,7 +132,7 @@ func removeVSCodeEndpointHooks(path string) (bool, error) {
for eventName, refs := range hooksFile.Hooks {
filtered := refs[:0]
for _, ref := range refs {
- if isEndpointHookCommand(ref.Command, "vscode") {
+ if hookcmd.IsEndpointHook(ref.Command, "vscode") {
changed = true
continue
}
@@ -162,7 +164,7 @@ func isVSCodeInstalledAt(path string) bool {
}
for _, refs := range hooksFile.Hooks {
for _, ref := range refs {
- if isEndpointHookCommand(ref.Command, "vscode") {
+ if hookcmd.IsEndpointHook(ref.Command, "vscode") {
return true
}
}
diff --git a/pkg/asymptoteobserve/hookcmd/hookcmd.go b/pkg/asymptoteobserve/hookcmd/hookcmd.go
new file mode 100644
index 00000000..6e47ba9e
--- /dev/null
+++ b/pkg/asymptoteobserve/hookcmd/hookcmd.go
@@ -0,0 +1,184 @@
+// Package hookcmd recognises the hook commands Beacon's endpoint install writes into a runtime's
+// config. The installer (cli/beacon) uses it to find its own hooks for status, repair and
+// uninstall; the hooks binary (cli/beacon-hooks) uses it to tell whether Beacon's Cursor hooks
+// already cover an event. Both must agree, which is why it is one package.
+package hookcmd
+
+import "strings"
+
+// Binary stems a Beacon hook command may run: the current binary and the one older versions
+// installed.
+const (
+ BinaryStem = "beacon-hooks"
+ LegacyBinaryStem = "asym-hooks"
+)
+
+// CursorEvents names the Cursor hooks.json event(s) the installer wires each beacon-hooks
+// subcommand to. The installer writes Cursor's hooks from it, and the hooks binary only trusts a
+// Beacon entry for a subcommand under one of these events.
+var CursorEvents = map[string][]string{
+ "session-start": {"sessionStart"},
+ "prompt-submit": {"beforeSubmitPrompt"},
+ "pre-tool": {"preToolUse"},
+ "agent-thought": {"afterAgentThought"},
+ "agent-response": {"afterAgentResponse"},
+ "post-tool": {"afterFileEdit", "postToolUse", "postToolUseFailure"},
+ "stop": {"stop"},
+ "session-end": {"sessionEnd"},
+}
+
+// IsEndpointHook decides whether command is one an endpoint install wrote for platform ("" for
+// any platform).
+//
+// Both directions are costly. A false negative makes repair add a second hook beside the first
+// and leaves uninstall's behind; a false positive rewrites or deletes a hook somebody else
+// installed.
+func IsEndpointHook(command, platform string) bool {
+ fields := Fields(command)
+ hasPlatform := platform == "" || hasPlatform(fields, platform)
+ namesPlatform := namesPlatform(fields)
+ beacon, legacy := binaries(fields)
+
+ if carriesEndpointSettings(fields) && beacon {
+ return hasPlatform || !namesPlatform
+ }
+ if beacon && !namesPlatform {
+ return true
+ }
+ return legacy && hasPlatform
+}
+
+// Runs reports whether command is an endpoint hook that explicitly names platform and runs
+// subcommand, which every Beacon hook command ends with.
+func Runs(command, platform, subcommand string) bool {
+ fields := Fields(command)
+ if len(fields) == 0 || fields[len(fields)-1] != subcommand || !hasPlatform(fields, platform) {
+ return false
+ }
+ return IsEndpointHook(command, platform)
+}
+
+// HasPlatform reports whether command names platform with --platform.
+func HasPlatform(command, platform string) bool {
+ return hasPlatform(Fields(command), platform)
+}
+
+// CarriesEndpointSettings reports whether a command was written by an endpoint install, as
+// opposed to being some other invocation of the same binary.
+//
+// Two spellings, because the values moved from the environment to flags. An inline
+// `BEACON_ENDPOINT_MODE=1 ...` prefix is a POSIX shell construct that neither Windows shell
+// accepts, so a Windows hook carries `--log`/`--config`/`--cli` instead. Both must be recognized:
+// already installed POSIX hooks use the prefix, and until a repair rewrites them one machine has
+// both.
+func CarriesEndpointSettings(command string) bool {
+ return carriesEndpointSettings(Fields(command))
+}
+
+func carriesEndpointSettings(fields []string) bool {
+ for _, field := range fields {
+ if field == "BEACON_ENDPOINT_MODE=1" {
+ return true
+ }
+ // --cli is no longer written (inventory comes from the scheduled job, not the hook), but
+ // it is still recognized so hooks installed by older versions are repaired and removed.
+ for _, name := range []string{"--log", "--config", "--cli"} {
+ if field == name || strings.HasPrefix(field, name+"=") {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+// binaries reports whether any token names the Beacon or legacy hooks binary: its basename, with
+// either path separator, contains the stem (so `beacon-hooks.exe` and a renamed
+// `old-beacon-hooks` both count). Looking at each token's basename rather than searching the
+// whole command keeps a directory named after the binary from passing as the binary itself.
+func binaries(fields []string) (beacon, legacy bool) {
+ for _, field := range fields {
+ name := field[strings.LastIndexAny(field, `/\`)+1:]
+ beacon = beacon || strings.Contains(name, BinaryStem)
+ legacy = legacy || strings.Contains(name, LegacyBinaryStem)
+ }
+ return beacon, legacy
+}
+
+// namesPlatform reports whether a command specifies a platform at all. A command that names none
+// is treated as an any-platform install, which is how hooks written before the flag existed are
+// still recognized. Both `--platform x` and `--platform=x` count.
+func namesPlatform(fields []string) bool {
+ for _, field := range fields {
+ if field == "--platform" || strings.HasPrefix(field, "--platform=") {
+ return true
+ }
+ }
+ return false
+}
+
+func hasPlatform(fields []string, platform string) bool {
+ for i, field := range fields {
+ if field == "--platform" {
+ return i+1 < len(fields) && fields[i+1] == platform
+ }
+ if value, found := strings.CutPrefix(field, "--platform="); found {
+ return value == platform
+ }
+ }
+ return false
+}
+
+// Fields splits a hook command into argv-like tokens, keeping quoted runs together.
+//
+// strings.Fields is not enough once paths contain spaces, as the default Windows install
+// locations under %ProgramFiles% or a user profile routinely do. Quoting is stripped because
+// callers compare against bare values like "cursor".
+//
+// Both quote characters, because the command may have been written for either shell -- POSIX
+// hooks are single-quoted and Windows ones double-quoted. Backslash is not an escape: on Windows
+// it is a path separator. The one exception is \' outside quotes, which is how a single quote in
+// a value is written by closing the quoted run, writing \' and reopening it.
+func Fields(command string) []string {
+ var (
+ fields []string
+ current strings.Builder
+ quote rune
+ started bool
+ )
+ flush := func() {
+ if started {
+ fields = append(fields, current.String())
+ current.Reset()
+ started = false
+ }
+ }
+ runes := []rune(command)
+ for i := 0; i < len(runes); i++ {
+ r := runes[i]
+ switch {
+ case quote != 0:
+ if r == quote {
+ quote = 0
+ break
+ }
+ current.WriteRune(r)
+ case r == '\\' && i+1 < len(runes) && runes[i+1] == '\'':
+ current.WriteRune('\'')
+ started = true
+ i++
+ case r == '"' || r == '\'':
+ // Marks the token as started even if the quotes turn out to be empty, so `--platform ""`
+ // yields an empty value rather than dropping the argument and shifting every token after
+ // it left by one.
+ quote = r
+ started = true
+ case r == ' ' || r == '\t':
+ flush()
+ default:
+ current.WriteRune(r)
+ started = true
+ }
+ }
+ flush()
+ return fields
+}
diff --git a/pkg/asymptoteobserve/hookcmd/hookcmd_test.go b/pkg/asymptoteobserve/hookcmd/hookcmd_test.go
new file mode 100644
index 00000000..cd477c5b
--- /dev/null
+++ b/pkg/asymptoteobserve/hookcmd/hookcmd_test.go
@@ -0,0 +1,179 @@
+package hookcmd
+
+import (
+ "reflect"
+ "testing"
+)
+
+// strings.Fields was enough while every path was POSIX. The default Windows install locations are
+// under %ProgramFiles% and a user profile, both of which routinely contain a space, so a quoted path
+// splits into fragments and every token comparison after it is made against half a path.
+func TestFieldsKeepsQuotedPathsWhole(t *testing.T) {
+ cases := []struct {
+ name string
+ command string
+ want []string
+ }{
+ {
+ name: "the Windows form",
+ command: `"C:\Program Files\Beacon\hooks\beacon-hooks.exe" pre-tool --platform cursor`,
+ want: []string{`C:\Program Files\Beacon\hooks\beacon-hooks.exe`, "pre-tool", "--platform", "cursor"},
+ },
+ {
+ name: "the POSIX form, single quotes and an env prefix",
+ command: `BEACON_ENDPOINT_MODE=1 BEACON_ENDPOINT_LOG='/var/log/beacon-agent/runtime.jsonl' '/opt/beacon/hooks/beacon-hooks' --platform cursor`,
+ want: []string{
+ "BEACON_ENDPOINT_MODE=1",
+ "BEACON_ENDPOINT_LOG=/var/log/beacon-agent/runtime.jsonl",
+ "/opt/beacon/hooks/beacon-hooks",
+ "--platform", "cursor",
+ },
+ },
+ {
+ // A dropped empty argument would shift every token after it left by one, which is how a
+ // value gets read as a flag name.
+ name: "an empty quoted value is still an argument",
+ command: `beacon-hooks --platform "" --log x`,
+ want: []string{"beacon-hooks", "--platform", "", "--log", "x"},
+ },
+ {
+ name: "runs of whitespace and tabs collapse",
+ command: "beacon-hooks\t--platform cursor ",
+ want: []string{"beacon-hooks", "--platform", "cursor"},
+ },
+ {
+ // A backslash is a path separator here, not an escape.
+ name: "backslashes survive",
+ command: `C:\beacon\beacon-hooks.exe --log C:\logs\runtime.jsonl`,
+ want: []string{`C:\beacon\beacon-hooks.exe`, "--log", `C:\logs\runtime.jsonl`},
+ },
+ {
+ // The installer writes a single quote inside a value as \' between two quoted runs.
+ name: "a single quote escaped the way the installer writes it",
+ command: `'C:\Users\O'\''Brien\hooks\beacon-hooks.exe' --platform claude`,
+ want: []string{`C:\Users\O'Brien\hooks\beacon-hooks.exe`, "--platform", "claude"},
+ },
+ {
+ name: "empty",
+ command: " ",
+ want: nil,
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := Fields(tc.command); !reflect.DeepEqual(got, tc.want) {
+ t.Fatalf("Fields = %#v, want %#v", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestIsEndpointHook(t *testing.T) {
+ cases := []struct {
+ name string
+ command string
+ platform string
+ want bool
+ }{
+ // The flags form carries no BEACON_ENDPOINT_MODE=1 prefix and does name a platform. Missing
+ // it would make repair add a duplicate beside the hook Beacon just wrote.
+ {"flags form", `"C:\Program Files\Beacon\hooks\beacon-hooks.exe" --platform cursor --log "C:\ProgramData\Beacon\Endpoint\logs\runtime.jsonl" --config "C:\ProgramData\Beacon\Endpoint\config.json"`, "cursor", true},
+ {"flags form, another runtime", `"C:\Program Files\Beacon\hooks\beacon-hooks.exe" --platform cursor --log "C:\ProgramData\Beacon\Endpoint\logs\runtime.jsonl"`, "vscode", false},
+ // Without endpoint settings it belongs to whoever wrote it, and must not be claimed for a
+ // runtime it does not name.
+ {"equals form, foreign", `/opt/beacon/hooks/beacon-hooks --platform=grok`, "cursor", false},
+ {"equals form, own", `/opt/beacon/hooks/beacon-hooks --platform=cursor --log=/var/log/beacon-agent/runtime.jsonl`, "cursor", true},
+ {"equals form, another runtime", `/opt/beacon/hooks/beacon-hooks --platform=cursor --log=/var/log/beacon-agent/runtime.jsonl`, "vscode", false},
+ // Written before --platform existed. Repair has to keep finding these or it will leave two.
+ {"no platform named", `/opt/beacon/hooks/beacon-hooks pre-tool`, "cursor", true},
+ {"legacy binary", `/opt/asym/asym-hooks --platform cursor pre-tool`, "cursor", true},
+ {"legacy binary, another runtime", `/opt/asym/asym-hooks --platform claude pre-tool`, "cursor", false},
+ // A directory named after the binary is not the binary.
+ {"binary name only in a directory with a space", `'/Users/dev/beacon-hooks backup/audit' --platform cursor --log /tmp/r.jsonl stop`, "cursor", false},
+ {"wrapper without endpoint settings", `/opt/my-wrapper/beacon-hooks --platform cursor stop`, "cursor", false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := IsEndpointHook(tc.command, tc.platform); got != tc.want {
+ t.Fatalf("IsEndpointHook(%q, %q) = %v, want %v", tc.command, tc.platform, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestRuns(t *testing.T) {
+ cases := []struct {
+ name string
+ command string
+ subcommand string
+ want bool
+ }{
+ {"current form", `'/Users/dev/.beacon/endpoint/hooks/beacon-hooks' --platform cursor --log '/Users/dev/.beacon/endpoint/logs/runtime.jsonl' pre-tool`, "pre-tool", true},
+ {"older env-prefix form", `BEACON_ENDPOINT_MODE=1 BEACON_ENDPOINT_LOG='/tmp/r.jsonl' '/home/dev/.beacon/endpoint/hooks/beacon-hooks' --platform cursor stop`, "stop", true},
+ {"windows binary", `'C:\Users\dev\.beacon\endpoint\hooks\beacon-hooks.exe' --platform cursor --log 'C:\Users\dev\.beacon\endpoint\logs\runtime.jsonl' session-start`, "session-start", true},
+ {"equals flag", `/opt/beacon/bin/beacon-hooks --platform=cursor --config=/etc/beacon/config.json prompt-submit`, "prompt-submit", true},
+ {"path with spaces", `'/opt/beacon hooks/beacon-hooks' --platform cursor --log '/var/log/beacon logs/runtime.jsonl' post-tool`, "post-tool", true},
+ {"another subcommand", `'/opt/beacon/beacon-hooks' --platform cursor --log /tmp/r.jsonl pre-tool`, "post-tool", false},
+ {"another platform", `'/opt/beacon/beacon-hooks' --platform claude --log /tmp/r.jsonl prompt-submit`, "prompt-submit", false},
+ // Recognised for repair as an any-platform hook, but it is not a Cursor entry Beacon wrote.
+ {"no platform named", `/opt/beacon/hooks/beacon-hooks --log /tmp/r.jsonl stop`, "stop", false},
+ {"someone else's binary", `/usr/local/bin/audit --platform cursor --log /tmp/r.jsonl prompt-submit`, "prompt-submit", false},
+ {"wrapper without endpoint settings", `/opt/my-wrapper/beacon-hooks --platform cursor stop`, "stop", false},
+ {"binary name only in a directory with a space", `'/Users/dev/beacon-hooks backup/audit' --platform cursor --log /tmp/r.jsonl stop`, "stop", false},
+ {"empty", "", "prompt-submit", false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := Runs(tc.command, "cursor", tc.subcommand); got != tc.want {
+ t.Fatalf("Runs(%q, cursor, %q) = %v, want %v", tc.command, tc.subcommand, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestHasPlatformReadsQuotedAndSeparatedValues(t *testing.T) {
+ cases := []struct {
+ command string
+ platform string
+ want bool
+ }{
+ {`beacon-hooks --platform cursor`, "cursor", true},
+ {`beacon-hooks --platform "cursor"`, "cursor", true},
+ {`beacon-hooks --platform=cursor`, "cursor", true},
+ {`beacon-hooks --platform cursor`, "vscode", false},
+ {`"C:\Program Files\Beacon\beacon-hooks.exe" --platform vscode`, "vscode", true},
+ {`beacon-hooks --platform`, "cursor", false},
+ {`beacon-hooks`, "cursor", false},
+ }
+ for _, tc := range cases {
+ if got := HasPlatform(tc.command, tc.platform); got != tc.want {
+ t.Fatalf("HasPlatform(%q, %q) = %v, want %v", tc.command, tc.platform, got, tc.want)
+ }
+ }
+}
+
+func TestCarriesEndpointSettingsRecognizesBothSpellings(t *testing.T) {
+ carries := []string{
+ `BEACON_ENDPOINT_MODE=1 beacon-hooks --platform cursor`,
+ `beacon-hooks --platform cursor --log /var/log/beacon-agent/runtime.jsonl`,
+ `beacon-hooks --platform cursor --config /etc/beacon/endpoint/config.json`,
+ `beacon-hooks --platform cursor --cli /opt/beacon/bin/beacon`,
+ `beacon-hooks --platform cursor --log=/var/log/beacon-agent/runtime.jsonl`,
+ }
+ for _, command := range carries {
+ if !CarriesEndpointSettings(command) {
+ t.Fatalf("endpoint settings not detected in %q", command)
+ }
+ }
+ // A path that merely contains the text of a flag is not that flag.
+ notCarries := []string{
+ `beacon-hooks --platform cursor`,
+ `"C:\tools\--log\beacon-hooks.exe" --platform cursor`,
+ `beacon-hooks --platform cursor --logfile /tmp/x`,
+ }
+ for _, command := range notCarries {
+ if CarriesEndpointSettings(command) {
+ t.Fatalf("endpoint settings falsely detected in %q", command)
+ }
+ }
+}