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
Map Muse Code hook events in beacon-hooks
Claudeb0a216087811
diff --git a/cli/beacon-hooks/cmd/compaction.go b/cli/beacon-hooks/cmd/compaction.gonew file mode 100644index 00000000..f5d7f675--- /dev/null+++ b/cli/beacon-hooks/cmd/compaction.go@@ -0,0 +1,51 @@+package cmd++import (+ "github.com/spf13/cobra"+)++// Context compaction, as two commands over one implementation.+//+// Shaped like subagent.go rather than like cursor-event: the runtime binds a distinct command per+// lifecycle event, so argv already says which event fired and the payload never has to be consulted+// to find out. That matters here because pre and post are the same payload plus a verb -- reading+// `hook_event_name` to tell them apart would make the mapping depend on a field whose spelling+// varies between runtimes, for a question the install already answered.+//+// Compaction is worth recording at all because it is the point where an agent's own history stops+// being a complete account of the session. An investigator reading a Muse Code session that+// compacted mid-run needs to see that the earlier turns were summarized away rather than never+// happening, and a `token.usage` drop across a compaction boundary is expected rather than+// anomalous.+var preCompactCmd = &cobra.Command{+ Use: "pre-compact",+ Short: "Record the start of context compaction",+ Run: func(cmd *cobra.Command, args []string) {+ runCompaction("session.compacting", "Context compaction started")+ },+}++var postCompactCmd = &cobra.Command{+ Use: "post-compact",+ Short: "Record the completion of context compaction",+ Run: func(cmd *cobra.Command, args []string) {+ runCompaction("session.compacted", "Context compaction completed")+ },+}++func init() {+ rootCmd.AddCommand(preCompactCmd)+ rootCmd.AddCommand(postCompactCmd)+}++func runCompaction(action, message string) {+ input, err := readStdinJSON()+ if err != nil {+ outputJSON(hookNoopResponse())+ return+ }+ sessionID := resolveSessionID(input, platformFlag)+ logger := newHookLogger("compaction", platformFlag, sessionID)+ emitHookEvent(logger, action, "session", "info", message, input, sessionFields(sessionID, input))+ outputJSON(hookNoopResponse())+}diff --git a/cli/beacon-hooks/cmd/endpoint_events.go b/cli/beacon-hooks/cmd/endpoint_events.goindex 49f705f4..9dd2aa14 100644--- a/cli/beacon-hooks/cmd/endpoint_events.go+++ b/cli/beacon-hooks/cmd/endpoint_events.go@@ -37,32 +37,42 @@ func emitInferredHookEvent(logger *logging.Logger, action, category, severity, memitHookEventWithFidelity(logger, action, category, severity, message, asymptoteobserve.FidelityInferred, input, fields)}+// rawPayloadKeys names the runtimes whose whole hook payload is kept under `raw.<key>`, and the+// key each one uses.+//+// These runtimes carry real signal with no endpoint-schema field of its own -- Qwen's+// `permission_mode` on every tool event, its `source` on SessionStart and the `context_usage` /+// `context_limit` / `input_tokens` trio on Stop; Muse Code's `turn_id`, which is the only per-turn+// boundary anything in its payload offers. Keeping the payload preserves them without inventing+// schema fields for one runtime. It is the whole event's own path through SanitizeMap, so raw is+// secret-redacted and string-limited like every other field, and it is the first thing dropped when+// an event exceeds the 64 KiB ceiling.+//+// A table rather than one `if` per runtime. The branches were identical apart from the key, so each+// new runtime copied the same three lines and the only thing distinguishing them was a string --+// which is data, and belongs in one. The Cascade entry is why this is keyed on the --platform value+// rather than derived from it: `devin-desktop` writes under `cascade`, so the key is not always the+// flag.+var rawPayloadKeys = map[string]string{+ "grok": "grok",+ "hermes": "hermes",+ "qwen": "qwen",+ "vscode": "vscode",+ "muse": "muse",+ "devin-desktop": "cascade",+}++func rawPayloadKey(platform string) string {+ return rawPayloadKeys[platform]+}+func emitHookEventWithFidelity(logger *logging.Logger, action, category, severity, message, fidelity string, input map[string]interface{}, fields map[string]interface{}) {if fields == nil {fields = map[string]interface{}{}}seedCursorCloudRunID(input)- if platformFlag == "grok" {- fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{"grok": input})- }- if platformFlag == "hermes" {- fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{"hermes": input})- }- // Qwen carries real signal with no endpoint-schema field of its own: `permission_mode` on every- // tool event, `source` on SessionStart, `stop_hook_active` and the `context_usage` /- // `context_limit` / `input_tokens` trio on Stop, and the verbatim `tool_use_id` whose promoted- // form is the join key applyToolCallID writes just below. Keeping the payload under `raw.qwen`- // preserves it without inventing schema fields for one runtime. It is the whole event's own path- // through SanitizeMap, so raw is secret-redacted and string-limited like every other field, and- // it is the first thing dropped when an event exceeds the 64 KiB ceiling.- if platformFlag == "qwen" {- fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{"qwen": input})- }- if platformFlag == "vscode" {- fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{"vscode": input})- }- if isCascadePlatform(platformFlag) {- fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{"cascade": input})+ if key := rawPayloadKey(platformFlag); key != "" {+ fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{key: input})}applyToolCallID(fields, input)if model := getFirstStr(input, "model"); model != "" {diff --git a/cli/beacon-hooks/cmd/muse_hooks_test.go b/cli/beacon-hooks/cmd/muse_hooks_test.gonew file mode 100644index 00000000..261b8450--- /dev/null+++ b/cli/beacon-hooks/cmd/muse_hooks_test.go@@ -0,0 +1,469 @@+package cmd++import (+ "path/filepath"+ "testing"++ "github.com/spf13/cobra"++ hookconfig "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/policycontract"+)++// Muse Code's hook payloads are the Claude Code shape: snake_case base fields, `tool_name` /+// `tool_input` / `tool_response`, `cwd`, `session_id`. Most of the adapter therefore needs no+// Muse-specific reader -- the default branches already do the right thing.+//+// These tests exist because that is a claim about Muse's contract rather than an accident of the+// code, and because the contract itself was recovered by measurement against a real binary rather+// than read from a published spec. Each one pins a default reader to a Muse payload, so a future+// refactor of the claude branches cannot quietly take Muse's session id, workspace or tool fields+// with it -- and so a contract change shows up as a failing test rather than as telemetry going+// silently missing, which is how a Muse hook fails: the host ignores a hook it does not like+// without a warning, an exit code or a log line.++// The base fields Muse sends on every event: session_id, cwd, model, permission_mode,+// transcript_path, and (on everything except SessionStart) turn_id. Reading them is what puts+// session.id, session.working_directory and repository on every Muse event.+func TestMuseSessionAndWorkspaceComeFromTheBaseFields(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "muse"++ input := map[string]interface{}{+ "hook_event_name": "PreToolUse",+ "session_id": "muse-session-1",+ "cwd": "/tmp/muse-project",+ "model": "muse-spark-1.3",+ "permission_mode": "default",+ "transcript_path": "/tmp/muse/transcripts/muse-session-1.jsonl",+ "turn_id": "turn-7",+ }++ if got := resolveSessionID(input, "muse"); got != "muse-session-1" {+ t.Errorf("resolveSessionID = %q, want muse-session-1", got)+ }+ sessionID, transcriptPath := resolveSessionIDWithTranscript(input, "muse")+ if sessionID != "muse-session-1" {+ t.Errorf("resolveSessionIDWithTranscript session = %q, want muse-session-1", sessionID)+ }+ if transcriptPath != "/tmp/muse/transcripts/muse-session-1.jsonl" {+ t.Errorf("resolveSessionIDWithTranscript transcript = %q, want Muse's transcript_path", transcriptPath)+ }+ if got := resolveCwd(input, "muse"); got != "/tmp/muse-project" {+ t.Errorf("resolveCwd = %q, want /tmp/muse-project", got)+ }+}++// transcript_path is documented as nullable and model as the literal string "unknown". Neither is+// an error, and neither may take the session id or the workspace down with it: a hook that panicked+// or bailed on a null would drop every event from a session that happened to have no transcript.+func TestMuseToleratesNullTranscriptPath(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "muse"++ input := map[string]interface{}{+ "hook_event_name": "UserPromptSubmit",+ "session_id": "muse-session-2",+ "cwd": "/tmp/muse-project",+ "model": "unknown",+ "transcript_path": nil,+ }++ sessionID, transcriptPath := resolveSessionIDWithTranscript(input, "muse")+ if sessionID != "muse-session-2" {+ t.Fatalf("resolveSessionIDWithTranscript session = %q, want muse-session-2", sessionID)+ }+ if transcriptPath != "" {+ t.Fatalf("resolveSessionIDWithTranscript transcript = %q, want empty for a null path", transcriptPath)+ }+ if got := resolveCwd(input, "muse"); got != "/tmp/muse-project" {+ t.Fatalf("resolveCwd = %q, want the workspace to survive a null transcript_path", got)+ }+}++// Muse gets its own state directory. Sharing Claude's would mix two runtimes' session state and+// hook logs in one place: a stale-evaluation cleanup for a Muse session would walk Claude's+// sessions, and `~/.beacon/claude/hooks.log` would interleave two runtimes.+func TestMuseHasItsOwnStateDirectory(t *testing.T) {+ setupHookConfigDirs(t)++ stateDir := hookconfig.GetStateDir("muse")+ if stateDir != hookconfig.MuseDir {+ t.Fatalf("GetStateDir(muse) = %q, want MuseDir %q", stateDir, hookconfig.MuseDir)+ }+ if stateDir == hookconfig.ClaudeDir {+ t.Fatalf("GetStateDir(muse) = %q, want a directory distinct from Claude's", stateDir)+ }+ if got, want := hookconfig.GetLogFile("muse"), filepath.Join(hookconfig.MuseDir, "hooks.log"); got != want {+ t.Fatalf("GetLogFile(muse) = %q, want %q", got, want)+ }+}++// Two independent reasons Muse's pre-tool answer must be the empty object, both load-bearing.+//+// The first is the one every observing hook has: Muse reads a tool decision from+// hookSpecificOutput, so answering "allow" would disarm the user's own permission prompt on a+// runtime where the hook was installed only to watch.+//+// The second is specific to Muse and is why `{"permission":"allow"}` is not merely impolite here:+// its hook runner rejects a stdout object carrying keys it does not know. The Cursor-shaped+// response would not read as a permissive answer, it would fail the hook run.+func TestMusePreToolDoesNotDecideOnBehalfOfTheUser(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "muse"+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_MODE", "1")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ out := runHookWithInput(t, runPreTool, map[string]interface{}{+ "hook_event_name": "PreToolUse",+ "session_id": "muse-session-1",+ "cwd": "/tmp/muse-project",+ "tool_name": "bash",+ "tool_use_id": "tool-1",+ "tool_input": map[string]interface{}{"command": "rm -rf build"},+ })+ if len(out) != 0 {+ t.Fatalf("pre-tool response = %#v, want an empty object carrying no decision", out)+ }++ event := lastEndpointEvent(t, logPath)+ // tool.invoked, not command.executed: pre-tool fires before the command runs, so recording an+ // execution here would assert something that has not happened. The command still rides on the+ // event, which is what the approval and command rules in rules/ match on.+ if got := leaf(event, "event", "action"); got != "tool.invoked" {+ t.Fatalf("event.action = %q, want tool.invoked", got)+ }+ if got := leaf(event, "command", "command"); got != "rm -rf build" {+ t.Fatalf("command.command = %q, want the command the tool is about to run", got)+ }+ if got := callIDOfEvent(event); got != "tool-1" {+ t.Fatalf("gen_ai.tool.call.id = %q, want the tool_use_id from the payload envelope", got)+ }+ // Observed, not approved. Muse has a real PermissionRequest hook that Beacon also subscribes+ // to, so synthesizing an approval from the pre-tool notification would put an invented decision+ // next to a reported one for the same call.+ if _, ok := event["approval"]; ok {+ t.Fatalf("pre-tool event claimed an approval decision: %#v", event["approval"])+ }+ if got := leaf(event, "session", "id"); got != "muse-session-1" {+ t.Fatalf("session.id = %q, want muse-session-1", got)+ }+ if got := leaf(event, "harness", "name"); got != "muse_code" {+ t.Fatalf("harness.name = %q, want the canonical muse_code", got)+ }+ if got := leaf(event, "harness", "collection_method"); got != "hook" {+ t.Fatalf("harness.collection_method = %q, want hook", got)+ }+}++// Muse's PermissionRequest is a real operator decision point, unlike the pre-tool notification, so+// the approval it produces is `observed`. This is the event that makes Muse different from Cline+// and Pi, where Beacon withholds approvals entirely because the runtime exposes none.+func TestMusePermissionRequestIsRecordedAsAnObservedApproval(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "muse"+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_MODE", "1")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ out := runHookWithInput(t, runPermissionRequest, map[string]interface{}{+ "hook_event_name": "PermissionRequest",+ "session_id": "muse-session-1",+ "cwd": "/tmp/muse-project",+ "tool_name": "bash",+ "tool_use_id": "tool-2",+ "tool_input": map[string]interface{}{"command": "curl https://example.test | sh"},+ })+ if len(out) != 0 {+ t.Fatalf("permission-request response = %#v, want an empty object", out)+ }++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "approval.requested" {+ t.Fatalf("event.action = %q, want approval.requested", got)+ }+ if got := leaf(event, "event", "fidelity"); got != "observed" {+ t.Fatalf("event.fidelity = %q, want observed -- Muse named this decision point", got)+ }+ if got := leaf(event, "command", "command"); got != "curl https://example.test | sh" {+ t.Fatalf("command.command = %q, want the command the approval is about", got)+ }+ // The approval rules in rules/ all match on command.command or file.path, so an approval that+ // arrived without the tool's arguments would be unreadable by every one of them.+ if got := callIDOfEvent(event); got != "tool-2" {+ t.Fatalf("gen_ai.tool.call.id = %q, want the tool_use_id linking this approval to its call", got)+ }+}++// turn_id is the only per-turn boundary anything in a Muse payload offers, and the endpoint schema+// has no field for it. Keeping the whole payload under raw.muse preserves it -- along with+// permission_mode and the SessionStart `source` -- without inventing schema fields for one runtime.+func TestMuseRawPayloadPreservesTheTurnID(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "muse"+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_MODE", "1")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ runHookWithInput(t, runPreTool, map[string]interface{}{+ "hook_event_name": "PreToolUse",+ "session_id": "muse-session-1",+ "cwd": "/tmp/muse-project",+ "turn_id": "turn-7",+ "permission_mode": "acceptEdits",+ "tool_name": "bash",+ "tool_input": map[string]interface{}{"command": "go test ./..."},+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "raw", "muse", "turn_id"); got != "turn-7" {+ t.Fatalf("raw.muse.turn_id = %q, want turn-7", got)+ }+ if got := leaf(event, "raw", "muse", "permission_mode"); got != "acceptEdits" {+ t.Fatalf("raw.muse.permission_mode = %q, want acceptEdits", got)+ }+}++// The policy seam is off by default and fails open, but when a provider does deny, the response has+// to be the shape Muse reads or the deny is silently dropped and the tool runs anyway.+//+// Muse validates that hookSpecificOutput echoes the event that fired the hook, which is why this is+// derived from the phase rather than hardcoded: Beacon binds each phase to a distinct Muse event in+// the hooks file it writes, so a deny raised from the permission phase can be honored here, where+// on Qwen it cannot.+func TestMusePolicyDenyEchoesTheFiringEvent(t *testing.T) {+ origPlatform := platformFlag+ t.Cleanup(func() { platformFlag = origPlatform })+ platformFlag = "muse"++ for phase, wantEvent := range map[policycontract.Phase]string{+ policycontract.PhasePreTool: "PreToolUse",+ policycontract.PhasePermissionRequest: "PermissionRequest",+ } {+ deny := policyDenyResponse("Security policy blocks network installs", phase)+ if deny == nil {+ t.Fatalf("policyDenyResponse(muse, %v) = nil; a provider deny would be silently dropped", phase)+ }+ specific, ok := deny["hookSpecificOutput"].(map[string]interface{})+ if !ok {+ t.Fatalf("policyDenyResponse(muse, %v) = %#v, want a hookSpecificOutput object", phase, deny)+ }+ if got := specific["hookEventName"]; got != wantEvent {+ t.Fatalf("hookEventName = %v, want %q -- Muse requires it to match the firing event", got, wantEvent)+ }+ if got := specific["permissionDecision"]; got != "deny" {+ t.Fatalf("permissionDecision = %v, want deny", got)+ }+ if got := specific["permissionDecisionReason"]; got != "Security policy blocks network installs" {+ t.Fatalf("permissionDecisionReason = %v, want the provider's reason", got)+ }+ }+}++// The deny must not use Muse's turn-cancelling shape.+//+// `{"decision":"block"}` is the one JSON shape measured to block on Muse -- but it was measured on+// UserPromptSubmit, where blocking cancels the whole turn. Emitting it from a tool phase would+// escalate "do not run this command" into "abandon what the user asked for", which is not what a+// per-call policy deny means. The tool-family shape is used instead, and if that inference is wrong+// the deny is ignored -- which is what returning nil would have done anyway.+func TestMusePolicyDenyDoesNotCancelTheWholeTurn(t *testing.T) {+ origPlatform := platformFlag+ t.Cleanup(func() { platformFlag = origPlatform })+ platformFlag = "muse"++ deny := policyDenyResponse("blocked", policycontract.PhasePreTool)+ if got, ok := deny["decision"]; ok {+ t.Fatalf("deny carried a top-level decision=%v; that is Muse's turn-cancelling shape, not a per-call deny", got)+ }+ if _, ok := deny["continue"]; ok {+ t.Fatalf("deny carried a `continue` key: %#v", deny)+ }+}++// Only the installed --platform spelling is wired. `muse-code` is a harness alias a person might+// type at the CLI, not a value the hook binary is ever invoked with, and treating it as one here+// would suggest a deny works on an invocation Beacon never produces.+func TestMusePolicyDenyIsScopedToTheInstalledPlatformSpelling(t *testing.T) {+ origPlatform := platformFlag+ t.Cleanup(func() { platformFlag = origPlatform })++ platformFlag = "muse-code"+ if deny := policyDenyResponse("blocked", policycontract.PhasePreTool); deny != nil {+ t.Fatalf("policyDenyResponse(muse-code) = %#v; only --platform muse is wired", deny)+ }+ platformFlag = "muse"+ if deny := policyDenyResponse("blocked", policycontract.PhasePreTool); deny == nil {+ t.Fatal("policyDenyResponse(muse) = nil, want Muse's deny shape")+ }+}++// Muse's tool names are not published, and the ones that are confirmed are snake_case+// (`read_skill`, `subagent_spawn`). The fallback file-edit set is Claude Code's PascalCase names,+// which a snake_case runtime never matches -- so without a Muse branch a file edit would never+// reach the diff path and never be recorded as file.modified.+func TestMuseFileEditsAreRecognizedBySnakeCaseToolNames(t *testing.T) {+ origPlatform := platformFlag+ t.Cleanup(func() { platformFlag = origPlatform })+ platformFlag = "muse"++ for _, name := range []string{"write_file", "edit_file", "create_file", "apply_patch", "str_replace_editor"} {+ if !isFileEditTool("muse", name) {+ t.Errorf("isFileEditTool(muse, %q) = false; a Muse file edit would never be recorded", name)+ }+ }+ // The six confirmed subagent control tools drive the lead agent's own fan-out loop. Recording+ // them as file activity would put the agent's control plane in the file-modification stream.+ for _, name := range []string{+ "subagent_spawn", "subagent_status", "subagent_send_message",+ "subagent_cancel", "subagent_wait", "subagent_read_result",+ } {+ if isFileEditTool("muse", name) {+ t.Errorf("isFileEditTool(muse, %q) = true; a subagent control call is not a file edit", name)+ }+ }+}++// A Muse file edit has to survive the whole post-tool path, not just the predicate above: the+// action, the category and the file block all come off it.+func TestMusePostToolRecordsAFileModification(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "muse"+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_MODE", "1")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "hook_event_name": "PostToolUse",+ "session_id": "muse-session-1",+ "cwd": "/tmp/muse-project",+ "tool_name": "edit_file",+ "tool_use_id": "tool-3",+ "tool_input": map[string]interface{}{"file_path": "/tmp/muse-project/main.go"},+ "tool_response": map[string]interface{}{"success": true},+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "file.modified" {+ t.Fatalf("event.action = %q, want file.modified", got)+ }+ if got := leaf(event, "file", "path"); got != "/tmp/muse-project/main.go" {+ t.Fatalf("file.path = %q, want the edited path", got)+ }+ if got := callIDOfEvent(event); got != "tool-3" {+ t.Fatalf("gen_ai.tool.call.id = %q, want the tool_use_id from the payload envelope", got)+ }+}++// Muse names the child session on SubagentStart and the parent nowhere: the event's own session_id+// is the child's, and `child_session_id` repeats it. Recording it explicitly is what keeps a reader+// from assuming session.id means the parent, as it does on every other runtime here.+//+// The missing parent is left missing. Muse's on-disk session log does carry parent_session_id, but+// reading it is a poll path rather than this one, and synthesizing a parent from a payload that+// does not name one would be a fabricated join key in a security log.+func TestMuseSubagentStartRecordsTheChildSession(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "muse"+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_MODE", "1")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ runHookWithInput(t, subagentStartCmd.Run, map[string]interface{}{+ "hook_event_name": "SubagentStart",+ "session_id": "muse-child-session",+ "child_session_id": "muse-child-session",+ "subagent_id": "subagent-42",+ "cwd": "/tmp/muse-project",+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "subagent.started" {+ t.Fatalf("event.action = %q, want subagent.started", got)+ }+ if got := leaf(event, "raw", "subagent", "id"); got != "subagent-42" {+ t.Fatalf("raw.subagent.id = %q, want subagent-42", got)+ }+ if got := leaf(event, "raw", "subagent", "child_session_id"); got != "muse-child-session" {+ t.Fatalf("raw.subagent.child_session_id = %q, want the child session Muse named", got)+ }+}++// Compaction is where an agent's own history stops being a complete account of the session. An+// investigator reading a Muse session that compacted mid-run needs to see that the earlier turns+// were summarized away rather than never happening.+func TestMuseCompactionEventsAreRecorded(t *testing.T) {+ for _, tc := range []struct {+ name string+ run func()+ action string+ }{+ {"pre", func() { runCompaction("session.compacting", "Context compaction started") }, "session.compacting"},+ {"post", func() { runCompaction("session.compacted", "Context compaction completed") }, "session.compacted"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "muse"+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_MODE", "1")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ out := runHookWithInput(t, func(*cobra.Command, []string) { tc.run() }, map[string]interface{}{+ "hook_event_name": "PreCompact",+ "session_id": "muse-session-1",+ "cwd": "/tmp/muse-project",+ "turn_id": "turn-9",+ })+ if len(out) != 0 {+ t.Fatalf("compaction response = %#v, want an empty object", out)+ }++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != tc.action {+ t.Fatalf("event.action = %q, want %q", got, tc.action)+ }+ if got := leaf(event, "event", "category"); got != "session" {+ t.Fatalf("event.category = %q, want session", got)+ }+ if got := leaf(event, "session", "id"); got != "muse-session-1" {+ t.Fatalf("session.id = %q, want muse-session-1", got)+ }+ })+ }+}++// Every Muse event Beacon writes carries the canonical harness name and the hook collection method,+// whichever command produced it. Without this, one Muse session splits across harness names in any+// query that groups by harness.name.+func TestMuseSessionStartCarriesTheCanonicalHarness(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "muse"+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_MODE", "1")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ runHookWithInput(t, runSessionStart, map[string]interface{}{+ "hook_event_name": "SessionStart",+ "session_id": "muse-session-1",+ "cwd": "/tmp/muse-project",+ "model": "muse-spark-1.3",+ "source": "startup",+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "session.started" {+ t.Fatalf("event.action = %q, want session.started", got)+ }+ if got := leaf(event, "harness", "name"); got != "muse_code" {+ t.Fatalf("harness.name = %q, want muse_code", got)+ }+ // The model rides on the event, and it is a Muse Spark id -- which must not have been mistaken+ // for the harness on the way through. See TestMuseSparkModelNamesAreNotTreatedAsTheHarness.+ if got := leaf(event, "model"); got != "muse-spark-1.3" {+ t.Fatalf("model = %q, want the Muse Spark model id", got)+ }+ if got := leaf(event, "raw", "muse", "source"); got != "startup" {+ t.Fatalf("raw.muse.source = %q, want startup", got)+ }+}diff --git a/cli/beacon-hooks/cmd/policy.go b/cli/beacon-hooks/cmd/policy.goindex 4cea2308..515ea5d9 100644--- a/cli/beacon-hooks/cmd/policy.go+++ b/cli/beacon-hooks/cmd/policy.go@@ -41,7 +41,7 @@ func enforcePolicy(logger *logging.Logger, input map[string]interface{}, sessionif reason == "" {reason = "Tool call denied by policy provider"}- deny := policyDenyResponse(reason)+ deny := policyDenyResponse(reason, phase)if deny == nil {// Platform has no deny shape: honor "unknown platform -> allow".return nil, false@@ -162,7 +162,7 @@ func emitPolicyDenied(logger *logging.Logger, input map[string]interface{}, c po// caller allows (unknown platform -> allow). It is phase-independent: a platform// with a confirmed deny shape honors a deny in every phase the seam runs in, so a// provider deny is never silently dropped for a platform we enforce on.-func policyDenyResponse(reason string) map[string]interface{} {+func policyDenyResponse(reason string, phase policycontract.Phase) map[string]interface{} {switch {case platformFlag == "cursor":return map[string]interface{}{"permission": "deny"}@@ -185,7 +185,56 @@ func policyDenyResponse(reason string) map[string]interface{} {"permissionDecisionReason": reason,},}+ // Muse Code's deny contract is split between what has been measured and what has only been+ // read out of the binary, and this returns the half that has not been measured -- stated here+ // rather than left for a reader to discover.+ //+ // Measured, on a live hook: the host is fail-open on everything except `{"decision":"block"}`+ // and exit code 2. Every other shape, this one included, was ignored and the turn proceeded.+ // But that measurement was taken on UserPromptSubmit, whose deny cancels the whole turn --+ // which is not what a per-call policy deny means, and emitting it from a tool phase would+ // escalate "do not run this command" into "abandon what the user asked for". So the turn-family+ // shape is deliberately not used here.+ //+ // The tool-family shape below comes from the binary's own validation strings, which require+ // hookSpecificOutput to carry a hookEventName matching the firing event alongside+ // permissionDecision / permissionDecisionReason. Strong evidence, not measurement: the account+ // used for the measurement hit a billing error before any tool call, so no tool-side deny was+ // ever exercised.+ //+ // The cost of that being wrong is bounded and is the direction to be wrong in. Sending the+ // wrong family's shape was measured to be ignored silently, so an incorrect guess degrades to+ // exactly what returning nil does -- the deny does not take effect and the tool runs -- rather+ // than blocking a call for the wrong reason. Returning nil would give up the case where the+ // inference is right for no safety gain.+ //+ // hookEventName is derived from the phase rather than hardcoded, unlike the claude/qwen branch+ // above, because Muse requires it to match the firing event and Beacon binds each phase to a+ // distinct Muse event in the hooks file it writes. That is what lets a deny raised from the+ // PermissionRequest phase be honored here, where on Qwen it cannot be.+ case platformFlag == "muse":+ return map[string]interface{}{+ "hookSpecificOutput": map[string]interface{}{+ "hookEventName": museHookEventNameForPhase(phase),+ "permissionDecision": "deny",+ "permissionDecisionReason": reason,+ },+ }default:return nil}}++// museHookEventNameForPhase names the Muse Code event the policy seam is answering.+//+// Muse validates that a hook's hookSpecificOutput echoes the event that fired it, so this must+// track the binding in the managed hooks file Beacon writes: PreToolUse for the pre-tool phase,+// PermissionRequest for the permission phase. PreToolUse is the fallback because it is the phase+// the seam runs in on every runtime, so an unrecognized phase degrades to the common case rather+// than to an event name Muse would reject.+func museHookEventNameForPhase(phase policycontract.Phase) string {+ if phase == policycontract.PhasePermissionRequest {+ return "PermissionRequest"+ }+ return "PreToolUse"+}diff --git a/cli/beacon-hooks/cmd/post_tool.go b/cli/beacon-hooks/cmd/post_tool.goindex f853193d..85bd537c 100644--- a/cli/beacon-hooks/cmd/post_tool.go+++ b/cli/beacon-hooks/cmd/post_tool.go@@ -473,6 +473,26 @@ func isFileEditTool(platform, toolName string) bool {if platform == "qwen" {return isQwenFileEditTool(toolName)}+ // Muse Code's tool names are not published, and the fallback below is Claude Code's PascalCase+ // set, which a snake_case runtime never matches -- so without a branch here a Muse file edit+ // would never reach the diff path and never be recorded as file.modified. The names that ARE+ // confirmed are snake_case (`read_skill`, `subagent_spawn`), which is what makes the generic+ // substring rule the right shape rather than a guessed literal list: it matches whatever+ // spelling Meta chose, and a literal list guessed wrong would silently capture nothing.+ //+ // Same rule as hermes, antigravity and copilot above, and it is a heuristic in all four cases.+ // Its false-positive direction is bounded: toolFields only attaches a `file` block when the+ // tool's own arguments carry a path, so a non-file tool whose name happens to contain "write"+ // yields file.modified with no path rather than a fabricated edit. None of the six confirmed+ // subagent_* control tools contain any of these substrings, so the agent's own control loop is+ // not classified as file activity.+ if platform == "muse" {+ lower := strings.ToLower(toolName)+ return strings.Contains(lower, "edit") ||+ strings.Contains(lower, "write") ||+ strings.Contains(lower, "create") ||+ strings.Contains(lower, "patch")+ }return toolName == "Write" || toolName == "Edit" || toolName == "MultiEdit"}diff --git a/cli/beacon-hooks/cmd/pre_tool.go b/cli/beacon-hooks/cmd/pre_tool.goindex 38e602e1..129e00ba 100644--- a/cli/beacon-hooks/cmd/pre_tool.go+++ b/cli/beacon-hooks/cmd/pre_tool.go@@ -50,7 +50,13 @@ func runPreTool(cmd *cobra.Command, args []string) {} else if platformFlag == "antigravity" {emitAntigravityPromptFromTranscript(logger, input, sessionID)emitPreToolObserved(logger, input, sessionID)- } else if platformFlag == "claude" || platformFlag == "qwen" || isDevinLikePlatform(platformFlag) || platformFlag == "grok" || platformFlag == "hermes" || platformFlag == "vscode" {+ } else if platformFlag == "claude" || platformFlag == "qwen" || isDevinLikePlatform(platformFlag) || platformFlag == "grok" || platformFlag == "hermes" || platformFlag == "vscode" || platformFlag == "muse" {+ // Muse Code belongs on the observing side rather than with the runtimes whose pre-tool+ // notification gets turned into a synthesized approval, and the reason is that it has a+ // real one. Its PermissionRequest event is a separate hook Beacon also subscribes to, so+ // deriving an approval.allowed from PreToolUse as well would record two approvals for one+ // tool call -- one of them inferred and describing nothing an operator did -- and put an+ // invented decision next to a reported one for the same call.emitPreToolObserved(logger, input, sessionID)} else {emitPreToolDecision(logger, input, sessionID, "approval.allowed", "allow", "Pre-tool observed", asymptoteobserve.FidelityInferred)@@ -122,7 +128,11 @@ func preToolResponse() map[string]interface{} {// where the hook was installed to watch. An empty object carries no decision, so Qwen's normal// permission flow runs untouched -- which is the only correct answer for a telemetry hook, and// what TestQwenPreToolDoesNotApproveOnBehalfOfTheUser holds in place.- if platformFlag == "claude" || platformFlag == "qwen" || isDevinLikePlatform(platformFlag) || platformFlag == "hermes" || platformFlag == "vscode" {+ // Muse Code requires the empty object for a second reason on top of the one above, and it is+ // not a preference: its hook runner rejects a stdout object carrying keys it does not know, so+ // `{"permission":"allow"}` would not read as a permissive answer -- it would fail the hook run+ // outright. Emitting nothing speculative is the only shape that leaves a Muse turn untouched.+ if platformFlag == "claude" || platformFlag == "qwen" || isDevinLikePlatform(platformFlag) || platformFlag == "hermes" || platformFlag == "vscode" || platformFlag == "muse" {return emptyResponse}return allowResponsediff --git a/cli/beacon-hooks/cmd/pre_tool_test.go b/cli/beacon-hooks/cmd/pre_tool_test.goindex c67fdbd0..46c01fb2 100644--- a/cli/beacon-hooks/cmd/pre_tool_test.go+++ b/cli/beacon-hooks/cmd/pre_tool_test.go@@ -907,47 +907,40 @@ func TestRunSessionEndRemovesSessionLog(t *testing.T) {func setupHookConfigDirs(t *testing.T) {t.Helper()tmp := t.TempDir()++ // Every per-runtime state directory is redirected under one temp root, as a table rather than+ // as a save/restore pair per runtime.+ //+ // It was the latter, and the shape was the problem rather than the length: adding a runtime+ // meant editing three parallel lists in lockstep -- the saved original, the assignment, and the+ // restore -- and getting only two of them right leaks a temp path into every test that runs+ // afterwards, which then fails somewhere else entirely. Here a runtime is one line and cannot+ // be half-added.+ for name, target := range map[string]*string{+ "antigravity": &hookconfig.AntigravityDir,+ "claude": &hookconfig.ClaudeDir,+ "cline": &hookconfig.ClineDir,+ "copilot": &hookconfig.CopilotDir,+ "cursor": &hookconfig.CursorDir,+ "devin": &hookconfig.DevinDir,+ "factory": &hookconfig.FactoryDir,+ "grok": &hookconfig.GrokDir,+ "hermes": &hookconfig.HermesDir,+ "muse": &hookconfig.MuseDir,+ "opencode": &hookconfig.OpenCodeDir,+ "qwen": &hookconfig.QwenDir,+ "vscode": &hookconfig.VSCodeDir,+ } {+ orig := *target+ t.Cleanup(func() { *target = orig })+ *target = filepath.Join(tmp, name)+ }+origBeaconDir := hookconfig.BeaconDir- origClaudeDir := hookconfig.ClaudeDir- origAntigravityDir := hookconfig.AntigravityDir- origCopilotDir := hookconfig.CopilotDir- origCursorDir := hookconfig.CursorDir- origVSCodeDir := hookconfig.VSCodeDir- origDevinDir := hookconfig.DevinDir- origFactoryDir := hookconfig.FactoryDir- origGrokDir := hookconfig.GrokDir- origHermesDir := hookconfig.HermesDir- origOpenCodeDir := hookconfig.OpenCodeDir- origClineDir := hookconfig.ClineDir- origQwenDir := hookconfig.QwenDirorigPlatform := platformFlaghookconfig.BeaconDir = tmp- hookconfig.ClaudeDir = filepath.Join(tmp, "claude")- hookconfig.AntigravityDir = filepath.Join(tmp, "antigravity")- hookconfig.CopilotDir = filepath.Join(tmp, "copilot")- hookconfig.CursorDir = filepath.Join(tmp, "cursor")- hookconfig.VSCodeDir = filepath.Join(tmp, "vscode")- hookconfig.DevinDir = filepath.Join(tmp, "devin")- hookconfig.FactoryDir = filepath.Join(tmp, "factory")- hookconfig.GrokDir = filepath.Join(tmp, "grok")- hookconfig.HermesDir = filepath.Join(tmp, "hermes")- hookconfig.OpenCodeDir = filepath.Join(tmp, "opencode")- hookconfig.ClineDir = filepath.Join(tmp, "cline")- hookconfig.QwenDir = filepath.Join(tmp, "qwen")t.Cleanup(func() {hookconfig.BeaconDir = origBeaconDir- hookconfig.ClaudeDir = origClaudeDir- hookconfig.AntigravityDir = origAntigravityDir- hookconfig.CopilotDir = origCopilotDir- hookconfig.CursorDir = origCursorDir- hookconfig.VSCodeDir = origVSCodeDir- hookconfig.DevinDir = origDevinDir- hookconfig.FactoryDir = origFactoryDir- hookconfig.GrokDir = origGrokDir- hookconfig.HermesDir = origHermesDir- hookconfig.OpenCodeDir = origOpenCodeDir- hookconfig.ClineDir = origClineDir- hookconfig.QwenDir = origQwenDirplatformFlag = origPlatform})}diff --git a/cli/beacon-hooks/cmd/qwen_hooks_test.go b/cli/beacon-hooks/cmd/qwen_hooks_test.goindex 72866414..b686ae3c 100644--- a/cli/beacon-hooks/cmd/qwen_hooks_test.go+++ b/cli/beacon-hooks/cmd/qwen_hooks_test.go@@ -5,6 +5,7 @@ import ("testing"hookconfig "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/policycontract")// Qwen Code's hook payloads are the Claude Code shape: snake_case base fields, `tool_name` /@@ -119,7 +120,7 @@ func TestQwenPolicyDenyUsesQwensPermissionDecisionShape(t *testing.T) {t.Cleanup(func() { platformFlag = origPlatform })platformFlag = "qwen"- deny := policyDenyResponse("Security policy blocks database writes")+ deny := policyDenyResponse("Security policy blocks database writes", policycontract.PhasePreTool)if deny == nil {t.Fatal("policyDenyResponse(qwen) = nil; a provider deny would be silently dropped and the tool would run")}@@ -147,12 +148,12 @@ func TestQwenIsNotTreatedAsAnUnknownPlatform(t *testing.T) {t.Cleanup(func() { platformFlag = origPlatform })platformFlag = "qwen-code"- if deny := policyDenyResponse("blocked"); deny != nil {+ if deny := policyDenyResponse("blocked", policycontract.PhasePreTool); deny != nil {t.Fatalf("policyDenyResponse(qwen-code) = %#v; only the installed --platform spelling (qwen) is wired", deny)}platformFlag = "qwen"- if deny := policyDenyResponse("blocked"); deny == nil {+ if deny := policyDenyResponse("blocked", policycontract.PhasePreTool); deny == nil {t.Fatal("policyDenyResponse(qwen) = nil, want Qwen's deny shape")}}diff --git a/cli/beacon-hooks/cmd/root.go b/cli/beacon-hooks/cmd/root.goindex 8b4b67c0..6b30069e 100644--- a/cli/beacon-hooks/cmd/root.go+++ b/cli/beacon-hooks/cmd/root.go@@ -29,8 +29,8 @@ var (var rootCmd = &cobra.Command{Use: "beacon-hooks",- Short: "Beacon hooks for Claude Code, Codex, GitHub Copilot, Cursor, VS Code, Devin, Factory, Grok, Hermes, Antigravity, opencode, Qwen Code, and Cline",- Long: `Beacon hooks binary for Claude Code, Codex, GitHub Copilot, Cursor, VS Code, Devin, Factory, Grok, Hermes, Antigravity, opencode, Qwen Code, and Cline integration.+ Short: "Beacon hooks for Claude Code, Codex, GitHub Copilot, Cursor, VS Code, Devin, Factory, Grok, Hermes, Antigravity, opencode, Qwen Code, Muse Code, and Cline",+ Long: `Beacon hooks binary for Claude Code, Codex, GitHub Copilot, Cursor, VS Code, Devin, Factory, Grok, Hermes, Antigravity, opencode, Qwen Code, Muse Code, and Cline integration.This binary provides hook commands that are called by IDE plugin systemsto evaluate code changes for security violations.@@ -39,7 +39,7 @@ Use --platform to specify the calling platform (default: claude).`,}func init() {- rootCmd.PersistentFlags().StringVar(&platformFlag, "platform", "claude", "Platform context: claude, cline, codex, antigravity, copilot, cursor, vscode, devin, devin-cli, devin-desktop, factory, grok, hermes, opencode, or qwen")+ rootCmd.PersistentFlags().StringVar(&platformFlag, "platform", "claude", "Platform context: claude, cline, codex, antigravity, copilot, cursor, vscode, devin, devin-cli, devin-desktop, factory, grok, hermes, muse, opencode, or qwen")rootCmd.PersistentFlags().StringVar(&logFlag, "log", "", "Endpoint runtime log to append to (same value as BEACON_ENDPOINT_LOG)")rootCmd.PersistentFlags().StringVar(&configFlag, "config", "", "Endpoint config to read (same value as BEACON_ENDPOINT_CONFIG)")rootCmd.PersistentFlags().StringVar(&cliFlag, "cli", "", "Path to the beacon CLI for inventory heartbeats (same value as BEACON_ENDPOINT_CLI)")diff --git a/cli/beacon-hooks/cmd/subagent.go b/cli/beacon-hooks/cmd/subagent.goindex b13f286f..b2e92f6b 100644--- a/cli/beacon-hooks/cmd/subagent.go+++ b/cli/beacon-hooks/cmd/subagent.go@@ -61,7 +61,26 @@ func runSubagentLifecycle(action, message string) {})}}+ // Muse Code names the child session on the subagent event, and the parent nowhere.+ //+ // Its SubagentStart carries `subagent_id` and `child_session_id`, and -- measured rather than+ // assumed -- the event's own `session_id` is the CHILD's, not the parent's. So session.id on a+ // Muse subagent event identifies the subagent's session, and no field in the payload recovers+ // which session spawned it. Recording child_session_id explicitly is what makes that legible+ // instead of leaving a reader to assume session.id means the parent, as it does on every other+ // runtime here.+ //+ // The gap is left as a gap. Muse's own session log nests a child under its parent's directory+ // and carries parent_session_id, so the correlation exists on disk -- but reading it is a poll+ // path, not this one, and inventing a parent id from a hook payload that does not carry one+ // would be a fabricated join key in a security log.+ if platformFlag == "muse" {+ subagent = mergeNested(subagent, map[string]interface{}{+ "child_session_id": getFirstStr(input, "child_session_id", "childSessionId"),+ })+ }fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{"subagent": map[string]interface{}{+ "child_session_id": subagent["child_session_id"],"id": subagent["id"],"type": subagent["type"],"role": subagent["role"],diff --git a/cli/beacon-hooks/internal/config/config.go b/cli/beacon-hooks/internal/config/config.goindex 0a9a22be..12ed7f8f 100644--- a/cli/beacon-hooks/internal/config/config.go+++ b/cli/beacon-hooks/internal/config/config.go@@ -22,6 +22,7 @@ var (HermesDir = filepath.Join(BeaconDir, "hermes")OpenCodeDir = filepath.Join(BeaconDir, "opencode")QwenDir = filepath.Join(BeaconDir, "qwen")+ MuseDir = filepath.Join(BeaconDir, "muse")ClineDir = filepath.Join(BeaconDir, "cline"))@@ -103,6 +104,8 @@ func GetStateDir(platform string) string {return OpenCodeDircase "qwen":return QwenDir+ case "muse":+ return MuseDircase "cline":return ClineDirdefault: