Skip to content

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

Rust

feat(hooks): add [handoff] deliver_on_session_start opt-out

Natan Pimentelb404c84694f4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fb9e5cc3..69d347d8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,13 @@ version in [`docs/changelog/`](docs/changelog/):
### Added
+- Added `[handoff] deliver_on_session_start = false` to `.ai-memory.toml`. A
+ project that sets it no longer gets its handoff, or the continuity notice, at
+ session start; the handoff is still created when the session ends and stays
+ open for `memory_handoff_accept`. The native hook, the shell and PowerShell
+ scripts and the generated TypeScript integrations send `handoff=0` only when
+ the value is explicitly falsy (#1621).
+
- Added first-party Qoder CLI/IDE lifecycle and MCP support. Both installers
merge into `~/.qoder/settings.json`: `install-mcp --client qoder` writes a
sessionless stdio bridge, while `install-hooks --agent qoder` registers the
diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rs
index 9f9f4980..f06938c3 100644
--- a/crates/ai-memory-cli/src/commands/hook_capture.rs
+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs
@@ -639,6 +639,7 @@ fn marker_query_suffix_impl_from_selection(
let (mut drop_subagent, mut default_global) = (None, None);
let (mut briefing, mut briefing_budget) = (None, None);
let (mut profile_contribute, mut profile_consume) = (None, None);
+ let mut handoff_off = false;
// The nearest marker that declares more than `[capture]` (#668): a
// nested capture-only marker (e.g. one that only sets `ignore_paths`)
// must not shadow an outer marker's workspace/project/briefing/etc.
@@ -658,6 +659,12 @@ fn marker_query_suffix_impl_from_selection(
// marker sends nothing, so the server keeps what it stored.
profile_contribute = Some(profile_flag_value(parse_toml_flag(&marker, "contribute")));
profile_consume = Some(profile_flag_value(parse_toml_flag(&marker, "consume")));
+ // `[handoff] deliver_on_session_start = false` keeps this project's
+ // handoffs out of its session starts. Sent only when explicitly
+ // falsy, so an absent key leaves the request byte-identical.
+ handoff_off = parse_toml_flag(&marker, "deliver_on_session_start")
+ .as_deref()
+ .is_some_and(crate::marker::is_falsy);
}
if let Some(val) = scope.workspace {
qs.push_str(&format!("&workspace={}", url_encode(&val)));
@@ -705,6 +712,9 @@ fn marker_query_suffix_impl_from_selection(
if let Some(val) = profile_consume {
qs.push_str(&format!("&profile_consume={val}"));
}
+ if handoff_off {
+ qs.push_str("&handoff=0");
+ }
// Per-repo session-start brief opt-in: forwarded on every request for
// simplicity (the capture path ignores it); only the `/handoff` GET at
// session start acts on it. Truthiness and the char-budget clamp are
@@ -1831,6 +1841,47 @@ drop_subagent_captures = "true"
assert!(!none.contains("profile_"), "{none}");
}
+ /// `[handoff] deliver_on_session_start` is forwarded as `&handoff=0` only
+ /// when explicitly falsy; every other shape leaves the request unchanged,
+ /// and a `[handoff]`-only marker is a settings boundary.
+ #[test]
+ fn marker_query_suffix_forwards_the_handoff_opt_out_only_when_falsy() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let inner = tmp.path().join("inner");
+ std::fs::create_dir(&inner).unwrap();
+ std::fs::write(
+ tmp.path().join(".ai-memory.toml"),
+ "workspace = \"outer\"\n",
+ )
+ .unwrap();
+ for off in ["false", "\"no\"", "0", "\"OFF\""] {
+ std::fs::write(
+ inner.join(".ai-memory.toml"),
+ format!("[handoff]\ndeliver_on_session_start = {off}\n"),
+ )
+ .unwrap();
+ let qs = marker_query_suffix(inner.to_str().unwrap(), None);
+ assert!(qs.contains("&handoff=0"), "{off}: {qs}");
+ assert!(
+ !qs.contains("workspace=outer"),
+ "a [handoff] marker is a boundary: {qs}"
+ );
+ }
+ for on in ["true", "\"yes\"", "banana"] {
+ std::fs::write(
+ inner.join(".ai-memory.toml"),
+ format!("[handoff]\ndeliver_on_session_start = {on}\n"),
+ )
+ .unwrap();
+ let qs = marker_query_suffix(inner.to_str().unwrap(), None);
+ assert!(!qs.contains("handoff"), "{on}: {qs}");
+ }
+ // The sibling project keeps delivering: the opt-out is read from the
+ // nearest settings marker only.
+ let outer = marker_query_suffix(tmp.path().to_str().unwrap(), None);
+ assert!(!outer.contains("handoff"), "{outer}");
+ }
+
/// A marker WITHOUT `drop_subagent_captures` does not forward the flag, so
/// the server keeps that project's subagent captures (opt-in only).
#[test]
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 5d98f16d..9f8223b6 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -4406,7 +4406,7 @@ pub(crate) const TS_FIND_SETTINGS_MARKER: &str = r#"function declaresSettings(te
}
if (/^\s*aliases\s*=/m.test(text)) return true;
if (/^\s*server\s*=/m.test(text)) return true;
- for (const key of ["default_global", "inject_on_session_start", "max_chars", "contribute", "consume"]) {
+ for (const key of ["default_global", "inject_on_session_start", "max_chars", "contribute", "consume", "deliver_on_session_start"]) {
if (tomlFlag(text, key) !== undefined) return true;
}
return false;
@@ -4495,6 +4495,7 @@ pub(crate) fn ts_apply_marker_params(
let briefingBudget: string | undefined;
let profileContribute: string | undefined;
let profileConsume: string | undefined;
+ let handoffOff = false;
let explicitIdentity: string | undefined;
let identityStyle: string | undefined;
let aliases: string | undefined;
@@ -4514,6 +4515,7 @@ pub(crate) fn ts_apply_marker_params(
briefingBudget = tomlFlag(body, "max_chars");
profileContribute = profileFlag(tomlFlag(body, "contribute"));
profileConsume = profileFlag(tomlFlag(body, "consume"));
+ handoffOff = profileFlag(tomlFlag(body, "deliver_on_session_start")) === "0";
if (route) {
routed = true;
workspace = route.workspace;
@@ -4546,6 +4548,7 @@ pub(crate) fn ts_apply_marker_params(
briefingBudget = tomlFlag(body, "max_chars");
profileContribute = profileFlag(tomlFlag(body, "contribute"));
profileConsume = profileFlag(tomlFlag(body, "consume"));
+ handoffOff = profileFlag(tomlFlag(body, "deliver_on_session_start")) === "0";
explicitIdentity = tomlKey(body, "identity");
identityStyle = tomlKey(body, "identity_style");
aliases = markerAliases(body);
@@ -4577,6 +4580,7 @@ pub(crate) fn ts_apply_marker_params(
if (briefingBudget) url.searchParams.set("briefing_budget", briefingBudget);
if (profileContribute) url.searchParams.set("profile_contribute", profileContribute);
if (profileConsume) url.searchParams.set("profile_consume", profileConsume);
+ if (handoffOff) url.searchParams.set("handoff", "0");
return true;
}"#
.replace("__DEFAULT_LINE__", apply_default)
@@ -13044,6 +13048,8 @@ model = "gpt-5"
assert!(plugin.contains("tomlFlag(body, \"contribute\")"));
assert!(plugin.contains("url.searchParams.set(\"profile_contribute\", profileContribute)"));
assert!(plugin.contains("url.searchParams.set(\"profile_consume\", profileConsume)"));
+ assert!(plugin.contains("tomlFlag(body, \"deliver_on_session_start\")"));
+ assert!(plugin.contains("url.searchParams.set(\"handoff\", \"0\")"));
// #668: applyMarkerParams resolves scope/settings via the
// settings-walk, not the nearest-marker findMarker, so a nested
// capture-only marker does not shadow an outer marker's scope.
@@ -13055,7 +13061,7 @@ model = "gpt-5"
));
assert!(plugin.contains("if (/^\\s*aliases\\s*=/m.test(text)) return true;"));
assert!(plugin.contains(
- "for (const key of [\"default_global\", \"inject_on_session_start\", \"max_chars\", \"contribute\", \"consume\"])"
+ "for (const key of [\"default_global\", \"inject_on_session_start\", \"max_chars\", \"contribute\", \"consume\", \"deliver_on_session_start\"])"
));
assert!(plugin.contains("if (declaresSettings(text)) return marker;"));
assert!(plugin.contains(
diff --git a/crates/ai-memory-cli/src/marker.rs b/crates/ai-memory-cli/src/marker.rs
index 94c25e94..cacbd09e 100644
--- a/crates/ai-memory-cli/src/marker.rs
+++ b/crates/ai-memory-cli/src/marker.rs
@@ -1227,12 +1227,13 @@ fn declares_more_than_capture(text: &str) -> bool {
"identity",
"identity_style",
];
- const FLAG_KEYS: [&str; 5] = [
+ const FLAG_KEYS: [&str; 6] = [
"default_global",
"inject_on_session_start",
"max_chars",
"contribute",
"consume",
+ "deliver_on_session_start",
];
QUOTED_KEYS
.iter()
@@ -2355,6 +2356,7 @@ project = "infra" # this is fine
"[recall]\ndefault_global = true\n",
"[briefing]\ninject_on_session_start = true\n",
"[briefing]\nmax_chars = 4000\n",
+ "[handoff]\ndeliver_on_session_start = false\n",
] {
assert!(
declares_more_than_capture(text),
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index f3ef5cde..238fb4c0 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -1616,6 +1616,12 @@ pub struct HandoffQuery {
/// Set falsy by a client that re-fetches on every prompt (Kimi Code) once
/// the session already received the digest, so it is delivered once.
pub profile_digest: Option<String>,
+ /// The marker's `[handoff] deliver_on_session_start`, sent as `0` only
+ /// when the project opted out. An explicit falsy value keeps this
+ /// project's handoff and continuity notice out of its session starts: the
+ /// handoff stays open and unclaimed, and the rest of the on-start context
+ /// is delivered as usual. Absent or anything else delivers as before.
+ pub handoff: Option<String>,
}
impl HandoffQuery {
@@ -1768,16 +1774,24 @@ async fn fetch_and_accept_handoff_at(
let busy_since = now
.saturating_sub(LIVE_BATON_QUIET_PERIOD)
.unwrap_or(jiff::Timestamp::MIN);
- let handoff = state
- .reader
- .startup_handoff(
- ws,
- proj,
- query.cwd.clone(),
- owner_filter.clone(),
- busy_since,
- )
- .await?;
+ // `[handoff] deliver_on_session_start = false` never reads the baton, so
+ // there is nothing to claim, announce or render; it stays open for a
+ // project that has not opted out (or for `memory_handoff_accept`).
+ let deliver_handoff = !crate::payload::query_flag_falsy(query.handoff.as_deref());
+ let handoff = if deliver_handoff {
+ state
+ .reader
+ .startup_handoff(
+ ws,
+ proj,
+ query.cwd.clone(),
+ owner_filter.clone(),
+ busy_since,
+ )
+ .await?
+ } else {
+ None
+ };
let handoff_md = handoff.as_ref().map(render_handoff_markdown);
// The brief is additive and non-destructive: unlike the handoff (a
// single-use slot claimed below), it is recomposed on every opted-in
@@ -1831,16 +1845,20 @@ async fn fetch_and_accept_handoff_at(
// the admission-chain round-trip: the handoff is never claimed, and
// `handoff_notice` (computed below from the still-open `pending` value,
// before it is consumed here) is what tells the agent it exists.
- let continuity_notice = render_continuity_notice(
- state,
- &query,
- ws,
- proj,
- owner_filter.clone(),
- handoff.as_ref().map(|pending| pending.lifecycle.created_at),
- now,
- )
- .await;
+ let continuity_notice = if deliver_handoff {
+ render_continuity_notice(
+ state,
+ &query,
+ ws,
+ proj,
+ owner_filter.clone(),
+ handoff.as_ref().map(|pending| pending.lifecycle.created_at),
+ now,
+ )
+ .await
+ } else {
+ None
+ };
let handoff_notice = if state.claim_handoff_on_session_start {
None
} else {
@@ -5495,6 +5513,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
agent: Some("claude-code".into()),
cwd: Some(cwd.to_string()),
workspace: Some("default".into()),
@@ -6304,6 +6323,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
identity: Some(identity.to_owned()),
identity_src: Some(source.to_owned()),
aliases: None,
@@ -14814,6 +14834,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
workspace: Some("checkpoint-workspace".into()),
project: Some(project.into()),
agent: Some("codex".into()),
@@ -14892,6 +14913,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
agent: Some("opencode2".into()),
session_id: Some(SessionId::new().to_string()),
..Default::default()
@@ -15125,6 +15147,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
agent: Some(agent.into()),
session_id: Some(session_id),
..Default::default()
@@ -15315,6 +15338,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
agent: Some("claude-code".into()),
session_id: Some(SessionId::new().to_string()),
..Default::default()
@@ -16048,6 +16072,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
agent: Some("claude-code".into()),
cwd: Some(tmp.path().to_string_lossy().into_owned()),
workspace: Some("default".into()),
@@ -16668,6 +16693,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
agent: Some("claude-code".into()),
cwd: Some(cwd.clone()),
workspace: Some("default".into()),
@@ -16757,6 +16783,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
agent: Some("claude-code".into()),
cwd: Some(cwd.clone()),
workspace: Some("default".into()),
@@ -16865,6 +16892,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
agent: Some("claude-code".into()),
cwd: Some(cwd),
workspace: Some("default".into()),
@@ -17043,6 +17071,15 @@ pub(crate) mod tests {
}
async fn session_start_handoff(state: &Arc<HookState>, cwd: &str) -> (String, Duration) {
+ session_start_handoff_for(state, cwd, "scratch", None).await
+ }
+
+ async fn session_start_handoff_for(
+ state: &Arc<HookState>,
+ cwd: &str,
+ project: &str,
+ handoff: Option<&str>,
+ ) -> (String, Duration) {
let started = std::time::Instant::now();
let (status, body) = read_handoff_response(
handle_handoff(
@@ -17051,10 +17088,11 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: handoff.map(str::to_string),
agent: Some("claude-code".into()),
cwd: Some(cwd.to_string()),
workspace: Some("default".into()),
- project: Some("scratch".into()),
+ project: Some(project.to_string()),
project_src: None,
project_strategy: None,
briefing: None,
@@ -17078,6 +17116,91 @@ pub(crate) mod tests {
(body, started.elapsed())
}
+ /// `[handoff] deliver_on_session_start = false` (sent as `handoff=0`)
+ /// keeps the baton out of that project's session start without claiming
+ /// it; the same project asking again without the opt-out still gets it.
+ #[tokio::test]
+ async fn handoff_opt_out_leaves_the_baton_open_and_undelivered() {
+ let tmp = TempDir::new().unwrap();
+ let state = state_with_pending_handoff(
+ &tmp,
+ ai_memory_wiki::AdmissionChain::new(Vec::new()).unwrap(),
+ )
+ .await;
+ let cwd = tmp.path().to_string_lossy().into_owned();
+
+ for falsy in ["0", "false", "no", "OFF"] {
+ let (body, _) = session_start_handoff_for(&state, &cwd, "scratch", Some(falsy)).await;
+ assert!(
+ !body.contains("HANDOFF-MARKER") && !body.to_lowercase().contains("handoff"),
+ "{falsy}: an opted-out project must receive no handoff or notice: {body}",
+ );
+ assert!(
+ open_handoff_exists(&state).await,
+ "{falsy}: an opted-out start must not claim the baton",
+ );
+ }
+
+ // Control: anything but an explicit falsy value delivers and claims.
+ let (body, _) = session_start_handoff_for(&state, &cwd, "scratch", Some("1")).await;
+ assert!(body.contains("HANDOFF-MARKER"), "{body}");
+ assert!(!open_handoff_exists(&state).await);
+ }
+
+ /// Adversarial: one project's opt-out must not hide or consume another
+ /// project's baton, and the other project's delivery must not touch the
+ /// opted-out project's.
+ #[tokio::test]
+ async fn handoff_opt_out_is_scoped_to_the_requesting_project() {
+ let tmp = TempDir::new().unwrap();
+ let state = state_with_pending_handoff(
+ &tmp,
+ ai_memory_wiki::AdmissionChain::new(Vec::new()).unwrap(),
+ )
+ .await;
+ let cwd = tmp.path().to_string_lossy().into_owned();
+ let other = state
+ .writer
+ .get_or_create_project(state.workspace_id, "project-b".to_string(), None)
+ .await
+ .unwrap();
+ state
+ .writer
+ .insert_handoff(NewHandoff {
+ workspace_id: state.workspace_id,
+ project_id: other,
+ from_session_id: None,
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: None,
+ summary: "HANDOFF-B".to_string(),
+ open_questions: Vec::new(),
+ next_steps: Vec::new(),
+ files_touched: Vec::new(),
+ owner_user: None,
+ })
+ .await
+ .unwrap();
+
+ // scratch opts out; project-b does not.
+ let (scratch, _) = session_start_handoff_for(&state, &cwd, "scratch", Some("0")).await;
+ assert!(!scratch.contains("HANDOFF-MARKER"), "{scratch}");
+ let (b, _) = session_start_handoff_for(&state, &cwd, "project-b", None).await;
+ assert!(b.contains("HANDOFF-B"), "{b}");
+ assert!(
+ !b.contains("HANDOFF-MARKER"),
+ "project-b must never see scratch's baton: {b}"
+ );
+ assert!(
+ open_handoff_exists(&state).await,
+ "project-b's delivery must not consume the opted-out project's baton",
+ );
+
+ // project-b opting out afterwards changes nothing for scratch.
+ let (scratch, _) = session_start_handoff_for(&state, &cwd, "scratch", None).await;
+ assert!(scratch.contains("HANDOFF-MARKER"), "{scratch}");
+ }
+
/// `GET /handoff` is called synchronously by the session-start hook. Under the default
/// `ignore` policy a webhook has nothing to decide — one ordinary observer
/// on a host that stalls must therefore neither hold the endpoint nor cost
@@ -18060,6 +18183,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
agent: Some("codex".into()),
cwd: Some(cwd.into()),
workspace: Some("acme".into()),
@@ -18143,6 +18267,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
agent: Some("codex".into()),
cwd: Some("/repo/api/src".into()),
workspace: Some("default".into()),
@@ -18218,6 +18343,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
agent: Some("codex".into()),
cwd: Some(cwd.clone()),
workspace: Some("default".into()),
@@ -18373,6 +18499,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
agent: Some("codex".into()),
cwd: Some(cwd),
workspace: Some("default".into()),
@@ -18495,6 +18622,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
agent: Some("claude-code".into()),
cwd: Some(cwd.into()),
workspace: None,
@@ -18579,6 +18707,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
agent: Some("claude-code".into()),
cwd: Some(cwd.into()),
workspace: None,
@@ -18647,6 +18776,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
agent: Some("claude-code".into()),
cwd: Some(cwd.into()),
workspace: None,
@@ -18811,6 +18941,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
agent: Some("kimi-code".into()),
cwd: Some("/repo".into()),
workspace: Some("default".into()),
@@ -19666,6 +19797,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
agent: Some("codex".into()),
cwd: Some(cwd.into()),
workspace: None,
@@ -22785,6 +22917,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
managed_run: Some(run.run_id.to_string()),
session_id: Some("private-vendor".into()),
cwd: Some(cwd.clone()),
@@ -22855,6 +22988,7 @@ pub(crate) mod tests {
profile_contribute: None,
profile_consume: None,
profile_digest: None,
+ handoff: None,
agent: Some(agent.into()),
cwd: Some(cwd.into()),
workspace: None,
diff --git a/docs/marker-file.md b/docs/marker-file.md
index 8656bafb..369a93b6 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -191,6 +191,15 @@ inject_on_session_start = "true"
# defaults to 4000.
max_chars = 4000
+# Optional. Stop delivering this project's handoff at session start. Only an
+# explicit false / "no" / "off" / "0" turns it off; the default is to deliver.
+# Handoffs are still created when a session ends, and stay open (an agent can
+# still take one with `memory_handoff_accept`), so only the automatic delivery
+# stops. The brief, the profile digest and everything else on start are
+# unchanged.
+[handoff]
+deliver_on_session_start = false
+
# Optional. The cross-project profile (docs/cross-project-profile.md): your
# usual choices from other projects, delivered at session start as defaults
# below this repository's rules file. Both keys default to on.
@@ -293,6 +302,14 @@ values are ignored and behave like the default `basename(cwd)` strategy.
falsy (`false` / `0` / `no` / `off`, quoted or bare). A marker that sets only
`[profile]` keys is a settings boundary, like one with `[briefing]` keys.
+`[handoff] deliver_on_session_start` is on unless the value is explicitly falsy
+(`false` / `0` / `no` / `off`, quoted or bare). Clients send `handoff=0` on the
+session-start fetch only when the marker turns it off, so the server reads
+nothing, claims nothing and adds no handoff or continuity notice for that
+project. A marker that sets only `[handoff]` is a settings boundary, like one
+with `[briefing]` or `[profile]` keys. Use it for projects whose automatic
+handoffs are mostly noise, such as a bot fleet driven by routines and webhooks.
+
`[recall] default_global` applies to an agent's unscoped `memory_query` and
`memory_recent` calls. A `memory_query` with `as_of` is not broadened: it
reads the current project as it stood at that instant, and an explicit
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index c7c99296..726c447c 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -58,6 +58,7 @@ means the boundary is not built yet.
| 4j | 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`, and CodeBuddy's documented `CODEBUDDY_PROJECT_DIR` in the native hook (never its process cwd) (#1299) | `hook.rs` `a_handoff_is_never_claimed_without_a_project_directory` (CodeBuddy, 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); `codebuddy_missing_cwd_uses_codebuddy_project_dir_only` and, end to end against a real server, `ai-memory-cli/tests/suite/external_capture.rs` `codebuddy_start_without_a_directory_leaves_the_default_projects_handoff` (a CodeBuddy SessionStart with no `cwd`, run from inside the project, leaves the server-default project's handoff open; controls: the payload's `cwd`, then `CODEBUDDY_PROJECT_DIR`, claim 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 |
| 4k | The idle-session auto-end (`[sessions] idle_end_after_hours`) never ends a session it does not own: idle-threshold + active-run exclusion at selection, guarded CAS stamp, conditional page write, owner attribution | `ai-memory-store/src/reader.rs` `idle_open_sessions` — ONE statement: the idle-threshold predicate (`ended_at IS NULL` + `COALESCE(MAX(observations.created_at), started_at) < cutoff`), `ORDER BY last_activity ASC` capped at the batch, and a correlated `pages` subquery bound to the session's own `workspace_id`/`project_id` and to the path rendered in SQL from the id blob (`lower(hex(id))` with 8-4-4-4-12 hyphens — byte-for-byte the Rust `format!("sessions/{session_id}.md")`, proven by the selection test with a page present and absent) capturing the latest `sessions/<id>.md` version as the tick's write precondition — a read path, never a write; `active_managed_run_native_session_ids` (only `state = 'active'` managed runs). `ai-memory-store/src/ops.rs` `idle_end_sessions` — per-candidate `UPDATE sessions … WHERE id AND workspace_id AND project_id AND ended_at IS NULL` that also re-verifies the session's observation count (EVERY row of the session — the digest's population, no per-row scope filter) and the latest page version; `ended_at` = the tick's clock (last activity kept in the audit detail), `ended_observation_count` counted at the stamp, one `idle_session_end` audit row in the same transaction, and the consolidation gate: the job is enqueued INSIDE the stamp's transaction (`session_consolidation::enqueue_in_tx`), so a failed enqueue rolls back the stamp, the audit row and the job, while the page the tick already wrote stays as an ordinary version; a lost stamp skips the enqueue and never aborts the batch. The lifecycle-only gate applies the same scope/open guard before any mutation, re-checks substantiveness atomically, reuses `end_lifecycle_only_session_in_tx` (releasing the accepted handoff), and writes its OWN `idle_session_end` audit row distinct from the `release_lifecycle_only_handoff` row. `ai-memory-hooks/src/idle_end.rs` `run_idle_end_tick` — excludes active-run sessions in Rust via `SessionId::from_native` BEFORE the batch bound (the serve loop over-fetches, so an excluded backlog cannot starve the batch), classifies via `session_has_substantive_observation`, builds the page and its count from one digest snapshot (`SessionDigest::load_with_count` — the count the CAS guard re-verifies), writes the page with `Wiki::write_page_if` under `PagePrecondition::Latest(seen)`/`Absent` (`Mismatch` skips the whole session), keeps an agent-written page (`session_page_written_by_agent`), and attributes via `router.rs` `stored_session_identity` (the hook path's own fail-closed parse). The tick creates no additional handoff: the consolidation gate and the lifecycle-only release gate are its only handoff-affecting effects | `store` `tests/suite/idle_session_end.rs` — guard by guard: `idle_end_loses_to_an_already_ended_session` (the `ended_at IS NULL` predicate; fails with it removed), `idle_end_counts_the_same_observation_population_as_the_digest` (a multi-project session ends with `ended_observation_count` = 2; fails if the CAS count's population diverges from the digest/counter's), `idle_end_cas_rejects_a_stale_observation_count` (the count guard; fails with it removed), `idle_end_cas_rejects_a_moved_latest_page` (the page-version guard; fails with it removed), `idle_end_pre_stamp_non_end_observation_in_window_loses_the_cas` / `idle_end_pre_stamp_checkpoint_page_in_window_loses_the_cas` / `idle_end_pre_stamp_real_session_end_in_window_loses_the_cas` (the test-only seam runs on the writer connection BEFORE the candidate's stamp transaction and injects the SQL effects a concurrent writer would leave in the read-to-stamp window — simulated effects, not a run of the hook's `SessionEnd` handler; a `Lost` with the consolidation gate on creates no job; each fails with its guard removed), `idle_end_candidate_cannot_cross_the_project_boundary` (a foreign-scope candidate is refused; same-scope control ends), `idle_end_lifecycle_only_refuses_a_foreign_scope_candidate` (the lifecycle-only scope/open guard: `Lost`, no audit, the claimed handoff stays `Accepted`; fails with the guard removed), `idle_end_lifecycle_only_refuses_an_already_ended_session_with_control` (dedicated already-ended case: `Lost` with no audit and no handoff release, next to the open control in the same fixture that ends and releases), `idle_end_lifecycle_only_loses_to_a_substantive_race` (the atomic substantiveness re-check), `idle_end_reopens_the_handoff_a_lifecycle_only_session_claimed` (exactly one `idle_session_end` row, distinct from the release row), `idle_end_watermark_converges_a_late_real_session_end` (a late real `SessionEnd` converges through `AlreadyEnded`/`ReEnd`), `idle_end_batch_stamps_every_candidate_in_one_command`, `idle_selection_is_cutoff_scoped_ordered_and_bounded` (threshold, order, bound; `seen_page_id` captured with a page present and `None` without — the `session_page_path` rendering), `idle_end_stamps_watermark_audit_page_and_consolidation`, `idle_end_consolidation_enqueue_shares_the_callers_transaction` + `idle_end_consolidation_enqueue_failure_rolls_back_and_retries` (the in-transaction enqueue; fails out-of-transaction), `session_observation_count_refuses_foreign_and_missing_scopes` (foreign workspace / foreign project / missing id each count 0; the right tuple counts — the raw-id reader's scope join), `enqueue_in_tx_refuses_a_foreign_scope_and_leaves_the_foreign_queue` (a foreign tuple enqueues nothing and the foreign project's queue is unchanged; the right tuple enqueues — the job INSERT's scope binding). `hooks` `tests/suite/idle_end.rs` + `src/synth.rs` `load_with_count_scopes`: `foreign_and_missing_tuples_load_nothing_the_right_tuple_loads` (`SessionDigest::load_with_count` refuses a foreign tuple and a missing id as `SessionCollision`; the right tuple loads and counts — the tuple validation; fails with it removed), `idle_tick_skips_a_session_ended_by_a_real_session_end_between_selection_and_write` (a real `/hook` `SessionEnd` landing between selection and page write leaves the hook's page as the only version and no additional handoff from the tick; fails with the conditional write removed — the CAS itself is proven by the store tests above), `idle_tick_late_real_session_end_with_new_work_reends_with_handoff` (the late real end re-ends with exactly one handoff), `idle_tick_excludes_active_managed_run_sessions` (+control after `cancel_managed_run`), `idle_tick_excluded_backlog_cannot_starve_the_batch` (25 excluded sessions cannot consume the batch), `idle_tick_ends_idle_substantive_session_with_page_job_and_no_handoff` (owner attribution via `last_modified_by.username`; no additional handoff from the tick), `idle_tick_lifecycle_only_ends_without_page_or_job_and_creates_no_handoff`, `idle_tick_skips_active_sessions_and_respects_the_batch`, `idle_tick_keeps_a_session_page_written_by_the_agent`; `cli` `serve.rs` `idle_end_tick_does_not_start_when_disabled_or_maintenance_off` and `idle_end_tick_ends_an_idle_session_on_the_first_pass` (tick-clock `ended_at`, paused `tokio::time`), `config.rs` `sessions_idle_end_defaults_off_loads_from_toml_and_rejects_out_of_range` | STRONG |
| 4l | The cut-off-session pointer (session-start notice, `memory_briefing` `recent_sessions`, `memory_handoff_list` `newer_unended_session`) names only the caller's own or shared sessions, carries no captured text, and claims nothing; `memory_read_session_observations` without a `session_id` defaults through the same owner-filtered, scope-bound ordering | `ai-memory-store/src/reader.rs` `recent_session_activity` applies the same `OwnerFilter` clause on the session row as `sessions_for_scope` (`actor_user IS NULL OR = :actor`, or `IS NULL` for an unattributed caller) inside the resolved, authorized `(workspace, project)`; `ai-memory-hooks/src/router.rs` `render_continuity_notice` renders only the stored agent kind, the session UUID, an age and the scope's server-side names (the `render_handoff_notice`/`render_inbox_notice` bar) and is computed after `authorize_resolved`; the MCP fields reuse the tool's own resolved scope and owner filter | router `session_start_never_names_another_operators_cut_off_session` (adversarial: with registered users, bob's cut-off session is not named to alice; control: bob's next session is pointed at it; fails with the owner clause removed), `session_start_names_a_session_cut_off_without_ending` (the notice carries none of the session's prompt, command or output text); store `session_activity.rs` `the_owner_filter_hides_another_operators_sessions`; MCP `memory_read_session_observations_default_never_crosses_owner_or_project` (adversarial: bob's newer open session in alice's cwd and alice's newer session in another project are never alice's default; control: alice's own older session is, and bob's default is his own; fails with the owner filter set to `Any`); CLI `harness_switch_e2e.rs` (real server and hook binary; no captured text in the notice) | STRONG |
+| 4m | A project's `[handoff] deliver_on_session_start = false` hides and claims only its own session-start baton | `ai-memory-hooks/src/router.rs` `fetch_and_accept_handoff_at` reads `HandoffQuery.handoff` for the one resolved `(workspace, project)`: opted out, it neither reads (`startup_handoff`), claims, announces nor renders the continuity notice; the handoff stays `open`, and the SessionEnd path that creates it is untouched | `router.rs` `handoff_opt_out_leaves_the_baton_open_and_undelivered` (falsy values hide the baton and leave it open; `1` still delivers and claims) and `handoff_opt_out_is_scoped_to_the_requesting_project` (a second project keeps receiving its own baton, never the opted-out one's, and does not consume it) | STRONG |
| 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 569944f8..63d3d8f1 100644
--- a/hooks/_lib.sh
+++ b/hooks/_lib.sh
@@ -101,8 +101,8 @@ ai_memory_profile_flag() {
# Whether "$1" (a marker file) declares anything beyond a `[capture]`
# section: any root-level scope key (workspace/project/project_strategy), or
# any of the other settings ai_memory_marker_qs / ai_memory_briefing_qs
-# forward (drop_subagent_captures, default_global, [briefing] and [profile]
-# keys). Mirrors
+# forward (drop_subagent_captures, default_global, [briefing], [profile] and
+# [handoff] keys). Mirrors
# `declares_more_than_capture` in marker.rs. A marker with any of these is a
# resolution boundary; only a marker whose only content is `[capture]` (e.g.
# ignore_paths) is scope/settings-transparent (#668).
@@ -115,7 +115,7 @@ ai_memory_marker_declares_settings() {
ai_memory_strip_utf8_bom <"$file" \
| LC_ALL=C grep -Eq '^[[:space:]]*aliases[[:space:]]*=' && return 0
ai_memory_marker_declares_server "$file" && return 0
- for key in default_global inject_on_session_start max_chars contribute consume; do
+ for key in default_global inject_on_session_start max_chars contribute consume deliver_on_session_start; do
[ -n "$(ai_memory_parse_toml_flag "$file" "$key")" ] && return 0
done
return 1
@@ -680,6 +680,7 @@ ai_memory_marker_qs() {
isty=""
pcon=""
pcons=""
+ hoff=""
aliases=""
routed=""
# The nearest marker that declares more than `[capture]` (#668): a nested
@@ -723,6 +724,9 @@ ai_memory_marker_qs() {
# what it stored.
pcon=$(ai_memory_profile_flag "$(ai_memory_parse_toml_flag "$marker" contribute)")
pcons=$(ai_memory_profile_flag "$(ai_memory_parse_toml_flag "$marker" consume)")
+ # `[handoff] deliver_on_session_start = false` is sent only when
+ # explicitly falsy; an absent key leaves the request unchanged.
+ [ "$(ai_memory_profile_flag "$(ai_memory_parse_toml_flag "$marker" deliver_on_session_start)")" = 0 ] && hoff=0
[ -n "$pr" ] && ps="marker"
fi
# Before repo-root can fill `pr`: a repo-root name is an inference, while
@@ -768,6 +772,7 @@ ai_memory_marker_qs() {
[ -n "$dg" ] && qs="${qs}&default_global=$(ai_memory_url_encode "$dg")"
[ -n "$pcon" ] && qs="${qs}&profile_contribute=$(ai_memory_url_encode "$pcon")"
[ -n "$pcons" ] && qs="${qs}&profile_consume=$(ai_memory_url_encode "$pcons")"
+ [ -n "$hoff" ] && qs="${qs}&handoff=0"
qs="${qs}$(ai_memory_managed_qs)"
printf '%s' "$qs"
}
diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1
index 788600be..29ffedeb 100644
--- a/hooks/lib/ai-memory-hook.ps1
+++ b/hooks/lib/ai-memory-hook.ps1
@@ -65,7 +65,7 @@ function Test-AiMemoryMarkerDeclaresSettings {
}
if ([regex]::IsMatch($text, '(?m)^\s*aliases\s*=')) { return $true }
if ([regex]::IsMatch($text, '(?m)^[\s]*server\s*=')) { return $true }
- foreach ($key in @("default_global", "inject_on_session_start", "max_chars", "contribute", "consume")) {
+ foreach ($key in @("default_global", "inject_on_session_start", "max_chars", "contribute", "consume", "deliver_on_session_start")) {
if ([regex]::IsMatch($text, "(?m)^\s*$key\s*=")) { return $true }
}
return $false
@@ -589,6 +589,7 @@ function Get-AiMemoryMarkerQuery {
$identityStyle = $null
$profileContribute = $null
$profileConsume = $null
+ $handoffOff = $false
$aliases = $null
$identityQuery = ""
$homeRouted = $false
@@ -629,6 +630,8 @@ function Get-AiMemoryMarkerQuery {
# what it stored.
$profileContribute = ConvertTo-AiMemoryProfileFlag (Get-AiMemoryTomlFlag -File $marker -Key "contribute")
$profileConsume = ConvertTo-AiMemoryProfileFlag (Get-AiMemoryTomlFlag -File $marker -Key "consume")
+ # `[handoff] deliver_on_session_start = false`: sent only when explicitly falsy.
+ $handoffOff = (ConvertTo-AiMemoryProfileFlag (Get-AiMemoryTomlFlag -File $marker -Key "deliver_on_session_start")) -eq "0"
if ($proj) { $projSrc = "marker" }
}
# Before repo-root can fill $proj: a repo-root name is an inference, while
@@ -662,6 +665,7 @@ function Get-AiMemoryMarkerQuery {
if ($defaultGlobal) { $qs += "&default_global=$([uri]::EscapeDataString($defaultGlobal))" }
if ($profileContribute) { $qs += "&profile_contribute=$([uri]::EscapeDataString($profileContribute))" }
if ($profileConsume) { $qs += "&profile_consume=$([uri]::EscapeDataString($profileConsume))" }
+ if ($handoffOff) { $qs += "&handoff=0" }
return $qs
}
diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.sh
index 4b8f1865..e93472cd 100755
--- a/tests/hooks/test_lib.sh
+++ b/tests/hooks/test_lib.sh
@@ -502,6 +502,26 @@ assert_eq "marker_qs forwards [profile] contribute and consume" \
assert_eq "marker_qs sends explicit [profile] defaults when a marker omits the keys" \
"&cwd=$(ai_memory_url_encode "$TMP/profile-only")&workspace=outer&profile_contribute=1&profile_consume=1" \
"$(ai_memory_marker_qs "$TMP/profile-only")"
+# `[handoff] deliver_on_session_start = false` is sent as &handoff=0 only when
+# explicitly falsy, and a [handoff]-only marker is a settings boundary.
+mkdir -p "$TMP/handoff-off/inner" "$TMP/handoff-on"
+printf 'workspace = "outer"\n' >"$TMP/handoff-off/.ai-memory.toml"
+printf '[handoff]\ndeliver_on_session_start = "false"\n' >"$TMP/handoff-off/inner/.ai-memory.toml"
+printf '[handoff]\ndeliver_on_session_start = true\n' >"$TMP/handoff-on/.ai-memory.toml"
+assert_eq "handoff-only marker is a settings boundary" \
+ "$TMP/handoff-off/inner/.ai-memory.toml" "$(ai_memory_find_settings_marker "$TMP/handoff-off/inner")"
+assert_eq "marker_qs forwards the [handoff] opt-out" \
+ "&cwd=$(ai_memory_url_encode "$TMP/handoff-off/inner")&profile_contribute=1&profile_consume=1&handoff=0" \
+ "$(ai_memory_marker_qs "$TMP/handoff-off/inner")"
+assert_eq "marker_qs omits handoff for a sibling project and for a truthy value" \
+ "&cwd=$(ai_memory_url_encode "$TMP/handoff-off")&workspace=outer&profile_contribute=1&profile_consume=1" \
+ "$(ai_memory_marker_qs "$TMP/handoff-off")"
+assert_eq "marker_qs omits handoff when deliver_on_session_start is true" \
+ "&cwd=$(ai_memory_url_encode "$TMP/handoff-on")&profile_contribute=1&profile_consume=1" \
+ "$(ai_memory_marker_qs "$TMP/handoff-on")"
+HF_PS=$(grep -q 'deliver_on_session_start' hooks/lib/ai-memory-hook.ps1 \
+ && grep -q '&handoff=0' hooks/lib/ai-memory-hook.ps1 && printf 'ok' || printf 'missing')
+assert_eq "powershell marker query forwards the [handoff] opt-out (static)" "ok" "$HF_PS"
PSH=""
if command -v pwsh >/dev/null 2>&1; then
PSH=$(command -v pwsh)