Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(hooks): file Cursor sessions under their repo and the cursor agent

IshanRTripathi45fada5d2294
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a6f92c69..c49f25f4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+- Cursor sessions no longer land in the default `default/scratch` bucket.
+ Cursor sends the workspace directory only as `workspace_roots` — its
+ `sessionStart` / `sessionEnd` payloads carry no `cwd` key at all, and its
+ tool events send `cwd: ""` — so cwd resolution produced nothing and the
+ server fell back to its default project for every Cursor event. Both the
+ native `ai-memory hook` path and the POSIX/PowerShell hook scripts now read
+ `workspace_roots` (alongside Antigravity's `workspacePaths`) and treat an
+ empty `cwd` as absent rather than as an answer.
+- Cursor sessions are no longer attributed to `claude-code`. The Cursor CLI
+ also runs the hook commands declared in Claude Code's
+ `~/.claude/settings.json`, which `install-hooks --agent claude-code`
+ hardcoded to `--agent claude-code`, so a Cursor-driven session was stored
+ with `agent_kind = claude-code`. Hook payloads carrying Cursor's
+ `cursor_version` marker are now attributed to `cursor` regardless of the
+ `?agent=` the hook command declared.
+
## [2.0.3] - 2026-09-04
### Changed
diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rs
index 7e58329a..6af75470 100644
--- a/crates/ai-memory-cli/src/commands/hook_capture.rs
+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs
@@ -101,16 +101,26 @@ pub fn canonical_context(payload: &serde_json::Value) -> (Option<String>, Option
.filter(|value| !value.trim().is_empty())
.map(str::to_owned)
};
- let cwd = direct(&["cwd", "current_dir", "working_dir", "directory"])
- .or_else(|| {
+ // `workspacePaths` is Antigravity's spelling; `workspace_roots` is
+ // Cursor's. Cursor never sends a usable top-level `cwd` — `sessionStart`
+ // / `sessionEnd` omit it and its tool events send `cwd: ""` — so without
+ // this the whole session resolves to no cwd and lands in `default/scratch`.
+ let first_array_path = |keys: &[&str]| {
+ keys.iter().find_map(|key| {
payload
- .get("workspacePaths")
+ .get(*key)
.and_then(serde_json::Value::as_array)
- .and_then(|paths| paths.first())
- .and_then(serde_json::Value::as_str)
- .filter(|value| !value.trim().is_empty())
+ .and_then(|paths| {
+ paths
+ .iter()
+ .filter_map(serde_json::Value::as_str)
+ .find(|value| !value.trim().is_empty())
+ })
.map(str::to_owned)
})
+ };
+ let cwd = direct(&["cwd", "current_dir", "working_dir", "directory"])
+ .or_else(|| first_array_path(&["workspacePaths", "workspace_roots"]))
.or_else(|| {
[
["path", "cwd"].as_slice(),
@@ -707,6 +717,40 @@ mod tests {
);
}
+ /// Cursor routes the workspace directory through `workspace_roots`:
+ /// `sessionStart` omits `cwd` entirely and tool events send `cwd: ""`.
+ /// Both must resolve, or every Cursor event reaches the server with no
+ /// cwd and is filed under the default `scratch` project. Shapes captured
+ /// live from Cursor CLI 2026.09.02-c22c1a3.
+ #[test]
+ fn canonical_context_reads_cursor_workspace_roots() {
+ let session_start = serde_json::json!({
+ "session_id": "cf111450-8c45-4da1-a384-7a48e08099c3",
+ "hook_event_name": "sessionStart",
+ "cursor_version": "2026.09.02-c22c1a3",
+ "workspace_roots": ["/checkouts/repo-a"]
+ });
+ assert_eq!(
+ canonical_context(&session_start),
+ (
+ Some("/checkouts/repo-a".into()),
+ Some("cf111450-8c45-4da1-a384-7a48e08099c3".into())
+ )
+ );
+
+ let tool_event = serde_json::json!({
+ "session_id": "cf111450-8c45-4da1-a384-7a48e08099c3",
+ "hook_event_name": "postToolUse",
+ "cursor_version": "2026.09.02-c22c1a3",
+ "cwd": "",
+ "workspace_roots": ["/checkouts/repo-a"]
+ });
+ assert_eq!(
+ canonical_context(&tool_event).0,
+ Some("/checkouts/repo-a".into())
+ );
+ }
+
/// `marker_query_suffix` appends `&workspace=…&project=…` (and
/// `&project_strategy=…`, `&drop_subagent=…`) when the marker declares them.
/// Each value is URL-encoded, so a workspace with a space round-trips as `%20`.
diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rs
index 134cdff7..9f0aeabc 100644
--- a/crates/ai-memory-hooks/src/payload.rs
+++ b/crates/ai-memory-hooks/src/payload.rs
@@ -401,6 +401,26 @@ pub fn parse_agent(s: &str) -> AgentKind {
AgentKind::from_wire(s)
}
+/// Identify the harness from the payload itself when it carries an
+/// unambiguous vendor marker, overriding the `?agent=` the hook command
+/// declared.
+///
+/// The Cursor CLI also loads and runs the hook commands declared in Claude
+/// Code's `~/.claude/settings.json` (its Claude Code config compatibility
+/// path, alongside `~/.cursor/hooks.json`). Those commands were installed by
+/// `install-hooks --agent claude-code`, so they hardcode
+/// `--agent claude-code` — and a Cursor-driven session was therefore stored
+/// with `agent_kind = claude-code`. The query string is the *installer's*
+/// guess; `cursor_version` is stamped on every Cursor hook payload and never
+/// appears in a Claude Code one, so the body is the stronger evidence.
+///
+/// Returns `None` when the payload carries no vendor marker, leaving the
+/// declared `?agent=` untouched.
+#[must_use]
+pub fn agent_from_payload(raw: &serde_json::Value) -> Option<AgentKind> {
+ extract_string(raw, &["cursor_version"]).map(|_| AgentKind::Cursor)
+}
+
impl HookEnvelope {
/// Build an envelope from the parsed query + the body JSON. Performs
/// best-effort extraction of `session_id` / `cwd` / a body excerpt
@@ -409,7 +429,8 @@ impl HookEnvelope {
#[must_use]
pub fn from_query_and_body(query: HookQuery, raw: serde_json::Value) -> Self {
let event = HookEvent::parse(&query.event);
- let agent = query.agent.as_deref().map_or(AgentKind::Other, parse_agent);
+ let agent = agent_from_payload(&raw)
+ .unwrap_or_else(|| query.agent.as_deref().map_or(AgentKind::Other, parse_agent));
// OpenCode's plugin SDK sends `sessionID` (capital `ID`) on the
// tool.execute.*/session.* events; Claude Code uses `session_id`,
// Codex `sessionId`, and Antigravity CLI uses `conversationId`.
@@ -441,8 +462,16 @@ impl HookEnvelope {
)
});
let session_id = body_session_id.or_else(|| query.session_id.filter(|s| !s.is_empty()));
+ // Cursor spells the workspace directory `workspace_roots` (an array,
+ // normally one entry; multi-root workspaces carry several) and never
+ // sends a usable top-level `cwd`: its `sessionStart` / `sessionEnd`
+ // payloads omit `cwd` entirely, and its tool events send `cwd: ""`.
+ // Without this spelling every Cursor session resolved to no cwd at all
+ // and landed in the server-default `default/scratch` bucket.
let body_cwd = extract_string(&raw, &["cwd", "current_dir", "working_dir", "directory"])
- .or_else(|| extract_first_string_array_item(&raw, &["workspacePaths"]))
+ .or_else(|| {
+ extract_first_string_array_item(&raw, &["workspacePaths", "workspace_roots"])
+ })
.or_else(|| {
extract_string_path(
&raw,
@@ -1365,6 +1394,111 @@ mod tests {
assert_eq!(env.title_hint.as_deref(), Some("claude-sonnet-4-6"));
}
+ /// Cursor's `sessionStart` carries no `cwd` key at all — the workspace
+ /// directory arrives only as `workspace_roots`. Shape captured live from
+ /// Cursor CLI 2026.09.02-c22c1a3.
+ #[test]
+ fn envelope_resolves_cursor_session_start_cwd_from_workspace_roots() {
+ let q = HookQuery {
+ event: "session-start".into(),
+ agent: Some("cursor".into()),
+ ..Default::default()
+ };
+ let raw = serde_json::json!({
+ "conversation_id": "cf111450-8c45-4da1-a384-7a48e08099c3",
+ "session_id": "cf111450-8c45-4da1-a384-7a48e08099c3",
+ "is_background_agent": false,
+ "hook_event_name": "sessionStart",
+ "cursor_version": "2026.09.02-c22c1a3",
+ "workspace_roots": ["/checkouts/repo-a"],
+ "transcript_path": serde_json::Value::Null
+ });
+
+ let env = HookEnvelope::from_query_and_body(q, raw);
+
+ assert_eq!(env.event, HookEvent::SessionStart);
+ assert_eq!(env.agent, AgentKind::Cursor);
+ assert_eq!(
+ env.cwd.as_deref(),
+ Some("/checkouts/repo-a"),
+ "without workspace_roots the session resolves to no cwd and lands \
+ in the server-default scratch project"
+ );
+ }
+
+ /// Cursor's tool events DO carry a `cwd` key, but send it as an empty
+ /// string; resolution must fall through to `workspace_roots` instead of
+ /// accepting `""`.
+ #[test]
+ fn envelope_resolves_cursor_tool_event_cwd_despite_empty_cwd_string() {
+ let q = HookQuery {
+ event: "post-tool-use".into(),
+ agent: Some("cursor".into()),
+ ..Default::default()
+ };
+ let raw = serde_json::json!({
+ "conversation_id": "cf111450-8c45-4da1-a384-7a48e08099c3",
+ "session_id": "cf111450-8c45-4da1-a384-7a48e08099c3",
+ "tool_name": "Shell",
+ "tool_input": {"command": "echo cap > CAP.txt", "cwd": "", "timeout": 30000},
+ "tool_use_id": "b0fe7c49-7ee7-45e6-91ee-6ee68b7b17e2",
+ "cwd": "",
+ "hook_event_name": "postToolUse",
+ "cursor_version": "2026.09.02-c22c1a3",
+ "workspace_roots": ["/checkouts/repo-a"]
+ });
+
+ let env = HookEnvelope::from_query_and_body(q, raw);
+
+ assert_eq!(env.cwd.as_deref(), Some("/checkouts/repo-a"));
+ }
+
+ /// The Cursor CLI also runs the hook commands declared in Claude Code's
+ /// `~/.claude/settings.json`, which `install-hooks --agent claude-code`
+ /// hardcoded to `--agent claude-code`. The payload's `cursor_version`
+ /// identifies the real harness, so the session must not be filed as
+ /// Claude Code.
+ #[test]
+ fn envelope_attributes_cursor_payload_to_cursor_over_declared_claude_code() {
+ let q = HookQuery {
+ event: "session-start".into(),
+ agent: Some("claude-code".into()),
+ ..Default::default()
+ };
+ let raw = serde_json::json!({
+ "conversation_id": "cf111450-8c45-4da1-a384-7a48e08099c3",
+ "session_id": "cf111450-8c45-4da1-a384-7a48e08099c3",
+ "hook_event_name": "sessionStart",
+ "cursor_version": "2026.09.02-c22c1a3",
+ "workspace_roots": ["/checkouts/repo-a"]
+ });
+
+ let env = HookEnvelope::from_query_and_body(q, raw);
+
+ assert_eq!(env.agent, AgentKind::Cursor);
+ assert_eq!(env.cwd.as_deref(), Some("/checkouts/repo-a"));
+ }
+
+ /// A genuine Claude Code payload carries no vendor marker, so the
+ /// declared `?agent=` still decides.
+ #[test]
+ fn envelope_keeps_declared_agent_when_payload_has_no_vendor_marker() {
+ let q = HookQuery {
+ event: "session-start".into(),
+ agent: Some("claude-code".into()),
+ ..Default::default()
+ };
+ let raw = serde_json::json!({
+ "session_id": "abc-123",
+ "cwd": "/checkouts/repo-a",
+ "hook_event_name": "SessionStart"
+ });
+
+ let env = HookEnvelope::from_query_and_body(q, raw);
+
+ assert_eq!(env.agent, AgentKind::ClaudeCode);
+ }
+
#[test]
fn envelope_uses_query_session_id_when_body_omits_it() {
let q = HookQuery {
diff --git a/hooks/_lib.sh b/hooks/_lib.sh
index 6cc6b287..16726a55 100644
--- a/hooks/_lib.sh
+++ b/hooks/_lib.sh
@@ -74,7 +74,8 @@ ai_memory_parse_toml_flag() {
# Returns the value or nothing. This is intentionally a tiny shell fallback,
# not a JSON parser; taking the first match preserves the top-level cwd when
# tool payloads contain nested `cwd` fields later in the object. Antigravity
-# CLI sends `workspacePaths: ["/repo", ...]` instead of `cwd`.
+# CLI sends `workspacePaths: ["/repo", ...]` instead of `cwd`; Cursor sends
+# `workspace_roots: ["/repo", ...]`.
# Undo the JSON string escapes that can appear in a path value: \\ -> \
# and \/ -> /. Windows payloads carry cwd as "C:\\dev\\proj"; without this
# the doubled backslashes leak into the query string (#188).
@@ -89,15 +90,26 @@ ai_memory_extract_cwd() {
raw=$(printf '%s' "$rest" \
| sed -n -E 's/^[[:space:]]*:[[:space:]]*"([^"]*)".*/\1/p' \
| head -n 1)
- ai_memory_json_unescape_path "$raw"
- return 0
+ if [ -n "$raw" ]; then
+ ai_memory_json_unescape_path "$raw"
+ return 0
+ fi
fi
- rest=${payload#*\"workspacePaths\"}
- [ "$rest" = "$payload" ] && return 0
- raw=$(printf '%s' "$rest" \
- | sed -n -E 's/^[[:space:]]*:[[:space:]]*\[[[:space:]]*"([^"]*)".*/\1/p' \
- | head -n 1)
- ai_memory_json_unescape_path "$raw"
+ # Antigravity CLI sends `workspacePaths`, Cursor `workspace_roots`.
+ # Cursor never sends a usable `cwd`: `sessionStart` / `sessionEnd` omit it
+ # and its tool events send `cwd: ""`, so an empty match above must fall
+ # through to here rather than returning the empty string.
+ for key in workspacePaths workspace_roots; do
+ rest=${payload#*\"$key\"}
+ [ "$rest" = "$payload" ] && continue
+ raw=$(printf '%s' "$rest" \
+ | sed -n -E 's/^[[:space:]]*:[[:space:]]*\[[[:space:]]*"([^"]*)".*/\1/p' \
+ | head -n 1)
+ if [ -n "$raw" ]; then
+ ai_memory_json_unescape_path "$raw"
+ return 0
+ fi
+ done
}
# Extract a harness-native session id from the common hook payload spellings.
diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1
index f818c861..a4fd6848 100644
--- a/hooks/lib/ai-memory-hook.ps1
+++ b/hooks/lib/ai-memory-hook.ps1
@@ -7,16 +7,23 @@ function Get-AiMemoryCwd {
$Value = $Parsed.$Name
if ($Value -is [string] -and $Value.Length -gt 0) { return $Value }
}
- $Paths = $Parsed.workspacePaths
- if ($null -ne $Paths -and $Paths.Count -gt 0 -and $Paths[0] -is [string] -and $Paths[0].Length -gt 0) {
- return $Paths[0]
+ # `workspacePaths` is Antigravity's spelling, `workspace_roots`
+ # Cursor's. Cursor never sends a usable `cwd` (session events omit it,
+ # tool events send ""), so the empty checks above fall through here.
+ foreach ($Name in @("workspacePaths", "workspace_roots")) {
+ $Paths = $Parsed.$Name
+ if ($null -ne $Paths -and $Paths.Count -gt 0 -and $Paths[0] -is [string] -and $Paths[0].Length -gt 0) {
+ return $Paths[0]
+ }
}
} catch {
}
- $match = [regex]::Match($Payload, '"cwd"\s*:\s*"([^"]*)"')
+ $match = [regex]::Match($Payload, '"cwd"\s*:\s*"([^"]+)"')
if ($match.Success) { return $match.Groups[1].Value }
- $workspaceMatch = [regex]::Match($Payload, '"workspacePaths"\s*:\s*\[\s*"([^"]*)"')
- if ($workspaceMatch.Success) { return $workspaceMatch.Groups[1].Value }
+ foreach ($Name in @("workspacePaths", "workspace_roots")) {
+ $workspaceMatch = [regex]::Match($Payload, '"' + $Name + '"\s*:\s*\[\s*"([^"]+)"')
+ if ($workspaceMatch.Success) { return $workspaceMatch.Groups[1].Value }
+ }
return $null
}
diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.sh
index b295fcde..09f96258 100755
--- a/tests/hooks/test_lib.sh
+++ b/tests/hooks/test_lib.sh
@@ -87,6 +87,15 @@ assert_eq "extract cwd from antigravity workspacePaths" "/home/u/agy" "$(ai_memo
PAYLOAD_WINDOWS='{"session_id":"x","cwd":"C:\\dev\\myproject"}'
assert_eq "extract cwd unescapes Windows JSON path" 'C:\dev\myproject' \
"$(ai_memory_extract_cwd "$PAYLOAD_WINDOWS")"
+# Cursor sends the workspace directory only as `workspace_roots`: its
+# sessionStart omits `cwd` and its tool events send `cwd: ""`. Both must
+# resolve or every Cursor event is filed under the default scratch project.
+PAYLOAD_CURSOR_START='{"session_id":"x","hook_event_name":"sessionStart","cursor_version":"2026.09.02","workspace_roots":["/home/u/cur"]}'
+assert_eq "extract cwd from cursor workspace_roots" "/home/u/cur" \
+ "$(ai_memory_extract_cwd "$PAYLOAD_CURSOR_START")"
+PAYLOAD_CURSOR_TOOL='{"session_id":"x","cwd":"","hook_event_name":"postToolUse","workspace_roots":["/home/u/cur"]}'
+assert_eq "extract cwd falls through cursor empty cwd" "/home/u/cur" \
+ "$(ai_memory_extract_cwd "$PAYLOAD_CURSOR_TOOL")"
antigravity_initial() {
if ai_memory_antigravity_is_initial_invocation "$1"; then