Skip to content

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

Rust

fix(antigravity): keep turn checkpoints from ending sessions; harden transcript reads

4nrry2f69bd55c1c8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 29db78ca..fc1212db 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -123,7 +123,14 @@ version in [`docs/changelog/`](docs/changelog/):
for a conversation whose prompts were already captured. Rerun
`install-hooks --agent antigravity-cli --apply` to add `SessionStart`;
existing native-hook installs get the prompts and checkpoints without it.
- (#TBD)
+ A turn checkpoint never ends a conversation, even a turn with no captured
+ prompt or tool call, so a handoff it claimed at start is never offered
+ again; the conversation start is claimed atomically, so a concurrent
+ `SessionStart` and first `PreInvocation` cannot both claim a handoff;
+ prompt ingest keys include the prompt's time and text, so a rewind that
+ reuses step numbers keeps its new prompts; and the transcript is opened
+ with `O_NOFOLLOW | O_NONBLOCK` and, on Linux, checked against the opened
+ descriptor's real path. (#TBD)
### Fixed
- Fixed `memory_lint` reporting findings for TTL-expired pages. The lint pass
diff --git a/Cargo.lock b/Cargo.lock
index 4834cd91..2e746f24 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -169,6 +169,7 @@ dependencies = [
"git2",
"icu_normalizer",
"jiff",
+ "libc",
"rusqlite",
"serde",
"serde_json",
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index ef5eea83..bdada3e3 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -567,6 +567,31 @@ fn antigravity_conversation_start_marker(
)
}
+/// Claims an Antigravity conversation's start atomically. `create_new` lets
+/// exactly one of a concurrent native SessionStart and first-turn
+/// PreInvocation win, so only one of them posts session-start and claims a
+/// handoff. `false` means the conversation already started; any other
+/// failure counts as a win, as the best-effort marker always has (the worst
+/// case is a repeated start, never a lost one).
+fn claim_conversation_start(marker: &Path) -> bool {
+ if let Some(parent) = marker.parent() {
+ let _ = fs::create_dir_all(parent);
+ }
+ match fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(marker)
+ {
+ Ok(_) => {
+ // Rewrites the empty marker and applies the bounded retention.
+ mark_briefed(marker);
+ true
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => false,
+ Err(_) => true,
+ }
+}
+
/// Transcript read cursors kept at once. A cursor that falls out only makes
/// the next read of its conversation start over, and the server's ingest
/// keys drop the prompts it already has.
@@ -631,9 +656,10 @@ pub(crate) fn antigravity_transcript_prompts_captured(data_dir: &Path, conversat
> 0
}
-/// Ingest key of a recovered prompt: stable per conversation and step, so a
-/// repeated read (a lost cursor, a crash before it was stored) is dropped by
-/// the server instead of stored twice.
+/// Ingest key of a recovered prompt: stable per conversation, step, time and
+/// text, so a repeated read (a lost cursor, a crash before it was stored, a
+/// rewind that re-reads the file) is dropped by the server instead of stored
+/// twice, while a new prompt that reuses a rewound step number is not.
fn antigravity_prompt_ingest_key(
conversation: &str,
prompt: &ai_memory_hooks::TranscriptPrompt,
@@ -642,8 +668,16 @@ fn antigravity_prompt_ingest_key(
|| format!("offset:{}", prompt.line_offset),
|step| format!("step:{step}"),
);
+ let text = format!("{:x}", Sha256::digest(prompt.text.as_bytes()));
+ let created_at = prompt.created_at.as_deref().unwrap_or("");
let mut hasher = Sha256::new();
- for part in ["antigravity-transcript-prompt", conversation, step.as_str()] {
+ for part in [
+ "antigravity-transcript-prompt",
+ conversation,
+ step.as_str(),
+ created_at,
+ text.as_str(),
+ ] {
hasher.update(part.len().to_be_bytes());
hasher.update(part.as_bytes());
}
@@ -1075,11 +1109,7 @@ where
&json,
);
let started = match &marker {
- Some(marker) if marker.exists() => true,
- Some(marker) => {
- mark_briefed(marker);
- false
- }
+ Some(marker) => !claim_conversation_start(marker),
None => antigravity == AntigravityBoundary::TurnStart,
};
if started && antigravity == AntigravityBoundary::ConversationStart {
@@ -6306,6 +6336,69 @@ mod tests {
assert!(first_request(&mut requests).await.is_none());
}
+ /// A re-read of the same prompt keeps its key (the server drops it), while
+ /// a rewind's new prompt that reuses the step number gets a new one.
+ #[test]
+ fn antigravity_prompt_ingest_key_follows_step_time_and_text() {
+ let prompt = |text: &str, created_at: Option<&str>| ai_memory_hooks::TranscriptPrompt {
+ step_index: Some(4),
+ line_offset: 0,
+ text: text.into(),
+ created_at: created_at.map(Into::into),
+ };
+ let at = Some("2026-10-18T10:00:00Z");
+ let key = antigravity_prompt_ingest_key("conv", &prompt("fix the parser", at));
+ assert_eq!(
+ key,
+ antigravity_prompt_ingest_key("conv", &prompt("fix the parser", at)),
+ "a repeated read is deduplicated"
+ );
+ for other in [
+ antigravity_prompt_ingest_key("conv", &prompt("rewound prompt", at)),
+ antigravity_prompt_ingest_key(
+ "conv",
+ &prompt("fix the parser", Some("2026-10-18T11:00:00Z")),
+ ),
+ antigravity_prompt_ingest_key("other-conv", &prompt("fix the parser", at)),
+ ] {
+ assert_ne!(key, other);
+ }
+ assert!(key.starts_with("agy_") && key.len() == 64);
+ }
+
+ /// A concurrent native SessionStart and first-turn PreInvocation race
+ /// for the same marker: exactly one of them may claim the start (and so
+ /// the handoff); a later boundary of the same conversation never does.
+ #[test]
+ fn antigravity_conversation_start_is_claimed_exactly_once_under_races() {
+ let tmp = tempfile::tempdir().unwrap();
+ let marker = tmp.path().join("briefed").join("agy-start-race");
+ let barrier = std::sync::Arc::new(std::sync::Barrier::new(8));
+ let winners = (0..8)
+ .map(|_| {
+ let marker = marker.clone();
+ let barrier = std::sync::Arc::clone(&barrier);
+ std::thread::spawn(move || {
+ barrier.wait();
+ claim_conversation_start(&marker)
+ })
+ })
+ .collect::<Vec<_>>()
+ .into_iter()
+ .map(|t| t.join().unwrap())
+ .filter(|won| *won)
+ .count();
+ assert_eq!(winners, 1, "exactly one boundary claims the start");
+ assert!(marker.is_file());
+ assert!(
+ !claim_conversation_start(&marker),
+ "a later turn never re-claims"
+ );
+ // Control: another conversation still claims its own start.
+ let other = tmp.path().join("briefed").join("agy-start-other");
+ assert!(claim_conversation_start(&other));
+ }
+
#[test]
fn antigravity_conversation_marker_is_keyed_by_a_sanitized_conversation_id() {
let dir = Path::new("/d");
@@ -6667,11 +6760,14 @@ mod tests {
&ai_memory_hooks::TranscriptPrompt {
step_index: Some(0),
line_offset: 0,
- text: String::new(),
- created_at: None,
+ text: "Fix the login redirect".into(),
+ created_at: Some("2026-10-18T10:00:00Z".into()),
},
);
- assert_eq!(key, expected_key, "stable per conversation and step");
+ assert_eq!(
+ key, expected_key,
+ "stable per conversation, step, time and text"
+ );
assert_eq!(query_param(&first.url, "agent"), Some("antigravity-cli"));
// The prompt is scoped exactly like the event it rode with.
let scope = |url: &str| {
@@ -6795,6 +6891,7 @@ mod tests {
let dir = tmp.path().join("hook-state/antigravity-transcripts");
let cursor = ai_memory_hooks::TranscriptCursor {
file: Some("transcript.jsonl".into()),
+ head: Some("0123456789abcdef".into()),
offset: 42,
last_step: Some(3),
resync: false,
diff --git a/crates/ai-memory-hooks/Cargo.toml b/crates/ai-memory-hooks/Cargo.toml
index d67fa918..e91d80e5 100644
--- a/crates/ai-memory-hooks/Cargo.toml
+++ b/crates/ai-memory-hooks/Cargo.toml
@@ -33,6 +33,8 @@ uuid.workspace = true
axum.workspace = true
sha2.workspace = true
+libc.workspace = true
+
[dev-dependencies]
ai-memory-test-support.workspace = true
tempfile.workspace = true
diff --git a/crates/ai-memory-hooks/src/antigravity.rs b/crates/ai-memory-hooks/src/antigravity.rs
index 83abe8a2..22ee668c 100644
--- a/crates/ai-memory-hooks/src/antigravity.rs
+++ b/crates/ai-memory-hooks/src/antigravity.rs
@@ -277,12 +277,19 @@ pub struct TranscriptCursor {
/// File name of the transcript the offset belongs to.
#[serde(default)]
pub file: Option<String>,
+ /// Fingerprint of the transcript's first complete line. Antigravity only
+ /// appends, so a different first line means the file was rewritten (a
+ /// rewind), even when it did not get shorter.
+ #[serde(default)]
+ pub head: Option<String>,
/// Byte offset just past the last line consumed.
#[serde(default)]
pub offset: u64,
- /// Highest `step_index` of a prompt already returned. A rewritten or
- /// truncated transcript is re-read from the start, and this keeps its
- /// old prompts from being returned twice.
+ /// Highest `step_index` of a prompt already returned in the current
+ /// file. It is cleared when the file is rewritten or truncated, because a
+ /// rewind can reuse step numbers for new prompts; the prompts that file
+ /// still holds come back once more and the server drops them by their
+ /// content-derived ingest keys.
#[serde(default)]
pub last_step: Option<u64>,
/// The previous read stopped inside a line longer than the scan budget;
@@ -378,7 +385,7 @@ fn open_regular_file(path: &Path) -> Option<File> {
if !before.is_file() {
return None;
}
- let file = File::open(path).ok()?;
+ let file = open_no_follow(path)?;
let after = file.metadata().ok()?;
if !after.is_file() {
return None;
@@ -390,9 +397,67 @@ fn open_regular_file(path: &Path) -> Option<File> {
return None;
}
}
+ // The directories were canonical when checked, but one swapped for a
+ // symlink afterwards would still be followed by the open, and the inode
+ // comparison above sees the same swapped file. The descriptor's own path
+ // must be the one that was checked.
+ #[cfg(target_os = "linux")]
+ {
+ use std::os::unix::io::AsRawFd as _;
+ let opened = std::fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd())).ok()?;
+ if opened != path {
+ return None;
+ }
+ }
Some(file)
}
+/// Bytes of the first line that identify a transcript file.
+const TRANSCRIPT_HEAD_BYTES: usize = 256;
+
+/// Short fingerprint of the first complete line (or of its first
+/// [`TRANSCRIPT_HEAD_BYTES`] when it is longer). `None` while the first line
+/// is still being written, so a growing file is never mistaken for a
+/// rewritten one. Leaves the file positioned at its start.
+fn head_fingerprint(file: &mut File) -> std::io::Result<Option<String>> {
+ use sha2::{Digest as _, Sha256};
+ let mut buf = [0_u8; TRANSCRIPT_HEAD_BYTES];
+ let mut filled = 0;
+ while filled < buf.len() {
+ match file.read(&mut buf[filled..])? {
+ 0 => break,
+ read => filled += read,
+ }
+ }
+ file.seek(SeekFrom::Start(0))?;
+ let head = match buf[..filled].iter().position(|&b| b == b'\n') {
+ Some(newline) => &buf[..newline],
+ None if filled == buf.len() => &buf[..],
+ None => return Ok(None),
+ };
+ let digest = format!("{:x}", Sha256::digest(head));
+ Ok(Some(digest[..16].to_owned()))
+}
+
+/// `O_NOFOLLOW` refuses a final-component symlink swapped in after the
+/// metadata check, and `O_NONBLOCK` keeps a FIFO swapped in from blocking the
+/// open (and so the hook) indefinitely; reads of a regular file are
+/// unaffected.
+#[cfg(unix)]
+fn open_no_follow(path: &Path) -> Option<File> {
+ use std::os::unix::fs::OpenOptionsExt as _;
+ std::fs::OpenOptions::new()
+ .read(true)
+ .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
+ .open(path)
+ .ok()
+}
+
+#[cfg(not(unix))]
+fn open_no_follow(path: &Path) -> Option<File> {
+ File::open(path).ok()
+}
+
/// Read the user prompts written to `path` since `cursor`. At most
/// [`MAX_TRANSCRIPT_SCAN_BYTES`] are read and [`MAX_TRANSCRIPT_PROMPTS`]
/// returned; a line still being written is left for the next read. `None`
@@ -400,13 +465,19 @@ fn open_regular_file(path: &Path) -> Option<File> {
#[must_use]
pub fn read_transcript_prompts(path: &Path, cursor: &TranscriptCursor) -> Option<TranscriptRead> {
let name = path.file_name()?.to_str()?.to_owned();
- let file = open_regular_file(path)?;
+ let mut file = open_regular_file(path)?;
let len = file.metadata().ok()?.len();
+ let head = head_fingerprint(&mut file).ok()?;
let mut next = cursor.clone();
- if next.file.as_deref() != Some(name.as_str()) || len < next.offset {
+ let rewritten = matches!((&next.head, &head), (Some(old), Some(new)) if old != new);
+ if next.file.as_deref() != Some(name.as_str()) || len < next.offset || rewritten {
next.file = Some(name);
next.offset = 0;
next.resync = false;
+ next.last_step = None;
+ }
+ if head.is_some() {
+ next.head = head;
}
let mut reader = BufReader::with_capacity(64 * 1024, file);
reader.seek(SeekFrom::Start(next.offset)).ok()?;
@@ -1206,6 +1277,60 @@ mod tests {
read.prompts.iter().map(|p| p.text.as_str()).collect()
}
+ /// A rewind truncates or rewrites the transcript and can reuse step
+ /// numbers for new prompts: they must still be returned, whether the file
+ /// got shorter or kept its length. An append is not a rewrite.
+ #[test]
+ fn transcript_rewrites_return_new_prompts_that_reuse_step_numbers() {
+ let home = tempdir().unwrap();
+ let path = write_transcript(
+ home.path(),
+ "antigravity",
+ "conv-rewind",
+ "transcript.jsonl",
+ &[
+ &user_input(0, "first long prompt about the parser module"),
+ &user_input(1, "second prompt"),
+ ],
+ );
+ let first = read_transcript_prompts(&path, &TranscriptCursor::default()).unwrap();
+ assert_eq!(
+ texts(&first),
+ ["first long prompt about the parser module", "second prompt"]
+ );
+
+ // Control: an append returns only the new prompt.
+ let mut appended = fs::read_to_string(&path).unwrap();
+ appended.push_str(&format!("{}\n", user_input(2, "third prompt")));
+ fs::write(&path, &appended).unwrap();
+ let after_append = read_transcript_prompts(&path, &first.cursor).unwrap();
+ assert_eq!(texts(&after_append), ["third prompt"]);
+
+ // Shorter rewrite reusing step 0.
+ fs::write(&path, format!("{}\n", user_input(0, "edited"))).unwrap();
+ let shorter = read_transcript_prompts(&path, &after_append.cursor).unwrap();
+ assert_eq!(texts(&shorter), ["edited"]);
+
+ // Same-or-longer rewrite reusing steps 0 and 1.
+ fs::write(
+ &path,
+ format!(
+ "{}\n{}\n",
+ user_input(0, "rewritten first prompt, now even longer than before"),
+ user_input(1, "rewritten second prompt that keeps growing")
+ ),
+ )
+ .unwrap();
+ let longer = read_transcript_prompts(&path, &shorter.cursor).unwrap();
+ assert_eq!(
+ texts(&longer),
+ [
+ "rewritten first prompt, now even longer than before",
+ "rewritten second prompt that keeps growing"
+ ]
+ );
+ }
+
#[test]
fn reads_prompts_from_the_app_transcript_and_the_cli_full_transcript() {
let home = tempdir().unwrap();
@@ -1325,7 +1450,10 @@ mod tests {
assert_eq!(texts(&next), ["third"]);
assert_eq!(next.cursor.prompts, 3);
- // Rewritten shorter: re-read from the start, old steps not repeated.
+ // Rewritten shorter: re-read from the start. A rewind can reuse step
+ // numbers, so the file's prompts all come back; the ones already
+ // delivered carry the same content-derived ingest key and the server
+ // drops them.
fs::write(
&path,
format!(
@@ -1336,7 +1464,7 @@ mod tests {
)
.unwrap();
let rewritten = read_transcript_prompts(&path, &next.cursor).unwrap();
- assert_eq!(texts(&rewritten), ["after rewrite"]);
+ assert_eq!(texts(&rewritten), ["third", "after rewrite"]);
// A cursor for the other transcript file starts over too.
let mut other = rewritten.cursor.clone();
@@ -1444,4 +1572,61 @@ mod tests {
["not a transcript"]
);
}
+
+ /// A FIFO named like the transcript must be refused without blocking the
+ /// hook, and a directory swapped for a symlink after the containment check
+ /// must not let the open reach a file outside the checked path.
+ #[test]
+ #[cfg(target_os = "linux")]
+ fn transcript_reader_refuses_fifos_and_swapped_directories() {
+ use std::os::unix::fs::symlink;
+ let home = tempdir().unwrap();
+ let path = write_transcript(
+ home.path(),
+ "antigravity",
+ "conv-fifo",
+ "transcript.jsonl",
+ &[],
+ );
+ fs::remove_file(&path).unwrap();
+ let made = std::process::Command::new("mkfifo")
+ .arg(&path)
+ .status()
+ .unwrap();
+ assert!(made.success());
+ let started = std::time::Instant::now();
+ assert_eq!(
+ read_transcript_prompts(&path, &TranscriptCursor::default()),
+ None
+ );
+ assert!(started.elapsed() < std::time::Duration::from_secs(2));
+
+ // `.system_generated` swapped for a symlink to a foreign tree.
+ let path = write_transcript(
+ home.path(),
+ "antigravity",
+ "conv-swap",
+ "transcript.jsonl",
+ &[&user_input(0, "real prompt")],
+ );
+ let system_generated = path.parent().unwrap().parent().unwrap().to_path_buf();
+ let foreign = home.path().join("foreign");
+ fs::create_dir_all(foreign.join("logs")).unwrap();
+ fs::write(
+ foreign.join("logs").join("transcript.jsonl"),
+ format!("{}\n", user_input(0, "foreign secret")),
+ )
+ .unwrap();
+ // Control: before the swap the checked path is read.
+ assert_eq!(
+ texts(&read_transcript_prompts(&path, &TranscriptCursor::default()).unwrap()),
+ ["real prompt"]
+ );
+ fs::remove_dir_all(&system_generated).unwrap();
+ symlink(&foreign, &system_generated).unwrap();
+ assert_eq!(
+ read_transcript_prompts(&path, &TranscriptCursor::default()),
+ None
+ );
+ }
}
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 521ad860..81058a16 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -4199,6 +4199,18 @@ async fn process_authorized(
.reader
.session_has_substantive_observation(page_ws, page_proj, session_id)
.await?;
+ // A turn checkpoint never ends a session. A turn with no captured
+ // prompt or tool call (an answer without tools, or a prompt the
+ // transcript reader skipped) would otherwise take the lifecycle-only
+ // end path below, which closes the live conversation and reopens the
+ // handoff it claimed at start, so the next session would receive it
+ // a second time and later turns would never checkpoint.
+ if turn_checkpoint && !substantive {
+ if let Some(key) = ingest_key {
+ state.writer.complete_observation_ingest(proj, key).await?;
+ }
+ return Ok(outcome);
+ }
if !substantive {
let lifecycle_outcome = state
.writer
@@ -14194,6 +14206,115 @@ pub(crate) mod tests {
);
}
+ /// A turn with nothing captured (an answer without tools, or a prompt
+ /// the transcript reader skipped) is still only a checkpoint: it must not
+ /// take the lifecycle-only end path, which would close the conversation
+ /// and reopen the handoff it claimed at start for a second receiver.
+ #[tokio::test]
+ async fn antigravity_lifecycle_only_turn_keeps_conversation_open_and_handoff_claimed() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let prior = "agy-prior-conversation";
+ antigravity_turn(&state, prior, "Earlier work on the parser", None).await;
+ process(
+ &state,
+ antigravity_event(prior, "session-end", ""),
+ None,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+
+ let conversation = "agy-quiet-turn";
+ let session = SessionId::from_native(conversation);
+ process(
+ &state,
+ antigravity_event(conversation, "session-start", ""),
+ None,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+ let receiver = |agent: &str, session_id: String| HandoffQuery {
+ profile_contribute: None,
+ profile_consume: None,
+ profile_digest: None,
+ agent: Some(agent.into()),
+ session_id: Some(session_id),
+ ..Default::default()
+ };
+ let quiet =
+ jiff::Timestamp::now() + LIVE_BATON_QUIET_PERIOD + jiff::SignedDuration::from_secs(1);
+ let claimed = fetch_and_accept_handoff_at(
+ &state,
+ receiver("antigravity-cli", session.to_string()),
+ None,
+ Vec::new(),
+ None,
+ quiet,
+ )
+ .await
+ .unwrap()
+ .expect("the new conversation claims the earlier handoff");
+ assert!(claimed.contains("Earlier work on the parser"), "{claimed}");
+
+ // The model finished a turn without any tool and no prompt was captured.
+ process(
+ &state,
+ antigravity_event(conversation, "stop", ""),
+ None,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ state
+ .reader
+ .session_end_disposition(
+ session,
+ state.workspace_id,
+ state.project_id,
+ AgentKind::AntigravityCli
+ )
+ .await
+ .unwrap(),
+ ai_memory_store::SessionEndDisposition::Open,
+ "a turn checkpoint must not end the conversation"
+ );
+ assert!(
+ fetch_and_accept_handoff_at(
+ &state,
+ receiver("claude-code", SessionId::new().to_string()),
+ None,
+ Vec::new(),
+ None,
+ quiet,
+ )
+ .await
+ .unwrap()
+ .is_none(),
+ "a claimed handoff is never offered again"
+ );
+
+ // Control: once the conversation does real work, its idle turn checkpoints.
+ let pages_before = session_pages(&state).await.len();
+ antigravity_turn(&state, conversation, "Now fix the lexer", None).await;
+ assert_eq!(session_pages(&state).await.len(), pages_before + 1);
+ assert_eq!(
+ state
+ .reader
+ .session_end_disposition(
+ session,
+ state.workspace_id,
+ state.project_id,
+ AgentKind::AntigravityCli
+ )
+ .await
+ .unwrap(),
+ ai_memory_store::SessionEndDisposition::Open
+ );
+ }
+
#[tokio::test]
async fn antigravity_stop_checkpoint_requires_a_finished_idle_root_unmanaged_stop() {
for case in [
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 12a48d53..a661148b 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -47,7 +47,7 @@ means the boundary is not built yet.
| 3i | Cross-project `GET /admin/recent` (no `workspace`/`project`, the `ai-memory recent --global` path) is root-only on a multi-user server | `ai-memory-mcp/src/admin.rs` `handle_recent` runs the no-scope branch through `ReaderPool::recent_pages_global` as `OPERATOR` (every project, each hit tagged with its workspace and project); the route sits in the operational router under `require_root_for_multiuser_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`), so a DB user or proxy-asserted user never reaches the unfiltered read. A partial scope is still a 400, never a silent global fallback; an unknown scoped project is a 404 and does not leak another project's pages. `ai-memory-cli/src/commands/recent.rs` sends no scope only when `--global` is passed, and clap rejects `--global` with `--workspace`/`--project` | MCP `admin_status_search.rs` `global_recent_never_reaches_a_non_root_caller` (a restricted project the user holds no grant on, for both a DB-user deployment and a trusted-proxy deployment with no `users` rows: user 403 and anonymous 401 with neither the sentinel path nor the restricted snippet in the body; root control 200 with both projects' hits), `global_recent_tags_each_hit_with_its_workspace_and_project`, `recent_rejects_partial_scope_instead_of_global_fallback`, `recent_unknown_scope_is_404_and_does_not_leak_other_projects`; the shared `admin.rs` all-admin 403/401 route matrix includes `/admin/recent`; CLI `cli.rs` `recent_global_parses_and_conflicts_with_an_explicit_scope` | STRONG. Bite check: with the gate's operator test forced off (`authorize(Capability::Admin, false)`) the refusal test fails on the DB-user case (200 instead of 403) |
| 4 | Handoff single-claim / no-steal | `ai-memory-store/src/ops.rs` `accept_handoff_in_transaction` (metadata `state='open'` guard + atomic CAS; the receiver-session check, which requires the receiving session to exist in the claim's own workspace, project and agent kind and refuses with `InvalidState` before the handoff row is touched; an ended receiver is final EXCEPT for the agents where `AgentKind::reuses_session_id_after_end()` holds — Grok and Kimi Code, whose harnesses reuse the native session id across SessionEnd→resume, so accepting reopens `ended_at` only after the claim-once guard) | `multi_session.rs` `a_second_accept_cannot_steal_an_accepted_handoff`; `handoff_ownership.rs` `another_operator_cannot_claim_the_handoff`; `multi_session.rs` `handoff_accept_rejects_foreign_or_missing_receiver_session` (receivers from a sibling project, another workspace, a different agent kind, and a nonexistent session are each refused as `InvalidState` with the handoff left open and every `accepted_*` column NULL; the matching receiver claims it; the same receiver retrying and a second matching session get `false` with the first claim intact; fails with the `project_id` or `agent_kind` predicate, or the missing-session refusal, removed. The `workspace_id` predicate is redundant defence in depth: project ids are globally unique, so the cross-workspace receiver is already caught by `project_id`); `multi_session.rs` `accept_reopens_an_ended_receiver_session_but_keeps_claim_once` (Grok reopen + no-steal) and `accept_reopens_an_ended_kimi_receiver_but_keeps_every_guard` (Kimi Code resume claims and reopens `ended_at`; adversarial controls: an ended claude-code receiver stays refused, a kimi-code receiver in another project stays refused, and the already-claimed guard still refuses the resumed kimi session a second baton) | STRONG |
| 4b | Handoff owner-scoped recovery (`any_owner` admin gate) | `ai-memory-mcp/src/server.rs` `require_admin_capability` on `memory_handoff_accept`/`_cancel` `any_owner` | `handoff_admission.rs` — cancel gate + **accept gate** (adversarial: non-admin `any_owner` accept refused) | STRONG |
-| 4c | Turn-checkpoint baton is owner+scope-bound | `ai-memory-store/src/ops.rs` `checkpoint_session_handoff` — reads the session's own `(workspace, project, owner_user)` from `sessions WHERE id=?1 AND ended_at IS NULL`, refuses on scope/owner mismatch, refreshes only that session's own `state='open'` baton (id preserved), returns `None` when the session already ended | `ops.rs` `checkpoint_session_handoff_refreshes_only_the_live_sessions_own_baton` (#865); `router.rs` `antigravity_parallel_conversations_keep_owned_batons_claimed_once` (Antigravity checkpoints of two operators each stamp their own owner and reach only that operator), `antigravity_stop_checkpoint_requires_a_finished_idle_root_unmanaged_stop` (a busy, cancelled, failed, reasonless, subagent, managed or non-Antigravity `Stop` publishes nothing; the finished `NO_TOOL_CALL`/`model_stop` controls do) | STRONG |
+| 4c | Turn-checkpoint baton is owner+scope-bound | `ai-memory-store/src/ops.rs` `checkpoint_session_handoff` — reads the session's own `(workspace, project, owner_user)` from `sessions WHERE id=?1 AND ended_at IS NULL`, refuses on scope/owner mismatch, refreshes only that session's own `state='open'` baton (id preserved), returns `None` when the session already ended | `ops.rs` `checkpoint_session_handoff_refreshes_only_the_live_sessions_own_baton` (#865); `router.rs` `antigravity_parallel_conversations_keep_owned_batons_claimed_once` (Antigravity checkpoints of two operators each stamp their own owner and reach only that operator), `antigravity_stop_checkpoint_requires_a_finished_idle_root_unmanaged_stop` (a busy, cancelled, failed, reasonless, subagent, managed or non-Antigravity `Stop` publishes nothing; the finished `NO_TOOL_CALL`/`model_stop` controls do) | STRONG; `router.rs` `antigravity_lifecycle_only_turn_keeps_conversation_open_and_handoff_claimed` (a turn checkpoint never ends a session: one with nothing captured only completes its ingest key, so the handoff it claimed at start is never reopened for a second receiver) |
| 4d | Native session rebind / drifted-end is owner+agent+cwd CAS | `ai-memory-store/src/ops.rs` — `session.moved` rebind gated on `agent==OpenCode` + `ended_at IS NULL` + lexical `normalize_cwd(stored)==normalize_cwd(from)`; `expire_same_cwd_auto_handoffs` AND-gated on `owner_user IS ?4 AND id IS NOT ?5` and on the source not being another still-open session (row 4e, #883); drifted `SessionEnd` ends only same owner+agent+cwd | `ops.rs` `native_move_rebinds_live_session_only_from_its_current_cwd`, `native_move_rejects_foreign_owner_and_ignores_completed_replay`, `drifted_session_end_ends_only_the_same_actor_agent_and_cwd` (#865) | STRONG |
| 4e | A live session's baton stays its own until the session is quiet | `ai-memory-store/src/ops.rs` - `expire_same_cwd_auto_handoffs` spares batons of other open sessions; `accept_handoff_in_transaction(.., busy_since)` re-checks inside the claim that the source is not an open session with observations after the cutoff, and its sweep `expire_superseded_auto_handoffs(.., busy_since)` spares a busy open session's baton (every open session's when `None`, the explicit MCP accept); `reader.rs` `startup_handoff` selects with the same cutoff; `ai-memory-hooks/src/router.rs` `LIVE_BATON_QUIET_PERIOD` | `multi_session.rs` `parallel_live_sessions_keep_their_own_checkpoint_batons`, `startup_claim_rechecks_the_source_and_sweeps_only_quiet_open_batons`; `router.rs` `opencode_parallel_live_batons_are_owned_and_wait_for_quiet`, `antigravity_parallel_conversations_keep_owned_batons_claimed_once` (Antigravity conversations never end, so every one holds a live baton: none is handed over while busy, a claim supersedes only the claimer's own older quiet baton, and each is claimed once) - each fails with its guard removed | STRONG |
| 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 |
@@ -136,7 +136,7 @@ means the boundary is not built yet.
| 26 | Cross-harness native-history continuation stays checkout-scoped and client-local | `ai-memory-store/src/workstream.rs` `prepare_run` selects the newest current native session only when its harness differs from the destination and pins that typed identity on the run before destination linking can change recency; `ai-memory-cli/src/commands/run.rs` validates the returned `NativeSessionIdentity`, resolves only known adapter flavors, requires `native_session_in_checkout`, exports through the bounded read-only adapter, and writes an untrusted-history dossier to a private temporary directory exposed only to the child as `AI_MEMORY_PREVIOUS_SESSION_HISTORY`; the server wire type deliberately has no path/content field and same-harness launches select no source; `ai-memory-hooks/src/router.rs` keeps the server-authored resume directive outside the untrusted-history fence while fencing the transcript evidence itself, and `ai-memory-core/src/routing_snippet.rs` gives installed project instructions the same wrapper-variable-gated fallback | Core `prepare_response_carries_only_previous_native_identity`, `older_prepare_response_defaults_to_no_adoption`, and `snippets_route_managed_continue_to_the_previous_native_history`; store `managed_adoption_stops_after_any_harness_links_the_workstream` (switch control, destination-link recency cannot replace the pinned source, same-harness refusal); hooks `managed_context_points_at_local_history_on_a_harness_switch` (no session id rendered, directive precedes the untrusted fence); CLI `previous_session_history_is_private_local_and_checkout_scoped` (legitimate control, foreign checkout refused, private local file removed with its owner) | STRONG for checkout isolation, prompt-boundary placement, and server path/content privacy. The dossier is a bounded visible-history projection, not raw hidden reasoning; if the source store is absent, remote, unreadable, or over bounds, the child receives only the portable ledger and handoff |
| 27 | Plain-HTTP human authentication stays fail-closed beyond loopback unless the operator supplies the dedicated dangerous override (#1383) | `ai-memory-cli/src/cli.rs` exposes `serve --allow-insecure-human-auth` separately from `--allow-insecure-no-auth`; `serve.rs` `validate_http_exposure` accepts it only when authentication and human mode are both active and the listener is non-loopback with a Non-Secure cookie, while the ordinary unauthenticated guard still runs otherwise. `HttpExposure::InsecureHumanAuthByOverride` gives that path its own unconditional stderr banner and structured warning, naming passwords, API credentials, session cookies, and memory data as plaintext. The default remains refusal, and `secure_cookie=true` or loopback remains the safe path | `serve.rs` `human_auth_non_loopback_requires_secure_cookie_posture` (default refusal, the no-auth override cannot substitute, the dedicated override succeeds, and that override cannot expose a server with no authentication even under inconsistent human-mode input; secure-cookie and loopback controls), `every_unsafe_exposure_produces_an_operator_banner` (the dedicated banner names the flag and session-cookie risk), and `cli.rs` `serve_parses_insecure_transport_overrides` (both dangerous flags remain distinct) | STRONG for the startup boundary. This is an explicit operator acceptance of transport risk, not encryption; authorization, CSRF, rate limits, Host validation, and the unauthenticated exposure refusal are unchanged |
-| 28 | An Antigravity hook reads, and uploads as prompts, only the named conversation's own transcript, within bounds | `ai-memory-hooks/src/antigravity.rs` `antigravity_transcript_path` accepts the payload's `transcriptPath` only when it is absolute, has no `..`, names `transcript.jsonl` or `transcript_full.jsonl`, and its canonical directory equals `canonical(<home>/.gemini/<app>/brain)/<conversationId>/.system_generated/logs` for `<app>` `antigravity`, `antigravity-cli` or `antigravity-ide`, with `conversationId` a plain id (`antigravity_conversation_id`); `read_transcript_prompts` opens only a regular, non-symlink file that is still the same file once open (`open_regular_file`), reads at most `MAX_TRANSCRIPT_SCAN_BYTES` per hook and parses lines up to `MAX_TRANSCRIPT_LINE_BYTES`, and returns only `USER_INPUT` steps whose `source` is absent or `USER_EXPLICIT`; `ai-memory-cli/src/commands/hook.rs` `antigravity_transcript_prompt_events` runs inside the spool block, so after the capture allowlist, routing, server-profile and external-capture gates, with the home `run_with_payload` resolved once; each prompt is capped and scrubbed client-side, keyed by conversation and step, and sanitized again by the server (row 7) | `antigravity.rs` `transcript_path_refuses_anything_outside_the_conversations_own_logs` (another conversation's transcript, the same layout outside the home, another file in the logs directory, an unknown app directory, `..`, a traversal or empty id, a relative path, a missing or non-string path; the conversation's own transcript is the control), `transcript_path_refuses_symlinked_directories_that_leave_the_conversation` (a symlinked `.system_generated` and `brain/<id>` refused; a symlinked `~/.gemini` accepted as the control), `transcript_reader_refuses_symlinks_and_special_files` (a symlinked transcript and a directory refused; the same bytes as a regular file are read), `skips_injected_malformed_empty_and_non_prompt_steps`, `a_line_longer_than_the_scan_budget_is_skipped_across_reads`, `one_read_returns_a_bounded_number_of_prompts`; `hook.rs` `antigravity_transcript_reads_are_confined_to_the_conversations_own_logs` (end to end through the native hook: a forged path outside the home, another conversation's transcript and an arbitrary JSONL file under the home spool no prompt; the conversation's own transcript spools one), `antigravity_transcript_prompts_follow_the_capture_allowlist` (a repository the allowlist leaves out is not read) | STRONG on Unix; the symlink cases are `cfg(unix)`, and elsewhere the canonical-directory check still runs |
+| 28 | An Antigravity hook reads, and uploads as prompts, only the named conversation's own transcript, within bounds | `ai-memory-hooks/src/antigravity.rs` `antigravity_transcript_path` accepts the payload's `transcriptPath` only when it is absolute, has no `..`, names `transcript.jsonl` or `transcript_full.jsonl`, and its canonical directory equals `canonical(<home>/.gemini/<app>/brain)/<conversationId>/.system_generated/logs` for `<app>` `antigravity`, `antigravity-cli` or `antigravity-ide`, with `conversationId` a plain id (`antigravity_conversation_id`); `read_transcript_prompts` opens only a regular, non-symlink file that is still the same file once open (`open_regular_file`, opened with `O_NOFOLLOW | O_NONBLOCK` so a symlink or FIFO swapped in after the check is refused without blocking, and on Linux only when the opened descriptor's `/proc/self/fd` path is the checked one, so a directory swapped for a symlink after the containment check is refused too), reads at most `MAX_TRANSCRIPT_SCAN_BYTES` per hook and parses lines up to `MAX_TRANSCRIPT_LINE_BYTES`, and returns only `USER_INPUT` steps whose `source` is absent or `USER_EXPLICIT`; `ai-memory-cli/src/commands/hook.rs` `antigravity_transcript_prompt_events` runs inside the spool block, so after the capture allowlist, routing, server-profile and external-capture gates, with the home `run_with_payload` resolved once; each prompt is capped and scrubbed client-side, keyed by conversation and step, and sanitized again by the server (row 7) | `antigravity.rs` `transcript_path_refuses_anything_outside_the_conversations_own_logs` (another conversation's transcript, the same layout outside the home, another file in the logs directory, an unknown app directory, `..`, a traversal or empty id, a relative path, a missing or non-string path; the conversation's own transcript is the control), `transcript_path_refuses_symlinked_directories_that_leave_the_conversation` (a symlinked `.system_generated` and `brain/<id>` refused; a symlinked `~/.gemini` accepted as the control), `transcript_reader_refuses_symlinks_and_special_files` (a symlinked transcript and a directory refused; the same bytes as a regular file are read), `skips_injected_malformed_empty_and_non_prompt_steps`, `a_line_longer_than_the_scan_budget_is_skipped_across_reads`, `one_read_returns_a_bounded_number_of_prompts`; `hook.rs` `antigravity_transcript_reads_are_confined_to_the_conversations_own_logs` (end to end through the native hook: a forged path outside the home, another conversation's transcript and an arbitrary JSONL file under the home spool no prompt; the conversation's own transcript spools one), `antigravity_transcript_prompts_follow_the_capture_allowlist` (a repository the allowlist leaves out is not read) | STRONG on Unix; the symlink cases are `cfg(unix)`, and elsewhere the canonical-directory check still runs; `antigravity.rs` `transcript_reader_refuses_fifos_and_swapped_directories` |
### IBM Bob evidence