Skip to content

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

fix(hooks): record Cursor's turn-end status on the stop event

aakashpawar1999a8f35f8f6423
diff --git a/cli/beacon-hooks/cmd/openhands_hooks_test.go b/cli/beacon-hooks/cmd/openhands_hooks_test.go
index 59d9b44a..d4ed2e5e 100644
--- a/cli/beacon-hooks/cmd/openhands_hooks_test.go
+++ b/cli/beacon-hooks/cmd/openhands_hooks_test.go
@@ -899,7 +899,7 @@ func TestOpenHandsSessionLifecycleEvents(t *testing.T) {
t.Fatalf("stop session id = %q; the mapping under test would not run", stopSession)
}
emitHookEvent(newHookLogger("stop", platformFlag, stopSession), "tool.completed", "tool", "info",
- "Agent response completed", stopInput, sessionFields(stopSession, stopInput))
+ "Agent response completed", stopInput, stopFields(stopSession, stopInput))
stopEvent := lastEndpointEvent(t, logPath)
if got := leaf(stopEvent, "event", "action"); got != "tool.completed" {
t.Fatalf("event.action = %q, want tool.completed", got)
diff --git a/cli/beacon-hooks/cmd/prompt_id_test.go b/cli/beacon-hooks/cmd/prompt_id_test.go
index dcd74e19..15480093 100644
--- a/cli/beacon-hooks/cmd/prompt_id_test.go
+++ b/cli/beacon-hooks/cmd/prompt_id_test.go
@@ -154,7 +154,7 @@ func TestCursorTurnCarriesOneIDAcrossHookFamilies(t *testing.T) {
stopInput := envelope("stop", "gen-1", map[string]interface{}{"status": "completed"})
stopSession := resolveSessionID(stopInput, "cursor")
emitHookEvent(newHookLogger("stop", "cursor", stopSession), "tool.completed", "tool", "info",
- "Agent response completed", stopInput, sessionFields(stopSession, stopInput))
+ "Agent response completed", stopInput, stopFields(stopSession, stopInput))
runHookWithInput(t, runPromptSubmit, envelope("beforeSubmitPrompt", "gen-2", map[string]interface{}{"prompt": "now a license"}))
events := endpointEvents(t, logPath)
diff --git a/cli/beacon-hooks/cmd/qwen_event_test.go b/cli/beacon-hooks/cmd/qwen_event_test.go
index 57a4bc09..eb72696a 100644
--- a/cli/beacon-hooks/cmd/qwen_event_test.go
+++ b/cli/beacon-hooks/cmd/qwen_event_test.go
@@ -319,7 +319,7 @@ func TestQwenStopContextIsNormalizedIntoContextNotUsage(t *testing.T) {
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))
+ emitHookEvent(logger, "tool.completed", "tool", "info", "Agent response completed", input, stopFields(sessionID, input))
event := lastEndpointEvent(t, logPath)
if got := qwenAction(t, event); got != "tool.completed" {
diff --git a/cli/beacon-hooks/cmd/stop.go b/cli/beacon-hooks/cmd/stop.go
index 4d534d6f..5ff2f60e 100644
--- a/cli/beacon-hooks/cmd/stop.go
+++ b/cli/beacon-hooks/cmd/stop.go
@@ -63,7 +63,7 @@ func runStop(cmd *cobra.Command, args []string) {
if sessionID == "" {
if isDevinLikePlatform(platformFlag) {
logger.Info("stop completed")
- emitHookEvent(logger, "tool.completed", "tool", "info", "Agent response completed", input, sessionFields("", input))
+ emitHookEvent(logger, "tool.completed", "tool", "info", "Agent response completed", input, stopFields("", input))
uploadCloudTelemetry(logger, true)
outputJSON(stopResponse())
return
@@ -82,11 +82,36 @@ func runStop(cmd *cobra.Command, args []string) {
elapsed := time.Since(start)
logger.Info("stop completed", "duration_ms", elapsed.Milliseconds())
- emitHookEvent(logger, "tool.completed", "tool", "info", "Agent response completed", input, sessionFields(sessionID, input))
+ emitHookEvent(logger, "tool.completed", "tool", "info", "Agent response completed", input, stopFields(sessionID, input))
uploadCloudTelemetry(logger, true)
outputJSONAndExit(stopResponse())
}
+// stopFields is the turn-end event's fields: the session, plus how the turn ended when the runtime
+// says so.
+//
+// The action and message stay tool.completed / "Agent response completed" on every runtime, because
+// the dashboard and TraceMessages recognize the turn end by that shape. What changes is that Cursor,
+// whose stop hook sends status completed, aborted or error, now has that status recorded verbatim
+// as turn.status, so in the event log and to threat rules a stopped or failed turn no longer reads
+// exactly like a finished one.
+//
+// Read on Cursor only, as subagent.go reads Cursor's subagentStop status. As of each runtime's hook
+// reference, no other runtime that reaches this hook sends a top-level status on Stop (Claude Code
+// and Qwen nest one per background task, which is not the turn's outcome), so a status key showing
+// up elsewhere is not known to mean how the turn ended. A payload with no status gets no turn block
+// at all rather than a default.
+func stopFields(sessionID string, input map[string]interface{}) map[string]interface{} {
+ fields := sessionFields(sessionID, input)
+ if platformFlag != "cursor" {
+ return fields
+ }
+ if status := strings.TrimSpace(getFirstStr(input, "status")); status != "" {
+ fields["turn"] = map[string]interface{}{"status": status}
+ }
+ return fields
+}
+
// platformToTranscriptName maps the platform flag to the transcript platform identifier.
func platformToTranscriptName(platform string) string {
switch platform {
diff --git a/cli/beacon-hooks/cmd/stop_turn_test.go b/cli/beacon-hooks/cmd/stop_turn_test.go
new file mode 100644
index 00000000..79ff9095
--- /dev/null
+++ b/cli/beacon-hooks/cmd/stop_turn_test.go
@@ -0,0 +1,105 @@
+package cmd
+
+import (
+ "encoding/json"
+ "path/filepath"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+// emitStop writes the turn-end event the way runStop does. runStop itself ends with os.Exit, so the
+// test calls the emitter with the arguments runStop passes it, as the Kimi, Qwen and Kiro stop tests
+// do.
+func emitStop(t *testing.T, platform string, input map[string]interface{}) map[string]interface{} {
+ t.Helper()
+ setupHookConfigDirs(t)
+ original := platformFlag
+ t.Cleanup(func() { platformFlag = original })
+ platformFlag = platform
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)
+ t.Setenv("BEACON_DISABLE_GIT_METADATA", "1")
+
+ sessionID := resolveSessionID(input, platform)
+ emitHookEvent(newHookLogger("stop", platform, sessionID), "tool.completed", "tool", "info",
+ "Agent response completed", input, stopFields(sessionID, input))
+ return lastEndpointEvent(t, logPath)
+}
+
+func cursorStopInput(status string) map[string]interface{} {
+ return map[string]interface{}{
+ "conversation_id": "conv-1",
+ "generation_id": "gen-1",
+ "hook_event_name": "stop",
+ "cursor_version": "1.7.2",
+ "status": status,
+ "loop_count": 0,
+ }
+}
+
+// Cursor's stop hook names how the turn ended. Each status is kept as Cursor wrote it, while the
+// event keeps the shape the dashboard reads as a turn end.
+func TestCursorStopRecordsTurnStatus(t *testing.T) {
+ for _, status := range []string{"completed", "aborted", "error"} {
+ t.Run(status, func(t *testing.T) {
+ event := emitStop(t, "cursor", cursorStopInput(status))
+ if got := leaf(event, "turn", "status"); got != status {
+ t.Fatalf("turn.status = %q, want %q", got, status)
+ }
+ if got := leaf(event, "event", "action"); got != "tool.completed" {
+ t.Fatalf("event.action = %q, want tool.completed", got)
+ }
+ if got, _ := event["message"].(string); got != "Agent response completed" {
+ t.Fatalf("message = %q, want Agent response completed", got)
+ }
+ if got := promptIDOfEvent(event); got != "gen-1" {
+ t.Fatalf("prompt.id = %q, want the turn's generation_id kept beside turn.status", got)
+ }
+ })
+ }
+}
+
+// Claude Code's Stop payload names no status, so its event gains nothing: no turn block, and in
+// particular no "completed" that Claude Code never said.
+func TestStopWithoutStatusWritesNoTurn(t *testing.T) {
+ event := emitStop(t, "claude", map[string]interface{}{
+ "session_id": "claude-session",
+ "cwd": "/repo",
+ "hook_event_name": "Stop",
+ "stop_hook_active": false,
+ })
+ if _, ok := event["turn"]; ok {
+ t.Fatalf("turn = %v, want no turn block when the runtime names no status", event["turn"])
+ }
+}
+
+// Only Cursor's top-level status is known to be the turn's outcome. A status key on another
+// runtime's Stop payload is not read as one.
+func TestStopStatusIsReadOnCursorOnly(t *testing.T) {
+ event := emitStop(t, "qwen", map[string]interface{}{
+ "session_id": "qwen-session",
+ "cwd": "/repo",
+ "hook_event_name": "Stop",
+ "status": "running",
+ })
+ if _, ok := event["turn"]; ok {
+ t.Fatalf("turn = %v, want no turn block for a status Qwen Code does not define as the turn's outcome", event["turn"])
+ }
+}
+
+// The block the hook writes is the one the typed schema reads, so beacon scan and every typed reader
+// see it.
+func TestStopTurnRoundTripsThroughSchema(t *testing.T) {
+ data, err := json.Marshal(emitStop(t, "cursor", cursorStopInput("aborted")))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var event asymptoteobserve.Event
+ if err := json.Unmarshal(data, &event); err != nil {
+ t.Fatal(err)
+ }
+ if event.Turn == nil || event.Turn.Status != "aborted" {
+ t.Fatalf("schema turn = %+v, want status aborted", event.Turn)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/asymptote/metadata_fields_test.go b/cli/beacon/internal/endpoint/asymptote/metadata_fields_test.go
index a36b2f7a..022b2509 100644
--- a/cli/beacon/internal/endpoint/asymptote/metadata_fields_test.go
+++ b/cli/beacon/internal/endpoint/asymptote/metadata_fields_test.go
@@ -71,6 +71,7 @@ var metadataOnlyKept = []string{
"approval.decision",
"policy.id", "policy.name", "policy.decision", "policy.enforcement",
"prompt.id",
+ "turn.status",
"system_context.kind", "system_context.source",
"system_context.skills.skill_name", "system_context.skills.skill_name_hash",
"content.retention", "content.hash",
diff --git a/docs/runtimes/cursor.mdx b/docs/runtimes/cursor.mdx
index ad97a8f7..70563adf 100644
--- a/docs/runtimes/cursor.mdx
+++ b/docs/runtimes/cursor.mdx
@@ -61,6 +61,7 @@ beacon endpoint hooks install --harness cursor --level project
| Command, tool, and file telemetry | Supported for tool, shell command, MCP-like, approval, and file edit payloads where Cursor exposes them; Cursor Cloud support is limited to Cursor's [cloud-supported command hooks](https://cursor.com/docs/hooks#cloud-agent-support). |
| Pre-tool answer | `preToolUse`, `beforeShellExecution` and `beforeReadFile` answer `{"permission":"allow"}`, because Cursor's hooks reference does not make `permission` optional and blocks an action whose hook response does not match the schema. Cursor enforces only a hook's `deny`: an `allow` does not override your allowlist or approval mode, so a command Cursor would ask about still asks. A deny from a `BEACON_POLICY_PROVIDER` policy provider returns `{"permission":"deny"}` |
| Agent responses | Supported for local Cursor through `afterAgentResponse` hooks. Each finished assistant message is recorded as an `agent.message` event with the reply text in `gen_ai.output.messages` (a `text` part) and a `content` marker, in the same turn (`prompt.id`) as the prompt that produced it. Cursor Cloud does not install this hook. `beacon endpoint cursor sync` also recovers committed assistant text |
+| Turn end | Supported for local Cursor through the `stop` hook, recorded as `tool.completed` ("Agent response completed") like every runtime's turn end. Cursor's `status` for the turn (`completed`, `aborted` or `error`) is kept verbatim as `turn.status`, so in the runtime log a stopped or failed turn can be told apart from a finished one, and a threat rule can match `e.turn.status`. The session view and shared traces do not show it yet |
| Agent reasoning telemetry | Supported for local Cursor through `afterAgentThought` hooks. Each completed thinking block is recorded as an `agent.reasoning` event carrying the reasoning text in the OpenTelemetry GenAI output-messages shape (`gen_ai.output.messages` with a `reasoning` part), plus a `content` marker with the original text's hash and byte count. Reasoning is only available for models/modes where Cursor exposes visible thinking text. |
| Repository and branch context | Events include the workspace path as `repository`, and `branch` is resolved from the workspace's local git checkout (`.git/HEAD`) when Cursor does not supply one; disable local git resolution with `BEACON_DISABLE_GIT_METADATA=1`. |
| Token usage and cost | No Cursor hook payload or local record carries a token count or a cost. Team admins can collect per-request token usage and Cursor's charges from the Cursor Admin API with [`beacon endpoint cursor usage sync`](/cli/endpoint-cursor#token-usage-from-the-cursor-admin-api), which writes one `token.usage` event per request |
diff --git a/pkg/asymptoteobserve/event.go b/pkg/asymptoteobserve/event.go
index 509aa64f..db53b84c 100644
--- a/pkg/asymptoteobserve/event.go
+++ b/pkg/asymptoteobserve/event.go
@@ -278,6 +278,16 @@ type PromptInfo struct {
Text string `json:"text,omitempty"`
}
+// TurnInfo says how the agent's turn ended, as the runtime reported it on its turn-end hook.
+//
+// Status is the runtime's own word, kept verbatim: Cursor's stop hook sends completed, aborted or
+// error. The block is set only when the runtime names a status. Beacon never fills in a default,
+// because a turn recorded as completed when the runtime said nothing would read like one the
+// runtime confirmed.
+type TurnInfo struct {
+ Status string `json:"status,omitempty"`
+}
+
// SystemContextInfo says what a session.context event recorded when the runtime gave the model
// context of its own, outside the conversation: which kind it was, where Beacon read it, and for a
// skill index, which skills it listed. The text itself is in gen_ai.system_instructions. This block
@@ -724,6 +734,7 @@ type Event struct {
Approval *ApprovalInfo `json:"approval,omitempty"`
Policy *PolicyInfo `json:"policy,omitempty"`
Prompt *PromptInfo `json:"prompt,omitempty"`
+ Turn *TurnInfo `json:"turn,omitempty"`
SystemContext *SystemContextInfo `json:"system_context,omitempty"`
Content *ContentInfo `json:"content,omitempty"`
Destination *DestinationInfo `json:"destination,omitempty"`
diff --git a/pkg/asymptoteobserve/pipeline.go b/pkg/asymptoteobserve/pipeline.go
index 44d19974..f7e82cde 100644
--- a/pkg/asymptoteobserve/pipeline.go
+++ b/pkg/asymptoteobserve/pipeline.go
@@ -171,6 +171,10 @@ func copyEvent(event Event) Event {
prompt := *event.Prompt
out.Prompt = &prompt
}
+ if event.Turn != nil {
+ turn := *event.Turn
+ out.Turn = &turn
+ }
if event.Content != nil {
content := *event.Content
out.Content = &content
diff --git a/spec/threat-rules/FIELDS.md b/spec/threat-rules/FIELDS.md
index fbd4ffd1..1e17fe4a 100644
--- a/spec/threat-rules/FIELDS.md
+++ b/spec/threat-rules/FIELDS.md
@@ -157,6 +157,7 @@ Regenerate with `beacon rules fields --markdown > spec/threat-rules/FIELDS.md`.
| `e.trace.id` | string |
| `e.trace.parent_span_id` | string |
| `e.trace.span_id` | string |
+| `e.turn.status` | string |
| `e.user.name` | string |
| `e.user.uid` | string |
| `e.user_agent.name` | string |