Skip to content

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

Rust

Merge branch 'main' into release/2.7

AkitaOnRails06f07e7c6b17
diff --cc CHANGELOG.md
index 27a529e3,1b9fcf5a..1f936fa9
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -7,21 -7,74 +7,88 @@@ and this project adheres to [Semantic V
## [Unreleased]
+### Added
+- Added `ai-memory recover` and a bounded local recovery journal for server
+ outages. Offline managed launches now record only uniquely correlated native
+ session locators; recovery quarantines overlapping spool entries before exact
+ `/hook/batch` transcript replay, journals harnesses without transcript export
+ as spool-only without calling their exporter, retains bounded recovery dedup
+ keys with their sessions,
+ fails closed on terminal drops, and lets only the original owner finish an
+ expired unsuperseded managed run through exact idempotent replay. Backfill
+ and recovery replay now use reserved `recovery_*` idempotency keys, so
+ re-running `backfill --force` over sessions imported by ai-memory ≤2.6.0 (or
+ plain-backfilling a recovery-replayed session) can duplicate those older
+ observations. (#1125)
+
### Fixed
+ - Fixed the cross-project profile rewriting a settled entry whenever new
+ evidence merely agreed with it: a statement now changes only when the ruling
+ or its scope does (the LLM merge reports `changed`), so the line every project
+ receives stays put. The profile digest also moved to the front of the
+ session-start payload, ahead of the handoff and brief that change every
+ session, so it stays in the harness's cacheable prompt prefix; its footer now
+ asks the agent to open an entry before relying on its one-line summary; and
+ topic grouping no longer compares every candidate with every other, which
+ grew quadratically on long-lived installs. See
+ `docs/design-cross-project-profile.md` §11. (#1000)
+ - Fixed the scheduled auto-improve tests' intermittent empty log captures
+ (the same latent flaw #1116 fixed for the hooks checkpoint test): a shared
+ `warn!` callsite's first-in-process execution on a bare thread caches
+ `Interest::never()`, after which no per-test `set_default` capture ever
+ sees the event under single-process harnesses (libtest, Windows CI). The
+ tick outcome now carries the typed `failure_summaries` and
+ `skipped_proposals` the warnings mirror, and the tests assert those
+ instead of a captured log stream. Logged messages and levels are
+ unchanged. (#1118)
+ - Fixed hook observation bodies being capped *before* the sanitizer ever saw
+ them: excerpt extraction (`tool: …` bodies, user prompts, notifications,
+ post-compaction summaries, extension bodies) applied its 2 KB / 16 KB
+ ceilings at parse time, so a secret straddling the cutoff was cut in half
+ and the surviving prefix, too short to match a pattern, was stored
+ unredacted — the body-side twin of the #980 title-hint leak. The per-event
+ caps (`payload::durable_body_cap`) now run at the ingest funnel, applied to
+ the already-scrubbed text, mirroring `Sanitized::new` and the #1109
+ feedback-reason fix. The stored body shapes and byte limits are unchanged.
+ (#1114)
+ - Fixed the native hook's client-side spool cap truncating oversized
+ lifecycle bodies (user prompts, notifications, post-compaction summaries)
+ before any scrubbing: the capped field is now scrubbed with the built-in
+ sanitizer first and truncated second — the order `assistant_capture` and
+ the #980 / #1109 fixes established — so a straddling secret can no longer
+ reach the spool (and through it the server) as an unredacted fragment.
+ (#1114)
+ - Fixed the managed-workstream ledger capping event content *before* the
+ sanitizer ever saw it: the 64 KiB per-event cap in
+ `hooks::workstream::sanitize_events` truncated first, so a secret
+ straddling the cutoff was cut into a prefix too short to match any
+ pattern and persisted unredacted in the immutable raw segment — the same
+ ordering bug as the #980 title-hint and #1109 feedback-reason leaks. The
+ cap now runs after scrubbing, the server-generated checkpoint and losses
+ boundary events get the same ordering, and the store's `finish_run`
+ scrubs with the caller's sanitizer before its own 16 KiB bound as
+ defense in depth. The stored shapes and byte limits are unchanged.
+ (#1113)
+ - Fixed SessionEnd replacing the session page an agent wrote itself through
+ `memory_write_page` with `session_id`: the rule-based summary overwrote it
+ on every substantive session end, and the opt-in SessionEnd worker's skip
+ never applied, since it read the page after that overwrite and compared an
+ observation count that the agent's own tool call, the Stop and the
+ SessionEnd always advance. A session page carrying `consolidated_by: agent`
+ is now kept by both, and by the PreCompact and PostCompaction checkpoints,
+ which rewrote it the same way. The write no longer stamps
+ `observation_generation`. (#1138)
+ - Fixed `ai-memory run claude` resuming the launch session forever after a
+ `/clear`: Claude Code continues a cleared conversation in a new session,
+ and the workstream now follows it — the newest one after several clears —
+ so the next launch resumes where the work actually went and that
+ transcript, not the abandoned one, is imported. Only a transcript that
+ records the `/clear` command, names this launch's session as its origin,
+ and stays in this checkout (or a directory below it) is followed. (#1135)
+ - Fixed `ai-memory backfill` failing on every Antigravity CLI session: it and
+ `ai-memory run` now import the session's user prompts from `agy`'s
+ `history.jsonl`, keeping only lines whose conversation and workspace match
+ the checkout. (#1134)
- Fixed the hook spool charging a spooled event's retry budget while the
server was unreachable: an endpoint-level delivery failure (connection
refused, timeout, DNS — the existing `Unreachable` classification) no
diff --cc crates/ai-memory-cli/tests/suite/backfill_e2e.rs
index b4a60b68,36343c4e..7be8d0bb
--- a/crates/ai-memory-cli/tests/suite/backfill_e2e.rs
+++ b/crates/ai-memory-cli/tests/suite/backfill_e2e.rs
@@@ -307,41 -326,149 +337,184 @@@ mod slow
"the re-run must not duplicate the imported session",
);
+ let observations_before = status_json(data_dir.path(), home.path(), &cwd, &base)["counts"]
+ ["observations"]
+ .as_u64()
+ .unwrap();
+ let forced: Value = serde_json::from_str(&run_cli(
+ &[
+ "backfill",
+ "--workspace",
+ WORKSPACE,
+ "--project",
+ PROJECT,
+ "--force",
+ "--json",
+ ],
+ data_dir.path(),
+ home.path(),
+ Some(&cwd),
+ &base,
+ ))
+ .expect("forced replay report");
+ assert_eq!(forced["imported_sessions"], 1);
+ assert_eq!(
+ session_count(&client, &base, WORKSPACE, PROJECT).await,
+ 1,
+ "a real second replay must reuse the session",
+ );
+ let status = status_json(data_dir.path(), home.path(), &cwd, &base);
+ assert!(status["ingest"]["replayed"].as_u64().unwrap_or(0) >= 2);
+ assert!(status["ingest"]["ignored_end"].as_u64().unwrap_or(0) >= 1);
+ assert_eq!(
+ status["counts"]["observations"].as_u64(),
+ Some(observations_before),
+ "the second replay must create no duplicate observations"
+ );
+
drop(server);
}
+
+ const AG_MINE: &str = "a0d5ac62-2501-4780-b783-76d159c56cb3";
+ const AG_THEIRS: &str = "9576275f-7c4e-4709-b372-22d1ad2a0af8";
+ /// Rare, non-secret tokens: a secret-shaped canary would be redacted by the
+ /// sanitizer and could not show a leak from another project.
+ const AG_OWN: &str = "wombatnebulaagyown";
+ const AG_FOREIGN: &str = "pangolinquasaragyforeign";
+ const AG_RESUMED: &str = "ocelotpulsaragyresumed";
+
+ fn push_varint(output: &mut Vec<u8>, mut value: usize) {
+ while value >= 0x80 {
+ output.push(u8::try_from(value & 0x7f).unwrap() | 0x80);
+ value >>= 7;
+ }
+ output.push(u8::try_from(value).unwrap());
+ }
+
+ fn push_bytes_field(output: &mut Vec<u8>, field: u8, value: &[u8]) {
+ output.push((field << 3) | 2);
+ push_varint(output, value.len());
+ output.extend_from_slice(value);
+ }
+
+ /// Plant an `agy` conversation store whose metadata names `workspace`: the
+ /// workspace `file://` URI sits in field 1 of the message in field 1.
+ fn plant_antigravity_conversation(home: &Path, id: &str, workspace: &Path) {
+ let root = home.join(".gemini/antigravity-cli/conversations");
+ fs::create_dir_all(&root).expect("conversations dir");
+ let mut nested = Vec::new();
+ push_bytes_field(
+ &mut nested,
+ 1,
+ format!("file://{}", workspace.display()).as_bytes(),
+ );
+ let mut metadata = Vec::new();
+ push_bytes_field(&mut metadata, 1, &nested);
+ let connection =
+ rusqlite::Connection::open(root.join(format!("{id}.db"))).expect("conversation db");
+ connection
+ .execute_batch(
+ "CREATE TABLE trajectory_metadata_blob (id text DEFAULT \"main\", data blob, PRIMARY KEY (id))",
+ )
+ .expect("metadata table");
+ connection
+ .execute(
+ "INSERT INTO trajectory_metadata_blob (id, data) VALUES ('main', ?1)",
+ [metadata],
+ )
+ .expect("metadata row");
+ }
+
+ fn agy_prompt(id: &str, workspace: &Path, display: &str, millis: i64) -> Value {
+ json!({
+ "display": display,
+ "timestamp": millis,
+ "workspace": workspace.to_string_lossy(),
+ "conversationId": id,
+ })
+ }
+
+ /// `agy` keeps one `history.jsonl` for every project. Backfill imports this
+ /// conversation's prompts from it, in order, and nothing typed in another
+ /// conversation or another directory reaches the store.
+ #[tokio::test]
+ async fn backfill_imports_antigravity_prompts_from_history_and_nothing_foreign() {
+ let data_dir = tempfile::tempdir().expect("data dir");
+ let home = tempfile::tempdir().expect("home");
+ let project = tempfile::tempdir().expect("project cwd");
+ let elsewhere = tempfile::tempdir().expect("other project");
+ let cwd = fs::canonicalize(project.path()).expect("canonicalize project cwd");
+ let other = fs::canonicalize(elsewhere.path()).expect("canonicalize other project");
+ plant_antigravity_conversation(home.path(), AG_MINE, &cwd);
+ plant_antigravity_conversation(home.path(), AG_THEIRS, &other);
+ let past = 1_780_000_000_000;
+ write_jsonl(
+ &home.path().join(".gemini/antigravity-cli/history.jsonl"),
+ &[
+ agy_prompt(AG_MINE, &cwd, &format!("first {AG_OWN} prompt"), past),
+ agy_prompt(
+ AG_THEIRS,
+ &other,
+ &format!("{AG_FOREIGN} elsewhere"),
+ past + 1,
+ ),
+ agy_prompt(AG_THEIRS, &cwd, &format!("{AG_FOREIGN} here"), past + 2),
+ agy_prompt(AG_MINE, &other, &format!("{AG_RESUMED} resumed"), past + 3),
+ agy_prompt(AG_MINE, &cwd, "second prompt", past + 4),
+ ],
+ );
+ let client = reqwest::Client::new();
+ let (server, base) =
+ start_backfill_server(&client, data_dir.path(), home.path(), &cwd).await;
+
+ let report = backfill_report(data_dir.path(), home.path(), &cwd, &base);
+
+ assert_eq!(report["imported_sessions"], 1, "{report}");
+ assert_eq!(report["imported_events"], 2, "{report}");
+ assert_eq!(report["failed_sessions"], 0, "{report}");
+ let hits = call_tool(
+ &client,
+ &base,
+ "memory_query",
+ json!({ "query": AG_OWN, "limit": 10, "workspace": WORKSPACE, "project": PROJECT }),
+ )
+ .await;
+ assert!(
+ hits.contains(AG_OWN),
+ "imported prompt not searchable: {hits}"
+ );
+ assert!(
+ tree_contains(data_dir.path(), AG_OWN).is_some(),
+ "the own prompt must persist, or the absence checks prove nothing",
+ );
+ for foreign in [AG_FOREIGN, AG_RESUMED] {
+ if let Some(path) = tree_contains(data_dir.path(), foreign) {
+ panic!("{foreign} leaked into {}", path.display());
+ }
+ }
+
+ drop(server);
+ }
+
+ /// Without `history.jsonl` the session imports with no events instead of
+ /// failing the whole backfill.
+ #[tokio::test]
+ async fn backfill_succeeds_on_antigravity_without_history() {
+ let data_dir = tempfile::tempdir().expect("data dir");
+ let home = tempfile::tempdir().expect("home");
+ let project = tempfile::tempdir().expect("project cwd");
+ let cwd = fs::canonicalize(project.path()).expect("canonicalize project cwd");
+ plant_antigravity_conversation(home.path(), AG_MINE, &cwd);
+ let client = reqwest::Client::new();
+ let (server, base) =
+ start_backfill_server(&client, data_dir.path(), home.path(), &cwd).await;
+
+ let report = backfill_report(data_dir.path(), home.path(), &cwd, &base);
+
+ assert_eq!(report["imported_sessions"], 1, "{report}");
+ assert_eq!(report["imported_events"], 0, "{report}");
+ assert_eq!(report["failed_sessions"], 0, "{report}");
+
+ drop(server);
+ }
}
diff --cc crates/ai-memory-workstream/src/lib.rs
index c55094e8,b2d7ecff..f5e371f6
--- a/crates/ai-memory-workstream/src/lib.rs
+++ b/crates/ai-memory-workstream/src/lib.rs
@@@ -25,11 -25,10 +25,10 @@@ pub use repository::
RepositoryFingerprints, RepositoryIdentity, inspect_repository, inspect_repository_fingerprints,
};
pub use transcript::{
- AmbiguousNativeSession, ExportedTranscript, NativeSessionCandidate,
- claude_attached_background_session, claude_live_background_attach_id,
- claude_session_ran_in_background, discover_native_session, export_transcript,
- export_transcript_delta, export_transcript_range, kiro_harness_from_source_cursor,
- kiro_v3_resume_uses_default_store, list_native_sessions, native_memory_dir,
- native_session_exists, native_session_in_checkout, native_store_root, transcript_baseline,
- transcript_interval_digests, wait_for_transcript_flush,
+ AmbiguousNativeSession, ClaudeContinuation, ExportedTranscript, NativeSessionCandidate,
+ claude_continued_session, claude_live_background_attach_id, claude_session_ran_in_background,
- discover_native_session, export_transcript, kiro_harness_from_source_cursor,
- kiro_v3_resume_uses_default_store, list_native_sessions, native_memory_dir,
- native_session_exists, native_session_in_checkout, native_store_root,
- wait_for_transcript_flush,
++ discover_native_session, export_transcript, export_transcript_delta, export_transcript_range,
++ kiro_harness_from_source_cursor, kiro_v3_resume_uses_default_store, list_native_sessions,
++ native_memory_dir, native_session_exists, native_session_in_checkout, native_store_root,
++ transcript_baseline, transcript_interval_digests, wait_for_transcript_flush,
};
diff --cc crates/ai-memory-workstream/src/transcript.rs
index 5319748c,b2c01a9f..99178d2e
--- a/crates/ai-memory-workstream/src/transcript.rs
+++ b/crates/ai-memory-workstream/src/transcript.rs
@@@ -21,13 -21,12 +21,19 @@@ use crate::{ManagedHarness, clean_path}
const MAX_SCAN_FILES: usize = 50_000;
const MAX_EVENT_BYTES: usize = 128 * 1024;
+const MAX_SESSION_HEADER_BYTES: usize = 128 * 1024;
+const MAX_SOURCE_RECORD_BYTES: usize = 1024 * 1024;
+const MAX_EXPORTED_EVENTS: usize = 4_096;
+const MAX_EXPORTED_BYTES: usize = 32 * 1024 * 1024;
+const MAX_SOURCE_RECORDS: usize = 32_768;
+const MAX_SOURCE_BYTES: usize = 64 * 1024 * 1024;
+const MAX_SESSION_METADATA_BYTES: u64 = 1024 * 1024;
+ /// `agy` cuts `display` near 8 KiB; 4-byte UTF-8 and JSON escaping stay well
+ /// under this.
+ const MAX_ANTIGRAVITY_HISTORY_LINE_BYTES: usize = 64 * 1024;
+ /// A new conversation's first prompt is logged without an id, within a second
+ /// of its `.db` being created.
+ const ANTIGRAVITY_OPENING_PROMPT_WINDOW: Duration = Duration::from_secs(5);
const LEGACY_MANAGED_WORKSTREAM_PACKET_PREFIX: &str = "> **ai-memory managed workstream:";
/// Checkout-local native session that can seed an otherwise-empty workstream.
@@@ -141,419 -120,21 +148,424 @@@ pub async fn export_transcript
native_session_id: &str,
source_cursor: Option<&str>,
) -> Result<ExportedTranscript> {
- if harness == ManagedHarness::OpenCode {
- return export_opencode(home, session_dir, native_session_id, source_cursor);
- }
- if harness == ManagedHarness::OpenCode2 {
- return export_opencode2(home, session_dir, native_session_id, source_cursor);
- }
- if harness == ManagedHarness::Crush {
- return export_crush(home, cwd, session_dir, native_session_id, source_cursor);
+ let home = home.to_path_buf();
+ let cwd = cwd.to_path_buf();
+ let session_dir = session_dir.map(Path::to_path_buf);
+ let native_session_id = native_session_id.to_owned();
+ let source_cursor = source_cursor.map(str::to_owned);
+ tokio::task::spawn_blocking(move || {
+ export_transcript_blocking(
+ harness,
+ &home,
+ &cwd,
+ session_dir.as_deref(),
+ &native_session_id,
+ source_cursor.as_deref(),
+ None,
+ )
+ })
+ .await
+ .map_err(|error| anyhow!("native transcript reader failed: {error}"))?
+}
+
+fn export_transcript_blocking(
+ harness: ManagedHarness,
+ home: &Path,
+ cwd: &Path,
+ session_dir: Option<&Path>,
+ native_session_id: &str,
+ source_cursor: Option<&str>,
+ final_cursor: Option<&str>,
+) -> Result<ExportedTranscript> {
+ let transcript = if harness == ManagedHarness::OpenCode {
+ export_opencode_range(
+ home,
+ session_dir,
+ native_session_id,
+ source_cursor,
+ final_cursor,
+ )?
+ } else if harness == ManagedHarness::OpenCode2 {
+ export_opencode2_range(
+ home,
+ session_dir,
+ native_session_id,
+ source_cursor,
+ final_cursor,
+ )?
+ } else if harness == ManagedHarness::Crush {
+ export_crush_range(
+ home,
+ cwd,
+ session_dir,
+ native_session_id,
+ source_cursor,
+ final_cursor,
+ )?
+ } else if harness == ManagedHarness::Antigravity {
- return Err(anyhow!(
- "antigravity conversations expose no decodable transcript; this session's events come from hook capture"
- ));
++ // Only user prompts are importable (from `agy`'s history.jsonl); a
++ // bounded recovery range is not supported for this harness.
++ if final_cursor.is_some() {
++ return Err(anyhow!(
++ "antigravity transcripts support no bounded recovery range; this session's events come from hook capture"
++ ));
++ }
++ export_antigravity(home, cwd, session_dir, native_session_id, source_cursor)?
+ } else {
+ let path = locate_session_file(harness, home, cwd, session_dir, native_session_id)?
+ .ok_or_else(|| anyhow!("native transcript for {native_session_id} was not found"))?;
+ export_jsonl_range(
+ harness,
+ &path,
+ native_session_id,
+ source_cursor,
+ final_cursor,
+ )?
+ };
+ validate_export_bounds(transcript)
+}
+
+/// Export only records inside an exact previously captured cursor range.
+/// Both cursor identities are validated against the adapter/session, and rows
+/// or bytes appended after `final_cursor` are never read.
+pub async fn export_transcript_range(
+ harness: ManagedHarness,
+ home: &Path,
+ cwd: &Path,
+ session_dir: Option<&Path>,
+ native_session_id: &str,
+ source_cursor: Option<&str>,
+ final_cursor: &str,
+) -> Result<ExportedTranscript> {
+ let home = home.to_path_buf();
+ let cwd = cwd.to_path_buf();
+ let session_dir = session_dir.map(Path::to_path_buf);
+ let native_session_id = native_session_id.to_owned();
+ let source_cursor = source_cursor.map(str::to_owned);
+ let final_cursor = final_cursor.to_owned();
+ tokio::task::spawn_blocking(move || {
+ if let Some(source_cursor) = source_cursor.as_deref() {
+ validate_transcript_cursor(
+ harness,
+ &home,
+ &cwd,
+ session_dir.as_deref(),
+ &native_session_id,
+ source_cursor,
+ )?;
+ }
+ validate_transcript_cursor(
+ harness,
+ &home,
+ &cwd,
+ session_dir.as_deref(),
+ &native_session_id,
+ &final_cursor,
+ )?;
+ validate_cursor_range(harness, source_cursor.as_deref(), &final_cursor)?;
+ export_transcript_blocking(
+ harness,
+ &home,
+ &cwd,
+ session_dir.as_deref(),
+ &native_session_id,
+ source_cursor.as_deref(),
+ Some(&final_cursor),
+ )
+ })
+ .await
+ .map_err(|error| anyhow!("native transcript range reader failed: {error}"))?
+}
+
+/// Export only records after a cursor previously returned for this exact
+/// adapter/session. Invalid or stale cursors fail closed instead of replaying
+/// the complete transcript.
+pub async fn export_transcript_delta(
+ harness: ManagedHarness,
+ home: &Path,
+ cwd: &Path,
+ session_dir: Option<&Path>,
+ native_session_id: &str,
+ source_cursor: &str,
+) -> Result<ExportedTranscript> {
+ let home = home.to_path_buf();
+ let cwd = cwd.to_path_buf();
+ let session_dir = session_dir.map(Path::to_path_buf);
+ let native_session_id = native_session_id.to_owned();
+ let source_cursor = source_cursor.to_owned();
+ tokio::task::spawn_blocking(move || {
+ validate_transcript_cursor(
+ harness,
+ &home,
+ &cwd,
+ session_dir.as_deref(),
+ &native_session_id,
+ &source_cursor,
+ )?;
+ export_transcript_blocking(
+ harness,
+ &home,
+ &cwd,
+ session_dir.as_deref(),
+ &native_session_id,
+ Some(&source_cursor),
+ None,
+ )
+ })
+ .await
+ .map_err(|error| anyhow!("native transcript delta reader failed: {error}"))?
+}
+
+fn validate_cursor_range(
+ harness: ManagedHarness,
+ source_cursor: Option<&str>,
+ final_cursor: &str,
+) -> Result<()> {
+ if matches!(
+ harness,
+ ManagedHarness::OpenCode | ManagedHarness::OpenCode2 | ManagedHarness::Crush
+ ) {
+ let start = source_cursor
+ .map(serde_json::from_str::<SqlCursor>)
+ .transpose()
+ .context("invalid native transcript SQL cursor")?
+ .unwrap_or_default();
+ let end: SqlCursor = serde_json::from_str(final_cursor)
+ .context("invalid native transcript final SQL cursor")?;
+ if (end.updated, end.id.as_str()) < (start.updated, start.id.as_str()) {
+ return Err(anyhow!(
+ "native transcript final cursor precedes its start cursor"
+ ));
+ }
+ } else if let Some(source_cursor) = source_cursor {
+ let start: FileCursor =
+ serde_json::from_str(source_cursor).context("invalid native transcript file cursor")?;
+ let end: FileCursor = serde_json::from_str(final_cursor)
+ .context("invalid native transcript final file cursor")?;
+ if start.path != end.path || start.flavor != end.flavor || end.offset < start.offset {
+ return Err(anyhow!(
+ "native transcript final cursor precedes or changes its start cursor"
+ ));
+ }
}
- if harness == ManagedHarness::Antigravity {
- return export_antigravity(home, cwd, session_dir, native_session_id, source_cursor);
+ Ok(())
+}
+
+fn validate_transcript_cursor(
+ harness: ManagedHarness,
+ home: &Path,
+ cwd: &Path,
+ session_dir: Option<&Path>,
+ native_session_id: &str,
+ source_cursor: &str,
+) -> Result<()> {
+ if matches!(
+ harness,
+ ManagedHarness::OpenCode | ManagedHarness::OpenCode2 | ManagedHarness::Crush
+ ) {
+ serde_json::from_str::<SqlCursor>(source_cursor)
+ .context("invalid native transcript SQL cursor")?;
+ return Ok(());
}
+ let cursor: FileCursor =
+ serde_json::from_str(source_cursor).context("invalid native transcript file cursor")?;
let path = locate_session_file(harness, home, cwd, session_dir, native_session_id)?
.ok_or_else(|| anyhow!("native transcript for {native_session_id} was not found"))?;
- export_jsonl(harness, &path, native_session_id, source_cursor)
+ if Path::new(&cursor.path) != path || cursor.flavor != file_flavor(harness) {
+ return Err(anyhow!(
+ "native transcript cursor does not match this adapter session"
+ ));
+ }
+ let len = fs::metadata(&path)?.len();
+ if cursor.offset > len {
+ return Err(anyhow!(
+ "native transcript cursor is past the current transcript end"
+ ));
+ }
+ if journal_rewrites_in_place(harness) {
+ let expected = cursor
+ .prefix_sha256
+ .as_deref()
+ .ok_or_else(|| anyhow!("native transcript cursor has no prefix identity"))?;
+ let mut file = File::open(path)?;
+ let actual = hash_file_prefix(&mut file, cursor.offset)?
+ .map(|hasher| format!("{:x}", hasher.finalize()))
+ .ok_or_else(|| anyhow!("native transcript cursor prefix is incomplete"))?;
+ if actual != expected {
+ return Err(anyhow!(
+ "native transcript changed before the recovery cursor"
+ ));
+ }
+ }
+ Ok(())
+}
+
+fn validate_export_bounds(transcript: ExportedTranscript) -> Result<ExportedTranscript> {
+ if transcript.events.len() > MAX_EXPORTED_EVENTS {
+ return Err(anyhow!(
+ "native transcript exceeds the {MAX_EXPORTED_EVENTS} event recovery limit"
+ ));
+ }
+ let mut bytes = 0_usize;
+ for event in &transcript.events {
+ bytes = bytes.saturating_add(serde_json::to_vec(event)?.len());
+ if bytes > MAX_EXPORTED_BYTES {
+ return Err(anyhow!(
+ "native transcript exceeds the {MAX_EXPORTED_BYTES} byte recovery limit"
+ ));
+ }
+ }
+ Ok(transcript)
+}
+
+fn enforce_parse_bounds(
+ events: &[NewWorkstreamEvent],
+ checked_events: &mut usize,
+ event_bytes: &mut usize,
+ source_bytes: &mut usize,
+ source_record_bytes: usize,
+) -> Result<()> {
+ *source_bytes = source_bytes.saturating_add(source_record_bytes);
+ if *source_bytes > MAX_SOURCE_BYTES {
+ return Err(anyhow!(
+ "native transcript exceeds the {MAX_SOURCE_BYTES} source-byte limit"
+ ));
+ }
+ if events.len() > MAX_EXPORTED_EVENTS {
+ return Err(anyhow!(
+ "native transcript exceeds the {MAX_EXPORTED_EVENTS} event recovery limit"
+ ));
+ }
+ for event in &events[*checked_events..] {
+ *event_bytes = event_bytes.saturating_add(serde_json::to_vec(event)?.len());
+ if *event_bytes > MAX_EXPORTED_BYTES {
+ return Err(anyhow!(
+ "native transcript exceeds the {MAX_EXPORTED_BYTES} byte recovery limit"
+ ));
+ }
+ }
+ *checked_events = events.len();
+ Ok(())
+}
+
+/// Capture the exact adapter cursor at the current end of one native session.
+/// Recovery may use it only for that same session and adapter.
+pub async fn transcript_baseline(
+ harness: ManagedHarness,
+ home: &Path,
+ cwd: &Path,
+ session_dir: Option<&Path>,
+ native_session_id: &str,
+) -> Result<String> {
+ let home = home.to_path_buf();
+ let cwd = cwd.to_path_buf();
+ let session_dir = session_dir.map(Path::to_path_buf);
+ let native_session_id = native_session_id.to_owned();
+ tokio::task::spawn_blocking(move || {
+ transcript_baseline_blocking(
+ harness,
+ &home,
+ &cwd,
+ session_dir.as_deref(),
+ &native_session_id,
+ )
+ })
+ .await
+ .map_err(|error| anyhow!("native transcript baseline reader failed: {error}"))?
+}
+
+fn transcript_baseline_blocking(
+ harness: ManagedHarness,
+ home: &Path,
+ cwd: &Path,
+ session_dir: Option<&Path>,
+ native_session_id: &str,
+) -> Result<String> {
+ let sql_cursor = |db: PathBuf, sql: &str| -> Result<String> {
+ let connection = Connection::open_with_flags(
+ &db,
+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
+ )?;
+ let cursor = connection
+ .query_row(sql, params![native_session_id], |row| {
+ Ok(SqlCursor {
+ updated: row.get(0)?,
+ id: row.get(1)?,
+ })
+ })
+ .optional()?
+ .unwrap_or_default();
+ Ok(serde_json::to_string(&cursor)?)
+ };
+ match harness {
+ ManagedHarness::OpenCode => sql_cursor(
+ opencode_db(home, session_dir),
+ "SELECT p.time_updated, p.id FROM part p WHERE p.session_id = ?1 ORDER BY p.time_updated DESC, p.id DESC LIMIT 1",
+ ),
+ ManagedHarness::OpenCode2 => sql_cursor(
+ opencode_db(home, session_dir),
+ "SELECT time_updated, id FROM session_message WHERE session_id = ?1 ORDER BY time_updated DESC, id DESC LIMIT 1",
+ ),
+ ManagedHarness::Crush => sql_cursor(
+ crush_db(home, cwd, session_dir),
+ "SELECT updated_at, id FROM messages WHERE session_id = ?1 ORDER BY updated_at DESC, id DESC LIMIT 1",
+ ),
+ ManagedHarness::Antigravity => Err(anyhow!(
+ "{} does not expose a reliable transcript cursor",
+ harness.as_str()
+ )),
+ _ => {
+ let path = locate_session_file(harness, home, cwd, session_dir, native_session_id)?
+ .ok_or_else(|| {
+ anyhow!("native transcript for {native_session_id} was not found")
+ })?;
+ let mut file = File::open(&path)?;
+ let mut reader = BufReader::new(&mut file);
+ let mut offset = 0_u64;
+ let mut committed_offset = 0_u64;
+ let mut prefix_hasher = Sha256::new();
+ let mut line = Vec::new();
+ let mut records = 0_usize;
+ loop {
+ line.clear();
+ let read = std::io::Read::by_ref(&mut reader)
+ .take((MAX_SOURCE_RECORD_BYTES + 1) as u64)
+ .read_until(b'\n', &mut line)?;
+ if read == 0 {
+ break;
+ }
+ records += 1;
+ if records > MAX_SOURCE_RECORDS {
+ return Err(anyhow!(
+ "native transcript baseline exceeds the {MAX_SOURCE_RECORDS} source-record limit"
+ ));
+ }
+ if read > MAX_SOURCE_RECORD_BYTES {
+ return Err(anyhow!(
+ "native transcript baseline record exceeds the {MAX_SOURCE_RECORD_BYTES} byte limit"
+ ));
+ }
+ offset = offset.saturating_add(read as u64);
+ if offset > MAX_SOURCE_BYTES as u64 {
+ return Err(anyhow!(
+ "native transcript baseline exceeds the {MAX_SOURCE_BYTES} source-byte limit"
+ ));
+ }
+ if !line.ends_with(b"\n") {
+ break;
+ }
+ prefix_hasher.update(&line);
+ committed_offset = offset;
+ }
+ Ok(serde_json::to_string(&FileCursor {
+ path: path.to_string_lossy().into_owned(),
+ offset: committed_offset,
+ flavor: file_flavor(harness),
+ prefix_sha256: journal_rewrites_in_place(harness)
+ .then(|| format!("{:x}", prefix_hasher.finalize())),
+ })?)
+ }
+ }
}
/// New sessions appeared in a store that records no launch identity and none
@@@ -6868,54 -6450,166 +7450,203 @@@ mod tests
assert!(sessions.is_empty());
}
- /// Every step payload is an undocumented protobuf blob, so the ledger for
- /// this harness comes from hook capture. The failure has to say so.
+ #[test]
+ fn transcript_interval_identity_is_ordered_and_semantic() {
+ let event = |id: &str, role: &str, timestamp: &str, content: &str| NewWorkstreamEvent {
+ event_id: id.into(),
+ agent: AgentKind::ClaudeCode,
+ native_session_id: "session".into(),
+ source_record_id: None,
+ kind: WorkstreamEventKind::Message,
+ role: Some(role.into()),
+ content: content.into(),
+ occurred_at: Some(timestamp.into()),
+ metadata: json!({}),
+ };
+ let first = event("one", "user", "2026-10-07T10:00:00Z", "hello");
+ let second = event("two", "assistant", "2026-10-07T10:00:01Z", "world");
+ let expected = transcript_interval_digests(&[first.clone(), second.clone()]);
+ assert_eq!(
+ transcript_interval_digests(&[first.clone(), second.clone()]),
+ expected
+ );
+ assert_ne!(
+ transcript_interval_digests(&[second.clone(), first.clone()]),
+ expected,
+ "row order is part of interval identity"
+ );
+ for changed in [
+ event("one", "assistant", "2026-10-07T10:00:00Z", "hello"),
+ event("one", "user", "2026-10-07T10:00:02Z", "hello"),
+ event("one", "user", "2026-10-07T10:00:00Z", "changed"),
+ ] {
+ assert_ne!(
+ transcript_interval_digests(&[changed, second.clone()]),
+ expected
+ );
+ }
+ }
+
- #[tokio::test]
- async fn antigravity_transcript_export_explains_why_it_is_unavailable() {
+ const AG_MINE: &str = "a0d5ac62-2501-4780-b783-76d159c56cb3";
+ const AG_THEIRS: &str = "9576275f-7c4e-4709-b372-22d1ad2a0af8";
+ /// Far from any fixture `.db` creation time, so unlabelled lines at this
+ /// time are never opening-prompt candidates.
+ const AG_PAST: i64 = 1_780_000_000_000;
+
+ struct AntigravityFixture {
+ temp: tempfile::TempDir,
+ root: PathBuf,
+ cwd: PathBuf,
+ other: PathBuf,
+ }
+
+ /// A fake home holding this checkout's conversation `AG_MINE`.
+ fn antigravity_fixture() -> AntigravityFixture {
let temp = tempfile::TempDir::new().unwrap();
+ let root = temp.path().join(".gemini/antigravity-cli/conversations");
+ let cwd = temp.path().join("checkout");
+ let other = temp.path().join("elsewhere");
+ for dir in [&root, &cwd, &other] {
+ fs::create_dir_all(dir).unwrap();
+ }
+ write_antigravity_conversation(&root, AG_MINE, &file_uri(&cwd));
+ AntigravityFixture {
+ temp,
+ root,
+ cwd,
+ other,
+ }
+ }
+
+ fn history_line(id: Option<&str>, workspace: &Path, display: &str, millis: i64) -> String {
+ let mut line = json!({
+ "display": display,
+ "timestamp": millis,
+ "workspace": workspace.to_string_lossy(),
+ });
+ if let Some(id) = id {
+ line["conversationId"] = json!(id);
+ }
+ line.to_string()
+ }
+
+ fn write_antigravity_history(root: &Path, lines: &[String]) {
+ let mut body = lines.join("\n");
+ body.push('\n');
+ fs::write(root.parent().unwrap().join("history.jsonl"), body).unwrap();
+ }
+
+ async fn export_antigravity_fixture(
+ fixture: &AntigravityFixture,
+ cursor: Option<&str>,
+ ) -> ExportedTranscript {
+ export_transcript(
+ ManagedHarness::Antigravity,
+ fixture.temp.path(),
+ &fixture.cwd,
+ None,
+ AG_MINE,
+ cursor,
+ )
+ .await
+ .unwrap()
+ }
+
+ fn prompts(exported: &ExportedTranscript) -> Vec<&str> {
+ exported
+ .events
+ .iter()
+ .map(|event| {
+ assert_eq!(event.role.as_deref(), Some("user"));
+ assert_eq!(event.agent, AgentKind::AntigravityCli);
+ event.content.as_str()
+ })
+ .collect()
+ }
+
+ /// `history.jsonl` holds every conversation of every workspace. Only this
+ /// conversation's prompts typed in this checkout may come out.
+ #[tokio::test]
+ async fn antigravity_history_exports_only_this_conversations_prompts_in_this_workspace() {
+ let fixture = antigravity_fixture();
+ let (cwd, other) = (&fixture.cwd, &fixture.other);
+ write_antigravity_history(
+ &fixture.root,
+ &[
+ history_line(Some(AG_MINE), cwd, "own first", AG_PAST),
+ history_line(Some(AG_THEIRS), cwd, "canary-same-workspace", AG_PAST + 1),
+ history_line(
+ Some(AG_THEIRS),
+ other,
+ "canary-other-workspace",
+ AG_PAST + 2,
+ ),
+ history_line(None, other, "canary-unlabelled", AG_PAST + 3),
+ history_line(Some(AG_MINE), cwd, "own second", AG_PAST + 4),
+ ],
+ );
+
+ let exported = export_antigravity_fixture(&fixture, None).await;
+
+ assert_eq!(prompts(&exported), ["own first", "own second"]);
+ assert!(
+ !exported
+ .losses
+ .iter()
+ .any(|loss| loss.contains("another workspace")),
+ "other conversations are not this session's losses: {:?}",
+ exported.losses
+ );
+ }
+
+ /// `agy --conversation=<id>` run from another directory keeps the id but
+ /// records that directory, so the id alone must not admit the line.
+ #[tokio::test]
+ async fn antigravity_history_drops_prompts_from_a_resumed_conversation_in_another_workspace() {
+ let fixture = antigravity_fixture();
+ write_antigravity_history(
+ &fixture.root,
+ &[
+ history_line(Some(AG_MINE), &fixture.other, "canary-resumed", AG_PAST),
+ history_line(Some(AG_MINE), &fixture.cwd, "own", AG_PAST + 1),
+ ],
+ );
+
+ let exported = export_antigravity_fixture(&fixture, None).await;
+
+ assert_eq!(prompts(&exported), ["own"]);
+ assert!(
+ exported
+ .losses
+ .iter()
+ .any(|loss| loss.contains("another workspace")),
+ "{:?}",
+ exported.losses
+ );
+ }
+
+ /// The conversation itself must belong to this checkout before any
+ /// history line is read, even when the history names this checkout.
+ #[tokio::test]
+ async fn antigravity_export_rejects_a_conversation_from_another_workspace() {
+ let fixture = antigravity_fixture();
+ write_antigravity_conversation(&fixture.root, AG_THEIRS, &file_uri(&fixture.other));
+ write_antigravity_history(
+ &fixture.root,
+ &[history_line(
+ Some(AG_THEIRS),
+ &fixture.cwd,
+ "canary",
+ AG_PAST,
+ )],
+ );
+
let error = export_transcript(
ManagedHarness::Antigravity,
- temp.path(),
- temp.path(),
+ fixture.temp.path(),
+ &fixture.cwd,
None,
- "a0d5ac62-2501-4780-b783-76d159c56cb3",
+ AG_THEIRS,
None,
)
.await
diff --cc docs/security-boundaries.md
index 416a330b,44fe8127..f824388b
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@@ -72,13 -72,13 +72,14 @@@ boundary not yet built
| 11f | Native hook executable-path integrity after self-replacement (#1027) | `ai-memory-cli/src/commands/render_shared.rs` `hook_embedded_exe_path` is the single executable resolver for every persisted native hook form (POSIX/Windows command, Windows exec, Zero, ZCode, OpenCode 2 assistant capture): it prefers an existing literal path, strips Linux's trailing ` (deleted)` procfs marker only when the stripped installed binary exists, and otherwise falls back to the platform command name. Upgrade keeps the already-loaded config and refreshes in-process | `render_shared.rs` `embedded_exe_strips_the_marker_when_the_stripped_path_exists`, `embedded_exe_preserves_a_real_file_whose_name_has_the_marker_suffix`, `embedded_exe_falls_back_when_the_resolved_path_is_missing`, `hook_embedded_exe_path_names_an_existing_file_without_marker`; `upgrade_e2e.rs` `native_upgrade_refreshes_hooks_without_a_deleted_path_or_losing_cli_data_dir` reproduces the replacement window through the shipped binary, plants the corrupt suffix, and proves refresh removes it while preserving a CLI-only data dir | STRONG on Linux reproduction plus platform-neutral resolver/render coverage; Windows path rendering remains covered by its existing command/exec tests and full Windows CI |
| 11g | Cross-project file attribution cannot bypass destination capture or server routing (#932) | `ai-memory-hooks/src/capture_policy.rs` `absolute_file_tool_paths` accepts only bounded, recognized, absolute file-tool candidates; `ai-memory-cli/src/commands/hook.rs` `file_tool_routing_cwd` requires every path to prove the same repository/marker boundary and resolves that destination before capture policy, server profile, scope hints, or spool credentials. Relative, mixed-project, unsupported, and arbitrary non-project paths keep the payload cwd | `hook.rs` `absolute_file_target_uses_destination_scope_and_capture_policy` (hostile content under the destination exclusion is never spooled; a public control is routed there), `absolute_file_target_cannot_escape_a_destination_server_profile` (unregistered destination profile drops instead of falling back to source/install default), `file_target_routing_refuses_relative_external_and_mixed_project_paths` | STRONG for native `ai-memory hook`; generated and compatibility hooks retain cwd-only routing |
| 11h | Docker-wrapper capture-policy capability (#1002) | `bin/ai-memory` routes ordinary Linux/macOS `install-hooks` and upgrade refreshes through the stable checksum-verified native host client, so the hook process executes the capture-policy boundary in 11b before spool/network. Only an explicit `AI_MEMORY_HOOK_PLATFORM=posix|windows` retains the documented script compatibility path and its warning; `AI_MEMORY_NATIVE_BIN` may not point back to the wrapper | `scripts/check-native-packaging.sh` `Checking host-launch wrapper routing`: a default allowlist install reaches the fake native client while a Docker executable that always fails proves no container fallback occurred; the explicit `posix` control reaches fake Docker and adds no native invocation; the self-referential native override is refused | STRONG on the shipped Linux/macOS wrapper. Windows and remote/manual script installers remain explicitly outside capture-policy v1 |
+| 11j | Offline recovery journal and transcript replay | `ai-memory-cli/src/commands/recovery.rs` keeps bounded locators, ordered semantic transcript digests, pre-launch cursors and persistent correlated-delivery/loss evidence in an atomic journal, refuses symlinked path components, sanitizes/caps failure reasons, and bounds each replay plus the whole pass; `hook_spool` coordinates enqueue and quarantine with short filesystem locks, canonically resolves partial scope from the recorded cwd, bounds per-file reads and current global occupancy across the main spool and recovery directories, sweeps completed tombstones, and holds correlated events outside drain until replay succeeds or restores them on failure; degraded resumes use `ai-memory-workstream`'s adapter-validated delta export, whose blocking parse and baseline scans are capped by record, event-count, source-byte and serialized-byte totals; `backfill::import_exact_session` chunks by item and byte limits and requires per-item durable acknowledgements; `run.rs` journals every session launch, including explicit spool-only evidence for unsupported exporters, and journals a resumed export only after capturing its exact pre-launch cursor; `workstream.rs` `/recover/finish` retains owner/project authorization, rejects superseded runs, and validates a finished retry by durable transcript/native/cursor/exit identity without regenerating its checkpoint; validated recovery ingest keys bind session, agent, event kind and sanitized event identity until session purge | `transcript.rs` `persisted_baseline_exports_only_offline_append_and_rejects_rewrite`, parser/baseline cap and ordered-semantic digest tests; CLI `run_offline.rs` real degraded spool-only and overlap/idempotency tests; `recovery.rs` `spool_only_without_correlated_evidence_never_auto_clears`, `a_dropped_spool_event_stays_lost_on_the_next_empty_pass`, loss/time-budget tests; `hook_spool.rs` partial-scope late enqueue, completion-race, occupancy churn/active-cap, bounded-read and tombstone-sweep tests, plus interval isolation (`completed_tombstone_keeps_a_later_resume_of_the_same_session` proves a post-interval resume hook is delivered, `completing_one_recovery_interval_leaves_the_other_intervals_entries_intact` proves one interval's completion never consumes another's evidence and ambiguous entries fail closed into the main spool); `backfill.rs` `two_sequential_recovery_intervals_on_one_resumed_session_replay_exactly_once` proves the second interval's content and session-end are stored with end-of-session effects while reruns stay pure replays; `transcript.rs` `an_oversized_first_record_is_skipped_by_session_listing_caps` proves the first-record byte caps bite before allocation; store `insert_observation_ingest_dedups_on_key` rejects cross-session and changed-event preclaims; hooks `expired_run_recovery_is_owner_only_and_refuses_superseded_runs` proves changed transcript refusal and changed-checkpoint no-op | STRONG on Unix integration coverage; Unix lock opens use no-follow and atomic replacement rechecks the destination. Windows owner-only ACL/reparse and lock semantics require the PR `windows` lane |
| 11i | OpenCode executable probing and generated-config cleanup (#1097) | `ai-memory-cli/src/config.rs` captures the full process environment once in typed `RuntimeEnv`; `run.rs` overlays explicit `run --env` values with platform key semantics and uses that same effective environment for executable resolution, probing, and launch without rereading process environment; `opencode_dialect.rs` invokes only direct argv `--version`, caps output and time, and rejects malformed/future majors. Automatic launch skips only OpenCode on probe failure; explicit OpenCode fails. `install_hooks.rs` quarantines the incompatible sibling before reading its exact ownership markers, restores unowned content with an atomic no-replace link, and never deletes or overwrites a concurrent replacement; `install_mcp.rs` owns the shared dual-schema endpoint/token inference used by both installers, rejects conflicting generated V1/V2 entries before mutation, and migrates an alternate-major entry only when endpoint, generated shape, and absent-or-Authorization-only headers match, preserving custom headers and ambiguous entries; auto-wire migrates MCP before hooks infer from that exact config path and skips hook mutation when transition preflight fails | `run.rs` `automatic_opencode_probe_failure_keeps_another_harness_available`, `opencode_executable_probe_selects_v2_for_launch_and_autowire`, effective-child-environment PATH casing controls, fake V1/V2/env-derived-major/malformed/future/timeout executable tests, `setup-agent` V1/V2 no-probe integration controls; `install_hooks.rs` `opencode_plugin_cleanup_removes_only_exact_owned_incompatible_sibling`, `opencode_plugin_cleanup_preserves_a_concurrent_user_replacement`, `opencode_plugin_restore_moves_quarantine_when_destination_is_free`, `opencode_plugin_restore_preserves_an_existing_replacement`, `opencode_plugin_restore_does_not_replace_a_file_created_at_restore_window`, `opencode_plugin_cleanup_does_not_escape_custom_target_directory`; `install_mcp.rs` `opencode_install_reuses_owned_endpoint_and_token_across_major_transitions`, `opencode_install_refuses_conflicting_owned_transition_entries`, `opencode_install_does_not_infer_from_a_user_owned_transition_entry`, `opencode_mcp_migration_moves_only_owned_alternate_shape`, `opencode_mcp_migration_preserves_ambiguous_user_entry`, `opencode_mcp_migration_preserves_custom_headers`, `opencode_mcp_migration_accepts_only_historical_generated_headers` | STRONG for Unix process probes and platform-neutral ownership gates; exact Windows executable resolution remains covered by `run.rs` resolver tests and requires the PR `windows` label |
| 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer`; `serve.rs` mounts `/identity` inside the host and machine-auth gates even with web disabled; `nix/nixos-module.nix` treats only literal `127.0.0.1`/`::1` as loopback, requires exactly one secret environment source for other binds, keeps secret auth and `llm_headers` values out of the Nix store, and brackets IPv6 in `ExecStart` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401; `serve.rs` `machine_identity_remains_authenticated_with_web_disabled_and_expired_keys` (wrong and expired keys refused, valid machine key accepted, web remains disabled); `flake.nix` `nixos-module-eval` refuses `localhost` and `0.0.0.0` without a secret source, refuses two secret sources, `settings.auth` secrets, and `settings.llm_headers`, with literal IPv4/IPv6 loopback and one-source controls | STRONG |
- | 12b | Managed-workstream provenance privacy, stable replay identity and server event namespace | `ai-memory-core/src/workstream.rs` `scrub_workstream_provenance`; `ai-memory-hooks/src/workstream.rs` `finish_run` reserved client-id check and `sanitize_events` before immutable segments; `ai-memory-store/src/workstream.rs` `finish_run` stable identity check and `stored_event`, using an explicitly supplied configured sanitizer; no changes to the typed observation boundary | `store/tests/suite/workstream_provenance.rs` `workstream_provenance_is_bounded_scrubbed_and_idempotent_before_storage` (hostile and oversized source ids, unknown metadata, legitimate correlation, retry and distinct event ids), `workstream_provenance_legacy_reads_strip_secrets_and_unknown_metadata` (search and tail, malformed/oversized legacy JSON), `workstream_provenance_reused_event_id_retains_data_and_refuses_identity_change` (first indexed version retained, identity refusal and batch rollback), `workstream_provenance_replay_survives_sanitizer_changes` (new extra patterns and removal of a built-in-pattern allowlist exemption, with identity-refusal control), `workstream_provenance_replay_preserves_legacy_rows_above_bounds`, `workstream_provenance_finished_run_ignores_late_events`, `workstream_provenance_retry_with_marker_matching_pattern_is_idempotent`; `hooks` `workstream_provenance_finish_scrubs_before_raw_segment_and_search` (custom sanitizer, immutable segment, SQL recovery and finished-run no-op), `workstream_provenance_client_cannot_use_server_event_ids` (reserved ids refused before raw writes, normal client event and server-generated checkpoint/loss controls); `cli/tests/suite/workstream_provenance.rs` (text/JSON and old server DTOs) | STRONG: privacy, stable-identity and reserved-namespace regressions fail with their guards bypassed; an isolated allowlist bypass fails on the unknown key, and bypassing the raw-id search authorization returns 200 where its test requires 403. No provenance is emitted in startup packets, and old raw segments are not rewritten |
- | 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), never falls back to a link it set aside, and turns an `AmbiguousNativeSession` into a warning with nothing imported; for Claude it moves the run's own session to a background session only when `ai-memory-workstream` `claude_attached_background_session` finds a `sessionKind: "bg"` record that names that exact session as its attached client and this checkout as `cwd` (#1050); `ai-memory-workstream/src/transcript.rs` `discover_crush` claims only the one top-level session created (or, with `--continue`, touched) during the run, and in a data directory outside the project only one that edited a file in it | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `claude_attached_background_session_follows_only_this_checkouts_bg_records` (a concurrent launch's background session, another checkout's, and a non-background record refused; own attachment control); `run.rs` `a_claude_run_that_attached_to_a_background_session_follows_it`; `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run`; `run.rs` `ambiguous_crush_discovery_keeps_the_run`; `transcript.rs` `crush_discovery_claims_only_the_session_the_run_created`, `crush_discovery_in_a_shared_store_claims_only_an_edit_here` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout; Crush, which has no hooks, relies on that discovery alone and claims nothing when it is ambiguous |
+ | 12b | Managed-workstream provenance privacy, stable replay identity and server event namespace | `ai-memory-core/src/workstream.rs` `scrub_workstream_provenance`; `ai-memory-hooks/src/workstream.rs` `finish_run` reserved client-id check and `sanitize_events` before immutable segments, with `sanitize_events` and `append_boundary_events` scrubbing event/checkpoint/losses content *before* the 64 KiB cap so a cap-straddling secret is never cut into an unmatchable prefix (#1113); `ai-memory-store/src/workstream.rs` `finish_run` stable identity check and `stored_event`, scrubbing content with the explicitly supplied configured sanitizer before its 16 KiB store-boundary bound; no changes to the typed observation boundary | `store/tests/suite/workstream_provenance.rs` `workstream_provenance_is_bounded_scrubbed_and_idempotent_before_storage` (hostile and oversized source ids, unknown metadata, legitimate correlation, retry and distinct event ids), `workstream_provenance_legacy_reads_strip_secrets_and_unknown_metadata` (search and tail, malformed/oversized legacy JSON), `workstream_provenance_reused_event_id_retains_data_and_refuses_identity_change` (first indexed version retained, identity refusal and batch rollback), `workstream_provenance_replay_survives_sanitizer_changes` (new extra patterns and removal of a built-in-pattern allowlist exemption, with identity-refusal control), `workstream_provenance_replay_preserves_legacy_rows_above_bounds`, `workstream_provenance_finished_run_ignores_late_events`, `workstream_provenance_retry_with_marker_matching_pattern_is_idempotent`, `workstream_content_is_scrubbed_before_the_store_cap` (a credential straddling the 16 KiB store cap is redacted, not persisted as an unmatchable prefix; benign control verbatim; #1113); `hooks` `workstream_provenance_finish_scrubs_before_raw_segment_and_search` (custom sanitizer, immutable segment, SQL recovery and finished-run no-op), `workstream_provenance_client_cannot_use_server_event_ids` (reserved ids refused before raw writes, normal client event and server-generated checkpoint/loss controls), `finish_run_scrubs_event_content_before_the_byte_cap` and `finish_run_scrubs_boundary_events_before_the_byte_cap` (a credential straddling the 64 KiB event cap is redacted in the raw segment and never reaches the index; checkpoint/losses and benign controls; #1113); `cli/tests/suite/workstream_provenance.rs` (text/JSON and old server DTOs) | STRONG: privacy, stable-identity and reserved-namespace regressions fail with their guards bypassed; an isolated allowlist bypass fails on the unknown key, and bypassing the raw-id search authorization returns 200 where its test requires 403. No provenance is emitted in startup packets, and old raw segments are not rewritten |
+ | 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), never falls back to a link it set aside, and turns an `AmbiguousNativeSession` into a warning with nothing imported; for Claude it moves the run's own session to a background session only when `ai-memory-workstream` `claude_continued_session` finds a `sessionKind: "bg"` record that names that exact session as its attached client and this checkout as `cwd` (#1050), and to a `/clear`ed session only when that session's own transcript records the `/clear` command and names the run's session as its launch `session_id` from this checkout or below it; `ai-memory-workstream/src/transcript.rs` `discover_crush` claims only the one top-level session created (or, with `--continue`, touched) during the run, and in a data directory outside the project only one that edited a file in it | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `claude_continued_session_follows_only_this_checkouts_bg_records` (a concurrent launch's background session, another checkout's, and a non-background record refused; own attachment control); `transcript.rs` `claude_continued_session_follows_only_this_launchs_clear` (an uncleared transcript, a quoted `/clear`, another checkout's clear, a concurrent launch's clear, a subagent file, and a pre-run clear refused; own clear and the newest of two as controls); `run.rs` `a_claude_run_that_attached_to_a_background_session_follows_it`, `a_claude_run_that_was_cleared_follows_the_new_session`; `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run`; `run.rs` `ambiguous_crush_discovery_keeps_the_run`; `transcript.rs` `crush_discovery_claims_only_the_session_the_run_created`, `crush_discovery_in_a_shared_store_claims_only_an_edit_here` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout; Crush, which has no hooks, relies on that discovery alone and claims nothing when it is ambiguous |
| 13a | Managed Codex stale-daemon run recovery (#987; concurrent launches, project/worktree isolation, operator isolation) | `managed_runs.owner_user` (V71) uses the topology-aware `IdentityKey` owner stamp; `router.rs` resolves and authorizes the SessionStart repository before handling the untrusted run id; store `link_or_adopt_native_session` selects and links in one writer transaction and admits only the sole live, undelivered, never-linked Codex run in the exact workspace/project/checkout-cwd/owner bucket. An active supplied id must itself match every boundary; another harness, an ambiguity, or a second native session is refused | `multi_session.rs` `stale_codex_run_recovery_cannot_cross_project_owner_or_session_boundaries` (foreign owner, foreign checkout, and cross-project candidates refused; project-local controls and racing rebind), `stale_codex_run_recovery_fails_closed_on_ambiguity_and_active_mismatch` (two candidates and active foreign id refused, exact control); `workstream.rs` `prepare_stamps_the_operator_bucket_used_by_session_start_recovery` (HTTP actor stamp with foreign and legitimate controls); `router.rs` `managed_session_start_delivers_ledger_and_pending_handoff` supplies a finished stale id and proves the new run is linked and delivered | STRONG for SessionStart recovery. No candidate is selected from a run id's stale scope, another checkout, or another operator bucket; ambiguity deliberately falls back to no managed packet |
| 13b | Managed-run lease exclusivity and explicit recovery (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and otherwise refuses an `active` run inside the writer transaction (`StoreError::WorkstreamBusy`). The explicit `force_unlock` path may expire and replace that row in the same transaction only when its durable `owner_user` equals the incoming actor's attribution; different operators remain isolated. `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` normally uses `wait_out_held_lease`; `--force-unlock` instead asks once and fails immediately when refused. Neither path treats the informational `lease_owner` label as authority | `multi_session.rs` `force_unlock_replaces_only_the_same_operators_active_run` (foreign operator refused with live control, same operator succeeds, old run loses heartbeat, unattributed single-user control); hooks `workstream.rs` `force_unlock_cannot_evict_another_operator` exercises the HTTP actor boundary; CLI `run.rs` `force_unlock_asks_once_instead_of_waiting_out_the_lease`; existing controls `managed_workstream_batches_are_idempotent_and_release_the_lease`, `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over`, `interactive_launch_waits_out_a_lapsing_lease_then_proceeds`, and `ctrl_c_aborts_the_held_lease_wait_immediately` | STRONG for exclusivity. The `lease_owner` label (`host:pid`) is informational only and not unique inside ai-jail (every jailed launcher reports `ai-sandbox:<ns-pid>`), so it must never become an ownership key. A shared unattributed/root context is intentionally one operator bucket; deployments needing person-level refusal must authenticate DB users |
+ | 13c | A native store shared by every project yields only this checkout's records (Antigravity `history.jsonl`) | `ai-memory-workstream/src/transcript.rs` `export_antigravity` — the conversation must first pass `locate_session_file` (UUID file name + `.db` workspace == `cwd`); every `history.jsonl` line must match both that `conversationId` and, by `same_path`, this `cwd` (a conversation resumed in another directory keeps its id but records that directory, so the id alone is not enough); an id-less opening prompt is attributed only when exactly one same-workspace candidate falls within 5 s of the `.db` creation time and no other conversation of this checkout was created within 5 s of it; slash/shell entries and oversized lines are dropped, and only records naming this conversation are reported as its losses | `transcript.rs` `antigravity_history_exports_only_this_conversations_prompts_in_this_workspace` (other conversation in this and another workspace refused; own control passes), `antigravity_history_drops_prompts_from_a_resumed_conversation_in_another_workspace` (same id, foreign workspace refused), `antigravity_export_rejects_a_conversation_from_another_workspace`, `antigravity_export_rejects_unknown_or_traversal_ids`, `antigravity_opening_prompt_is_refused_when_another_conversation_started_with_it` (an opener another conversation of this checkout could own is refused), `antigravity_opening_prompt_covers_a_single_prompt_conversation` (control), `antigravity_history_reports_no_losses_for_foreign_records`; `backfill_e2e.rs` `backfill_imports_antigravity_prompts_from_history_and_nothing_foreign` (foreign prompts absent from wiki and db) | STRONG |
| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard; incremental `recent` resolves and authorizes the requested project before decoding its scope-bound cursor; batch outcomes do not bypass the capture grant or session owner check | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository` (foreign raw workstream id refuses populated provenance; granted reader receives the source record and tool correlation); `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (18 tests) or the SQL filter (9 tests) neutralized; `routes.rs` `api_recent_incremental_rechecks_restricted_scope_on_cursor` (a valid cursor cannot bypass a revoked grant; granted control passes), `api_recent_incremental_paginates_over_120_pages_and_binds_cursor`; `mcp_stateless_http.rs` `generic_machine_client_writes_queries_and_claims_a_handoff` (real machine key, foreign scope and partial scope refused); `router.rs` `an_unauthorized_batch_item_is_consumed_rather_than_retried`, `batch_acknowledges_foreign_collision_then_commits_next_item` (refused foreign item followed by a legitimate stored item) | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them |
| 14aa | Companion capture privacy before persistence and delivery | `companions/ai-memory-client/src/lib.rs` `reject_sensitive`, `sanitize_external_value`, `check_body`; `src/scrub.rs` `sanitize_external_text`; relay `identity::validate`, `check_scope`, `relay::init` and `flush_locked`; importer `plan_external_conversation`, `planned_hook_event`, `truncate_utf8`, `ImportClient::post_hook_batch` | SDK secret-position, nested key, numeric metric (11 names plus numeric `*_tokens` counts; string values still redact), bounded schema and literal-marker tests; relay `sensitive_envelope_is_rejected_before_enqueue_with_clean_control`, `new_native_bodies_are_sanitized_before_hash_enqueue_and_exact_retry`, `unsafe_legacy_pending_is_dropped_locally_and_never_blocks_its_session`, `unsafe_legacy_native_identity_is_dropped_and_its_session_continues`, `legacy_binding_scope_spaces_are_preserved_on_delivery`; importer `sensitive_native_identity_is_refused_before_manifest_and_http_with_unicode_control`, `shared_key_sanitation_precedes_plan_manifest_transport_and_exact_retry`, `preview_and_manifest_use_scrubbed_bodies_and_digest`, `forged_body_authority_is_refused_before_transport`, `sanitized_redaction_markers_survive_utf8_byte_caps_in_bodies_and_titles`. Controls preserve opaque native Unicode IDs, metric representation and untrusted provenance. An unsafe item queued before these checks never reaches the wire (body or request line); it leaves the queue as a local `dropped_policy` receipt so the rest of its session ships. Guard-removal runtime probes target the final formatted sources and restore identical hashes. | Client-side privacy only; server scope, auth, admission and capture-policy guards remain authoritative |
| 14ap | Managed-run mutation owner and current project access (finish, cancel, heartbeat, native-session link, context acceptance) | `hooks/src/workstream.rs` `authorize_run_owner` derives `ManagedRunAuthority` only from authenticated middleware extensions and checks the real run before any mutation — for finish before status/payload/segment handling; cancel, heartbeat, link and context acceptance go through the same helper, so none is a side door around finish's rule; `ReaderPool::authorize_managed_run` and `store/src/workstream.rs` `authorize_run_mutation` use a read snapshot and the existing writer transaction, respectively. Strict resolution (`project_authz.rs` `resolve_project_authz_strict`, the canonical decision with a fail-closed resolution mode, so the reserved global-scope write gate applies here too) requires the actual workspace/project pair, current user existence and current Write decision for DB principals. The private trusted-proxy policy requires authenticated User capability, a canonical identity, no DB principal and server proxy configuration; it retains legacy project admission after strict scope validation, with ownership still enforced. Human-login disable does not revoke API keys. The legacy resolver and auth middleware remain unchanged. Both writer entry paths, including finished retries, require the same authority; no cross-owner bypass | MCP `auth.rs` `owner_finish_http_refuses_another_writer_before_payload_or_segment`, `owner_finish_http_trusted_proxy_preserves_restricted_lifecycle`, `owner_finish_http_active_api_key_survives_disabled_human_login`; store `multi_session.rs` `owner_finish_store_refuses_another_writer_including_finished_retry`, `owner_finish_store_rechecks_write_after_preflight`, `owner_finish_store_refuses_a_deleted_user_after_preflight`, `owner_finish_store_proxy_policy_requires_server_and_authenticated_identity`, `owner_finish_store_raw_ids_use_the_actual_project_and_workspace`, `owner_finish_store_topology_reload_and_phase_controls`, `owner_finish_store_strict_resolution_refuses_pairing_missing_and_sql_failure`, `owner_finish_store_keeps_qualified_identity_namespaces`; hooks `workstream.rs` `owner_finish_revocation_between_preflight_and_both_writer_paths`; MCP `auth.rs` `owner_finish_http_real_auth_rungs_shared_and_project_controls`, `owner_finish_http_preserves_late_active_terminal_and_missing_phases`; hooks `workstream.rs` `run_mutation_routes_refuse_another_operator` (another operator and root under another identity refused on heartbeat/link/accept/cancel, run left active; owner admitted); store `project_authz.rs` `strict_resolution_shares_the_global_gate_and_fails_closed_on_a_gap`. Guard-neutralization recipes and results accompany the local frozen patch | SQL refusal is atomic within finish's writer transaction; a revocation after preflight can leave an unindexed raw segment. Cancel, heartbeat, link and acceptance check one read snapshot immediately before a single-row update (a run's owner never changes). A later hook event carrying `AI_MEMORY_RUN_ID` links its native session only through `link_native_session_in_scope`, which applies the SessionStart boundary (`ManagedRunBoundaryRow::admits`: the run's own project and operator) and refuses a foreign run id while the event itself is still captured (`router.rs` `hook_event_links_a_managed_run_only_from_its_operator`, `hook_event_in_another_project_does_not_link_the_run`, control `hook_event_links_a_shared_run_on_a_single_operator_server`; #1082). Shared NULL ownership, trusted-proxy project admission and late still-active finishes remain intentional |