Skip to content

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

Rust

fix(relay): retry concurrent queue journal setup

Éverton Toffanetto85792d2204f0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 762d7fbb..3faef28c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -118,6 +118,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
older servers leave unsupported fields unknown. (#1016)
### Changed
+- Made concurrent relay queue opens retry SQLite BUSY/LOCKED during WAL setup
+ within one 10-second configuration budget, rechecking queue identity and
+ schema version metadata before each attempt. Exhausted contention now asks
+ callers to retry the same queue, preserving committed migrations and delivery
+ history. SQLite diagnostic causes were displayed once.
- Documented FutureInfra as an endpoint for the existing `openai-compat`
provider. (#1026)
- `.github/workflows/nix.yml` builds the flake on `x86_64-linux` for path-
diff --git a/companions/ai-memory-relay/README.md b/companions/ai-memory-relay/README.md
index ec964f20..12f3829d 100644
--- a/companions/ai-memory-relay/README.md
+++ b/companions/ai-memory-relay/README.md
@@ -242,6 +242,17 @@ 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 --git a/companions/ai-memory-relay/src/queue.rs b/companions/ai-memory-relay/src/queue.rs
index 2c9447b1..6d3d28a1 100644
--- a/companions/ai-memory-relay/src/queue.rs
+++ b/companions/ai-memory-relay/src/queue.rs
@@ -8,7 +8,7 @@
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
-use std::time::Duration;
+use std::time::{Duration, Instant};
use anyhow::{Context, Result, bail};
use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
@@ -29,6 +29,14 @@ pub const MAX_SESSION_PINS: i64 = 50_000;
const SCHEMA_VERSION: &str = "2";
const IDENTITY: &str = "ai-memory-relay-queue";
+#[cfg(test)]
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(crate) enum OpenPhase {
+ AfterPreflight,
+ BeforeJournal,
+ JournalBusy,
+}
+
const SCHEMA: &str = "
CREATE TABLE IF NOT EXISTS meta(
key TEXT PRIMARY KEY,
@@ -169,6 +177,30 @@ impl Queue {
/// metadata commit together, so an interrupted initialization can reopen
/// the empty database left by rollback.
pub fn open(dir: &Path) -> Result<Self> {
+ #[cfg(test)]
+ {
+ Self::open_for_test(dir, Duration::from_secs(10), &mut |_| {})
+ }
+ #[cfg(not(test))]
+ {
+ Self::open_inner(dir, Duration::from_secs(10))
+ }
+ }
+
+ #[cfg(test)]
+ pub(crate) fn open_for_test(
+ dir: &Path,
+ timeout: Duration,
+ hook: &mut dyn FnMut(OpenPhase),
+ ) -> Result<Self> {
+ Self::open_inner(dir, timeout, hook)
+ }
+
+ fn open_inner(
+ dir: &Path,
+ timeout: Duration,
+ #[cfg(test)] hook: &mut dyn FnMut(OpenPhase),
+ ) -> Result<Self> {
let path = dir.join(fsguard::DB_FILE);
fsguard::check_queue_file(&path)?;
for name in fsguard::SIDECARS {
@@ -183,8 +215,10 @@ impl Queue {
}
let mut conn = Connection::open(&path)
.with_context(|| format!("open relay queue at {}", path.display()))?;
- conn.busy_timeout(Duration::from_secs(10))?;
+ conn.busy_timeout(timeout)?;
classify(&conn, &path)?;
+ #[cfg(test)]
+ hook(OpenPhase::AfterPreflight);
// Recheck under the write lock: another opener may have initialized or
// migrated since the read-only preflight.
{
@@ -208,8 +242,14 @@ impl Queue {
}
tx.commit()?;
}
- conn.execute_batch(
- "PRAGMA journal_mode=WAL;\nPRAGMA synchronous=FULL;\nPRAGMA foreign_keys=ON;",
+ #[cfg(test)]
+ hook(OpenPhase::BeforeJournal);
+ configure(
+ &conn,
+ &path,
+ timeout,
+ #[cfg(test)]
+ hook,
)
.with_context(|| format!("configure relay queue at {}", path.display()))?;
Ok(Self { conn, path })
@@ -695,6 +735,63 @@ enum DbState {
V1,
}
+fn configure(
+ conn: &Connection,
+ path: &Path,
+ timeout: Duration,
+ #[cfg(test)] hook: &mut dyn FnMut(OpenPhase),
+) -> Result<()> {
+ // WAL needs an exclusive lock outside a transaction. SQLite can return
+ // BUSY without calling its busy handler when other openers hold read/write
+ // locks. Own this phase's wait budget instead of restarting a 10s wait.
+ let deadline = Instant::now() + timeout;
+ conn.busy_timeout(Duration::ZERO)?;
+ let result = loop {
+ let attempt = (|| -> Result<()> {
+ // Keep the same connection and recheck identity/version metadata
+ // before every WAL attempt, including after a lock was released.
+ if classify(conn, path)? != DbState::Ready {
+ bail!(
+ "relay queue identity or schema version changed before journal configuration"
+ );
+ }
+ conn.execute_batch(
+ "PRAGMA journal_mode=WAL;\nPRAGMA synchronous=FULL;\nPRAGMA foreign_keys=ON;",
+ )?;
+ Ok(())
+ })();
+ match attempt {
+ Err(error) if is_lock_contention(&error) => {
+ #[cfg(test)]
+ hook(OpenPhase::JournalBusy);
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ if remaining.is_zero() {
+ break Err(error);
+ }
+ std::thread::sleep(remaining.min(Duration::from_millis(10)));
+ if Instant::now() >= deadline {
+ break Err(error);
+ }
+ }
+ other => break other,
+ }
+ };
+ conn.busy_timeout(timeout)?;
+ result.map_err(|error| {
+ if is_lock_contention(&error) {
+ error.context("relay queue busy; retry opening the same queue")
+ } else {
+ error
+ }
+ })
+}
+
+pub(crate) fn is_lock_contention(error: &anyhow::Error) -> bool {
+ matches!(error.downcast_ref::<rusqlite::Error>(),
+ Some(rusqlite::Error::SqliteFailure(error, _))
+ if matches!(error.code, rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked))
+}
+
/// Classify an existing file before touching it. Never mutates.
fn classify(conn: &Connection, path: &Path) -> Result<DbState> {
let refuse = |detail: String| -> anyhow::Error {
@@ -713,7 +810,14 @@ fn classify(conn: &Connection, path: &Path) -> Result<DbState> {
|r| r.get(0),
);
// A file that is not a SQLite database fails right here, before any write.
- let objects = objects.map_err(|e| refuse(format!("cannot read its object list: {e}")))?;
+ let objects = objects.map_err(|e| {
+ let error = anyhow::Error::new(e);
+ if is_lock_contention(&error) {
+ error
+ } else {
+ error.context(refuse("cannot read its object list".into()))
+ }
+ })?;
if objects == 0 {
return Ok(DbState::Fresh);
}
@@ -724,7 +828,14 @@ fn classify(conn: &Connection, path: &Path) -> Result<DbState> {
mapped.collect()
})();
let meta: HashMap<String, String> = rows
- .map_err(|e| refuse(format!("it carries no readable relay metadata: {e}")))?
+ .map_err(|e| {
+ let error = anyhow::Error::new(e);
+ if is_lock_contention(&error) {
+ error
+ } else {
+ error.context(refuse("it carries no readable relay metadata".into()))
+ }
+ })?
.into_iter()
.collect();
match (
diff --git a/companions/ai-memory-relay/tests/relay.rs b/companions/ai-memory-relay/tests/relay.rs
index 05900db2..02b737b6 100644
--- a/companions/ai-memory-relay/tests/relay.rs
+++ b/companions/ai-memory-relay/tests/relay.rs
@@ -19,6 +19,13 @@ use ai_memory_relay::identity::{self, InputEvent, ValidEvent};
use ai_memory_relay::queue::Queue;
use ai_memory_relay::relay::{self, FlushOptions};
+// Compile the same queue source with private test hooks; the shipped library
+// has no hook API. These hooks place a real SQLite holder at the WAL transition.
+use ai_memory_relay::fsguard;
+#[allow(dead_code)]
+#[path = "../src/queue.rs"]
+mod queue_under_test;
+
// ---------------------------------------------------------------- fixtures
/// A kept sandbox. The path is printed so a failure points at the evidence.
@@ -1482,6 +1489,398 @@ fn v1_migration_preserves_every_existing_value_and_concurrent_reopens() {
);
}
+#[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");
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 53774ace..1979b5a7 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -69,6 +69,8 @@ boundary not yet built.
| 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 |
| 15 | Agent-archive restore path confinement, resource bounds, and consistency | `ai-memory-cli/src/commands/restore_agents.rs` stages only bounded regular UTF-8 entries; requires a one-to-one manifest/body/checksum/target mapping; allowlists destinations by scope; rejects symlinked descendants; writes each file atomically and rolls back earlier writes after a later failure. `backup_agents.rs` skips direct and directory-root source symlinks, bounds individual assets, and atomically replaces a private archive only after gzip completion | `backup_agents.rs` `restore_agents_rejects_path_traversal`, `restore_agents_rejects_unauthorized_destination_path`, `restore_agents_verifies_sha256_integrity`, `restore_agents_requires_a_complete_one_to_one_manifest`, `restore_agents_rejects_oversized_entries_from_the_header`, `restore_agents_rejects_a_symlinked_destination_parent`, `backup_agents_does_not_follow_config_or_asset_root_symlinks`, and `failed_backup_leaves_the_previous_archive_intact`; `backup_and_restore_agents_round_trip` is the valid-path control; `restore_agents::tests::rollback_removes_new_files_and_restores_overwrites` covers recovery | STRONG |
+| 16 | Relay queue identity, migration, and private filesystem state | `companions/ai-memory-relay/src/queue.rs` `Queue::open_inner` performs read-only identity preflight, rechecks under `IMMEDIATE`, commits schema and metadata together; `configure` checks the presence of user objects and rechecks `identity`/`schema_version` metadata on the same connection before every bounded BUSY/LOCKED retry; `fsguard.rs` checks existing paths and creates owner-only files before SQLite opens them | `tests/relay.rs` `a_foreign_database_is_refused_byte_for_byte`, `unknown_schemas_refuse_without_mutation`, `a_foreign_database_with_a_writer_is_refused_before_write_coordination`, `a_foreign_identity_after_preflight_is_refused_without_mutation`, `a_foreign_identity_during_journal_retry_is_refused_without_mutation`, `journal_retry_refuses_a_changed_version_or_empty_database_without_mutation`; controls: `journal_transition_retries_sqlite_lock_without_losing_v1_values`, `fresh_queue_init_and_v1_reopens_work_across_processes`; recovery: `interrupted_and_failed_migrations_roll_back_and_recover`, `journal_reclassification_busy_preserves_committed_migration_and_retries_same_queue`; diagnostics: `classification_read_failures_display_the_sqlite_cause_once_and_preserve_foreign_bytes`; Unix privacy: `the_queue_database_and_its_sidecars_are_owner_only` and the contended migration control | Guard-removal proof covers preflight, locked recheck, and journal retry identity/version checks; full table structure is outside this classification. Windows path rejection is preserved; Windows ACL hardening remains operator-owned |
+
## Keeping this current (the standing protocol)