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
Install OpenHands endpoint hooks
Claudea08fea0a8594
diff --git a/cli/beacon/internal/endpoint/hooks/openhands.go b/cli/beacon/internal/endpoint/hooks/openhands.gonew file mode 100644index 00000000..f206510b--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/openhands.go@@ -0,0 +1,474 @@+package hooks++import (+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "sort"+ "strings"+)++// OpenHands registers hooks in one file, `.openhands/hooks.json`, which the runtime reads directly+// and which is also where a user keeps their own hooks. Beacon is a guest in it, so it merges its+// commands in and leaves everything else byte for byte -- unlike Muse Code, where Beacon owns a+// file outright because the runtime gave it one to own.+//+// The file is stricter than it looks, and every rule below is a rule the runtime enforces by+// silently dropping hooks rather than by reporting an error:+//+// - Its top level is the event map itself. HookConfig forbids extra fields, so one unrecognized+// top-level key fails validation and the whole file loads as nothing -- which rules out the+// marker key Beacon stamps on the files it owns elsewhere. Detection is by the hook command+// instead, which is the same thing every settings-file runtime already does.+//+// - A legacy wrapper form, `{"hooks": {...}}`, is also accepted, and the loader unwraps it by+// replacing the whole document with what is under that key. So adding a top-level event+// alongside an existing `hooks` wrapper does not merge -- it discards Beacon's hooks with a+// log line nobody sees. Beacon writes inside the wrapper when it finds one.+//+// - Event names may be snake_case or Claude Code's PascalCase, and providing both spellings of+// one event is a hard error that takes the entire file down, not just that event. So Beacon+// writes under whichever spelling the file already uses for an event and never introduces a+// second one.+//+// A file that already breaks one of these is refused rather than written into, because installing+// into it would report success and collect nothing.++const openHandsHookFileName = "hooks.json"++// openHandsHookName marks Beacon's hook definitions for a human reading the file.+//+// `name` is a documented HookDefinition field rather than an extra key, so it costs nothing and+// survives validation. It is deliberately not what uninstall and status match on: a user can edit+// it, and the command is what actually identifies a Beacon hook.+const openHandsHookName = "beacon-endpoint-telemetry"++// openHandsWrapperKey is the legacy Claude Code wrapper the loader unwraps the document into.+const openHandsWrapperKey = "hooks"++// openHandsAllToolsMatcher matches every tool.+//+// Required in spirit rather than in syntax: the matcher defaults to "*" when omitted, and the four+// events that are not tool-scoped ignore it entirely. Written on every group so the file says what+// it does instead of relying on a default.+const openHandsAllToolsMatcher = "*"++// OpenHands hook timeouts are seconds, and the runtime's own default is 60.+//+// Stated at the value for the reason the Qwen and Muse constants give: the same `timeout` field+// means milliseconds on Qwen and seconds here, and the two files look alike. Explicit values+// rather than the inherited default because 60 seconds is a long time to hold an agent turn for a+// telemetry hook that finishes in milliseconds -- these are ceilings on a hang, not budgets.+//+// The two long ones are long for a reason: prompt submission may run the inventory heartbeat, and+// the closing events flush cloud telemetry, which has a ten-second timeout of its own.+const (+ openHandsSessionStartTimeoutSeconds = 10+ openHandsPromptSubmitTimeoutSeconds = 30+ openHandsToolTimeoutSeconds = 10+ openHandsStopTimeoutSeconds = 45+ openHandsSessionEndTimeoutSeconds = 45+)++// openHandsEvent binds one OpenHands lifecycle event to the beacon-hooks subcommand that maps it.+//+// Both spellings of the event name are carried because both are accepted and only one of them may+// appear in a given file. The PascalCase alias is not written by Beacon on a fresh install -- the+// snake_case name is what the runtime's own writer emits and what its reference documents -- but+// it has to be recognized, because a hooks.json shared with Claude Code will use it.+type openHandsEvent struct {+ snakeKey string+ pascalKey string+ subcommand string+ timeout int+}++// openHandsEvents are the six events OpenHands exposes, all six of which Beacon subscribes to.+//+// There is nothing left out here, unlike the Muse and Cline mappings: OpenHands sends no model-call+// event, no compaction event and no subagent event, so this is its whole surface. What that costs+// is recorded where it is felt rather than here -- no token usage, and no approval decisions.+var openHandsEvents = []openHandsEvent{+ {"session_start", "SessionStart", "session-start", openHandsSessionStartTimeoutSeconds},+ {"user_prompt_submit", "UserPromptSubmit", "prompt-submit", openHandsPromptSubmitTimeoutSeconds},+ {"pre_tool_use", "PreToolUse", "pre-tool", openHandsToolTimeoutSeconds},+ {"post_tool_use", "PostToolUse", "post-tool", openHandsToolTimeoutSeconds},+ {"stop", "Stop", "stop", openHandsStopTimeoutSeconds},+ {"session_end", "SessionEnd", "session-end", openHandsSessionEndTimeoutSeconds},+}++type OpenHandsOptions struct {+ Level Level+ LogPath string+ UserMode bool+}++type OpenHandsStatus struct {+ Installed bool `json:"installed"`+ BinaryPath string `json:"binary_path,omitempty"`+ HooksPath string `json:"hooks_path,omitempty"`+ Message string `json:"message,omitempty"`+}++// openHandsHookGroup is one matcher group: a tool pattern and the hooks it fires.+//+// Hooks are held as raw JSON rather than as a typed slice so that a user's own hook definition+// round-trips byte for byte. HookDefinition has nine fields across three hook types, two of which+// (prompt and agent hooks) Beacon never writes, and a typed slice would quietly rewrite a user's+// entry into whatever subset this struct happened to model.+type openHandsHookGroup struct {+ Matcher string `json:"matcher,omitempty"`+ Hooks []json.RawMessage `json:"hooks"`+}++// openHandsHookRef is a command hook definition, holding only the fields Beacon writes.+//+// `type` and `command` are the contract; `name` is the marker; `timeout` is the ceiling. The+// remaining accepted fields belong to hook types Beacon does not use -- prompt, system_prompt,+// tools, max_iterations -- and `async` is deliberately absent: an async hook is fire-and-forget+// with its stdout discarded, which would make the policy seam's deny unreachable on the one event+// that can block.+type openHandsHookRef struct {+ Type string `json:"type"`+ Name string `json:"name,omitempty"`+ Command string `json:"command"`+ Timeout int `json:"timeout,omitempty"`+}++// openHandsHooksFile is a parsed hooks.json, remembering the shape it arrived in.+//+// wrapped and the per-event key spellings are both load-bearing on write: putting the events back+// under the wrong shape is how a merge silently discards either Beacon's hooks or the user's.+type openHandsHooksFile struct {+ wrapped bool+ events map[string][]openHandsHookGroup+}++var openHandsRuntime = hookRuntime{+ displayName: "OpenHands",+ configPath: openHandsHooksPath,+ install: installOpenHandsHooks,+ uninstall: removeOpenHandsHooks,+ isInstalled: isOpenHandsInstalledAt,+}++func InstallOpenHands(opts OpenHandsOptions) (OpenHandsStatus, error) {+ status, err := installRuntimeHooks(openHandsRuntime, RuntimeOptions(opts))+ if err != nil {+ return OpenHandsStatus{}, err+ }+ return openHandsStatusFromRuntime(status), nil+}++func UninstallOpenHands(opts OpenHandsOptions) (OpenHandsStatus, error) {+ status, err := uninstallRuntimeHooks(openHandsRuntime, RuntimeOptions(opts))+ if err != nil {+ return OpenHandsStatus{}, err+ }+ return openHandsStatusFromRuntime(status), nil+}++func OpenHandsHookStatus(opts OpenHandsOptions) OpenHandsStatus {+ return openHandsStatusFromRuntime(runtimeHookStatus(openHandsRuntime, RuntimeOptions(opts)))+}++func IsOpenHandsInstalled(opts OpenHandsOptions) bool {+ return isRuntimeInstalled(openHandsRuntime, RuntimeOptions(opts))+}++func openHandsStatusFromRuntime(status runtimeStatus) OpenHandsStatus {+ return OpenHandsStatus{+ Installed: status.Installed,+ BinaryPath: status.BinaryPath,+ HooksPath: status.ConfigPath,+ Message: status.Message,+ }+}++// installOpenHandsHooks merges Beacon's six hooks into hooks.json, replacing any it wrote before.+func installOpenHandsHooks(path, binaryPath, logPath, configPath string) error {+ file, err := readOpenHandsHooks(path)+ if err != nil {+ return err+ }+ prefix := endpointCommandPrefix("openhands", binaryPath, logPath, configPath)+ for _, event := range openHandsEvents {+ key := file.keyForEvent(event)+ ref, err := json.Marshal(openHandsHookRef{+ Type: "command",+ Name: openHandsHookName,+ Command: prefix + " " + event.subcommand,+ Timeout: event.timeout,+ })+ if err != nil {+ return err+ }+ groups := removeOpenHandsGroupHooks(file.events[key])+ file.events[key] = append(groups, openHandsHookGroup{+ Matcher: openHandsAllToolsMatcher,+ Hooks: []json.RawMessage{ref},+ })+ }+ return writeOpenHandsHooks(path, file)+}++// keyForEvent returns the spelling this file already uses for an event, or the canonical+// snake_case name when the event is absent.+//+// Introducing a second spelling of an event the file already names is what this exists to prevent:+// the loader raises on a duplicate event and the entire file -- every hook in it, Beacon's and the+// user's -- loads as nothing.+func (file openHandsHooksFile) keyForEvent(event openHandsEvent) string {+ if _, ok := file.events[event.pascalKey]; ok {+ return event.pascalKey+ }+ return event.snakeKey+}++// readOpenHandsHooks parses hooks.json, or returns an empty file when there is none.+//+// A file that OpenHands itself would reject is an error rather than something to merge into.+// Beacon cannot fix it, and writing into it would report a successful install while the runtime+// went on loading nothing at all -- which is the failure mode this whole file is arranged against.+func readOpenHandsHooks(path string) (openHandsHooksFile, error) {+ file := openHandsHooksFile{events: map[string][]openHandsHookGroup{}}+ data, err := os.ReadFile(path)+ if err != nil {+ if os.IsNotExist(err) {+ return file, nil+ }+ return openHandsHooksFile{}, err+ }+ // An empty file is not malformed JSON to a person, and treating it as an error would make+ // install fail on a hooks.json somebody had created but not written.+ if len(strings.TrimSpace(string(data))) == 0 {+ return file, nil+ }+ var document map[string]json.RawMessage+ if err := json.Unmarshal(data, &document); err != nil {+ return openHandsHooksFile{}, fmt.Errorf("read %s: %w", path, err)+ }+ if wrapper, ok := document[openHandsWrapperKey]; ok {+ file.wrapped = true+ // The loader replaces the document with the wrapper's contents, so anything beside it is+ // already being dropped by OpenHands. Beacon reads only the wrapper for the same reason,+ // and leaves the siblings where they are rather than merging them in.+ document = map[string]json.RawMessage{}+ if err := json.Unmarshal(wrapper, &document); err != nil {+ return openHandsHooksFile{}, fmt.Errorf("read %s: %w", path, err)+ }+ }+ for key, raw := range document {+ var groups []openHandsHookGroup+ if err := json.Unmarshal(raw, &groups); err != nil {+ return openHandsHooksFile{}, fmt.Errorf("read %s: hook event %q: %w", path, key, err)+ }+ file.events[key] = groups+ }+ if err := validateOpenHandsEventKeys(path, file.events); err != nil {+ return openHandsHooksFile{}, err+ }+ return file, nil+}++// validateOpenHandsEventKeys refuses a hooks.json OpenHands would refuse.+//+// Two ways it can already be broken, both silent at runtime and both worse after an install than+// before it, because the install would look like it worked.+func validateOpenHandsEventKeys(path string, events map[string][]openHandsHookGroup) error {+ known := map[string]bool{}+ for _, event := range openHandsEvents {+ known[event.snakeKey] = true+ known[event.pascalKey] = true+ if _, snake := events[event.snakeKey]; snake {+ if _, pascal := events[event.pascalKey]; pascal && event.snakeKey != event.pascalKey {+ return fmt.Errorf(+ "%s names the same hook event twice, as %q and %q; OpenHands rejects the whole "++ "file when it does, so remove one spelling and run the install again",+ path, event.snakeKey, event.pascalKey)+ }+ }+ }+ unknown := []string{}+ for key := range events {+ if !known[key] {+ unknown = append(unknown, key)+ }+ }+ if len(unknown) > 0 {+ sort.Strings(unknown)+ return fmt.Errorf(+ "%s has hook events OpenHands does not accept (%s); it rejects the whole file rather "++ "than the unknown entry, so Beacon's hooks would never run. Remove them and run "++ "the install again",+ path, strings.Join(unknown, ", "))+ }+ return nil+}++// writeOpenHandsHooks serializes the file back in the shape it arrived in.+func writeOpenHandsHooks(path string, file openHandsHooksFile) error {+ var document any = file.events+ if file.wrapped {+ document = map[string]any{openHandsWrapperKey: file.events}+ }+ data, err := json.MarshalIndent(document, "", " ")+ if err != nil {+ return err+ }+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {+ return err+ }+ // 0644 rather than the 0600 the settings-file installers use: this is a project file that gets+ // committed and read by everyone working in the repository, and a mode only its author can read+ // would make the hooks stop working for the next person to check it out.+ return os.WriteFile(path, data, 0644)+}++// removeOpenHandsGroupHooks strips Beacon's hook definitions out of an event's matcher groups,+// dropping a group that has nothing left in it and keeping every other group untouched.+func removeOpenHandsGroupHooks(groups []openHandsHookGroup) []openHandsHookGroup {+ filtered := make([]openHandsHookGroup, 0, len(groups))+ for _, group := range groups {+ kept := make([]json.RawMessage, 0, len(group.Hooks))+ for _, hook := range group.Hooks {+ if isOpenHandsEndpointHook(hook) {+ continue+ }+ kept = append(kept, hook)+ }+ if len(kept) == 0 {+ continue+ }+ group.Hooks = kept+ filtered = append(filtered, group)+ }+ return filtered+}++// isOpenHandsEndpointHook reports whether one hook definition is one Beacon wrote.+//+// The command, not the name. `name` is a field a user can edit and a field another tool could+// happen to reuse, while the command carries the hook binary's path and `--platform openhands` --+// which is the same evidence every other runtime's detection uses, through the same predicate.+func isOpenHandsEndpointHook(raw json.RawMessage) bool {+ var ref struct {+ Command string `json:"command"`+ }+ if err := json.Unmarshal(raw, &ref); err != nil {+ return false+ }+ return isEndpointHookCommand(ref.Command, "openhands")+}++// removeOpenHandsHooks takes Beacon's hooks back out and leaves the user's in place.+//+// The file is deleted only when Beacon removed something and nothing at all is left, so an+// uninstall does not leave an empty hooks.json behind in somebody's repository. A file that still+// holds another tool's hooks is rewritten without Beacon's rather than removed.+func removeOpenHandsHooks(path string) (bool, error) {+ if _, err := os.Stat(path); os.IsNotExist(err) {+ return false, nil+ }+ file, err := readOpenHandsHooks(path)+ if err != nil {+ return false, err+ }+ // Counted rather than compared position by position: removeOpenHandsGroupHooks drops groups+ // that end up empty, so the filtered slice does not line up with the original by index and a+ // pairwise comparison would read one group against another.+ changed := false+ for key, groups := range file.events {+ filtered := removeOpenHandsGroupHooks(groups)+ if openHandsHookCount(filtered) != openHandsHookCount(groups) {+ changed = true+ }+ if len(filtered) == 0 {+ delete(file.events, key)+ continue+ }+ file.events[key] = filtered+ }+ if !changed {+ return false, nil+ }+ if len(file.events) == 0 {+ return true, os.Remove(path)+ }+ return true, writeOpenHandsHooks(path, file)+}++func openHandsHookCount(groups []openHandsHookGroup) int {+ total := 0+ for _, group := range groups {+ total += len(group.Hooks)+ }+ return total+}++func isOpenHandsInstalledAt(path string) bool {+ file, err := readOpenHandsHooks(path)+ if err != nil {+ return false+ }+ for _, groups := range file.events {+ for _, group := range groups {+ for _, hook := range group.Hooks {+ if isOpenHandsEndpointHook(hook) {+ return true+ }+ }+ }+ }+ return false+}++func openHandsHooksPath(level Level) (string, error) {+ dir, err := openHandsConfigDir(level)+ if err != nil {+ return "", err+ }+ return filepath.Join(dir, openHandsHookFileName), nil+}++// openHandsConfigDir resolves the directory holding hooks.json for a scope.+//+// Both scopes are real, and they are not equivalent -- which is the opposite of the Muse and+// Hermes situation, where the project scope does nothing at all.+//+// Project scope, `<cwd>/.openhands`, is the documented location and the one that works everywhere:+// Cloud, the CLI and the local GUI all read it, and the agent server reads only it.+//+// User scope, `~/.openhands`, is the SDK loader's second search location. It is a real path but a+// narrower one, and two things about it are worth knowing before choosing it: the loader takes the+// first location that exists rather than merging, so a repository with its own .openhands/hooks.json+// shadows it entirely; and the agent server, which is what the CLI and the GUI talk to, does not+// consult it at all. Beacon writes where it is told and says this in the docs rather than picking+// for the operator, because a user-scope install is exactly right for someone running the SDK+// directly and exactly wrong for someone running the packaged CLI.+//+// OH_PERSISTENCE_DIR takes precedence at user scope, matching how the SDK resolves it. Sandboxed+// and containerized setups redirect state onto a volume with it, and on a machine that sets it+// ~/.openhands is not where OpenHands looks.+func openHandsConfigDir(level Level) (string, error) {+ switch level {+ case "", LevelUser:+ if base := strings.TrimSpace(os.Getenv("OH_PERSISTENCE_DIR")); base != "" {+ return base, nil+ }+ home, err := os.UserHomeDir()+ if err != nil {+ return "", err+ }+ return filepath.Join(home, ".openhands"), nil+ case LevelProject:+ cwd, err := os.Getwd()+ if err != nil {+ return "", err+ }+ return filepath.Join(cwd, ".openhands"), nil+ default:+ return "", fmt.Errorf("unknown hook level %q", level)+ }+}diff --git a/cli/beacon/internal/endpoint/hooks/openhands_test.go b/cli/beacon/internal/endpoint/hooks/openhands_test.gonew file mode 100644index 00000000..b536e1df--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/openhands_test.go@@ -0,0 +1,577 @@+package hooks++import (+ "encoding/json"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"+)++// OpenHands is silent about a hooks.json it does not like: a file that fails validation is dropped+// with a log line the user never sees, and the agent goes on working with no hooks at all. Nothing+// in the runtime tells Beacon that an install stopped working, so these tests are what would.++// openHandsUserHooksPath points the user scope at a temp home and returns the path Beacon writes.+// OH_PERSISTENCE_DIR is cleared as well as HOME because openHandsConfigDir prefers it, and a+// developer with it set would otherwise have these tests resolve outside the temp directory.+func openHandsUserHooksPath(t *testing.T) string {+ t.Helper()+ home := t.TempDir()+ testenv.SetHome(t, home)+ t.Setenv("OH_PERSISTENCE_DIR", "")+ path, err := openHandsHooksPath(LevelUser)+ if err != nil {+ t.Fatalf("openHandsHooksPath: %v", err)+ }+ return path+}++func writeOpenHandsFixture(t *testing.T, path, body string) {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {+ t.Fatalf("create hooks dir: %v", err)+ }+ if err := os.WriteFile(path, []byte(body), 0644); err != nil {+ t.Fatalf("write hooks fixture: %v", err)+ }+}++func readOpenHandsDocument(t *testing.T, path string) map[string]json.RawMessage {+ t.Helper()+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read hooks.json: %v", err)+ }+ var document map[string]json.RawMessage+ if err := json.Unmarshal(data, &document); err != nil {+ t.Fatalf("decode hooks.json: %v", err)+ }+ return document+}++// openHandsCommands returns every hook command in the file, keyed by the event it is registered+// under, reading the document exactly as OpenHands does -- unwrapping a legacy wrapper first.+func openHandsCommands(t *testing.T, path string) map[string][]string {+ t.Helper()+ document := readOpenHandsDocument(t, path)+ if wrapper, ok := document[openHandsWrapperKey]; ok {+ document = map[string]json.RawMessage{}+ if err := json.Unmarshal(wrapper, &document); err != nil {+ t.Fatalf("decode hooks wrapper: %v", err)+ }+ }+ out := map[string][]string{}+ for key, raw := range document {+ var groups []struct {+ Matcher string `json:"matcher"`+ Hooks []struct {+ Command string `json:"command"`+ } `json:"hooks"`+ }+ if err := json.Unmarshal(raw, &groups); err != nil {+ t.Fatalf("decode hook event %q: %v", key, err)+ }+ for _, group := range groups {+ for _, hook := range group.Hooks {+ out[key] = append(out[key], hook.Command)+ }+ }+ }+ return out+}++func installOpenHandsFixture(t *testing.T, path string) {+ t.Helper()+ if err := installOpenHandsHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {+ t.Fatalf("installOpenHandsHooks returned error: %v", err)+ }+}++// ---------------------------------------------------------------------------+// Fresh install+// ---------------------------------------------------------------------------++// All six events OpenHands exposes get a hook, under the snake_case names its own writer emits.+// The event names are the wire contract: a typo in one is not an error, it is that event silently+// never firing.+func TestInstallOpenHandsBindsEveryEvent(t *testing.T) {+ path := openHandsUserHooksPath(t)+ installOpenHandsFixture(t, path)++ commands := openHandsCommands(t, path)+ wantSubcommands := map[string]string{+ "session_start": "session-start",+ "user_prompt_submit": "prompt-submit",+ "pre_tool_use": "pre-tool",+ "post_tool_use": "post-tool",+ "stop": "stop",+ "session_end": "session-end",+ }+ if len(commands) != len(wantSubcommands) {+ t.Fatalf("registered events = %v, want exactly %d", commands, len(wantSubcommands))+ }+ for event, subcommand := range wantSubcommands {+ got := commands[event]+ if len(got) != 1 {+ t.Fatalf("event %q has %d hooks, want exactly 1: %v", event, len(got), got)+ }+ if !strings.HasSuffix(got[0], " "+subcommand) {+ t.Errorf("event %q command = %q, want it to end in the %q subcommand", event, got[0], subcommand)+ }+ if !strings.Contains(got[0], "--platform openhands") {+ t.Errorf("event %q command = %q, want --platform openhands", event, got[0])+ }+ // The endpoint settings ride as flags rather than as an inline VAR=value prefix, so the+ // hook reads the right log and config wherever the runtime is running.+ for _, flag := range []string{"--log", "--config"} {+ if !strings.Contains(got[0], flag) {+ t.Errorf("event %q command = %q, want the %s flag", event, got[0], flag)+ }+ }+ }+}++// Every hook Beacon writes is a command hook with an explicit timeout and the marker name. The+// timeout matters: OpenHands defaults to 60 seconds, which is a long time to hold an agent turn+// for a hook that finishes in milliseconds.+func TestInstallOpenHandsWritesTypedCommandHooks(t *testing.T) {+ path := openHandsUserHooksPath(t)+ installOpenHandsFixture(t, path)++ document := readOpenHandsDocument(t, path)+ for _, event := range openHandsEvents {+ var groups []struct {+ Matcher string `json:"matcher"`+ Hooks []openHandsHookRef `json:"hooks"`+ }+ if err := json.Unmarshal(document[event.snakeKey], &groups); err != nil {+ t.Fatalf("decode %q: %v", event.snakeKey, err)+ }+ if len(groups) != 1 || len(groups[0].Hooks) != 1 {+ t.Fatalf("event %q shape = %#v, want one group with one hook", event.snakeKey, groups)+ }+ if groups[0].Matcher != openHandsAllToolsMatcher {+ t.Errorf("event %q matcher = %q, want %q", event.snakeKey, groups[0].Matcher, openHandsAllToolsMatcher)+ }+ hook := groups[0].Hooks[0]+ if hook.Type != "command" {+ t.Errorf("event %q type = %q, want command", event.snakeKey, hook.Type)+ }+ if hook.Name != openHandsHookName {+ t.Errorf("event %q name = %q, want %q", event.snakeKey, hook.Name, openHandsHookName)+ }+ if hook.Timeout != event.timeout {+ t.Errorf("event %q timeout = %d, want %d", event.snakeKey, hook.Timeout, event.timeout)+ }+ }+}++// An async hook is fire-and-forget with its stdout discarded, which would make the policy seam's+// deny unreachable on the one event that can block. Beacon never writes the key, and this is the+// record of why rather than an accident of the struct.+func TestInstallOpenHandsDoesNotWriteAsyncHooks(t *testing.T) {+ path := openHandsUserHooksPath(t)+ installOpenHandsFixture(t, path)++ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read hooks.json: %v", err)+ }+ if strings.Contains(string(data), "\"async\"") {+ t.Fatalf("hooks.json declares async hooks:\n%s", data)+ }+}++// hooks.json is a project file that gets committed and read by everyone working in the repository.+// A mode only its author can read would make the hooks stop working for the next checkout.+func TestInstallOpenHandsWritesAWorldReadableFile(t *testing.T) {+ if os.Getenv("GOOS") == "windows" {+ t.Skip("file modes are not meaningful on Windows")+ }+ path := openHandsUserHooksPath(t)+ installOpenHandsFixture(t, path)++ info, err := os.Stat(path)+ if err != nil {+ t.Fatalf("stat hooks.json: %v", err)+ }+ if perm := info.Mode().Perm(); perm&0044 == 0 {+ t.Fatalf("hooks.json mode = %v, want it readable by group and other", perm)+ }+}++// ---------------------------------------------------------------------------+// Merging+// ---------------------------------------------------------------------------++// hooks.json is where a user keeps their own hooks, so Beacon is a guest in it. An install that+// replaced the file would silently end whatever quality gate or block rule was registered there.+func TestInstallOpenHandsPreservesExistingHooks(t *testing.T) {+ path := openHandsUserHooksPath(t)+ writeOpenHandsFixture(t, path, `{+ "stop": [+ {"matcher": "*", "hooks": [{"command": ".openhands/hooks/on_stop.sh", "timeout": 120}]}+ ],+ "pre_tool_use": [+ {"matcher": "terminal", "hooks": [{"command": ".openhands/hooks/block_dangerous.sh", "timeout": 10}]}+ ]+}`)+ installOpenHandsFixture(t, path)++ commands := openHandsCommands(t, path)+ if !openHandsHasCommand(commands["stop"], ".openhands/hooks/on_stop.sh") {+ t.Fatalf("stop hooks = %v, want the user's on_stop.sh preserved", commands["stop"])+ }+ if !openHandsHasCommand(commands["pre_tool_use"], ".openhands/hooks/block_dangerous.sh") {+ t.Fatalf("pre_tool_use hooks = %v, want the user's block_dangerous.sh preserved", commands["pre_tool_use"])+ }+ for _, event := range []string{"stop", "pre_tool_use"} {+ if !openHandsHasBeaconCommand(commands[event]) {+ t.Fatalf("%s hooks = %v, want Beacon's hook alongside the user's", event, commands[event])+ }+ }+ // The user's own timeout and matcher survive: Beacon appends a group rather than rewriting one.+ document := readOpenHandsDocument(t, path)+ if !strings.Contains(string(document["pre_tool_use"]), `"matcher": "terminal"`) {+ t.Fatalf("pre_tool_use = %s, want the user's terminal matcher untouched", document["pre_tool_use"])+ }+}++// Re-running the install replaces Beacon's own hooks rather than adding a second copy, so a repair+// does not end with the binary firing twice per event.+func TestInstallOpenHandsIsIdempotent(t *testing.T) {+ path := openHandsUserHooksPath(t)+ installOpenHandsFixture(t, path)+ installOpenHandsFixture(t, path)+ installOpenHandsFixture(t, path)++ for event, commands := range openHandsCommands(t, path) {+ if len(commands) != 1 {+ t.Fatalf("event %q has %d hooks after three installs, want 1: %v", event, len(commands), commands)+ }+ }+}++// The loader unwraps `{"hooks": {...}}` by replacing the whole document with what is under that+// key. Adding a top-level event beside the wrapper does not merge -- it discards Beacon's hooks+// with a log line nobody sees -- so Beacon writes inside the wrapper when it finds one.+func TestInstallOpenHandsWritesInsideTheLegacyWrapper(t *testing.T) {+ path := openHandsUserHooksPath(t)+ writeOpenHandsFixture(t, path, `{+ "hooks": {+ "PreToolUse": [+ {"matcher": "terminal", "hooks": [{"command": ".openhands/hooks/block_dangerous.sh"}]}+ ]+ }+}`)+ installOpenHandsFixture(t, path)++ document := readOpenHandsDocument(t, path)+ if len(document) != 1 {+ t.Fatalf("document keys = %v, want only the hooks wrapper", document)+ }+ if _, ok := document[openHandsWrapperKey]; !ok {+ t.Fatalf("document = %v, want the wrapper preserved", document)+ }+ commands := openHandsCommands(t, path)+ if !openHandsHasBeaconCommand(commands["PreToolUse"]) {+ t.Fatalf("PreToolUse hooks = %v, want Beacon's hook inside the wrapper", commands["PreToolUse"])+ }+ if !openHandsHasCommand(commands["PreToolUse"], ".openhands/hooks/block_dangerous.sh") {+ t.Fatalf("PreToolUse hooks = %v, want the user's hook preserved", commands["PreToolUse"])+ }+}++// Providing both spellings of one event is a hard error that takes the entire file down, not just+// that event. Beacon writes under whichever spelling the file already uses and never introduces a+// second one -- which is why a Claude Code-shaped file keeps its PascalCase names.+func TestInstallOpenHandsFollowsTheExistingEventSpelling(t *testing.T) {+ path := openHandsUserHooksPath(t)+ writeOpenHandsFixture(t, path, `{+ "PreToolUse": [+ {"matcher": "terminal", "hooks": [{"command": ".openhands/hooks/block_dangerous.sh"}]}+ ],+ "SessionStart": []+}`)+ installOpenHandsFixture(t, path)++ document := readOpenHandsDocument(t, path)+ for _, pascal := range []string{"PreToolUse", "SessionStart"} {+ if _, ok := document[pascal]; !ok {+ t.Fatalf("document = %v, want %q kept", openHandsKeys(document), pascal)+ }+ }+ for _, snake := range []string{"pre_tool_use", "session_start"} {+ if _, ok := document[snake]; ok {+ t.Fatalf("document = %v, want no second spelling %q", openHandsKeys(document), snake)+ }+ }+ // Events the file did not already name get the canonical snake_case spelling.+ if _, ok := document["post_tool_use"]; !ok {+ t.Fatalf("document = %v, want post_tool_use under the canonical name", openHandsKeys(document))+ }+ commands := openHandsCommands(t, path)+ if !openHandsHasBeaconCommand(commands["PreToolUse"]) {+ t.Fatalf("PreToolUse hooks = %v, want Beacon's hook under the existing spelling", commands["PreToolUse"])+ }+}++// ---------------------------------------------------------------------------+// Refusing a file the runtime would reject+// ---------------------------------------------------------------------------++// A file naming one event twice already fails to load, taking every hook in it down with it.+// Installing into it would report success while the runtime went on loading nothing at all.+func TestInstallOpenHandsRefusesDuplicateEventSpellings(t *testing.T) {+ path := openHandsUserHooksPath(t)+ writeOpenHandsFixture(t, path, `{+ "PreToolUse": [{"matcher": "*", "hooks": [{"command": "a.sh"}]}],+ "pre_tool_use": [{"matcher": "*", "hooks": [{"command": "b.sh"}]}]+}`)++ err := installOpenHandsHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json")+ if err == nil {+ t.Fatal("installOpenHandsHooks succeeded on a file OpenHands rejects")+ }+ if !strings.Contains(err.Error(), "twice") {+ t.Fatalf("error = %v, want it to name the duplicated event", err)+ }+ // The file is left exactly as it was: Beacon cannot fix it and must not half-rewrite it.+ commands := openHandsCommands(t, path)+ if openHandsHasBeaconCommand(commands["PreToolUse"]) || openHandsHasBeaconCommand(commands["pre_tool_use"]) {+ t.Fatalf("hooks were written into a rejected file: %v", commands)+ }+}++// HookConfig forbids extra fields, so one unrecognized top-level key fails validation and the whole+// file loads as nothing.+func TestInstallOpenHandsRefusesUnknownEventKeys(t *testing.T) {+ path := openHandsUserHooksPath(t)+ writeOpenHandsFixture(t, path, `{+ "stop": [{"matcher": "*", "hooks": [{"command": "a.sh"}]}],+ "PreCompact": [{"matcher": "*", "hooks": [{"command": "b.sh"}]}]+}`)++ err := installOpenHandsHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json")+ if err == nil {+ t.Fatal("installOpenHandsHooks succeeded on a file OpenHands rejects")+ }+ if !strings.Contains(err.Error(), "PreCompact") {+ t.Fatalf("error = %v, want it to name the unaccepted event", err)+ }+}++func TestInstallOpenHandsRefusesMalformedJSON(t *testing.T) {+ path := openHandsUserHooksPath(t)+ writeOpenHandsFixture(t, path, `{"stop": [`)++ if err := installOpenHandsHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err == nil {+ t.Fatal("installOpenHandsHooks succeeded on malformed JSON")+ }+}++// An empty file is not malformed JSON to a person, and failing on one would make install fail on a+// hooks.json somebody had created but not written.+func TestInstallOpenHandsTreatsAnEmptyFileAsNoHooks(t *testing.T) {+ path := openHandsUserHooksPath(t)+ writeOpenHandsFixture(t, path, " \n")+ installOpenHandsFixture(t, path)++ if len(openHandsCommands(t, path)) != len(openHandsEvents) {+ t.Fatalf("commands = %v, want every event registered", openHandsCommands(t, path))+ }+}++// ---------------------------------------------------------------------------+// Status and uninstall+// ---------------------------------------------------------------------------++func TestOpenHandsInstalledDetectionMatchesTheCommand(t *testing.T) {+ path := openHandsUserHooksPath(t)+ if isOpenHandsInstalledAt(path) {+ t.Fatal("isOpenHandsInstalledAt = true before any install")+ }+ installOpenHandsFixture(t, path)+ if !isOpenHandsInstalledAt(path) {+ t.Fatal("isOpenHandsInstalledAt = false after install")+ }++ // A user's own hook is not Beacon's, however it is named.+ other := filepath.Join(t.TempDir(), "hooks.json")+ writeOpenHandsFixture(t, other, `{+ "stop": [{"matcher": "*", "hooks": [{"name": "beacon-endpoint-telemetry", "command": "./my_stop.sh"}]}]+}`)+ if isOpenHandsInstalledAt(other) {+ t.Fatal("isOpenHandsInstalledAt = true for a hook that only borrowed the marker name")+ }+}++// Uninstall removes what Beacon added and nothing more. A file that still holds another tool's+// hooks is rewritten without Beacon's rather than removed.+func TestUninstallOpenHandsLeavesOtherHooksInPlace(t *testing.T) {+ path := openHandsUserHooksPath(t)+ writeOpenHandsFixture(t, path, `{+ "stop": [{"matcher": "*", "hooks": [{"command": ".openhands/hooks/on_stop.sh", "timeout": 120}]}]+}`)+ installOpenHandsFixture(t, path)++ changed, err := removeOpenHandsHooks(path)+ if err != nil {+ t.Fatalf("removeOpenHandsHooks: %v", err)+ }+ if !changed {+ t.Fatal("removeOpenHandsHooks reported no change after an install")+ }+ if isOpenHandsInstalledAt(path) {+ t.Fatal("Beacon hooks survived the uninstall")+ }+ commands := openHandsCommands(t, path)+ if !openHandsHasCommand(commands["stop"], ".openhands/hooks/on_stop.sh") {+ t.Fatalf("stop hooks = %v, want the user's hook left in place", commands["stop"])+ }+ // The events Beacon added and nobody else used are gone rather than left as empty entries.+ if _, ok := commands["pre_tool_use"]; ok {+ t.Fatalf("commands = %v, want the events Beacon added removed entirely", commands)+ }+}++// An uninstall that emptied the file removes it, so nothing is left behind in somebody's+// repository. A file Beacon never touched is left alone and reported as no change.+func TestUninstallOpenHandsRemovesAFileItEmptied(t *testing.T) {+ path := openHandsUserHooksPath(t)+ installOpenHandsFixture(t, path)++ changed, err := removeOpenHandsHooks(path)+ if err != nil {+ t.Fatalf("removeOpenHandsHooks: %v", err)+ }+ if !changed {+ t.Fatal("removeOpenHandsHooks reported no change after an install")+ }+ if _, err := os.Stat(path); !os.IsNotExist(err) {+ t.Fatalf("hooks.json still exists after removing the only hooks in it: %v", err)+ }+}++func TestUninstallOpenHandsIsANoOpWhenNothingWasInstalled(t *testing.T) {+ path := openHandsUserHooksPath(t)++ changed, err := removeOpenHandsHooks(path)+ if err != nil {+ t.Fatalf("removeOpenHandsHooks on a missing file: %v", err)+ }+ if changed {+ t.Fatal("removeOpenHandsHooks reported a change with no file present")+ }++ writeOpenHandsFixture(t, path, `{"stop": [{"matcher": "*", "hooks": [{"command": "./mine.sh"}]}]}`)+ before, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read fixture: %v", err)+ }+ changed, err = removeOpenHandsHooks(path)+ if err != nil {+ t.Fatalf("removeOpenHandsHooks: %v", err)+ }+ if changed {+ t.Fatal("removeOpenHandsHooks reported a change for a file with no Beacon hooks")+ }+ after, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read fixture: %v", err)+ }+ if string(before) != string(after) {+ t.Fatalf("file was rewritten with no Beacon hooks to remove:\n%s\n%s", before, after)+ }+}++// ---------------------------------------------------------------------------+// Scopes+// ---------------------------------------------------------------------------++// Both scopes are real, which is the opposite of the Muse and Hermes situation where the project+// scope does nothing at all. Project scope is the documented location every host reads; user scope+// is the SDK loader's second search location.+func TestOpenHandsConfigDirResolvesBothScopes(t *testing.T) {+ home := t.TempDir()+ testenv.SetHome(t, home)+ t.Setenv("OH_PERSISTENCE_DIR", "")++ userDir, err := openHandsConfigDir(LevelUser)+ if err != nil {+ t.Fatalf("openHandsConfigDir(user): %v", err)+ }+ if want := filepath.Join(home, ".openhands"); userDir != want {+ t.Fatalf("user dir = %q, want %q", userDir, want)+ }+ // The empty level is the same as user scope, which is what an unset --level resolves to.+ defaultDir, err := openHandsConfigDir("")+ if err != nil {+ t.Fatalf("openHandsConfigDir(\"\"): %v", err)+ }+ if defaultDir != userDir {+ t.Fatalf("default dir = %q, want the user dir %q", defaultDir, userDir)+ }++ projectDir, err := openHandsConfigDir(LevelProject)+ if err != nil {+ t.Fatalf("openHandsConfigDir(project): %v", err)+ }+ cwd, err := os.Getwd()+ if err != nil {+ t.Fatalf("getwd: %v", err)+ }+ if want := filepath.Join(cwd, ".openhands"); projectDir != want {+ t.Fatalf("project dir = %q, want %q", projectDir, want)+ }++ if _, err := openHandsConfigDir("machine"); err == nil {+ t.Fatal("openHandsConfigDir accepted an unknown level")+ }+}++// Sandboxed and containerized setups redirect OpenHands state onto a volume with+// OH_PERSISTENCE_DIR, and on a machine that sets it ~/.openhands is not where OpenHands looks. An+// install that ignored it would write a file the runtime never reads.+func TestOpenHandsUserScopeHonorsThePersistenceDirEnv(t *testing.T) {+ testenv.SetHome(t, t.TempDir())+ persistence := t.TempDir()+ t.Setenv("OH_PERSISTENCE_DIR", persistence)++ path, err := openHandsHooksPath(LevelUser)+ if err != nil {+ t.Fatalf("openHandsHooksPath: %v", err)+ }+ if want := filepath.Join(persistence, openHandsHookFileName); path != want {+ t.Fatalf("hooks path = %q, want %q", path, want)+ }+}++func openHandsHasCommand(commands []string, want string) bool {+ for _, command := range commands {+ if strings.Contains(command, want) {+ return true+ }+ }+ return false+}++func openHandsHasBeaconCommand(commands []string) bool {+ for _, command := range commands {+ if isEndpointHookCommand(command, "openhands") {+ return true+ }+ }+ return false+}++func openHandsKeys(document map[string]json.RawMessage) []string {+ keys := make([]string, 0, len(document))+ for key := range document {+ keys = append(keys, key)+ }+ return keys+}