The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
fix(hooks): record each Cursor IDE event once (#1100)
Shukan Shah5c79f3949203
diff --git a/CLAUDE.md b/CLAUDE.mdindex 0cdbf68f..20d4b920 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -45,7 +45,7 @@ Do not recreate or depend on removed `asymptote` mirror trees. Keep new work focSupported runtime surfaces today:- Claude Code and Codex CLI use local OpenTelemetry settings, and `beacon endpoint install` writes their user-level hooks alongside those settings (`otlpTargetCarriesHook` in `cli/beacon/cmd/endpoint_targets.go`), because Claude's OTLP export has no session lifecycle, file activity, or subagent events and Codex's SessionStart hook supplies the OS-user context its spans lack. Both runtimes' Stop hooks record the turn's final reply from `last_assistant_message` as `agent.message` (Codex through the dedicated `codex-assistant-response` command, since its OTLP export carries no response text and it gets no generic hooks). `beacon endpoint codex sync` is the offline poll backfill from `~/.codex/sessions`; it never reads `~/.codex/auth.json` and cannot approve, deny, or delay tool calls.-- Cursor hook telemetry for sessions, prompt submission, tool use, command execution, MCP-like tool activity, approval decisions, file edits, and agent reasoning (`afterAgentThought` thinking text recorded as `agent.reasoning` events in the OTel GenAI `gen_ai.output.messages` reasoning-part shape) where hook payloads expose those fields.+- Cursor hook telemetry for sessions, prompt submission, tool use, command execution, MCP-like tool activity, approval decisions, file edits, and agent reasoning (`afterAgentThought` thinking text recorded as `agent.reasoning` events in the OTel GenAI `gen_ai.output.messages` reasoning-part shape) where hook payloads expose those fields. The Cursor IDE also runs the hooks in the user-level `~/.claude/settings.json`, with Cursor payloads; when Beacon's own `~/.cursor/hooks.json` runs the same hook subcommand and that entry's matcher selects the call's tool, that Claude Code run writes nothing and asks no policy provider (`cursorRecordsThisHook` in `cli/beacon-hooks/cmd/cursor_compat.go`), so each event is recorded once. The two 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, a subcommand Beacon's Cursor hooks don't run, or a machine without them at the user level still gets the Claude Code run's record and policy check.- Cline uses a Beacon-managed plugin (`~/.cline/plugins/beacon.ts`) for live capture plus `beacon endpoint cline sync` for local history backfill. Cline's own OTel export/hosted prompt storage are not used, and approvals are not exposed or synthesized.- Pi-family runtimes use Beacon-managed extensions and the shared `cli/beacon-hooks/cmd/pi_family.go` mapper while keeping separate harness names and install roots: Pi (`pi_cli`), Oh My Pi (`omp`), Prime Agent (`prime_agent`), and Senpi/OMO (`omo_senpi`). Pi, Prime, and Senpi do not expose operator approval decisions, so Beacon does not synthesize them. Oh My Pi exposes real approval events and the extension carries the remembered tool input onto those approvals.- Prime Agent is the Pi-family exception with a single persistent `ipython` tool: kernel cells are recorded as `command.executed`, carry Python status/output metadata, and have no invented exit code. MCP is not separately attributed because Prime exposes integrations inside the kernel. `beacon endpoint prime sync` is the local poll backfill from `~/.prime/agent/sessions` and session artifacts.@@ -584,7 +584,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`), `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.+- 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`; the public adapter also reads it to skip those duplicate runs), `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/cursor_compat.go b/cli/beacon-hooks/cmd/cursor_compat.gonew file mode 100644index 00000000..c21ed3f0--- /dev/null+++ b/cli/beacon-hooks/cmd/cursor_compat.go@@ -0,0 +1,129 @@+package cmd++import (+ "encoding/json"+ "os"+ "path/filepath"+ "regexp"+ "strings"+)++// cursorUserHooksPath locates the user-level Cursor hooks file, where `beacon endpoint install`+// writes Beacon's Cursor hooks. Tests replace it.+var cursorUserHooksPath = func() string {+ home, err := os.UserHomeDir()+ if err != nil {+ return ""+ }+ 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.+//+// 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'+// 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+// requests), and everything when they aren't installed at the user level.+//+// 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]+ if len(events) == 0 {+ return false+ }+ path := cursorUserHooksPath()+ if path == "" {+ return false+ }+ data, err := os.ReadFile(path)+ if err != nil {+ return false+ }+ var file struct {+ Hooks map[string][]struct {+ Command string `json:"command"`+ Matcher string `json:"matcher"`+ } `json:"hooks"`+ }+ if json.Unmarshal(data, &file) != nil {+ return false+ }+ 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) {+ return true+ }+ }+ }+ return false+}++// cursorMatcherSelects reports whether a Cursor hook entry's matcher selects tool. An entry with no+// matcher runs for every call. Cursor reads a matcher as a pattern found anywhere in the tool's+// name, which is how Beacon's "MCP" selects "MCP:slack_send_message". A matcher that isn't a valid+// pattern, or a call that names no tool, counts as not selected, which leaves the Claude Code run+// recording: a duplicate beats a lost event.+func cursorMatcherSelects(matcher, tool string) bool {+ if strings.TrimSpace(matcher) == "" {+ return true+ }+ if tool == "" {+ return false+ }+ pattern, err := regexp.Compile(matcher)+ if err != nil {+ return false+ }+ 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.gonew file mode 100644index 00000000..952c42b7--- /dev/null+++ b/cli/beacon-hooks/cmd/cursor_compat_test.go@@ -0,0 +1,379 @@+package cmd++import (+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "reflect"+ "sort"+ "strings"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/logging"+)++// beaconCursorHook is the command `beacon endpoint install` writes into ~/.cursor/hooks.json.+func beaconCursorHook(command string) string {+ return "'/Users/dev/.beacon/endpoint/hooks/beacon-hooks' --platform cursor --log '/var/log/beacon-agent/runtime.jsonl' --config '/Library/Application Support/Beacon/Endpoint/config.json' " + command+}++// cursorPreToolMatcher is the matcher `beacon endpoint install` gives Beacon's Cursor pre-tool hook.+const cursorPreToolMatcher = "Write|Edit|MultiEdit|Shell|MCP"++// writeCursorHooks installs a user-level Cursor hooks file holding these commands, by event.+func writeCursorHooks(t *testing.T, hooks map[string][]string) {+ t.Helper()+ entries := map[string][]map[string]string{}+ for event, commands := range hooks {+ for _, command := range commands {+ entries[event] = append(entries[event], map[string]string{"command": command})+ }+ }+ writeCursorHookEntries(t, entries)+}++// writeCursorHookEntries installs a user-level Cursor hooks file holding these entries, by event.+func writeCursorHookEntries(t *testing.T, entries map[string][]map[string]string) {+ t.Helper()+ data, err := json.Marshal(map[string]interface{}{"version": 1, "hooks": entries})+ if err != nil {+ t.Fatal(err)+ }+ path := filepath.Join(t.TempDir(), "hooks.json")+ if err := os.WriteFile(path, data, 0o644); err != nil {+ t.Fatal(err)+ }+ original := cursorUserHooksPath+ cursorUserHooksPath = func() string { return path }+ t.Cleanup(func() { cursorUserHooksPath = original })+}++// setupCursorCompatRun prepares one hook run: the platform its entry declares, the subcommand it+// runs, and an empty runtime log.+func setupCursorCompatRun(t *testing.T, declared, command string) string {+ t.Helper()+ setupHookConfigDirs(t)+ platformFlag = declared+ hookCommand = command+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)+ t.Cleanup(func() {+ hookCommand = ""+ duplicateCursorRun = false+ logging.SuppressEndpointEvents(false)+ })+ return logPath+}++// countEndpointEvents is the number of events in the runtime log, zero when nothing created it.+func countEndpointEvents(t *testing.T, path string) int {+ t.Helper()+ data, err := os.ReadFile(path)+ if errors.Is(err, os.ErrNotExist) {+ return 0+ }+ if err != nil {+ t.Fatalf("read endpoint log: %v", err)+ }+ count := 0+ for _, line := range strings.Split(string(data), "\n") {+ if strings.TrimSpace(line) != "" {+ count+++ }+ }+ return count+}++func cursorPromptPayload() map[string]interface{} {+ return map[string]interface{}{+ "conversation_id": "conv-compat",+ "generation_id": "gen-1",+ "hook_event_name": "beforeSubmitPrompt",+ "prompt": "summarize this repository",+ "workspace_roots": []interface{}{"/repo"},+ }+}++func TestClaudeHookRecordsNothingWhenCursorHooksRecordTheEvent(t *testing.T) {+ writeCursorHooks(t, map[string][]string{"beforeSubmitPrompt": {beaconCursorHook("prompt-submit")}})++ logPath := setupCursorCompatRun(t, "cursor", "prompt-submit")+ native := runHookWithInput(t, runPromptSubmit, cursorPromptPayload())+ if n := countEndpointEvents(t, logPath); n != 1 {+ t.Fatalf("Cursor's own hook wrote %d events, want 1", n)+ }++ logPath = setupCursorCompatRun(t, "claude", "prompt-submit")+ compat := runHookWithInput(t, runPromptSubmit, cursorPromptPayload())+ if n := countEndpointEvents(t, logPath); n != 0 {+ t.Fatalf("Claude Code hook run by Cursor wrote %d events, want 0", n)+ }+ // The reply is Cursor's, exactly as before: only the recording stepped aside.+ if !reflect.DeepEqual(compat, native) {+ t.Fatalf("Claude Code hook replied %#v, want Cursor's reply %#v", compat, native)+ }+}++func TestClaudeHookRecordsCursorEventsWhenBeaconCursorHooksAreAbsent(t *testing.T) {+ // No Cursor hooks file: the Claude Code hook is the only one recording Cursor, as before.+ logPath := setupCursorCompatRun(t, "claude", "prompt-submit")+ runHookWithInput(t, runPromptSubmit, cursorPromptPayload())+ event := lastEndpointEvent(t, logPath)+ if harness := event["harness"].(map[string]interface{})["name"]; harness != "cursor" {+ t.Fatalf("harness = %q, want cursor", harness)+ }+ if action := event["event"].(map[string]interface{})["action"]; action != "prompt.submitted" {+ t.Fatalf("event.action = %q, want prompt.submitted", action)+ }+}++func TestClaudeHookRecordsCommandsBeaconCursorHooksDoNotRun(t *testing.T) {+ // Beacon's Cursor hooks run session-start but nothing that records prompts.+ writeCursorHooks(t, map[string][]string{"sessionStart": {beaconCursorHook("session-start")}})+ logPath := setupCursorCompatRun(t, "claude", "prompt-submit")+ runHookWithInput(t, runPromptSubmit, cursorPromptPayload())+ if n := countEndpointEvents(t, logPath); n != 1 {+ t.Fatalf("wrote %d events, want the prompt recorded once", n)+ }+}++func TestOnlyBeaconCursorEntriesCount(t *testing.T) {+ // A person's own Cursor hook that happens to end in the same word is not Beacon's.+ writeCursorHooks(t, map[string][]string{"beforeSubmitPrompt": {"/usr/local/bin/my-audit prompt-submit"}})+ logPath := setupCursorCompatRun(t, "claude", "prompt-submit")+ runHookWithInput(t, runPromptSubmit, cursorPromptPayload())+ if n := countEndpointEvents(t, logPath); n != 1 {+ t.Fatalf("wrote %d events, want the prompt recorded once", n)+ }+}++func TestClaudePayloadsStillRecordWithBeaconCursorHooksInstalled(t *testing.T) {+ writeCursorHooks(t, map[string][]string{"beforeSubmitPrompt": {beaconCursorHook("prompt-submit")}})+ logPath := setupCursorCompatRun(t, "claude", "prompt-submit")+ runHookWithInput(t, runPromptSubmit, map[string]interface{}{+ "session_id": "claude-session",+ "hook_event_name": "UserPromptSubmit",+ "prompt": "summarize this repository",+ "cwd": "/repo",+ })+ event := lastEndpointEvent(t, logPath)+ if harness := event["harness"].(map[string]interface{})["name"]; harness != "claude_code" {+ t.Fatalf("harness = %q, want claude_code", harness)+ }+}++func TestSuppressionDoesNotOutliveTheRun(t *testing.T) {+ writeCursorHooks(t, map[string][]string{"beforeSubmitPrompt": {beaconCursorHook("prompt-submit")}})+ logPath := setupCursorCompatRun(t, "claude", "prompt-submit")+ runHookWithInput(t, runPromptSubmit, cursorPromptPayload())+ // The next run in the same process reads its own payload and decides afresh.+ platformFlag = "claude"+ runHookWithInput(t, runPromptSubmit, map[string]interface{}{+ "session_id": "claude-session",+ "hook_event_name": "UserPromptSubmit",+ "prompt": "next prompt",+ "cwd": "/repo",+ })+ if n := countEndpointEvents(t, logPath); n != 1 {+ t.Fatalf("wrote %d events, want only the Claude Code prompt", n)+ }+}++func installBeaconCursorPreTool(t *testing.T) {+ t.Helper()+ writeCursorHookEntries(t, map[string][]map[string]string{+ "preToolUse": {{"command": beaconCursorHook("pre-tool"), "matcher": cursorPreToolMatcher}},+ })+}++func cursorToolPayload(tool string, toolInput map[string]interface{}) map[string]interface{} {+ return map[string]interface{}{+ "conversation_id": "conv-compat",+ "hook_event_name": "preToolUse",+ "tool_name": tool,+ "tool_input": toolInput,+ }+}++func TestClaudeHookSkipsToolCallsCursorsMatcherSelects(t *testing.T) {+ installBeaconCursorPreTool(t)+ for _, tool := range []string{"Write", "MCP:slack_send_message"} {+ logPath := setupCursorCompatRun(t, "claude", "pre-tool")+ runHookWithInput(t, runPreTool, cursorToolPayload(tool, map[string]interface{}{"file_path": "/repo/notes.md"}))+ if n := countEndpointEvents(t, logPath); n != 0 {+ t.Fatalf("%s: Claude Code hook run by Cursor wrote %d events, want 0", tool, n)+ }+ }+}++func TestClaudeHookStillCoversToolsOnlyItsMatcherSelects(t *testing.T) {+ // Beacon's Cursor pre-tool hook doesn't select Read, so the Claude Code run is the only one+ // that sees the call: it records it and asks the policy provider, as before.+ installBeaconCursorPreTool(t)+ logPath := setupPolicyTest(t, "claude", denyResponse)+ hookCommand = "pre-tool"+ t.Cleanup(func() {+ hookCommand = ""+ duplicateCursorRun = false+ logging.SuppressEndpointEvents(false)+ })+ out := runHookWithInput(t, runPreTool, cursorToolPayload("Read", map[string]interface{}{"file_path": "/repo/.env"}))+ if out["permission"] != "deny" {+ t.Fatalf("Read reply = %#v, want the provider's deny", out)+ }+ assertDenialEvent(t, logPath)+}++// TestClaudeHookIgnoresAStaleEntryUnderTheWrongEvent reproduces cli/beacon's own+// testdata/cursor_hooks_golden.json: an older Beacon version's env-prefix `pre-tool` command,+// left behind under beforeShellExecution, has no matcher -- so it would select every tool if the+// duplicate check scanned every event for the subcommand rather than only the event (preToolUse)+// Beacon's current installer wires pre-tool to. A Read call, which only Claude's matcher selects,+// must still be recorded and still reach the policy provider.+func TestClaudeHookIgnoresAStaleEntryUnderTheWrongEvent(t *testing.T) {+ writeCursorHookEntries(t, map[string][]map[string]string{+ "beforeShellExecution": {{"command": "BEACON_ENDPOINT_MODE=1 BEACON_ENDPOINT_LOG=/tmp/old.jsonl /old/beacon-hooks --platform cursor pre-tool"}},+ "preToolUse": {{"command": beaconCursorHook("pre-tool"), "matcher": cursorPreToolMatcher}},+ })+ logPath := setupPolicyTest(t, "claude", denyResponse)+ hookCommand = "pre-tool"+ t.Cleanup(func() {+ hookCommand = ""+ duplicateCursorRun = false+ logging.SuppressEndpointEvents(false)+ })+ out := runHookWithInput(t, runPreTool, cursorToolPayload("Read", map[string]interface{}{"file_path": "/repo/.env"}))+ if out["permission"] != "deny" {+ t.Fatalf("Read reply = %#v, want the provider's deny (the stale beforeShellExecution entry must not suppress it)", out)+ }+ assertDenialEvent(t, logPath)+}++func TestCursorMatcherSelects(t *testing.T) {+ cases := []struct {+ matcher, tool string+ want bool+ }{+ {"", "Read", true},+ {"", "", true},+ {cursorPreToolMatcher, "Write", true},+ {cursorPreToolMatcher, "Shell", true},+ {cursorPreToolMatcher, "MCP:slack_send_message", true},+ {cursorPreToolMatcher, "Read", false},+ {cursorPreToolMatcher, "Grep", false},+ {cursorPreToolMatcher, "", false},+ {"(", "Write", false},+ }+ for _, tc := range cases {+ if got := cursorMatcherSelects(tc.matcher, tc.tool); got != tc.want {+ t.Errorf("cursorMatcherSelects(%q, %q) = %v, want %v", tc.matcher, tc.tool, got, tc.want)+ }+ }+}++func TestDuplicateCursorRunDoesNotAskThePolicyProvider(t *testing.T) {+ installBeaconCursorPreTool(t)+ payload := func() map[string]interface{} {+ return cursorToolPayload("Shell", map[string]interface{}{"command": "claude --dangerously-skip-permissions -p go"})+ }+ t.Cleanup(func() {+ hookCommand = ""+ duplicateCursorRun = false+ logging.SuppressEndpointEvents(false)+ })++ // Cursor's own hook asks the provider and records the deny.+ logPath := setupPolicyTest(t, "cursor", denyResponse)+ hookCommand = "pre-tool"+ if out := runHookWithInput(t, runPreTool, payload()); out["permission"] != "deny" {+ t.Fatalf("Cursor's own hook replied %#v, want permission=deny", out)+ }+ assertDenialEvent(t, logPath)++ // The Claude Code copy of the same call neither decides nor records.+ logPath = setupPolicyTest(t, "claude", denyResponse)+ hookCommand = "pre-tool"+ if out := runHookWithInput(t, runPreTool, payload()); out["permission"] == "deny" {+ t.Fatalf("duplicate run denied the call: %#v", out)+ }+ if n := countEndpointEvents(t, logPath); n != 0 {+ t.Fatalf("duplicate run wrote %d events, want 0", n)+ }+}++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+ cursorUserHooksPath = func() string { return path }+ t.Cleanup(func() { cursorUserHooksPath = original })++ if cursorRecordsThisHook("prompt-submit", nil) {+ t.Fatal("a missing file reported Beacon's Cursor hooks as installed")+ }+ if err := os.WriteFile(path, []byte("{not json"), 0o644); err != nil {+ t.Fatal(err)+ }+ if cursorRecordsThisHook("prompt-submit", nil) {+ t.Fatal("an unreadable file reported Beacon's Cursor hooks as installed")+ }+ if cursorRecordsThisHook("", nil) {+ 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-hooks/cmd/helpers.go b/cli/beacon-hooks/cmd/helpers.goindex a33d1e63..ca4a7711 100644--- a/cli/beacon-hooks/cmd/helpers.go+++ b/cli/beacon-hooks/cmd/helpers.go@@ -13,18 +13,25 @@ import (// 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.+// so a hook installed for Claude Code can be handling a Cursor event.var declaredPlatform string+// duplicateCursorRun is set when this run is Cursor running Beacon's Claude Code hook for an event+// Beacon's own Cursor hook records too. Such a run writes no events and consults no policy+// provider; see cursorRecordsThisHook.+var duplicateCursorRun bool+// readStdinJSON decodes JSON from stdin into a map.func readStdinJSON() (map[string]interface{}, error) {declaredPlatform = platformFlag+ duplicateCursorRun = falsevar input map[string]interface{}err := json.NewDecoder(os.Stdin).Decode(&input)if err == nil {applyPayloadPlatformOverride(input)+ duplicateCursorRun = declaredPlatform == "claude" && platformFlag == "cursor" && cursorRecordsThisHook(hookCommand, input)}+ logging.SuppressEndpointEvents(duplicateCursorRun)return input, err}diff --git a/cli/beacon-hooks/cmd/main_test.go b/cli/beacon-hooks/cmd/main_test.goindex 3fe5eb93..00363db9 100644--- a/cli/beacon-hooks/cmd/main_test.go+++ b/cli/beacon-hooks/cmd/main_test.go@@ -27,6 +27,10 @@ func TestMain(m *testing.M) {Client: localingest.Client{SocketPath: filepath.Join(dir, "no-ingest.sock")},Spool: localingest.Spool{Dir: filepath.Join(dir, "spool")},}+ // Beacon's Cursor hooks are not installed unless a test writes a hooks file of its own; the+ // developer's real ~/.cursor/hooks.json must not decide what a test records.+ cursorHooksPath := filepath.Join(dir, "cursor-hooks.json")+ cursorUserHooksPath = func() string { return cursorHooksPath }// A suite run from inside a Claude Code session must not append to that session's env file.os.Unsetenv("CLAUDE_ENV_FILE")code := m.Run()diff --git a/cli/beacon-hooks/cmd/policy.go b/cli/beacon-hooks/cmd/policy.goindex 1a104863..2d51e664 100644--- a/cli/beacon-hooks/cmd/policy.go+++ b/cli/beacon-hooks/cmd/policy.go@@ -74,7 +74,9 @@ func (d policyDenial) emit() {// the caller proceeds with the normal allow flow. It is a no-op (nil) when no// provider is configured.func enforcePolicy(logger *logging.Logger, input map[string]interface{}, sessionID string, phase policycontract.Phase) *policyDenial {- if !policy.Enabled() {+ // A duplicate Cursor run records nothing, so it must not decide anything either: a deny here+ // would block a call with no record of why. Beacon's own Cursor hook asks the provider.+ if !policy.Enabled() || duplicateCursorRun {return nil}candidate := newPolicyCandidate(input, sessionID)diff --git a/cli/beacon-hooks/cmd/root.go b/cli/beacon-hooks/cmd/root.goindex 78de257f..3ac31ff9 100644--- a/cli/beacon-hooks/cmd/root.go+++ b/cli/beacon-hooks/cmd/root.go@@ -10,6 +10,11 @@ import (var platformFlag string+// hookCommand is the subcommand this process runs (session-start, pre-tool, ...), as cobra resolved+// it. It is how a run tells whether another hook entry runs the same command; see+// cursorRecordsThisHook.+var hookCommand string+// The endpoint settings a hook needs, as flags.//// They already existed as environment variables, and still do -- an already-installed hook carries@@ -48,7 +53,10 @@ func init() {// every use, and several runtimes surface hook stderr to the person at the keyboard.rootCmd.PersistentFlags().StringVar(&cliFlag, "cli", "", "Ignored; kept for hook commands written by older versions (mapped to BEACON_ENDPOINT_CLI)")_ = rootCmd.PersistentFlags().MarkHidden("cli")- rootCmd.PersistentPreRun = func(*cobra.Command, []string) { applyEndpointFlagsToEnv() }+ rootCmd.PersistentPreRun = func(cmd *cobra.Command, _ []string) {+ hookCommand = cmd.Name()+ applyEndpointFlagsToEnv()+ }}// applyEndpointFlagsToEnv puts flag values where the rest of the binary already looks for them.diff --git a/cli/beacon-hooks/internal/logging/logging.go b/cli/beacon-hooks/internal/logging/logging.goindex 4969e16f..552e43a1 100644--- a/cli/beacon-hooks/internal/logging/logging.go+++ b/cli/beacon-hooks/internal/logging/logging.go@@ -37,6 +37,17 @@ const (endpointRuntimeFileMode = asymptoteobserve.SharedRuntimeLogFileMode)+// endpointEventsSuppressed stops this process writing endpoint events. A hook sets it when another+// hook of Beacon's records the same event, as when Cursor runs Beacon's Claude Code hooks next to+// its own.+var endpointEventsSuppressed bool++// SuppressEndpointEvents turns endpoint event writes off (true) or back on (false) for the rest of+// this process.+func SuppressEndpointEvents(suppress bool) {+ endpointEventsSuppressed = suppress+}+// Logger provides structured JSON logging for hook eventstype Logger struct {hookName string@@ -124,6 +135,9 @@ func (l *Logger) EndpointEvent(action, category, severity, message string, field// approval from a pre-tool notification, for instance -- so those events are distinguishable from// the ones a runtime actually reported.func (l *Logger) EndpointEventWithFidelity(action, category, severity, message, fidelity string, fields map[string]interface{}) error {+ if endpointEventsSuppressed {+ return nil+ }path := endpointLogPath()if path == "" {return nildiff --git a/cli/beacon/internal/endpoint/hooks/cursor.go b/cli/beacon/internal/endpoint/hooks/cursor.goindex f371002e..a67498dd 100644--- a/cli/beacon/internal/endpoint/hooks/cursor.go+++ b/cli/beacon/internal/endpoint/hooks/cursor.go@@ -109,6 +109,11 @@ func installCursorHooksJSON(path, binaryPath, logPath, configPath string) errorreturn 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},