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
add hook impl claude code
Justin D'Souza6dd227293f9e
diff --git a/README.md b/README.mdindex 2e506a2c..564e42d8 100644--- a/README.md+++ b/README.md@@ -76,7 +76,7 @@ Claude Cowork, OpenClaw).| Agent Harness | Support path || --- | --- || [Antigravity CLI](https://docs.asymptotelabs.ai/cli/supported-runtimes-antigravity-cli) | Beacon hook adapter |-| [Claude Code](https://docs.asymptotelabs.ai/cli/supported-runtimes-claude-code) | Local OpenTelemetry configuration |+| [Claude Code](https://docs.asymptotelabs.ai/cli/supported-runtimes-claude-code) | Local OpenTelemetry configuration or Beacon hook adapter || [Claude Cowork](https://docs.asymptotelabs.ai/cli/supported-runtimes-claude-cowork) | Admin-configured OpenTelemetry setup || [Codex CLI](https://docs.asymptotelabs.ai/cli/supported-runtimes-codex-cli) | Local OpenTelemetry configuration || [Cursor](https://docs.asymptotelabs.ai/cli/supported-runtimes-cursor) | Beacon hook adapter |diff --git a/cli/beacon-hooks/cmd/endpoint_events.go b/cli/beacon-hooks/cmd/endpoint_events.goindex beb078c8..ee7a5fea 100644--- a/cli/beacon-hooks/cmd/endpoint_events.go+++ b/cli/beacon-hooks/cmd/endpoint_events.go@@ -184,7 +184,7 @@ func actionForTool(hookEvent, toolName string) string {switch {case strings.Contains(lower, "mcp"):return "mcp.tool_invoked"- case strings.Contains(lower, "shell") || strings.Contains(lower, "terminal") || strings.Contains(lower, "command"):+ case lower == "bash" || strings.Contains(lower, "shell") || strings.Contains(lower, "terminal") || strings.Contains(lower, "command"):return "command.executed"case strings.Contains(lower, "read"):return "file.read"diff --git a/cli/beacon-hooks/cmd/permission_request.go b/cli/beacon-hooks/cmd/permission_request.goindex 3bdeb419..1f4a2423 100644--- a/cli/beacon-hooks/cmd/permission_request.go+++ b/cli/beacon-hooks/cmd/permission_request.go@@ -8,8 +8,8 @@ import (var permissionRequestCmd = &cobra.Command{Use: "permission-request",- Short: "Observe Devin permission requests for local endpoint telemetry",- Long: `PermissionRequest hook - triggered when Devin needs a permission decision.`,+ Short: "Observe permission requests for local endpoint telemetry",+ Long: `PermissionRequest hook - triggered when an agent runtime needs a permission decision.`,Run: runPermissionRequest,}@@ -20,14 +20,13 @@ func init() {var devinApproveResponse = map[string]interface{}{"decision": "approve"}func runPermissionRequest(cmd *cobra.Command, args []string) {- if platformFlag != "devin" {- outputJSON(emptyResponse)- return- }-input, err := readStdinJSON()if err != nil {- outputJSON(devinApproveResponse)+ if platformFlag == "devin" {+ outputJSON(devinApproveResponse)+ return+ }+ outputJSON(emptyResponse)return}@@ -39,6 +38,12 @@ func runPermissionRequest(cmd *cobra.Command, args []string) {logger = logging.NewLoggerForPlatform("permission-request", platformFlag)}- emitPreToolDecision(logger, input, sessionID, "approval.allowed", "approve", "Permission request approved")- outputJSON(devinApproveResponse)+ if platformFlag == "devin" {+ emitPreToolDecision(logger, input, sessionID, "approval.allowed", "approve", "Permission request approved")+ outputJSON(devinApproveResponse)+ return+ }++ emitPreToolDecision(logger, input, sessionID, "approval.requested", "requested", "Permission request observed")+ outputJSON(emptyResponse)}diff --git a/cli/beacon-hooks/cmd/post_tool.go b/cli/beacon-hooks/cmd/post_tool.goindex a2131d8c..a4eebfaa 100644--- a/cli/beacon-hooks/cmd/post_tool.go+++ b/cli/beacon-hooks/cmd/post_tool.go@@ -275,7 +275,7 @@ func emitPostToolObserved(logger *logging.Logger, input map[string]interface{})for key, value := range toolFields(toolName, toolInput) {fields[key] = value}- if hookEvent == "postToolUseFailure" || hookEvent == "post_tool_use_failure" || getFirstStr(input, "error") != "" {+ if hookEvent == "PostToolUseFailure" || hookEvent == "postToolUseFailure" || hookEvent == "post_tool_use_failure" || getFirstStr(input, "error") != "" {emitHookEvent(logger, "tool.failed", "tool", "high", "Tool execution failed", input, fields)return}diff --git a/cli/beacon-hooks/cmd/post_tool_test.go b/cli/beacon-hooks/cmd/post_tool_test.goindex c3404615..ea8e6eb4 100644--- a/cli/beacon-hooks/cmd/post_tool_test.go+++ b/cli/beacon-hooks/cmd/post_tool_test.go@@ -238,6 +238,84 @@ func TestRunPostToolEmitsFactoryFileModifiedEvent(t *testing.T) {}}+func TestRunPostToolEmitsClaudeToolEvents(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "claude"+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ inputs := []map[string]interface{}{+ {+ "session_id": "claude-session",+ "cwd": "/repo",+ "hook_event_name": "PostToolUse",+ "tool_name": "Edit",+ "tool_input": map[string]interface{}{+ "file_path": "/repo/main.go",+ "old_string": "old",+ "new_string": "new token=claude-secret",+ },+ "tool_response": map[string]interface{}{"success": true},+ },+ {+ "session_id": "claude-session",+ "cwd": "/repo",+ "hook_event_name": "PostToolUse",+ "tool_name": "Bash",+ "tool_input": map[string]interface{}{"command": "go test ./..."},+ "tool_response": map[string]interface{}{"stdout": "ok"},+ },+ {+ "session_id": "claude-session",+ "cwd": "/repo",+ "hook_event_name": "PostToolUseFailure",+ "tool_name": "Bash",+ "tool_input": map[string]interface{}{"command": "go test ./..."},+ "error": "exit status 1",+ },+ {+ "session_id": "claude-session",+ "cwd": "/repo",+ "hook_event_name": "PostToolUse",+ "tool_name": "mcp__memory__write",+ "tool_input": map[string]interface{}{"name": "remember"},+ "tool_response": map[string]interface{}{"ok": true},+ },+ }++ for _, input := range inputs {+ if out := runHookWithInput(t, runPostTool, input); len(out) != 0 {+ t.Fatalf("post-tool response = %#v, want empty response", out)+ }+ }++ events := endpointEvents(t, logPath)+ if len(events) != 4 {+ t.Fatalf("event count = %d, want 4: %#v", len(events), events)+ }+ wantActions := []string{"file.modified", "command.executed", "tool.failed", "mcp.tool_invoked"}+ for i, want := range wantActions {+ if got := events[i]["event"].(map[string]interface{})["action"]; got != want {+ t.Fatalf("event[%d].action = %q, want %q", i, got, want)+ }+ if harness := events[i]["harness"].(map[string]interface{})["name"]; harness != "claude" {+ t.Fatalf("event[%d] harness = %q, want claude", i, harness)+ }+ }+ if file := events[0]["file"].(map[string]interface{}); file["path"] != "/repo/main.go" || file["operation"] != "modify" {+ t.Fatalf("file event = %#v, want main.go modify", file)+ }+ if command := events[1]["command"].(map[string]interface{})["command"]; command != "go test ./..." {+ t.Fatalf("command = %q, want go test ./...", command)+ }+ if severity := events[2]["severity"]; severity != "high" {+ t.Fatalf("failure severity = %q, want high", severity)+ }+ if mcp := events[3]["mcp"].(map[string]interface{}); mcp["tool"] != "remember" {+ t.Fatalf("mcp = %#v, want tool remember", mcp)+ }+}+func TestResolveToolInput(t *testing.T) {tests := []struct {name stringdiff --git a/cli/beacon-hooks/cmd/pre_tool.go b/cli/beacon-hooks/cmd/pre_tool.goindex aa4241e1..a46e82a1 100644--- a/cli/beacon-hooks/cmd/pre_tool.go+++ b/cli/beacon-hooks/cmd/pre_tool.go@@ -48,7 +48,7 @@ func runPreTool(cmd *cobra.Command, args []string) {if platformFlag == "antigravity" {emitAntigravityPromptFromTranscript(logger, input, sessionID)emitPreToolObserved(logger, input, sessionID)- } else if platformFlag == "devin" || platformFlag == "grok" || platformFlag == "vscode" {+ } else if platformFlag == "claude" || platformFlag == "devin" || platformFlag == "grok" || platformFlag == "vscode" {emitPreToolObserved(logger, input, sessionID)} else {emitPreToolDecision(logger, input, sessionID, "approval.allowed", "allow", "Pre-tool observed")@@ -75,7 +75,7 @@ func preToolResponse() map[string]interface{} {if platformFlag == "antigravity" || platformFlag == "grok" {return map[string]interface{}{"decision": "allow"}}- if platformFlag == "devin" || platformFlag == "vscode" {+ if platformFlag == "claude" || platformFlag == "devin" || platformFlag == "vscode" {return emptyResponse}return allowResponsediff --git a/cli/beacon-hooks/cmd/pre_tool_test.go b/cli/beacon-hooks/cmd/pre_tool_test.goindex 00223bf0..7d2144d7 100644--- a/cli/beacon-hooks/cmd/pre_tool_test.go+++ b/cli/beacon-hooks/cmd/pre_tool_test.go@@ -313,6 +313,45 @@ func TestRunPreToolEmitsDevinToolTelemetryWithoutApproval(t *testing.T) {}}+func TestRunPreToolEmitsClaudeTelemetryWithoutDecision(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "claude"+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ out := runHookWithInput(t, runPreTool, map[string]interface{}{+ "session_id": "claude-session",+ "transcript_path": "/tmp/claude-session.jsonl",+ "cwd": "/repo",+ "hook_event_name": "PreToolUse",+ "tool_name": "Bash",+ "tool_input": map[string]interface{}{+ "command": "go test ./...",+ },+ })+ if len(out) != 0 {+ t.Fatalf("claude pre-tool response = %#v, want empty non-controlling response", out)+ }++ event := lastEndpointEvent(t, logPath)+ if action := event["event"].(map[string]interface{})["action"]; action != "tool.invoked" {+ t.Fatalf("event.action = %q, want tool.invoked", action)+ }+ if harness := event["harness"].(map[string]interface{})["name"]; harness != "claude" {+ t.Fatalf("harness = %q, want claude", harness)+ }+ if _, ok := event["approval"]; ok {+ t.Fatalf("Claude PreToolUse should not emit approval telemetry: %#v", event["approval"])+ }+ if command := event["command"].(map[string]interface{})["command"]; command != "go test ./..." {+ t.Fatalf("command = %q, want go test ./...", command)+ }+ session := event["session"].(map[string]interface{})+ if session["id"] != "claude-session" || session["working_directory"] != "/repo" {+ t.Fatalf("session = %#v, want id and working_directory", session)+ }+}+func TestRunPreToolEmitsAntigravityCommandTelemetry(t *testing.T) {setupHookConfigDirs(t)platformFlag = "antigravity"@@ -461,23 +500,33 @@ func TestRunPermissionRequestEmitsDevinApproval(t *testing.T) {}}-func TestRunPermissionRequestNoopsForNonDevinPlatform(t *testing.T) {+func TestRunPermissionRequestEmitsClaudeTelemetryWithoutDecision(t *testing.T) {setupHookConfigDirs(t)- platformFlag = "cursor"+ platformFlag = "claude"logPath := filepath.Join(t.TempDir(), "runtime.jsonl")t.Setenv("BEACON_ENDPOINT_LOG", logPath)out := runHookWithInput(t, runPermissionRequest, map[string]interface{}{+ "session_id": "claude-session",+ "cwd": "/repo","hook_event_name": "PermissionRequest",- "tool_name": "Shell",+ "tool_name": "Bash",+ "tool_input": map[string]interface{}{"command": "git status"},})if len(out) != 0 {- t.Fatalf("non-Devin permission response = %#v, want empty response", out)+ t.Fatalf("claude permission response = %#v, want empty response", out)+ }++ event := lastEndpointEvent(t, logPath)+ if action := event["event"].(map[string]interface{})["action"]; action != "approval.requested" {+ t.Fatalf("event.action = %q, want approval.requested", action)}- if _, err := os.Stat(logPath); err == nil {- t.Fatalf("non-Devin permission request should not write endpoint log")- } else if !os.IsNotExist(err) {- t.Fatalf("unexpected endpoint log stat error: %v", err)+ approval := event["approval"].(map[string]interface{})+ if approval["decision"] != "requested" {+ t.Fatalf("approval = %#v, want requested", approval)+ }+ if command := event["command"].(map[string]interface{})["command"]; command != "git status" {+ t.Fatalf("command = %q, want git status", command)}}diff --git a/cli/beacon/README.md b/cli/beacon/README.mdindex 3f375a52..a1b920e0 100644--- a/cli/beacon/README.md+++ b/cli/beacon/README.md@@ -123,6 +123,9 @@ tooling, not in Beacon endpoint configuration../beacon endpoint hooks install --harness cursor./beacon endpoint hooks status --harness cursor+./beacon endpoint hooks install --harness claude --level user+./beacon endpoint hooks status --harness claude+./beacon endpoint hooks install --harness opencode./beacon endpoint hooks status --harness opencode@@ -153,6 +156,15 @@ normalization, retention, redaction, and JSONL output locally. For localtroubleshooting, set `BEACON_OPENCODE_DEBUG=1` in the environment that launchesopencode to emit best-effort plugin debug logs.+Claude Code supports two Beacon setup paths. `beacon endpoint install --harness claude`+configures Claude Code's local OpenTelemetry export to Beacon's collector.+`beacon endpoint hooks install --harness claude` writes command hooks into+`~/.claude/settings.json` or `.claude/settings.json` and sends normalized events+directly to the local runtime JSONL log. The hook path is useful when an+Anthropic organization policy blocks third-party telemetry export. Claude Code+hooks are intentionally not included in `beacon endpoint hooks install --all` in+this release; install them explicitly with `--harness claude`.+The Grok Build integration writes Beacon's owned local hook file at`~/.grok/hooks/beacon-endpoint.json` for user-level installs or `.grok/hooks/beacon-endpoint.json`for project-level installs. Project hooks require trusting the project in Grokdiff --git a/cli/beacon/cmd/endpoint.go b/cli/beacon/cmd/endpoint.goindex 932b67e8..ca5eb432 100644--- a/cli/beacon/cmd/endpoint.go+++ b/cli/beacon/cmd/endpoint.go@@ -875,6 +875,16 @@ func runEndpointHooksInstall(cmd *cobra.Command, args []string) error {return err}fmt.Printf("Cursor hooks installed: %s\n", status.HooksJSONPath)+ case "claude", "claude_code":+ status, err := endpointhooks.InstallClaude(endpointhooks.ClaudeOptions{+ Level: endpointhooks.Level(endpointOpts.hookLevel),+ LogPath: cfg.LogPath,+ UserMode: cfg.UserMode,+ })+ if err != nil {+ return err+ }+ fmt.Printf("Claude Code hooks installed: %s\n", status.SettingsPath)case "vscode", "vs_code":status, err := endpointhooks.InstallVSCode(endpointhooks.VSCodeOptions{Level: endpointhooks.Level(endpointOpts.hookLevel),@@ -967,6 +977,16 @@ func runEndpointHooksUninstall(cmd *cobra.Command, args []string) error {return err}fmt.Println(status.Message)+ case "claude", "claude_code":+ status, err := endpointhooks.UninstallClaude(endpointhooks.ClaudeOptions{+ Level: endpointhooks.Level(endpointOpts.hookLevel),+ LogPath: cfg.LogPath,+ UserMode: cfg.UserMode,+ })+ if err != nil {+ return err+ }+ fmt.Println(status.Message)case "vscode", "vs_code":status, err := endpointhooks.UninstallVSCode(endpointhooks.VSCodeOptions{Level: endpointhooks.Level(endpointOpts.hookLevel),@@ -1042,6 +1062,12 @@ func runEndpointHooksStatus(cmd *cobra.Command, args []string) error {LogPath: cfg.LogPath,UserMode: cfg.UserMode,})+ case "claude", "claude_code":+ statuses["claude"] = endpointhooks.ClaudeHookStatus(endpointhooks.ClaudeOptions{+ Level: endpointhooks.Level(endpointOpts.hookLevel),+ LogPath: cfg.LogPath,+ UserMode: cfg.UserMode,+ })case "vscode", "vs_code":statuses["vscode"] = endpointhooks.VSCodeHookStatus(endpointhooks.VSCodeOptions{Level: endpointhooks.Level(endpointOpts.hookLevel),@@ -1090,6 +1116,10 @@ func runEndpointHooksStatus(cmd *cobra.Command, args []string) error {status := statuses["cursor"].(endpointhooks.CursorStatus)fmt.Printf("Cursor hooks: installed=%t path=%s\n", status.Installed, status.HooksJSONPath)fmt.Println(status.Message)+ case "claude", "claude_code":+ status := statuses["claude"].(endpointhooks.ClaudeStatus)+ fmt.Printf("Claude Code hooks: installed=%t path=%s\n", status.Installed, status.SettingsPath)+ fmt.Println(status.Message)case "vscode", "vs_code":status := statuses["vscode"].(endpointhooks.VSCodeStatus)fmt.Printf("VS Code hooks: installed=%t path=%s\n", status.Installed, status.HooksPath)diff --git a/cli/beacon/cmd/endpoint_diagnostics.go b/cli/beacon/cmd/endpoint_diagnostics.goindex 57bf3e61..ae6510ad 100644--- a/cli/beacon/cmd/endpoint_diagnostics.go+++ b/cli/beacon/cmd/endpoint_diagnostics.go@@ -387,6 +387,9 @@ func hookStatusesWithConfig(targets []string, cfg endpointconfig.Config) map[strcase "cursor":status := endpointhooks.CursorHookStatus(endpointhooks.CursorOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.HooksJSONPath, Raw: status}+ case "claude", "claude_code":+ status := endpointhooks.ClaudeHookStatus(endpointhooks.ClaudeOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})+ statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.SettingsPath, Raw: status}case "vscode", "vs_code":status := endpointhooks.VSCodeHookStatus(endpointhooks.VSCodeOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.HooksPath, Raw: status}diff --git a/cli/beacon/internal/endpoint/hooks/claude.go b/cli/beacon/internal/endpoint/hooks/claude.gonew file mode 100644index 00000000..d878e38e--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/claude.go@@ -0,0 +1,105 @@+package hooks++import (+ "fmt"+ "os"+ "path/filepath"+)++type ClaudeOptions struct {+ Level Level+ LogPath string+ UserMode bool+}++type ClaudeStatus struct {+ Installed bool `json:"installed"`+ BinaryPath string `json:"binary_path,omitempty"`+ SettingsPath string `json:"settings_path,omitempty"`+ Message string `json:"message,omitempty"`+}++var claudeRuntime = hookRuntime{+ displayName: "Claude Code",+ configPath: claudeSettingsPath,+ install: installClaudeSettings,+ uninstall: removeClaudeEndpointHooks,+ isInstalled: isClaudeInstalledAt,+}++func InstallClaude(opts ClaudeOptions) (ClaudeStatus, error) {+ status, err := installRuntimeHooks(claudeRuntime, RuntimeOptions(opts))+ if err != nil {+ return ClaudeStatus{}, err+ }+ return claudeStatusFromRuntime(status), nil+}++func UninstallClaude(opts ClaudeOptions) (ClaudeStatus, error) {+ status, err := uninstallRuntimeHooks(claudeRuntime, RuntimeOptions(opts))+ if err != nil {+ return ClaudeStatus{}, err+ }+ return claudeStatusFromRuntime(status), nil+}++func ClaudeHookStatus(opts ClaudeOptions) ClaudeStatus {+ return claudeStatusFromRuntime(runtimeHookStatus(claudeRuntime, RuntimeOptions(opts)))+}++func IsClaudeInstalled(opts ClaudeOptions) bool {+ return isRuntimeInstalled(claudeRuntime, RuntimeOptions(opts))+}++func claudeStatusFromRuntime(status runtimeStatus) ClaudeStatus {+ return ClaudeStatus{+ Installed: status.Installed,+ BinaryPath: status.BinaryPath,+ SettingsPath: status.ConfigPath,+ Message: status.Message,+ }+}++func installClaudeSettings(path, binaryPath, logPath, configPath string) error {+ prefix := endpointCommandPrefix("claude", binaryPath, logPath, configPath)+ endpointHooks := map[string]settingsHookGroup{+ "SessionStart": {Hooks: []settingsHookRef{{Type: "command", Command: prefix + " session-start"}}},+ "UserPromptSubmit": {Hooks: []settingsHookRef{{Type: "command", Command: prefix + " prompt-submit", Timeout: 30}}},+ "PreToolUse": {Matcher: "Bash|Edit|Write|MultiEdit|Read|Glob|Grep|WebFetch|WebSearch|Agent|mcp__.*", Hooks: []settingsHookRef{{Type: "command", Command: prefix + " pre-tool"}}},+ "PostToolUse": {Matcher: "*", Hooks: []settingsHookRef{{Type: "command", Command: prefix + " post-tool"}}},+ "PostToolUseFailure": {Matcher: "*", Hooks: []settingsHookRef{{Type: "command", Command: prefix + " post-tool"}}},+ "Stop": {Hooks: []settingsHookRef{{Type: "command", Command: prefix + " stop", Timeout: 45}}},+ "SubagentStart": {Hooks: []settingsHookRef{{Type: "command", Command: prefix + " subagent-start"}}},+ "SubagentStop": {Hooks: []settingsHookRef{{Type: "command", Command: prefix + " subagent-stop"}}},+ "PermissionRequest": {Matcher: "*", Hooks: []settingsHookRef{{Type: "command", Command: prefix + " permission-request"}}},+ "SessionEnd": {Hooks: []settingsHookRef{{Type: "command", Command: prefix + " session-end"}}},+ }+ return installSettingsEndpointHooks(path, "claude", endpointHooks)+}++func removeClaudeEndpointHooks(path string) (bool, error) {+ return removeSettingsEndpointHooks(path, "claude")+}++func isClaudeInstalledAt(path string) bool {+ return isSettingsEndpointInstalledAt(path, "claude")+}++func claudeSettingsPath(level Level) (string, error) {+ switch level {+ case "", LevelUser:+ home, err := os.UserHomeDir()+ if err != nil {+ return "", err+ }+ return filepath.Join(home, ".claude", "settings.json"), nil+ case LevelProject:+ cwd, err := os.Getwd()+ if err != nil {+ return "", err+ }+ return filepath.Join(cwd, ".claude", "settings.json"), nil+ default:+ return "", fmt.Errorf("unknown hook level %q", level)+ }+}diff --git a/cli/beacon/internal/endpoint/hooks/claude_test.go b/cli/beacon/internal/endpoint/hooks/claude_test.gonew file mode 100644index 00000000..88602345--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/claude_test.go@@ -0,0 +1,149 @@+package hooks++import (+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func TestInstallClaudeSettingsPreservesExistingSettingsAndHooks(t *testing.T) {+ path := filepath.Join(t.TempDir(), "settings.json")+ existing := `{"env":{"EXISTING":"1"},"permissions":{"defaultMode":"default"},"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"echo keep"}]}],"PostToolUse":[{"hooks":[{"type":"command","command":"BEACON_ENDPOINT_MODE=1 beacon-hooks --platform factory post-tool"}]}]}}`+ if err := os.WriteFile(path, []byte(existing), 0600); err != nil {+ t.Fatal(err)+ }++ if err := installClaudeSettings(path, "/tmp/beacon hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {+ t.Fatalf("installClaudeSettings returned error: %v", err)+ }+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read settings: %v", err)+ }+ text := string(data)+ for _, want := range []string{+ "EXISTING",+ "defaultMode",+ "echo keep",+ "--platform factory",+ "BEACON_ENDPOINT_MODE=1",+ "BEACON_ENDPOINT_LOG='/tmp/runtime.jsonl'",+ "BEACON_ENDPOINT_CONFIG='/tmp/config.json'",+ "'/tmp/beacon hooks' --platform claude",+ "SessionStart",+ "UserPromptSubmit",+ "PreToolUse",+ "Bash|Edit|Write|MultiEdit|Read|Glob|Grep|WebFetch|WebSearch|Agent|mcp__.*",+ "PostToolUseFailure",+ "SubagentStart",+ "SubagentStop",+ "PermissionRequest",+ "SessionEnd",+ } {+ if !strings.Contains(text, want) {+ t.Fatalf("settings missing %q:\n%s", want, text)+ }+ }+}++func TestInstallClaudeSettingsReplacesOnlyClaudeBeaconHooks(t *testing.T) {+ path := filepath.Join(t.TempDir(), "settings.json")+ existing := `{"hooks":{"PostToolUse":[{"hooks":[{"type":"command","command":"BEACON_ENDPOINT_MODE=1 old-beacon-hooks --platform claude post-tool"}]},{"hooks":[{"type":"command","command":"/tmp/asym-hooks --platform claude post-tool"}]},{"hooks":[{"type":"command","command":"BEACON_ENDPOINT_MODE=1 beacon-hooks --platform factory post-tool"}]},{"hooks":[{"type":"command","command":"BEACON_ENDPOINT_MODE=1 beacon-hooks post-tool"}]},{"hooks":[{"type":"command","command":"echo keep"}]}]}}`+ if err := os.WriteFile(path, []byte(existing), 0600); err != nil {+ t.Fatal(err)+ }++ if err := installClaudeSettings(path, "/tmp/new-beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {+ t.Fatalf("installClaudeSettings returned error: %v", err)+ }+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read settings: %v", err)+ }+ text := string(data)+ if strings.Contains(text, "old-beacon-hooks") || strings.Contains(text, "asym-hooks") {+ t.Fatalf("old Claude endpoint hook was not replaced:\n%s", text)+ }+ if !strings.Contains(text, "--platform factory") || !strings.Contains(text, "beacon-hooks post-tool") || !strings.Contains(text, "echo keep") || !strings.Contains(text, "/tmp/new-beacon-hooks") {+ t.Fatalf("expected preserved hooks and new hook:\n%s", text)+ }+}++func TestRemoveClaudeEndpointHooksPreservesOtherHooks(t *testing.T) {+ path := filepath.Join(t.TempDir(), "settings.json")+ existing := `{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"echo keep"},{"type":"command","command":"BEACON_ENDPOINT_MODE=1 beacon-hooks --platform claude session-start"},{"type":"command","command":"BEACON_ENDPOINT_MODE=1 beacon-hooks --platform factory session-start"}]}]}}`+ if err := os.WriteFile(path, []byte(existing), 0600); err != nil {+ t.Fatal(err)+ }++ changed, err := removeClaudeEndpointHooks(path)+ if err != nil {+ t.Fatalf("removeClaudeEndpointHooks returned error: %v", err)+ }+ if !changed {+ t.Fatal("expected endpoint hook removal")+ }+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read settings: %v", err)+ }+ text := string(data)+ if strings.Contains(text, "--platform claude") {+ t.Fatalf("Claude endpoint hook was not removed:\n%s", text)+ }+ if !strings.Contains(text, "echo keep") || !strings.Contains(text, "--platform factory") {+ t.Fatalf("non-Claude hooks were not preserved:\n%s", text)+ }+}++func TestInstallClaudeSettingsHandlesNullHooks(t *testing.T) {+ path := filepath.Join(t.TempDir(), "settings.json")+ if err := os.WriteFile(path, []byte(`{"hooks":null}`), 0600); err != nil {+ t.Fatal(err)+ }++ if err := installClaudeSettings(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {+ t.Fatalf("installClaudeSettings returned error: %v", err)+ }+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read settings: %v", err)+ }+ if !strings.Contains(string(data), "UserPromptSubmit") {+ t.Fatalf("Claude hooks were not installed from hooks:null:\n%s", string(data))+ }+}++func TestClaudeSettingsPathProjectLevel(t *testing.T) {+ dir := t.TempDir()+ t.Chdir(dir)++ target, err := claudeSettingsPath(LevelProject)+ if err != nil {+ t.Fatalf("claudeSettingsPath returned error: %v", err)+ }+ if got, want := target, filepath.Join(dir, ".claude", "settings.json"); got != want {+ t.Fatalf("project settings path = %q, want %q", got, want)+ }+}++func TestClaudeHookStatusDetectsInstalled(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ path := filepath.Join(home, ".claude", "settings.json")+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte(`{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"BEACON_ENDPOINT_MODE=1 beacon-hooks --platform claude stop"}]}]}}`), 0600); err != nil {+ t.Fatal(err)+ }++ status := ClaudeHookStatus(ClaudeOptions{Level: LevelUser, UserMode: true})+ if !status.Installed {+ t.Fatalf("ClaudeHookStatus installed = false, status=%#v", status)+ }+ if status.SettingsPath != path {+ t.Fatalf("SettingsPath = %q, want %q", status.SettingsPath, path)+ }+}diff --git a/cli/beacon/internal/endpoint/hooks/factory.go b/cli/beacon/internal/endpoint/hooks/factory.goindex 5a6fa363..a2a1bdcb 100644--- a/cli/beacon/internal/endpoint/hooks/factory.go+++ b/cli/beacon/internal/endpoint/hooks/factory.go@@ -1,7 +1,6 @@package hooksimport (- "encoding/json""fmt""os""path/filepath"@@ -20,21 +19,9 @@ type FactoryStatus struct {Message string `json:"message,omitempty"`}-type factoryHookGroup struct {- Matcher string `json:"matcher,omitempty"`- Hooks []factoryHookRef `json:"hooks"`-}--type factoryHookRef struct {- Type string `json:"type"`- Command string `json:"command"`- Timeout int `json:"timeout,omitempty"`-}--type factorySettings struct {- values map[string]json.RawMessage- hooks map[string][]factoryHookGroup-}+type factoryHookGroup = settingsHookGroup+type factoryHookRef = settingsHookRef+type factorySettings = settingsHooksFilevar factoryRuntime = hookRuntime{displayName: "Factory",@@ -78,10 +65,6 @@ func factoryStatusFromRuntime(status runtimeStatus) FactoryStatus {}func installFactorySettings(path, binaryPath, logPath, configPath string) error {- settings, err := readFactorySettings(path)- if err != nil {- return err- }prefix := endpointCommandPrefix("factory", binaryPath, logPath, configPath)endpointHooks := map[string]factoryHookGroup{"SessionStart": {Hooks: []factoryHookRef{{Type: "command", Command: prefix + " session-start"}}},@@ -90,144 +73,31 @@ func installFactorySettings(path, binaryPath, logPath, configPath string) error"Stop": {Hooks: []factoryHookRef{{Type: "command", Command: prefix + " stop", Timeout: 45}}},"SessionEnd": {Hooks: []factoryHookRef{{Type: "command", Command: prefix + " session-end"}}},}- for eventName, group := range endpointHooks {- settings.hooks[eventName] = mergeFactoryEndpointHook(settings.hooks[eventName], group)- }- data, err := settings.marshal()- if err != nil {- return err- }- return os.WriteFile(path, data, 0600)+ return installSettingsEndpointHooks(path, "factory", endpointHooks)}func readFactorySettings(path string) (factorySettings, error) {- settings := factorySettings{- values: map[string]json.RawMessage{},- hooks: map[string][]factoryHookGroup{},- }- data, err := os.ReadFile(path)- if err == nil {- if err := json.Unmarshal(data, &settings.values); err != nil {- return factorySettings{}, err- }- if rawHooks, ok := settings.values["hooks"]; ok {- if err := json.Unmarshal(rawHooks, &settings.hooks); err != nil {- return factorySettings{}, err- }- }- } else if !os.IsNotExist(err) {- return factorySettings{}, err- }- if settings.hooks == nil {- settings.hooks = map[string][]factoryHookGroup{}- }- return settings, nil-}--func (settings factorySettings) marshal() ([]byte, error) {- out := make(map[string]json.RawMessage, len(settings.values)+1)- for key, value := range settings.values {- if key != "hooks" {- out[key] = value- }- }- if len(settings.hooks) > 0 {- data, err := json.Marshal(settings.hooks)- if err != nil {- return nil, err- }- out["hooks"] = data- }- return json.MarshalIndent(out, "", " ")+ return readSettingsHooks(path)}func mergeFactoryEndpointHook(existing []factoryHookGroup, group factoryHookGroup) []factoryHookGroup {- out := make([]factoryHookGroup, 0, len(existing)+1)- for _, item := range existing {- filtered, changed := filterFactoryEndpointHooks(item)- if !changed || len(filtered.Hooks) > 0 {- out = append(out, item)- if changed {- out[len(out)-1] = filtered- }- }- }- return append(out, group)+ return mergeSettingsEndpointHook(existing, group, "factory")}func removeFactoryEndpointHooks(path string) (bool, error) {- settings, err := readFactorySettings(path)- if err != nil {- if os.IsNotExist(err) {- return false, nil- }- return false, err- }- changed := false- for eventName, groups := range settings.hooks {- filtered := groups[:0]- for _, group := range groups {- withoutEndpointHooks, groupChanged := filterFactoryEndpointHooks(group)- if groupChanged {- changed = true- }- if len(withoutEndpointHooks.Hooks) == 0 {- continue- }- filtered = append(filtered, withoutEndpointHooks)- }- if len(filtered) == 0 {- delete(settings.hooks, eventName)- } else {- settings.hooks[eventName] = filtered- }- }- if !changed {- return false, nil- }- out, err := settings.marshal()- if err != nil {- return false, err- }- return true, os.WriteFile(path, out, 0600)+ return removeSettingsEndpointHooks(path, "factory")}func isFactoryEndpointHookGroup(group factoryHookGroup) bool {- for _, hook := range group.Hooks {- if isEndpointHookCommand(hook.Command, "factory") {- return true- }- }- return false+ return isSettingsEndpointHookGroup(group, "factory")}func filterFactoryEndpointHooks(group factoryHookGroup) (factoryHookGroup, bool) {- filtered := group- filtered.Hooks = group.Hooks[:0]- changed := false- for _, hook := range group.Hooks {- if isEndpointHookCommand(hook.Command, "factory") {- changed = true- continue- }- filtered.Hooks = append(filtered.Hooks, hook)- }- return filtered, changed+ return filterSettingsEndpointHooks(group, "factory")}func isFactoryInstalledAt(path string) bool {- settings, err := readFactorySettings(path)- if err != nil {- return false- }- for _, groups := range settings.hooks {- for _, group := range groups {- if isFactoryEndpointHookGroup(group) {- return true- }- }- }- return false+ return isSettingsEndpointInstalledAt(path, "factory")}func factorySettingsPath(level Level) (string, error) {diff --git a/cli/beacon/internal/endpoint/hooks/settings_hooks.go b/cli/beacon/internal/endpoint/hooks/settings_hooks.gonew file mode 100644index 00000000..14c26d01--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/settings_hooks.go@@ -0,0 +1,175 @@+package hooks++import (+ "encoding/json"+ "os"+ "strings"+)++type settingsHookGroup struct {+ Matcher string `json:"matcher,omitempty"`+ Hooks []settingsHookRef `json:"hooks"`+}++type settingsHookRef struct {+ Type string `json:"type"`+ Command string `json:"command"`+ Timeout int `json:"timeout,omitempty"`+}++type settingsHooksFile struct {+ values map[string]json.RawMessage+ hooks map[string][]settingsHookGroup+}++func readSettingsHooks(path string) (settingsHooksFile, error) {+ settings := settingsHooksFile{+ values: map[string]json.RawMessage{},+ hooks: map[string][]settingsHookGroup{},+ }+ data, err := os.ReadFile(path)+ if err == nil {+ if err := json.Unmarshal(data, &settings.values); err != nil {+ return settingsHooksFile{}, err+ }+ if rawHooks, ok := settings.values["hooks"]; ok {+ if err := json.Unmarshal(rawHooks, &settings.hooks); err != nil {+ return settingsHooksFile{}, err+ }+ }+ } else if !os.IsNotExist(err) {+ return settingsHooksFile{}, err+ }+ if settings.hooks == nil {+ settings.hooks = map[string][]settingsHookGroup{}+ }+ return settings, nil+}++func (settings settingsHooksFile) marshal() ([]byte, error) {+ out := make(map[string]json.RawMessage, len(settings.values)+1)+ for key, value := range settings.values {+ if key != "hooks" {+ out[key] = value+ }+ }+ if len(settings.hooks) > 0 {+ data, err := json.Marshal(settings.hooks)+ if err != nil {+ return nil, err+ }+ out["hooks"] = data+ }+ return json.MarshalIndent(out, "", " ")+}++func installSettingsEndpointHooks(path, platform string, endpointHooks map[string]settingsHookGroup) error {+ settings, err := readSettingsHooks(path)+ if err != nil {+ return err+ }+ for eventName, group := range endpointHooks {+ settings.hooks[eventName] = mergeSettingsEndpointHook(settings.hooks[eventName], group, platform)+ }+ data, err := settings.marshal()+ if err != nil {+ return err+ }+ return os.WriteFile(path, data, 0600)+}++func mergeSettingsEndpointHook(existing []settingsHookGroup, group settingsHookGroup, platform string) []settingsHookGroup {+ out := make([]settingsHookGroup, 0, len(existing)+1)+ for _, item := range existing {+ filtered, changed := filterSettingsEndpointHooks(item, platform)+ if !changed || len(filtered.Hooks) > 0 {+ out = append(out, item)+ if changed {+ out[len(out)-1] = filtered+ }+ }+ }+ return append(out, group)+}++func removeSettingsEndpointHooks(path, platform string) (bool, error) {+ settings, err := readSettingsHooks(path)+ if err != nil {+ if os.IsNotExist(err) {+ return false, nil+ }+ return false, err+ }+ changed := false+ for eventName, groups := range settings.hooks {+ filtered := groups[:0]+ for _, group := range groups {+ withoutEndpointHooks, groupChanged := filterSettingsEndpointHooks(group, platform)+ if groupChanged {+ changed = true+ }+ if len(withoutEndpointHooks.Hooks) == 0 {+ continue+ }+ filtered = append(filtered, withoutEndpointHooks)+ }+ if len(filtered) == 0 {+ delete(settings.hooks, eventName)+ } else {+ settings.hooks[eventName] = filtered+ }+ }+ if !changed {+ return false, nil+ }+ out, err := settings.marshal()+ if err != nil {+ return false, err+ }+ return true, os.WriteFile(path, out, 0600)+}++func filterSettingsEndpointHooks(group settingsHookGroup, platform string) (settingsHookGroup, bool) {+ filtered := group+ filtered.Hooks = group.Hooks[:0]+ changed := false+ for _, hook := range group.Hooks {+ if isSettingsEndpointHookCommand(hook.Command, platform) {+ changed = true+ continue+ }+ filtered.Hooks = append(filtered.Hooks, hook)+ }+ return filtered, changed+}++func isSettingsEndpointHookGroup(group settingsHookGroup, platform string) bool {+ for _, hook := range group.Hooks {+ if isSettingsEndpointHookCommand(hook.Command, platform) {+ return true+ }+ }+ return false+}++func isSettingsEndpointHookCommand(command, platform string) bool {+ if platform != "" && !strings.Contains(command, "--platform "+platform) {+ return false+ }+ return isEndpointHookCommand(command, platform)+}++func isSettingsEndpointInstalledAt(path, platform string) bool {+ settings, err := readSettingsHooks(path)+ if err != nil {+ return false+ }+ for _, groups := range settings.hooks {+ for _, group := range groups {+ if isSettingsEndpointHookGroup(group, platform) {+ return true+ }+ }+ }+ return false+}