Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(workstream): resume a linked Codex session after Codex compresses it
Éverton Toffanettod2a8c4c00882
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c6a02aca..b8573114 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,14 @@ version in [`docs/changelog/`](docs/changelog/):### Fixed+- `ai-memory run codex` no longer starts a new session when Codex has+ compressed the linked rollout. Codex keeps a rollout it has not written for+ a week as `rollout-*.jsonl.zst`, which the launcher did not recognize, so it+ reported the session as missing and repointed the workstream to a fresh one.+ The compressed copy is now read for the resume, the pre-launch baseline and+ the transcript import, and the plain file wins when both exist. `backfill`+ and the session listings see compressed Codex sessions too (#1653).+- `ai-memory user list` and `ai-memory api-key list` now size their columnsby terminal display width rather than bytes, as `list-projects` and thegrants tables already do. An accented username, display name or key labeldiff --git a/Cargo.lock b/Cargo.lockindex 31e682e3..0d895be5 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -66,6 +66,7 @@ dependencies = ["rstest","rusqlite","rustls",+ "ruzstd","secrecy","serde","serde_json",@@ -348,6 +349,7 @@ dependencies = ["jiff","libc","rusqlite",+ "ruzstd","serde","serde_json","sha2",@@ -3512,6 +3514,12 @@ version = "1.0.22"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"+[[package]]+name = "ruzstd"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69e4ce4a039f42bf25920b95667e4d789e98749ab11bbb8d2c2936f788421bb5"+[[package]]name = "ryu"version = "1.0.23"diff --git a/Cargo.toml b/Cargo.tomlindex 4f0789aa..b4c956e0 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -161,6 +161,13 @@ flate2 = "1"# covers PowerShell Compress-Archive release zips and Stored test fixtures.zip = { version = "8.6", default-features = false, features = ["deflate"] }+# Native transcript reading: Codex keeps a rollout it has not written for a+# week as `.jsonl.zst`, so the workstream adapter needs a zstd decoder to find+# and resume that session. Pure Rust, so the build needs no extra C library.+# The `hash` feature only computes frame checksums and nothing here compares+# them, so it stays off; frames that carry one still decode.+ruzstd = { version = "0.9", default-features = false, features = ["std"] }+# Text munging / hook payload sanitisation.regex = "1"# Unicode NFC for the portable page-path key. Already in the tree viadiff --git a/crates/ai-memory-cli/Cargo.toml b/crates/ai-memory-cli/Cargo.tomlindex bb05512e..2ddc407e 100644--- a/crates/ai-memory-cli/Cargo.toml+++ b/crates/ai-memory-cli/Cargo.toml@@ -107,6 +107,7 @@ tempfile.workspace = true[dev-dependencies]ai-memory-test-support.workspace = true+ruzstd.workspace = truetempfile.workspace = truerstest.workspace = truerusqlite.workspace = truediff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rsindex 33042cc4..95fdaa83 100644--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@ -8306,6 +8306,52 @@ mod tests {assert_eq!(explicit.expected_session_id.as_deref(), Some("chosen"));}+ /// Codex compresses a rollout idle for a week to `.jsonl.zst`. The launch+ /// still resumes that linked session instead of treating it as missing.+ #[test]+ fn compressed_codex_rollout_is_resumed_not_orphaned() {+ let temp = tempfile::tempdir().unwrap();+ let cwd = temp.path().join("repo");+ let day = temp.path().join(".codex/sessions/2026/10/05");+ std::fs::create_dir_all(&cwd).unwrap();+ std::fs::create_dir_all(&day).unwrap();+ let id = "01a10e73-0053-7f73-8dbd-5c76bcb2f5e5";+ let record = serde_json::json!({"type":"session_meta","payload":{"id":id,"cwd":cwd}});+ let compressed = day.join(format!("rollout-2026-10-05T20-43-00-{id}.jsonl.zst"));+ std::fs::write(+ &compressed,+ ruzstd::encoding::compress_to_vec(+ format!("{record}\n").as_bytes(),+ ruzstd::encoding::CompressionLevel::Fastest,+ ),+ )+ .unwrap();+ let env = EffectiveChildEnv::default();+ let plan = || {+ build_preflighted_launch_plan(+ ManagedHarness::Codex,+ None,+ Vec::new(),+ Some(id),+ false,+ temp.path(),+ &cwd,+ &env,+ )+ .unwrap()+ };++ let (resumed, orphaned) = plan();+ assert!(orphaned.is_none());+ assert!(resumed.args.iter().any(|arg| arg == "resume"));+ assert_eq!(resumed.expected_session_id.as_deref(), Some(id));++ std::fs::remove_file(&compressed).unwrap();+ let (fresh, orphaned) = plan();+ assert_eq!(orphaned.as_deref(), Some(id));+ assert!(!fresh.args.iter().any(|arg| arg == "resume"));+ }+/// A linked session missing from this launch's store is only replaced/// when it was linked under the same store (or nothing was recorded).#[test]diff --git a/crates/ai-memory-workstream/Cargo.toml b/crates/ai-memory-workstream/Cargo.tomlindex 6cef9644..ea6b0e00 100644--- a/crates/ai-memory-workstream/Cargo.toml+++ b/crates/ai-memory-workstream/Cargo.toml@@ -20,6 +20,7 @@ sha2.workspace = truejiff.workspace = truelibc.workspace = truerusqlite.workspace = true+ruzstd.workspace = truetokio.workspace = trueuuid.workspace = truediff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rsindex 26e1264d..b90603b2 100644--- a/crates/ai-memory-workstream/src/transcript.rs+++ b/crates/ai-memory-workstream/src/transcript.rs@@ -13,6 +13,7 @@ use ai_memory_core::{};use anyhow::{Context as _, Result, anyhow};use rusqlite::{Connection, OpenFlags, OptionalExtension as _, params};+use ruzstd::decoding::{FrameDecoder, StreamingDecoder};use serde::{Deserialize, Serialize};use serde_json::{Value, json};use sha2::{Digest as _, Sha256};@@ -388,13 +389,14 @@ fn validate_transcript_cursor(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"))?;- if Path::new(&cursor.path) != path || cursor.flavor != file_flavor(harness) {+ if Path::new(&cursor.path) != cursor_path(harness, &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 {+ if !transcript_reaches(harness, &path, cursor.offset)? {return Err(anyhow!("native transcript cursor is past the current transcript end"));@@ -536,8 +538,7 @@ fn transcript_baseline_blocking(.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 reader = open_transcript(harness, &path)?;let mut offset = 0_u64;let mut committed_offset = 0_u64;let mut prefix_hasher = Sha256::new();@@ -601,7 +602,7 @@ fn transcript_baseline_blocking(committed_offset = offset;}Ok(serde_json::to_string(&FileCursor {- path: path.to_string_lossy().into_owned(),+ path: cursor_path(harness, &path).to_string_lossy().into_owned(),offset: committed_offset,flavor: file_flavor(harness),prefix_sha256: journal_rewrites_in_place(harness)@@ -1120,10 +1121,13 @@ fn export_jsonl_range(final_cursor: Option<&str>,) -> Result<ExportedTranscript> {let flavor = file_flavor(harness);+ let compressed = compressed_codex_rollout(harness, path);+ let named_path = cursor_path(harness, path);let cursor = source_cursor.and_then(|raw| serde_json::from_str::<FileCursor>(raw).ok()).filter(|cursor| {- Path::new(&cursor.path) == path && (cursor.flavor.is_none() || cursor.flavor == flavor)+ Path::new(&cursor.path) == named_path+ && (cursor.flavor.is_none() || cursor.flavor == flavor)});let final_cursor = final_cursor.map(serde_json::from_str::<FileCursor>)@@ -1131,7 +1135,7 @@ fn export_jsonl_range(.context("invalid native transcript final file cursor")?;if final_cursor.as_ref()- .is_some_and(|cursor| Path::new(&cursor.path) != path || cursor.flavor != flavor)+ .is_some_and(|cursor| Path::new(&cursor.path) != named_path || cursor.flavor != flavor){return Err(anyhow!("native transcript final cursor does not match this adapter session"@@ -1139,7 +1143,16 @@ fn export_jsonl_range(}let mut file = File::open(path).with_context(|| format!("opening native transcript {}", path.display()))?;- let file_len = file.metadata()?.len();+ // The file length of a compressed rollout says nothing about its content,+ // and this reader does not trust the frame's optional content size: a+ // final cursor is checked by decoding up to it, and otherwise the read+ // below stops at the end of the stream or the source-byte budget.+ let file_len = match (compressed, final_cursor.as_ref()) {+ (false, _) => file.metadata()?.len(),+ (true, Some(cursor)) if transcript_reaches(harness, path, cursor.offset)? => cursor.offset,+ (true, Some(_)) => 0,+ (true, None) => u64::MAX,+ };let len = final_cursor.as_ref().map_or(file_len, |cursor| cursor.offset);@@ -1165,8 +1178,20 @@ fn export_jsonl_range(Sha256::new(),)};- file.seek(SeekFrom::Start(start))?;- let mut reader = BufReader::new(file);+ let (mut reader, start): (Box<dyn BufRead>, u64) = if compressed {+ // A zstd stream cannot seek: decode and drop the bytes before `start`.+ // A shorter stream ends the skip early, which clamps `start` the way+ // `min(len)` clamps it for a plain file.+ let mut reader = transcript_reader(harness, path, file)?;+ let skipped = std::io::copy(+ &mut std::io::Read::by_ref(&mut reader).take(start),+ &mut std::io::sink(),+ )?;+ (reader, skipped)+ } else {+ file.seek(SeekFrom::Start(start))?;+ (Box::new(BufReader::new(file)), start)+ };let mut offset = start;let mut committed_offset = start;let mut line = Vec::new();@@ -1417,7 +1442,7 @@ fn export_jsonl_range(Ok(ExportedTranscript {native_session_id: native_session_id.to_string(),source_cursor: Some(serde_json::to_string(&FileCursor {- path: path.to_string_lossy().into_owned(),+ path: named_path.to_string_lossy().into_owned(),offset: committed_offset,flavor,prefix_sha256: if journal_rewrites_in_place(harness) {@@ -3785,6 +3810,9 @@ fn transcript_file(harness: ManagedHarness, path: &Path) -> bool {.and_then(|name| name.to_str()).is_some_and(|name| Uuid::parse_str(name).is_ok());}+ if compressed_codex_rollout(harness, path) {+ return !cursor_path(harness, path).exists();+ }path.extension().is_some_and(|ext| ext == "jsonl")|| matches!(harness, ManagedHarness::Pi | ManagedHarness::Omp) && temporary_transcript(path)}@@ -3797,6 +3825,187 @@ fn temporary_transcript(path: &Path) -> bool {.is_some_and(|name| name.contains(".jsonl."))}+/// Codex moves a rollout it has not written for seven days to a zstd+/// `rollout-*.jsonl.zst` sibling, keeping its modification time, and restores+/// the plain `.jsonl` when it reopens that session to write to it, which+/// `codex resume` does at startup. A reader that finds both uses the plain+/// file. The compressed copy is the same session, so it is located, listed and+/// read like the plain one, and a cursor names the plain path in either form.+/// Modeled on Codex 0.163.0: `RolloutFile::from_path` and+/// `materialize_rollout_for_append` in+/// <https://github.com/openai/codex/blob/rust-v0.163.0/codex-rs/rollout/src/compression.rs>+/// and the `Resume` arm of `RolloutRecorder::new_inner` in+/// <https://github.com/openai/codex/blob/rust-v0.163.0/codex-rs/rollout/src/recorder.rs>.+fn compressed_codex_rollout(harness: ManagedHarness, path: &Path) -> bool {+ harness == ManagedHarness::Codex+ && path+ .file_name()+ .and_then(|name| name.to_str())+ .is_some_and(|name| name.starts_with("rollout-") && name.ends_with(".jsonl.zst"))+}++/// The path a file cursor names: the plain `.jsonl` a compressed Codex rollout+/// is restored to, so a cursor stays valid across Codex's own conversion.+fn cursor_path(harness: ManagedHarness, path: &Path) -> PathBuf {+ if compressed_codex_rollout(harness, path) {+ path.with_extension("")+ } else {+ path.to_path_buf()+ }+}++/// Open a transcript for sequential reads, decompressing a compressed Codex+/// rollout.+fn open_transcript(harness: ManagedHarness, path: &Path) -> std::io::Result<Box<dyn BufRead>> {+ transcript_reader(harness, path, File::open(path)?)+}++/// [`open_transcript`] over a file already opened at `path`.+fn transcript_reader(+ harness: ManagedHarness,+ path: &Path,+ file: File,+) -> std::io::Result<Box<dyn BufRead>> {+ if compressed_codex_rollout(harness, path) {+ return Ok(Box::new(BufReader::new(ZstdFrames::new(BufReader::new(+ file,+ ))?)));+ }+ Ok(Box::new(BufReader::new(file)))+}++/// Whether a transcript holds at least `offset` bytes of content, counted in+/// decompressed bytes for a compressed Codex rollout, which is decoded only+/// up to `offset` rather than trusting the frame's optional content size.+fn transcript_reaches(harness: ManagedHarness, path: &Path, offset: u64) -> std::io::Result<bool> {+ if compressed_codex_rollout(harness, path) {+ let decoded = std::io::copy(+ &mut std::io::Read::take(open_transcript(harness, path)?, offset),+ &mut std::io::sink(),+ )?;+ return Ok(decoded == offset);+ }+ Ok(fs::metadata(path)?.len() >= offset)+}++/// Every frame of a zstd stream, in order. `StreamingDecoder` stops after one;+/// Codex writes a single frame, but the format allows a concatenation, which+/// `zstd -d` reads whole. A skippable frame, which Codex never writes, is+/// reported as a decoding error.+struct ZstdFrames<R: BufRead> {+ decoder: Option<StreamingDecoder<TrackedSource<R>, FrameDecoder>>,+ source_error: SourceError,+}++impl<R: BufRead> ZstdFrames<R> {+ fn new(source: R) -> std::io::Result<Self> {+ let source_error = SourceError::default();+ let source = TrackedSource {+ inner: source,+ error: source_error.clone(),+ };+ let decoder = StreamingDecoder::new(source).map_err(|error| source_error.or(error))?;+ Ok(Self {+ decoder: Some(decoder),+ source_error,+ })+ }+}++impl<R: BufRead> std::io::Read for ZstdFrames<R> {+ fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {+ while let Some(decoder) = self.decoder.as_mut() {+ let read = decoder+ .read(buf)+ .map_err(|error| self.source_error.or(error))?;+ if read > 0 || buf.is_empty() {+ return Ok(read);+ }+ let Some(finished) = self.decoder.take() else {+ break;+ };+ let mut source = finished.into_inner();+ if !source.fill_buf()?.is_empty() {+ self.decoder = Some(+ StreamingDecoder::new(source).map_err(|error| self.source_error.or(error))?,+ );+ }+ }+ Ok(0)+ }+}++/// The decoder reports a failed read of its input as one of its own errors.+/// The input's last I/O error is kept here so a file that could not be read is+/// reported as such, and only a stream that is not valid zstd counts as damaged.+#[derive(Clone, Default)]+struct SourceError(std::rc::Rc<std::cell::RefCell<Option<std::io::Error>>>);++impl SourceError {+ fn record(&self, error: &std::io::Error) {+ *self.0.borrow_mut() = Some(std::io::Error::new(error.kind(), error.to_string()));+ }++ /// The input's I/O error if the decoder failed because of one, else a+ /// decoding error.+ fn or(&self, error: impl std::fmt::Display) -> std::io::Error {+ self.0+ .borrow_mut()+ .take()+ .unwrap_or_else(|| zstd_decode_error(error))+ }+}++struct TrackedSource<R> {+ inner: R,+ error: SourceError,+}++impl<R: BufRead> std::io::Read for TrackedSource<R> {+ fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {+ self.inner+ .read(buf)+ .inspect_err(|error| self.error.record(error))+ }+}++impl<R: BufRead> BufRead for TrackedSource<R> {+ fn fill_buf(&mut self) -> std::io::Result<&[u8]> {+ self.inner+ .fill_buf()+ .inspect_err(|error| self.error.record(error))+ }++ fn consume(&mut self, amount: usize) {+ self.inner.consume(amount);+ }+}++/// A compressed rollout whose bytes are not a zstd stream this reader decodes.+#[derive(Debug)]+struct ZstdDecodeError(String);++impl std::fmt::Display for ZstdDecodeError {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(formatter, "invalid zstd stream: {}", self.0)+ }+}++impl std::error::Error for ZstdDecodeError {}++fn zstd_decode_error(error: impl std::fmt::Display) -> std::io::Error {+ std::io::Error::new(+ std::io::ErrorKind::InvalidData,+ ZstdDecodeError(error.to_string()),+ )+}++fn is_zstd_decode_error(error: &std::io::Error) -> bool {+ error+ .get_ref()+ .is_some_and(|inner| inner.is::<ZstdDecodeError>())+}+fn read_bounded_file(path: &Path, limit: u64) -> std::io::Result<Vec<u8>> {let file = File::open(path)?;if file.metadata()?.len() > limit {@@ -3874,12 +4083,20 @@ fn session_header(harness: ManagedHarness, path: &Path) -> Result<Option<(Stringif harness == ManagedHarness::Copilot {return copilot_session_header(path);}- let mut reader = BufReader::new(File::open(path)?);+ // A damaged compressed rollout has no readable header, like a plain file+ // with no parseable line; it is skipped rather than failing the store.+ let mut reader = match open_transcript(harness, path) {+ Ok(reader) => reader,+ Err(error) if is_zstd_decode_error(&error) => return Ok(None),+ Err(error) => return Err(error.into()),+ };for _ in 0..64 {- let line = match read_capped_line(&mut reader, MAX_SESSION_HEADER_BYTES)? {- CappedLine::Eof => break,- CappedLine::Oversized => return Ok(None),- CappedLine::Line(line) => line,+ let line = match read_capped_line(&mut reader, MAX_SESSION_HEADER_BYTES) {+ Ok(CappedLine::Eof) => break,+ Ok(CappedLine::Oversized) => return Ok(None),+ Ok(CappedLine::Line(line)) => line,+ Err(error) if is_zstd_decode_error(&error) => return Ok(None),+ Err(error) => return Err(error.into()),};let Ok(value) = serde_json::from_str::<Value>(&line) else {continue;@@ -7398,6 +7615,391 @@ mod tests {assert_eq!(candidates.first(), Some(&temporary));}+ fn codex_rollout(store: &Path, id: &str, cwd: &Path, texts: &[&str]) -> PathBuf {+ let day = store.join("2026/10/05");+ fs::create_dir_all(&day).unwrap();+ fs::create_dir_all(cwd).unwrap();+ let path = day.join(format!("rollout-2026-10-05T20-43-00-{id}.jsonl"));+ let mut records = vec![json!({"type":"session_meta","payload":{"id":id,"cwd":cwd}})];+ records.extend(texts.iter().map(|text| {+ json!({"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":text}]}})+ }));+ let body = records+ .iter()+ .map(|record| format!("{record}\n"))+ .collect::<String>();+ fs::write(&path, body).unwrap();+ path+ }++ /// What Codex does to a rollout idle for a week: a zstd copy replaces it.+ fn compress_codex_rollout(plain: &Path) -> PathBuf {+ let compressed = plain.with_extension("jsonl.zst");+ let bytes = fs::read(plain).unwrap();+ fs::write(+ &compressed,+ ruzstd::encoding::compress_to_vec(+ bytes.as_slice(),+ ruzstd::encoding::CompressionLevel::Fastest,+ ),+ )+ .unwrap();+ fs::remove_file(plain).unwrap();+ compressed+ }++ fn exported_texts(transcript: &ExportedTranscript) -> Vec<&str> {+ transcript+ .events+ .iter()+ .map(|event| event.content.as_str())+ .collect()+ }++ /// A rollout Codex compressed is still the linked session, so a managed+ /// launch resumes it instead of starting fresh. The compressed copy is+ /// located through the same header and checkout match as a plain one.+ #[test]+ fn codex_compressed_rollout_still_exists_only_for_its_own_checkout() {+ let temp = tempfile::tempdir().unwrap();+ let store = temp.path().join("sessions");+ let cwd = temp.path().join("repo");+ let other = temp.path().join("other");+ let mine = "01a10e73-0053-7f73-8dbd-5c76bcb2f5e5";+ let theirs = "01a10e73-0053-7f73-8dbd-5c76bcb2f5e6";+ let exists = |id: &str| {+ native_session_exists(ManagedHarness::Codex, temp.path(), &cwd, Some(&store), id)+ .unwrap()+ };++ let plain = codex_rollout(&store, mine, &cwd, &["hello"]);+ assert!(exists(mine));+ let compressed = compress_codex_rollout(&plain);+ assert!(!plain.exists());+ assert!(exists(mine), "the compressed copy is the same session");+ assert!(+ native_session_in_checkout(+ ManagedHarness::Codex,+ temp.path(),+ &cwd,+ Some(&store),+ mine+ )+ .unwrap()+ );+ assert_eq!(+ locate_session_file(ManagedHarness::Codex, temp.path(), &cwd, Some(&store), mine)+ .unwrap(),+ Some(compressed)+ );++ // Another checkout's compressed rollout is refused like a plain one.+ compress_codex_rollout(&codex_rollout(&store, theirs, &other, &["elsewhere"]));+ assert!(!exists(theirs));++ // A damaged compressed copy is skipped, not an unreadable store.+ let broken = "01a10e73-0053-7f73-8dbd-5c76bcb2f5e7";+ fs::write(+ store.join(format!(+ "2026/10/05/rollout-2026-10-05T20-43-00-{broken}.jsonl.zst"+ )),+ b"not zstd",+ )+ .unwrap();+ assert!(!exists(broken));+ // So is one cut short before its first block ends.+ let truncated = "01a10e73-0053-7f73-8dbd-5c76bcb2f5e8";+ let whole = fs::read(compress_codex_rollout(&codex_rollout(+ &store,+ truncated,+ &cwd,+ &["a reply long enough to span more than the header record"],+ )))+ .unwrap();+ fs::write(+ store.join(format!(+ "2026/10/05/rollout-2026-10-05T20-43-00-{truncated}.jsonl.zst"+ )),+ &whole[..whole.len() / 2],+ )+ .unwrap();+ assert!(!exists(truncated));+ assert!(exists(mine));+ }++ /// Codex reads the plain file when both forms exist (a conversion in+ /// progress). Its staging files (`rollout-compress-*.tmp` while+ /// compressing, `<rollout>.decompress.<pid>.<n>.tmp` while restoring) and+ /// a `.jsonl.zst` without the `rollout-` prefix are never sessions.+ #[tokio::test]+ async fn codex_plain_rollout_hides_its_compressed_sibling() {+ let temp = tempfile::tempdir().unwrap();+ let store = temp.path().join("sessions");+ let cwd = temp.path().join("repo");+ let id = "01a16548-23e9-7cf1-b3d6-ab3405055748";+ let plain = codex_rollout(&store, id, &cwd, &["hello"]);+ let compressed = compress_codex_rollout(&plain);+ let others = [+ compressed.with_file_name("rollout-compress-a1b2c3.tmp"),+ PathBuf::from(format!("{}.decompress.4242.0.tmp", plain.display())),+ compressed.with_file_name(format!("notes-{id}.jsonl.zst")),+ ];+ for other in &others {+ fs::copy(&compressed, other).unwrap();+ assert!(!transcript_file(ManagedHarness::Codex, other), "{other:?}");+ }+ assert!(transcript_file(ManagedHarness::Codex, &compressed));+ assert!(!transcript_file(ManagedHarness::Claude, &compressed));++ codex_rollout(&store, id, &cwd, &["hello"]);+ assert!(!transcript_file(ManagedHarness::Codex, &compressed));+ assert_eq!(+ locate_session_file(ManagedHarness::Codex, temp.path(), &cwd, Some(&store), id)+ .unwrap(),+ Some(plain)+ );+ let listed =+ list_native_sessions(ManagedHarness::Codex, temp.path(), &cwd, Some(&store), 10)+ .await+ .unwrap();+ assert_eq!(listed.len(), 1);+ assert_eq!(listed[0].native_session_id, id);+ }++ /// The pre-launch baseline of a compressed rollout names the plain path,+ /// so the import after the run lines up whether Codex restored the file+ /// (it does on `codex resume`) or the run ended before Codex reopened it.+ #[test]+ fn codex_cursor_survives_codex_restoring_a_compressed_rollout() {+ let temp = tempfile::tempdir().unwrap();+ let store = temp.path().join("sessions");+ let cwd = temp.path().join("repo");+ let id = "01a16539-8691-7df3-a8fd-dd78556eaed4";+ let codex = ManagedHarness::Codex;+ let plain = codex_rollout(&store, id, &cwd, &["before"]);+ let plain_len = fs::metadata(&plain).unwrap().len();+ let before_compression =+ export_transcript_blocking(codex, temp.path(), &cwd, Some(&store), id, None, None)+ .unwrap();+ assert_eq!(exported_texts(&before_compression), ["before"]);+ let compressed = compress_codex_rollout(&plain);++ let baseline =+ transcript_baseline_blocking(codex, temp.path(), &cwd, Some(&store), id).unwrap();+ let cursor: FileCursor = serde_json::from_str(&baseline).unwrap();+ assert_eq!(Path::new(&cursor.path), plain);+ assert_eq!(cursor.offset, plain_len);+ assert_eq!(+ before_compression.source_cursor.as_deref(),+ Some(baseline.as_str()),+ "a cursor taken before compression is the same cursor"+ );++ // The run ended before Codex reopened the rollout: still compressed.+ validate_transcript_cursor(codex, temp.path(), &cwd, Some(&store), id, &baseline).unwrap();+ let unchanged = export_transcript_blocking(+ codex,+ temp.path(),+ &cwd,+ Some(&store),+ id,+ Some(&baseline),+ None,+ )+ .unwrap();+ assert!(unchanged.events.is_empty(), "{:?}", unchanged.events);+ assert_eq!(unchanged.source_cursor.as_deref(), Some(baseline.as_str()));++ // Codex resumed the session: it restored the plain file and appended.+ codex_rollout(&store, id, &cwd, &["before", "after"]);+ fs::remove_file(&compressed).unwrap();+ validate_transcript_cursor(codex, temp.path(), &cwd, Some(&store), id, &baseline).unwrap();+ let delta = export_transcript_blocking(+ codex,+ temp.path(),+ &cwd,+ Some(&store),+ id,+ Some(&baseline),+ None,+ )+ .unwrap();+ assert_eq!(exported_texts(&delta), ["after"]);+ let next: FileCursor =+ serde_json::from_str(delta.source_cursor.as_deref().unwrap()).unwrap();+ assert_eq!(Path::new(&next.path), plain);+ assert_eq!(next.offset, fs::metadata(&plain).unwrap().len());+ }++ /// Reading the compressed form exports exactly what the plain form does,+ /// from the start, from a cursor, and up to an exact final cursor.+ #[test]+ fn codex_compressed_rollout_exports_like_the_plain_file() {+ let temp = tempfile::tempdir().unwrap();+ let store = temp.path().join("sessions");+ let cwd = temp.path().join("repo");+ let id = "01a16797-f057-7762-b123-f8ba78018cf7";+ let codex = ManagedHarness::Codex;+ let plain = codex_rollout(&store, id, &cwd, &["one", "two", "three"]);+ let export = |source: Option<&str>, last: Option<&str>| {+ export_transcript_blocking(codex, temp.path(), &cwd, Some(&store), id, source, last)+ .unwrap()+ };+ let ends = fs::read_to_string(&plain)+ .unwrap()+ .split_inclusive('\n')+ .scan(0, |end, line| {+ *end += line.len() as u64;+ Some(*end)+ })+ .collect::<Vec<_>>();+ let at = |offset: u64| {+ serde_json::to_string(&FileCursor {+ path: plain.to_string_lossy().into_owned(),+ offset,+ flavor: None,+ prefix_sha256: None,+ })+ .unwrap()+ };+ let (middle, end_of_two) = (at(ends[1]), at(ends[2]));+ let whole = export(None, None);+ let from_middle = export(Some(&middle), None);+ let exact = export(Some(&middle), Some(&end_of_two));+ assert_eq!(exported_texts(&from_middle), ["two", "three"]);+ assert_eq!(exported_texts(&exact), ["two"]);++ compress_codex_rollout(&plain);+ let compressed_whole = export(None, None);+ assert_eq!(exported_texts(&compressed_whole), ["one", "two", "three"]);+ assert_eq!(compressed_whole.source_cursor, whole.source_cursor);+ let compressed_from_middle = export(Some(&middle), None);+ assert_eq!(exported_texts(&compressed_from_middle), ["two", "three"]);+ assert_eq!(+ compressed_from_middle.source_cursor,+ from_middle.source_cursor+ );+ let compressed_exact = export(Some(&middle), Some(&end_of_two));+ assert_eq!(exported_texts(&compressed_exact), ["two"]);+ assert_eq!(compressed_exact.source_cursor, exact.source_cursor);++ // Past the end: a source cursor clamps to the end as it does for a+ // plain file, and a final cursor or a recovery cursor is refused.+ let beyond = at(ends[3] + 10);+ assert!(export(Some(&beyond), None).events.is_empty());+ assert_eq!(+ export(Some(&beyond), None).source_cursor,+ whole.source_cursor+ );+ let error = export_transcript_blocking(+ codex,+ temp.path(),+ &cwd,+ Some(&store),+ id,+ Some(&middle),+ Some(&beyond),+ )+ .unwrap_err();+ assert!(+ error+ .to_string()+ .contains("past the current transcript end"),+ "{error}"+ );+ let error = validate_transcript_cursor(codex, temp.path(), &cwd, Some(&store), id, &beyond)+ .unwrap_err();+ assert!(+ error+ .to_string()+ .contains("past the current transcript end"),+ "{error}"+ );+ validate_transcript_cursor(codex, temp.path(), &cwd, Some(&store), id, &at(ends[3]))+ .unwrap();+ }++ /// `StreamingDecoder` reads one frame; the reader continues into the next.+ #[test]+ fn codex_compressed_rollout_reader_reads_every_frame() {+ let temp = tempfile::tempdir().unwrap();+ let path = temp.path().join("rollout-x.jsonl.zst");+ let frame = |text: &[u8]| {+ ruzstd::encoding::compress_to_vec(text, ruzstd::encoding::CompressionLevel::Fastest)+ };+ // `printf 'second\n' | zstd -c --check`: the CLI adds a content+ // checksum by default, which the encoder used for the other frame+ // does not, and the reader still consumes it to reach the end.+ let checksummed = [+ 0x28, 0xb5, 0x2f, 0xfd, 0x04, 0x58, 0x39, 0x00, 0x00, 0x73, 0x65, 0x63, 0x6f, 0x6e,+ 0x64, 0x0a, 0x16, 0x40, 0x4c, 0x55,+ ];+ fs::write(&path, [frame(b"first\n"), checksummed.to_vec()].concat()).unwrap();+ let read = || {+ let mut content = String::new();+ std::io::Read::read_to_string(+ &mut open_transcript(ManagedHarness::Codex, &path).unwrap(),+ &mut content,+ )+ .map(|_| content)+ };+ assert_eq!(read().unwrap(), "first\nsecond\n");+ assert!(transcript_reaches(ManagedHarness::Codex, &path, 13).unwrap());+ assert!(!transcript_reaches(ManagedHarness::Codex, &path, 14).unwrap());++ fs::write(&path, [frame(b"first\n"), b"garbage".to_vec()].concat()).unwrap();+ let error = read().unwrap_err();+ assert!(is_zstd_decode_error(&error), "{error}");+ }++ /// A file that fails to read mid-stream is an I/O error, not a damaged+ /// stream, so a lookup reports it instead of treating the session as gone.+ #[test]+ fn codex_compressed_rollout_reader_keeps_input_errors_apart_from_damage() {+ struct FailsAfter {+ bytes: Vec<u8>,+ position: usize,+ fail_at: usize,+ }+ impl std::io::Read for FailsAfter {+ fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {+ if self.position >= self.bytes.len() {+ return Ok(0);+ }+ if self.position >= self.fail_at {+ return Err(std::io::Error::other("disk went away"));+ }+ let end = self.fail_at.min(self.position + buf.len());+ let count = end - self.position;+ buf[..count].copy_from_slice(&self.bytes[self.position..end]);+ self.position = end;+ Ok(count)+ }+ }+ let text = (0..400)+ .map(|line| format!("{{\"line\":{line},\"text\":\"record number {line}\"}}\n"))+ .collect::<String>();+ let bytes = ruzstd::encoding::compress_to_vec(+ text.as_bytes(),+ ruzstd::encoding::CompressionLevel::Fastest,+ );+ let decode = |fail_at: usize| {+ let source = FailsAfter {+ bytes: bytes.clone(),+ position: 0,+ fail_at,+ };+ let mut content = Vec::new();+ ZstdFrames::new(BufReader::with_capacity(16, source))+ .and_then(|mut frames| std::io::Read::read_to_end(&mut frames, &mut content))+ .map(|_| content)+ };+ assert_eq!(decode(bytes.len()).unwrap(), text.as_bytes());+ let error = decode(bytes.len() / 2).unwrap_err();+ assert!(!is_zstd_decode_error(&error), "{error}");+ assert!(error.to_string().contains("disk went away"), "{error}");+ }+#[test]fn claude_session_ran_in_background_needs_its_own_bg_record() {let temp = tempfile::tempdir().unwrap();diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex 0a1bbfa4..f8224ee7 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -458,7 +458,11 @@ linked id in the harness's native store without modifying it. If the transcriptwas deleted, cleared, or lost with a sandbox overlay, ai-memory starts a freshnative session and repoints the same workstream when that session is observed.An unreadable or malformed store is reported but is not mistaken for a missing-session. Use `ai-memory run --fresh <harness>` to deliberately skip the linked+session. Codex compresses a rollout it has not written for a week to+`rollout-*.jsonl.zst` and restores the plain file when `codex resume` reopens+it. The compressed copy counts as the linked session, so the launch resumes it+and the transcript import reads it like the plain file. Use+`ai-memory run --fresh <harness>` to deliberately skip the linkedsession and the adoption chooser. `--fresh` cannot be combined with a nativeresume, continue, session, or fork selector.@@ -728,7 +732,7 @@ change does not add an atomic disk/SQL seal or change lease/retry policy.| Harness | Fresh native session | Returning native session | Read-only source ||---|---|---|---|| Claude Code | generated `--session-id` | `--resume <id>` | `~/.claude/projects/**/*.jsonl` |-| Codex | native default creation | `resume <id>` | `~/.codex/sessions/**/rollout-*.jsonl` |+| Codex | native default creation | `resume <id>` | `~/.codex/sessions/**/rollout-*.jsonl`, or the `rollout-*.jsonl.zst` copy Codex keeps of a rollout idle for a week (the plain file wins when both exist) || OpenCode V1 | native default creation | `--session <id>` | `~/.local/share/opencode/opencode.db` opened read-only; selected when the exact launch executable reports major 1 || OpenCode V2 | native default creation | `--session <id>` | same `opencode.db` filename, using the `session_v2`/`session_message` tables; selected when the exact launch executable reports major 2 || Pi | generated `--session-id` | `--session <id>` | `~/.pi/agent/sessions/**/*.jsonl` |diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex c94c98df..5febef38 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -116,7 +116,7 @@ means the boundary is not built yet.| 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 otherwise never taken from a caller (only derived from already-authorized hits); the one exception, the web page-history `from`/`to` version ids, is looked up only inside the scope `routes/mod.rs` `resolve_read_scope` (`lookup_existing_scope_guarded`, `ProjectAccess::Read`) has already authorized and the requested path (`page_version_body`), so a foreign id reads as not found; 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`, `observation_stream_evidence_stays_inside_a_restricted_project` (with `[retrieval] observation_stream` on, a non-grantee naming the restricted project, listing it in `scopes`, or searching their own project never sees the session page or its observation excerpt; the writer and a read-grant holder do; fails with the read check in `ProjectAuthz::authorize` neutralized), `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`, `a_reader_cannot_change_a_projects_profile_flags_at_session_start` (a Read grant's `profile_contribute`/`profile_consume` at session start neither opts the project out nor back in; Write-grant control records both; fails with the Write check forced on), `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` (also a paginated namespace URL, `/p/secrets/?page=2`), `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (19 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); `ai-memory-web` `history_replay.rs` `history_and_timeline_honour_grants_in_a_restricted_project` (page history in HTML and JSON and the session timeline: a non-grantee gets 403 without the body, a grantee and root get 200; bite: resolving through the unguarded `lookup_existing_scope` fails it) | 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`; importer agentmemory routes `vault::plan`, `export::plan`, `export::replay_session`, `agentmemory::validate_id` | 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`, agentmemory `page_bodies_are_redacted_before_planning`, `text_is_redacted_before_the_plan_exists` (page bodies and replayed observations), `ids_that_look_like_credentials_or_carry_controls_are_refused`. 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 |-| 14au | Exact native managed identity and privacy (invariant #16) | `core/src/workstream.rs` `NativeSessionIdentity` validates original bytes and exact scrub equality; `workstream/src/harness.rs` and `transcript.rs` retain selector/path restrictions; CLI `run.rs` validates old-server prepare/status, planned selectors and finish transport; hooks `workstream.rs` checks payload and selected identity before raw segments, with the existing owner/current Write preflight first; `router.rs` validates both managed auto-links while preserving legacy shared capture; store `workstream.rs` carries validated identities into link/finish SQL after finish authority and before mutation. Store, HTTP search and CLI search project invalid historical identity to empty String without rewriting history | Core `native_identity_original_bytes_limits_privacy_and_collisions`; harness `native_identity_selector_rejects_original_before_resume_arguments`; transcript `native_identity_adapter_preserves_exact_and_rejects_privacy_changes`, `copilot_discovery_requires_uuid_directory_header_and_checkout` (another checkout's session, a `session.start` naming a different session than its directory, and non-UUID or `../` ids refused; exact-checkout control), `claude_transcript_is_located_by_the_real_folder_name` (a server-linked Claude id probed across project folders still resolves only to a transcript whose own header names this checkout; another checkout's transcript and a subagent sidechain with the same id are refused); store multi-session `native_identity_store_link_refuses_original_dirty_bytes`, `native_identity_store_adoption_refuses_before_link`, `native_identity_store_finish_refuses_without_sql_or_index_mutation`, `native_identity_store_history_projects_unknown_without_rewriting`; hooks `native_identity_http_link_refuses_before_status_or_sql`, `native_identity_http_finish_refuses_before_segment_or_sql`, `native_identity_http_event_guard_and_configured_history_projection`, `native_identity_http_stored_identity_refuses_before_raw_segment`, router `native_identity_managed_start_refuses_but_keeps_shared_legacy_capture`; CLI `native_identity_run_preflight_refuses_before_resume_or_private_path`, `native_identity_run_old_server_refusal_prevents_child_and_transport`, `native_identity_finish_transport_refuses_before_request_and_preserves_exact_control`, `native_identity_run_status_and_expected_refuse_before_discovery`, `native_identity_run_configured_selector_refuses_before_link_or_child`, `native_identity_run_configured_old_status_refuses_before_native_io_and_finish`, `native_identity_run_configured_discovery_refuses_before_export`, suite `native_identity_search_old_server_json_projects_unknown_and_keeps_history` | Representation/privacy only: no native authenticity, file-existence, run/event correlation or outcome proof. Original legacy rows and shared observation semantics remain intact; parent finish owner/current Write rules remain mandatory |+| 14au | Exact native managed identity and privacy (invariant #16) | `core/src/workstream.rs` `NativeSessionIdentity` validates original bytes and exact scrub equality; `workstream/src/harness.rs` and `transcript.rs` retain selector/path restrictions; CLI `run.rs` validates old-server prepare/status, planned selectors and finish transport; hooks `workstream.rs` checks payload and selected identity before raw segments, with the existing owner/current Write preflight first; `router.rs` validates both managed auto-links while preserving legacy shared capture; store `workstream.rs` carries validated identities into link/finish SQL after finish authority and before mutation. Store, HTTP search and CLI search project invalid historical identity to empty String without rewriting history | Core `native_identity_original_bytes_limits_privacy_and_collisions`; harness `native_identity_selector_rejects_original_before_resume_arguments`; transcript `native_identity_adapter_preserves_exact_and_rejects_privacy_changes`, `copilot_discovery_requires_uuid_directory_header_and_checkout` (another checkout's session, a `session.start` naming a different session than its directory, and non-UUID or `../` ids refused; exact-checkout control), `claude_transcript_is_located_by_the_real_folder_name` (a server-linked Claude id probed across project folders still resolves only to a transcript whose own header names this checkout; another checkout's transcript and a subagent sidechain with the same id are refused), `codex_compressed_rollout_still_exists_only_for_its_own_checkout` (a Codex rollout compressed to `.jsonl.zst` is located through the same header and checkout match: another checkout's compressed session is refused, and a copy whose header does not decode is skipped; exact-checkout control); store multi-session `native_identity_store_link_refuses_original_dirty_bytes`, `native_identity_store_adoption_refuses_before_link`, `native_identity_store_finish_refuses_without_sql_or_index_mutation`, `native_identity_store_history_projects_unknown_without_rewriting`; hooks `native_identity_http_link_refuses_before_status_or_sql`, `native_identity_http_finish_refuses_before_segment_or_sql`, `native_identity_http_event_guard_and_configured_history_projection`, `native_identity_http_stored_identity_refuses_before_raw_segment`, router `native_identity_managed_start_refuses_but_keeps_shared_legacy_capture`; CLI `native_identity_run_preflight_refuses_before_resume_or_private_path`, `native_identity_run_old_server_refusal_prevents_child_and_transport`, `native_identity_finish_transport_refuses_before_request_and_preserves_exact_control`, `native_identity_run_status_and_expected_refuse_before_discovery`, `native_identity_run_configured_selector_refuses_before_link_or_child`, `native_identity_run_configured_old_status_refuses_before_native_io_and_finish`, `native_identity_run_configured_discovery_refuses_before_export`, suite `native_identity_search_old_server_json_projects_unknown_and_keeps_history` | Representation/privacy only: no native authenticity, file-existence, run/event correlation or outcome proof. Original legacy rows and shared observation semantics remain intact; parent finish owner/current Write rules remain mandatory || 14b | Repository identity routing (#708) | `ai-memory-store/src/ops.rs` `resolve_project_by_identity` — one transaction; an identity already on a project is never overwritten; an unclaimed project is claimed only when the capturing user may write it (the choke point's `resolve_project_authz` on the same transaction), otherwise it is returned unclaimed; a different identity under the same name splits into a new project with no shared `repo_path`; when a Phase-5 client explicitly sends `IdentityStyle::Path` (#1033) a project it creates takes `path_style_name` only while no different full identity in the workspace claims that canonical key (checked in the same transaction), so the same path on another forge falls back instead of being merged; authorized captures can claim/promote compatible legacy rows in that transaction while preserving UUID, but handoff/static reads never rename; explicit `host_path` remains the opt-out; `ai-memory-hooks/src/workstream.rs` `resolve_run_scope` sends a managed run through the same transaction (identity holder, else the `$HOME`-guarded cwd-prefix candidate, inside the requested workspace only) only when the wire identity derives the requested name, then authorizes Write (#1182); `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity and style; `ai-memory-core/src/repository_identity.rs` strips credentials from remote URLs client-side, and the server accepts only the routing rungs (`explicit`, `git_remote`) from the wire | `tests/suite/identity_resolution.rs` `an_outsider_cannot_take_an_unclaimed_projects_identity` (control: `an_existing_project_is_claimed_in_place`), `two_unrelated_repositories_with_one_folder_name_stay_apart`, `a_created_or_split_project_admits_its_creator`, `the_same_path_on_another_forge_falls_back_instead_of_merging`, `an_unclaimed_project_holding_the_path_name_is_not_taken`, `old_client_omitted_style_stays_host_path_and_does_not_promote`, `explicit_path_capture_claims_and_promotes_an_identityless_legacy_name_in_one_transaction`, `unauthorized_capture_cannot_claim_or_promote_an_identityless_legacy_name`, and `explicit_path_capture_falls_back_when_another_identity_claims_the_canonical_key` (controls: `the_path_style_names_a_new_project_from_the_host_less_path`, `opting_in_leaves_existing_projects_where_they_are`), `multi_session.rs` `two_operators_on_two_clones_of_one_repository_share_its_path_named_project`; hooks `workstream.rs` `managed_run_by_remote_identity_refuses_a_viewer_without_write`, `managed_run_identity_never_claims_a_restricted_legacy_project`, `managed_run_identity_never_redirects_another_project_name`; `router.rs` `the_path_style_names_a_new_repository_and_never_merges_another_forge`, `one_path_with_two_remotes_is_two_projects`, `two_api_checkouts_with_different_remotes_get_two_projects` (a manifest rung on the wire is ignored); `repository_identity.rs` credential and normalisation tables — the claim guard and the cache key each proven to fail their test when removed | STRONG — first claimant wins: in a restricted workspace a user who creates a project under a remote identity first holds it until root grants others || 14bb | Local marker aliases cannot cross repository or workspace boundaries (#1033) | `ai-memory-core/src/repository_identity.rs` owns the bounded `MarkerAliases` type and exact one-line/root-level portable grammar; native/POSIX/PowerShell/generated TypeScript clients forward one normalized JSON-array query value only with marker provenance and a hostful git-remote identity; `ai-memory-store/src/project_coordinates.rs` probes exact names only inside the selected workspace, deduplicates by UUID, and requires the selected row's full stored git-remote identity; `ops.rs` authorizes in the writer transaction and reuses Phase 1 `promotion_target`, additionally requiring marker `project` to equal the canonical path-style name derived from that remote; handoff uses the read-only path and capture uses the write-authorized path; `router.rs` includes aliases, provenance, and read/write mode in its cache key | Core/CLI shared `marker_aliases` fixture parity covers duplicate keys, table placement, multiline arrays, trailing junk/comma, escapes, max length and duplicate-heavy over-count; store `marker_aliases_require_same_remote_identity_and_preserve_uuid`, `marker_aliases_cannot_promote_to_an_arbitrary_marker_project`, `hostile_ambiguous_and_cross_workspace_marker_aliases_fail_closed`; hooks `hook_and_handoff_queries_validate_aliases_identically`, `malformed_aliases_are_rejected_before_subagent_scope_resolution`, `empty_aliases_preserve_marker_project_precedence`, `capture_promotes_an_alias_but_handoff_only_reads_it`, `project_cache_separates_alias_sets`; shell `marker aliases keep canonical project and forward remote identity`; Windows PowerShell parity and capture-only marker transparency run in Windows CI; OpenClaw `openclaw_runtime_preserves_marker_and_home_identity_precedence` proves no-marker remote routing sends explicit `path`, ordinary project markers keep name precedence and omit identity, while alias markers and home identity routes forward it | STRONG: hostile arbitrary-name, different-identity and ambiguous aliases refuse or resolve without rename with a legitimate canonical same-identity control; another workspace is never searched; no alias table or persistent fallback exists || 14bb2 | Operator-home route selectors cannot silently cross repository or path boundaries (#1033) | `ai-memory-cli/src/marker.rs` returns a typed invalid result for malformed/oversized maps; command scope resolution propagates it unless both CLI scope fields are explicit, while native hooks drop before spool/network. The native, POSIX, PowerShell, generated TypeScript and OpenClaw parsers enforce the shared 64-route/64-KiB/512-byte grammar, recognize malformed `[routes`, `routes =`, `routes.`, and orphan `route_*` syntax before any no-routes return, preserve legacy parsing for malformed root-only settings without route syntax, apply global duplicate-field/raw-selector/normalized-path checks, require exact hostful identities (including host-edge-dot refusal), match paths component-wise, and enforce a no-escape boundary for `~/` selectors. A route replaces only routing fields; root privacy/behavior flags survive. Bounded native/PowerShell/TypeScript reads reject before full-file allocation where their APIs permit. | `ai-memory-core/fixtures/home_route_cases.json` is executed by native `marker.rs`, POSIX, PowerShell, generated TypeScript, and OpenClaw runtime parity, including malformed route syntax and root-only malformed legacy behavior; shell `test_lib.sh` also exercises route selection, sibling refusal, root-setting retention and invalid-map drop; Windows `powershell_marker_aliases.rs` executes drive and UNC path routing independently of identity; generated TypeScript runtime tests assert marker versus repo-root `project_src`; CLI tests prove unscoped/partial refusal and complete-explicit bypass. | STRONG for native/POSIX/generated TypeScript/OpenClaw on this platform; PowerShell runtime evidence is enforced on Windows CI and skipped where PowerShell is unavailable |