Skip to content

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

feat(hooks): map Cline hook payloads onto endpoint events

Claude2867649240eb
diff --git a/cli/beacon-hooks/cmd/cline_event.go b/cli/beacon-hooks/cmd/cline_event.go
new file mode 100644
index 00000000..f37274a7
--- /dev/null
+++ b/cli/beacon-hooks/cmd/cline_event.go
@@ -0,0 +1,592 @@
+package cmd
+
+import (
+ "encoding/json"
+ "path/filepath"
+ "strings"
+
+ hookdiff "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/diff"
+ "github.com/spf13/cobra"
+)
+
+// cline-event is the single entry point for every Cline lifecycle payload.
+//
+// Cline delivers its hooks through an in-process plugin whose handlers all fire in the same
+// process, so one command that receives a typed envelope is a better fit than the
+// command-per-hook shape used for runtimes that exec a separate hook per event. This mirrors how
+// opencode is integrated.
+var clineEventCmd = &cobra.Command{
+ Use: "cline-event",
+ Short: "Record Cline hook telemetry",
+ Long: `cline-event receives raw Beacon Cline plugin payloads and writes local endpoint telemetry.`,
+ Run: runClineEvent,
+}
+
+func init() {
+ rootCmd.AddCommand(clineEventCmd)
+}
+
+func runClineEvent(cmd *cobra.Command, args []string) {
+ input, err := readStdinJSON()
+ if err != nil {
+ outputJSON(emptyResponse)
+ return
+ }
+ sessionID := resolveSessionID(input, "cline")
+ logger := newHookLogger("cline-event", "cline", sessionID)
+ for _, event := range clineEndpointEvents(input, sessionID) {
+ if event.action == "" {
+ continue
+ }
+ _ = logger.EndpointEvent(event.action, event.category, event.severity, event.message, event.fields)
+ }
+ outputJSON(emptyResponse)
+}
+
+// The lifecycle points Beacon records, independent of which name Cline used to announce them.
+const (
+ clineStageTaskStart = "task_start"
+ clineStagePrompt = "prompt"
+ clineStageToolBefore = "tool_before"
+ clineStageToolAfter = "tool_after"
+ clineStageTaskEnd = "task_end"
+ clineStageTaskError = "task_error"
+)
+
+// clineStage decides which lifecycle point a payload describes.
+//
+// Cline names the same points more than one way, and Beacon has to accept all of them because two
+// different surfaces produce these payloads. The plugin SDK exposes handlers (beforeRun,
+// beforeTool, afterTool, afterRun) over a documented stage list that spells them differently
+// (run_start, tool_call_before, tool_call_after, run_end), and Cline's file-based hooks name the
+// script after the hook itself (PreToolUse, PostToolUse, TaskStart) and pass the same name back in
+// the payload's `hookName` base field. Recognizing every spelling is what lets one mapper serve
+// both surfaces instead of two mappers disagreeing about the same task.
+//
+// Matching is done on letters and digits only, lowercased, so PreToolUse, pre_tool_use and
+// tool_call_before all reduce to a single comparison instead of a case list per spelling.
+func clineStage(input map[string]interface{}) string {
+ var normalized strings.Builder
+ for _, r := range strings.ToLower(getFirstStr(input, "type", "hookName", "hook_name", "stage", "event")) {
+ if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') {
+ normalized.WriteRune(r)
+ }
+ }
+ switch normalized.String() {
+ case "beforerun", "runstart", "sessionstart", "taskstart", "taskresume":
+ return clineStageTaskStart
+ case "userpromptsubmit", "promptsubmit", "input":
+ return clineStagePrompt
+ case "beforetool", "toolcallbefore", "pretooluse":
+ return clineStageToolBefore
+ case "aftertool", "toolcallafter", "posttooluse":
+ return clineStageToolAfter
+ case "afterrun", "runend", "sessionshutdown", "taskcomplete":
+ return clineStageTaskEnd
+ case "stoperror", "error", "taskcancel":
+ return clineStageTaskError
+ default:
+ return ""
+ }
+}
+
+// clineEndpointEvents maps one Cline payload onto the endpoint events it justifies.
+//
+// An unrecognized stage returns nothing rather than a generic event. Cline streams runtime events
+// well beyond the lifecycle points above, and turning each into an undifferentiated
+// "something happened" record would fill the runtime log with rows no query asks for.
+func clineEndpointEvents(input map[string]interface{}, sessionID string) []normalizedEvent {
+ fields := clineBaseFields(input, sessionID)
+ one := func(action, category, severity, message string, values map[string]interface{}) []normalizedEvent {
+ return []normalizedEvent{{action: action, category: category, severity: severity, message: message, fields: values}}
+ }
+
+ switch clineStage(input) {
+ case clineStageTaskStart:
+ events := one("session.started", "session", "info", "Cline task started", fields)
+ // Cline's run-start context carries the message that started the task, so the prompt is
+ // recorded from the same payload rather than waiting for a prompt hook that only the
+ // file-based surface has.
+ if prompt := clinePromptText(input); prompt != "" {
+ events = append(events, clinePromptEvent(cloneFields(fields), prompt))
+ }
+ return events
+ case clineStagePrompt:
+ prompt := clinePromptText(input)
+ if prompt == "" {
+ return nil
+ }
+ return []normalizedEvent{clinePromptEvent(fields, prompt)}
+ case clineStageToolBefore:
+ mergeMap(fields, clineToolFields(input, false))
+ return one("tool.invoked", "tool", "info", "Cline tool invoked", fields)
+ case clineStageToolAfter:
+ return clineToolAfterEvents(input, fields)
+ case clineStageTaskEnd:
+ if usage := clineUsage(input); len(usage) > 0 {
+ fields["gen_ai"] = mergeNested(fields["gen_ai"], map[string]interface{}{"usage": usage})
+ }
+ return one("session.ended", "session", "info", "Cline task completed", fields)
+ case clineStageTaskError:
+ fields["error"] = map[string]interface{}{"type": clineErrorType(input)}
+ return one("session.error", "session", "high", "Cline task ended with an error", fields)
+ default:
+ return nil
+ }
+}
+
+// supportedClineEventTypes lists every spelling clineStage recognizes.
+//
+// Exists so a test can assert that each one still maps to an event: these strings are the contract
+// between this mapper and the managed plugin, and a silent typo on either side produces no
+// telemetry rather than an error.
+func supportedClineEventTypes() []string {
+ return []string{
+ "PostToolUse",
+ "PreToolUse",
+ "TaskCancel",
+ "TaskComplete",
+ "TaskResume",
+ "TaskStart",
+ "UserPromptSubmit",
+ "afterRun",
+ "afterTool",
+ "beforeRun",
+ "beforeTool",
+ "error",
+ "input",
+ "run_end",
+ "run_start",
+ "session_shutdown",
+ "session_start",
+ "stop_error",
+ "tool_call_after",
+ "tool_call_before",
+ }
+}
+
+func clineBaseFields(input map[string]interface{}, sessionID string) map[string]interface{} {
+ fields := sessionFields(sessionID, input)
+ applyWorkspaceFields(fields, input, "")
+ fields["raw"] = map[string]interface{}{"cline": input}
+ if model := clineModel(input); model != "" {
+ fields["model"] = model
+ }
+ return fields
+}
+
+func clinePromptEvent(fields map[string]interface{}, prompt string) normalizedEvent {
+ fields["prompt"] = map[string]interface{}{"text": prompt}
+ fields["gen_ai"] = map[string]interface{}{
+ "input": map[string]interface{}{
+ "messages": []interface{}{map[string]interface{}{
+ "role": "user",
+ "parts": []interface{}{map[string]interface{}{"type": "text", "content": prompt}},
+ }},
+ },
+ }
+ fields["content"] = retainedContentFields(prompt)
+ return normalizedEvent{
+ action: "prompt.submitted", category: "prompt", severity: "info",
+ message: "Prompt submitted to Cline", fields: fields,
+ }
+}
+
+// clinePromptText finds the user's message in a run-start or prompt payload.
+//
+// Reads a nested "input" key, which on a tool payload would be the tool's arguments instead. That
+// is safe because only the two prompt-bearing stages reach here, and stated because the collision
+// is not obvious to the next reader.
+func clinePromptText(input map[string]interface{}) string {
+ if text := getFirstStr(input, "prompt", "userMessage", "user_message", "message", "text"); text != "" {
+ return text
+ }
+ for _, key := range []string{"input", "message", "prompt", "run", "context"} {
+ nested := firstMap(input, key)
+ if nested == nil {
+ continue
+ }
+ if text := getFirstStr(nested, "text", "content", "message", "prompt"); text != "" {
+ return text
+ }
+ if text := clineTextParts(nested["content"]); text != "" {
+ return text
+ }
+ }
+ return clineTextParts(input["content"])
+}
+
+// clineTextParts joins the text of a structured message body, skipping non-text parts.
+func clineTextParts(value interface{}) string {
+ parts, ok := value.([]interface{})
+ if !ok {
+ return ""
+ }
+ var texts []string
+ for _, part := range parts {
+ partMap, ok := part.(map[string]interface{})
+ if !ok {
+ if text, ok := part.(string); ok && text != "" {
+ texts = append(texts, text)
+ }
+ continue
+ }
+ if partType := getFirstStr(partMap, "type"); partType != "" && partType != "text" {
+ continue
+ }
+ if text := getFirstStr(partMap, "text", "content"); text != "" {
+ texts = append(texts, text)
+ }
+ }
+ return strings.Join(texts, "\n")
+}
+
+// clineModel reports the model behind a payload, qualified by its provider when both are present.
+//
+// Provider-qualified because a bare model id is ambiguous once a runtime can reach the same model
+// through more than one provider, and because opencode already writes provider/model -- one shape
+// for this field across runtimes is worth more than matching each runtime's own spelling.
+func clineModel(input map[string]interface{}) string {
+ model := getFirstStr(input, "model", "modelId", "model_id")
+ provider := getFirstStr(input, "apiProvider", "api_provider", "provider", "providerId", "provider_id")
+ if model == "" {
+ info := firstMap(input, "modelInfo", "model_info", "model", "api", "apiConfiguration")
+ model = getFirstStr(info, "modelId", "model_id", "model", "id", "name")
+ provider = firstNonEmpty(provider, getFirstStr(info, "apiProvider", "api_provider", "provider", "providerId", "provider_id"))
+ }
+ if model == "" {
+ return ""
+ }
+ if provider != "" && !strings.Contains(model, "/") {
+ return provider + "/" + model
+ }
+ return model
+}
+
+func clineToolName(input map[string]interface{}) string {
+ if tool := getFirstStr(input, "toolName", "tool_name", "tool"); tool != "" {
+ return tool
+ }
+ call := firstMap(input, "toolCall", "tool_call")
+ if tool := getFirstStr(call, "name", "toolName", "tool_name", "tool"); tool != "" {
+ return tool
+ }
+ return getFirstStr(input, "name")
+}
+
+func clineToolInput(input map[string]interface{}) map[string]interface{} {
+ if args := firstMap(input, "input", "toolInput", "tool_input", "arguments", "args", "params"); args != nil {
+ return args
+ }
+ call := firstMap(input, "toolCall", "tool_call")
+ return firstMap(call, "input", "arguments", "args", "params")
+}
+
+func clineToolResponse(input map[string]interface{}) map[string]interface{} {
+ if response := firstMap(input, "result", "toolResult", "tool_result", "output", "response"); response != nil {
+ return response
+ }
+ // A tool that returns a bare string still has a result worth recording, so it is wrapped in the
+ // same shape the map case produces rather than being dropped.
+ if text := getFirstStr(input, "result", "output", "response"); text != "" {
+ return map[string]interface{}{"output": text}
+ }
+ return nil
+}
+
+// clineToolError reports the failure text on a completed tool call, or "" when it succeeded.
+func clineToolError(input map[string]interface{}) string {
+ if text := getFirstStr(input, "error", "errorMessage", "error_message"); text != "" {
+ return text
+ }
+ for _, source := range []map[string]interface{}{firstMap(input, "error"), clineToolResponse(input)} {
+ if source == nil {
+ continue
+ }
+ if text := getFirstStr(source, "message", "error", "errorMessage", "error_message"); text != "" {
+ return text
+ }
+ }
+ return ""
+}
+
+func clineErrorType(input map[string]interface{}) string {
+ if errorInfo := firstMap(input, "error"); errorInfo != nil {
+ if name := getFirstStr(errorInfo, "name", "type", "code"); name != "" {
+ return name
+ }
+ }
+ return firstNonEmpty(getFirstStr(input, "errorType", "error_type", "reason"), "task_error")
+}
+
+// clineToolAction classifies a Cline tool call into an endpoint action and category.
+//
+// Cline's built-in tool names are snake_case verbs -- read_file, write_to_file, execute_command,
+// use_mcp_tool -- so the token rules at the bottom classify almost all of them correctly, and they
+// also cover tools a plugin registers, whose names Beacon cannot know in advance. The explicit
+// cases above exist only for the built-ins those rules would get wrong: three read tools whose
+// names contain no reading verb at all.
+func clineToolAction(name string) (string, string) {
+ switch strings.ToLower(strings.TrimSpace(name)) {
+ case "list_files", "search_files", "list_code_definition_names":
+ return "file.read", "file"
+ }
+ switch {
+ case toolNameHasToken(name, "mcp"):
+ return "mcp.tool_invoked", "mcp"
+ case toolNameHasToken(name, "command") || toolNameHasToken(name, "commands") ||
+ toolNameHasToken(name, "bash") || toolNameHasToken(name, "shell") || toolNameHasToken(name, "terminal"):
+ return "command.executed", "command"
+ case toolNameHasToken(name, "read"):
+ return "file.read", "file"
+ case toolNameHasToken(name, "write") || toolNameHasToken(name, "edit") ||
+ toolNameHasToken(name, "replace") || toolNameHasToken(name, "patch") || toolNameHasToken(name, "create"):
+ return "file.modified", "file"
+ default:
+ return "tool.completed", "tool"
+ }
+}
+
+// clineFileOperation reports what a tool did to a file, for the file.operation field.
+func clineFileOperation(name string) string {
+ switch strings.ToLower(strings.TrimSpace(name)) {
+ case "list_files", "search_files", "list_code_definition_names":
+ return "read"
+ }
+ switch {
+ case toolNameHasToken(name, "read") || toolNameHasToken(name, "view") || toolNameHasToken(name, "list"):
+ return "read"
+ case toolNameHasToken(name, "write") || toolNameHasToken(name, "create"):
+ return "create"
+ case toolNameHasToken(name, "edit") || toolNameHasToken(name, "replace") || toolNameHasToken(name, "patch"):
+ return "modify"
+ default:
+ return ""
+ }
+}
+
+func clineToolMessage(action string) string {
+ switch action {
+ case "command.executed":
+ return "Cline shell command executed"
+ case "file.read":
+ return "Cline file read"
+ case "file.modified":
+ return "Cline file modified"
+ case "mcp.tool_invoked":
+ return "Cline MCP tool executed"
+ default:
+ return "Cline tool completed"
+ }
+}
+
+// clineWorkspacePath resolves a Cline tool path against the workspace root.
+//
+// Cline addresses files relative to the workspace -- read_file receives "src/app.ts", not an
+// absolute path -- while every other runtime Beacon supports reports absolute paths. Left relative,
+// a Cline file path is not comparable with the same file seen through Cursor or Claude Code, and
+// threat rules that match on absolute paths never fire on Cline activity.
+//
+// Joining is skipped when the path is already absolute, and when no workspace root was resolved:
+// a wrong root would be worse than a relative path, because it names a file that was never touched.
+func clineWorkspacePath(path, root string) string {
+ path = hookdiff.NormalizePath(path)
+ if path == "" || root == "" || filepath.IsAbs(path) {
+ return path
+ }
+ return filepath.Join(root, path)
+}
+
+func clineToolPath(toolInput map[string]interface{}, root string) string {
+ return clineWorkspacePath(
+ firstToolString(toolInput, "path", "file_path", "filePath", "target_file", "targetFile"),
+ root,
+ )
+}
+
+func clineToolFields(input map[string]interface{}, completed bool) map[string]interface{} {
+ toolName := clineToolName(input)
+ toolInput := clineToolInput(input)
+ toolResponse := clineToolResponse(input)
+ fields := toolFieldsWithResponse(toolName, toolInput, toolResponse)
+
+ call := map[string]interface{}{}
+ if len(toolInput) > 0 {
+ call["arguments"] = toolInput
+ }
+ if completed && len(toolResponse) > 0 {
+ if output, ok := toolResponse["output"]; ok {
+ call["result"] = output
+ } else {
+ call["result"] = toolResponse
+ }
+ }
+ if callID := getFirstStr(input, "callId", "call_id", "toolCallId", "tool_call_id"); callID != "" {
+ call["id"] = callID
+ }
+ fields["gen_ai"] = map[string]interface{}{
+ "operation": map[string]interface{}{"name": "execute_tool"},
+ "tool": map[string]interface{}{
+ "name": toolName,
+ "call": call,
+ },
+ }
+ if duration, ok := firstToolIntAcross([]map[string]interface{}{input, toolResponse}, "durationMs", "duration_ms"); ok {
+ fields["tool"] = mergeNested(fields["tool"], map[string]interface{}{"duration_ms": duration})
+ }
+
+ // resolveCwd is asked for the cline shape explicitly rather than through platformFlag: this
+ // function only ever runs on Cline payloads, and reading the flag would make the resolved path
+ // depend on how the binary happened to be invoked.
+ root := resolveCwd(input, "cline")
+ path := clineToolPath(toolInput, root)
+ if path != "" {
+ operation := clineFileOperation(toolName)
+ if operation == "" {
+ // A path on a tool that does nothing to files -- a search root, a project directory --
+ // is not file activity, and recording it as such would put unread files in the log.
+ delete(fields, "file")
+ if tool, ok := fields["tool"].(map[string]interface{}); ok {
+ delete(tool, "path")
+ }
+ } else {
+ fields["file"] = map[string]interface{}{
+ "path": path,
+ "operation": operation,
+ "language": strings.TrimPrefix(filepath.Ext(path), "."),
+ }
+ fields["tool"] = mergeNested(fields["tool"], map[string]interface{}{"name": toolName, "path": path})
+ }
+ }
+
+ if completed {
+ action, _ := clineToolAction(toolName)
+ if action == "file.modified" && path != "" {
+ mergeMap(fields, clineDiffFields(toolName, toolInput, toolResponse, path))
+ if file, ok := fields["file"].(map[string]interface{}); ok {
+ // diffFields records every diff as a modification; a create stays a create.
+ file["operation"] = clineFileOperation(toolName)
+ }
+ }
+ if action == "command.executed" {
+ fields["command"] = clineCommandFields(input, toolInput, toolResponse)
+ }
+ }
+
+ if encoded, err := json.Marshal(map[string]interface{}{"input": toolInput, "response": toolResponse}); err == nil && len(encoded) > 0 {
+ fields["content"] = retainedContentFields(string(encoded))
+ }
+ return fields
+}
+
+// clineDiffFields builds the file diff for a mutation.
+//
+// write_to_file goes through the shared builder, which turns its `content` argument into an
+// added-lines diff. replace_in_file deliberately does not: its `diff` argument is already a diff,
+// so passing it through records what Cline actually applied instead of an approximation
+// reconstructed from the pieces.
+//
+// The path is only used for the event field. The shared builder names files by base name in diff
+// headers, the same for every runtime, so it needs nothing resolved.
+func clineDiffFields(toolName string, toolInput, toolResponse map[string]interface{}, path string) map[string]interface{} {
+ diffText := hookdiff.FromToolResponse(toolName, toolInput, toolResponse)
+ if diffText == "" {
+ diffText = firstToolString(toolInput, "diff", "content", "new_string", "newString")
+ }
+ return diffFields(path, diffText)
+}
+
+func clineCommandFields(input, toolInput, toolResponse map[string]interface{}) map[string]interface{} {
+ fields := map[string]interface{}{"command": firstToolString(toolInput, "command", "cmd")}
+ if output := firstToolString(toolResponse, "output", "stdout", "text", "result"); output != "" {
+ fields["output"] = output
+ }
+ if exitCode, ok := firstToolIntAcross([]map[string]interface{}{toolResponse, input}, "exit_code", "exitCode"); ok {
+ fields["exit_code"] = exitCode
+ }
+ if duration, ok := firstToolIntAcross([]map[string]interface{}{input, toolResponse}, "durationMs", "duration_ms"); ok {
+ fields["duration_ms"] = duration
+ }
+ return fields
+}
+
+func clineToolAfterEvents(input map[string]interface{}, fields map[string]interface{}) []normalizedEvent {
+ mergeMap(fields, clineToolFields(input, true))
+ if errText := clineToolError(input); errText != "" {
+ fields["error"] = map[string]interface{}{"type": "tool_error"}
+ fields["content"] = retainedContentFields(errText)
+ return []normalizedEvent{{
+ action: "tool.failed", category: "tool", severity: "high",
+ message: "Cline tool failed", fields: fields,
+ }}
+ }
+ action, category := clineToolAction(clineToolName(input))
+ // A file action with no file is not a file action. Cline's read tools accept a directory or a
+ // pattern instead of a path, and reporting those as file.read with no file field produces a row
+ // that every file-scoped query matches and none can explain.
+ if strings.HasPrefix(action, "file.") {
+ if _, ok := fields["file"]; !ok {
+ action, category = "tool.completed", "tool"
+ }
+ }
+ return []normalizedEvent{{
+ action: action, category: category, severity: "info",
+ message: clineToolMessage(action), fields: fields,
+ }}
+}
+
+// clineUsage normalizes Cline's reported token counts into gen_ai.usage.
+//
+// Read from the task-end payload only, and deliberately not from any per-model-call stage. Beacon's
+// token rollups sum gen_ai.usage across events, so emitting usage at both granularities would count
+// every token twice. Cline's documented usage lives on the run result, which makes task-end the one
+// place it can be read without guessing at a field path.
+//
+// Cost is taken only as Cline reports it. Beacon never derives cost from a local price table.
+func clineUsage(input map[string]interface{}) map[string]interface{} {
+ usage := firstMap(input, "usage", "tokens")
+ if usage == nil {
+ for _, key := range []string{"result", "run", "output", "metrics"} {
+ if nested := firstMap(input, key); nested != nil {
+ if usage = firstMap(nested, "usage", "tokens"); usage != nil {
+ break
+ }
+ }
+ }
+ }
+ if usage == nil {
+ return nil
+ }
+ sources := []map[string]interface{}{usage}
+ out := map[string]interface{}{}
+ if value, ok := firstToolIntAcross(sources, "inputTokens", "input_tokens", "tokensIn", "tokens_in", "promptTokens", "prompt_tokens"); ok {
+ out["input_tokens"] = value
+ }
+ if value, ok := firstToolIntAcross(sources, "outputTokens", "output_tokens", "tokensOut", "tokens_out", "completionTokens", "completion_tokens"); ok {
+ out["output_tokens"] = value
+ }
+ if value, ok := firstToolIntAcross(sources, "cacheReadTokens", "cache_read_tokens", "cachedTokens", "cached_tokens"); ok {
+ out["cache_read"] = map[string]interface{}{"input_tokens": value}
+ }
+ if value, ok := firstToolIntAcross(sources, "cacheWriteTokens", "cache_write_tokens", "cacheCreationTokens", "cache_creation_tokens"); ok {
+ out["cache_creation"] = map[string]interface{}{"input_tokens": value}
+ }
+ if value, ok := clineCost(usage, input); ok {
+ out["cost_usd"] = value
+ }
+ return out
+}
+
+func clineCost(sources ...map[string]interface{}) (float64, bool) {
+ for _, source := range sources {
+ if source == nil {
+ continue
+ }
+ for _, key := range []string{"totalCost", "total_cost", "costUsd", "cost_usd", "cost"} {
+ if value, ok := jsonFloat(source[key]); ok {
+ return value, true
+ }
+ }
+ }
+ return 0, false
+}
diff --git a/cli/beacon-hooks/cmd/cline_event_test.go b/cli/beacon-hooks/cmd/cline_event_test.go
new file mode 100644
index 00000000..72bd8f02
--- /dev/null
+++ b/cli/beacon-hooks/cmd/cline_event_test.go
@@ -0,0 +1,480 @@
+package cmd
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// clineTestLog puts a Cline hook run in a temp endpoint log and returns its path.
+func clineTestLog(t *testing.T) string {
+ t.Helper()
+ setupHookConfigDirs(t)
+ platformFlag = "cline"
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ t.Setenv("BEACON_ENDPOINT_MODE", "1")
+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)
+ t.Setenv("BEACON_CONTENT_RETENTION", "full")
+ return logPath
+}
+
+func clineEventActions(t *testing.T, logPath string) []string {
+ t.Helper()
+ var actions []string
+ for _, event := range endpointEvents(t, logPath) {
+ event, _ := event["event"].(map[string]interface{})
+ actions = append(actions, event["action"].(string))
+ }
+ return actions
+}
+
+func clineEventWithAction(t *testing.T, logPath, action string) map[string]interface{} {
+ t.Helper()
+ for _, event := range endpointEvents(t, logPath) {
+ meta, _ := event["event"].(map[string]interface{})
+ if meta["action"] == action {
+ return event
+ }
+ }
+ t.Fatalf("no %s event in log; got %v", action, clineEventActions(t, logPath))
+ return nil
+}
+
+func readClineFixture(t *testing.T, name string) map[string]interface{} {
+ t.Helper()
+ data, err := os.ReadFile(filepath.Join("..", "testdata", "cline", name))
+ if err != nil {
+ t.Fatalf("read cline fixture %s: %v", name, err)
+ }
+ var payload map[string]interface{}
+ if err := json.Unmarshal(data, &payload); err != nil {
+ t.Fatalf("decode cline fixture %s: %v", name, err)
+ }
+ return payload
+}
+
+func nested(t *testing.T, event map[string]interface{}, keys ...string) map[string]interface{} {
+ t.Helper()
+ current := event
+ for _, key := range keys {
+ next, ok := current[key].(map[string]interface{})
+ if !ok {
+ t.Fatalf("event is missing the %s object: %v", strings.Join(keys, "."), event)
+ }
+ current = next
+ }
+ return current
+}
+
+// A task start is both the start of a session and the moment the user's request arrives, so it
+// produces two events. Recording only one would lose either the session boundary or the prompt.
+func TestClineEventTaskStartRecordsSessionAndPrompt(t *testing.T) {
+ logPath := clineTestLog(t)
+
+ out := runHookWithInput(t, runClineEvent, map[string]interface{}{
+ "type": "beforeRun",
+ "taskId": "task-1",
+ "workspaceRoots": []interface{}{"/tmp/project"},
+ "apiProvider": "anthropic",
+ "modelId": "claude-sonnet-4",
+ "input": map[string]interface{}{"text": "ship it token=cline-secret"},
+ })
+ if len(out) != 0 {
+ t.Fatalf("response = %#v, want empty object", out)
+ }
+
+ if got := clineEventActions(t, logPath); len(got) != 2 || got[0] != "session.started" || got[1] != "prompt.submitted" {
+ t.Fatalf("actions = %v, want [session.started prompt.submitted]", got)
+ }
+ event := clineEventWithAction(t, logPath, "prompt.submitted")
+ if harness := nested(t, event, "harness")["name"]; harness != "cline" {
+ t.Errorf("harness.name = %q, want cline", harness)
+ }
+ if id := nested(t, event, "session")["id"]; id != "task-1" {
+ t.Errorf("session.id = %q, want task-1", id)
+ }
+ if got := nested(t, event, "prompt")["text"]; got != "ship it token=[REDACTED]" {
+ t.Errorf("prompt.text = %q, want the redacted prompt", got)
+ }
+ if got := event["model"]; got != "anthropic/claude-sonnet-4" {
+ t.Errorf("model = %q, want the provider-qualified model", got)
+ }
+ if got := nested(t, event, "session")["working_directory"]; got != "/tmp/project" {
+ t.Errorf("session.working_directory = %q, want the workspace root", got)
+ }
+}
+
+// The file-based hook surface names the hook in `hookName` and sends prompts on their own, so a
+// prompt payload with no run-start context still has to produce a prompt event.
+func TestClineEventPromptOnlyPayload(t *testing.T) {
+ logPath := clineTestLog(t)
+
+ runHookWithInput(t, runClineEvent, map[string]interface{}{
+ "hookName": "UserPromptSubmit",
+ "taskId": "task-2",
+ "prompt": "explain this repo",
+ })
+
+ if got := clineEventActions(t, logPath); len(got) != 1 || got[0] != "prompt.submitted" {
+ t.Fatalf("actions = %v, want [prompt.submitted]", got)
+ }
+}
+
+func TestClineEventBeforeToolRecordsInvocation(t *testing.T) {
+ logPath := clineTestLog(t)
+
+ runHookWithInput(t, runClineEvent, map[string]interface{}{
+ "type": "beforeTool",
+ "taskId": "task-3",
+ "workspaceRoots": []interface{}{"/tmp/project"},
+ "toolCall": map[string]interface{}{"name": "read_file", "input": map[string]interface{}{"path": "src/app.ts"}},
+ })
+
+ event := clineEventWithAction(t, logPath, "tool.invoked")
+ if got := nested(t, event, "tool")["name"]; got != "read_file" {
+ t.Errorf("tool.name = %q, want read_file", got)
+ }
+ if got := nested(t, event, "gen_ai", "tool", "call")["arguments"]; got == nil {
+ t.Errorf("gen_ai.tool.call.arguments is missing: %v", event)
+ }
+}
+
+// Cline addresses files relative to the workspace. Every other runtime reports absolute paths, so
+// the join is what makes a Cline file event comparable with the same file seen through Cursor or
+// Claude Code -- and what lets a threat rule matching an absolute path fire on Cline activity.
+func TestClineEventResolvesWorkspaceRelativePaths(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ roots interface{}
+ path string
+ want string
+ }{
+ {
+ name: "relative path is joined to the workspace root",
+ roots: []interface{}{"/tmp/project"},
+ path: "src/app.ts",
+ want: filepath.Join("/tmp/project", "src/app.ts"),
+ },
+ {
+ name: "absolute path is left alone",
+ roots: []interface{}{"/tmp/project"},
+ path: "/etc/hosts",
+ want: "/etc/hosts",
+ },
+ {
+ name: "relative path stays relative when no root is known",
+ roots: nil,
+ path: "src/app.ts",
+ want: "src/app.ts",
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ logPath := clineTestLog(t)
+ payload := map[string]interface{}{
+ "type": "afterTool",
+ "taskId": "task-4",
+ "toolCall": map[string]interface{}{"name": "read_file", "input": map[string]interface{}{"path": tc.path}},
+ }
+ if tc.roots != nil {
+ payload["workspaceRoots"] = tc.roots
+ }
+ runHookWithInput(t, runClineEvent, payload)
+
+ event := clineEventWithAction(t, logPath, "file.read")
+ if got := nested(t, event, "file")["path"]; got != tc.want {
+ t.Errorf("file.path = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestClineEventWriteToFileRecordsDiff(t *testing.T) {
+ logPath := clineTestLog(t)
+ runHookWithInput(t, runClineEvent, readClineFixture(t, "tool_after_write.json"))
+
+ event := clineEventWithAction(t, logPath, "file.modified")
+ file := nested(t, event, "file")
+ if got := file["path"]; got != filepath.Join("/Users/example/projects/beacon-demo", "src/health.ts") {
+ t.Errorf("file.path = %q, want the resolved workspace path", got)
+ }
+ // write_to_file creates a file. diffFields records every diff as a modification, so a create
+ // that came back as "modify" would mean the operation was overwritten by the diff builder.
+ if got := file["operation"]; got != "create" {
+ t.Errorf("file.operation = %q, want create", got)
+ }
+ if file["diff_hash"] == nil || file["diff_bytes"] == nil {
+ t.Errorf("file diff metadata is missing: %v", file)
+ }
+ // The content Cline wrote is recorded as an added-lines diff through the shared builder, which
+ // names files by base name for every runtime. The absolute path lives in file.path above.
+ diff, _ := file["diff"].(string)
+ if !strings.Contains(diff, "+++ b/health.ts") || !strings.Contains(diff, "+export const health") {
+ t.Errorf("diff does not describe the written file: %q", diff)
+ }
+ if got := nested(t, event, "tool")["duration_ms"]; got != float64(34) {
+ t.Errorf("tool.duration_ms = %v, want 34", got)
+ }
+}
+
+// replace_in_file's argument is already a diff, so it is passed through rather than reconstructed:
+// what Beacon records should be what Cline applied.
+func TestClineEventReplaceInFilePassesTheDiffThrough(t *testing.T) {
+ logPath := clineTestLog(t)
+ diffText := "------- SEARCH\nold()\n=======\nnew()\n+++++++ REPLACE"
+
+ runHookWithInput(t, runClineEvent, map[string]interface{}{
+ "type": "afterTool",
+ "taskId": "task-5",
+ "workspaceRoots": []interface{}{"/tmp/project"},
+ "toolCall": map[string]interface{}{
+ "name": "replace_in_file",
+ "input": map[string]interface{}{"path": "src/app.ts", "diff": diffText},
+ },
+ })
+
+ file := nested(t, clineEventWithAction(t, logPath, "file.modified"), "file")
+ if got := file["operation"]; got != "modify" {
+ t.Errorf("file.operation = %q, want modify", got)
+ }
+ if got := file["diff"]; got != diffText {
+ t.Errorf("file.diff = %q, want the diff Cline applied", got)
+ }
+ if got := file["diff_bytes"]; got != float64(len(diffText)) {
+ t.Errorf("file.diff_bytes = %v, want %d", got, len(diffText))
+ }
+}
+
+func TestClineEventExecuteCommandRecordsCommand(t *testing.T) {
+ logPath := clineTestLog(t)
+ runHookWithInput(t, runClineEvent, readClineFixture(t, "tool_after_command.json"))
+
+ event := clineEventWithAction(t, logPath, "command.executed")
+ command := nested(t, event, "command")
+ if got := command["command"]; got != "npm test" {
+ t.Errorf("command.command = %q, want npm test", got)
+ }
+ if got := command["output"]; got != "2 passing" {
+ t.Errorf("command.output = %q, want the captured output", got)
+ }
+ // A zero exit code is a real value, not an absent one: dropping it would report every clean
+ // command as having no result.
+ if got, ok := command["exit_code"]; !ok || got != float64(0) {
+ t.Errorf("command.exit_code = %v (present=%t), want 0", got, ok)
+ }
+ if got := command["duration_ms"]; got != float64(4120) {
+ t.Errorf("command.duration_ms = %v, want 4120", got)
+ }
+}
+
+func TestClineEventMCPToolIsRecordedAsMCP(t *testing.T) {
+ logPath := clineTestLog(t)
+
+ runHookWithInput(t, runClineEvent, map[string]interface{}{
+ "type": "afterTool",
+ "taskId": "task-6",
+ "toolCall": map[string]interface{}{
+ "name": "use_mcp_tool",
+ "input": map[string]interface{}{"server_name": "github", "tool_name": "list_issues"},
+ },
+ })
+
+ if got := clineEventActions(t, logPath); len(got) != 1 || got[0] != "mcp.tool_invoked" {
+ t.Fatalf("actions = %v, want [mcp.tool_invoked]", got)
+ }
+}
+
+func TestClineEventToolFailureIsHighSeverity(t *testing.T) {
+ logPath := clineTestLog(t)
+
+ runHookWithInput(t, runClineEvent, map[string]interface{}{
+ "type": "afterTool",
+ "taskId": "task-7",
+ "toolCall": map[string]interface{}{"name": "read_file", "input": map[string]interface{}{"path": "missing.ts"}},
+ "error": map[string]interface{}{"message": "ENOENT: no such file"},
+ })
+
+ event := clineEventWithAction(t, logPath, "tool.failed")
+ if got := event["severity"]; got != "high" {
+ t.Errorf("severity = %q, want high", got)
+ }
+ if got := nested(t, event, "error")["type"]; got != "tool_error" {
+ t.Errorf("error.type = %q, want tool_error", got)
+ }
+}
+
+// A file action with no file is not a file action: Cline's search tools take a pattern rather than
+// a path, and a file.read with no file field matches every file-scoped query and explains none.
+func TestClineEventFileActionWithoutAPathBecomesToolCompleted(t *testing.T) {
+ logPath := clineTestLog(t)
+
+ runHookWithInput(t, runClineEvent, map[string]interface{}{
+ "type": "afterTool",
+ "taskId": "task-8",
+ "toolCall": map[string]interface{}{"name": "search_files", "input": map[string]interface{}{"regex": "TODO"}},
+ })
+
+ if got := clineEventActions(t, logPath); len(got) != 1 || got[0] != "tool.completed" {
+ t.Fatalf("actions = %v, want [tool.completed]", got)
+ }
+}
+
+func TestClineEventTaskEndRecordsUsage(t *testing.T) {
+ logPath := clineTestLog(t)
+ runHookWithInput(t, runClineEvent, readClineFixture(t, "run_end_usage.json"))
+
+ event := clineEventWithAction(t, logPath, "session.ended")
+ usage := nested(t, event, "gen_ai", "usage")
+ if got := usage["input_tokens"]; got != float64(1841) {
+ t.Errorf("gen_ai.usage.input_tokens = %v, want 1841", got)
+ }
+ if got := usage["output_tokens"]; got != float64(412) {
+ t.Errorf("gen_ai.usage.output_tokens = %v, want 412", got)
+ }
+ if got := nested(t, event, "gen_ai", "usage", "cache_read")["input_tokens"]; got != float64(1024) {
+ t.Errorf("gen_ai.usage.cache_read.input_tokens = %v, want 1024", got)
+ }
+ if got := usage["cost_usd"]; got != 0.0231 {
+ t.Errorf("gen_ai.usage.cost_usd = %v, want the runtime-reported cost", got)
+ }
+}
+
+// Cost is only ever what the runtime reported. Beacon must not derive it from a local price table,
+// so a usage payload without a cost must produce no cost field at all.
+func TestClineEventDoesNotInventCost(t *testing.T) {
+ logPath := clineTestLog(t)
+
+ runHookWithInput(t, runClineEvent, map[string]interface{}{
+ "type": "afterRun",
+ "taskId": "task-9",
+ "result": map[string]interface{}{"usage": map[string]interface{}{"inputTokens": 10, "outputTokens": 2}},
+ })
+
+ usage := nested(t, clineEventWithAction(t, logPath, "session.ended"), "gen_ai", "usage")
+ if _, ok := usage["cost_usd"]; ok {
+ t.Errorf("gen_ai.usage.cost_usd = %v, want no cost when the runtime reported none", usage["cost_usd"])
+ }
+}
+
+// Token usage is read at exactly one lifecycle point. Beacon's rollups sum gen_ai.usage across
+// events, so a second stage reporting the same tokens would double every Cline task's token count.
+func TestClineEventReportsUsageOnlyAtTaskEnd(t *testing.T) {
+ logPath := clineTestLog(t)
+
+ runHookWithInput(t, runClineEvent, map[string]interface{}{
+ "type": "afterModel",
+ "taskId": "task-10",
+ "usage": map[string]interface{}{"inputTokens": 10, "outputTokens": 2},
+ "toolCall": map[string]interface{}{"name": "read_file"},
+ })
+
+ if data, err := os.ReadFile(logPath); err == nil && len(strings.TrimSpace(string(data))) != 0 {
+ t.Fatalf("afterModel wrote events, want none: %s", data)
+ }
+}
+
+// An unrecognized stage writes nothing. Cline streams far more runtime events than the lifecycle
+// points Beacon maps, and a generic "something happened" row per event would bury the log.
+func TestClineEventIgnoresUnknownStages(t *testing.T) {
+ logPath := clineTestLog(t)
+
+ runHookWithInput(t, runClineEvent, map[string]interface{}{
+ "type": "iteration_start",
+ "taskId": "task-11",
+ })
+
+ if data, err := os.ReadFile(logPath); err == nil && len(strings.TrimSpace(string(data))) != 0 {
+ t.Fatalf("unknown stage wrote events, want none: %s", data)
+ }
+}
+
+// A malformed payload must not fail the hook. Cline runs these in-process; an error here would
+// surface in the user's editor, and telemetry is never worth that.
+func TestClineEventSurvivesAnEmptyPayload(t *testing.T) {
+ clineTestLog(t)
+ out := runHookWithInput(t, runClineEvent, map[string]interface{}{})
+ if len(out) != 0 {
+ t.Fatalf("response = %#v, want empty object", out)
+ }
+}
+
+// Every spelling the mapper claims to accept must still produce an event. These strings are the
+// contract between this mapper and the managed plugin, and a typo on either side produces silence
+// rather than an error.
+func TestClineEventSupportedTypesAllProduceEvents(t *testing.T) {
+ for _, eventType := range supportedClineEventTypes() {
+ t.Run(eventType, func(t *testing.T) {
+ logPath := clineTestLog(t)
+ runHookWithInput(t, runClineEvent, map[string]interface{}{
+ "type": eventType,
+ "taskId": "task-12",
+ "workspaceRoots": []interface{}{"/tmp/project"},
+ "prompt": "do the thing",
+ "toolCall": map[string]interface{}{"name": "read_file", "input": map[string]interface{}{"path": "src/app.ts"}},
+ "usage": map[string]interface{}{"inputTokens": 4},
+ "error": map[string]interface{}{"name": "aborted"},
+ })
+ if actions := clineEventActions(t, logPath); len(actions) == 0 {
+ t.Fatalf("type %q produced no events", eventType)
+ }
+ })
+ }
+}
+
+func TestClineStageRecognizesSpellingVariants(t *testing.T) {
+ for input, want := range map[string]string{
+ "beforeRun": clineStageTaskStart,
+ "run_start": clineStageTaskStart,
+ "TaskStart": clineStageTaskStart,
+ "pre_tool_use": clineStageToolBefore,
+ "PreToolUse": clineStageToolBefore,
+ "tool_call_before": clineStageToolBefore,
+ "PostToolUse": clineStageToolAfter,
+ "tool_call_after": clineStageToolAfter,
+ "afterRun": clineStageTaskEnd,
+ "session_shutdown": clineStageTaskEnd,
+ "stop_error": clineStageTaskError,
+ "iteration_start": "",
+ "": "",
+ } {
+ t.Run(input, func(t *testing.T) {
+ if got := clineStage(map[string]interface{}{"type": input}); got != want {
+ t.Errorf("clineStage(%q) = %q, want %q", input, got, want)
+ }
+ })
+ }
+}
+
+func TestClineToolActionClassification(t *testing.T) {
+ for tool, want := range map[string]string{
+ "read_file": "file.read",
+ "list_files": "file.read",
+ "search_files": "file.read",
+ "list_code_definition_names": "file.read",
+ "write_to_file": "file.modified",
+ "replace_in_file": "file.modified",
+ "execute_command": "command.executed",
+ "run_commands": "command.executed",
+ "use_mcp_tool": "mcp.tool_invoked",
+ "access_mcp_resource": "mcp.tool_invoked",
+ "browser_action": "tool.completed",
+ "ask_followup_question": "tool.completed",
+ } {
+ t.Run(tool, func(t *testing.T) {
+ if got, _ := clineToolAction(tool); got != want {
+ t.Errorf("clineToolAction(%q) = %q, want %q", tool, got, want)
+ }
+ })
+ }
+}
+
+// The token rules must not classify a tool by a word that merely appears inside another word --
+// the reason toolNameHasToken splits on boundaries instead of matching substrings.
+func TestClineToolActionDoesNotMatchSubstrings(t *testing.T) {
+ for _, tool := range []string{"spreadsheet_export", "thread_summary"} {
+ if got, _ := clineToolAction(tool); got != "tool.completed" {
+ t.Errorf("clineToolAction(%q) = %q, want tool.completed", tool, got)
+ }
+ }
+}
diff --git a/cli/beacon-hooks/cmd/pre_tool_test.go b/cli/beacon-hooks/cmd/pre_tool_test.go
index cee00ff4..51602071 100644
--- a/cli/beacon-hooks/cmd/pre_tool_test.go
+++ b/cli/beacon-hooks/cmd/pre_tool_test.go
@@ -904,6 +904,7 @@ func setupHookConfigDirs(t *testing.T) {
origGrokDir := hookconfig.GrokDir
origHermesDir := hookconfig.HermesDir
origOpenCodeDir := hookconfig.OpenCodeDir
+ origClineDir := hookconfig.ClineDir
origPlatform := platformFlag
hookconfig.BeaconDir = tmp
hookconfig.ClaudeDir = filepath.Join(tmp, "claude")
@@ -916,6 +917,7 @@ func setupHookConfigDirs(t *testing.T) {
hookconfig.GrokDir = filepath.Join(tmp, "grok")
hookconfig.HermesDir = filepath.Join(tmp, "hermes")
hookconfig.OpenCodeDir = filepath.Join(tmp, "opencode")
+ hookconfig.ClineDir = filepath.Join(tmp, "cline")
t.Cleanup(func() {
hookconfig.BeaconDir = origBeaconDir
hookconfig.ClaudeDir = origClaudeDir
@@ -928,6 +930,7 @@ func setupHookConfigDirs(t *testing.T) {
hookconfig.GrokDir = origGrokDir
hookconfig.HermesDir = origHermesDir
hookconfig.OpenCodeDir = origOpenCodeDir
+ hookconfig.ClineDir = origClineDir
platformFlag = origPlatform
})
}
diff --git a/cli/beacon-hooks/internal/diff/diff.go b/cli/beacon-hooks/internal/diff/diff.go
index 62902451..5c7bd8db 100644
--- a/cli/beacon-hooks/internal/diff/diff.go
+++ b/cli/beacon-hooks/internal/diff/diff.go
@@ -43,7 +43,7 @@ func FromToolResponse(toolName string, toolInput, toolResponse map[string]interf
content := GetStringFromMaps("code", toolInput, toolResponse)
return fromWriteTool(filePath, content, "")
- case "Write", "Create", "write", "write_file":
+ case "Write", "Create", "write", "write_file", "write_to_file":
content := GetStringFromMaps("content", toolInput, toolResponse)
originalFile := GetStringFromMaps("originalFile", toolInput, toolResponse)
return fromWriteTool(filePath, content, originalFile)
diff --git a/cli/beacon-hooks/internal/diff/diff_test.go b/cli/beacon-hooks/internal/diff/diff_test.go
index f17ceb4a..50d660d8 100644
--- a/cli/beacon-hooks/internal/diff/diff_test.go
+++ b/cli/beacon-hooks/internal/diff/diff_test.go
@@ -126,3 +126,22 @@ func TestFromCursorEdits_MultilineEdit(t *testing.T) {
t.Error("Missing file header")
}
}
+
+// Cline's write tool is spelled write_to_file. Without it in the Write case, FromToolResponse
+// returns nothing and a created file reaches the log as raw content with no diff metadata.
+func TestFromToolResponse_ClineWriteToFile(t *testing.T) {
+ got := FromToolResponse(
+ "write_to_file",
+ map[string]interface{}{"path": "src/health.ts", "content": "export const health = () => true\n"},
+ nil,
+ )
+ if !strings.Contains(got, "--- a/health.ts") || !strings.Contains(got, "+++ b/health.ts") {
+ t.Fatalf("diff header = %q, want the file named in both halves", got)
+ }
+ if !strings.Contains(got, "@@ -0,0 +1,") {
+ t.Errorf("diff = %q, want a new-file hunk header", got)
+ }
+ if !strings.Contains(got, "+export const health") {
+ t.Errorf("diff = %q, want the written content as added lines", got)
+ }
+}
diff --git a/cli/beacon-hooks/testdata/cline/README.md b/cli/beacon-hooks/testdata/cline/README.md
new file mode 100644
index 00000000..9ec07aaa
--- /dev/null
+++ b/cli/beacon-hooks/testdata/cline/README.md
@@ -0,0 +1,25 @@
+# Cline payload fixtures
+
+These payloads are **constructed from Cline's published hook documentation, not captured from a
+running Cline install**. That is a deliberate limitation of this pack and the reason the mapper's
+readers accept several spellings per field: Cline documents the base fields every hook receives
+(`clineVersion`, `hookName`, `timestamp`, `taskId`, `workspaceRoots`, `userId`) and the hook
+handlers a plugin implements (`beforeRun`, `beforeTool`, `afterTool`, `afterRun`), but not the field
+names inside each handler's context object.
+
+What the fixtures do pin is the part Beacon controls: the envelope the Beacon-managed Cline plugin
+sends to `beacon-hooks --platform cline cline-event`. The mapper's job is to turn that envelope into
+endpoint events, and these files are that contract.
+
+Covered payloads:
+
+- `task_start.json` — `beforeRun` carrying the message that started the task
+- `tool_after_write.json` — `afterTool` for `write_to_file`, with a workspace-relative path
+- `tool_after_command.json` — `afterTool` for `execute_command`, with output and an exit code
+- `run_end_usage.json` — `afterRun` with runtime-reported token counts and cost
+
+Replace a fixture with a captured payload whenever one becomes available, and keep the field
+tolerance in the mapper until every fixture here is a real capture.
+
+Keep secrets and real prompt content out of fixtures. Use sanitized payloads that preserve the
+field shape needed by `beacon-hooks --platform cline cline-event`.
diff --git a/cli/beacon-hooks/testdata/cline/run_end_usage.json b/cli/beacon-hooks/testdata/cline/run_end_usage.json
new file mode 100644
index 00000000..d908f3ff
--- /dev/null
+++ b/cli/beacon-hooks/testdata/cline/run_end_usage.json
@@ -0,0 +1,16 @@
+{
+ "type": "afterRun",
+ "clineVersion": "3.36.0",
+ "hookName": "afterRun",
+ "timestamp": "2026-08-21T10:16:30Z",
+ "taskId": "task-3f9c1d",
+ "workspaceRoots": ["/Users/example/projects/beacon-demo"],
+ "result": {
+ "usage": {
+ "inputTokens": 1841,
+ "outputTokens": 412,
+ "cacheReadTokens": 1024,
+ "totalCost": 0.0231
+ }
+ }
+}
diff --git a/cli/beacon-hooks/testdata/cline/task_start.json b/cli/beacon-hooks/testdata/cline/task_start.json
new file mode 100644
index 00000000..5e0c5a44
--- /dev/null
+++ b/cli/beacon-hooks/testdata/cline/task_start.json
@@ -0,0 +1,14 @@
+{
+ "type": "beforeRun",
+ "clineVersion": "3.36.0",
+ "hookName": "beforeRun",
+ "timestamp": "2026-08-21T10:15:00Z",
+ "taskId": "task-3f9c1d",
+ "userId": "user-local",
+ "workspaceRoots": ["/Users/example/projects/beacon-demo"],
+ "apiProvider": "anthropic",
+ "modelId": "claude-sonnet-4",
+ "input": {
+ "text": "Add a health endpoint, then run the tests"
+ }
+}
diff --git a/cli/beacon-hooks/testdata/cline/tool_after_command.json b/cli/beacon-hooks/testdata/cline/tool_after_command.json
new file mode 100644
index 00000000..b18220db
--- /dev/null
+++ b/cli/beacon-hooks/testdata/cline/tool_after_command.json
@@ -0,0 +1,20 @@
+{
+ "type": "afterTool",
+ "clineVersion": "3.36.0",
+ "hookName": "afterTool",
+ "timestamp": "2026-08-21T10:16:03Z",
+ "taskId": "task-3f9c1d",
+ "workspaceRoots": ["/Users/example/projects/beacon-demo"],
+ "toolCall": {
+ "name": "execute_command",
+ "input": {
+ "command": "npm test",
+ "requires_approval": false
+ }
+ },
+ "durationMs": 4120,
+ "result": {
+ "output": "2 passing",
+ "exitCode": 0
+ }
+}
diff --git a/cli/beacon-hooks/testdata/cline/tool_after_write.json b/cli/beacon-hooks/testdata/cline/tool_after_write.json
new file mode 100644
index 00000000..fbc00bfb
--- /dev/null
+++ b/cli/beacon-hooks/testdata/cline/tool_after_write.json
@@ -0,0 +1,20 @@
+{
+ "type": "afterTool",
+ "clineVersion": "3.36.0",
+ "hookName": "afterTool",
+ "timestamp": "2026-08-21T10:15:42Z",
+ "taskId": "task-3f9c1d",
+ "workspaceRoots": ["/Users/example/projects/beacon-demo"],
+ "toolCall": {
+ "name": "write_to_file",
+ "input": {
+ "path": "src/health.ts",
+ "content": "export const health = () => ({ ok: true })\n"
+ }
+ },
+ "callId": "call-7a2",
+ "durationMs": 34,
+ "result": {
+ "output": "File written"
+ }
+}