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 Kiro hook events in beacon-hooks
Claude85810e940cff
diff --git a/cli/beacon-hooks/cmd/endpoint_events.go b/cli/beacon-hooks/cmd/endpoint_events.goindex 24c196a1..176290c8 100644--- a/cli/beacon-hooks/cmd/endpoint_events.go+++ b/cli/beacon-hooks/cmd/endpoint_events.go@@ -314,7 +314,13 @@ func toolFieldsWithResponse(toolName string, toolInput, toolResponse map[string]// that names the editor operation (view, str_replace, create), not a shell command.// Promoting it into command.command would store an editor operation as shell execution and// let the policy seam upgrade tool.invoked to command.executed.- if !(platformFlag == openHandsPlatform && openHandsFileEditorTools[strings.ToLower(strings.TrimSpace(toolName))]) {+ // Kiro's write tool has the same shape for the same reason: its `command` argument may name+ // an editor operation (create, str_replace, insert) rather than a shell command, because+ // the tool descends from Amazon Q Developer CLI's multiplexed fs_write. Guarded on the+ // tool name so `shell`/`execute_bash`, where `command` really is the command line, keeps+ // the field that makes a shell event worth recording.+ if !(platformFlag == openHandsPlatform && openHandsFileEditorTools[strings.ToLower(strings.TrimSpace(toolName))]) &&+ !(platformFlag == kiroPlatform && kiroWriteCommandIsEditorOperation(toolName, toolInput)) {fields["command"] = map[string]interface{}{"command": command}fields["tool"] = mergeNested(fields["tool"], map[string]interface{}{"name": toolName, "command": command})}@@ -326,7 +332,15 @@ func toolFieldsWithResponse(toolName string, toolInput, toolResponse map[string]// `dir_path` is the snake_case sibling of `DirectoryPath` already in this list: it is what// OpenHands' list_directory names its target. Unambiguous, so reading it costs nothing and its// absence costs a `file` field on every directory listing.- if path := firstToolString(toolInput, "file_path", "filePath", "path", "Path", "AbsolutePath", "absolute_path", "notebook_path", "DirectoryPath", "dir_path", "SearchPath", "searchPath"); path != "" {+ path := firstToolString(toolInput, "file_path", "filePath", "path", "Path", "AbsolutePath", "absolute_path", "notebook_path", "DirectoryPath", "dir_path", "SearchPath", "searchPath")+ // Kiro's read tool -- its most frequent one -- puts the path inside an `operations` array+ // rather than at the top level of tool_input, so every key above misses it and a read event+ // would carry no file at all. Asked after the shared list rather than before it, because a+ // payload that does carry a top-level path has said something more direct.+ if path == "" && platformFlag == kiroPlatform {+ path = kiroToolPath(toolInput)+ }+ if path != "" {fields["file"] = map[string]interface{}{"path": path,"operation": fileOperation(toolName, toolInput),@@ -441,6 +455,11 @@ func mcpToolFields(toolName string, toolInput, toolResponse map[string]interface// platform like the Cascade pair above, because `kind` is a key other runtimes use for other// things.hasOpenHandsMCPObservation := platformFlag == openHandsPlatform && openHandsIsMCPToolCall(toolResponse)+ // Kiro says so in the tool name, which is the easy case -- but it says it with a prefix no+ // generic signal above recognizes: `@postgres/query` contains no "mcp", carries no mcp_*+ // 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)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")@@ -450,6 +469,20 @@ func mcpToolFields(toolName string, toolInput, toolResponse map[string]interfaceresource := firstToolStringAcross([]map[string]interface{}{toolInput, toolResponse}, "mcp.resource.uri", "mcp_resource_uri", "resource_uri", "uri")session := firstToolStringAcross([]map[string]interface{}{toolInput, toolResponse}, "mcp.session.id", "mcp_session_id")+ if hasKiroMCPToolName {+ // Read before the shared derivation rather than after, because deriveMCPServerTool+ // recognizes only the `mcp:` and `mcp__` spellings and would leave both halves empty for+ // an `@server/tool` name -- recording an MCP call whose server and tool are blank.+ if server == "" || tool == "" {+ derivedServer, derivedTool, _ := kiroMCPServerTool(toolName)+ if server == "" {+ server = derivedServer+ }+ if tool == "" {+ tool = derivedTool+ }+ }+ }if derivedServer, derivedTool := deriveMCPServerTool(toolName); derivedServer != "" || derivedTool != "" {if server == "" {server = derivedServer@@ -459,7 +492,7 @@ func mcpToolFields(toolName string, toolInput, toolResponse map[string]interface}}- isMCP := mcpServer != "" || mcpTool != "" || mcpMethod != "" || mcpProtocol != "" || mcpResource != "" || mcpSession != "" || hasCascadeServerToolPair || hasOpenHandsMCPObservation || strings.Contains(strings.ToLower(toolName), "mcp")+ isMCP := mcpServer != "" || mcpTool != "" || mcpMethod != "" || mcpProtocol != "" || mcpResource != "" || mcpSession != "" || hasCascadeServerToolPair || hasOpenHandsMCPObservation || hasKiroMCPToolName || strings.Contains(strings.ToLower(toolName), "mcp")if !isMCP {return nil}@@ -729,6 +762,11 @@ func fileOperation(toolName string, toolInput map[string]interface{}) string {return operation}}+ if platformFlag == kiroPlatform {+ if operation := kiroFileOperation(toolName, toolInput, nil); 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"):@@ -754,6 +792,11 @@ func actionForTool(hookEvent, toolName string, toolInput, toolResponse map[strinreturn action}}+ if platformFlag == kiroPlatform {+ if action := kiroToolAction(toolName, toolInput, toolResponse); action != "" {+ return action+ }+ }if platformFlag == "grok" {if hookEvent == "post_tool_use_failure" {return "tool.failed"diff --git a/cli/beacon-hooks/cmd/helpers.go b/cli/beacon-hooks/cmd/helpers.goindex 6b361f49..eb3c6c08 100644--- a/cli/beacon-hooks/cmd/helpers.go+++ b/cli/beacon-hooks/cmd/helpers.go@@ -20,14 +20,22 @@ func readStdinJSON() (map[string]interface{}, error) {return input, err}-// outputJSON writes a JSON object to stdout.+// outputJSON writes a JSON object to stdout, unless the runtime would read it as agent context.+//+// The suppression is not an optimization. On a runtime whose hook contract is exit codes rather+// than response objects, stdout is either ignored or pasted into the model's context window, so+// the no-op `{}` every command here finishes with is at best unread and at worst text Beacon put+// in front of the model. See hookStdoutIsConsumedAsAgentContext.func outputJSON(data map[string]interface{}) {+ if hookStdoutIsConsumedAsAgentContext(platformFlag) {+ return+ }json.NewEncoder(os.Stdout).Encode(data)}// outputJSONAndExit writes a JSON object to stdout and exits.func outputJSONAndExit(data map[string]interface{}) {- json.NewEncoder(os.Stdout).Encode(data)+ outputJSON(data)os.Exit(0)}diff --git a/cli/beacon-hooks/cmd/kiro.go b/cli/beacon-hooks/cmd/kiro.gonew file mode 100644index 00000000..9160f8c2--- /dev/null+++ b/cli/beacon-hooks/cmd/kiro.go@@ -0,0 +1,626 @@+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"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+)++// Kiro payload readers and tool taxonomy.+//+// Kiro (AWS) runs one agent harness behind the Kiro IDE, the Kiro CLI, Web, Mobile and Crew, and+// the local surfaces all load the same `.kiro/hooks/*.json` files. Its hook envelope is spelled+// exactly the way Claude Code spells its own:+//+// {"hook_event_name": "preToolUse", "cwd": "...", "session_id": "...",+// "tool_name": "read", "tool_input": {...}, "tool_response": {...},+// "prompt": "...", "assistant_response": "..."}+//+// So Kiro rides the shared subcommands, the way OpenHands does and 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 would be the thing+// that drifts. There is not one envelope reader in this file, because there is nothing to+// translate -- `session_id`, `cwd` and `prompt` all resolve through the shared default cases.+//+// What is here is everything the envelope does not settle:+//+// - The tool taxonomy. Kiro's tool names are published and its argument schemas are not, so the+// classification below is keyed on names only. Every entry in the table comes from Kiro's own+// tool catalog and its CLI tool reference, including the aliases, because a hook payload+// carries whichever spelling the surface used.+//+// - The read tool's arguments. `read`/`fs_read` takes an `operations` array rather than a `path`,+// which is the one argument shape Kiro documents, and the shared path reader cannot see into+// it.+//+// - MCP. Kiro names an MCP tool `@server/tool`, which contains none of the signals the shared+// MCP detection looks for.+//+// - Stdout. On Kiro a hook's stdout is not a response object, it is text handed to the model.+// See hookStdoutIsConsumedAsAgentContext.+//+// Deliberately not read: `hook_event_name`. Beacon binds each Kiro event to a distinct subcommand+// in the hooks file it writes, so the command that is running already knows which event it is+// answering.+//+// Deliberately not retained under `raw`: the envelope has no field left over once the readers+// below have run, so keeping the whole payload would duplicate `tool_input` and `tool_response`+// -- file contents included -- to preserve nothing.++const kiroPlatform = "kiro"++// kiroToolKind is what one Kiro tool does, as far as the endpoint schema is concerned.+//+// One table of names rather than the four sets the OpenHands taxonomy uses. Kiro publishes an+// explicit catalog of about thirty tools, most of them with one or two aliases, and four+// overlapping sets over that many names invites the failure where a name lands in two of them and+// the answer depends on which set is consulted first. A single map cannot express that.+type kiroToolKind int++const (+ // kiroToolOther is a tool with no filesystem or shell meaning. It is not absent from the+ // table: an entry saying "this is a tool call and nothing more" is what keeps a future+ // substring rule from guessing something else about it, and it documents that the tool was+ // considered.+ kiroToolOther kiroToolKind = iota+ kiroToolRead+ kiroToolCreate+ kiroToolModify+ kiroToolDelete+ kiroToolShell+)++// kiroToolKinds maps every published Kiro tool name and alias onto what it does.+//+// Two catalogs are merged here because Kiro ships two and they disagree. The unified tool catalog+// lists file writes split across `fs_write`, `fs_append`, `str_replace` and `delete_file`, while+// the CLI's own tool reference lists a single `write` tool with `fs_write`/`fsWrite` as its+// aliases. Rather than pick one, both are present: a hook installed once receives payloads from+// whatever surface and whatever version the operator is running, and a name that is not in this+// table falls through to the generic classifier, which is wrong about most of them.+//+// The names are matched lowercased and exactly. There is no prefix or substring rule, and the+// generic classifier below is the reason: `execute_bash` contains none of the words that classifier+// looks for ("bash" only as a whole name, "shell", "terminal", "command"), so Kiro's shell tool+// would be recorded as an unclassified `tool.invoked` without an entry here -- a shell execution+// missing from every query that looks for one. `list_processes` and `get_process_output` are the+// mirror case: they read process state rather than run anything, and are entered as `other` so a+// later substring rule cannot promote them to command executions.+var kiroToolKinds = map[string]kiroToolKind{+ // Reads. `glob`, `grep`, `file_search` and `grep_search` take a directory to search rather+ // than a file that was read; recording that directory under file.path with operation "read" is+ // the same shape the OpenHands and Qwen taxonomies already produce, and it is the honest one:+ // a search did happen, and the directory is what it touched.+ "read": kiroToolRead,+ "fs_read": kiroToolRead,+ "fsread": kiroToolRead,+ "read_file": kiroToolRead,+ "read_files": kiroToolRead,+ "list_directory": kiroToolRead,+ "file_search": kiroToolRead,+ "glob": kiroToolRead,+ "grep_search": kiroToolRead,+ "grep": kiroToolRead,+ // `code` and `read_code` parse source into symbols and signatures. They read files and change+ // nothing, so they are reads: the CLI's tree-sitter/LSP tool and the IDE's editor-native+ // equivalent.+ "code": kiroToolRead,+ "read_code": kiroToolRead,++ // Writes. `write`/`fs_write` creates or overwrites, which is "create"; the rest change a file+ // that already exists, which is "modify". A `write` call that carries an editor command+ // argument is reclassified by kiroWriteOperation, since the Amazon Q Developer CLI lineage+ // multiplexed several operations onto that one tool.+ "write": kiroToolCreate,+ "fs_write": kiroToolCreate,+ "fswrite": kiroToolCreate,+ "fs_append": kiroToolModify,+ "str_replace": kiroToolModify,+ "delete_file": kiroToolDelete,++ // Shell. `control_bash_process` starts and stops background processes, which is command+ // execution; the two tools that inspect those processes are not.+ "shell": kiroToolShell,+ "execute_bash": kiroToolShell,+ "execute_cmd": kiroToolShell,+ "control_bash_process": kiroToolShell,+ "get_process_output": kiroToolOther,+ "list_processes": kiroToolOther,++ // Everything else Kiro publishes. `aws`/`use_aws` is deliberately not shell: it does run the+ // AWS CLI, but its arguments are a service, an operation and a parameter map rather than a+ // command string, so classifying it as command.executed would produce a command event with no+ // command in it. Recorded as the tool call it is, with the tool name intact.+ "aws": kiroToolOther,+ "use_aws": kiroToolOther,+ "web_search": kiroToolOther,+ "web_fetch": kiroToolOther,+ "invoke_subagent": kiroToolOther,+ "subagent": kiroToolOther,+ "use_subagent": kiroToolOther,+ "delegate": kiroToolOther,+ "disclose_context": kiroToolOther,+ "introspect": kiroToolOther,+ "knowledge": kiroToolOther,+ "thinking": kiroToolOther,+ "todo": kiroToolOther,+ "todo_list": kiroToolOther,+ "goal": kiroToolOther,+ "session": kiroToolOther,+ "session_settings": kiroToolOther,+ "tool_search": kiroToolOther,+ "create_hook": kiroToolOther,+ "kiro_powers": kiroToolOther,+ "report": kiroToolOther,+}++// kiroWriteCommands are the editor operations a multiplexed write tool selects between.+//+// Kiro does not publish its write tool's arguments. What it does publish is that `fs_write` and+// `fsWrite` are aliases of one `write` tool, which is the shape Amazon Q Developer CLI shipped --+// Kiro CLI's own docs carry an "Upgrading from Q CLI" guide -- and there that tool took a+// `command` argument naming the operation. The newer unified catalog instead lists the operations+// as separate tools. Both shapes are handled, because a hook installed once sees whatever the+// installed version sends.+//+// This set has a second job, and it is the one that would bite: `command` is also the argument+// name Kiro's shell tool uses for the command line. Without knowing that a write's `command` names+// an operation rather than a shell command, the shared field extraction would write "str_replace"+// into command.command and let the policy seam upgrade the call from tool.invoked to+// command.executed. That is the OpenHands `file_editor` defect exactly, guarded the same way.+var kiroWriteCommands = map[string]bool{+ "create": true,+ "str_replace": true,+ "insert": true,+ "append": true,+ "delete": true,+ "undo_edit": true,+}++// kiroMultiplexedWriteTools are the tool names whose `command` argument may name an editor+// operation rather than a shell command.+//+// Only the write tool and its aliases. Deliberately not every Kiro tool: `command` means a shell+// command line on `shell`/`execute_bash`, and a set that reached those would drop the one field+// that makes a shell event worth recording.+var kiroMultiplexedWriteTools = map[string]bool{+ "write": true,+ "fs_write": true,+ "fswrite": true,+}++// kiroMCPToolPrefix is what Kiro puts in front of an MCP tool's name.+//+// Kiro names an MCP tool `@server/tool` -- the documented example is `@postgres/query`. None of+// the shared MCP signals see that: the name contains no "mcp", the arguments are the server's own+// and carry no mcp_* key, and the result is whatever the server returned. Without this the call+// would be recorded as an ordinary tool.invoked with a tool name starting with a punctuation mark.+const kiroMCPToolPrefix = "@"++// hookStdoutIsConsumedAsAgentContext reports whether a runtime feeds a hook's stdout to the model+// rather than parsing it as a response object.+//+// Kiro does. Its contract is exit codes, not JSON: on exit 0 the hook's stdout is *added to the+// agent's context* for SessionStart and UserPromptSubmit and ignored for everything else, and a+// block is exit code 2 with the reason on stderr. There is no response object to return.+//+// Beacon's shared commands all finish by writing a JSON object to stdout -- `{}` for most of them,+// `{"permission":"allow"}` for pre-tool -- which every other runtime reads as "no opinion". On+// Kiro those same bytes are not read at all on the tool events, and are pasted into the model's+// context on the two events that are. A hook whose job is to observe would be putting `{}` in+// front of the model at the start of every session and before every prompt: a small amount of+// unexplained text in the context window, contributed by a component the user installed to watch+// rather than to speak.+//+// So on Kiro nothing is written to stdout at all. Silence is a valid and complete answer under an+// exit-code contract, which is what makes this safe rather than merely tidy.+//+// Written as a question about the runtime rather than as `platform == kiroPlatform` inline,+// because it is a property other runtimes have -- Claude Code's SessionStart additionalContext+// works the same way -- and the next one belongs in this function, not in a second copy of the+// condition next to each writer.+func hookStdoutIsConsumedAsAgentContext(platform string) bool {+ return platform == kiroPlatform+}++// kiroToolKindFor classifies a Kiro tool by name, and reports whether the name is known at all.+//+// The second result matters: an unknown name is a tool this build has not seen -- an MCP tool, a+// tool added after this table was written -- and the caller falls through to the shared+// classifier rather than being told the tool does nothing.+func kiroToolKindFor(toolName string) (kiroToolKind, bool) {+ kind, ok := kiroToolKinds[strings.ToLower(strings.TrimSpace(toolName))]+ return kind, ok+}++// kiroWriteOperation reads the editor operation a multiplexed write call performed, or "" when the+// call is not one.+//+// Both the arguments and the result are consulted, because they answer at different times: the+// arguments carry the operation on PreToolUse, where there is no result yet, and a result that+// echoes it is available on PostToolUse. The arguments are preferred so the two phases classify+// the same call the same way.+//+// Guarded on the tool name and on the value being a known editor operation, in that order. Both+// guards are load-bearing: the name keeps a shell command line out of here, and the value set+// keeps a shell command that happened to be run through a mis-named tool from being read as an+// operation.+func kiroWriteOperation(toolName string, toolInput, toolResponse map[string]interface{}) string {+ if !kiroMultiplexedWriteTools[strings.ToLower(strings.TrimSpace(toolName))] {+ return ""+ }+ value := strings.ToLower(strings.TrimSpace(firstToolStringAcross(+ []map[string]interface{}{toolInput, toolResponse}, "command", "mode")))+ if !kiroWriteCommands[value] {+ return ""+ }+ return value+}++// kiroWriteCommandIsEditorOperation reports whether a call's `command` argument names an editor+// operation rather than a shell command, so the shared field extraction can leave it alone.+func kiroWriteCommandIsEditorOperation(toolName string, toolInput map[string]interface{}) bool {+ return kiroWriteOperation(toolName, toolInput, nil) != ""+}++// kiroIsMCPToolName reports whether a tool name came from an MCP server.+//+// A leading `@` and a `/`. Both are required: `@builtin`, `@mcp` and `@powers` are matcher+// prefixes an operator writes in a hooks file, not tool names, and none of them carries a slash.+// Requiring the separator is what keeps one of those from being recorded as an MCP call with an+// empty tool.+func kiroIsMCPToolName(toolName string) bool {+ trimmed := strings.TrimSpace(toolName)+ if !strings.HasPrefix(trimmed, kiroMCPToolPrefix) {+ return false+ }+ server, tool, found := strings.Cut(strings.TrimPrefix(trimmed, kiroMCPToolPrefix), "/")+ // Both halves, not just the separator. `@/tool` and `@server/` are malformed rather than+ // namespaced, and accepting either would record an MCP call with a blank server or a blank+ // tool -- a row that looks like MCP activity and names nothing.+ return found && strings.TrimSpace(server) != "" && strings.TrimSpace(tool) != ""+}++// kiroMCPServerTool splits `@server/tool` into its two halves.+//+// The tool half keeps any further slashes rather than being split again, because the separator is+// documented between the server and the tool and a server is free to name a tool with a slash in+// it. Splitting greedily would rename the tool.+func kiroMCPServerTool(toolName string) (server, tool string, ok bool) {+ if !kiroIsMCPToolName(toolName) {+ return "", "", false+ }+ server, tool, _ = strings.Cut(strings.TrimPrefix(strings.TrimSpace(toolName), kiroMCPToolPrefix), "/")+ return strings.TrimSpace(server), strings.TrimSpace(tool), true+}++// kiroToolAction maps a Kiro tool call onto an endpoint event action, or returns "" to let the+// generic classifier decide.+//+// MCP is asked first, before the name table, because an MCP server chooses its own tool names and+// nothing stops one from being called `read`. A name that says it came from a server is a+// statement by the runtime; a name that happens to match a built-in is a coincidence. Kiro is the+// easy case for this -- its MCP names carry a prefix a built-in cannot have -- but the ordering is+// the same one the OpenHands taxonomy needed for a harder version of the question.+func kiroToolAction(toolName string, toolInput, toolResponse map[string]interface{}) string {+ if kiroIsMCPToolName(toolName) {+ return "mcp.tool_invoked"+ }+ kind, known := kiroToolKindFor(toolName)+ if !known {+ return ""+ }+ if operation := kiroWriteOperation(toolName, toolInput, toolResponse); operation != "" {+ kind = kiroWriteKindForOperation(operation)+ }+ switch kind {+ case kiroToolRead:+ return "file.read"+ case kiroToolCreate, kiroToolModify, kiroToolDelete:+ return "file.modified"+ case kiroToolShell:+ return "command.executed"+ default:+ // A known tool with no filesystem or shell meaning. "" hands it to the shared classifier,+ // whose tool.invoked fallback is the right answer -- and which is also where an+ // MCP-flavored name would still be caught if one ever reached here.+ return ""+ }+}++// kiroWriteKindForOperation maps a multiplexed write's operation onto the write kind it is.+func kiroWriteKindForOperation(operation string) kiroToolKind {+ switch operation {+ case "create":+ return kiroToolCreate+ case "delete":+ return kiroToolDelete+ default:+ return kiroToolModify+ }+}++// kiroFileOperation is the `file.operation` value for a Kiro tool, or "" to fall through to the+// generic reader.+//+// Separate from kiroToolAction, as the Qwen and OpenHands pairs are, because the two answer+// different questions: an action says which event this is, an operation says what happened to the+// file. They also disagree here in a way that matters. `delete_file` is a file event, so its+// action belongs in the file family, but "delete" is not a modification and forcing it into+// "create" or "modify" would make a deletion unreadable as one. fx settled that the same way:+// the action stays in the family and the operation keeps its own word.+func kiroFileOperation(toolName string, toolInput, toolResponse map[string]interface{}) string {+ if kiroIsMCPToolName(toolName) {+ return ""+ }+ kind, known := kiroToolKindFor(toolName)+ if !known {+ return ""+ }+ if operation := kiroWriteOperation(toolName, toolInput, toolResponse); operation != "" {+ kind = kiroWriteKindForOperation(operation)+ }+ switch kind {+ case kiroToolRead:+ return "read"+ case kiroToolCreate:+ return "create"+ case kiroToolModify:+ return "modify"+ case kiroToolDelete:+ return "delete"+ default:+ return ""+ }+}++// isKiroFileEditTool reports whether a Kiro tool changes a file, which is what routes a post-tool+// payload down the diff path.+//+// A delete is excluded on purpose. It changes a file and it is recorded as a file event, but there+// is no content on either side of it to build a diff from, and sending it down that path would+// only make the diff builder return nothing after the payload had already been read as an edit.+func isKiroFileEditTool(toolName string, toolInput map[string]interface{}) bool {+ if kiroIsMCPToolName(toolName) {+ return false+ }+ kind, known := kiroToolKindFor(toolName)+ if !known {+ return false+ }+ if operation := kiroWriteOperation(toolName, toolInput, nil); operation != "" {+ kind = kiroWriteKindForOperation(operation)+ }+ return kind == kiroToolCreate || kind == kiroToolModify+}++// kiroToolPath reads the file a call names, out of the one argument shape Kiro documents.+//+// `read`/`fs_read` takes `{"operations": [{"mode": "Line", "path": "..."}]}` rather than a `path`,+// so the shared reader -- which looks for a path at the top level of tool_input -- finds nothing+// and a read event carries no file at all. That is Kiro's most frequent tool.+//+// The first operation's path, when there are several. The endpoint schema's file.path is one+// string, so a multi-file read has to choose, and the alternative -- joining them -- would produce+// a value that is not a path and that no rule matching on file.path could use. What is lost is+// recorded honestly rather than hidden: the event still names the tool, and a reader can see from+// tool.name that a read happened, just not that it covered four files.+//+// Returns "" for anything else, which leaves the shared reader's own key list in charge.+func kiroToolPath(toolInput map[string]interface{}) string {+ operations, ok := toolInput["operations"].([]interface{})+ if !ok {+ return ""+ }+ for _, raw := range operations {+ operation, ok := raw.(map[string]interface{})+ if !ok {+ continue+ }+ if path := firstToolString(operation, "path", "file_path", "filePath"); path != "" {+ return path+ }+ }+ return ""+}++// kiroToolFailed reports whether a tool result describes a failure.+//+// `success` on the tool_response, which Kiro documents on its postToolUse example+// (`{"success": true, "result": [...]}`). Read only when the key is actually present and boolean:+// an absent `success` is not a failure, and treating it as one would record every tool whose+// result Kiro shapes differently as a high-severity failure.+//+// Deliberately not a shell command's exit code. Kiro reports a non-zero exit inside the result of+// a command that ran, which is an ordinary outcome the log should record as command.executed --+// the same call OpenHands' reader makes, and for the same reason: reading it as a failure would+// turn every failing test run and every grep that matched nothing into tool.failed at high+// severity.+func kiroToolFailed(toolResponse map[string]interface{}) bool {+ if toolResponse == nil {+ return false+ }+ value, ok := toolResponse["success"]+ if !ok {+ return false+ }+ switch success := value.(type) {+ case bool:+ return !success+ case string:+ return strings.EqualFold(strings.TrimSpace(success), "false")+ default:+ return false+ }+}++// kiroAssistantResponse reads the agent's final message off a Stop payload.+//+// `assistant_response` is Kiro's own field and the only place the agent's reply reaches a hook.+// Deliberately not added to a shared key list: "assistant_response" is unambiguous here, but the+// shared readers are consulted for every runtime and a key added there is a key read from payloads+// that mean something else by it.+func kiroAssistantResponse(input map[string]interface{}) string {+ return getFirstStr(input, "assistant_response")+}++// emitKiroAssistantResponse records the agent's final reply as its own event.+//+// The shared stop command records that a turn finished; it does not record what the agent said,+// because most runtimes do not tell it. Kiro does, on the same payload, and dropping it would+// throw away the one piece of model output this runtime puts on a hook -- the half of a session+// that prompt.submitted only covers the user's side of.+//+// Written in the OTel GenAI output-messages shape with the retention marker beside it, exactly as+// the agent-thought command writes reasoning, so a reader that already understands one understands+// the other. `agent.message` rather than `agent.reasoning`: this is the reply, not the thinking,+// and it is the action the fx and Devin Cloud mappers already use for the same thing.+func emitKiroAssistantResponse(logger *logging.Logger, input map[string]interface{}, sessionID string) {+ text := kiroAssistantResponse(input)+ if text == "" {+ return+ }+ fields := sessionFields(sessionID, input)+ fields["gen_ai"] = mergeNested(fields["gen_ai"], map[string]interface{}{+ "output": map[string]interface{}{"messages": asymptoteobserve.TextOutputMessages(text)},+ })+ fields["content"] = retainedContentFields(text)+ emitHookEvent(logger, "agent.message", "session", "info", "Agent response captured", input, fields)+}++// applyKiroToolResult attaches what the shared toolFieldsWithResponse cannot reach: the operation a+// write call performed, and a shell command's output.+//+// The operation has to be applied here rather than left to fileOperation because a multiplexed+// write's operation lives in its arguments, and the shared reader has already written its answer+// into the file field by the time this runs.+func applyKiroToolResult(fields map[string]interface{}, toolName string, toolInput, toolResponse map[string]interface{}) {+ if operation := kiroFileOperation(toolName, toolInput, toolResponse); operation != "" {+ if file, ok := fields["file"].(map[string]interface{}); ok {+ file["operation"] = operation+ }+ }+ kind, known := kiroToolKindFor(toolName)+ if !known || kind != kiroToolShell {+ return+ }+ output := kiroResultText(toolResponse)+ if output == "" {+ return+ }+ command := mutableChild(fields["command"])+ command["output"] = output+ fields["command"] = command+ // The retention marker describes the command output specifically, so it is not overwritten:+ // a caller that already retained something -- a diff -- has the more specific claim.+ if _, exists := fields["content"]; !exists {+ fields["content"] = retainedContentFields(output)+ }+}++// kiroResultText joins the text a tool returned.+//+// Kiro's documented tool_response is `{"success": true, "result": [...]}`, where result is a list.+// Its element type is not documented, so both shapes are read: a plain string, and an object with+// the text under one of the usual keys. Anything else is skipped rather than formatted, because+// the alternative is writing a Go rendering of a map into a field a person reads as output.+//+// A bare string `result` is read too, for the same reason the table above carries two catalogs:+// the shape is inferred from one example and the cost of being wrong is a missing field.+//+// The type assertions are deliberate rather than a call to the shared string reader. That reader+// normalizes any value through fmt.Sprint, so a `result` list would come back as Go's rendering of+// a slice -- `[ok \tbeacon\t0.2s\n]`, brackets and all -- written into a field a person reads as+// command output.+func kiroResultText(toolResponse map[string]interface{}) string {+ if toolResponse == nil {+ return ""+ }+ for _, key := range []string{"result", "output", "stdout"} {+ if text, ok := toolResponse[key].(string); ok && text != "" {+ return text+ }+ }+ items, ok := toolResponse["result"].([]interface{})+ if !ok {+ return ""+ }+ var out strings.Builder+ for _, item := range items {+ switch value := item.(type) {+ case string:+ out.WriteString(value)+ case map[string]interface{}:+ if text := firstToolString(value, "text", "output", "content", "stdout"); text != "" {+ out.WriteString(text)+ }+ }+ }+ return out.String()+}++// parseKiroEdit turns one post-tool payload into the file edit it performed, or nil when it is not+// one.+//+// A single edit rather than the slice the OpenHands reader returns: Kiro's write tools each name+// one file, and there is no patch tool that commits several at once.+//+// nil is not a failure. It means this payload is not a recordable edit -- a read, a shell command,+// a delete, a write 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 parseKiroEdit(input map[string]interface{}, logger *logging.Logger) *evaluationParams {+ toolName := getFirstStr(input, "tool_name")+ toolInput := resolveToolInput(input)+ toolResponse := resolveToolResponse(input)++ if !isKiroFileEditTool(toolName, toolInput) {+ return nil+ }+ // A failure is not an edit. Kiro reports a failed write with the same tool name and the same+ // arguments as a successful one -- `success` on the result is the only thing that separates+ // them -- so without this guard a diff would be built from the content of a write that never+ // landed, and the log would assert a file changed when it did not. Same guard, same reason, as+ // the Qwen and OpenHands branches.+ if kiroToolFailed(toolResponse) {+ return nil+ }++ filePath := hookdiff.NormalizePath(kiroEditPath(toolInput, toolResponse))+ if filePath == "" {+ return nil+ }+ if !config.IsScannableFile(filePath) {+ logger.Debug("Skipping non-scannable file: " + filePath)+ return nil+ }+ diffStr := hookdiff.FromKiroWrite(kiroWriteOperation(toolName, toolInput, toolResponse), toolName, toolInput, toolResponse)+ if diffStr == "" {+ logger.Debug("Could not construct diff, skipping", "tool_name", toolName, "file_path", filePath)+ return nil+ }+ return &evaluationParams{+ sessionID: resolveSessionID(input, kiroPlatform),+ toolName: toolName,+ filePath: filePath,+ diffStr: diffStr,+ }+}++// kiroEditPath resolves the file a write call targeted.+//+// The arguments first and the result second, both across the same key list, because Kiro publishes+// neither shape and the two plausible spellings -- `path` from the Amazon Q lineage, `file_path`+// from the ecosystem convention -- cost nothing to read together. The operations array is+// consulted last: a write does not use it, but a tool that multiplexes reads and writes onto one+// name would.+func kiroEditPath(toolInput, toolResponse map[string]interface{}) string {+ if path := firstToolStringAcross(+ []map[string]interface{}{toolInput, toolResponse},+ "path", "file_path", "filePath", "Path", "absolute_path"); path != "" {+ return path+ }+ return kiroToolPath(toolInput)+}diff --git a/cli/beacon-hooks/cmd/kiro_hooks_test.go b/cli/beacon-hooks/cmd/kiro_hooks_test.gonew file mode 100644index 00000000..2ad524fd--- /dev/null+++ b/cli/beacon-hooks/cmd/kiro_hooks_test.go@@ -0,0 +1,885 @@+package cmd++import (+ "path/filepath"+ "strings"+ "testing"+)++// Kiro hook payloads are the shapes Kiro documents, reproduced rather than approximated:+// `hook_event_name`, `cwd`, `session_id`, `tool_name`, `tool_input`, `tool_response`, `prompt`,+// `assistant_response`, with `read`'s arguments as an `operations` array and a tool result as+// `{"success": ..., "result": [...]}`.+//+// They carry more weight than the usual fixture, for two reasons specific to this runtime. Kiro+// publishes its tool *names* and not its tool *arguments*, so the readers below are the written+// record of which spellings Beacon reads and which it deliberately does not. And Kiro's hook+// contract is exit codes rather than response objects, so a mapping that stopped working would+// produce no error anywhere: the hook would exit 0, the turn would proceed, and the only visible+// symptom would be a missing line in the runtime log.++// containsLine reports whether a rendered diff carries an exact line.+//+// Exact rather than a substring of the whole blob: "+return err" is a substring of a diff that+// only ever wrote "+return errors.New(...)", and an assertion that cannot tell those apart would+// pass for a diff describing the wrong change.+func containsLine(diff, want string) bool {+ for _, line := range strings.Split(diff, "\n") {+ if line == want {+ return true+ }+ }+ return false+}++func kiroTestSetup(t *testing.T) string {+ t.Helper()+ setupHookConfigDirs(t)+ platformFlag = kiroPlatform+ 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 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+}++// kiroReadInput is the one tool-argument shape Kiro documents: a `read` call takes an operations+// array rather than a path.+func kiroReadInput(paths ...string) map[string]interface{} {+ operations := make([]interface{}, 0, len(paths))+ for _, path := range paths {+ operations = append(operations, map[string]interface{}{"mode": "Line", "path": path})+ }+ return map[string]interface{}{"operations": operations}+}++// kiroResult is Kiro's documented tool_response envelope.+func kiroResult(success bool, parts ...string) map[string]interface{} {+ items := make([]interface{}, 0, len(parts))+ for _, part := range parts {+ items = append(items, part)+ }+ return map[string]interface{}{"success": success, "result": items}+}++// ---------------------------------------------------------------------------+// Envelope+// ---------------------------------------------------------------------------++// Kiro spells the envelope exactly as Claude Code does, which is why this file contains no+// envelope readers at all. Pinned rather than assumed: session.id and session.working_directory on+// every Kiro event come from these two shared default cases, and a refactor of either would take+// Kiro's session identity with it silently.+func TestKiroEnvelopeResolvesThroughTheSharedReaders(t *testing.T) {+ input := map[string]interface{}{+ "hook_event_name": "preToolUse",+ "session_id": "abc123-def456-789",+ "cwd": "/current/working/directory",+ }+ if got := resolveSessionID(input, kiroPlatform); got != "abc123-def456-789" {+ t.Fatalf("resolveSessionID = %q, want abc123-def456-789", got)+ }+ if got := resolveCwd(input, kiroPlatform); got != "/current/working/directory" {+ t.Fatalf("resolveCwd = %q, want /current/working/directory", got)+ }+}++// ---------------------------------------------------------------------------+// Stdout+// ---------------------------------------------------------------------------++// The property this whole suppression exists for. On Kiro a hook's stdout is not a response+// object: on exit 0 it is *added to the agent's context* for SessionStart and UserPromptSubmit and+// ignored everywhere else. Beacon's shared commands all finish by writing `{}` or+// `{"permission":"allow"}`, so without the suppression an observing hook would be pasting text in+// front of the model at the start of every session and before every prompt.+func TestKiroHooksWriteNothingToStdout(t *testing.T) {+ for _, tc := range []struct {+ name string+ input map[string]interface{}+ }{+ {+ name: "session-start",+ input: map[string]interface{}{"hook_event_name": "sessionStart", "session_id": "k1", "cwd": "/repo"},+ },+ {+ name: "prompt-submit",+ input: map[string]interface{}{"hook_event_name": "userPromptSubmit", "session_id": "k1", "cwd": "/repo", "prompt": "hello"},+ },+ {+ name: "pre-tool",+ input: map[string]interface{}{+ "hook_event_name": "preToolUse", "session_id": "k1", "cwd": "/repo",+ "tool_name": "read", "tool_input": kiroReadInput("/repo/main.go"),+ },+ },+ {+ name: "post-tool",+ input: map[string]interface{}{+ "hook_event_name": "postToolUse", "session_id": "k1", "cwd": "/repo",+ "tool_name": "read", "tool_input": kiroReadInput("/repo/main.go"),+ "tool_response": kiroResult(true, "package main"),+ },+ },+ // stop is deliberately absent. runStop ends the session-bearing path with+ // outputJSONAndExit, and os.Exit in an in-process test aborts the run -- the same reason+ // the Qwen and OpenHands stop tests exercise their mapping directly. What matters for+ // stdout is already covered: outputJSONAndExit writes through outputJSON, so the+ // suppression it inherits is the same one the four commands above prove.+ } {+ t.Run(tc.name, func(t *testing.T) {+ kiroTestSetup(t)+ var out map[string]interface{}+ switch tc.name {+ case "session-start":+ out = runHookWithInput(t, runSessionStart, tc.input)+ case "prompt-submit":+ out = runHookWithInput(t, runPromptSubmit, tc.input)+ case "pre-tool":+ out = runHookWithInput(t, runPreTool, tc.input)+ case "post-tool":+ out = runHookWithInput(t, runPostTool, tc.input)+ }+ if len(out) != 0 {+ t.Fatalf("%s wrote %#v to stdout; on Kiro that is agent context, not a response", tc.name, out)+ }+ })+ }+}++// The suppression must be Kiro's alone. Every other runtime reads a hook's stdout as its response,+// and silencing one of those would turn an observing hook into a hook that answers nothing --+// which on Cursor is a missing `continue` and on Claude Code a missing permission object.+func TestStdoutSuppressionIsScopedToKiro(t *testing.T) {+ for _, platform := range []string{"claude", "cursor", "qwen", "muse", openHandsPlatform} {+ t.Run(platform, func(t *testing.T) {+ if hookStdoutIsConsumedAsAgentContext(platform) {+ t.Fatalf("hookStdoutIsConsumedAsAgentContext(%q) = true; only Kiro reads hook "++ "stdout as agent context", platform)+ }+ })+ }+ if !hookStdoutIsConsumedAsAgentContext(kiroPlatform) {+ t.Fatal("hookStdoutIsConsumedAsAgentContext(kiro) = false, want true")+ }+}++// A runtime whose stdout is agent context still emits its telemetry. Suppressing the response must+// not suppress the event, which is the only thing the hook exists to produce.+func TestKiroStdoutSuppressionDoesNotSuppressTelemetry(t *testing.T) {+ logPath := kiroTestSetup(t)++ runHookWithInput(t, runPromptSubmit, map[string]interface{}{+ "hook_event_name": "userPromptSubmit",+ "session_id": "k-prompt",+ "cwd": "/repo",+ "prompt": "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 prompt text", got)+ }+ if got := leaf(event, "harness", "name"); got != "kiro" {+ t.Fatalf("harness.name = %q, want the canonical kiro", got)+ }+ if got := leaf(event, "harness", "collection_method"); got != "hook" {+ t.Fatalf("harness.collection_method = %q, want hook", got)+ }+ if got := leaf(event, "session", "working_directory"); got != "/repo" {+ t.Fatalf("session.working_directory = %q, want /repo", got)+ }+}++// ---------------------------------------------------------------------------+// Pre-tool+// ---------------------------------------------------------------------------++// Kiro exposes no approval decision to a hook, and it is the sharpest case for not synthesizing+// one: Kiro genuinely does ask the operator, through permissions.yaml and an interactive trust+// picker, and PreToolUse fires identically whether the call was pre-approved by a rule, waved+// through by autopilot, or about to stop and wait for a person. An approval.allowed derived from+// it would claim a decision in exactly the cases where none has been made.+func TestKiroPreToolObservesWithoutSynthesizingAnApproval(t *testing.T) {+ logPath := kiroTestSetup(t)++ runHookWithInput(t, runPreTool, map[string]interface{}{+ "hook_event_name": "preToolUse",+ "session_id": "k-pre",+ "cwd": "/repo",+ "tool_name": "shell",+ "tool_input": map[string]interface{}{"command": "rm -rf /tmp/data"},+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "tool.invoked" {+ t.Fatalf("event.action = %q, want tool.invoked", got)+ }+ if _, ok := event["approval"]; ok {+ t.Fatalf("pre-tool recorded an approval Kiro never reported: %#v", event["approval"])+ }+ if got := leaf(event, "command", "command"); got != "rm -rf /tmp/data" {+ t.Fatalf("command.command = %q, want the shell command", got)+ }+}++// ---------------------------------------------------------------------------+// Tool taxonomy+// ---------------------------------------------------------------------------++// The table's whole reason for existing. Every one of these names is wrong under the generic+// substring classifier: `execute_bash` contains none of the words it looks for and would be an+// unclassified tool.invoked, `fs_write` and `str_replace` are not Claude's PascalCase edit names,+// and `list_directory` only reaches file.read by accident of containing "list".+func TestKiroToolActions(t *testing.T) {+ for _, tc := range []struct {+ tool string+ want string+ }{+ {"read", "file.read"},+ {"fs_read", "file.read"},+ {"fsRead", "file.read"},+ {"read_file", "file.read"},+ {"read_files", "file.read"},+ {"list_directory", "file.read"},+ {"file_search", "file.read"},+ {"glob", "file.read"},+ {"grep_search", "file.read"},+ {"grep", "file.read"},+ {"code", "file.read"},+ {"read_code", "file.read"},+ {"write", "file.modified"},+ {"fs_write", "file.modified"},+ {"fsWrite", "file.modified"},+ {"fs_append", "file.modified"},+ {"str_replace", "file.modified"},+ {"delete_file", "file.modified"},+ {"shell", "command.executed"},+ {"execute_bash", "command.executed"},+ {"execute_cmd", "command.executed"},+ {"control_bash_process", "command.executed"},+ {"@postgres/query", "mcp.tool_invoked"},+ } {+ t.Run(tc.tool, func(t *testing.T) {+ if got := kiroToolAction(tc.tool, nil, nil); got != tc.want {+ t.Fatalf("kiroToolAction(%q) = %q, want %q", tc.tool, got, tc.want)+ }+ })+ }+}++// Tools that read or report state rather than doing something to the machine hand the answer back+// to the shared classifier, whose tool.invoked fallback is right for them. "" rather than a+// default is what keeps that true, and it is also what stops a later substring rule from+// promoting `list_processes` or `get_process_output` to command executions.+func TestKiroNonFilesystemToolsFallThroughToTheSharedClassifier(t *testing.T) {+ for _, tool := range []string{+ "get_process_output", "list_processes", "aws", "use_aws", "web_search", "web_fetch",+ "invoke_subagent", "disclose_context", "introspect", "todo_list", "tool_search",+ "create_hook", "kiro_powers",+ } {+ t.Run(tool, func(t *testing.T) {+ if got := kiroToolAction(tool, nil, nil); got != "" {+ t.Fatalf("kiroToolAction(%q) = %q, want \"\" so the shared classifier answers", tool, got)+ }+ if got := actionForTool("postToolUse", tool, nil, nil); got != "tool.invoked" {+ t.Fatalf("actionForTool(%q) = %q, want tool.invoked", tool, got)+ }+ })+ }+}++// A tool this build has not seen is not a tool that does nothing. An unknown name has to fall to+// the shared classifier, or a Kiro build that adds a tool would have every call to it recorded as+// an unclassifiable event rather than as whatever its name says.+func TestKiroUnknownToolNamesFallThroughToTheSharedClassifier(t *testing.T) {+ if got := kiroToolAction("some_future_tool", nil, nil); got != "" {+ t.Fatalf("kiroToolAction(unknown) = %q, want \"\"", got)+ }+ if _, known := kiroToolKindFor("some_future_tool"); known {+ t.Fatal("kiroToolKindFor reported an unknown tool as known")+ }+}++// file.operation answers a different question from event.action and disagrees with it here on+// purpose. `delete_file` belongs in the file family as an action, but "delete" is not a+// modification, and forcing it into "create" or "modify" would make a deletion unreadable as one.+func TestKiroFileOperations(t *testing.T) {+ for _, tc := range []struct {+ tool string+ want string+ }{+ {"read", "read"},+ {"grep", "read"},+ {"write", "create"},+ {"fs_write", "create"},+ {"fs_append", "modify"},+ {"str_replace", "modify"},+ {"delete_file", "delete"},+ {"shell", ""},+ {"web_fetch", ""},+ } {+ t.Run(tc.tool, func(t *testing.T) {+ if got := kiroFileOperation(tc.tool, nil, nil); got != tc.want {+ t.Fatalf("kiroFileOperation(%q) = %q, want %q", tc.tool, got, tc.want)+ }+ })+ }+}++// A delete is a file event and is not an edit. Sending it down the diff path would read the+// payload as an edit and then find no content on either side to render, so it is excluded at the+// predicate rather than discovered by the diff builder.+func TestKiroDeleteIsAFileEventButNotAnEdit(t *testing.T) {+ if got := kiroToolAction("delete_file", nil, nil); got != "file.modified" {+ t.Fatalf("kiroToolAction(delete_file) = %q, want file.modified", got)+ }+ if isKiroFileEditTool("delete_file", nil) {+ t.Fatal("isKiroFileEditTool(delete_file) = true; a delete has no content to diff")+ }+}++// ---------------------------------------------------------------------------+// The read tool's operations array+// ---------------------------------------------------------------------------++// Kiro's most frequent tool puts the path inside an `operations` array, which none of the shared+// path keys can see into. Without the reader a read event carries a tool name and no file at all.+func TestKiroReadPathComesFromTheOperationsArray(t *testing.T) {+ logPath := kiroTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "hook_event_name": "postToolUse",+ "session_id": "k-read",+ "cwd": "/repo",+ "tool_name": "read",+ "tool_input": kiroReadInput("/repo/docs/hooks.md"),+ "tool_response": kiroResult(true, "# Hooks\n"),+ })++ 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 != "/repo/docs/hooks.md" {+ t.Fatalf("file.path = %q, want the path from operations[0]", got)+ }+ if got := leaf(event, "file", "operation"); got != "read" {+ t.Fatalf("file.operation = %q, want read", got)+ }+ if got := leaf(event, "file", "language"); got != "md" {+ t.Fatalf("file.language = %q, want md", got)+ }+}++// A top-level path is a more direct statement than an operations array, so it wins. This is what+// keeps the Kiro reader additive: it fills a gap rather than overriding what the payload said.+func TestKiroTopLevelPathBeatsTheOperationsArray(t *testing.T) {+ toolInput := kiroReadInput("/repo/from-operations.go")+ toolInput["path"] = "/repo/from-top-level.go"++ fields := toolFieldsWithResponse("read", toolInput, nil)+ file, ok := fields["file"].(map[string]interface{})+ if !ok {+ t.Fatalf("no file field: %#v", fields)+ }+ if got, _ := file["path"].(string); got != "/repo/from-top-level.go" {+ t.Fatalf("file.path = %q, want the top-level path", got)+ }+}++// The operations reader must stay Kiro's. `operations` is a generic word, and reading it for every+// runtime would put a path into an event for a payload that meant something else by it.+func TestOperationsArrayIsNotReadForOtherRuntimes(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "claude"+ fields := toolFieldsWithResponse("Read", kiroReadInput("/repo/main.go"), nil)+ if _, ok := fields["file"]; ok {+ t.Fatalf("claude read an operations array Kiro alone uses: %#v", fields["file"])+ }+}++// ---------------------------------------------------------------------------+// The write tool's command argument+// ---------------------------------------------------------------------------++// The defect this guard exists to prevent. Kiro's write tool descends from Amazon Q Developer+// CLI's multiplexed fs_write, where `command` names the editor operation -- and `command` is also+// what the shell tool calls its command line. Without the guard, "str_replace" is written into+// command.command and the policy seam upgrades the call from a file edit to a shell execution.+func TestKiroWriteCommandArgumentIsNotAShellCommand(t *testing.T) {+ logPath := kiroTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "hook_event_name": "postToolUse",+ "session_id": "k-write",+ "cwd": "/repo",+ "tool_name": "fs_write",+ "tool_input": map[string]interface{}{+ "command": "str_replace",+ "path": "/repo/app.go",+ "old_str": "old line",+ "new_str": "new line",+ },+ "tool_response": kiroResult(true, "Edited /repo/app.go"),+ })++ event := lastEndpointEvent(t, logPath)+ if _, ok := event["command"]; ok {+ t.Fatalf("a write's editor operation was recorded as a shell command: %#v", event["command"])+ }+ 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 != "/repo/app.go" {+ t.Fatalf("file.path = %q, want /repo/app.go", got)+ }+ if got := leaf(event, "file", "operation"); got != "modify" {+ t.Fatalf("file.operation = %q, want modify -- command=str_replace is a replacement", got)+ }+}++// The other half of the same guard. On the shell tool `command` really is the command line, and a+// set that reached it would drop the one field that makes a shell event worth recording.+func TestKiroShellCommandIsStillRecorded(t *testing.T) {+ logPath := kiroTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "hook_event_name": "postToolUse",+ "session_id": "k-shell",+ "cwd": "/repo",+ "tool_name": "execute_bash",+ "tool_input": map[string]interface{}{"command": "go test ./...", "summary": "run tests"},+ "tool_response": kiroResult(true, "ok \tbeacon\t0.2s\n"),+ })++ 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)+ }+ if got := leaf(event, "command", "output"); got != "ok \tbeacon\t0.2s\n" {+ t.Fatalf("command.output = %q, want the tool result text", got)+ }+ if _, ok := event["content"].(map[string]interface{}); !ok {+ t.Fatalf("no content marker for the retained command output: %#v", event["content"])+ }+}++// A `command` value that is not one of the editor operations is not treated as one. The value set+// is the second half of the guard: without it, a write tool that really did carry a command line+// would have it swallowed instead of recorded.+func TestKiroWriteGuardOnlyClaimsKnownEditorOperations(t *testing.T) {+ if kiroWriteCommandIsEditorOperation("fs_write", map[string]interface{}{"command": "rm -rf /"}) {+ t.Fatal("the write guard claimed a shell command line as an editor operation")+ }+ if !kiroWriteCommandIsEditorOperation("fs_write", map[string]interface{}{"command": "create"}) {+ t.Fatal("the write guard missed a known editor operation")+ }+ if kiroWriteCommandIsEditorOperation("execute_bash", map[string]interface{}{"command": "create"}) {+ t.Fatal("the write guard reached the shell tool, where `command` is the command line")+ }+}++// ---------------------------------------------------------------------------+// MCP+// ---------------------------------------------------------------------------++// Kiro names an MCP tool `@server/tool`, which carries none of the signals the shared MCP+// detection looks for: no "mcp" in the name, no mcp_* argument, and a result that is whatever the+// server returned. Without the branch the call is an ordinary tool.invoked whose tool name starts+// with a punctuation mark.+func TestKiroMCPToolIsRecognizedFromItsName(t *testing.T) {+ logPath := kiroTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "hook_event_name": "postToolUse",+ "session_id": "k-mcp",+ "cwd": "/repo",+ "tool_name": "@postgres/query",+ "tool_input": map[string]interface{}{"sql": "SELECT * FROM orders LIMIT 10;"},+ "tool_response": kiroResult(true, "10 rows"),+ })++ 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 != "postgres" {+ t.Fatalf("mcp.server = %q, want postgres", got)+ }+ if got := leaf(event, "mcp", "tool"); got != "query" {+ t.Fatalf("mcp.tool = %q, want query", got)+ }+}++// `@builtin`, `@mcp` and `@powers` are matcher prefixes an operator writes in a hooks file, not+// tool names. Requiring the slash is what keeps one of them from being recorded as an MCP call+// with an empty tool.+func TestKiroMatcherPrefixesAreNotMCPToolNames(t *testing.T) {+ for _, name := range []string{"@builtin", "@mcp", "@powers", "@", "@server/", "@/tool"} {+ t.Run(name, func(t *testing.T) {+ if kiroIsMCPToolName(name) {+ t.Fatalf("kiroIsMCPToolName(%q) = true; only @server/tool is a tool name", name)+ }+ })+ }+}++// A server is free to name a tool with a slash in it, so only the first separator splits.+func TestKiroMCPToolNameSplitsOnTheFirstSeparatorOnly(t *testing.T) {+ server, tool, ok := kiroMCPServerTool("@github/repos/get")+ if !ok {+ t.Fatal("kiroMCPServerTool did not recognize a namespaced tool name")+ }+ if server != "github" || tool != "repos/get" {+ t.Fatalf("kiroMCPServerTool = (%q, %q), want (github, repos/get)", server, tool)+ }+}++// An MCP server chooses its own tool names and nothing stops one from being called `read`. The+// prefix is a statement by the runtime; a name that matches a built-in is a coincidence, so MCP is+// asked first.+func TestKiroMCPNameBeatsAColidingBuiltinName(t *testing.T) {+ if got := kiroToolAction("@files/read", nil, nil); got != "mcp.tool_invoked" {+ t.Fatalf("kiroToolAction(@files/read) = %q, want mcp.tool_invoked", got)+ }+ if got := kiroFileOperation("@files/read", nil, nil); got != "" {+ t.Fatalf("kiroFileOperation(@files/read) = %q, want \"\"", got)+ }+}++// ---------------------------------------------------------------------------+// Failures+// ---------------------------------------------------------------------------++// Kiro says so on the result: its documented tool_response carries `success`.+func TestKiroFailedToolIsRecordedAsAFailure(t *testing.T) {+ logPath := kiroTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "hook_event_name": "postToolUse",+ "session_id": "k-fail",+ "cwd": "/repo",+ "tool_name": "fs_write",+ "tool_input": map[string]interface{}{"path": "/repo/locked.go", "content": "package main\n"},+ "tool_response": map[string]interface{}{"success": false, "result": []interface{}{"permission denied"}},+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "tool.failed" {+ t.Fatalf("event.action = %q, want tool.failed", got)+ }+ if got, _ := event["severity"].(string); got != "high" {+ t.Fatalf("severity = %q, want high", got)+ }+}++// A write that failed is not an edit. Kiro reports it with the same tool name and the same+// arguments as a successful one, so without the guard a diff would be built from the content of a+// write that never landed and the log would assert a file changed when it did not.+func TestKiroFailedWriteProducesNoDiff(t *testing.T) {+ logPath := kiroTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "hook_event_name": "postToolUse",+ "session_id": "k-fail-write",+ "cwd": "/repo",+ "tool_name": "fs_write",+ "tool_input": map[string]interface{}{"path": "/repo/app.go", "content": "package main\n"},+ "tool_response": map[string]interface{}{"success": false, "result": []interface{}{"EACCES"}},+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "tool.failed" {+ t.Fatalf("event.action = %q, want tool.failed", got)+ }+ if _, ok := event["file"].(map[string]interface{})["diff"]; ok {+ t.Fatalf("a failed write produced a diff: %#v", event["file"])+ }+}++// An absent `success` is not a failure. Kiro documents the key on postToolUse and nowhere else, so+// treating its absence as failure would record every tool whose result is shaped differently as a+// high-severity failure.+func TestKiroMissingSuccessKeyIsNotAFailure(t *testing.T) {+ if kiroToolFailed(map[string]interface{}{"result": []interface{}{"fine"}}) {+ t.Fatal("kiroToolFailed = true for a result with no success key")+ }+ if kiroToolFailed(nil) {+ t.Fatal("kiroToolFailed = true for an absent result")+ }+ if !kiroToolFailed(map[string]interface{}{"success": false}) {+ t.Fatal("kiroToolFailed = false for success:false")+ }+}++// A shell command that exits non-zero ran. Reading its exit status as a tool failure would turn+// every failing test run and every grep that matched nothing into a high-severity event.+func TestKiroNonZeroExitIsNotAToolFailure(t *testing.T) {+ logPath := kiroTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "hook_event_name": "postToolUse",+ "session_id": "k-exit",+ "cwd": "/repo",+ "tool_name": "shell",+ "tool_input": map[string]interface{}{"command": "go test ./..."},+ "tool_response": map[string]interface{}{+ "success": true,+ "result": []interface{}{map[string]interface{}{"text": "FAIL\n", "exit_code": float64(1)}},+ },+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "command.executed" {+ t.Fatalf("event.action = %q, want command.executed", got)+ }+}++// ---------------------------------------------------------------------------+// File edits+// ---------------------------------------------------------------------------++func TestKiroCreateProducesAWholeFileDiff(t *testing.T) {+ logPath := kiroTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "hook_event_name": "postToolUse",+ "session_id": "k-create",+ "cwd": "/repo",+ "tool_name": "fs_write",+ "tool_input": map[string]interface{}{+ "command": "create",+ "path": "/repo/health.go",+ "file_text": "package main\n\nfunc health() {}\n",+ },+ "tool_response": kiroResult(true, "Created /repo/health.go"),+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "file.modified" {+ t.Fatalf("event.action = %q, want file.modified", got)+ }+ diff := leaf(event, "file", "diff")+ if diff == "" {+ t.Fatal("no diff recorded for a create")+ }+ for _, want := range []string{"+++ b/health.go", "+func health() {}"} {+ if !containsLine(diff, want) {+ t.Fatalf("diff missing %q:\n%s", want, diff)+ }+ }+}++// The ecosystem spelling and the Amazon Q spelling are both read, because Kiro publishes neither+// and the cost of reading both is one lookup. `content` is the one that would otherwise be missed+// by a reader written only against the Q lineage.+func TestKiroCreateReadsBothContentSpellings(t *testing.T) {+ for _, key := range []string{"file_text", "content", "text"} {+ t.Run(key, func(t *testing.T) {+ logPath := kiroTestSetup(t)+ runHookWithInput(t, runPostTool, map[string]interface{}{+ "hook_event_name": "postToolUse",+ "session_id": "k-create-" + key,+ "cwd": "/repo",+ "tool_name": "write",+ "tool_input": map[string]interface{}{"path": "/repo/a.go", key: "package main\n"},+ "tool_response": kiroResult(true, "ok"),+ })+ if diff := leaf(lastEndpointEvent(t, logPath), "file", "diff"); diff == "" {+ t.Fatalf("no diff when the content arrived under %q", key)+ }+ })+ }+}++func TestKiroStrReplaceProducesAnEditDiff(t *testing.T) {+ logPath := kiroTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "hook_event_name": "postToolUse",+ "session_id": "k-replace",+ "cwd": "/repo",+ "tool_name": "str_replace",+ "tool_input": map[string]interface{}{+ "path": "/repo/app.go",+ "old_str": "return nil",+ "new_str": "return err",+ },+ "tool_response": kiroResult(true, "Edited /repo/app.go"),+ })++ diff := leaf(lastEndpointEvent(t, logPath), "file", "diff")+ if !containsLine(diff, "-return nil") || !containsLine(diff, "+return err") {+ t.Fatalf("edit diff did not describe the replacement:\n%s", diff)+ }+}++// An append adds lines and removes none, so its diff has an empty old side rather than no diff.+func TestKiroAppendProducesAnAdditionOnlyDiff(t *testing.T) {+ logPath := kiroTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "hook_event_name": "postToolUse",+ "session_id": "k-append",+ "cwd": "/repo",+ "tool_name": "fs_append",+ "tool_input": map[string]interface{}{"path": "/repo/notes.go", "new_str": "// appended\n"},+ "tool_response": kiroResult(true, "ok"),+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "file", "operation"); got != "modify" {+ t.Fatalf("file.operation = %q, want modify", got)+ }+ diff := leaf(event, "file", "diff")+ if !containsLine(diff, "+// appended") {+ t.Fatalf("append diff did not describe the addition:\n%s", diff)+ }+ if containsLine(diff, "-// appended") {+ t.Fatalf("append diff removed a line it should only have added:\n%s", diff)+ }+}++// A write whose arguments this build cannot read is recorded as a file event with no diff, not+// dropped. The event still names the file and the operation, which is the part an investigator+// needs; the diff is the part that is honestly unavailable.+func TestKiroUnreadableWriteStillRecordsTheFileEvent(t *testing.T) {+ logPath := kiroTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "hook_event_name": "postToolUse",+ "session_id": "k-opaque",+ "cwd": "/repo",+ "tool_name": "fs_write",+ "tool_input": map[string]interface{}{"path": "/repo/app.go", "payload": "some unknown shape"},+ "tool_response": kiroResult(true, "ok"),+ })++ 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 != "/repo/app.go" {+ t.Fatalf("file.path = %q, want /repo/app.go", got)+ }+ if got := leaf(event, "file", "diff"); got != "" {+ t.Fatalf("file.diff = %q, want empty for an unreadable write", got)+ }+}++// ---------------------------------------------------------------------------+// Stop+// ---------------------------------------------------------------------------++// Kiro puts the agent's final reply on the Stop payload and nowhere else. The shared stop command+// records that a turn finished and not what was said, so without this the one piece of model+// output Kiro puts on a hook is lost -- leaving sessions where only the user's half is recorded.+// The emitter is exercised directly rather than through runStop, which ends the session-bearing+// path with outputJSONAndExit and would abort the test run. Same workaround, same reason, as the+// Qwen and OpenHands stop tests; the arguments below are the ones runStop passes it.+func TestKiroStopRecordsTheAssistantResponse(t *testing.T) {+ logPath := kiroTestSetup(t)++ input := map[string]interface{}{+ "hook_event_name": "stop",+ "session_id": "k-stop",+ "cwd": "/repo",+ "assistant_response": "I added the health endpoint and the test passes.",+ }+ sessionID := resolveSessionID(input, kiroPlatform)+ if sessionID != "k-stop" {+ t.Fatalf("stop session id = %q; the mapping under test would not run", sessionID)+ }+ emitKiroAssistantResponse(newHookLogger("stop", kiroPlatform, sessionID), input, sessionID)++ message := lastEndpointEvent(t, logPath)+ if got := leaf(message, "event", "action"); got != "agent.message" {+ t.Fatalf("event.action = %q, want agent.message", got)+ }+ if got := leaf(message, "event", "category"); got != "session" {+ t.Fatalf("event.category = %q, want session", got)+ }+ if _, ok := message["content"].(map[string]interface{}); !ok {+ t.Fatalf("no content marker for the retained response: %#v", message["content"])+ }+ if got := leaf(message, "session", "id"); got != "k-stop" {+ t.Fatalf("session.id = %q, want k-stop", got)+ }+ if got := leaf(message, "harness", "name"); got != "kiro" {+ t.Fatalf("harness.name = %q, want kiro", got)+ }+ // The text reaches the log in the OTel GenAI output-messages shape, so a reader that already+ // understands hook-captured reasoning understands this too rather than needing a Kiro-shaped+ // special case.+ genAI, ok := message["gen_ai"].(map[string]interface{})+ if !ok {+ t.Fatalf("no gen_ai block: %#v", message)+ }+ output, ok := genAI["output"].(map[string]interface{})+ if !ok {+ t.Fatalf("no gen_ai.output block: %#v", genAI)+ }+ messages, ok := output["messages"].([]interface{})+ if !ok || len(messages) == 0 {+ t.Fatalf("gen_ai.output.messages = %#v, want the assistant response", output["messages"])+ }+}++// A Stop with no reply writes no message event. An empty agent.message would assert the agent+// answered with nothing, which is different from the runtime not reporting an answer.+func TestKiroStopWithoutAResponseWritesNoMessageEvent(t *testing.T) {+ logPath := kiroTestSetup(t)++ // Something else has to be in the log, or an empty file would pass this for the wrong reason.+ runHookWithInput(t, runSessionStart, map[string]interface{}{+ "hook_event_name": "sessionStart", "session_id": "k-stop-quiet", "cwd": "/repo",+ })+ input := map[string]interface{}{+ "hook_event_name": "stop",+ "session_id": "k-stop-quiet",+ "cwd": "/repo",+ }+ emitKiroAssistantResponse(newHookLogger("stop", kiroPlatform, "k-stop-quiet"), input, "k-stop-quiet")++ for _, event := range endpointEvents(t, logPath) {+ if leaf(event, "event", "action") == "agent.message" {+ t.Fatalf("wrote an agent.message for a Stop with no assistant_response: %#v", event)+ }+ }+}++// assistant_response must stay Kiro's. The shared prompt and thought readers are consulted for+// every runtime, and a key added there is a key read from payloads that mean something else by it.+func TestKiroAssistantResponseIsNotReadForOtherRuntimes(t *testing.T) {+ logPath := kiroTestSetup(t)+ platformFlag = "claude"++ // A Claude Code Stop payload carrying the same key. The branch that reads it is guarded on the+ // platform, so no message event may appear -- and prompt-submit, which does run end to end+ // here, must not pick the key up either.+ runHookWithInput(t, runPromptSubmit, map[string]interface{}{+ "hook_event_name": "UserPromptSubmit",+ "session_id": "claude-stop",+ "cwd": "/repo",+ "assistant_response": "not read on this runtime",+ })++ for _, event := range endpointEvents(t, logPath) {+ if leaf(event, "event", "action") == "agent.message" {+ t.Fatalf("claude recorded an agent.message from a Kiro-only key: %#v", event)+ }+ if got := leaf(event, "prompt", "text"); got == "not read on this runtime" {+ t.Fatalf("assistant_response leaked into prompt.text: %q", got)+ }+ }+}diff --git a/cli/beacon-hooks/cmd/post_tool.go b/cli/beacon-hooks/cmd/post_tool.goindex 2c29bacd..de31a83a 100644--- a/cli/beacon-hooks/cmd/post_tool.go+++ b/cli/beacon-hooks/cmd/post_tool.go@@ -83,6 +83,14 @@ func runPostTool(cmd *cobra.Command, args []string) {outputJSON(emptyResponse)return}+ } else if platformFlag == kiroPlatform {+ // Kiro gets its own reader rather than riding parseClaudeCopilotInput because a write may+ // name its operation in an argument rather than in the tool name, and because the argument+ // spellings are not published -- both of which the shared reader has no way to ask about.+ // A nil result is not a failure: it means this payload is a read, a shell command, a+ // 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 {params = parseClaudeCopilotInput(input, logger)}@@ -396,6 +404,16 @@ func emitPostToolObserved(logger *logging.Logger, input map[string]interface{})return}}+ // Kiro says so on the result itself: its documented tool_response carries `success`. Same+ // predicate the diff path uses, called rather than restated, so the two cannot drift the way+ // the Qwen pair once did.+ if platformFlag == kiroPlatform {+ applyKiroToolResult(fields, toolName, toolInput, toolResponse)+ if kiroToolFailed(toolResponse) {+ emitHookEvent(logger, "tool.failed", "tool", "high", "Tool execution failed", input, fields)+ return+ }+ }action := actionForTool(hookEvent, toolName, toolInput, toolResponse)category := "tool"if strings.HasPrefix(action, "file.") {@@ -500,6 +518,19 @@ func isFileEditTool(platform, toolName string) bool {if platform == "qwen" {return isQwenFileEditTool(toolName)}+ // Kiro's write tools are named things the Claude Code fallback below does not recognize --+ // `fs_write`, `str_replace`, `fs_append` -- and the one it would recognize by substring,+ // `delete_file`, is not an edit that can produce a diff. The taxonomy answers both, from the+ // same table the action classifier reads, so the two cannot disagree about what a write is.+ //+ // nil arguments, deliberately: this predicate takes only a name, and the one Kiro case that+ // needs more -- a multiplexed `write` whose `command` argument says "delete" -- never reaches+ // here, because kiroToolAction answers first for every tool in the table. Threading the+ // arguments through this shared signature for a branch that cannot be taken would change six+ // runtimes' call sites to document one that does not happen.+ if platform == kiroPlatform {+ return isKiroFileEditTool(toolName, nil)+ }// 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 AREdiff --git a/cli/beacon-hooks/cmd/pre_tool.go b/cli/beacon-hooks/cmd/pre_tool.goindex 08e9f596..647aa3ab 100644--- a/cli/beacon-hooks/cmd/pre_tool.go+++ b/cli/beacon-hooks/cmd/pre_tool.go@@ -50,7 +50,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 {+ } else if platformFlag == "claude" || platformFlag == "qwen" || isDevinLikePlatform(platformFlag) || platformFlag == "grok" || platformFlag == "hermes" || platformFlag == "vscode" || platformFlag == "muse" || platformFlag == openHandsPlatform || platformFlag == kiroPlatform {// 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@@ -64,6 +64,14 @@ func runPreTool(cmd *cobra.Command, args []string) {// not surfaced to hooks. Synthesizing approval.allowed from it would put an operator// decision in the log that no operator made, which is the call Cline, Pi and fx already// settled the same way.+ //+ // Kiro is on that same side, and it is the sharpest case for it: Kiro genuinely does ask+ // the operator, through permissions.yaml rules and an interactive trust picker, and it+ // exposes none of that to a hook. PreToolUse fires whether the call was pre-approved by a+ // rule, waved through by autopilot, or about to stop and wait for a person -- so an+ // 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.emitPreToolObserved(logger, input, sessionID)} else {emitPreToolDecision(logger, input, sessionID, "approval.allowed", "allow", "Pre-tool observed", asymptoteobserve.FidelityInferred)@@ -146,7 +154,13 @@ func preToolResponse() map[string]interface{} {// in the conversation, so it puts a decision Beacon did not make in front of the user -- and if// OpenHands ever reads that key, an observing hook would begin approving tool calls on the// user's behalf without a line of Beacon changing. An empty object asserts nothing either way.- if platformFlag == "claude" || platformFlag == "qwen" || isDevinLikePlatform(platformFlag) || platformFlag == "hermes" || platformFlag == "vscode" || platformFlag == "muse" || platformFlag == openHandsPlatform {+ // Kiro reaches this branch and never uses what it returns: hookStdoutIsConsumedAsAgentContext+ // suppresses the write entirely, because on Kiro stdout is model context rather than a+ // response object. The empty object is still the right value to hand back -- it is what the+ // 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".+ if platformFlag == "claude" || platformFlag == "qwen" || isDevinLikePlatform(platformFlag) || platformFlag == "hermes" || platformFlag == "vscode" || platformFlag == "muse" || platformFlag == openHandsPlatform || platformFlag == kiroPlatform {return emptyResponse}return allowResponsediff --git a/cli/beacon-hooks/cmd/pre_tool_test.go b/cli/beacon-hooks/cmd/pre_tool_test.goindex cf43728e..40fe2ad9 100644--- a/cli/beacon-hooks/cmd/pre_tool_test.go+++ b/cli/beacon-hooks/cmd/pre_tool_test.go@@ -1065,6 +1065,14 @@ func runHookWithInput(t *testing.T, run func(cmd *cobra.Command, args []string),if captured.err != nil {t.Fatalf("read hook output: %v", captured.err)}+ // No output at all is a valid result, not a decode failure. A runtime whose hook contract is+ // exit codes rather than response objects gets nothing on stdout -- see+ // hookStdoutIsConsumedAsAgentContext -- and a helper that fataled on it could not test those+ // runtimes at all. Distinguished from a truncated write, which still reaches the decoder below+ // and still fails there.+ if len(bytes.TrimSpace(captured.data)) == 0 {+ return nil+ }var out map[string]interface{}// Decoder rather than Unmarshal, so trailing output after the JSON value is tolerated exactly// as it was before.diff --git a/cli/beacon-hooks/cmd/root.go b/cli/beacon-hooks/cmd/root.goindex f3e7be58..8f6fffdc 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, 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, opencode, OpenHands, Qwen Code, Muse Code, and Cline integration.+ 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.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, 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, 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/cmd/stop.go b/cli/beacon-hooks/cmd/stop.goindex 5972fe70..b3b06f77 100644--- a/cli/beacon-hooks/cmd/stop.go+++ b/cli/beacon-hooks/cmd/stop.go@@ -40,6 +40,13 @@ func runStop(cmd *cobra.Command, args []string) {logger := newHookLogger("stop", platformFlag, sessionID)logger.Debug("Stop hook called", "session_id", sessionID, "has_transcript", transcriptPath != "", "platform", platformFlag)+ // Kiro puts the agent's final reply on this payload and nowhere else. Recorded before the+ // completion event below and before the sessionID guard, because the reply happened before the+ // turn ended and because a payload with no session id still carries real model output --+ // dropping it there would lose the message to protect a field it does not need.+ if platformFlag == kiroPlatform {+ emitKiroAssistantResponse(logger, input, sessionID)+ }if sessionID == "" {if isDevinLikePlatform(platformFlag) {logger.Info("stop completed")diff --git a/cli/beacon-hooks/internal/config/config.go b/cli/beacon-hooks/internal/config/config.goindex 670d2e55..185309d5 100644--- a/cli/beacon-hooks/internal/config/config.go+++ b/cli/beacon-hooks/internal/config/config.go@@ -24,6 +24,7 @@ var (QwenDir = filepath.Join(BeaconDir, "qwen")MuseDir = filepath.Join(BeaconDir, "muse")OpenHandsDir = filepath.Join(BeaconDir, "openhands")+ KiroDir = filepath.Join(BeaconDir, "kiro")ClineDir = filepath.Join(BeaconDir, "cline"))@@ -109,6 +110,8 @@ func GetStateDir(platform string) string {return MuseDircase "openhands":return OpenHandsDir+ case "kiro":+ return KiroDircase "cline":return ClineDirdefault:diff --git a/cli/beacon-hooks/internal/diff/diff.go b/cli/beacon-hooks/internal/diff/diff.goindex 7bcc2de7..d5529f17 100644--- a/cli/beacon-hooks/internal/diff/diff.go+++ b/cli/beacon-hooks/internal/diff/diff.go@@ -369,3 +369,102 @@ func FromContentChange(filePath, oldContent, newContent string) string {}return fromWriteTool(filePath, newContent, oldContent)}++// FromKiroWrite builds the diff for one Kiro write call.+//+// Kiro is the one supported runtime that publishes its tool names and not its tool arguments, so+// this reads every plausible spelling of each field rather than one. That sounds like guessing and+// is the opposite: an unrecognized shape returns "", which records the file event with its path+// and no diff, while a shape that resolves produces a diff from values that can only have been the+// content. There is no reading here that could produce a *wrong* diff -- only one or none.+//+// The two spellings come from two real places. `file_text`, `old_str` and `new_str` are Amazon Q+// Developer CLI's names for the same tool, which Kiro CLI descends from and still documents a+// migration path out of; `content`, `old_string` and `new_string` are the ecosystem convention the+// shared resolver already knows. Reading both costs one lookup.+//+// operation is passed in rather than derived, because deciding whether a write is a create or a+// replacement is the taxonomy's job and it already answered. An empty operation means the tool+// name is the whole answer.+func FromKiroWrite(operation, toolName string, toolInput, toolResponse map[string]interface{}) string {+ filePath := NormalizePath(kiroWritePath(toolInput, toolResponse))+ if filePath == "" {+ return ""+ }+ if operation == "" {+ operation = kiroOperationForToolName(toolName)+ }+ switch operation {+ case "create":+ content := GetStringFromMaps("file_text", toolInput, toolResponse)+ if content == "" {+ content = GetStringFromMaps("content", toolInput, toolResponse)+ }+ if content == "" {+ content = GetStringFromMaps("text", toolInput, toolResponse)+ }+ if content == "" {+ return ""+ }+ // A create that reports the previous contents is an overwrite, and rendering it as a new+ // file would hide what was replaced. Kiro is not documented to send this; it is read+ // because fromWriteTool already distinguishes the two cases and an absent value degrades+ // to the new-file rendering that would have been produced anyway.+ original := GetStringFromMaps("original_file", toolInput, toolResponse)+ if original == "" {+ original = GetStringFromMaps("originalFile", toolInput, toolResponse)+ }+ if original == "" {+ original = GetStringFromMaps("old_content", toolInput, toolResponse)+ }+ return fromWriteTool(filePath, content, original)+ case "str_replace":+ oldString := resolveEditString("old_string", "oldString", "old_str", toolInput, toolResponse)+ newString := resolveEditString("new_string", "newString", "new_str", toolInput, toolResponse)+ return fromEditTool(filePath, oldString, newString)+ case "insert", "append":+ // An insert or an append adds lines and removes none, so the diff has an empty old side.+ // Rendering it through the same edit builder keeps the shape identical to a replacement's,+ // which is what a reader and a rule matching on file.diff both expect.+ added := resolveEditString("new_string", "newString", "new_str", toolInput, toolResponse)+ if added == "" {+ added = GetStringFromMaps("content", toolInput, toolResponse)+ }+ if added == "" {+ added = GetStringFromMaps("file_text", toolInput, toolResponse)+ }+ return fromEditTool(filePath, "", added)+ default:+ // Includes "delete" and "undo_edit". Neither carries content on both sides, so there is+ // nothing to render; the caller records the file event without a diff.+ return ""+ }+}++// kiroOperationForToolName maps Kiro's split write tools onto the operation each one performs.+//+// Kiro's unified tool catalog lists the operations as separate tools while its CLI reference lists+// one multiplexed tool, so a payload may name the operation in the tool or in an argument. This+// covers the first case; the caller covers the second.+func kiroOperationForToolName(toolName string) string {+ switch strings.ToLower(strings.TrimSpace(toolName)) {+ case "write", "fs_write", "fswrite":+ return "create"+ case "str_replace":+ return "str_replace"+ case "fs_append":+ return "append"+ default:+ return ""+ }+}++// kiroWritePath resolves the file a Kiro write call named, reading the arguments before the result.+func kiroWritePath(toolInput, toolResponse map[string]interface{}) string {+ for _, key := range []string{"path", "file_path", "filePath", "Path", "absolute_path"} {+ if value := GetStringFromMaps(key, toolInput, toolResponse); value != "" {+ return value+ }+ }+ return ""+}diff --git a/cli/beacon-hooks/internal/diff/diff_test.go b/cli/beacon-hooks/internal/diff/diff_test.goindex 9c30207e..1ebc5224 100644--- a/cli/beacon-hooks/internal/diff/diff_test.go+++ b/cli/beacon-hooks/internal/diff/diff_test.go@@ -253,3 +253,107 @@ func TestFromContentChangeReturnsNothingWhenTheContentIsUnchanged(t *testing.T)})}}++// FromKiroWrite is the one diff builder written against a tool whose arguments the vendor does not+// publish, so its safety property is worth stating as a test rather than as a comment: an+// unrecognized shape must produce no diff, never a wrong one. Every case below is a shape Kiro+// could plausibly send, and each either resolves exactly or returns "".+func TestFromKiroWriteReadsBothArgumentSpellings(t *testing.T) {+ for _, tc := range []struct {+ name string+ operation string+ toolName string+ input map[string]interface{}+ wantLines []string+ }{+ {+ name: "create with the Amazon Q spelling",+ operation: "create",+ toolName: "fs_write",+ input: map[string]interface{}{"path": "/repo/a.go", "file_text": "package main\n"},+ wantLines: []string{"+++ b/a.go", "+package main"},+ },+ {+ name: "create with the ecosystem spelling",+ operation: "",+ toolName: "write",+ input: map[string]interface{}{"path": "/repo/a.go", "content": "package main\n"},+ wantLines: []string{"+++ b/a.go", "+package main"},+ },+ {+ name: "replacement with the Amazon Q spelling",+ operation: "str_replace",+ toolName: "fs_write",+ input: map[string]interface{}{"path": "/repo/a.go", "old_str": "one", "new_str": "two"},+ wantLines: []string{"-one", "+two"},+ },+ {+ name: "replacement with the ecosystem spelling",+ operation: "",+ toolName: "str_replace",+ input: map[string]interface{}{"path": "/repo/a.go", "old_string": "one", "new_string": "two"},+ wantLines: []string{"-one", "+two"},+ },+ {+ name: "append adds and removes nothing",+ operation: "",+ toolName: "fs_append",+ input: map[string]interface{}{"path": "/repo/a.go", "new_str": "// tail\n"},+ wantLines: []string{"+// tail"},+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ got := FromKiroWrite(tc.operation, tc.toolName, tc.input, nil)+ for _, want := range tc.wantLines {+ if !hasExactLine(got, want) {+ t.Fatalf("diff missing %q:\n%s", want, got)+ }+ }+ })+ }+}++// The safety property itself. A shape this build cannot read yields nothing, which records the+// file event without a diff -- rather than a diff built from a value that was not the content.+func TestFromKiroWriteReturnsNothingRatherThanGuessing(t *testing.T) {+ for _, tc := range []struct {+ name string+ operation string+ toolName string+ input map[string]interface{}+ }{+ {"no path", "create", "fs_write", map[string]interface{}{"file_text": "x"}},+ {"no content", "create", "fs_write", map[string]interface{}{"path": "/repo/a.go"}},+ {"unreadable arguments", "", "fs_write", map[string]interface{}{"path": "/repo/a.go", "payload": "?"}},+ {"a delete has no content on either side", "delete", "delete_file", map[string]interface{}{"path": "/repo/a.go"}},+ {"an unknown tool", "", "some_future_tool", map[string]interface{}{"path": "/repo/a.go", "content": "x"}},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if got := FromKiroWrite(tc.operation, tc.toolName, tc.input, nil); got != "" {+ t.Fatalf("FromKiroWrite = %q, want empty", got)+ }+ })+ }+}++// A create that reports the file's previous contents is an overwrite, and rendering it as a new+// file would hide what was replaced.+func TestFromKiroWriteRendersAnOverwriteAsAReplacement(t *testing.T) {+ got := FromKiroWrite("create", "fs_write", map[string]interface{}{+ "path": "/repo/a.go",+ "file_text": "new\n",+ "original_file": "old\n",+ }, nil)+ if !hasExactLine(got, "-old") || !hasExactLine(got, "+new") {+ t.Fatalf("overwrite was not rendered as a replacement:\n%s", got)+ }+}++func hasExactLine(diff, want string) bool {+ for _, line := range strings.Split(diff, "\n") {+ if line == want {+ return true+ }+ }+ return false+}