Skip to content

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

Install Muse Code endpoint hooks

Claudeed2deb2b5411
diff --git a/cli/beacon/internal/endpoint/hooks/muse.go b/cli/beacon/internal/endpoint/hooks/muse.go
new file mode 100644
index 00000000..f08e96c5
--- /dev/null
+++ b/cli/beacon/internal/endpoint/hooks/muse.go
@@ -0,0 +1,425 @@
+package hooks
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+)
+
+const (
+ // museManagedHookFileName is the file Beacon owns outright. It sits beside Muse Code's own
+ // settings.json rather than inside a Beacon directory because settings.json points at it by
+ // absolute path, and keeping the two together means a person reading their Muse config finds
+ // the hooks file next to the key that names it.
+ museManagedHookFileName = "beacon-endpoint-hooks.json"
+
+ // museManagedHookMarker stamps the file as Beacon's. Muse tolerates unknown keys at the top
+ // level of a managed hooks file -- and only there -- so this is the one place a marker can go.
+ museManagedHookMarker = "beacon-managed-muse-hooks:v1"
+
+ // museSettingsFileName is Muse Code's own settings file, which Beacon edits by exactly one key.
+ museSettingsFileName = "settings.json"
+
+ // museManagedHooksKey is that key. It takes a path, not a boolean and not a set of hooks:
+ // inline `hooks` in settings.json did not fire in testing, and only the managed file did.
+ museManagedHooksKey = "managed_hooks_path"
+)
+
+// Muse Code hook timeouts are seconds.
+//
+// Stated at the value rather than left to a reader, for the reason the Qwen constants above spell
+// out: the same `timeout` field means milliseconds on Qwen and seconds here, the two settings files
+// look alike, and getting it wrong kills every hook mid-write while the install still reports
+// success. Seconds here is measured, not assumed -- a hook sleeping 3s under `timeout: 1` was
+// killed at about 1s wall.
+//
+// Events with no entry inherit the host default, which is the right answer for the ones that only
+// append a line.
+const (
+ musePromptSubmitTimeoutSeconds = 30
+ museToolTimeoutSeconds = 10
+ museStopTimeoutSeconds = 45
+)
+
+// museAllEventsMatcher matches every event in a group.
+//
+// The matcher is optional -- a group without one still fires -- but it is an accepted key, and the
+// nesting it sits on is not optional at all: handlers listed directly under an event name, or event
+// names hoisted out of the `hooks` wrapper, are both ignored in total silence. Writing the matcher
+// keeps the shape of what Beacon emits identical to the shape that was verified to fire.
+const museAllEventsMatcher = "*"
+
+type MuseOptions struct {
+ Level Level
+ LogPath string
+ UserMode bool
+}
+
+type MuseStatus struct {
+ Installed bool `json:"installed"`
+ BinaryPath string `json:"binary_path,omitempty"`
+ HooksPath string `json:"hooks_path,omitempty"`
+ SettingsPath string `json:"settings_path,omitempty"`
+ Message string `json:"message,omitempty"`
+}
+
+// museHooksFile is the managed hooks file, typed to exactly the keys Muse accepts.
+//
+// Deliberately its own types rather than the shared settingsHook* ones, and this is a safety
+// property rather than tidiness. Muse deserializes matcher groups and handler objects strictly, and
+// a rejection is silent: one unrecognized key and that whole event is skipped while the rest of the
+// file keeps working, with no warning, no exit code and no log line. `env`, `shell` and a group's
+// `enabled` are all confirmed rejections. The shared settingsHookRef carries `shell` and
+// `show_output` -- both omitted today, so both harmless today -- but a field added there for
+// another runtime would silently remove one event's worth of Muse monitoring and leave the install
+// looking healthy. Types that cannot express a key Muse rejects are what stops that.
+type museHooksFile struct {
+ Description string `json:"description,omitempty"`
+ Beacon string `json:"beacon,omitempty"`
+ // SchemaVersion is optional -- a file without it fires -- and is written because it costs
+ // nothing and documents which shape this file is.
+ SchemaVersion int `json:"schema_version,omitempty"`
+ Hooks map[string][]museHookGroup `json:"hooks"`
+}
+
+type museHookGroup struct {
+ Matcher string `json:"matcher,omitempty"`
+ Hooks []museHookRef `json:"hooks"`
+}
+
+// museHookRef holds only accepted handler keys: type, command, timeout, statusMessage. The
+// remaining accepted keys -- commandWindows, silent, async -- are not written. commandWindows in
+// particular has nothing to carry: Muse Code ships for macOS and Linux only, so there is no Windows
+// host to hook.
+type museHookRef struct {
+ Type string `json:"type"`
+ Command string `json:"command"`
+ Timeout int `json:"timeout,omitempty"`
+ StatusMessage string `json:"statusMessage,omitempty"`
+}
+
+var museRuntime = hookRuntime{
+ displayName: "Muse Code",
+ configPath: museHooksPath,
+ install: installMuseHooks,
+ uninstall: removeMuseHooks,
+ isInstalled: isMuseInstalledAt,
+}
+
+func InstallMuse(opts MuseOptions) (MuseStatus, error) {
+ status, err := installRuntimeHooks(museRuntime, RuntimeOptions(opts))
+ if err != nil {
+ return MuseStatus{}, err
+ }
+ return museStatusFromRuntime(status), nil
+}
+
+func UninstallMuse(opts MuseOptions) (MuseStatus, error) {
+ status, err := uninstallRuntimeHooks(museRuntime, RuntimeOptions(opts))
+ if err != nil {
+ return MuseStatus{}, err
+ }
+ return museStatusFromRuntime(status), nil
+}
+
+func MuseHookStatus(opts MuseOptions) MuseStatus {
+ return museStatusFromRuntime(runtimeHookStatus(museRuntime, RuntimeOptions(opts)))
+}
+
+func IsMuseInstalled(opts MuseOptions) bool {
+ return isRuntimeInstalled(museRuntime, RuntimeOptions(opts))
+}
+
+func museStatusFromRuntime(status runtimeStatus) MuseStatus {
+ out := MuseStatus{
+ Installed: status.Installed,
+ BinaryPath: status.BinaryPath,
+ HooksPath: status.ConfigPath,
+ Message: status.Message,
+ }
+ if status.ConfigPath != "" {
+ out.SettingsPath = museSettingsPathForHooks(status.ConfigPath)
+ }
+ return out
+}
+
+// installMuseHooks writes Beacon's managed hooks file and points Muse's settings.json at it.
+//
+// Two files, in that order, because the second is what makes the first take effect and a
+// settings.json naming a file that does not exist yet is a window where Muse silently finds
+// nothing.
+func installMuseHooks(path, binaryPath, logPath, configPath string) error {
+ settingsPath := museSettingsPathForHooks(path)
+ // Checked before anything is written. Muse reads exactly one managed hooks file, so pointing
+ // the key at Beacon's would disable whatever the existing one registered -- and disable it the
+ // way Muse does everything, without a word. Refusing is the only answer that cannot silently
+ // take someone's hooks away; overwriting would look like a clean install and quietly end their
+ // monitoring.
+ if err := museManagedHooksPathIsFree(settingsPath, path); err != nil {
+ return err
+ }
+
+ prefix := endpointCommandPrefix("muse", binaryPath, logPath, configPath)
+ command := func(subcommand string, timeout int) []museHookRef {
+ return []museHookRef{{
+ Type: "command",
+ Command: prefix + " " + subcommand,
+ Timeout: timeout,
+ StatusMessage: "Beacon endpoint telemetry",
+ }}
+ }
+ group := func(subcommand string, timeout int) []museHookGroup {
+ return []museHookGroup{{Matcher: museAllEventsMatcher, Hooks: command(subcommand, timeout)}}
+ }
+
+ hooks := museHooksFile{
+ Description: "Beacon managed Muse Code endpoint telemetry hooks.",
+ Beacon: museManagedHookMarker,
+ SchemaVersion: 1,
+ Hooks: map[string][]museHookGroup{
+ "SessionStart": group("session-start", 0),
+ "UserPromptSubmit": group("prompt-submit", musePromptSubmitTimeoutSeconds),
+ "PreToolUse": group("pre-tool", museToolTimeoutSeconds),
+ "PermissionRequest": group("permission-request", museToolTimeoutSeconds),
+ "PostToolUse": group("post-tool", museToolTimeoutSeconds),
+ "PreCompact": group("pre-compact", 0),
+ "PostCompact": group("post-compact", 0),
+ "SubagentStart": group("subagent-start", 0),
+ "SubagentStop": group("subagent-stop", 0),
+ "Stop": group("stop", museStopTimeoutSeconds),
+ // PreLLMCall and PostLLMCall are deliberately absent, and their absence is the
+ // privacy decision rather than an oversight. Both carry the full `messages` array and
+ // the tool schemas -- the entire conversation on every model call, not a preview -- so
+ // subscribing would ship far more content to the endpoint log than the prompt and tool
+ // arguments Beacon already retains, for signal it mostly already has. PostLLMCall is
+ // also expected to fire per response chunk, which makes it the highest-volume event
+ // Muse emits by a wide margin. UserPromptSubmit already captures prompt text under the
+ // usual retention and redaction controls.
+ },
+ }
+ data, err := json.MarshalIndent(hooks, "", " ")
+ if err != nil {
+ return err
+ }
+ if err := os.WriteFile(path, data, 0644); err != nil {
+ return err
+ }
+ return setMuseManagedHooksPath(settingsPath, path)
+}
+
+// museManagedHooksPathIsFree reports whether Beacon may claim the managed_hooks_path key.
+//
+// Free means one of: no settings file, no key, an empty key, or a key that already names Beacon's
+// own file. Anything else belongs to somebody and this returns an error naming it, because the
+// alternative is taking over a slot whose previous occupant then stops running with no diagnostic
+// anywhere.
+func museManagedHooksPathIsFree(settingsPath, hooksPath string) error {
+ settings, err := readMuseSettings(settingsPath)
+ if err != nil {
+ return err
+ }
+ existing := museManagedHooksPathValue(settings)
+ if existing == "" || sameFilePath(existing, hooksPath) {
+ return nil
+ }
+ return fmt.Errorf(
+ "Muse Code already registers a managed hooks file at %s; Muse reads only one, so Beacon "+
+ "will not replace it. Merge Beacon's hooks into that file, or clear %q in %s and run "+
+ "the install again",
+ existing, museManagedHooksKey, settingsPath)
+}
+
+// setMuseManagedHooksPath rewrites settings.json with the key set, preserving every other key.
+//
+// Decoded into json.RawMessage rather than a typed struct so that settings Beacon has never heard
+// of survive the round trip byte for byte. A user's Muse configuration is theirs; Beacon is a guest
+// in this file and edits one key of it.
+func setMuseManagedHooksPath(settingsPath, hooksPath string) error {
+ settings, err := readMuseSettings(settingsPath)
+ if err != nil {
+ return err
+ }
+ encoded, err := json.Marshal(hooksPath)
+ if err != nil {
+ return err
+ }
+ settings[museManagedHooksKey] = encoded
+ data, err := json.MarshalIndent(settings, "", " ")
+ if err != nil {
+ return err
+ }
+ if err := os.MkdirAll(filepath.Dir(settingsPath), 0755); err != nil {
+ return err
+ }
+ return os.WriteFile(settingsPath, data, 0600)
+}
+
+func readMuseSettings(path string) (map[string]json.RawMessage, error) {
+ settings := map[string]json.RawMessage{}
+ data, err := os.ReadFile(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return settings, nil
+ }
+ return nil, err
+ }
+ // An empty file is not malformed JSON to a person, and treating it as an error would make
+ // `install` fail on a settings.json somebody had touched but not written.
+ if len(data) == 0 {
+ return settings, nil
+ }
+ if err := json.Unmarshal(data, &settings); err != nil {
+ return nil, fmt.Errorf("read %s: %w", path, err)
+ }
+ return settings, nil
+}
+
+func museManagedHooksPathValue(settings map[string]json.RawMessage) string {
+ raw, ok := settings[museManagedHooksKey]
+ if !ok {
+ return ""
+ }
+ var value string
+ if err := json.Unmarshal(raw, &value); err != nil {
+ return ""
+ }
+ return value
+}
+
+// removeMuseHooks deletes Beacon's hooks file and releases the settings key it claimed.
+//
+// The key is cleared only when it still names Beacon's file. If something else has claimed it since
+// the install, that is now somebody's live registration and deleting it would break their hooks on
+// the way out -- an uninstall may remove what it added and nothing more.
+func removeMuseHooks(path string) (bool, error) {
+ settingsPath := museSettingsPathForHooks(path)
+ changed := false
+
+ settings, err := readMuseSettings(settingsPath)
+ if err != nil {
+ return false, err
+ }
+ if sameFilePath(museManagedHooksPathValue(settings), path) {
+ delete(settings, museManagedHooksKey)
+ data, err := json.MarshalIndent(settings, "", " ")
+ if err != nil {
+ return false, err
+ }
+ if err := os.WriteFile(settingsPath, data, 0600); err != nil {
+ return false, err
+ }
+ changed = true
+ }
+
+ data, err := os.ReadFile(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return changed, nil
+ }
+ return changed, err
+ }
+ if !isMuseManagedHookFile(data) {
+ return changed, nil
+ }
+ if err := os.Remove(path); err != nil {
+ return changed, err
+ }
+ return true, nil
+}
+
+// isMuseInstalledAt requires both halves, because either alone is a broken install that would
+// report as working.
+//
+// A hooks file with no settings key is a file Muse never reads. A settings key pointing at a file
+// that is missing or is not Beacon's is a registration with nothing behind it. Muse gives no
+// feedback in either case, so a status that checked one half would confidently report telemetry
+// that is not being collected.
+func isMuseInstalledAt(path string) bool {
+ data, err := os.ReadFile(path)
+ if err != nil || !isMuseManagedHookFile(data) {
+ return false
+ }
+ settings, err := readMuseSettings(museSettingsPathForHooks(path))
+ if err != nil {
+ return false
+ }
+ return sameFilePath(museManagedHooksPathValue(settings), path)
+}
+
+func isMuseManagedHookFile(data []byte) bool {
+ var hooks museHooksFile
+ if err := json.Unmarshal(data, &hooks); err != nil {
+ return false
+ }
+ if hooks.Beacon != museManagedHookMarker {
+ return false
+ }
+ for _, groups := range hooks.Hooks {
+ for _, group := range groups {
+ for _, hook := range group.Hooks {
+ if isEndpointHookCommand(hook.Command, "muse") {
+ return true
+ }
+ }
+ }
+ }
+ return false
+}
+
+// sameFilePath compares two configured paths for identity.
+//
+// Cleaned rather than resolved through the filesystem: this has to answer the same way for a path
+// that does not exist yet, which is exactly the case during install and immediately after
+// uninstall. filepath.Clean collapses the differences a hand-edited settings file plausibly carries
+// -- a trailing separator, a doubled one, an interior "." -- and leaves anything more exotic
+// looking like a different path, which is the safe direction: Beacon then declines to touch it.
+func sameFilePath(a, b string) bool {
+ if a == "" || b == "" {
+ return false
+ }
+ return filepath.Clean(a) == filepath.Clean(b)
+}
+
+func museSettingsPathForHooks(hooksPath string) string {
+ return filepath.Join(filepath.Dir(hooksPath), museSettingsFileName)
+}
+
+func museHooksPath(level Level) (string, error) {
+ dir, err := museConfigDir(level)
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(dir, museManagedHookFileName), nil
+}
+
+// museConfigDir resolves the directory Muse Code keeps settings.json in.
+//
+// User scope only, and the project case is an error rather than a second path. Muse documents a
+// project-level `.muse/hooks.json`, but the shipping build ignores it silently -- so a project
+// install would create a file, report success, and collect nothing, which is worse than refusing.
+// The error says which scope works instead.
+//
+// XDG_CONFIG_HOME takes precedence, matching how Muse itself resolves the directory. Worth noting
+// for anyone debugging a live install: the variable is stripped from the environment Muse hands to
+// hook commands, so a hook cannot resolve this path the same way -- which is why Beacon passes the
+// log and config locations to the hook as flags rather than expecting it to find them.
+func museConfigDir(level Level) (string, error) {
+ switch level {
+ case "", LevelUser:
+ if base := os.Getenv("XDG_CONFIG_HOME"); base != "" {
+ return filepath.Join(base, "muse"), nil
+ }
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(home, ".config", "muse"), nil
+ case LevelProject:
+ return "", fmt.Errorf(
+ "Muse Code has no working project-level hook registration -- its project .muse/hooks.json " +
+ "is ignored by the shipping build -- so install Muse hooks at user scope instead")
+ default:
+ return "", fmt.Errorf("unknown hook level %q", level)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/hooks/muse_test.go b/cli/beacon/internal/endpoint/hooks/muse_test.go
new file mode 100644
index 00000000..17ec56a8
--- /dev/null
+++ b/cli/beacon/internal/endpoint/hooks/muse_test.go
@@ -0,0 +1,552 @@
+package hooks
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+)
+
+// museInstallDir sets up a temp Muse config directory and returns the managed hooks path Beacon
+// would write into it. XDG_CONFIG_HOME is cleared as well as HOME because museConfigDir prefers it,
+// and a developer with it set would otherwise have these tests resolve outside the temp directory.
+func museInstallDir(t *testing.T) string {
+ t.Helper()
+ home := t.TempDir()
+ testenv.SetHome(t, home)
+ t.Setenv("XDG_CONFIG_HOME", "")
+ dir := filepath.Join(home, ".config", "muse")
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatalf("create Muse config dir: %v", err)
+ }
+ return filepath.Join(dir, museManagedHookFileName)
+}
+
+func readMuseHooksFile(t *testing.T, path string) museHooksFile {
+ t.Helper()
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read Muse hooks: %v", err)
+ }
+ var hooks museHooksFile
+ if err := json.Unmarshal(data, &hooks); err != nil {
+ t.Fatalf("decode Muse hooks: %v", err)
+ }
+ return hooks
+}
+
+// Every non-LLM event Muse emits gets a hook, and each carries the endpoint settings as flags. The
+// event names are the wire contract: a typo in one of them is not an error, it is that event
+// silently never firing.
+func TestInstallMuseHooksBindsEveryNonLLMEvent(t *testing.T) {
+ path := museInstallDir(t)
+ if err := installMuseHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatalf("installMuseHooks returned error: %v", err)
+ }
+
+ hooks := readMuseHooksFile(t, path)
+ if hooks.Beacon != museManagedHookMarker {
+ t.Fatalf("managed marker = %q, want %q", hooks.Beacon, museManagedHookMarker)
+ }
+ wantCommands := map[string]string{
+ "SessionStart": "session-start",
+ "UserPromptSubmit": "prompt-submit",
+ "PreToolUse": "pre-tool",
+ "PermissionRequest": "permission-request",
+ "PostToolUse": "post-tool",
+ "PreCompact": "pre-compact",
+ "PostCompact": "post-compact",
+ "SubagentStart": "subagent-start",
+ "SubagentStop": "subagent-stop",
+ "Stop": "stop",
+ }
+ if len(hooks.Hooks) != len(wantCommands) {
+ t.Fatalf("bound %d events, want %d: %v", len(hooks.Hooks), len(wantCommands), hooks.Hooks)
+ }
+ for eventName, subcommand := range wantCommands {
+ groups := hooks.Hooks[eventName]
+ if len(groups) != 1 || len(groups[0].Hooks) != 1 {
+ t.Fatalf("%s hook shape = %#v, want one command hook", eventName, groups)
+ }
+ command := groups[0].Hooks[0].Command
+ for _, want := range []string{
+ "--platform muse",
+ "--log '/tmp/runtime.jsonl'",
+ "--config '/tmp/config.json'",
+ " " + subcommand,
+ } {
+ if !strings.Contains(command, want) {
+ t.Fatalf("%s command missing %q:\n%s", eventName, want, command)
+ }
+ }
+ if groups[0].Hooks[0].Type != "command" {
+ t.Fatalf("%s handler type = %q, want command", eventName, groups[0].Hooks[0].Type)
+ }
+ }
+}
+
+// The two model-call events are excluded on purpose. Both carry the full messages array and the
+// tool schemas -- the whole conversation on every model call -- and PostLLMCall is expected to fire
+// per response chunk. Subscribing to either would quietly turn a telemetry install into a full
+// transcript capture, so the exclusion is pinned rather than left to a reader of the map.
+func TestInstallMuseHooksDoesNotSubscribeToModelCallEvents(t *testing.T) {
+ path := museInstallDir(t)
+ if err := installMuseHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatalf("installMuseHooks returned error: %v", err)
+ }
+ hooks := readMuseHooksFile(t, path)
+ for _, event := range []string{"PreLLMCall", "PostLLMCall"} {
+ if _, ok := hooks.Hooks[event]; ok {
+ t.Fatalf("%s is bound; it carries the entire conversation on every model call", event)
+ }
+ }
+}
+
+// Muse reads `timeout` as seconds. The same field is milliseconds on Qwen and the two settings
+// files look alike, so this is the assertion that keeps a copy-paste from another installer from
+// turning every Muse timeout into a few milliseconds -- which kills each hook mid-write while the
+// install still reports success.
+func TestMuseTimeoutsAreSecondsNotMilliseconds(t *testing.T) {
+ path := museInstallDir(t)
+ if err := installMuseHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatalf("installMuseHooks returned error: %v", err)
+ }
+ hooks := readMuseHooksFile(t, path)
+ for event, want := range map[string]int{
+ "UserPromptSubmit": musePromptSubmitTimeoutSeconds,
+ "PreToolUse": museToolTimeoutSeconds,
+ "PermissionRequest": museToolTimeoutSeconds,
+ "PostToolUse": museToolTimeoutSeconds,
+ "Stop": museStopTimeoutSeconds,
+ } {
+ got := hooks.Hooks[event][0].Hooks[0].Timeout
+ if got != want {
+ t.Fatalf("%s timeout = %d, want %d seconds", event, got, want)
+ }
+ if got > 300 {
+ t.Fatalf("%s timeout = %d; that is a milliseconds value in a seconds field", event, got)
+ }
+ }
+}
+
+// Muse deserializes matcher groups and handler objects strictly and rejects a file with an
+// unrecognized key in either -- silently, skipping that whole event. This asserts on the emitted
+// JSON rather than on the Go types, because the types are only a way of producing this shape and it
+// is the shape Muse actually reads.
+func TestInstallMuseHooksEmitsOnlyAcceptedKeys(t *testing.T) {
+ path := museInstallDir(t)
+ if err := installMuseHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatalf("installMuseHooks returned error: %v", err)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read Muse hooks: %v", err)
+ }
+ var raw struct {
+ Hooks map[string][]map[string]json.RawMessage `json:"hooks"`
+ }
+ if err := json.Unmarshal(data, &raw); err != nil {
+ t.Fatalf("decode Muse hooks: %v", err)
+ }
+ acceptedGroupKeys := map[string]bool{"matcher": true, "hooks": true}
+ acceptedHandlerKeys := map[string]bool{
+ "type": true, "command": true, "commandWindows": true,
+ "timeout": true, "statusMessage": true, "silent": true, "async": true,
+ }
+ for event, groups := range raw.Hooks {
+ for _, group := range groups {
+ for key := range group {
+ if !acceptedGroupKeys[key] {
+ t.Fatalf("%s group carries key %q; Muse skips the whole event", event, key)
+ }
+ }
+ var handlers []map[string]json.RawMessage
+ if err := json.Unmarshal(group["hooks"], &handlers); err != nil {
+ t.Fatalf("%s handlers: %v", event, err)
+ }
+ for _, handler := range handlers {
+ for key := range handler {
+ if !acceptedHandlerKeys[key] {
+ t.Fatalf("%s handler carries key %q; Muse skips the whole event", event, key)
+ }
+ }
+ }
+ }
+ }
+}
+
+// The nesting is the part that fails silently when it is wrong: handlers listed directly under an
+// event name, or event names hoisted out of the `hooks` wrapper, produce a file Muse ignores
+// entirely with no warning, no exit code and no log line.
+func TestInstallMuseHooksKeepsTheMatcherGroupNesting(t *testing.T) {
+ path := museInstallDir(t)
+ if err := installMuseHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatalf("installMuseHooks returned error: %v", err)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read Muse hooks: %v", err)
+ }
+ var raw map[string]json.RawMessage
+ if err := json.Unmarshal(data, &raw); err != nil {
+ t.Fatalf("decode Muse hooks: %v", err)
+ }
+ if _, ok := raw["hooks"]; !ok {
+ t.Fatal("no `hooks` wrapper; Muse ignores the file in silence")
+ }
+ for _, event := range []string{"PreToolUse", "Stop"} {
+ if _, hoisted := raw[event]; hoisted {
+ t.Fatalf("%s is hoisted to the top level; Muse ignores the file in silence", event)
+ }
+ }
+ var groups []museHookGroup
+ if err := json.Unmarshal(mustNestedHooks(t, data)["PreToolUse"], &groups); err != nil {
+ t.Fatalf("PreToolUse is not a list of matcher groups: %v", err)
+ }
+ if len(groups) != 1 || groups[0].Matcher != museAllEventsMatcher || len(groups[0].Hooks) != 1 {
+ t.Fatalf("PreToolUse group = %#v, want one matcher group holding one handler", groups)
+ }
+}
+
+func mustNestedHooks(t *testing.T, data []byte) map[string]json.RawMessage {
+ t.Helper()
+ var raw struct {
+ Hooks map[string]json.RawMessage `json:"hooks"`
+ }
+ if err := json.Unmarshal(data, &raw); err != nil {
+ t.Fatalf("decode Muse hooks: %v", err)
+ }
+ return raw.Hooks
+}
+
+// Writing the hooks file is only half an install: Muse reads it because settings.json names it.
+// A hooks file with nothing pointing at it is a file Muse never opens.
+func TestInstallMuseHooksPointsSettingsAtTheManagedFile(t *testing.T) {
+ path := museInstallDir(t)
+ if err := installMuseHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatalf("installMuseHooks returned error: %v", err)
+ }
+ settings := readMuseSettingsForTest(t, museSettingsPathForHooks(path))
+ if got := museManagedHooksPathValue(settings); got != path {
+ t.Fatalf("%s = %q, want %q", museManagedHooksKey, got, path)
+ }
+ if !isMuseInstalledAt(path) {
+ t.Fatal("isMuseInstalledAt = false after a complete install")
+ }
+}
+
+func readMuseSettingsForTest(t *testing.T, path string) map[string]json.RawMessage {
+ t.Helper()
+ settings, err := readMuseSettings(path)
+ if err != nil {
+ t.Fatalf("read Muse settings: %v", err)
+ }
+ return settings
+}
+
+// Beacon is a guest in settings.json and edits one key of it. Anything else in the file -- including
+// settings Beacon has never heard of -- survives the round trip.
+func TestInstallMuseHooksPreservesOtherSettings(t *testing.T) {
+ path := museInstallDir(t)
+ settingsPath := museSettingsPathForHooks(path)
+ original := `{"telemetry":{"destination":"legacy"},"model":"muse-spark-1.3","unknown_future_key":[1,2,3]}`
+ if err := os.WriteFile(settingsPath, []byte(original), 0600); err != nil {
+ t.Fatalf("seed settings: %v", err)
+ }
+
+ if err := installMuseHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatalf("installMuseHooks returned error: %v", err)
+ }
+
+ settings := readMuseSettingsForTest(t, settingsPath)
+ for key, want := range map[string]string{
+ "telemetry": `{"destination":"legacy"}`,
+ "model": `"muse-spark-1.3"`,
+ "unknown_future_key": `[1,2,3]`,
+ } {
+ got, ok := settings[key]
+ if !ok {
+ t.Fatalf("%q was dropped from settings.json", key)
+ }
+ if strings.ReplaceAll(strings.ReplaceAll(string(got), " ", ""), "\n", "") != want {
+ t.Fatalf("%q = %s, want %s", key, got, want)
+ }
+ }
+}
+
+// Muse reads exactly one managed hooks file, so claiming the key when somebody else already holds
+// it would disable their registration -- and disable it the way Muse does everything, without a
+// word. Refusing is the only answer that cannot silently take someone's hooks away.
+func TestInstallMuseHooksRefusesToStealAnExistingRegistration(t *testing.T) {
+ path := museInstallDir(t)
+ settingsPath := museSettingsPathForHooks(path)
+ theirs := filepath.Join(filepath.Dir(path), "their-hooks.json")
+ if err := os.WriteFile(settingsPath, []byte(`{"`+museManagedHooksKey+`":"`+theirs+`"}`), 0600); err != nil {
+ t.Fatalf("seed settings: %v", err)
+ }
+
+ err := installMuseHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json")
+ if err == nil {
+ t.Fatal("installMuseHooks succeeded over somebody else's managed hooks registration")
+ }
+ if !strings.Contains(err.Error(), theirs) {
+ t.Fatalf("error does not name the existing registration: %v", err)
+ }
+ // Nothing is written when the check fails, so a refused install leaves no half-installed file
+ // behind for a later status to find.
+ if _, statErr := os.Stat(path); !os.IsNotExist(statErr) {
+ t.Fatalf("a refused install left a hooks file behind: %v", statErr)
+ }
+ settings := readMuseSettingsForTest(t, settingsPath)
+ if got := museManagedHooksPathValue(settings); got != theirs {
+ t.Fatalf("%s = %q, want the existing registration %q untouched", museManagedHooksKey, got, theirs)
+ }
+}
+
+// Re-running an install is not somebody else's registration. The key already names Beacon's file,
+// so a repair or an upgrade proceeds.
+func TestInstallMuseHooksIsIdempotent(t *testing.T) {
+ path := museInstallDir(t)
+ for i := range 2 {
+ if err := installMuseHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatalf("installMuseHooks run %d returned error: %v", i+1, err)
+ }
+ }
+ if !isMuseInstalledAt(path) {
+ t.Fatal("isMuseInstalledAt = false after two installs")
+ }
+ settings := readMuseSettingsForTest(t, museSettingsPathForHooks(path))
+ if got := museManagedHooksPathValue(settings); got != path {
+ t.Fatalf("%s = %q, want %q", museManagedHooksKey, got, path)
+ }
+}
+
+// An uninstall removes what it added and nothing more.
+func TestRemoveMuseHooksClearsBothHalves(t *testing.T) {
+ path := museInstallDir(t)
+ settingsPath := museSettingsPathForHooks(path)
+ if err := os.WriteFile(settingsPath, []byte(`{"model":"muse-spark-1.3"}`), 0600); err != nil {
+ t.Fatalf("seed settings: %v", err)
+ }
+ if err := installMuseHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatalf("installMuseHooks returned error: %v", err)
+ }
+
+ changed, err := removeMuseHooks(path)
+ if err != nil {
+ t.Fatalf("removeMuseHooks returned error: %v", err)
+ }
+ if !changed {
+ t.Fatal("removeMuseHooks reported no change after an install")
+ }
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatalf("managed hooks file survived uninstall: %v", err)
+ }
+ settings := readMuseSettingsForTest(t, settingsPath)
+ if _, ok := settings[museManagedHooksKey]; ok {
+ t.Fatal("uninstall left a managed_hooks_path pointing at a deleted file")
+ }
+ if _, ok := settings["model"]; !ok {
+ t.Fatal("uninstall dropped an unrelated setting")
+ }
+ if isMuseInstalledAt(path) {
+ t.Fatal("isMuseInstalledAt = true after uninstall")
+ }
+}
+
+// A hooks file Beacon did not write is not Beacon's to delete, whatever it is called.
+func TestRemoveMuseHooksLeavesAForeignFileAlone(t *testing.T) {
+ path := museInstallDir(t)
+ foreign := `{"schema_version":1,"hooks":{"Stop":[{"hooks":[{"type":"command","command":"echo keep"}]}]}}`
+ if err := os.WriteFile(path, []byte(foreign), 0644); err != nil {
+ t.Fatalf("write foreign hooks: %v", err)
+ }
+
+ changed, err := removeMuseHooks(path)
+ if err != nil {
+ t.Fatalf("removeMuseHooks returned error: %v", err)
+ }
+ if changed {
+ t.Fatal("removeMuseHooks deleted a file Beacon did not write")
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("foreign hooks file was removed: %v", err)
+ }
+ if string(data) != foreign {
+ t.Fatalf("foreign hooks file was rewritten:\n%s", data)
+ }
+}
+
+// If something else claimed the key after Beacon's install, that is now a live registration
+// belonging to somebody -- so the uninstall removes Beacon's own file and leaves the key alone.
+// Clearing it would break their hooks on the way out.
+func TestRemoveMuseHooksDoesNotClearSomebodyElsesRegistration(t *testing.T) {
+ path := museInstallDir(t)
+ settingsPath := museSettingsPathForHooks(path)
+ if err := installMuseHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatalf("installMuseHooks returned error: %v", err)
+ }
+ theirs := filepath.Join(filepath.Dir(path), "their-hooks.json")
+ if err := os.WriteFile(settingsPath, []byte(`{"`+museManagedHooksKey+`":"`+theirs+`"}`), 0600); err != nil {
+ t.Fatalf("reclaim settings: %v", err)
+ }
+
+ if _, err := removeMuseHooks(path); err != nil {
+ t.Fatalf("removeMuseHooks returned error: %v", err)
+ }
+ settings := readMuseSettingsForTest(t, settingsPath)
+ if got := museManagedHooksPathValue(settings); got != theirs {
+ t.Fatalf("%s = %q, want the newer registration %q left in place", museManagedHooksKey, got, theirs)
+ }
+}
+
+// Either half alone is a broken install that would otherwise report as working: a hooks file with
+// no settings key is never read, and a settings key with no file behind it registers nothing. Muse
+// gives no feedback in either case.
+func TestIsMuseInstalledRequiresBothHalves(t *testing.T) {
+ t.Run("hooks file without the settings key", func(t *testing.T) {
+ path := museInstallDir(t)
+ if err := installMuseHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatalf("installMuseHooks returned error: %v", err)
+ }
+ if err := os.WriteFile(museSettingsPathForHooks(path), []byte(`{}`), 0600); err != nil {
+ t.Fatalf("clear settings: %v", err)
+ }
+ if isMuseInstalledAt(path) {
+ t.Fatal("isMuseInstalledAt = true for a hooks file nothing points at")
+ }
+ })
+
+ t.Run("settings key without the hooks file", func(t *testing.T) {
+ path := museInstallDir(t)
+ if err := installMuseHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatalf("installMuseHooks returned error: %v", err)
+ }
+ if err := os.Remove(path); err != nil {
+ t.Fatalf("remove hooks file: %v", err)
+ }
+ if isMuseInstalledAt(path) {
+ t.Fatal("isMuseInstalledAt = true for a registration with nothing behind it")
+ }
+ })
+}
+
+// XDG_CONFIG_HOME wins, matching how Muse itself resolves the directory. A user who sets it and
+// gets an install under ~/.config/muse has a hooks file Muse never looks at.
+func TestMuseConfigDirPrefersXDGConfigHome(t *testing.T) {
+ home := t.TempDir()
+ testenv.SetHome(t, home)
+ xdg := filepath.Join(home, "xdg")
+ t.Setenv("XDG_CONFIG_HOME", xdg)
+
+ dir, err := museConfigDir(LevelUser)
+ if err != nil {
+ t.Fatalf("museConfigDir returned error: %v", err)
+ }
+ if want := filepath.Join(xdg, "muse"); dir != want {
+ t.Fatalf("museConfigDir = %q, want %q", dir, want)
+ }
+
+ t.Setenv("XDG_CONFIG_HOME", "")
+ dir, err = museConfigDir(LevelUser)
+ if err != nil {
+ t.Fatalf("museConfigDir returned error: %v", err)
+ }
+ if want := filepath.Join(home, ".config", "muse"); dir != want {
+ t.Fatalf("museConfigDir without XDG = %q, want %q", dir, want)
+ }
+}
+
+// An empty level means user scope, the same default every other runtime here uses.
+func TestMuseConfigDirDefaultsToUserScope(t *testing.T) {
+ home := t.TempDir()
+ testenv.SetHome(t, home)
+ t.Setenv("XDG_CONFIG_HOME", "")
+
+ empty, err := museConfigDir("")
+ if err != nil {
+ t.Fatalf("museConfigDir(\"\") returned error: %v", err)
+ }
+ user, err := museConfigDir(LevelUser)
+ if err != nil {
+ t.Fatalf("museConfigDir(user) returned error: %v", err)
+ }
+ if empty != user {
+ t.Fatalf("museConfigDir(\"\") = %q, want the user path %q", empty, user)
+ }
+}
+
+// Project scope is refused rather than quietly given a path. Muse's project .muse/hooks.json is
+// ignored by the shipping build, so a project install would create a file, report success and
+// collect nothing -- and the operator would have no way to tell that from a working one.
+func TestMuseConfigDirRefusesProjectScope(t *testing.T) {
+ _, err := museConfigDir(LevelProject)
+ if err == nil {
+ t.Fatal("museConfigDir(project) succeeded; a project install collects nothing")
+ }
+ if !strings.Contains(err.Error(), "user scope") {
+ t.Fatalf("error does not point at the scope that works: %v", err)
+ }
+}
+
+// A settings.json that is not valid JSON is reported, not silently replaced. Overwriting it would
+// destroy a configuration whose only problem might be a trailing comma.
+func TestInstallMuseHooksReportsMalformedSettings(t *testing.T) {
+ path := museInstallDir(t)
+ settingsPath := museSettingsPathForHooks(path)
+ if err := os.WriteFile(settingsPath, []byte(`{"model": "muse-spark-1.3",}`), 0600); err != nil {
+ t.Fatalf("seed settings: %v", err)
+ }
+
+ err := installMuseHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json")
+ if err == nil {
+ t.Fatal("installMuseHooks succeeded over a malformed settings.json")
+ }
+ if !strings.Contains(err.Error(), settingsPath) {
+ t.Fatalf("error does not name the file that could not be read: %v", err)
+ }
+}
+
+// An empty settings.json is a file somebody touched, not a broken one.
+func TestInstallMuseHooksAcceptsAnEmptySettingsFile(t *testing.T) {
+ path := museInstallDir(t)
+ settingsPath := museSettingsPathForHooks(path)
+ if err := os.WriteFile(settingsPath, nil, 0600); err != nil {
+ t.Fatalf("seed settings: %v", err)
+ }
+ if err := installMuseHooks(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatalf("installMuseHooks returned error on an empty settings.json: %v", err)
+ }
+ if !isMuseInstalledAt(path) {
+ t.Fatal("isMuseInstalledAt = false after installing over an empty settings.json")
+ }
+}
+
+// The path comparison has to answer for paths that do not exist yet -- which is every path during
+// an install and immediately after an uninstall -- so it compares cleaned strings rather than
+// resolving through the filesystem.
+func TestSameFilePathToleratesCosmeticDifferences(t *testing.T) {
+ for _, tc := range []struct{ a, b string }{
+ {"/config/muse/hooks.json", "/config/muse/hooks.json"},
+ {"/config/muse/hooks.json", "/config/muse//hooks.json"},
+ {"/config/muse/hooks.json", "/config/muse/./hooks.json"},
+ } {
+ if !sameFilePath(tc.a, tc.b) {
+ t.Errorf("sameFilePath(%q, %q) = false, want true", tc.a, tc.b)
+ }
+ }
+ for _, tc := range []struct{ a, b string }{
+ {"", "/config/muse/hooks.json"},
+ {"/config/muse/hooks.json", ""},
+ {"", ""},
+ {"/config/muse/hooks.json", "/config/muse/other.json"},
+ } {
+ if sameFilePath(tc.a, tc.b) {
+ t.Errorf("sameFilePath(%q, %q) = true, want false", tc.a, tc.b)
+ }
+ }
+}