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.6

AkitaOnRails277371f5a223
diff --cc CHANGELOG.md
index 47786633,ca172515..badd5706
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -226,10 -85,44 +226,56 @@@ and this project adheres to [Semantic V
ai-jail's own dry-run preflight, so a backend that exists but fails ai-jail's
trust checks is treated as unavailable instead of producing a broken offer.
(#1024)
+- Fixed watcher reindexing racing with writes and batches to the same page by
+ sharing their per-page mutex from disk read through SQLite upsert. Both
- mutation guards were released before embedding; external editors remained
++ mutation guards are released before embedding; external editors remain
+ outside this coordination. (#1059)
++- Fixed a managed Claude Code run losing its conversation after `/resume` on a
++ Claude Code background session. The run used to finish on the foreground
++ session it started with, which held none of the conversation, so the next
++ `ai-memory run claude` or `continue` resumed it and Claude opened an empty
++ session. A Claude run now finishes on the background session its own
++ session attached to in this checkout, found from that transcript's
++ `sessionKind: "bg"` records; another launch's background session is never
++ taken. (#1050)
+ - Fixed `continue`, `resume` and bare `ai-memory run` losing sessions launched
+ under a custom native store, such as a second Claude Code config home set
+ with `CLAUDE_CONFIG_DIR`. Automatic harness selection now scans the store the
+ launch resolves (`--env`, then the process environment) instead of always the
+ default one. The client records the store of every session it links, at
+ launch or when the run finishes, in `client-projects.json`. A later launch
+ that cannot find that session and resolves a different store now stops with
+ an error naming both stores and keeps the workstream link, where it used to
+ start fresh and repoint the workstream. `--fresh` still starts a new session.
+ (#1047)
+ - Fixed Claude Code sessions never seeing the "broaden when the current project
+ comes up empty" and "maintained pages are evidence, not authority" rules,
+ because Claude Code truncates MCP server instructions at 2,048 characters.
+ The instructions now open with a self-contained core under that cap, and a
+ regression test keeps it there. (#1035)
+ - Fixed the macOS menu-bar app showing only a red status item when the bundled
+ server cannot start (for example a port already in use; #1044 reports OpenCode
+ v2's background service on `127.0.0.1:49374`). The menu extra now surfaces a
+ fatal `stderr.log` line written since the last start, and `docs/macos.md`
+ documents the port collision and how to move one side. (#1044)
+ - Fixed hook-spool drains stalling behind an event that has no session id.
+ `/hook/batch` reported such an event (anything but a session start) as a
+ failed item, so the drain retried it up to its attempt budget while every
+ event queued behind it waited. The server now acknowledges and drops it,
+ counted as `dropped_invalid` in the ingest metrics, and keeps processing the
+ rest of the batch. (#1062)
+ - Fixed `drop_subagent_captures` discarding entire top-level Claude Code
+ sessions launched with `--agent`. An `agent_type` alone no longer marks a
+ session as a subagent; `agent_id` and Grok's `subagentType` still do, so
+ actual subagent filtering remains enabled. Claude Code reports a Task
+ subagent under its parent's session id, so a subagent's events no longer
+ mark that session as a subagent: the parent's Stop, SessionEnd, summary and
+ handoff are kept. (#1041, #1048)
+
+ ### Docs
+ - Corrected the Codex support matrix to describe managed-run recovery from a
+ stale shared-daemon run id; `--no-daemon` remains an optional diagnostic and
+ isolation switch. (#987)
## [2.5.2] - 2026-10-01
diff --cc companions/ai-memory-relay/README.md
index 12f3829d,9d9ec049..550f466b
--- a/companions/ai-memory-relay/README.md
+++ b/companions/ai-memory-relay/README.md
@@@ -213,46 -213,3 +213,46 @@@ lost response, distinct event identitie
checks handoff delivery with native capture suppressed, rejected authentication
and acknowledged session collisions. Temporary data and logs are retained, and
the test prints their directory.
+Receipt assertions cover stored events, lost-response replays and collision drops.
+
+## Receipt outcomes and queue compatibility
+
+Batch ACKs may include `results: [{index, outcome}]`. When present, results must
+match every acknowledged index exactly, ascending and without duplicates.
+The complete ACK, including legacy prefix and failure fields, is validated before
+any item is released. Missing entries, extra indices or non-string outcomes retain
+the entire batch. An absent results field from an older server maps acknowledged
+events to `unknown`; future outcome strings also map to `unknown`.
+
+Receipts persist `stored`, `replayed`, `resumed`, `ignored_end`,
+`dropped_policy`, `dropped_subagent`, `dropped_unauthorized`,
- `dropped_collision` or `unknown`. All acknowledged outcomes release events,
++`dropped_collision`, `dropped_invalid` or `unknown`. All acknowledged outcomes release events,
+including drops. Flush reports `acknowledged_outcomes` for that invocation.
- Status adds `receipt_outcomes`, with all nine fixed keys, including zero counts,
++Status adds `receipt_outcomes`, with all ten fixed keys, including zero counts,
+for receipts within the retained 30-day window measured from first attempt.
+These are bounded delivery counts, not lifetime observation totals.
+
+A receipt keeps its first known outcome when another acknowledgement arrives
+for the same key. A legacy NULL or `unknown` outcome can be filled by a later
+known result. Delivery timestamps may advance without changing that outcome.
+A lost first response has no receipt yet, so its retry can record `replayed`.
+
+Opening a version 1 queue upgrades it to version 2 in one IMMEDIATE transaction,
+adding nullable receipt outcomes and updating schema metadata together. Pending
+order, binding, hashes, pins and existing receipt metadata survive; old NULL
+outcomes count as `unknown`. Concurrent opens recheck the version under the write
+lock. An interrupted migration rolls back and can be retried on reopen.
+After the transaction commits, journal configuration retries only SQLite
+BUSY/LOCKED errors within one 10-second budget. Each attempt rechecks the
+identity and schema version metadata on the same connection; a changed identity
+or schema version stops the open without retrying or adopting that database. The
+checks cover the presence of user objects and the `identity`/`schema_version`
+metadata; they do not validate the complete table structure. This wait
+budget covers journal configuration, separately from the existing SQLite busy
+timeout on transactions. Concurrent processes use SQLite's file locks.
+When the budget expires, the queue reports that it is busy and asks you to
+retry opening the same queue. A committed migration and pending events remain
+in that directory; do not switch queues or restore a backup to clear contention.
+Unknown schemas are refused. Older relay binaries refuse version 2 queues:
+downgrading requires restoring a pre-upgrade backup while all queue users are
+stopped. Do not recreate a queue to bypass its delivery history.
diff --cc companions/ai-memory-relay/src/ack.rs
index 6f710dbb,67e02ca2..8a28429a
--- a/companions/ai-memory-relay/src/ack.rs
+++ b/companions/ai-memory-relay/src/ack.rs
@@@ -3,49 -3,7 +3,50 @@@
//! Validate the entire response before releasing any queued event. An
//! inconsistent acknowledgement leaves the whole batch pending for retry.
-use serde::Deserialize;
+use serde::{Deserialize, Deserializer};
+use std::collections::BTreeMap;
+
+/// Bounded receipt and report vocabulary. Future server strings become unknown.
- pub const OUTCOMES: [&str; 9] = [
++pub const OUTCOMES: [&str; 10] = [
+ "stored",
+ "replayed",
+ "resumed",
+ "ignored_end",
+ "dropped_policy",
+ "dropped_subagent",
+ "dropped_unauthorized",
+ "dropped_collision",
++ "dropped_invalid",
+ "unknown",
+];
+
+/// Normalize an outcome without retaining arbitrary server text.
+pub fn outcome(value: &str) -> &'static str {
+ OUTCOMES
+ .iter()
+ .copied()
+ .find(|known| *known == value)
+ .unwrap_or("unknown")
+}
+
+/// Fixed keys, including zero counts.
+pub fn outcome_counts() -> BTreeMap<String, i64> {
+ OUTCOMES
+ .into_iter()
+ .map(|key| (key.to_owned(), 0))
+ .collect()
+}
+
+/// One acknowledged event's disposition.
+#[derive(Debug, Clone, Deserialize)]
+pub struct EventResult {
+ pub index: usize,
+ pub outcome: String,
+}
+
+fn present_results<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<EventResult>>, D::Error> {
+ Vec::<EventResult>::deserialize(d).map(Some)
+}
/// The server's ack. Unknown fields are accepted (the server may add some);
/// a missing `accepted` is a malformed ack and preserves the batch.
diff --cc companions/ai-memory-relay/tests/relay.rs
index 02b737b6,3ef35e58..15f407d8
--- a/companions/ai-memory-relay/tests/relay.rs
+++ b/companions/ai-memory-relay/tests/relay.rs
@@@ -1347,800 -1340,3 +1347,801 @@@ fn a_batch_stays_under_the_wire_budget_
);
}
}
+
+const V1_SCHEMA: &str = r#"
+CREATE TABLE IF NOT EXISTS meta(
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL
+);
+CREATE TABLE IF NOT EXISTS binding(
+ id INTEGER PRIMARY KEY CHECK(id = 1),
+ server_url TEXT NOT NULL,
+ producer TEXT NOT NULL,
+ actor TEXT NOT NULL,
+ workspace TEXT NOT NULL,
+ project TEXT NOT NULL,
+ created_at_ms INTEGER NOT NULL
+);
+CREATE TABLE IF NOT EXISTS pending(
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
+ ingest_key TEXT NOT NULL UNIQUE,
+ event_id TEXT NOT NULL,
+ agent TEXT NOT NULL,
+ event TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ cwd TEXT NOT NULL,
+ body_json TEXT NOT NULL,
+ body_sha256 TEXT NOT NULL,
+ body_bytes INTEGER NOT NULL,
+ first_seen_ms INTEGER NOT NULL,
+ first_attempt_ms INTEGER,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ last_error TEXT
+);
+CREATE INDEX IF NOT EXISTS pending_session ON pending(agent, session_id, seq);
+CREATE TABLE IF NOT EXISTS receipt(
+ ingest_key TEXT PRIMARY KEY,
+ body_sha256 TEXT NOT NULL,
+ first_attempt_ms INTEGER NOT NULL,
+ delivered_at_ms INTEGER NOT NULL
+);
+CREATE INDEX IF NOT EXISTS receipt_first_attempt ON receipt(first_attempt_ms);
+CREATE TABLE IF NOT EXISTS session_agent(
+ session_id TEXT PRIMARY KEY,
+ agent TEXT NOT NULL,
+ last_seen_ms INTEGER NOT NULL
+);
+"#;
+
+fn v1_fixture(name: &str) -> PathBuf {
+ let root = fixture(name);
+ let dir = queue_dir(&root);
+ std::fs::create_dir(&dir).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap();
+ }
+ let path = dir.join("relay.sqlite");
+ let conn = rusqlite::Connection::open(&path).unwrap();
+ conn.execute_batch(V1_SCHEMA).unwrap();
+ conn.execute_batch(
+ "INSERT INTO meta VALUES('identity','ai-memory-relay-queue'),('schema_version','1'),('extra','preserve');
+ INSERT INTO binding VALUES(1,'http://127.0.0.1:9/','example.runtime','operator-a','team','app',123);
+ INSERT INTO pending VALUES(7,'key-a','event-a','codex','session-start','session-a','/w','{}','hash-a',2,100,101,4,'retry');
+ INSERT INTO pending VALUES(11,'key-b','event-b','codex','session-end','session-a','/w','{}','hash-b',2,102,NULL,0,NULL);
+ INSERT INTO receipt VALUES('receipt-a','receipt-hash',103,104);
+ INSERT INTO session_agent VALUES('session-a','codex',105);"
+ ).unwrap();
+ drop(conn);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
+ }
+ dir
+}
+
+fn snapshot(conn: &rusqlite::Connection) -> Vec<String> {
+ [
+ "SELECT * FROM meta WHERE key != 'schema_version' ORDER BY key",
+ "SELECT * FROM binding",
+ "SELECT * FROM pending ORDER BY seq",
+ "SELECT ingest_key,body_sha256,first_attempt_ms,delivered_at_ms FROM receipt",
+ "SELECT * FROM session_agent",
+ "SELECT * FROM sqlite_sequence",
+ ]
+ .into_iter()
+ .map(|sql| {
+ let mut stmt = conn.prepare(sql).unwrap();
+ let n = stmt.column_count();
+ let rows: Vec<String> = stmt
+ .query_map([], |r| {
+ Ok((0..n)
+ .map(|i| format!("{:?}", r.get_ref(i).unwrap()))
+ .collect::<Vec<_>>()
+ .join("|"))
+ })
+ .unwrap()
+ .map(Result::unwrap)
+ .collect();
+ rows.join("\n")
+ })
+ .collect()
+}
+
+#[test]
+fn v1_migration_preserves_every_existing_value_and_concurrent_reopens() {
+ let dir = v1_fixture("migration");
+ let before = snapshot(&rusqlite::Connection::open(dir.join("relay.sqlite")).unwrap());
+ let barrier = Arc::new(std::sync::Barrier::new(2));
+ let handles: Vec<_> = (0..2)
+ .map(|_| {
+ let dir = dir.clone();
+ let barrier = barrier.clone();
+ thread::spawn(move || {
+ barrier.wait();
+ Queue::open(&dir).unwrap();
+ })
+ })
+ .collect();
+ for handle in handles {
+ handle.join().unwrap();
+ }
+ let queue = Queue::open(&dir).unwrap();
+ assert_eq!(queue.stats(200).unwrap().receipt_outcomes["unknown"], 1);
+ let conn = rusqlite::Connection::open(dir.join("relay.sqlite")).unwrap();
+ assert_eq!(snapshot(&conn), before);
+ assert_eq!(
+ conn.query_row(
+ "SELECT value FROM meta WHERE key='schema_version'",
+ [],
+ |r| r.get::<_, String>(0)
+ )
+ .unwrap(),
+ "2"
+ );
+ assert_eq!(
+ conn.query_row("SELECT outcome FROM receipt", [], |r| r
+ .get::<_, Option<String>>(0))
+ .unwrap(),
+ None
+ );
+}
+
+#[test]
+fn journal_transition_retries_sqlite_lock_without_losing_v1_values() {
+ use queue_under_test::OpenPhase;
+ let dir = v1_fixture("journal-transition");
+ let holder = rusqlite::Connection::open(dir.join("relay.sqlite")).unwrap();
+ let before = snapshot(&holder);
+ let mut busy = 0;
+ let result = queue_under_test::Queue::open_for_test(
+ &dir,
+ std::time::Duration::from_secs(10),
+ &mut |phase| match phase {
+ OpenPhase::BeforeJournal => holder.execute_batch("BEGIN IMMEDIATE;").unwrap(),
+ OpenPhase::JournalBusy => {
+ busy += 1;
+ holder.execute_batch("ROLLBACK;").unwrap();
+ }
+ _ => {}
+ },
+ );
+ assert_eq!(busy, 1, "the real holder must force SQLITE_BUSY");
+ let queue = result.unwrap();
+ assert_eq!(snapshot(&holder), before);
+ assert_eq!(queue.stats(200).unwrap().receipt_outcomes["unknown"], 1);
+ assert_eq!(
+ holder
+ .query_row("PRAGMA journal_mode", [], |r| r.get::<_, String>(0))
+ .unwrap(),
+ "wal"
+ );
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ for name in ["relay.sqlite", "relay.sqlite-wal", "relay.sqlite-shm"] {
+ assert_eq!(
+ std::fs::metadata(dir.join(name))
+ .unwrap()
+ .permissions()
+ .mode()
+ & 0o777,
+ 0o600
+ );
+ }
+ }
+}
+
+#[test]
+fn a_foreign_identity_after_preflight_is_refused_without_mutation() {
+ use queue_under_test::OpenPhase;
+ let dir = v1_fixture("foreign-after-preflight");
+ let path = dir.join("relay.sqlite");
+ let holder = rusqlite::Connection::open(&path).unwrap();
+ let mut before = Vec::new();
+ let result = queue_under_test::Queue::open_for_test(
+ &dir,
+ std::time::Duration::from_secs(10),
+ &mut |phase| {
+ if phase == OpenPhase::AfterPreflight {
+ holder
+ .execute("UPDATE meta SET value='foreign' WHERE key='identity'", [])
+ .unwrap();
+ before = std::fs::read(&path).unwrap();
+ }
+ },
+ );
+ assert!(format!("{:#}", result.unwrap_err()).contains("not a usable relay queue"));
+ assert_eq!(std::fs::read(&path).unwrap(), before);
+ for name in fsguard::SIDECARS {
+ assert!(!dir.join(name).exists(), "foreign queue gained {name}");
+ }
+}
+
+#[test]
+fn journal_transition_has_one_bounded_wait_budget() {
+ use queue_under_test::OpenPhase;
+ let dir = v1_fixture("journal-timeout");
+ let path = dir.join("relay.sqlite");
+ let holder = rusqlite::Connection::open(&path).unwrap();
+ let before = snapshot(&holder);
+ let timeout = std::time::Duration::from_millis(40);
+ let start = std::time::Instant::now();
+ let mut busy = 0;
+ let error = queue_under_test::Queue::open_for_test(&dir, timeout, &mut |phase| match phase {
+ OpenPhase::BeforeJournal => holder.execute_batch("BEGIN IMMEDIATE;").unwrap(),
+ OpenPhase::JournalBusy => busy += 1,
+ _ => {}
+ })
+ .unwrap_err();
+ assert!(queue_under_test::is_lock_contention(&error), "{error:#}");
+ assert!(busy > 0);
+ assert!(start.elapsed() < std::time::Duration::from_secs(1));
+ assert_eq!(snapshot(&holder), before);
+ assert_eq!(
+ holder
+ .query_row("PRAGMA journal_mode", [], |r| r.get::<_, String>(0))
+ .unwrap(),
+ "delete"
+ );
+ holder.execute_batch("ROLLBACK;").unwrap();
+ // The committed migration is usable after contention clears.
+ Queue::open(&dir).unwrap();
+}
+
+#[test]
+fn journal_reclassification_busy_preserves_committed_migration_and_retries_same_queue() {
+ use queue_under_test::OpenPhase;
+ let dir = v1_fixture("exclusive-reclassification");
+ let path = dir.join("relay.sqlite");
+ let holder = rusqlite::Connection::open(&path).unwrap();
+ let before = snapshot(&holder);
+ let mut committed = Vec::new();
+ let mut busy = 0;
+ let start = std::time::Instant::now();
+ let result = queue_under_test::Queue::open_for_test(
+ &dir,
+ std::time::Duration::from_millis(40),
+ &mut |phase| match phase {
+ OpenPhase::BeforeJournal => {
+ assert_eq!(
+ holder
+ .query_row(
+ "SELECT value FROM meta WHERE key='schema_version'",
+ [],
+ |r| r.get::<_, String>(0)
+ )
+ .unwrap(),
+ "2"
+ );
+ holder.prepare("SELECT outcome FROM receipt").unwrap();
+ committed = std::fs::read(&path).unwrap();
+ holder.execute_batch("BEGIN EXCLUSIVE;").unwrap();
+ }
+ OpenPhase::JournalBusy => busy += 1,
+ _ => {}
+ },
+ );
+ let error = result.unwrap_err();
+ assert!(start.elapsed() < std::time::Duration::from_secs(1));
+ assert!(busy > 1, "one short budget must contain retries");
+ assert!(queue_under_test::is_lock_contention(&error));
+ let display = format!("{error:#}");
+ assert!(display.contains("queue busy"), "{display}");
+ assert!(
+ display.contains("retry opening the same queue"),
+ "{display}"
+ );
+ for misleading in [
+ "not a usable relay queue",
+ "nothing was modified",
+ "empty directory",
+ "restore",
+ ] {
+ assert!(!display.contains(misleading), "{display}");
+ }
+ let cause = error.downcast_ref::<rusqlite::Error>().unwrap().to_string();
+ assert_eq!(display.matches(&cause).count(), 1, "{display}");
+ assert!(std::fs::read(&path).unwrap() == committed);
+ assert_eq!(snapshot(&holder), before);
+ holder.execute_batch("ROLLBACK;").unwrap();
+ let queue = Queue::open(&dir).unwrap();
+ assert_eq!(queue.stats(200).unwrap().receipt_outcomes["unknown"], 1);
+ assert_eq!(snapshot(&holder), before);
+}
+
+#[test]
+fn classification_read_failures_display_the_sqlite_cause_once_and_preserve_foreign_bytes() {
+ for malformed_file in [false, true] {
+ let dir = if malformed_file {
+ let dir = fsguard::prepare_queue_dir(&queue_dir(&fixture("invalid-sqlite"))).unwrap();
+ let path = dir.join("relay.sqlite");
+ fsguard::create_private_file(&path).unwrap();
+ std::fs::OpenOptions::new()
+ .append(true)
+ .open(&path)
+ .unwrap()
+ .write_all(b"not a SQLite database")
+ .unwrap();
+ dir
+ } else {
+ let dir = v1_fixture("missing-meta");
+ let conn = rusqlite::Connection::open(dir.join("relay.sqlite")).unwrap();
+ conn.execute_batch("DROP TABLE meta;").unwrap();
+ dir
+ };
+ let path = dir.join("relay.sqlite");
+ let before = std::fs::read(&path).unwrap();
+ let error = Queue::open(&dir).unwrap_err();
+ assert!(!queue_under_test::is_lock_contention(&error));
+ let display = format!("{error:#}");
+ assert!(display.contains("not a usable relay queue"), "{display}");
+ let cause = error.downcast_ref::<rusqlite::Error>().unwrap().to_string();
+ assert_eq!(display.matches(&cause).count(), 1, "{display}");
+ assert!(std::fs::read(&path).unwrap() == before);
+ for name in fsguard::SIDECARS {
+ assert!(!dir.join(name).exists());
+ }
+ }
+}
+
+#[test]
+fn a_foreign_database_with_a_writer_is_refused_before_write_coordination() {
+ let dir = v1_fixture("foreign-with-writer");
+ let path = dir.join("relay.sqlite");
+ let holder = rusqlite::Connection::open(&path).unwrap();
+ holder
+ .execute_batch("UPDATE meta SET value='foreign' WHERE key='identity'; BEGIN IMMEDIATE;")
+ .unwrap();
+ let before = std::fs::read(&path).unwrap();
+ let mut reached_after_preflight = false;
+ let error = queue_under_test::Queue::open_for_test(
+ &dir,
+ std::time::Duration::from_millis(40),
+ &mut |_| reached_after_preflight = true,
+ )
+ .unwrap_err();
+ assert!(
+ format!("{error:#}").contains("not a usable relay queue"),
+ "{error:#}"
+ );
+ assert!(!reached_after_preflight);
+ assert_eq!(std::fs::read(&path).unwrap(), before);
+ holder.execute_batch("ROLLBACK;").unwrap();
+}
+
+#[test]
+fn a_foreign_identity_during_journal_retry_is_refused_without_mutation() {
+ use queue_under_test::OpenPhase;
+ for begin in ["BEGIN IMMEDIATE;", "BEGIN EXCLUSIVE;"] {
+ let dir = v1_fixture("foreign-during-retry");
+ let path = dir.join("relay.sqlite");
+ let holder = rusqlite::Connection::open(&path).unwrap();
+ let mut before = Vec::new();
+ let mut busy = 0;
+ let result = queue_under_test::Queue::open_for_test(
+ &dir,
+ std::time::Duration::from_secs(10),
+ &mut |phase| match phase {
+ OpenPhase::BeforeJournal => holder.execute_batch(begin).unwrap(),
+ OpenPhase::JournalBusy => {
+ busy += 1;
+ holder
+ .execute_batch(
+ "ROLLBACK; UPDATE meta SET value='foreign' WHERE key='identity';",
+ )
+ .unwrap();
+ before = std::fs::read(&path).unwrap();
+ }
+ _ => {}
+ },
+ );
+ let error = result.unwrap_err();
+ assert!(format!("{error:#}").contains("not a usable relay queue"));
+ assert!(!queue_under_test::is_lock_contention(&error));
+ assert_eq!(busy, 1);
+ assert_eq!(std::fs::read(&path).unwrap(), before);
+ for name in fsguard::SIDECARS {
+ assert!(!dir.join(name).exists(), "foreign queue gained {name}");
+ }
+ }
+}
+
+#[test]
+fn only_sqlite_busy_and_locked_are_retryable() {
+ for (code, retry) in [
+ (5, true),
+ (6, true),
+ (517, true),
+ (262, true),
+ (1, false),
+ (8, false),
+ (11, false),
+ (17, false),
+ (26, false),
+ ] {
+ let error = anyhow::Error::new(rusqlite::Error::SqliteFailure(
+ rusqlite::ffi::Error::new(code),
+ Some("database is locked".into()),
+ ))
+ .context("configure queue");
+ assert_eq!(
+ queue_under_test::is_lock_contention(&error),
+ retry,
+ "code {code}"
+ );
+ }
+ assert!(!queue_under_test::is_lock_contention(&anyhow::anyhow!(
+ "database is locked"
+ )));
+ assert!(!queue_under_test::is_lock_contention(
+ &rusqlite::Error::InvalidQuery.into()
+ ));
+}
+
+#[test]
+fn journal_retry_refuses_a_changed_version_or_empty_database_without_mutation() {
+ use queue_under_test::OpenPhase;
+ for mutation in [
+ "UPDATE meta SET value='1' WHERE key='schema_version';",
+ "DROP TABLE meta; DROP TABLE binding; DROP TABLE pending; DROP TABLE receipt; DROP TABLE session_agent;",
+ ] {
+ let dir = v1_fixture("changed-version-or-empty-db");
+ let path = dir.join("relay.sqlite");
+ let holder = rusqlite::Connection::open(&path).unwrap();
+ let mut before = Vec::new();
+ let mut busy = 0;
+ let result = queue_under_test::Queue::open_for_test(
+ &dir,
+ std::time::Duration::from_secs(10),
+ &mut |phase| match phase {
+ OpenPhase::BeforeJournal => holder.execute_batch("BEGIN IMMEDIATE;").unwrap(),
+ OpenPhase::JournalBusy => {
+ busy += 1;
+ holder.execute_batch("ROLLBACK;").unwrap();
+ holder.execute_batch(mutation).unwrap();
+ before = std::fs::read(&path).unwrap();
+ }
+ _ => {}
+ },
+ );
+ assert!(
+ format!("{:#}", result.unwrap_err()).contains("changed before journal configuration")
+ );
+ assert_eq!(busy, 1);
+ assert_eq!(std::fs::read(&path).unwrap(), before);
+ for name in fsguard::SIDECARS {
+ assert!(!dir.join(name).exists(), "changed queue gained {name}");
+ }
+ }
+}
+
+#[test]
+fn fresh_queue_init_and_v1_reopens_work_across_processes() {
+ for legacy in [false, true] {
+ let dir = if legacy {
+ v1_fixture("process-reopen")
+ } else {
+ fsguard::prepare_queue_dir(&queue_dir(&fixture("process-init"))).unwrap()
+ };
+ let before = legacy
+ .then(|| snapshot(&rusqlite::Connection::open(dir.join("relay.sqlite")).unwrap()));
+ let barrier = Arc::new(std::sync::Barrier::new(4));
+ let handles: Vec<_> = (0..4)
+ .map(|_| {
+ let dir = dir.clone();
+ let barrier = barrier.clone();
+ thread::spawn(move || {
+ let mut command =
+ std::process::Command::new(env!("CARGO_BIN_EXE_ai-memory-relay"));
+ if legacy {
+ command.arg("status");
+ } else {
+ command.args([
+ "init",
+ "--server-url",
+ "http://127.0.0.1:9/",
+ "--producer",
+ "example.runtime",
+ "--actor",
+ "operator-a",
+ "--workspace",
+ "team",
+ "--project",
+ "app",
+ ]);
+ }
+ command.arg("--queue-dir").arg(dir);
+ barrier.wait();
+ command.output().unwrap()
+ })
+ })
+ .collect();
+ let outputs: Vec<_> = handles
+ .into_iter()
+ .map(|handle| handle.join().unwrap())
+ .collect();
+ for output in outputs {
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+ let queue = Queue::open(&dir).unwrap();
+ if let Some(before) = before {
+ assert_eq!(
+ snapshot(&rusqlite::Connection::open(queue.path()).unwrap()),
+ before
+ );
+ }
+ assert_eq!(queue.binding().unwrap().project, "app");
+ }
+}
+
+#[test]
+fn interrupted_and_failed_migrations_roll_back_and_recover() {
+ let dir = v1_fixture("rollback-migration");
+ let mut conn = rusqlite::Connection::open(dir.join("relay.sqlite")).unwrap();
+ let before = snapshot(&conn);
+ {
+ let tx = conn
+ .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
+ .unwrap();
+ tx.execute_batch("ALTER TABLE receipt ADD COLUMN outcome TEXT; UPDATE meta SET value='2' WHERE key='schema_version';").unwrap();
+ // Dropping an uncommitted transaction models interruption.
+ }
+ assert_eq!(snapshot(&conn), before);
+ conn.execute_batch("CREATE TRIGGER refuse_migration BEFORE UPDATE ON meta BEGIN SELECT RAISE(ABORT,'injected migration failure'); END;").unwrap();
+ assert!(Queue::open(&dir).is_err());
+ assert_eq!(snapshot(&conn), before);
+ assert!(conn.prepare("SELECT outcome FROM receipt").is_err());
+ conn.execute_batch("DROP TRIGGER refuse_migration;")
+ .unwrap();
+ drop(conn);
+ Queue::open(&dir).unwrap();
+}
+
+#[test]
+fn unknown_schemas_refuse_without_mutation() {
+ for version in ["3", "garbage", "0"] {
+ let dir = v1_fixture("future-schema");
+ let conn = rusqlite::Connection::open(dir.join("relay.sqlite")).unwrap();
+ conn.execute(
+ "UPDATE meta SET value=?1 WHERE key='schema_version'",
+ [version],
+ )
+ .unwrap();
+ drop(conn);
+ let path = dir.join("relay.sqlite");
+ let before = std::fs::read(&path).unwrap();
+ assert!(Queue::open(&dir).is_err());
+ assert_eq!(std::fs::read(&path).unwrap(), before);
+ }
+}
+
+#[test]
+fn sparse_drop_ack_dequeues_and_records_outcomes() {
+ let root = fixture("sparse-outcomes");
+ let server = stub(vec![Reply::Json(429, r#"{"accepted":1,"accepted_indices":[0,2],"results":[{"index":0,"outcome":"stored"},{"index":2,"outcome":"dropped_policy"}]}"#.into())]);
+ let dir = bind(&root, &server.url());
+ let mut queue = Queue::open(&dir).unwrap();
+ queue
+ .enqueue(
+ &(0..3)
+ .map(|i| valid(&format!("e{i}"), "codex", "session-start", &format!("s{i}")))
+ .collect::<Vec<_>>(),
+ ai_memory_relay::now_ms(),
+ )
+ .unwrap();
+ drop(queue);
+ let report = flush(&dir);
+ assert!(report.failure.is_none(), "{report:?}");
+ assert_eq!(pending_count(&dir), 1);
+ let stats = Queue::open(&dir)
+ .unwrap()
+ .stats(ai_memory_relay::now_ms())
+ .unwrap();
+ assert_eq!(stats.receipt_outcomes["stored"], 1);
+ assert_eq!(stats.receipt_outcomes["dropped_policy"], 1);
+ assert!(
+ report
+ .summary
+ .iter()
+ .any(|s| s.contains("\"dropped_policy\":1"))
+ );
+}
+
+#[test]
+fn malformed_results_keep_every_item_pending() {
+ let cases = [
+ r#"{"accepted":2,"results":[]}"#,
+ r#"{"accepted":2,"results":null}"#,
+ r#"{"accepted":2,"results":[{"index":0,"outcome":"stored"},{"index":1}]}"#,
+ r#"{"accepted":2,"results":[{"index":0,"outcome":"stored"},{"index":1,"outcome":7}]}"#,
+ r#"{"accepted":2,"results":[{"index":0,"outcome":"stored"},{"index":0,"outcome":"stored"}]}"#,
+ r#"{"accepted":1,"results":[{"index":0,"outcome":"stored"},{"index":1,"outcome":"stored"}]}"#,
+ r#"{"accepted":2,"results":[{"index":1,"outcome":"stored"},{"index":0,"outcome":"stored"}]}"#,
+ r#"{"accepted":2,"results":[{"index":0,"outcome":"stored"},{"index":2,"outcome":"stored"}]}"#,
+ r#"{"accepted":2,"failed_index":1,"results":[{"index":0,"outcome":"stored"},{"index":1,"outcome":"stored"}]}"#,
+ ];
+ for body in cases {
+ let root = fixture("invalid-results");
+ let server = stub(vec![Reply::Json(200, body.into())]);
+ let dir = bind(&root, &server.url());
+ let mut queue = Queue::open(&dir).unwrap();
+ queue
+ .enqueue(
+ &[
+ valid("a", "codex", "session-start", "a"),
+ valid("b", "codex", "session-start", "b"),
+ ],
+ ai_memory_relay::now_ms(),
+ )
+ .unwrap();
+ drop(queue);
+ assert!(flush(&dir).failure.is_some(), "{body}");
+ assert_eq!(pending_count(&dir), 2, "{body}");
+ assert_eq!(
+ Queue::open(&dir)
+ .unwrap()
+ .stats(ai_memory_relay::now_ms())
+ .unwrap()
+ .receipts,
+ 0
+ );
+ }
+}
+
+#[test]
+fn old_server_and_future_outcome_strings_are_unknown() {
+ for body in [
+ r#"{"accepted":1}"#,
+ r#"{"accepted":1,"results":[{"index":0,"outcome":"future_outcome"}]}"#,
+ ] {
+ let root = fixture("unknown-outcome");
+ let server = stub(vec![Reply::Json(200, body.into())]);
+ let dir = bind(&root, &server.url());
+ let mut queue = Queue::open(&dir).unwrap();
+ queue
+ .enqueue(
+ &[valid("a", "codex", "session-start", "a")],
+ ai_memory_relay::now_ms(),
+ )
+ .unwrap();
+ drop(queue);
+ assert!(flush(&dir).failure.is_none());
+ assert_eq!(
+ Queue::open(&dir)
+ .unwrap()
+ .stats(ai_memory_relay::now_ms())
+ .unwrap()
+ .receipt_outcomes["unknown"],
+ 1
+ );
+ }
+}
+
+#[test]
+fn receipt_conflicts_preserve_first_known_outcome_and_counts_use_retained_window() {
+ let dir = v1_fixture("receipt-window");
+ let mut queue = Queue::open(&dir).unwrap();
+ let conn = rusqlite::Connection::open(dir.join("relay.sqlite")).unwrap();
+ conn.execute_batch("INSERT INTO receipt VALUES('key-a','hash-a',101,102,'stored');")
+ .unwrap();
+ queue.confirm(&[("key-a".into(), "replayed")], 200).unwrap();
+ let (hash, first, result): (String, i64, String) = conn
+ .query_row(
+ "SELECT body_sha256,first_attempt_ms,outcome FROM receipt WHERE ingest_key='key-a'",
+ [],
+ |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
+ )
+ .unwrap();
+ assert_eq!(
+ (hash, first, result),
+ ("hash-a".into(), 101, "stored".into())
+ );
+ let now = identity::RETRY_WINDOW_MS + 102;
+ let stats = queue.stats(now).unwrap();
+ assert_eq!(stats.receipt_outcomes["stored"], 0);
+ assert_eq!(stats.receipt_outcomes["unknown"], 1);
+ queue.prune(now).unwrap();
+ assert_eq!(queue.stats(now).unwrap().receipts, 1);
+ let document: serde_json::Value =
+ serde_json::from_str(&relay::status(&dir).unwrap().summary[0]).unwrap();
+ assert_eq!(
+ document["receipt_outcomes"].as_object().unwrap().len(),
+ ack::OUTCOMES.len()
+ );
+}
+
+#[test]
+fn receipt_conflicts_promote_legacy_unknown_outcomes() {
+ for previous in [None, Some("unknown")] {
+ let dir = v1_fixture("receipt-promote");
+ let mut queue = Queue::open(&dir).unwrap();
+ let conn = rusqlite::Connection::open(dir.join("relay.sqlite")).unwrap();
+ conn.execute(
+ "INSERT INTO receipt VALUES('key-a','hash-a',101,102,?1)",
+ [previous],
+ )
+ .unwrap();
+ queue.confirm(&[("key-a".into(), "stored")], 200).unwrap();
+ let actual: String = conn
+ .query_row(
+ "SELECT outcome FROM receipt WHERE ingest_key='key-a'",
+ [],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(actual, "stored");
+ }
+}
+
+#[test]
+fn every_current_outcome_is_persisted_and_flush_counts_acknowledgements() {
+ let root = fixture("all-outcomes");
- let results: Vec<_> = ack::OUTCOMES[..8]
++ let known = &ack::OUTCOMES[..ack::OUTCOMES.len() - 1];
++ let results: Vec<_> = known
+ .iter()
+ .enumerate()
+ .map(|(index, outcome)| serde_json::json!({"index":index,"outcome":outcome}))
+ .collect();
- let body = serde_json::json!({"accepted":8,"accepted_indices":(0..8).collect::<Vec<_>>(),"results":results});
++ let body = serde_json::json!({"accepted":known.len(),"accepted_indices":(0..known.len()).collect::<Vec<_>>(),"results":results});
+ let server = stub(vec![Reply::Json(200, body.to_string())]);
+ let dir = bind(&root, &server.url());
+ let mut queue = Queue::open(&dir).unwrap();
+ queue
+ .enqueue(
- &(0..8)
++ &(0..known.len())
+ .map(|i| valid(&format!("e{i}"), "codex", "session-start", &format!("s{i}")))
+ .collect::<Vec<_>>(),
+ ai_memory_relay::now_ms(),
+ )
+ .unwrap();
+ drop(queue);
+ let report = flush(&dir);
+ assert!(report.failure.is_none(), "{report:?}");
+ assert_eq!(pending_count(&dir), 0);
+ let stats = Queue::open(&dir)
+ .unwrap()
+ .stats(ai_memory_relay::now_ms())
+ .unwrap();
+ let summary = report
+ .summary
+ .iter()
+ .find_map(|s| s.strip_prefix("acknowledged_outcomes: "))
+ .unwrap();
+ let counts: serde_json::Value = serde_json::from_str(summary).unwrap();
- for outcome in &ack::OUTCOMES[..8] {
++ for outcome in known {
+ assert_eq!(stats.receipt_outcomes[*outcome], 1);
+ assert_eq!(counts[*outcome], 1);
+ }
+ assert_eq!(counts["unknown"], 0);
+}
+
+#[test]
+fn results_match_sparse_partial_failure_and_empty_acks() {
+ for (body, len, expected) in [
+ (
+ r#"{"accepted":1,"accepted_indices":[0,2],"failed_index":3,"results":[{"index":0,"outcome":"replayed"},{"index":2,"outcome":"dropped_collision"}]}"#,
+ 5,
+ vec![0, 2],
+ ),
+ (
+ r#"{"accepted":0,"accepted_indices":[],"results":[]}"#,
+ 0,
+ vec![],
+ ),
+ (
+ r#"{"accepted":0,"accepted_indices":[],"results":[]}"#,
+ 3,
+ vec![],
+ ),
+ ] {
+ let parsed: BatchAck = serde_json::from_str(body).unwrap();
+ assert_eq!(ack::validate(len, &parsed).unwrap(), expected);
+ }
+}
diff --cc crates/ai-memory-cli/src/commands/run.rs
index 6c4a9619,06282eba..34bbc5f1
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@@ -16,17 -16,16 +16,18 @@@ use ai_memory_workstream::
JailHostFacts, JailSupport, JailToggleChoice, JailToggleKind, LaunchMode, LaunchPlan,
LaunchRoots, ManagedHarness, NativeSessionCandidate, ai_jail_support,
allows_native_session_adoption, apply_claude_true_yolo, apply_yolo, build_ai_jail_invocation,
- build_launch_plan, build_launch_plan_with_env, crush_global_config_path,
- discover_native_session, export_transcript, has_native_session_selector, inside_ai_jail_here,
- inspect_repository, is_interactive_session_invocation, jail_checklist, jail_toggle,
- kiro_explicit_session_id, kiro_harness_from_source_cursor, kiro_selects_non_default_engine,
- kiro_selects_v2_engine, kiro_selects_v3_engine, kiro_v3_resume_uses_default_store,
- list_native_sessions, marked_choices, native_session_exists, native_session_in_checkout,
+ build_launch_plan, build_launch_plan_with_env, claude_attached_background_session, clean_path,
+ crush_global_config_path, discover_native_session, export_transcript,
- has_native_session_selector, inside_ai_jail_here, inspect_repository, jail_checklist,
- jail_toggle, kiro_explicit_session_id, kiro_harness_from_source_cursor,
- kiro_selects_non_default_engine, kiro_selects_v2_engine, kiro_selects_v3_engine,
- kiro_v3_resume_uses_default_store, list_native_sessions, marked_choices, native_session_exists,
- native_session_in_checkout, native_store_root, omp_profile_flag, omp_profile_flag_env,
- parse_jail_toggles, store_override_vars, usable_ai_jail_here, wait_for_transcript_flush,
++ has_native_session_selector, inside_ai_jail_here, inspect_repository,
++ is_interactive_session_invocation, jail_checklist, jail_toggle, kiro_explicit_session_id,
++ kiro_harness_from_source_cursor, kiro_selects_non_default_engine, kiro_selects_v2_engine,
++ kiro_selects_v3_engine, kiro_v3_resume_uses_default_store, list_native_sessions,
++ marked_choices, native_session_exists, native_session_in_checkout, native_store_root,
+ omp_profile_flag, omp_profile_flag_env, parse_jail_toggles, store_override_vars,
+ usable_ai_jail_here, wait_for_transcript_flush,
};
use anyhow::{Context as _, Result, anyhow};
+use clap::ValueEnum as _;
use tokio::process::Command;
use tokio_util::sync::CancellationToken;
@@@ -537,8 -333,23 +538,24 @@@ async fn run_once_with_wiring
&repository.cwd,
&run_env,
));
+ let interactive_session = is_interactive_session_invocation(harness, &native_args);
if let Some(orphaned_session) = orphaned_session {
+ let recorded = super::project_registry::recorded_session_store(
+ config,
+ &endpoint,
+ harness.as_str(),
+ &orphaned_session,
+ )
+ .unwrap_or_else(|error| {
+ eprintln!(
+ "ai-memory: could not read the client-local session store record ({error:#}); treating the linked session as deleted"
+ );
+ None
+ });
+ let current = effective_store(harness, &home, &repository.cwd, plan.session_dir.as_deref());
+ if let Some(error) = store_mismatch_error(harness, &orphaned_session, recorded, &current) {
+ acquired_try!(Err(error));
+ }
eprintln!(
"ai-memory: linked {} session {} is missing from its native store; starting fresh and repointing workstream '{}' after the new session is established",
harness.as_str(),
@@@ -701,14 -512,19 +718,25 @@@
home.join(".kiro").display().to_string(),
);
}
- super::run_autowire::ensure_wired_with(config, harness, wire_overrides, &wire_env);
+ super::run_autowire::ensure_wired_with(
+ config,
+ harness,
+ wire_overrides,
+ &wire_env,
+ &repository.cwd,
+ );
}
+ // A Kiro v3 resume that dropped `KIRO_HOME` runs against the default store.
+ let linked_store = effective_store(
+ harness,
+ &home,
+ &repository.cwd,
+ if remove_kiro_home {
+ None
+ } else {
+ plan.session_dir.as_deref()
+ },
+ );
if plan.mode == LaunchMode::Session
&& let Some(native_session_id) = &plan.expected_session_id
{
@@@ -2027,6 -1897,103 +2141,103 @@@ fn build_preflighted_launch_plan
}
}
+ /// The store a launch reads, absolute and normalized so the default store and
+ /// an override spelling the same directory (relative, trailing slash,
+ /// symlinked) compare equal. A relative override resolves against the checkout,
+ /// where the harness runs.
+ fn effective_store(
+ harness: ManagedHarness,
+ home: &Path,
+ cwd: &Path,
+ session_dir: Option<&Path>,
+ ) -> PathBuf {
+ let root = native_store_root(harness, home, session_dir);
+ let absolute = if root.is_absolute() {
+ root
+ } else {
+ cwd.join(root)
+ };
+ std::fs::canonicalize(&absolute).unwrap_or_else(|_| canonical_prefix(&clean_path(&absolute)))
+ }
+
+ /// Canonicalize the deepest existing ancestor and keep the missing tail, so a
+ /// store that does not exist yet still compares equal to the same directory
+ /// once it does (on macOS, `/var` vs `/private/var`).
+ fn canonical_prefix(path: &Path) -> PathBuf {
+ let mut tail = Vec::new();
+ let mut existing = path;
+ loop {
+ if let Ok(real) = std::fs::canonicalize(existing) {
+ return tail.iter().rev().fold(real, |acc, part| acc.join(part));
+ }
+ match (existing.parent(), existing.file_name()) {
+ (Some(parent), Some(name)) => {
+ tail.push(name.to_os_string());
+ existing = parent;
+ }
+ _ => return path.to_path_buf(),
+ }
+ }
+ }
+
+ fn remember_session_store(
+ config: &Config,
+ endpoint: &ServerEndpoint,
+ harness: ManagedHarness,
+ native_session_id: &str,
+ store: &Path,
+ ) {
+ if let Err(error) = super::project_registry::record_session_store(
+ config,
+ endpoint,
+ harness.as_str(),
+ native_session_id,
+ store,
+ ) {
+ eprintln!(
+ "ai-memory: could not record the client-local session store ({error:#}); continuing the managed run"
+ );
+ }
+ }
+
+ /// Refuse to replace a linked session that was launched under a different
+ /// native store than this launch resolves.
+ ///
+ /// Such a session most likely still exists in its own store; starting fresh
+ /// would repoint the workstream and orphan it. With no record (or the same
+ /// store) the session really is gone and replacing it stays the right call.
+ fn store_mismatch_error(
+ harness: ManagedHarness,
+ native_session_id: &str,
+ recorded: Option<PathBuf>,
+ current: &Path,
+ ) -> Option<anyhow::Error> {
+ let recorded = recorded?;
+ if recorded == current {
+ return None;
+ }
+ // Native flags and profiles move some stores too, not only the variables.
+ let flags: &[&str] = match harness {
+ ManagedHarness::Pi => &["--session-dir"],
+ ManagedHarness::Omp => &["--session-dir", "--profile", "OMP_PROFILE"],
+ ManagedHarness::Crush => &["--data-dir"],
+ _ => &[],
+ };
+ let selectors = [store_override_vars(harness), flags].concat().join("/");
+ let hint = if selectors.is_empty() {
+ " from the original environment".to_owned()
+ } else {
+ format!(" with the same {selectors}")
+ };
+ Some(anyhow!(
- "linked {} session {} was launched under {} but this launch resolves {}; relaunch{hint} to resume it, or pass --fresh to start a new session",
++ "linked {} session {} was launched under {} but this launch resolves {}; relaunch{hint} (or the same `ai-memory run --profile`) to resume it, or pass --fresh to start a new session",
+ harness.as_str(),
+ display_session_id(native_session_id),
+ super::show::terminal_text(&recorded.to_string_lossy()),
+ super::show::terminal_text(&current.to_string_lossy()),
+ ))
+ }
+
fn ensure_executable_available(harness: ManagedHarness, executable: Option<&OsStr>) -> Result<()> {
let program = executable.unwrap_or_else(|| OsStr::new(harness.executable()));
if executable_available(program) {
@@@ -4733,6 -4431,131 +4944,132 @@@ mod tests
server.abort();
}
+ /// A store mismatch must stop before `/link` and before the harness
+ /// spawns, release the prepared run, and leave the workstream link alone.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn a_store_mismatch_stops_before_linking_or_spawning_and_releases_the_run() {
+ use std::os::unix::fs::PermissionsExt as _;
+
+ use crate::commands::run_autowire::WireOverrides;
+ use crate::config::Config;
+
+ const LINKED: &str = "33333333-3333-4333-8333-333333333333";
+ let cancels = Arc::new(AtomicUsize::new(0));
+ let links = Arc::new(AtomicUsize::new(0));
+ let cancel_hits = Arc::clone(&cancels);
+ let link_hits = Arc::clone(&links);
+ let app = Router::new()
+ .route(
+ "/workstream/runs",
+ post(|| async {
+ axum::Json(PrepareManagedRunResponse {
+ workstream_id: WorkstreamId::new(),
+ workstream_name: "default".into(),
+ run_id: ManagedRunId::new(),
+ resolved_agent: None,
+ native_session_id: Some(LINKED.into()),
+ source_cursor: None,
+ sync_after: 0,
+ sync_through: 0,
+ may_adopt_existing_session: false,
+ })
+ }),
+ )
+ .route(
+ "/workstream/runs/{run_id}/cancel",
+ post(move || {
+ cancel_hits.fetch_add(1, Ordering::SeqCst);
+ async { StatusCode::NO_CONTENT }
+ }),
+ )
+ .route(
+ "/workstream/runs/{run_id}/link",
+ post(move || {
+ link_hits.fetch_add(1, Ordering::SeqCst);
+ async { StatusCode::NO_CONTENT }
+ }),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+
+ let home = tempfile::tempdir().unwrap();
+ let data = tempfile::tempdir().unwrap();
+ let repo = tempfile::tempdir().unwrap();
+ let spawned = repo.path().join("spawned");
+ let script = repo.path().join("marker-harness");
+ std::fs::write(
+ &script,
+ format!("#!/bin/sh\ntouch {}\nexit 0\n", spawned.display()),
+ )
+ .unwrap();
+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
+
+ let mut config = Config::load(None, Some(home.path().to_path_buf())).unwrap();
+ config.data_dir = data.path().to_path_buf();
+ config.home_dir = Some(home.path().to_string_lossy().into_owned());
+ config.server_url = format!("http://{address}");
+ config.run_autowire = false;
+
+ let endpoint = ServerEndpoint::from_config_resolving_auth(&config).await;
+ let custom = home.path().join("claude-glm").join("projects");
+ let recorded = effective_store(
+ ManagedHarness::Claude,
+ home.path(),
+ repo.path(),
+ Some(&custom),
+ );
+ super::super::project_registry::record_session_store(
+ &config, &endpoint, "claude", LINKED, &recorded,
+ )
+ .unwrap();
+
+ let default_home = home.path().join(".claude");
+ let args = RunArgs {
+ workspace: Some("ws".into()),
+ project: Some("proj".into()),
+ workstream: None,
+ new_workstream: None,
+ executable: Some(script),
+ yolo: false,
+ true_yolo: false,
+ jail: None,
+ no_jail: false,
+ fresh: false,
+ force_unlock: false,
+ no_autowire: true,
++ profile: None,
+ // Pinned so a contributor's own CLAUDE_CONFIG_DIR cannot leak in.
+ env: vec![(
+ "CLAUDE_CONFIG_DIR".to_string(),
+ default_home.to_string_lossy().into_owned(),
+ )],
+ env_file: None,
+ harness: Some(RunHarnessChoice::Claude),
+ native_args: Vec::new(),
+ };
+
+ let error = run_from_with_wiring(&config, args, repo.path(), &WireOverrides::default())
+ .await
+ .expect_err("a session linked under another store must not be replaced");
+ let message = format!("{error:#}");
+ assert!(message.contains("--fresh"), "{message}");
+ assert!(!spawned.exists(), "the harness must not start");
+ assert_eq!(
+ links.load(Ordering::SeqCst),
+ 0,
+ "the workstream link must not move"
+ );
+ assert_eq!(
+ cancels.load(Ordering::SeqCst),
+ 1,
+ "the prepared run is released"
+ );
+
+ server.abort();
+ }
+
#[test]
fn missing_linked_session_starts_fresh_but_explicit_selectors_win() {
let temp = tempfile::tempdir().unwrap();
diff --cc crates/ai-memory-cli/src/commands/status.rs
index def62ad5,7a499e2d..af422507
--- a/crates/ai-memory-cli/src/commands/status.rs
+++ b/crates/ai-memory-cli/src/commands/status.rs
@@@ -19,21 -19,6 +19,23 @@@ use crate::http_client::{ServerEndpoint
#[derive(Debug, Deserialize, Serialize)]
struct IngestReport {
accepted: u64,
+ #[serde(default)]
+ dropped_unauthorized: u64,
+ #[serde(default)]
+ stored: u64,
+ #[serde(default)]
+ replayed: u64,
+ #[serde(default)]
+ resumed: u64,
+ #[serde(default)]
+ ignored_end: u64,
+ #[serde(default)]
+ dropped_collision: u64,
+ #[serde(default)]
++ dropped_invalid: u64,
++ #[serde(default)]
+ failed: u64,
+
dropped_by_policy: u64,
shed_saturated: u64,
shed_rate_limited: u64,
@@@ -360,14 -345,6 +362,14 @@@ pub async fn run(config: &Config, args
" dropped: {} (capture policy)",
ingest.dropped_by_policy
);
+ println!(
+ " outcomes: {} stored, {} replayed, {} resumed, {} ignored end, {} failed",
+ ingest.stored, ingest.replayed, ingest.resumed, ingest.ignored_end, ingest.failed
+ );
+ println!(
- " drops: {} unauthorized, {} collision",
- ingest.dropped_unauthorized, ingest.dropped_collision
++ " drops: {} unauthorized, {} collision, {} invalid",
++ ingest.dropped_unauthorized, ingest.dropped_collision, ingest.dropped_invalid
+ );
println!(
" shed: {} saturated, {} rate-limited",
ingest.shed_saturated, ingest.shed_rate_limited
@@@ -505,27 -482,6 +507,28 @@@ fn error_detail(role: &ProviderRoleHeal
mod tests {
use super::*;
+ #[test]
+ fn ingest_additions_default_for_older_servers_and_roundtrip() {
+ let old = serde_json::json!({"accepted": 2, "dropped_by_policy": 1, "shed_saturated": 0, "shed_rate_limited": 0, "last_persisted_ms": null});
+ let report: IngestReport = serde_json::from_value(old).unwrap();
+ let mut value = serde_json::to_value(report).unwrap();
+ for name in [
+ "stored",
+ "replayed",
+ "resumed",
+ "ignored_end",
+ "dropped_unauthorized",
+ "dropped_collision",
++ "dropped_invalid",
+ "failed",
+ ] {
+ assert_eq!(value[name], 0);
+ value[name] = serde_json::json!(7);
+ }
+ let current: IngestReport = serde_json::from_value(value.clone()).unwrap();
+ assert_eq!(serde_json::to_value(current).unwrap(), value);
+ }
+
/// #428's counters and #446's gate compose into a trap: under allowlist
/// mode an unmarked repository never sends, so `accepted: 0` with an empty
/// spool looks exactly like a broken install. `status` must be able to say
diff --cc crates/ai-memory-core/src/ingest_metrics.rs
index 7e4af73a,2dcf7b0f..0cd76ad8
--- a/crates/ai-memory-core/src/ingest_metrics.rs
+++ b/crates/ai-memory-core/src/ingest_metrics.rs
@@@ -117,15 -89,9 +125,16 @@@ impl IngestMetrics
pub fn snapshot(&self) -> IngestMetricsSnapshot {
IngestMetricsSnapshot {
accepted: self.accepted.load(Ordering::Relaxed),
+ stored: self.stored.load(Ordering::Relaxed),
+ replayed: self.replayed.load(Ordering::Relaxed),
+ resumed: self.resumed.load(Ordering::Relaxed),
+ ignored_end: self.ignored_end.load(Ordering::Relaxed),
+ dropped_collision: self.dropped_collision.load(Ordering::Relaxed),
+ failed: self.failed.load(Ordering::Relaxed),
+
dropped_by_policy: self.dropped_by_policy.load(Ordering::Relaxed),
dropped_unauthorized: self.dropped_unauthorized.load(Ordering::Relaxed),
+ dropped_invalid: self.dropped_invalid.load(Ordering::Relaxed),
shed_saturated: self.shed_saturated.load(Ordering::Relaxed),
shed_rate_limited: self.shed_rate_limited.load(Ordering::Relaxed),
last_persisted_ms: match self.last_persisted_ms.load(Ordering::Relaxed) {
@@@ -236,16 -173,11 +248,17 @@@ mod tests
vec![
"accepted",
"dropped_by_policy",
+ "dropped_collision",
+ "dropped_invalid",
"dropped_unauthorized",
+ "failed",
+ "ignored_end",
"last_persisted_ms",
+ "replayed",
+ "resumed",
"shed_rate_limited",
- "shed_saturated"
+ "shed_saturated",
+ "stored"
]
);
for v in value.as_object().unwrap().values() {
diff --cc crates/ai-memory-hooks/src/router.rs
index 060bbbde,a6739003..441ea545
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@@ -716,54 -721,6 +716,58 @@@ pub struct HookBatchItem
pub body: serde_json::Value,
}
+/// Final processing classification for an acknowledged hook delivery.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum HookProcessingOutcome {
+ /// A new observation was stored.
+ Stored,
+ /// A completed keyed delivery was repeated.
+ Replayed,
+ /// `ResumePending` retried downstream effects, without promising new writes.
+ /// An `AlreadyEnded` recovery also uses this when a wiki commit or a new
+ /// consolidation job was produced.
+ Resumed,
+ /// Missing/scoped-invalid ends and already-ended deliveries with no
+ /// recovered wiki commit or new consolidation job.
+ IgnoredEnd,
+ /// Capture policy discarded the delivery.
+ DroppedPolicy,
+ /// Subagent capture was disabled.
+ DroppedSubagent,
+ /// The caller lacked project write access.
+ DroppedUnauthorized,
+ /// Session identity or ownership conflicted.
+ DroppedCollision,
++ /// The event had no session id and was not a SessionStart, so it could
++ /// never be stored.
++ DroppedInvalid,
+}
+
+impl HookProcessingOutcome {
+ fn record(self, metrics: &ai_memory_core::IngestMetrics) {
+ match self {
+ Self::Stored => metrics.record_stored(),
+ Self::Replayed => metrics.record_replayed(),
+ Self::Resumed => metrics.record_resumed(),
+ Self::IgnoredEnd => metrics.record_ignored_end(),
+ Self::DroppedPolicy | Self::DroppedSubagent => metrics.record_dropped_by_policy(),
+ Self::DroppedUnauthorized => metrics.record_dropped_unauthorized(),
++ Self::DroppedInvalid => metrics.record_dropped_invalid(),
+ Self::DroppedCollision => metrics.record_dropped_collision(),
+ }
+ }
+}
+
+/// Processing result for one acknowledged batch index.
+#[derive(Debug, Serialize)]
+pub struct HookBatchResult {
+ /// Original zero-based request index.
+ pub index: usize,
+ /// Terminal processing outcome.
+ pub outcome: HookProcessingOutcome,
+}
+
/// Response to `POST /hook/batch`: legacy clients read the contiguous leading
/// prefix in `accepted`; newer clients prefer `accepted_indices` when present to
/// retain only non-contiguous items skipped by per-source rate limiting.
@@@ -914,6 -853,20 +918,24 @@@ async fn handle_hook_batch
accepted_indices.push(idx);
continue;
}
+ // An event with no session id that is not a SessionStart can never be
+ // stored. Reporting it as failed made the drain retry it until its
+ // attempt budget ran out, stalling every item queued behind it (#1062),
+ // so it is acknowledged and dropped before it spends any capacity.
+ if resolve_session_id(&env).is_err() {
- state.ingest_metrics.record_dropped_invalid();
++ HookProcessingOutcome::DroppedInvalid.record(&state.ingest_metrics);
+ warn!(
+ agent = %env.agent.as_str(),
+ event = ?env.event,
+ "hook batch item has no session id; dropped"
+ );
++ results.push(HookBatchResult {
++ index: idx,
++ outcome: HookProcessingOutcome::DroppedInvalid,
++ });
+ accepted_indices.push(idx);
+ continue;
+ }
let Ok(permit) = state.ingest_semaphore.clone().try_acquire_owned() else {
// The 429 rejects this item AND every item behind it, so count all
// of them: on `/hook` one 429 is one shed event, and a batch that
@@@ -7933,23 -7674,55 +8157,63 @@@ mod tests
.await
.unwrap();
let ack: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(ack["accepted"], 2, "both items leave the spool");
+ assert!(ack.get("failed_index").is_none() || ack["failed_index"].is_null());
++ // A relay releases an acknowledged index only with its result entry.
+ assert_eq!(
+ ack["results"],
- serde_json::json!([{ "index": 1, "outcome": "stored" }])
++ serde_json::json!([
++ { "index": 0, "outcome": "dropped_invalid" },
++ { "index": 1, "outcome": "stored" }
++ ])
+ );
- assert_eq!(ack["accepted"], 0);
- assert_eq!(ack["accepted_indices"], serde_json::json!([1]));
- assert_eq!(ack["failed_index"], 2);
- assert_eq!(state.reader.status_counts().await.unwrap().observations, 1);
- let metrics = state.ingest_metrics.snapshot();
- assert_eq!(
- (
- metrics.accepted,
- metrics.stored,
- metrics.failed,
- metrics.shed_rate_limited
- ),
- (2, 1, 1, 1)
+
+ let snap = metrics.snapshot();
+ assert_eq!(snap.dropped_invalid, 1);
+ assert_eq!(snap.accepted, 1, "only the valid item spends capacity");
+ assert!(
+ state
+ .reader
+ .session_project_ids(SessionId::from_native("behind-it"))
+ .await
+ .unwrap()
+ .is_some(),
+ "the valid item behind the dropped one is stored"
+ );
+ }
+
+ /// Control: a SessionStart without a session id is still processed (the
+ /// server mints one), so it is never counted as an invalid drop.
+ #[tokio::test]
+ async fn handle_hook_batch_still_processes_a_session_less_session_start() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let metrics = state.ingest_metrics.clone();
+
+ let response = handle_hook_batch(
+ State(Arc::new(state)),
+ None,
+ None,
+ None,
+ HeaderMap::new(),
+ Json(vec![HookBatchItem {
+ url: "http://h/hook?event=session-start&agent=claude-code".into(),
+ body: serde_json::json!({}),
+ }]),
+ )
+ .await
+ .into_response();
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let ack: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(ack["accepted"], 1);
+ let snap = metrics.snapshot();
+ assert_eq!(snap.dropped_invalid, 0);
+ assert_eq!(snap.accepted, 1);
+ assert!(
+ snap.last_persisted_ms.is_some(),
+ "it went through the writer"
);
}
diff --cc crates/ai-memory-workstream/src/lib.rs
index 5b8c61d4,3cb4fad8..e2b9bc2c
--- a/crates/ai-memory-workstream/src/lib.rs
+++ b/crates/ai-memory-workstream/src/lib.rs
@@@ -22,8 -22,9 +22,9 @@@ pub use jail::
};
pub use repository::{RepositoryIdentity, inspect_repository};
pub use transcript::{
- AmbiguousNativeSession, ExportedTranscript, NativeSessionCandidate, 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,
+ AmbiguousNativeSession, ExportedTranscript, NativeSessionCandidate,
+ claude_attached_background_session, discover_native_session, export_transcript,
+ kiro_harness_from_source_cursor, kiro_v3_resume_uses_default_store, list_native_sessions,
- native_session_exists, native_session_in_checkout, native_store_root,
++ native_memory_dir, native_session_exists, native_session_in_checkout, native_store_root,
wait_for_transcript_flush,
};
diff --cc docs/external-lifecycle.md
index cf1c1360,49e988ae..bb359823
--- a/docs/external-lifecycle.md
+++ b/docs/external-lifecycle.md
@@@ -160,12 -141,6 +160,13 @@@ Use the tuple recipe when event IDs hav
across concurrent requests and no all-or-nothing transaction for a batch.
- Prefer `accepted_indices` when present. Otherwise `accepted` is the contiguous
acknowledged prefix. Preserve every unacknowledged item for retry.
+- `results` contains one `{index, outcome}` for each acknowledged index, in
+ index order, including an empty array when nothing was acknowledged. Outcomes
+ are `stored`, `replayed`, `resumed`, `ignored_end`, `dropped_policy`,
- `dropped_subagent`, `dropped_unauthorized` and `dropped_collision`. A drop is a
++ `dropped_subagent`, `dropped_unauthorized`, `dropped_collision` and
++ `dropped_invalid` (no session id outside a SessionStart). A drop is a
+ terminal acknowledgement. Older servers omit `results`; the relay records
+ those receipts as `unknown`.
- A rate-limited source can be skipped while other sources advance. Inspect
acknowledgements even on HTTP 429 or a partial failure; `failed_index` identifies
a processing failure after earlier skips. An acknowledgement can also mean a
diff --cc docs/security-boundaries.md
index cb650a74,4e918447..d73f5635
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@@ -55,19 -52,18 +55,19 @@@ boundary not yet built
| 10d | Workspace delete's own row counts are scope-bound to `workspace_id` (a workspace's *own* rows are never over- or under-counted by a sibling workspace's), its cross-workspace observation/handoff cascade is reported by both preview and confirm rather than prevented (same as `purge-project` one level down), the non-empty guard fails closed without `force`, and `delete-workspace`'s `dry_run` always wins | `ai-memory-store/src/ops.rs` `delete_workspace` — every direct count and the `DELETE FROM workspaces` itself are scoped by `workspace_id = ?1`; the two `collateral_*` counts are scoped by `workspace_id != ?1` so a row is counted as one or the other but never both; `projects_deleted > 0 && !force → WorkspaceNotEmpty` fail-closed, and a missing workspace is `NotFound`, both checked identically under `PurgeMode::Preview` and `PurgeMode::Commit`; whole op in one transaction; `admin.rs` `handle_delete_workspace` checks `req.dry_run` unconditionally, before building the confirmed path, mirroring `reclaim-ledger-versions`/`purge-project`; root-only gate is the shared `/admin/*` multi-user auth ladder, not a separate check | `admin_move.rs` `delete_workspace_dry_run_never_counts_a_different_workspaces_rows` — previewing workspace A counts only its own project/page/session/observation/handoff rows, not workspace B's (which holds two like-named projects and its own full row set), and a session living in B that stamps an observation directly into A is counted in A's own `observations_deleted`, never in `collateral_observations_deleted` (the two counts are mutually exclusive by construction); `admin_move.rs` `delete_workspace_force_true_and_dry_run_true_still_only_previews` — `{"force": true, "dry_run": true}` deletes nothing; `ops.rs` `delete_workspace_dry_run_changes_nothing` — every table's row count, including `workspaces` itself and the `purged_scopes` tombstone (the two tables a confirmed delete's own transaction writes to), is identical before/after a `PurgeMode::Preview` run; `ops.rs` `delete_workspace_dry_run_and_confirmed_delete_both_report_collateral_damage_in_another_workspace` and `admin_move.rs` of the same name — deleting workspace W collaterally deletes an observation, and orphans a handoff's session reference, in a *different* workspace (via `sessions` cascading out of W), and both the preview and the confirmed response count it identically — the cascade itself is reported, not blocked, by either; `admin_move.rs` `delete_workspace_dry_run_refuses_non_empty_without_force` / `delete_workspace_dry_run_nonexistent_workspace_returns_404` — same `409`/`404` a confirmed delete would give; `admin.rs` `multiuser_delete_workspace_dry_run_rejects_db_user_and_anonymous` — root reaches the preview handler (404 control), DB user gets 403, anonymous gets 401 | STRONG |
| 10e | Reconcile-tombstone of a disk-deleted page is opt-in, soft, scope-bound, and false-positive-guarded (invariant #16, #929 delete-half) | `ai-memory-wiki/src/watcher.rs` — off by default (`[maintenance] reconcile_tombstones_deleted_pages`); a page is tombstoned only after its file is observed missing on two consecutive passes (streak resets if the path's `PageId` changed), re-verified against the live filesystem immediately before acting, with reserved/indexed-but-unwalked paths (`bootstrap.md`, `_meta.md`, `_pending/`, `sessions/*.md`) excluded and a circuit breaker that skips a whole scope when `> max(3, 50%)` of its pages look missing or a non-partial walk finds nothing; `ai-memory-store/src/ops.rs` `soft_delete_for_reconcile_if_latest` is a soft tombstone (`is_latest=0` + `superseded_at`, decay's shape) through the single writer actor in one transaction — never a filesystem write — scoped to the page's own `(workspace_id, project_id)` | `watcher.rs` `reconcile_delete_disabled_by_default_never_tombstones_a_missing_page`, `reconcile_delete_cross_project_isolation` (project A's deletion never tombstones project B's same-path page), `reconcile_tombstone_refuses_a_stale_latest_id`, `reconcile_tombstone_refuses_when_the_file_still_exists`, `reconcile_tombstone_never_touches_the_filesystem`; `ops.rs` `reconcile_tombstone_resurrects_instead_of_orphaning_on_recreate` | STRONG |
| 10f | Session-time repair is scope-bound (no cross-project timestamp rewrite) | `ai-memory-store/src/ops.rs` `repair_session_times` — every candidate is read back and updated with `WHERE id=? AND workspace_id=? AND project_id=?`; a row outside that 3-tuple is reported `NotFound` and untouched, same code path as an id that does not exist at all; `ai-memory-mcp/src/admin.rs` `handle_repair_session_times` passes the caller's `(workspace, project)` straight through, never the candidate's own | `ops.rs` `repair_session_times_does_not_touch_a_session_of_another_project` (control: sibling session in-scope repaired in the same batch); `admin_repair_session_times.rs` `cross_project_session_is_not_found_and_untouched`; both bite-checked by dropping the `project_id` filter | STRONG |
-| 11a | Hook backpressure (202/429) + bounded fan-out (invariant #5) | `ai-memory-hooks/src/router.rs` semaphore→429, 202 immediately, `MAX_HOOK_BATCH_ITEMS`, bounded LRU limiter | `router.rs` `handle_hook_returns_429_when_ingest_saturated`, `ingest_rate_limiter_is_bounded` | STRONG |
-| 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn), including shell commands whose arguments name an ignored path (`match_command`; argv elements matched whole and tokenized); an invalid marker makes file and shell calls metadata-only, and the server admits a metadata-only shell body only under an invalid marker (`router.rs` `metadata_protocol_is_legal`); generated OpenCode/OMP/Pi/OpenClaw integrations mirror it in `render_shared.rs` `ts_capture_policy_v1` (`captureMatchCommand`). Candidate/argument flavor (`Flavor::Posix` vs `Flavor::Windows`, used to pick which `ignore_paths` patterns even apply) is derived from the **host** (the cwd), never from the candidate string alone — a POSIX-host candidate spelled with a leading `//` is collapsed to a single `/` before flavor detection (`normalize_candidate`; TS `captureNormalize`'s `windowsHost` parameter, sourced from `captureHostWindows(cwd)`), fixing GHSA-vh98 (a `//`-prefixed candidate used to self-classify as `Flavor::Windows` regardless of host, matching zero POSIX patterns and being captured instead of dropped); a genuine Windows/UNC host (cwd itself windows-flavored) is unaffected | `capture_policy.rs` per-agent `…honors_exclusions` tests, `shell_fixture_vectors` (shared `capture-policy.json` `shell` drop/keep vectors: tool aliases incl. OpenClaw/Devin `exec`, `workdir`, glob directories, Windows paths, and a POSIX-host leading-`//` command via `/{root}/docs/adr/x.md`), `shell_tool_shapes_of_every_adapter_honor_exclusions`, `fixture_vectors` (incl. TS-adapter `bash`/`exec` vectors, and `normalization`'s leading-`//` POSIX vectors alongside the kept Windows-cwd UNC vectors as the no-regression control); `shell_matching_is_off_when_inactive_and_fails_closed_when_invalid_or_over_budget`; `router.rs` `capture_protocol_shell_decisions_survive_server_reinspection`, `capture_protocol_invalid_marker_shell_is_metadata_only` (active metadata-only shell refused, older client's invalid-marker keep stripped, commandless control kept), `capture_protocol_unparseable_marker_strips_shell_events` (server fallback for an unparseable marker), `capture_protocol_invalid_shell_metadata_claim_must_be_canonical` (a stripped shell claim with a path count or non-`extracted` state is refused); `capture_policy.rs` `invalid_marker_strips_shell_calls_with_unparseable_commands`, `long_bash_lc_script_in_argv_is_not_dropped_by_the_match_budget`, **`a_leading_double_slash_candidate_does_not_escape_posix_ignore_paths_via_flavor_mismatch`** (GHSA-vh98 adversarial: attempts the `//repo/secret/...` violation on a POSIX host, proves it now drops, with a plain-single-slash control and a Windows-hosted genuine-UNC control both still correct — fails on the pre-fix code); `hook.rs` `shell_command_reading_an_ignored_path_is_dropped_before_spool`; `render_shared.rs` `generated_capture_policy_v1_node_runtime_evidence` (runs the same fixture sections, including the GHSA-vh98 vectors, against the emitted TypeScript; `#[ignore]` locally, run with `--ignored` under Node 24 by the Linux CI test job) | STRONG |
-| 11c | 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 |
+| 11a | Hook backpressure (202/429) + bounded fan-out (invariant #5) | `ai-memory-hooks/src/router.rs` semaphore→429, 202 immediately, `MAX_HOOK_BATCH_ITEMS`, bounded LRU limiter; batch acknowledgements retain only processed indices and classify terminal drops without consuming capacity | `router.rs` `handle_hook_returns_429_when_ingest_saturated`, `ingest_rate_limiter_is_bounded`; `router.rs` `handle_hook_batch_skips_rate_limited_first_item_and_accepts_later_source`, `handle_hook_batch_reports_failed_index_after_rate_limited_skip`, `handle_hook_batch_drops_subagent_events_before_capacity_check` (each asserts result indices and includes an accepted control) | STRONG |
+| 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn), including shell commands whose arguments name an ignored path (`match_command`; argv elements matched whole and tokenized); an invalid marker makes file and shell calls metadata-only, and the server admits a metadata-only shell body only under an invalid marker (`router.rs` `metadata_protocol_is_legal`); generated OpenCode/OMP/Pi/OpenClaw integrations mirror it in `render_shared.rs` `ts_capture_policy_v1` (`captureMatchCommand`). Candidate/argument flavor (`Flavor::Posix` vs `Flavor::Windows`, used to pick which `ignore_paths` patterns even apply) is derived from the **host** (the cwd), never from the candidate string alone — a POSIX-host candidate spelled with a leading `//` is collapsed to a single `/` before flavor detection (`normalize_candidate`; TS `captureNormalize`'s `windowsHost` parameter, sourced from `captureHostWindows(cwd)`), fixing GHSA-vh98 (a `//`-prefixed candidate used to self-classify as `Flavor::Windows` regardless of host, matching zero POSIX patterns and being captured instead of dropped); a genuine Windows/UNC host (cwd itself windows-flavored) is unaffected; `hook.rs` `--check-capture` preflight uses the same capture policy before any spool or spawn | `capture_policy.rs` per-agent `…honors_exclusions` tests, `shell_fixture_vectors` (shared `capture-policy.json` `shell` drop/keep vectors: tool aliases incl. OpenClaw/Devin `exec`, `workdir`, glob directories, Windows paths, and a POSIX-host leading-`//` command via `/{root}/docs/adr/x.md`), `shell_tool_shapes_of_every_adapter_honor_exclusions`, `fixture_vectors` (incl. TS-adapter `bash`/`exec` vectors, and `normalization`'s leading-`//` POSIX vectors alongside the kept Windows-cwd UNC vectors as the no-regression control); `shell_matching_is_off_when_inactive_and_fails_closed_when_invalid_or_over_budget`; `router.rs` `capture_protocol_shell_decisions_survive_server_reinspection`, `capture_protocol_invalid_marker_shell_is_metadata_only` (active metadata-only shell refused, older client's invalid-marker keep stripped, commandless control kept), `capture_protocol_unparseable_marker_strips_shell_events` (server fallback for an unparseable marker), `capture_protocol_invalid_shell_metadata_claim_must_be_canonical` (a stripped shell claim with a path count or non-`extracted` state is refused); `capture_policy.rs` `invalid_marker_strips_shell_calls_with_unparseable_commands`, `long_bash_lc_script_in_argv_is_not_dropped_by_the_match_budget`, **`a_leading_double_slash_candidate_does_not_escape_posix_ignore_paths_via_flavor_mismatch`** (GHSA-vh98 adversarial: attempts the `//repo/secret/...` violation on a POSIX host, proves it now drops, with a plain-single-slash control and a Windows-hosted genuine-UNC control both still correct — fails on the pre-fix code); `hook.rs` `shell_command_reading_an_ignored_path_is_dropped_before_spool`; `render_shared.rs` `generated_capture_policy_v1_node_runtime_evidence` (runs the same fixture sections, including the GHSA-vh98 vectors, against the emitted TypeScript; `#[ignore]` locally, run with `--ignored` under Node 24 by the Linux CI test job); `hook.rs` `check_capture_refuses_partial_scope_and_excluded_content` (ignored-path and partial-scope violations refused, complete public-path control passes), `check_capture_bounds_marker_hints_and_refuses_oversized_scope` (513-byte hints refused, 512-byte control passes; native routing preserved) | STRONG |
| 11c | Capture hook ≤200ms budget (invariant #5) | `hooks/_lib.sh` capture path `curl --max-time 0.2` (context-fetch 1.0s and background drain 2.0s are separate, larger-budget paths) | none (shell-script timeout; hard to unit-test) — watch on any capture-path change | WATCH |
-| 11d | Hook server-profile routing: a marker-selected server gets only its own capture and its own token (#992) | `ai-memory-cli/src/server_profiles.rs` `resolve` (validated `ProfileName`, strict `servers.toml` parse, `roots` required once two profiles exist, component-wise root match) and `marker.rs` `find_server_selection` (inherited down the tree, any value shape counts); `commands/hook.rs` `resolve_hook_route` drops a `Rejected` route before spool, handoff and backfill, and hands the drainer no live token for a profile route; `commands/hook_spool.rs` `static_retry_token` (a profile entry retries only with its own stored token), the loopback reroot skip, and chunk splitting on `profile`; generated TS `captureServerRouted` drops a routed repository and gates `fetchHandoff`; `hooks/_lib.sh` `ai_memory_server_routed` (flag refused by `ai_memory_post_hook`/`ai_memory_get_handoff`) and `hooks/lib/ai-memory-hook.ps1` `Test-AiMemoryServerRouted` drop it in the script hooks | `hook.rs` `each_repository_spools_to_its_own_profile_with_its_own_token`, `a_selection_that_does_not_resolve_emits_nothing` (unknown / tokenless / outside roots / roots required / invalid name, plus a resolving control), `session_start_handoff_comes_from_the_profile_server_only`, `a_repository_without_a_server_key_keeps_the_install_default`; `hook_spool.rs` `a_profile_entry_is_never_retried_with_the_install_live_token` (server B accepts exactly the install's live token and must still not get it), `a_profile_entry_recovers_with_its_own_rotated_token` (control), `a_profile_entry_on_a_dead_loopback_port_is_not_rerouted_to_the_default`, `profile_and_default_entries_at_one_address_ride_separate_batches`; `server_profiles.rs` roots/registry/name tests; `marker.rs` `nested_markers_without_server_inherit_the_ancestor_selection`; `install_hooks.rs` `generated_integrations_fail_closed_on_a_server_profile_marker`, `openclaw_plugin.rs` `openclaw_plugin_fails_closed_on_a_server_profile_marker`, and the `server-routed-*` checks in `generated_capture_policy_v1_node_runtime_evidence`; `hook.rs` `an_event_without_a_payload_cwd_routes_by_the_process_cwd`, `a_refused_route_prints_nothing_for_kimi_user_prompts`; `hook_spool.rs` `a_profile_entry_is_not_retried_with_a_token_issued_for_a_new_url`; `server_profiles.rs` `changing_the_url_without_a_token_discards_the_old_token`, `omitted_roots_keep_the_registered_ones`; `marker.rs` `outside_home_the_walk_reaches_a_marker_above_the_checkout_root`, `encoding_noise_cannot_hide_a_server_key`, `an_unreadable_marker_is_a_refused_selection`; `backfill.rs` `a_spawned_backfill_authenticates_like_the_hook_that_spawned_it`; `tests/hooks/test_lib.sh` "server profiles (#992)" section; `hook.rs` `a_mixed_spool_drains_each_event_only_to_its_own_server` (two token-gated servers, one spool, one drain: each server receives exactly its own event with exactly its own bearer); `tests/suite/server_profiles.rs` (the built binary: `server add` → `hook` spools to the profile with its token, unknown profile spools nothing, `uninstall` removes the tokens; `two_real_servers_each_receive_only_their_own_repository` runs two real `ai-memory serve` children with different root tokens and checks on each server which repository landed there); `ai-memory-hooks` `powershell_server_routed.rs` `server_routed_guard_mirrors_the_native_walk` (runs `Test-AiMemoryServerRouted` under real PowerShell: inherited, BOM, look-alike keys, the `$HOME` boundary with its control, past a checkout root outside home, current directory); `tests/hooks/test_lib.sh` and `powershell_home.rs` `a_trailing_separator_on_home_keeps_the_walk_boundary` (a `$HOME` ending in `/` or `\` keeps both script walks at home: a `server` marker above it routes nothing, with a root-home control that does) | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` |
+| 11d | Hook server-profile routing: a marker-selected server gets only its own capture and its own token (#992) | `ai-memory-cli/src/server_profiles.rs` `resolve` (validated `ProfileName`, strict `servers.toml` parse, `roots` required once two profiles exist, component-wise root match) and `marker.rs` `find_server_selection` (inherited down the tree, any value shape counts); `commands/hook.rs` `resolve_hook_route` drops a `Rejected` route before spool, handoff and backfill, and hands the drainer no live token for a profile route; `commands/hook_spool.rs` `static_retry_token` (a profile entry retries only with its own stored token), the loopback reroot skip, and chunk splitting on `profile`; generated TS `captureServerRouted` drops a routed repository and gates `fetchHandoff`; `hooks/_lib.sh` `ai_memory_server_routed` (flag refused by `ai_memory_post_hook`/`ai_memory_get_handoff`) and `hooks/lib/ai-memory-hook.ps1` `Test-AiMemoryServerRouted` drop it in the script hooks; `--check-capture` refuses a rejected server-profile selection without printing its token or URL | `hook.rs` `each_repository_spools_to_its_own_profile_with_its_own_token`, `a_selection_that_does_not_resolve_emits_nothing` (unknown / tokenless / outside roots / roots required / invalid name, plus a resolving control), `session_start_handoff_comes_from_the_profile_server_only`, `a_repository_without_a_server_key_keeps_the_install_default`; `hook_spool.rs` `a_profile_entry_is_never_retried_with_the_install_live_token` (server B accepts exactly the install's live token and must still not get it), `a_profile_entry_recovers_with_its_own_rotated_token` (control), `a_profile_entry_on_a_dead_loopback_port_is_not_rerouted_to_the_default`, `profile_and_default_entries_at_one_address_ride_separate_batches`; `server_profiles.rs` roots/registry/name tests; `marker.rs` `nested_markers_without_server_inherit_the_ancestor_selection`; `install_hooks.rs` `generated_integrations_fail_closed_on_a_server_profile_marker`, `openclaw_plugin.rs` `openclaw_plugin_fails_closed_on_a_server_profile_marker`, and the `server-routed-*` checks in `generated_capture_policy_v1_node_runtime_evidence`; `hook.rs` `an_event_without_a_payload_cwd_routes_by_the_process_cwd`, `a_refused_route_prints_nothing_for_kimi_user_prompts`; `hook_spool.rs` `a_profile_entry_is_not_retried_with_a_token_issued_for_a_new_url`; `server_profiles.rs` `changing_the_url_without_a_token_discards_the_old_token`, `omitted_roots_keep_the_registered_ones`; `marker.rs` `outside_home_the_walk_reaches_a_marker_above_the_checkout_root`, `encoding_noise_cannot_hide_a_server_key`, `an_unreadable_marker_is_a_refused_selection`; `backfill.rs` `a_spawned_backfill_authenticates_like_the_hook_that_spawned_it`; `tests/hooks/test_lib.sh` "server profiles (#992)" section; `hook.rs` `a_mixed_spool_drains_each_event_only_to_its_own_server` (two token-gated servers, one spool, one drain: each server receives exactly its own event with exactly its own bearer); `tests/suite/server_profiles.rs` (the built binary: `server add` → `hook` spools to the profile with its token, unknown profile spools nothing, `uninstall` removes the tokens; `two_real_servers_each_receive_only_their_own_repository` runs two real `ai-memory serve` children with different root tokens and checks on each server which repository landed there); `ai-memory-hooks` `powershell_server_routed.rs` `server_routed_guard_mirrors_the_native_walk` (runs `Test-AiMemoryServerRouted` under real PowerShell: inherited, BOM, look-alike keys, the `$HOME` boundary with its control, past a checkout root outside home, current directory); `hook.rs` `a_selection_that_does_not_resolve_emits_nothing` (rejected routes refuse preflight; resolved profile control passes); `tests/hooks/test_lib.sh` and `powershell_home.rs` `a_trailing_separator_on_home_keeps_the_walk_boundary` (a `$HOME` ending in `/` or `\` keeps both script walks at home: a `server` marker above it routes nothing, with a root-home control that does) | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` |
| 11e | Native self-upgrade archive confinement (#1025) | `ai-memory-cli/src/commands/upgrade.rs` normalizes every tar/zip path, rejects links and special entries, extracts only the binary and `hooks/`, accepts only the exact non-runtime support layout emitted by `release.yml`, and caps both entry count and declared expanded bytes before writing | `upgrade.rs` `release_workflow_support_assets_are_exact_and_ignored` (shipped support paths admitted, near-miss docs/packaging/template paths refused), `extracts_archive_built_like_release_yml` and `extracts_zip_happy_path_with_hooks` (real workflow-shaped archives succeed but support assets are not written), `validate_rejects_path_traversal`, `zip_extract_rejects_path_traversal`, `tar_extract_rejects_declared_expansion_past_limit`, with binary/hooks extraction as the legitimate control | STRONG |
| 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 |
-| 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401 | STRONG |
+| 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 |
+| 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; `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` `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 |
+ | 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 |
| 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 |
-| 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 | `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`; `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 | 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 |
+| 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 |
| 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`; `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity too; `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`; `router.rs` `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 |
| 14c | Client-supplied event time is bounded and self-scoped (#919) | `ai-memory-hooks/src/payload.rs` `HookEnvelope::occurred_at_micros` — a `/hook` caller's optional `occurred_at` must be `> 0` and `<= now + 5min`; it only sets the caller's *own* admitted session's `started_at`/`ended_at`/`created_at`, never another session/project/user, and the ingest dedup `seen_at`/TTL stays on `now` | `payload.rs` `occurred_at_micros_rejects_a_far_future_timestamp`, `…_rejects_non_positive_values`, `…_rejects_garbage_strings` | MEDIUM — self-scoped numeric bound; no cross-tenant surface (a client already controls its own content) |
| 14d | `include_related` shows and walks only readable projects (#708) | `ai-memory-store/src/reader.rs` `related_walk(.., viewer)` — both the outgoing and incoming hop queries carry `readable_repository_predicate("pg.project_id", viewer)`, the same far-end filter `page_links` applies, so a page in a project the viewer cannot read is neither returned nor expanded; `ai-memory-mcp/src/server.rs` `memory_read_page` passes `viewer_from_parts`, and the access bump only touches the filtered nodes | `related_walk.rs` `the_walk_hides_and_does_not_cross_projects_the_viewer_cannot_read` (an outgoing and an incoming neighbour in an ungranted restricted project are absent, and so is a granted page reachable only through one; control: a granted restricted project is shown, and no viewer walks the whole graph) — fails with the predicate removed; `ai-memory-mcp` `server.rs` `bob_does_not_see_restricted_pages_through_the_related_walk` (an ungranted user's `memory_read_page{include_related}` omits the restricted page; control: no viewer still reaches it) — fails with `memory_read_page` passing `None` instead of `viewer_from_parts` | STRONG |