Skip to content

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

Rust

fix(hooks): never claim a handoff without a project directory

AkitaOnRailsaa616b0e5a53
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 02718a79..4a1e94dc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,16 @@ version in [`docs/changelog/`](docs/changelog/):
## [Unreleased]
### Fixed
+- Fixed a hook claiming a handoff from the wrong project when an event named
+ no directory. A `SessionStart` (or Kimi Code's `UserPromptSubmit`, or Grok's
+ first `PostToolUse`) whose payload carried no `cwd` sent `GET /handoff` with
+ no scope, so the server resolved its default project or the caller's last
+ active one, and the hook consumed that project's handoff. The native hook,
+ the shell and PowerShell hook bundles, and the generated OpenCode, OpenCode 2,
+ OMP and Pi integrations now fetch no handoff without a directory, for every
+ agent; the native hook says so on stderr at session start. The handoff stays
+ open for `memory_handoff_accept`. Devin still falls back to
+ `DEVIN_PROJECT_DIR`, then the hook's own directory. (#1312)
- Fixed `ai-memory setup` reporting "ai-memory is set up" after it installed
Codex hooks that Codex had not trusted yet. Codex skips an untrusted hook,
so Codex sessions went uncaptured. When Codex was wired, `setup` now asks
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index bba25db8..99942548 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -970,6 +970,12 @@ where
},
|cwd| marker_query_suffix(cwd, args.project_strategy.and_then(|s| s.baked())),
);
+ // `GET /handoff` claims the newest open baton in whatever project the
+ // server resolves. With no cwd the request names none, and the server
+ // falls back to its default or the caller's last active project, so an
+ // unscoped claim could consume another repository's handoff. Without a
+ // resolved directory the handoff stays open for `memory_handoff_accept`.
+ let handoff_scoped = policy_cwd.is_some();
let spool = hook_spool::spool_dir(&dd);
let session_qs = session_id_query_suffix(&dd, &args.agent, &args.event, &json);
let managed_qs = managed_run_query_suffix();
@@ -1097,7 +1103,13 @@ where
// consume the handoff server-side (the GET is destructive) and then
// discard the result — silently losing it. Those agents recover the
// handoff on demand via the MCP `memory_handoff_accept` tool.
- if agent_kind.session_start_injects_handoff() {
+ if agent_kind.session_start_injects_handoff() && !handoff_scoped {
+ eprintln!(
+ "ai-memory hook warning: the event named no project directory, so no handoff \
+ was fetched; recover a pending one with memory_handoff_accept"
+ );
+ }
+ if agent_kind.session_start_injects_handoff() && handoff_scoped {
let client = build_client();
let bearer = hook_spool::resolve_bearer(&client, &dd, effective_token).await;
let native_session_qs = canonical_session_id.as_deref().map_or_else(
@@ -1135,6 +1147,7 @@ where
// canonicalizes both (and the snake/native spellings) to UserPrompt.
if HookEvent::parse(&args.event) == HookEvent::UserPrompt
&& AgentKind::from_wire(&args.agent).user_prompt_injects_handoff()
+ && handoff_scoped
{
let client = build_client();
let bearer = hook_spool::resolve_bearer(&client, &dd, effective_token).await;
@@ -1227,7 +1240,7 @@ where
canonical_session_id.as_deref(),
policy_cwd.as_deref(),
);
- if !shown.is_file() && !subagent_payload {
+ if handoff_scoped && !shown.is_file() && !subagent_payload {
let client = build_client();
let bearer = hook_spool::resolve_bearer(&client, &dd, effective_token).await;
let native_session_qs = canonical_session_id
@@ -2518,6 +2531,84 @@ mod tests {
);
}
+ /// `GET /handoff` claims a baton in whatever project the server resolves,
+ /// so an event that names no directory must not send one: the server
+ /// would fall back to its default or the caller's last active project and
+ /// consume another repository's handoff. Control: the same event with a
+ /// `cwd` claims, scoped to that directory.
+ #[tokio::test]
+ async fn a_handoff_is_never_claimed_without_a_project_directory() {
+ let cases = [
+ ("claude-code", "session-start", serde_json::json!({})),
+ ("codex", "session-start", serde_json::json!({})),
+ (
+ "kimi-code",
+ "user-prompt-submit",
+ serde_json::json!({"prompt": "continue"}),
+ ),
+ (
+ "grok",
+ "post-tool-use",
+ serde_json::json!({"tool_name": "read_file", "tool_input": {}}),
+ ),
+ ];
+ for (agent, event, extra) in cases {
+ for with_cwd in [false, true] {
+ let tmp = tempfile::tempdir().unwrap();
+ let project = tmp.path().join("project");
+ std::fs::create_dir(&project).unwrap();
+ let (base, mut requests) = serve_requests("200 OK", "OTHER-PROJECT-HANDOFF").await;
+ let mut payload = extra.clone();
+ payload["session_id"] = "11111111-2222-3333-4444-555555555555".into();
+ if with_cwd {
+ payload["cwd"] = project.to_string_lossy().into_owned().into();
+ }
+ let mut stdout = Vec::new();
+ run_with_payload(
+ Some(tmp.path().join("data")),
+ HookArgs {
+ agent: agent.into(),
+ server_url: base,
+ ..devin_hook_args(event)
+ },
+ payload.to_string(),
+ &mut stdout,
+ |_, _| Ok(()),
+ )
+ .await
+ .unwrap();
+ let mut recorded = Vec::new();
+ while let Some(request) = first_request(&mut requests).await {
+ recorded.push(request);
+ }
+ let claims: Vec<_> = recorded
+ .iter()
+ .filter(|request| request.starts_with("GET /handoff?"))
+ .collect();
+ let stdout = String::from_utf8(stdout).unwrap();
+ if with_cwd {
+ assert_eq!(claims.len(), 1, "{agent}: {recorded:?}");
+ let target = claims[0].split_whitespace().nth(1).unwrap();
+ assert_eq!(
+ query_param(target, "cwd"),
+ Some(url_encode(&project.to_string_lossy()).as_str()),
+ "{agent}: the claim names its directory: {target}"
+ );
+ assert!(
+ stdout.contains("OTHER-PROJECT-HANDOFF"),
+ "{agent}: {stdout}"
+ );
+ } else {
+ assert!(claims.is_empty(), "{agent}: unscoped claim: {recorded:?}");
+ assert!(
+ !stdout.contains("OTHER-PROJECT-HANDOFF"),
+ "{agent}: {stdout}"
+ );
+ }
+ }
+ }
+ }
+
#[tokio::test]
async fn devin_generated_session_id_reaches_startup_handoff_claim() {
let tmp = tempfile::tempdir().unwrap();
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index c8aea8de..b39d1313 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -5062,6 +5062,10 @@ function postHook(event: string, payload: Record<string, unknown>): void {{
}}
async function fetchHandoff(cwd: string, id: string | undefined): Promise<string | undefined> {{
+ // The GET claims the newest open handoff in whatever project the server
+ // resolves; with no directory that is its default or last active project,
+ // so another repository's baton could be consumed. Leave it open instead.
+ if (!cwd) return undefined;
if (captureServerRouted(cwd)) return undefined;
const url = new URL(`${{SERVER}}/handoff`);
url.searchParams.set("agent", AGENT);
@@ -5816,6 +5820,10 @@ function postHook(event: string, payload: Record<string, unknown>): void {{
}}
async function fetchHandoff(cwd: string, id: string | undefined): Promise<string | undefined> {{
+ // The GET claims the newest open handoff in whatever project the server
+ // resolves; with no directory that is its default or last active project,
+ // so another repository's baton could be consumed. Leave it open instead.
+ if (!cwd) return undefined;
if (captureServerRouted(cwd)) return undefined;
const url = new URL(`${{SERVER}}/handoff`);
url.searchParams.set("agent", AGENT);
@@ -12472,6 +12480,158 @@ model = "gpt-5"
}
}
+ /// `GET /handoff` claims a baton in whatever project the server resolves,
+ /// so a generated integration must never send one without a directory:
+ /// the server would use its default or last active project. OpenCode
+ /// always has its plugin `directory`; Pi and OMP read `ctx.cwd`, which a
+ /// host may omit.
+ #[test]
+ fn generated_integrations_never_fetch_a_handoff_without_a_directory() {
+ let plugins = [
+ (
+ "opencode",
+ build_opencode_plugin("http://127.0.0.1:49374", None, None, "denylist"),
+ ),
+ (
+ "opencode2",
+ build_opencode2_plugin("http://127.0.0.1:49374", None, None, "denylist", false)
+ .unwrap(),
+ ),
+ (
+ "omp",
+ build_omp_extension("http://127.0.0.1:49374", None, None, "denylist"),
+ ),
+ (
+ "pi",
+ build_pi_extension("http://127.0.0.1:49374", None, None, "denylist"),
+ ),
+ ];
+ for (agent, plugin) in plugins {
+ let handoff = plugin
+ .split_once("async function fetchHandoff(")
+ .unwrap_or_else(|| panic!("{agent}: no fetchHandoff"))
+ .1;
+ let guard = handoff
+ .find("if (!cwd) return undefined;")
+ .unwrap_or_else(|| panic!("{agent}: handoff fetch must require a directory"));
+ let request = handoff.find("/handoff`").unwrap();
+ assert!(guard < request, "{agent}: guard must precede the request");
+ }
+ }
+
+ /// Slow tier: spawns Node to run the generated OMP extension.
+ mod slow_generated_handoff_runtime {
+ use super::*;
+
+ const PLACEHOLDER_SERVER: &str = "http://127.0.0.1:65535";
+
+ /// Binds a loopback stand-in for the server, points the rendered
+ /// extension at it, then drives `before_agent_start` for a context
+ /// whose `cwd` is empty and for one that names a directory. Every
+ /// `/handoff` request is recorded with the `cwd` it named.
+ const HARNESS: &str = r#"import { createServer } from "node:http";
+import { readFileSync, writeFileSync } from "node:fs";
+
+const project = process.argv[2]!;
+const claims: string[] = [];
+const server = createServer((req, res) => {
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
+ req.resume();
+ if (url.pathname === "/handoff") {
+ claims.push(url.searchParams.get("cwd") ?? "<none>");
+ res.writeHead(200, { "content-type": "text/plain" });
+ res.end("OTHER-PROJECT-HANDOFF");
+ return;
+ }
+ res.writeHead(204);
+ res.end();
+});
+await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", () => resolve()));
+const port = (server.address() as any).port;
+writeFileSync(
+ "./ext.ts",
+ readFileSync("./ext.template.ts", "utf8").replace("http://127.0.0.1:65535", `http://127.0.0.1:${port}`),
+);
+const { default: AiMemoryExtension } = await import("./ext.ts");
+const handlers: Record<string, any> = {};
+AiMemoryExtension({ on: (name: string, fn: any) => { handlers[name] = fn; } });
+const ctx = (id: string, cwd?: string) => ({
+ sessionManager: { getSessionId: () => id },
+ ...(cwd === undefined ? {} : { cwd }),
+});
+const unscoped = await handlers["before_agent_start"]({ prompt: "continue" }, ctx("s-unscoped", ""));
+const scoped = await handlers["before_agent_start"]({ prompt: "continue" }, ctx("s-scoped", project));
+console.log(JSON.stringify({
+ claims,
+ unscoped: unscoped?.message?.content ?? null,
+ scoped: scoped?.message?.content ?? null,
+}));
+process.exit(0);
+"#;
+
+ #[test]
+ fn omp_extension_never_claims_a_handoff_without_a_directory() {
+ if !Command::new("node")
+ .args(["--experimental-strip-types", "--version"])
+ .output()
+ .is_ok_and(|output| output.status.success())
+ {
+ eprintln!("skipping: node lacks --experimental-strip-types");
+ return;
+ }
+ let tmp = TempDir::new().unwrap();
+ let project = tmp.path().join("project");
+ fs::create_dir(&project).unwrap();
+ fs::write(
+ tmp.path().join("ext.template.ts"),
+ build_omp_extension(PLACEHOLDER_SERVER, None, None, "denylist"),
+ )
+ .unwrap();
+ fs::write(tmp.path().join("harness.ts"), HARNESS).unwrap();
+ let mut command = Command::new("node");
+ for (key, _) in std::env::vars_os() {
+ let key_text = key.to_string_lossy();
+ if key_text.starts_with("AI_MEMORY_") || key_text.starts_with("GIT_") {
+ command.env_remove(&key);
+ }
+ }
+ let output = command
+ .args(["--experimental-strip-types", "--no-warnings", "harness.ts"])
+ .arg(&project)
+ .current_dir(tmp.path())
+ .env("HOME", tmp.path())
+ .env("USERPROFILE", tmp.path())
+ .env("AI_MEMORY_HOME", tmp.path())
+ .env("AI_MEMORY_DATA_DIR", tmp.path().join("data"))
+ .env("GIT_CONFIG_GLOBAL", tmp.path().join("absent-gitconfig"))
+ .env("GIT_CONFIG_SYSTEM", tmp.path().join("absent-gitconfig"))
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "harness failed\nstdout:\n{}\nstderr:\n{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let run: serde_json::Value = serde_json::from_slice(
+ String::from_utf8_lossy(&output.stdout)
+ .lines()
+ .last()
+ .unwrap()
+ .as_bytes(),
+ )
+ .unwrap();
+ // Only the scoped context claims, and it names its directory.
+ assert_eq!(
+ run["claims"],
+ serde_json::json!([project.to_string_lossy()]),
+ "{run}"
+ );
+ assert_eq!(run["unscoped"], serde_json::Value::Null, "{run}");
+ assert_eq!(run["scoped"], "OTHER-PROJECT-HANDOFF", "{run}");
+ }
+ }
+
#[test]
fn pi_extension_denylist_bakes_inert_gate() {
let extension = build_pi_extension("http://127.0.0.1:49374", Some("tok"), None, "denylist");
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 0d876fac..68898e66 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -47,6 +47,7 @@ means the boundary is not built yet.
| 4f | Finalize-on-exit closes only a session the run provably owns (invariant #16) | `ai-memory-cli/src/commands/run.rs` `finalize_hookless_session` runs only for `harness.lacks_session_end_hook()` harnesses (Command Code, Kiro v2/v3, Antigravity); `own_native_session` returns a session only when it is named, chosen before the spawn, or linked under this run's own id in this checkout — a merely *discovered* native session (possibly a concurrent launch's) is never finalized | `run.rs` `a_session_linked_during_the_run_wins_over_discovery` — `own_native_session` returns `None` for the unlinked and other-checkout (`nested`) cases, so a foreign/concurrent session is refused; the named/linked control is finalized (#944) | STRONG |
| 4g | `memory_handoff_accept` `status` never points a caller at another session's baton | `ai-memory-store/src/reader.rs` `handoff_claimed_by_live_session` — the caller-supplied session id (header or native `_meta`, routing-only per row 6b) selects which claim to check, but the answer is bounded by the resolved `(workspace_id, project_id)`, the authenticated `handoff_owner_sql` owner filter, `state='accepted'`, and a still-open receiving session; `ai-memory-mcp/src/server.rs` `unclaimed_handoff` reports `consumed_by_hook` only on that match (and, for a requested `handoff_id`, only when it is the matched row), `none_pending` otherwise | `handoff_ownership.rs` `a_session_start_claim_is_confirmed_only_to_its_own_live_session` (forged session id under another operator, unattributed reader, foreign project, sibling session and ended session all empty; owner and root controls see the claim); `ai-memory-mcp` `tests/suite/handoff_identity.rs` `consumed_by_hook_is_reported_only_to_the_session_that_claimed_it` (over the production transport: a colleague forwarding the session id, the owner from another session, and a request with no session id all get `none_pending`; the claiming session gets `consumed_by_hook`) | STRONG |
| 4h | Offer-mode SessionStart never consumes or injects handoff-controlled text | `ai-memory-hooks/src/router.rs` `fetch_and_accept_handoff_at` branches on the startup configuration before admission/claim and `render_handoff_notice` emits only typed metadata (`HandoffId`, `AgentKind`, computed age); the normal writer CAS remains the only later claim path | `router.rs` `handoff_notice_is_metadata_only_and_never_carries_the_summary` plants hostile summary/questions/steps/files; `offer_mode_leaves_the_baton_open_and_notice_omits_the_summary` exercises the production hook route, asserts the row remains open, then proves the legitimate exact-id writer claim still consumes it (#1030) | STRONG |
+| 4i | A hook never claims a handoff for an event that names no project directory | `GET /handoff` claims the newest open handoff in whatever project the server resolves; a request without `cwd` lets the server use its default or the caller's last active project, so the claim could consume another repository's handoff. Every front door gates the claim on a resolved directory and leaves the handoff open for `memory_handoff_accept`: the native hook in `ai-memory-cli/src/commands/hook.rs` `run_with_payload` (`handoff_scoped`, a resolved `policy_cwd`, gates SessionStart, Kimi's UserPromptSubmit and Grok's PostToolUse, with a stderr warning at SessionStart); the shell bundle's `hooks/_lib.sh` `ai_memory_get_handoff` (refuses a URL without the `&cwd=` that `ai_memory_marker_qs` adds for every named directory); the PowerShell `hooks/lib/ai-memory-hook.ps1` `Invoke-AiMemoryHook` (`$FetchHandoff -and $Cwd`); and the generated OpenCode, OpenCode 2, OMP and Pi integrations' `fetchHandoff` (`if (!cwd) return undefined;`). OpenClaw's `fetchHandoff` already required a directory. The only fallbacks are Devin's documented ones (`DEVIN_PROJECT_DIR`, then the hook's own directory), in `resolve_hook_cwd_with`, `ai_memory_resolve_cwd` and `Resolve-AiMemoryCwd` | `hook.rs` `a_handoff_is_never_claimed_without_a_project_directory` (Claude Code and Codex SessionStart, Kimi UserPromptSubmit and Grok PostToolUse with no `cwd` send no `GET /handoff`; control: the same events with a `cwd` claim once, naming it); `tests/hooks/test_lib.sh` "a handoff is never claimed without a project directory" (every shell script that fetches a handoff, discovered from the bundle and run from an unrelated directory: no payload directory, no claim; control: a directory claims and names it; Devin claims for its own directory; the PowerShell helper runs the same pair where a PowerShell exists, else a static pin); `install_hooks.rs` `generated_integrations_never_fetch_a_handoff_without_a_directory` and, running the generated OMP extension in Node, `slow_generated_handoff_runtime::omp_extension_never_claims_a_handoff_without_a_directory` (an empty `ctx.cwd` sends no claim; control: a directory claims). Each fails with its guard removed | STRONG for the native hook, the shell bundle and the generated integrations; the PowerShell runtime case runs only where a PowerShell is installed |
| 5a | Pages shared: `author_id` is never a read filter (invariant #16) | `ai-memory-store/src/reader.rs` `search_pages`/`page_body_by_ids` — `author_id` is an attribution JOIN only, never a WHERE term; `observation_stream_votes` lets every session vote whatever its owner (the owner filter only withholds the observation excerpt and ids, never the vote or the page) | `multi_session.rs` — a page with a **non-null** `author_id` (operator A) is readable by operator B in the same project; `multi_session.rs` `another_operators_observations_lift_their_session_page_in_a_shared_project` (operator B's owned session, authored page and observations lift that page for operator A's query); `ai-memory-mcp` `server.rs` `observation_stream_evidence_stays_inside_a_restricted_project` (a second operator with only a read grant gets the session page lifted by the first operator's observation); `multi_session.rs` `observation_excerpts_follow_the_session_owner_while_the_vote_stays_shared` (B still gets A's session page ranked by A's observation, with the page's own snippet) | STRONG |
| 5b | Page supersession (loser stays reachable) | `ai-memory-store/src/ops.rs` `upsert_page_in_tx` — demote `is_latest=0` (never delete) + `supersedes` chain; read side: `reader.rs` `page_versions` lists every row at the path, with no `is_latest` filter, for `/web/w/…/h/*path` and `/api/v1/…/history/*path`. It does apply TTL expiry (`reader.rs` `history_visible`): a version whose own `expires_at` passed is neither listed nor readable by id, a path whose live version expired shows no history at all (the forget sweep hard-deletes every row there), and a `supersedes` link to a hidden version reads as `null`. Expiry is the only thing that hides a superseded version; a concurrent write never does | `multi_session.rs` `concurrent_writes_to_one_path_supersede_rather_than_destroy`; `retrieval_superseded.rs`; `multi_session.rs` `page_history_keeps_the_overwritten_version_and_stays_in_scope`; `ai-memory-web` `history_replay.rs` `history_keeps_both_sides_of_a_concurrent_divergent_write` (two attributed writers on one base: all three versions and both authors listed, one `is_latest`, the two writers' versions diff by id) and `history_lists_k_plus_one_versions_newest_first_and_diffs_the_latest`; bite: an `is_latest = 1` filter in `page_versions` fails both; `history_hides_expired_versions_and_expired_pages` (an expired superseded version and every version of a page whose live version expired answer 404 by path and by id on HTML and JSON, and the live successor's `supersedes` is `null`; control: a TTL in the future is listed and diffable; bites with the per-row predicate removed, with the live-version clause disabled, and with the `supersedes` hiding removed) | STRONG |
| 5c | Watcher reindex and Wiki writes share per-page serialization (invariant #16) | `ai-memory-wiki/src/wiki.rs` `reindex_page` takes `mutation_lock.read` before `reindex_page_locked` takes `lock_page`, covering disk read through the single-writer upsert; callers already holding the exclusive global guard do not reacquire it. `write_page` uses the same page mutex and `apply_batch` retains sorted, deduplicated locks; embedding runs after both guards are released | `wiki.rs` `reindex_page_lock_waits_before_reading_and_allows_another_path` (transient snapshot refused while locked, another path progresses, release indexes the committed bytes without rewriting disk), `reindex_page_lock_serializes_write_through_the_upsert` and `reindex_page_lock_and_reversed_duplicate_batches_do_not_deadlock` (real concurrent operations, final disk/SQL winner and supersession ancestry preserved); all three fail with the reindex page guard removed. `reindex_page_lock_releases_both_guards_before_embedding` checks both body and abstract embedding; `decay_cleanup_reindex_does_not_embed_under_the_exclusive_lock` covers the exclusive caller | STRONG for a shared Wiki handle and its clones. External editors and independently constructed Wiki handles do not participate in these locks |
diff --git a/hooks/_lib.sh b/hooks/_lib.sh
index 06afd683..137ed9a7 100644
--- a/hooks/_lib.sh
+++ b/hooks/_lib.sh
@@ -961,9 +961,18 @@ ai_memory_post_hook() {
# Every request in this bundle sends `X-AI-Memory-Client`: an unauthenticated
# server reached through a non-loopback host name refuses a handoff fetch
# without it, because a web page cannot add that header to a request it makes.
+#
+# The GET claims the newest open handoff in whatever project the server
+# resolves. `ai_memory_marker_qs` adds `&cwd=` whenever the payload named a
+# directory, so a URL without it names no project: the server would fall back
+# to its default or the caller's last active project, and the claim could
+# consume another repository's handoff. Fetch nothing then; the handoff stays
+# open for memory_handoff_accept (parity with the native hook).
ai_memory_get_handoff() {
case "$1" in
*"$AI_MEMORY_SERVER_ROUTED_QS"*|*'ai_memory_invalid_home_routes=1'*) return 0 ;;
+ *'&cwd='*) ;;
+ *) return 0 ;;
esac
_amhdr=$(ai_memory_auth_header_file)
if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1
index 3f62463e..cfdb584f 100644
--- a/hooks/lib/ai-memory-hook.ps1
+++ b/hooks/lib/ai-memory-hook.ps1
@@ -1079,7 +1079,13 @@ function Invoke-AiMemoryHook {
Clear-AiMemorySessionId -Agent $Agent
}
- if ($FetchHandoff) {
+ # `GET /handoff` claims the newest open baton in whatever project the
+ # server resolves. A payload that names no directory would send no `cwd`,
+ # the server would fall back to its default or the caller's last active
+ # project, and the claim could consume another repository's handoff.
+ # Without a directory the handoff stays open for memory_handoff_accept
+ # (parity with the native hook and `ai_memory_get_handoff`).
+ if ($FetchHandoff -and $Cwd) {
$NativeSessionQS = ""
$NativeSessionId = $null
try {
@@ -1211,7 +1217,7 @@ function Invoke-AiMemoryHook {
if ($ProfileFile) {
Set-AiMemoryBriefed -Path $ProfileFile
}
- } elseif ($AntigravityPreInvocationOutput) {
+ } elseif ($AntigravityPreInvocationOutput -or $GrokPostTool -or $CopilotCliSessionStartOutput) {
[Console]::Out.Write("{}")
}
}
diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.sh
index ebd4db9b..0ca3689e 100755
--- a/tests/hooks/test_lib.sh
+++ b/tests/hooks/test_lib.sh
@@ -786,7 +786,7 @@ assert_eq "owner: post_hook sends nothing" "0" "$(owner_requests)"
assert_eq "owner: post_hook spools nothing and drains nothing" "$BACKLOG" "$(owner_spooled)"
# 2. Delivery is untouched: the handoff GET still runs and still returns.
-HANDOFF=$(set +e; ai_memory_get_handoff "http://127.0.0.1:49374/handoff?agent=cursor")
+HANDOFF=$(set +e; ai_memory_get_handoff "http://127.0.0.1:49374/handoff?agent=cursor&cwd=%2Fwork")
assert_eq "owner: handoff GET still delivered" "HANDOFF BODY" "$HANDOFF"
assert_eq "owner: the GET is the only request" "1" "$(owner_requests)"
assert_eq "owner: still no POST" "0" "$(owner_posts)"
@@ -1066,6 +1066,101 @@ done
assert_eq "session-start bundles that fetch the handoff were found" "yes" \
"$([ "$BRIEF_BUNDLES" -ge 9 ] && printf 'yes' || printf 'no (%s)' "$BRIEF_BUNDLES")"
+# --- a handoff is never claimed without a project directory -------------
+# `GET /handoff` claims the newest open handoff in whatever project the server
+# resolves. A payload that names no directory sent no `cwd`, so the server fell
+# back to its default or last active project and the hook consumed another
+# repository's handoff. Every script that fetches a handoff (session start,
+# Kimi's user prompt, Grok's first tool call) is discovered and run twice
+# from an unrelated directory: with no directory it must not claim; the
+# control, with a directory, claims once and names it. Devin is the one
+# bundle with a fallback (DEVIN_PROJECT_DIR, then the hook's own directory),
+# so it still claims, naming that directory.
+HOOKS_ABS=$(cd "$(dirname "$0")/../../hooks" && pwd)
+SCOPE_REPO="$TMP/scope-repo"
+SCOPE_ELSEWHERE="$TMP/scope-elsewhere"
+mkdir -p "$SCOPE_REPO" "$SCOPE_ELSEWHERE"
+SCOPE_RUN=0
+# Runs script "$1" with a payload that names directory "$2" (none when empty)
+# and prints the handoff GETs it sent. It runs in a command substitution, so
+# the caller advances SCOPE_RUN to give every run its own session and state.
+scope_handoff_gets() {
+ rm -f "$FAKE_CURL_LOG"
+ if [ -n "$2" ]; then
+ dir_fields=$(printf '"cwd":"%s","workspacePaths":["%s"],' "$2" "$2")
+ else
+ dir_fields=""
+ fi
+ printf '{%s"invocationNum":0,"session_id":"scope-%s","conversationId":"scope-%s","prompt":"continue","tool_name":"read_file","tool_input":{}}' \
+ "$dir_fields" "$SCOPE_RUN" "$SCOPE_RUN" \
+ | (cd "$SCOPE_ELSEWHERE" && unset DEVIN_PROJECT_DIR \
+ && PATH="$FAKE_CURL_BIN:$PATH" AI_MEMORY_CURL_LOG="$FAKE_CURL_LOG" \
+ AI_MEMORY_DATA_DIR="$TMP/scope-data-$SCOPE_RUN" AI_MEMORY_HOOK_URL='http://memory.test' \
+ sh "$1") >/dev/null 2>&1 || true
+ grep '/handoff?' "$FAKE_CURL_LOG" 2>/dev/null || true
+}
+SCOPE_SCRIPTS=0
+for script in "$HOOKS_ABS"/*/*.sh; do
+ grep -q 'ai_memory_get_handoff "' "$script" || continue
+ name="$(basename "$(dirname "$script")")/$(basename "$script")"
+ SCOPE_SCRIPTS=$((SCOPE_SCRIPTS + 1))
+ SCOPE_RUN=$((SCOPE_RUN + 1))
+ GETS=$(scope_handoff_gets "$script" "")
+ case "$name" in
+ devin/*)
+ case "$GETS" in
+ *"cwd=$(ai_memory_url_encode "$SCOPE_ELSEWHERE")"*)
+ PASS=$((PASS + 1)); printf ' ok %s\n' "$name: no payload directory claims for the hook's own directory" ;;
+ *) FAIL=$((FAIL + 1)); printf ' FAIL %s: no payload directory claims for the hook'"'"'s own directory\n got =%s\n' "$name" "$GETS" ;;
+ esac
+ ;;
+ *)
+ assert_eq "$name: no project directory claims no handoff" "" "$GETS"
+ ;;
+ esac
+ SCOPE_RUN=$((SCOPE_RUN + 1))
+ GETS=$(scope_handoff_gets "$script" "$SCOPE_REPO")
+ case "$GETS" in
+ *"cwd=$(ai_memory_url_encode "$SCOPE_REPO")"*)
+ PASS=$((PASS + 1)); printf ' ok %s\n' "$name: a project directory claims, naming it" ;;
+ *) FAIL=$((FAIL + 1)); printf ' FAIL %s: a project directory claims, naming it\n got =%s\n' "$name" "$GETS" ;;
+ esac
+done
+assert_eq "scripts that fetch the handoff were found" "yes" \
+ "$([ "$SCOPE_SCRIPTS" -ge 12 ] && printf 'yes' || printf 'no (%s)' "$SCOPE_SCRIPTS")"
+assert_eq "get_handoff refuses a URL without cwd" "" \
+ "$(PATH="$FAKE_CURL_BIN:$PATH" AI_MEMORY_CURL_LOG="$FAKE_CURL_LOG" \
+ ai_memory_get_handoff 'http://memory.test/handoff?agent=cursor&session_id=s')"
+
+# PowerShell: the same rule in Invoke-AiMemoryHook. Run it with
+# Invoke-WebRequest shadowed where a PowerShell exists; otherwise pin the guard.
+PS_SCOPE_STATIC=$(grep -Fq 'if ($FetchHandoff -and $Cwd) {' hooks/lib/ai-memory-hook.ps1 \
+ && printf 'ok' || printf 'missing')
+assert_eq "powershell handoff fetch requires a directory (static)" "ok" "$PS_SCOPE_STATIC"
+PSH=""
+if command -v pwsh >/dev/null 2>&1; then
+ PSH=$(command -v pwsh)
+elif command -v powershell >/dev/null 2>&1; then
+ PSH=$(command -v powershell)
+fi
+if [ -n "$PSH" ]; then
+ PS_LIB=$(host_path "$PWD/hooks/lib/ai-memory-hook.ps1")
+ PS_REPO=$(host_path "$SCOPE_REPO")
+ ps_scope_gets() {
+ rm -f "$TMP/ps-scope.log"
+ printf '%s' "$1" | (cd "$SCOPE_ELSEWHERE" && HOME="$TMP" AI_MEMORY_DATA_DIR="$TMP/ps-scope-data-$2" \
+ AI_MEMORY_TEST_LOG="$(host_path "$TMP/ps-scope.log")" "$PSH" -NoProfile -ExecutionPolicy Bypass -Command \
+ ". '$PS_LIB'; function Invoke-WebRequest { param([switch] \$UseBasicParsing, [int] \$TimeoutSec, [string] \$Method = 'Get', [string] \$Uri, \$Headers, [string] \$ContentType, \$Body) Add-Content -LiteralPath \$env:AI_MEMORY_TEST_LOG -Value ('{0} {1}' -f \$Method.ToUpperInvariant(), \$Uri); if (\$Method -eq 'Post') { return \$null }; return [pscustomobject]@{ Content = 'HANDOFF' } }; Invoke-AiMemoryHook -Event 'session-start' -Agent 'claude-code' -FetchHandoff") >/dev/null 2>&1 || true
+ grep '/handoff?' "$TMP/ps-scope.log" 2>/dev/null || true
+ }
+ assert_eq "powershell: no project directory claims no handoff" "" \
+ "$(ps_scope_gets '{"session_id":"ps-scope-1"}' 1)"
+ case "$(ps_scope_gets "{\"session_id\":\"ps-scope-2\",\"cwd\":\"$(printf '%s' "$PS_REPO" | sed 's/\\/\\\\/g')\"}" 2)" in
+ *'/handoff?'*cwd=*) PASS=$((PASS + 1)); printf ' ok %s\n' "powershell: a project directory claims" ;;
+ *) FAIL=$((FAIL + 1)); printf ' FAIL %s\n' "powershell: a project directory claims" ;;
+ esac
+fi
+
# The PowerShell bundle builds every session-start handoff GET in one place.
PS_BRIEF_STATIC=$(grep -Fq 'if ($Event -eq "session-start" -and -not $BriefingOncePerSession) {' hooks/lib/ai-memory-hook.ps1 \
&& awk '/if \(\$Event -eq "session-start" -and -not \$BriefingOncePerSession\)/ {f=1; next}
@@ -1106,7 +1201,7 @@ MARKER_LOG="$AI_MEMORY_DATA_DIR/marker.log"
marker_round() {
# The hooks call it under `|| true`; without that, `set -e` stops at the
# missing auth-header file lookup inside it.
- ai_memory_get_handoff "http://127.0.0.1:49374/handoff?agent=cursor" >/dev/null 2>&1 || true
+ ai_memory_get_handoff "http://127.0.0.1:49374/handoff?agent=cursor&cwd=%2Fwork" >/dev/null 2>&1 || true
printf '%s' '{"e":"marker"}' \
| ai_memory_post_hook "http://127.0.0.1:49374/hook?event=stop&agent=cursor" >/dev/null 2>&1
}