Skip to content

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

Qwen Code support 3/6: map Qwen's tool taxonomy onto endpoint events

Justin96f175baf65e
diff --git a/cli/beacon-hooks/cmd/endpoint_events.go b/cli/beacon-hooks/cmd/endpoint_events.go
index e940bfce..e4ba921c 100644
--- a/cli/beacon-hooks/cmd/endpoint_events.go
+++ b/cli/beacon-hooks/cmd/endpoint_events.go
@@ -30,6 +30,16 @@ func emitHookEvent(logger *logging.Logger, action, category, severity, message s
if platformFlag == "hermes" {
fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{"hermes": input})
}
+ // Qwen carries real signal with no endpoint-schema field of its own: `permission_mode` on every
+ // tool event, `source` on SessionStart, `stop_hook_active` and the `context_usage` /
+ // `context_limit` / `input_tokens` trio on Stop, `tool_use_id` linking a pre-tool event to its
+ // post-tool result. Keeping the payload under `raw.qwen` preserves it without inventing schema
+ // fields for one runtime. It is the whole event's own path through SanitizeMap, so raw is
+ // secret-redacted and string-limited like every other field, and it is the first thing dropped
+ // when an event exceeds the 64 KiB ceiling.
+ if platformFlag == "qwen" {
+ fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{"qwen": input})
+ }
if platformFlag == "vscode" {
fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{"vscode": input})
}
@@ -241,7 +251,11 @@ func toolFieldsWithResponse(toolName string, toolInput, toolResponse map[string]
fields["command"] = map[string]interface{}{"command": command}
fields["tool"] = mergeNested(fields["tool"], map[string]interface{}{"name": toolName, "command": command})
}
- if path := firstToolString(toolInput, "file_path", "filePath", "path", "Path", "AbsolutePath", "DirectoryPath", "SearchPath", "searchPath"); path != "" {
+ // `absolute_path` and `notebook_path` are the snake_case siblings of `AbsolutePath` already in
+ // this list: the first is Gemini CLI's (and so early Qwen Code's) `read_file` parameter, the
+ // second is what `notebook_edit` names its target on both Qwen and Claude. Both are unambiguous
+ // file paths, so reading them costs nothing and their absence costs a `file` field.
+ if path := firstToolString(toolInput, "file_path", "filePath", "path", "Path", "AbsolutePath", "absolute_path", "notebook_path", "DirectoryPath", "SearchPath", "searchPath"); path != "" {
fields["file"] = map[string]interface{}{
"path": path,
"operation": fileOperation(toolName),
@@ -534,6 +548,11 @@ func normalizeToolString(value interface{}) string {
}
func fileOperation(toolName string) string {
+ if platformFlag == "qwen" {
+ if operation := qwenFileOperation(toolName); 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"):
@@ -574,6 +593,17 @@ func actionForTool(hookEvent, toolName string) string {
return "file.modified"
}
}
+ if platformFlag == "qwen" {
+ // PostToolUseFailure is classified before the tool id, so a failed edit is recorded as a
+ // failure rather than as a successful file.modified. Same ordering as grok, for the same
+ // reason: the tool name says what was attempted, not whether it worked.
+ if hookEvent == "PostToolUseFailure" {
+ return "tool.failed"
+ }
+ if action := qwenToolAction(toolName); action != "" {
+ return action
+ }
+ }
if platformFlag == "antigravity" {
switch lower {
case "run_command":
diff --git a/cli/beacon-hooks/cmd/post_tool.go b/cli/beacon-hooks/cmd/post_tool.go
index b0ccd7c8..200e25e6 100644
--- a/cli/beacon-hooks/cmd/post_tool.go
+++ b/cli/beacon-hooks/cmd/post_tool.go
@@ -150,6 +150,23 @@ func parseClaudeCopilotInput(input map[string]interface{}, logger *logging.Logge
return nil
}
+ // A failure is not an edit.
+ //
+ // Qwen's PostToolUseFailure carries the same `tool_name` and `tool_input` as a success -- the
+ // error is the only thing that distinguishes them -- so without this guard a `write_file` that
+ // hit EACCES would be sent down the diff path, and Beacon would build a diff from the content
+ // of a write that never landed and record it as a completed `file.modified`. That is worse than
+ // missing the event: the log would assert a file changed when it did not.
+ //
+ // Returning nil hands the payload back to emitPostToolObserved, which classifies it as
+ // `tool.failed` at high severity. Antigravity guards the same way just above, for the same
+ // reason. Scoped to the platform rather than applied to every runtime because the branch above
+ // establishes that each runtime's failure signal is its own; widening it would change Claude
+ // Code's recorded behavior with no fixture to say what that behavior should become.
+ if platformFlag == "qwen" && qwenToolFailed(input) {
+ return nil
+ }
+
filePath := diff.GetStringFromMaps("file_path", toolInput, toolResponse)
if filePath == "" {
filePath = diff.GetStringFromMaps("filePath", toolInput, toolResponse)
@@ -163,6 +180,9 @@ func parseClaudeCopilotInput(input map[string]interface{}, logger *logging.Logge
if filePath == "" {
filePath = diff.GetStringFromMaps("AbsolutePath", toolInput, toolResponse)
}
+ if filePath == "" {
+ filePath = diff.GetStringFromMaps("absolute_path", toolInput, toolResponse)
+ }
filePath = diff.NormalizePath(filePath)
if (sessionID == "" && !isDevinLikePlatform(platformFlag)) || toolName == "" || filePath == "" {
@@ -405,6 +425,9 @@ func isFileEditTool(platform, toolName string) bool {
strings.Contains(lower, "create") ||
strings.Contains(lower, "patch")
}
+ if platform == "qwen" {
+ return isQwenFileEditTool(toolName)
+ }
return toolName == "Write" || toolName == "Edit" || toolName == "MultiEdit"
}
diff --git a/cli/beacon-hooks/cmd/qwen_event.go b/cli/beacon-hooks/cmd/qwen_event.go
new file mode 100644
index 00000000..b03dc175
--- /dev/null
+++ b/cli/beacon-hooks/cmd/qwen_event.go
@@ -0,0 +1,120 @@
+package cmd
+
+import "strings"
+
+// Qwen Code's tool taxonomy.
+//
+// Qwen sends the Claude Code payload *shape* but not Claude's tool *names*: its built-ins are
+// snake_case ids inherited from the Gemini CLI it forked -- `run_shell_command`, `write_file`,
+// `edit`, `read_file`, `list_directory`, `glob`, `grep_search`. The generic classifier in
+// actionForTool works by substring, and on those names it is wrong in both directions that matter:
+//
+// - `write_file`, `edit`, `replace` and `notebook_edit` fall through to `tool.invoked`, because
+// the default isFileEditTool only recognizes Claude's `Write`/`Edit`/`MultiEdit`. A file the
+// agent rewrote would be recorded as an unclassified tool call, which is invisible to every
+// rule and dashboard that keys on `file.modified`.
+// - `list_directory`, `glob` and `grep_search` also fall through, so filesystem reads are not
+// recorded as reads.
+//
+// Both are misclassification rather than absence, which is the worse failure: the event is there,
+// the action is wrong, and nothing looks broken.
+//
+// The set is closed and matched by equality. A substring rule would be shorter and would also
+// classify any MCP tool whose name happens to contain "edit" or "glob" as a Qwen built-in, and MCP
+// tools are named by whoever wrote the server.
+
+// qwenReadTools are the built-ins that read from the filesystem without changing it.
+//
+// `search_file_content` and `read_many_files` are the Gemini CLI spellings of `grep_search` and a
+// multi-file read. They are kept because Qwen Code is a fork that renamed some tools and because a
+// hook installed against one version can receive payloads from another after an upgrade; an id that
+// no longer exists costs one dead map entry, while a missing one costs a misclassified event.
+var qwenReadTools = map[string]bool{
+ "read_file": true,
+ "read_many_files": true,
+ "list_directory": true,
+ "glob": true,
+ "grep_search": true,
+ "search_file_content": true,
+}
+
+// qwenEditTools are the built-ins that create or modify a file.
+//
+// `replace` is Gemini CLI's id for what Qwen Code documents as `edit`; see qwenReadTools for why
+// the older spelling is carried.
+var qwenEditTools = map[string]bool{
+ "write_file": true,
+ "edit": true,
+ "replace": true,
+ "notebook_edit": true,
+}
+
+// qwenCommandTools are the built-ins that execute a shell command.
+var qwenCommandTools = map[string]bool{
+ "run_shell_command": true,
+}
+
+// qwenToolAction maps a Qwen built-in onto an endpoint event action, or returns "" to let the
+// generic classifier decide.
+//
+// Returning "" rather than a default is what keeps MCP tools and Qwen's non-filesystem built-ins
+// (`web_fetch`, `web_search`, `todo_write`, `save_memory`, `task`, `skill`) on the shared path,
+// where the `mcp` rule and the `tool.invoked` fallback already give the right answer.
+func qwenToolAction(toolName string) string {
+ switch lower := strings.ToLower(strings.TrimSpace(toolName)); {
+ case qwenCommandTools[lower]:
+ return "command.executed"
+ case qwenReadTools[lower]:
+ return "file.read"
+ case qwenEditTools[lower]:
+ return "file.modified"
+ default:
+ return ""
+ }
+}
+
+// isQwenFileEditTool reports whether a Qwen built-in mutates a file.
+//
+// This gates the diff-capture path as well as the classification, so it is the closed edit set and
+// nothing else. A false positive here sends a non-edit tool through diff construction; a false
+// negative drops the diff for a real edit.
+func isQwenFileEditTool(toolName string) bool {
+ return qwenEditTools[strings.ToLower(strings.TrimSpace(toolName))]
+}
+
+// qwenFileOperation is the `file.operation` value for a Qwen built-in, or "" to fall through.
+//
+// Separate from qwenToolAction because the two answer different questions and disagree on one tool:
+// the generic fileOperation reads `replace` as neither a read nor a write and leaves the field
+// empty, so an edit made through the Gemini-era id would carry a path with no operation.
+func qwenFileOperation(toolName string) string {
+ lower := strings.ToLower(strings.TrimSpace(toolName))
+ switch {
+ case qwenReadTools[lower]:
+ return "read"
+ case lower == "write_file":
+ return "create"
+ case qwenEditTools[lower]:
+ return "modify"
+ default:
+ return ""
+ }
+}
+
+// qwenToolFailed reports whether a post-tool payload describes a tool that failed.
+//
+// Two independent signals, because either can arrive alone. `hook_event_name` is
+// "PostToolUseFailure" when Qwen routes the failure to that event, and `error` carries the message;
+// a payload delivered through the PostToolUse hook with an error set is still a failure. Reading
+// only the event name would miss the second, and reading only `error` would miss an interrupt that
+// Qwen reports with `is_interrupt` and an empty message.
+func qwenToolFailed(input map[string]interface{}) bool {
+ if getFirstStr(input, "hook_event_name") == "PostToolUseFailure" {
+ return true
+ }
+ if getFirstStr(input, "error") != "" {
+ return true
+ }
+ interrupted, _ := input["is_interrupt"].(bool)
+ return interrupted
+}
diff --git a/cli/beacon-hooks/cmd/qwen_event_test.go b/cli/beacon-hooks/cmd/qwen_event_test.go
new file mode 100644
index 00000000..331e3917
--- /dev/null
+++ b/cli/beacon-hooks/cmd/qwen_event_test.go
@@ -0,0 +1,423 @@
+package cmd
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func readQwenFixture(t *testing.T, name string) map[string]interface{} {
+ t.Helper()
+ data, err := os.ReadFile(filepath.Join("..", "testdata", "qwen", name))
+ if err != nil {
+ t.Fatalf("read qwen fixture %s: %v", name, err)
+ }
+ var payload map[string]interface{}
+ if err := json.Unmarshal(data, &payload); err != nil {
+ t.Fatalf("decode qwen fixture %s: %v", name, err)
+ }
+ return payload
+}
+
+// setupQwenHook wires a hook run for --platform qwen against a fresh runtime log.
+func setupQwenHook(t *testing.T) string {
+ t.Helper()
+ setupHookConfigDirs(t)
+ platformFlag = "qwen"
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ t.Setenv("BEACON_ENDPOINT_MODE", "1")
+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)
+ // Local git enrichment would shell out to whatever repository the test binary happens to run
+ // in, which makes the branch field depend on the checkout rather than the payload.
+ t.Setenv("BEACON_DISABLE_GIT_METADATA", "1")
+ return logPath
+}
+
+func qwenAction(t *testing.T, event map[string]interface{}) string {
+ t.Helper()
+ meta, ok := event["event"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("event has no event object: %#v", event)
+ }
+ action, _ := meta["action"].(string)
+ return action
+}
+
+// The whole point of the Qwen taxonomy: its built-ins are Gemini-era snake_case ids, and the
+// generic substring classifier gets four of them wrong. Each of the wrong-before cases is listed
+// here with the action it must produce, so a regression is a named failure rather than a silently
+// reclassified event.
+func TestQwenBuiltInToolsMapOntoTheRightAction(t *testing.T) {
+ origPlatform := platformFlag
+ t.Cleanup(func() { platformFlag = origPlatform })
+ platformFlag = "qwen"
+
+ for toolName, want := range map[string]string{
+ // Shell.
+ "run_shell_command": "command.executed",
+ // Filesystem reads. list_directory, glob and grep_search are the ones the generic
+ // classifier drops to tool.invoked.
+ "read_file": "file.read",
+ "read_many_files": "file.read",
+ "list_directory": "file.read",
+ "glob": "file.read",
+ "grep_search": "file.read",
+ "search_file_content": "file.read",
+ // Filesystem writes. All four are tool.invoked under the default isFileEditTool, which
+ // only knows Claude's Write/Edit/MultiEdit.
+ "write_file": "file.modified",
+ "edit": "file.modified",
+ "replace": "file.modified",
+ "notebook_edit": "file.modified",
+ // Not filesystem tools: these stay on the shared path deliberately.
+ "web_fetch": "tool.invoked",
+ "web_search": "tool.invoked",
+ "todo_write": "tool.invoked",
+ "save_memory": "tool.invoked",
+ "task": "tool.invoked",
+ "skill": "tool.invoked",
+ } {
+ t.Run(toolName, func(t *testing.T) {
+ if got := actionForTool("PostToolUse", toolName); got != want {
+ t.Errorf("actionForTool(PostToolUse, %q) = %q, want %q", toolName, got, want)
+ }
+ })
+ }
+}
+
+// An MCP tool is named by whoever wrote the server, so names containing "edit", "glob" or
+// "read_file" as substrings are ordinary. The Qwen set is matched by equality precisely so those
+// keep routing to mcp.tool_invoked instead of being claimed as Qwen built-ins.
+func TestQwenTaxonomyDoesNotClaimMCPTools(t *testing.T) {
+ origPlatform := platformFlag
+ t.Cleanup(func() { platformFlag = origPlatform })
+ platformFlag = "qwen"
+
+ for _, toolName := range []string{
+ "mcp__notion__edit", "mcp__fs__glob", "mcp__github__read_file", "mcp__shell__run_shell_command",
+ } {
+ if got := actionForTool("PostToolUse", toolName); got != "mcp.tool_invoked" {
+ t.Errorf("actionForTool(%q) = %q, want mcp.tool_invoked", toolName, got)
+ }
+ if isFileEditTool("qwen", toolName) {
+ t.Errorf("isFileEditTool(qwen, %q) = true; an MCP tool must not be sent through Qwen's diff path", toolName)
+ }
+ }
+}
+
+// The Qwen taxonomy must not leak into other runtimes. Its ids collide with real tools elsewhere --
+// grok has its own write_file, and "edit" is a Devin tool -- so a mapping keyed on the platform is
+// the only safe form.
+func TestQwenTaxonomyIsScopedToTheQwenPlatform(t *testing.T) {
+ origPlatform := platformFlag
+ t.Cleanup(func() { platformFlag = origPlatform })
+
+ platformFlag = "claude"
+ if got := actionForTool("PostToolUse", "list_directory"); got != "tool.invoked" {
+ t.Errorf("actionForTool(claude, list_directory) = %q, want the claude classification unchanged", got)
+ }
+ if isFileEditTool("claude", "replace") {
+ t.Error("isFileEditTool(claude, replace) = true; Qwen's edit set must not apply to Claude Code")
+ }
+ if !isFileEditTool("claude", "Write") {
+ t.Error("isFileEditTool(claude, Write) = false; Claude's own edit set regressed")
+ }
+}
+
+// A tool that failed is recorded as a failure, not as the thing it was trying to do. Without the
+// PostToolUseFailure check ordering ahead of the tool id, a write_file that hit EACCES would be
+// written to the log as a successful file.modified.
+func TestQwenFailedToolIsNotRecordedAsASuccessfulEdit(t *testing.T) {
+ logPath := setupQwenHook(t)
+
+ runHookWithInput(t, runPostTool, readQwenFixture(t, "post_tool_failure.json"))
+
+ event := lastEndpointEvent(t, logPath)
+ if got := qwenAction(t, event); got != "tool.failed" {
+ t.Fatalf("event.action = %q, want tool.failed", got)
+ }
+ if got := event["severity"]; got != "high" {
+ t.Fatalf("severity = %q, want high", got)
+ }
+ if got := event["harness"].(map[string]interface{})["name"]; got != "qwen_code" {
+ t.Fatalf("harness.name = %q, want qwen_code", got)
+ }
+}
+
+// A shell command has to reach the `command` field, not just `tool.name`: every command rule,
+// dashboard column and threat-rule match reads it from there.
+func TestQwenShellCommandIsRecordedAsACommand(t *testing.T) {
+ logPath := setupQwenHook(t)
+
+ runHookWithInput(t, runPostTool, readQwenFixture(t, "post_tool_shell.json"))
+
+ event := lastEndpointEvent(t, logPath)
+ if got := qwenAction(t, event); got != "command.executed" {
+ t.Fatalf("event.action = %q, want command.executed", got)
+ }
+ command, ok := event["command"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("event has no command object: %#v", event)
+ }
+ if command["command"] != "npm test" {
+ t.Fatalf("command.command = %q, want npm test", command["command"])
+ }
+ if got := event["tool"].(map[string]interface{})["name"]; got != "run_shell_command" {
+ t.Fatalf("tool.name = %q, want run_shell_command", got)
+ }
+ if got := event["session"].(map[string]interface{})["working_directory"]; got != "/Users/example/projects/beacon-demo" {
+ t.Fatalf("working_directory = %q, want the payload cwd", got)
+ }
+}
+
+// A whole-file write records the path, the operation and the diff. The diff is what makes the event
+// answer "what changed" rather than only "something changed".
+func TestQwenWriteFileRecordsPathOperationAndDiff(t *testing.T) {
+ logPath := setupQwenHook(t)
+
+ runHookWithInput(t, runPostTool, readQwenFixture(t, "post_tool_write_file.json"))
+
+ event := lastEndpointEvent(t, logPath)
+ if got := qwenAction(t, event); got != "file.modified" {
+ t.Fatalf("event.action = %q, want file.modified", got)
+ }
+ file, ok := event["file"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("event has no file object: %#v", event)
+ }
+ if file["path"] != "/Users/example/projects/beacon-demo/src/health.ts" {
+ t.Fatalf("file.path = %q, want the written path", file["path"])
+ }
+ // "modify" rather than "create", and that is the shared contract rather than a Qwen quirk: an
+ // event that carries a diff is built by diffFields, which has no tool name to distinguish a
+ // whole-file write from an in-place edit and reports "modify" for both on every runtime. The
+ // create/modify distinction Qwen's taxonomy does make is carried by the pre-tool event, which
+ // is asserted below.
+ if file["operation"] != "modify" {
+ t.Fatalf("file.operation = %q, want modify", file["operation"])
+ }
+ diff, _ := file["diff"].(string)
+ if !strings.Contains(diff, "export const health") {
+ t.Fatalf("file.diff = %q, want the written content", diff)
+ }
+}
+
+// The create/modify distinction Qwen's taxonomy draws: `write_file` replaces a whole file and
+// `edit` changes part of one. It reaches the log through the pre-tool event, which classifies from
+// the tool name rather than from a constructed diff.
+func TestQwenPreToolDistinguishesAWholeFileWriteFromAnEdit(t *testing.T) {
+ for toolName, want := range map[string]string{"write_file": "create", "edit": "modify", "replace": "modify"} {
+ t.Run(toolName, func(t *testing.T) {
+ logPath := setupQwenHook(t)
+ runHookWithInput(t, runPreTool, map[string]interface{}{
+ "session_id": "qwen-8f21c4a0",
+ "cwd": "/Users/example/projects/beacon-demo",
+ "hook_event_name": "PreToolUse",
+ "tool_name": toolName,
+ "tool_input": map[string]interface{}{
+ "file_path": "/Users/example/projects/beacon-demo/src/health.ts",
+ },
+ })
+ event := lastEndpointEvent(t, logPath)
+ file, ok := event["file"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("event has no file object: %#v", event)
+ }
+ if file["operation"] != want {
+ t.Fatalf("file.operation = %q, want %q", file["operation"], want)
+ }
+ })
+ }
+}
+
+// The `edit` tool's old_string/new_string shape has to reach the diff builder. Without `replace`
+// and `edit` recognized as Qwen edit tools, the event says a file changed and never says how.
+func TestQwenEditRecordsBothSidesOfTheReplacement(t *testing.T) {
+ logPath := setupQwenHook(t)
+
+ runHookWithInput(t, runPostTool, readQwenFixture(t, "post_tool_edit.json"))
+
+ event := lastEndpointEvent(t, logPath)
+ if got := qwenAction(t, event); got != "file.modified" {
+ t.Fatalf("event.action = %q, want file.modified", got)
+ }
+ file := event["file"].(map[string]interface{})
+ if file["path"] != "/Users/example/projects/beacon-demo/src/server.ts" {
+ t.Fatalf("file.path = %q, want the edited path", file["path"])
+ }
+ diff, _ := file["diff"].(string)
+ if !strings.Contains(diff, "const routes = []") || !strings.Contains(diff, "const routes = [health]") {
+ t.Fatalf("file.diff = %q, want both sides of the replacement", diff)
+ }
+}
+
+// Qwen's Gemini-era `replace` id carries the same payload as `edit`. Both must classify and diff
+// identically, because which one arrives depends on the installed Qwen Code version rather than on
+// what the agent did.
+func TestQwenLegacyReplaceIdBehavesLikeEdit(t *testing.T) {
+ logPath := setupQwenHook(t)
+
+ payload := readQwenFixture(t, "post_tool_edit.json")
+ payload["tool_name"] = "replace"
+ runHookWithInput(t, runPostTool, payload)
+
+ event := lastEndpointEvent(t, logPath)
+ if got := qwenAction(t, event); got != "file.modified" {
+ t.Fatalf("event.action = %q, want file.modified", got)
+ }
+ file := event["file"].(map[string]interface{})
+ // The generic fileOperation reads "replace" as neither a read nor a write and leaves this
+ // empty; qwenFileOperation is what fills it.
+ if file["operation"] != "modify" {
+ t.Fatalf("file.operation = %q, want modify", file["operation"])
+ }
+ if diff, _ := file["diff"].(string); !strings.Contains(diff, "const routes = [health]") {
+ t.Fatalf("file.diff = %q, want the replacement recorded", diff)
+ }
+}
+
+// Gemini CLI's read_file names its target `absolute_path`. The list already carried the CamelCase
+// `AbsolutePath`; without the snake_case sibling a Qwen file read produces an event with no path.
+func TestQwenReadFileResolvesTheAbsolutePathParameter(t *testing.T) {
+ logPath := setupQwenHook(t)
+
+ runHookWithInput(t, runPostTool, map[string]interface{}{
+ "session_id": "qwen-8f21c4a0",
+ "cwd": "/Users/example/projects/beacon-demo",
+ "hook_event_name": "PostToolUse",
+ "tool_name": "read_file",
+ "tool_input": map[string]interface{}{
+ "absolute_path": "/Users/example/projects/beacon-demo/src/server.ts",
+ },
+ })
+
+ event := lastEndpointEvent(t, logPath)
+ if got := qwenAction(t, event); got != "file.read" {
+ t.Fatalf("event.action = %q, want file.read", got)
+ }
+ file, ok := event["file"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("event has no file object: %#v", event)
+ }
+ if file["path"] != "/Users/example/projects/beacon-demo/src/server.ts" {
+ t.Fatalf("file.path = %q, want the absolute_path value", file["path"])
+ }
+ if file["operation"] != "read" {
+ t.Fatalf("file.operation = %q, want read", file["operation"])
+ }
+}
+
+// Qwen carries fields the endpoint schema has nowhere to put -- permission_mode, tool_use_id,
+// source, and the Stop context trio. raw.qwen is where they survive, and it goes through the same
+// sanitizer as every other field.
+func TestQwenRawPayloadPreservesFieldsWithNoSchemaHome(t *testing.T) {
+ logPath := setupQwenHook(t)
+
+ runHookWithInput(t, runPreTool, readQwenFixture(t, "pre_tool_shell.json"))
+
+ event := lastEndpointEvent(t, logPath)
+ raw, ok := event["raw"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("event has no raw object: %#v", event)
+ }
+ payload, ok := raw["qwen"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("raw has no qwen payload: %#v", raw)
+ }
+ for _, key := range []string{"permission_mode", "tool_use_id", "tool_call_id", "hook_event_name"} {
+ if payload[key] == nil || payload[key] == "" {
+ t.Errorf("raw.qwen is missing %s: %#v", key, payload)
+ }
+ }
+}
+
+// Stop's context_usage / context_limit / input_tokens are deliberately NOT normalized into
+// gen_ai.usage.
+//
+// Beacon's token rollups sum gen_ai.usage across events. Qwen's Stop hook fires once per assistant
+// turn and its input_tokens is the prompt token count for that turn's request -- which, in a
+// multi-turn session, already contains every prior turn. Summing it would inflate a session's token
+// total by roughly the square of its length. Qwen's own documentation is explicit that the value
+// "may include output tokens depending on provider", so it is not a clean input count either.
+//
+// The three fields are preserved verbatim under raw.qwen, where they are exact and carry no claim
+// of being a normalized token count. This test is the record of that decision: if a future change
+// starts writing gen_ai.usage from a Qwen Stop payload, it fails here first.
+//
+// The event is built through emitHookEvent with the arguments runStop passes it, rather than by
+// running the command. runStop ends the session-bearing path with outputJSONAndExit, and os.Exit in
+// an in-process test aborts the run -- so the command itself is not callable from this harness,
+// while the mapping it performs is exactly what this asserts.
+func TestQwenStopContextFieldsAreNotNormalizedIntoTokenUsage(t *testing.T) {
+ logPath := setupQwenHook(t)
+
+ input := readQwenFixture(t, "stop.json")
+ sessionID, _ := resolveSessionIDWithTranscript(input, platformFlag)
+ if sessionID == "" {
+ t.Fatal("stop fixture has no session id; the mapping under test would not run")
+ }
+ logger := newHookLogger("stop", platformFlag, sessionID)
+ emitHookEvent(logger, "tool.completed", "tool", "info", "Agent response completed", input, sessionFields(sessionID, input))
+
+ event := lastEndpointEvent(t, logPath)
+ if got := qwenAction(t, event); got != "tool.completed" {
+ t.Fatalf("event.action = %q, want tool.completed", got)
+ }
+ if genAI, ok := event["gen_ai"].(map[string]interface{}); ok {
+ if usage, ok := genAI["usage"]; ok {
+ t.Fatalf("gen_ai.usage = %#v; Qwen's per-turn prompt token count must not be summed as usage", usage)
+ }
+ }
+ payload, ok := event["raw"].(map[string]interface{})["qwen"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("event has no raw.qwen payload: %#v", event["raw"])
+ }
+ for _, key := range []string{"context_usage", "context_limit", "input_tokens", "stop_hook_active"} {
+ if payload[key] == nil {
+ t.Errorf("raw.qwen is missing %s, which is the only place it is preserved: %#v", key, payload)
+ }
+ }
+}
+
+// The lifecycle events a session is reconstructed from. Prompt text and the session model are what
+// make a Qwen session legible in the dashboard rather than a list of anonymous tool calls.
+func TestQwenSessionLifecycleIsRecorded(t *testing.T) {
+ logPath := setupQwenHook(t)
+
+ runHookWithInput(t, runSessionStart, readQwenFixture(t, "session_start.json"))
+ start := lastEndpointEvent(t, logPath)
+ if got := qwenAction(t, start); got != "session.started" {
+ t.Fatalf("event.action = %q, want session.started", got)
+ }
+ if got := start["model"]; got != "qwen3-coder-plus" {
+ t.Fatalf("model = %q, want the session model", got)
+ }
+
+ runHookWithInput(t, runPromptSubmit, readQwenFixture(t, "user_prompt_submit.json"))
+ prompt := lastEndpointEvent(t, logPath)
+ if got := qwenAction(t, prompt); got != "prompt.submitted" {
+ t.Fatalf("event.action = %q, want prompt.submitted", got)
+ }
+ if got := prompt["prompt"].(map[string]interface{})["text"]; got != "Add a health endpoint, then run the tests" {
+ t.Fatalf("prompt.text = %q, want the submitted prompt", got)
+ }
+
+ runHookWithInput(t, runSessionEnd, map[string]interface{}{
+ "session_id": "qwen-8f21c4a0",
+ "cwd": "/Users/example/projects/beacon-demo",
+ "hook_event_name": "SessionEnd",
+ "reason": "prompt_input_exit",
+ })
+ for _, event := range endpointEvents(t, logPath) {
+ if qwenAction(t, event) == "session.ended" {
+ return
+ }
+ }
+ // session-end is allowed to be log-only on platforms that do not emit an endpoint event for
+ // it; what must not happen is the run failing or writing a mis-typed event.
+ if got := qwenAction(t, lastEndpointEvent(t, logPath)); got != "prompt.submitted" {
+ t.Fatalf("last event after session-end = %q, want the log left intact", got)
+ }
+}
diff --git a/cli/beacon-hooks/internal/diff/diff.go b/cli/beacon-hooks/internal/diff/diff.go
index 5c7bd8db..8a513bd8 100644
--- a/cli/beacon-hooks/internal/diff/diff.go
+++ b/cli/beacon-hooks/internal/diff/diff.go
@@ -21,6 +21,9 @@ func FromToolResponse(toolName string, toolInput, toolResponse map[string]interf
if filePath == "" {
filePath = GetStringFromMaps("AbsolutePath", toolInput, toolResponse)
}
+ if filePath == "" {
+ filePath = GetStringFromMaps("absolute_path", toolInput, toolResponse)
+ }
filePath = NormalizePath(filePath)
if filePath == "" {
return ""
@@ -33,7 +36,10 @@ func FromToolResponse(toolName string, toolInput, toolResponse map[string]interf
// Fall back to tool-specific construction
switch toolName {
- case "Edit", "edit", "edit_file":
+ // "replace" is Gemini CLI's -- and so early Qwen Code's -- id for the old_string/new_string edit
+ // tool that Qwen Code now documents as "edit". Without it the tool is recognized as an edit by
+ // isFileEditTool but produces no diff, so the event records that a file changed and not how.
+ case "Edit", "edit", "edit_file", "replace":
oldString := resolveEditString("old_string", "oldString", "old_str", toolInput, toolResponse)
newString := resolveEditString("new_string", "newString", "new_str", toolInput, toolResponse)
return fromEditTool(filePath, oldString, newString)
diff --git a/cli/beacon-hooks/internal/diff/diff_test.go b/cli/beacon-hooks/internal/diff/diff_test.go
index 50d660d8..e521091e 100644
--- a/cli/beacon-hooks/internal/diff/diff_test.go
+++ b/cli/beacon-hooks/internal/diff/diff_test.go
@@ -145,3 +145,43 @@ func TestFromToolResponse_ClineWriteToFile(t *testing.T) {
t.Errorf("diff = %q, want the written content as added lines", got)
}
}
+
+// "replace" is Gemini CLI's -- and so early Qwen Code's -- id for the old_string/new_string edit
+// tool. Qwen's mapper recognizes it as a file edit, so the diff builder has to recognize it too:
+// otherwise the event records that a file changed and never records how, which is the difference
+// between an auditable edit and a bare notification.
+func TestFromToolResponseBuildsADiffForTheReplaceTool(t *testing.T) {
+ toolInput := map[string]interface{}{
+ "file_path": "/repo/src/server.ts",
+ "old_string": "const routes = []",
+ "new_string": "const routes = [health]",
+ }
+ got := FromToolResponse("replace", toolInput, nil)
+ if got == "" {
+ t.Fatal("FromToolResponse(replace) = \"\", want a diff")
+ }
+ if !strings.Contains(got, "const routes = []") || !strings.Contains(got, "const routes = [health]") {
+ t.Fatalf("diff = %q, want both sides of the replacement", got)
+ }
+ if want := FromToolResponse("edit", toolInput, nil); got != want {
+ t.Fatalf("replace and edit produced different diffs:\n replace: %q\n edit: %q", got, want)
+ }
+}
+
+// Gemini CLI's read_file names its target `absolute_path`. The resolver already read the CamelCase
+// `AbsolutePath`; without the snake_case sibling the path is empty and FromToolResponse bails out
+// before it looks at the tool at all.
+func TestFromToolResponseResolvesAbsolutePathParameter(t *testing.T) {
+ got := FromToolResponse("write_file", map[string]interface{}{
+ "absolute_path": "/repo/src/health.ts",
+ "content": "export const health = () => ({ ok: true })\n",
+ }, nil)
+ if got == "" {
+ t.Fatal("FromToolResponse = \"\", want a diff resolved from absolute_path")
+ }
+ // The diff header names the file by its base name, so what this asserts is that a path was
+ // resolved at all -- an unresolved path returns "" a few lines above.
+ if !strings.Contains(got, "health.ts") || !strings.Contains(got, "export const health") {
+ t.Fatalf("diff = %q, want the absolute_path target and its content", got)
+ }
+}
diff --git a/cli/beacon-hooks/testdata/qwen/README.md b/cli/beacon-hooks/testdata/qwen/README.md
new file mode 100644
index 00000000..bb9d612c
--- /dev/null
+++ b/cli/beacon-hooks/testdata/qwen/README.md
@@ -0,0 +1,28 @@
+# Qwen Code payload fixtures
+
+These payloads are **constructed from Qwen Code's published hooks documentation, not captured from
+a running Qwen Code install**. The documentation specifies the fields precisely -- the common
+envelope (`session_id`, `transcript_path`, `cwd`, `hook_event_name`, `timestamp`) and the
+event-specific fields for each hook -- so the shapes here are the documented contract rather than a
+guess. What they are not is evidence that a shipped build sends exactly this; replace a fixture with
+a captured payload whenever one becomes available.
+
+Qwen's own documentation calls the hook input "a forward-extensible JSON contract: new optional
+fields can be added to existing events", so the mapper reads the fields it needs and ignores the
+rest. These fixtures carry the optional fields as well as the required ones (`permission_mode`,
+`tool_use_id`, `tool_call_id`, `submitted_prompt`, the `Stop` context trio) because those are the
+part that reaches `raw.qwen` and is easy to drop by accident.
+
+Covered payloads:
+
+- `session_start.json` — `SessionStart` with `source` and the session's model
+- `user_prompt_submit.json` — `UserPromptSubmit` with both `prompt` and `submitted_prompt`
+- `pre_tool_shell.json` — `PreToolUse` for `run_shell_command`
+- `post_tool_shell.json` — `PostToolUse` for `run_shell_command`, with its response
+- `post_tool_write_file.json` — `PostToolUse` for `write_file`, a whole-file write
+- `post_tool_edit.json` — `PostToolUse` for `edit`, an `old_string`/`new_string` replacement
+- `post_tool_failure.json` — `PostToolUseFailure` for `write_file`, carrying `error`
+- `stop.json` — `Stop` with `context_usage`, `context_limit` and `input_tokens`
+
+Keep secrets and real prompt content out of fixtures. Use sanitized payloads that preserve the field
+shape `beacon-hooks --platform qwen` reads.
diff --git a/cli/beacon-hooks/testdata/qwen/post_tool_edit.json b/cli/beacon-hooks/testdata/qwen/post_tool_edit.json
new file mode 100644
index 00000000..a49c755a
--- /dev/null
+++ b/cli/beacon-hooks/testdata/qwen/post_tool_edit.json
@@ -0,0 +1,19 @@
+{
+ "session_id": "qwen-8f21c4a0",
+ "transcript_path": "/Users/example/.qwen/tmp/qwen-8f21c4a0/chat.json",
+ "cwd": "/Users/example/projects/beacon-demo",
+ "hook_event_name": "PostToolUse",
+ "timestamp": "2026-08-21T10:15:24.000Z",
+ "permission_mode": "default",
+ "tool_name": "edit",
+ "tool_use_id": "toolu_01QwenEdit",
+ "tool_input": {
+ "file_path": "/Users/example/projects/beacon-demo/src/server.ts",
+ "old_string": "const routes = []",
+ "new_string": "const routes = [health]",
+ "replace_all": false
+ },
+ "tool_response": {
+ "success": true
+ }
+}
diff --git a/cli/beacon-hooks/testdata/qwen/post_tool_failure.json b/cli/beacon-hooks/testdata/qwen/post_tool_failure.json
new file mode 100644
index 00000000..0667a6f8
--- /dev/null
+++ b/cli/beacon-hooks/testdata/qwen/post_tool_failure.json
@@ -0,0 +1,16 @@
+{
+ "session_id": "qwen-8f21c4a0",
+ "transcript_path": "/Users/example/.qwen/tmp/qwen-8f21c4a0/chat.json",
+ "cwd": "/Users/example/projects/beacon-demo",
+ "hook_event_name": "PostToolUseFailure",
+ "timestamp": "2026-08-21T10:15:40.000Z",
+ "permission_mode": "default",
+ "tool_name": "write_file",
+ "tool_use_id": "toolu_01QwenFail",
+ "tool_input": {
+ "file_path": "/Users/example/projects/beacon-demo/src/locked.ts",
+ "content": "export const nope = true\n"
+ },
+ "error": "EACCES: permission denied, open '/Users/example/projects/beacon-demo/src/locked.ts'",
+ "is_interrupt": false
+}
diff --git a/cli/beacon-hooks/testdata/qwen/post_tool_shell.json b/cli/beacon-hooks/testdata/qwen/post_tool_shell.json
new file mode 100644
index 00000000..f9d41742
--- /dev/null
+++ b/cli/beacon-hooks/testdata/qwen/post_tool_shell.json
@@ -0,0 +1,18 @@
+{
+ "session_id": "qwen-8f21c4a0",
+ "transcript_path": "/Users/example/.qwen/tmp/qwen-8f21c4a0/chat.json",
+ "cwd": "/Users/example/projects/beacon-demo",
+ "hook_event_name": "PostToolUse",
+ "timestamp": "2026-08-21T10:15:31.200Z",
+ "permission_mode": "default",
+ "tool_name": "run_shell_command",
+ "tool_use_id": "toolu_01QwenShell",
+ "tool_input": {
+ "command": "npm test",
+ "description": "Run the unit tests"
+ },
+ "tool_response": {
+ "output": "12 passing",
+ "exit_code": 0
+ }
+}
diff --git a/cli/beacon-hooks/testdata/qwen/post_tool_write_file.json b/cli/beacon-hooks/testdata/qwen/post_tool_write_file.json
new file mode 100644
index 00000000..82e4b0a6
--- /dev/null
+++ b/cli/beacon-hooks/testdata/qwen/post_tool_write_file.json
@@ -0,0 +1,17 @@
+{
+ "session_id": "qwen-8f21c4a0",
+ "transcript_path": "/Users/example/.qwen/tmp/qwen-8f21c4a0/chat.json",
+ "cwd": "/Users/example/projects/beacon-demo",
+ "hook_event_name": "PostToolUse",
+ "timestamp": "2026-08-21T10:15:20.000Z",
+ "permission_mode": "default",
+ "tool_name": "write_file",
+ "tool_use_id": "toolu_01QwenWrite",
+ "tool_input": {
+ "file_path": "/Users/example/projects/beacon-demo/src/health.ts",
+ "content": "export const health = () => ({ ok: true })\n"
+ },
+ "tool_response": {
+ "success": true
+ }
+}
diff --git a/cli/beacon-hooks/testdata/qwen/pre_tool_shell.json b/cli/beacon-hooks/testdata/qwen/pre_tool_shell.json
new file mode 100644
index 00000000..b204d324
--- /dev/null
+++ b/cli/beacon-hooks/testdata/qwen/pre_tool_shell.json
@@ -0,0 +1,16 @@
+{
+ "session_id": "qwen-8f21c4a0",
+ "transcript_path": "/Users/example/.qwen/tmp/qwen-8f21c4a0/chat.json",
+ "cwd": "/Users/example/projects/beacon-demo",
+ "hook_event_name": "PreToolUse",
+ "timestamp": "2026-08-21T10:15:09.500Z",
+ "permission_mode": "default",
+ "tool_name": "run_shell_command",
+ "tool_use_id": "toolu_01QwenShell",
+ "tool_call_id": "call_shell_001",
+ "tool_input": {
+ "command": "npm test",
+ "description": "Run the unit tests",
+ "directory": "."
+ }
+}
diff --git a/cli/beacon-hooks/testdata/qwen/session_start.json b/cli/beacon-hooks/testdata/qwen/session_start.json
new file mode 100644
index 00000000..3b044f73
--- /dev/null
+++ b/cli/beacon-hooks/testdata/qwen/session_start.json
@@ -0,0 +1,10 @@
+{
+ "session_id": "qwen-8f21c4a0",
+ "transcript_path": "/Users/example/.qwen/tmp/qwen-8f21c4a0/chat.json",
+ "cwd": "/Users/example/projects/beacon-demo",
+ "hook_event_name": "SessionStart",
+ "timestamp": "2026-08-21T10:15:00.000Z",
+ "permission_mode": "default",
+ "source": "startup",
+ "model": "qwen3-coder-plus"
+}
diff --git a/cli/beacon-hooks/testdata/qwen/stop.json b/cli/beacon-hooks/testdata/qwen/stop.json
new file mode 100644
index 00000000..64a9aec0
--- /dev/null
+++ b/cli/beacon-hooks/testdata/qwen/stop.json
@@ -0,0 +1,12 @@
+{
+ "session_id": "qwen-8f21c4a0",
+ "transcript_path": "/Users/example/.qwen/tmp/qwen-8f21c4a0/chat.json",
+ "cwd": "/Users/example/projects/beacon-demo",
+ "hook_event_name": "Stop",
+ "timestamp": "2026-08-21T10:15:45.000Z",
+ "stop_hook_active": false,
+ "last_assistant_message": "Added the health endpoint and the tests pass.",
+ "context_usage": 0.42,
+ "context_limit": 262144,
+ "input_tokens": 110100
+}
diff --git a/cli/beacon-hooks/testdata/qwen/user_prompt_submit.json b/cli/beacon-hooks/testdata/qwen/user_prompt_submit.json
new file mode 100644
index 00000000..a378be6c
--- /dev/null
+++ b/cli/beacon-hooks/testdata/qwen/user_prompt_submit.json
@@ -0,0 +1,9 @@
+{
+ "session_id": "qwen-8f21c4a0",
+ "transcript_path": "/Users/example/.qwen/tmp/qwen-8f21c4a0/chat.json",
+ "cwd": "/Users/example/projects/beacon-demo",
+ "hook_event_name": "UserPromptSubmit",
+ "timestamp": "2026-08-21T10:15:04.100Z",
+ "prompt": "Add a health endpoint, then run the tests",
+ "submitted_prompt": "Add a health endpoint, then run the tests"
+}