Skip to content

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

Rust

feat(hooks): report batch outcomes and relay receipts

Éverton Toffanetto9904b1b3028d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4ce62d08..137a2aeb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- Added per-event outcomes to `/hook/batch` acknowledgements and process-lifetime
+ ingest counters for stored events, replays, recovery, ignored endings,
+ collisions and failures. Legacy acknowledgement fields were preserved. (#1010)
+- Added receipt outcomes and delivery counts to the companion relay. Opening a
+ schema 1 queue now upgrades it atomically to schema 2; older relay binaries
+ refuse schema 2, so downgrade requires a pre-upgrade backup with all queue
+ users stopped. Pending order and existing delivery metadata were preserved.
+ Receipts now retain their first known outcome. (#1010)
+
+### Fixed
+- Fixed completed retries and no-op session endings advancing
+ `last_persisted_ms` without a durable write. Recovery still advances the
+ timestamp when it commits a new page or terminal effect. (#1010)
+
## [2.5.2] - 2026-10-01
### Added
diff --git a/companions/ai-memory-relay/README.md b/companions/ai-memory-relay/README.md
index 9d9ec049..ec964f20 100644
--- a/companions/ai-memory-relay/README.md
+++ b/companions/ai-memory-relay/README.md
@@ -213,3 +213,35 @@ lost response, distinct event identities and 15 concurrent sessions. It also
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,
+including drops. Flush reports `acknowledged_outcomes` for that invocation.
+Status adds `receipt_outcomes`, with all nine 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.
+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/ack.rs b/companions/ai-memory-relay/src/ack.rs
index 67e02ca2..6f710dbb 100644
--- a/companions/ai-memory-relay/src/ack.rs
+++ b/companions/ai-memory-relay/src/ack.rs
@@ -3,7 +3,49 @@
//! 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] = [
+ "stored",
+ "replayed",
+ "resumed",
+ "ignored_end",
+ "dropped_policy",
+ "dropped_subagent",
+ "dropped_unauthorized",
+ "dropped_collision",
+ "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.
@@ -17,6 +59,9 @@ pub struct BatchAck {
/// Item that failed processing after earlier skips.
#[serde(default)]
pub failed_index: Option<usize>,
+ /// Missing on old servers; present arrays must describe every acknowledged index.
+ #[serde(default, deserialize_with = "present_results")]
+ pub results: Option<Vec<EventResult>>,
}
/// Why an ack was refused. The batch stays pending in every case.
@@ -94,5 +139,25 @@ pub fn validate(batch_len: usize, ack: &BatchAck) -> Result<Vec<usize>, AckRejec
));
}
}
+ if let Some(results) = &ack.results
+ && (results.len() != accepted.len()
+ || results
+ .iter()
+ .zip(&accepted)
+ .any(|(result, index)| result.index != *index))
+ {
+ return reject(
+ "results must match acknowledged indices exactly, in ascending order".into(),
+ );
+ }
Ok(accepted)
}
+
+/// Outcome for an index after successful whole-response validation.
+pub fn acknowledged_outcome(ack: &BatchAck, index: usize) -> &'static str {
+ ack.results
+ .as_ref()
+ .and_then(|results| results.iter().find(|r| r.index == index))
+ .map(|result| outcome(&result.outcome))
+ .unwrap_or("unknown")
+}
diff --git a/companions/ai-memory-relay/src/queue.rs b/companions/ai-memory-relay/src/queue.rs
index b414ae4e..2c9447b1 100644
--- a/companions/ai-memory-relay/src/queue.rs
+++ b/companions/ai-memory-relay/src/queue.rs
@@ -26,7 +26,7 @@ pub const MAX_RECEIPTS: i64 = 200_000;
/// Session-to-agent pins retained at once, enforced the same way.
pub const MAX_SESSION_PINS: i64 = 50_000;
-const SCHEMA_VERSION: &str = "1";
+const SCHEMA_VERSION: &str = "2";
const IDENTITY: &str = "ai-memory-relay-queue";
const SCHEMA: &str = "
@@ -64,7 +64,8 @@ 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
+ delivered_at_ms INTEGER NOT NULL,
+ outcome TEXT
);
CREATE INDEX IF NOT EXISTS receipt_first_attempt ON receipt(first_attempt_ms);
CREATE TABLE IF NOT EXISTS session_agent(
@@ -144,6 +145,8 @@ pub struct Stats {
pub max_attempts: i64,
pub receipts: i64,
pub known_sessions: i64,
+ /// Outcomes within the retained first-attempt window, with fixed keys.
+ pub receipt_outcomes: std::collections::BTreeMap<String, i64>,
}
/// The companion's queue database.
@@ -181,21 +184,34 @@ impl Queue {
let mut conn = Connection::open(&path)
.with_context(|| format!("open relay queue at {}", path.display()))?;
conn.busy_timeout(Duration::from_secs(10))?;
- let state = classify(&conn, &path)?;
+ classify(&conn, &path)?;
+ // Recheck under the write lock: another opener may have initialized or
+ // migrated since the read-only preflight.
+ {
+ let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
+ match classify(&tx, &path)? {
+ DbState::Fresh => {
+ tx.execute_batch(SCHEMA)?;
+ tx.execute(
+ "INSERT INTO meta(key, value) VALUES('identity', ?1), ('schema_version', ?2)",
+ params![IDENTITY, SCHEMA_VERSION],
+ )?;
+ }
+ DbState::V1 => {
+ tx.execute_batch("ALTER TABLE receipt ADD COLUMN outcome TEXT;")?;
+ tx.execute(
+ "UPDATE meta SET value = ?1 WHERE key = 'schema_version'",
+ params![SCHEMA_VERSION],
+ )?;
+ }
+ DbState::Ready => {}
+ }
+ tx.commit()?;
+ }
conn.execute_batch(
"PRAGMA journal_mode=WAL;\nPRAGMA synchronous=FULL;\nPRAGMA foreign_keys=ON;",
)
.with_context(|| format!("configure relay queue at {}", path.display()))?;
- if state != DbState::Ready {
- let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
- tx.execute_batch(SCHEMA)
- .with_context(|| format!("initialize relay queue schema at {}", path.display()))?;
- tx.execute(
- "INSERT OR REPLACE INTO meta(key, value) VALUES('identity', ?1), ('schema_version', ?2)",
- params![IDENTITY, SCHEMA_VERSION],
- )?;
- tx.commit()?;
- }
Ok(Self { conn, path })
}
@@ -508,7 +524,7 @@ impl Queue {
/// An acknowledgement means delivered *or* deliberately dropped by server
/// policy (a capture-protocol drop, a subagent drop, a session-collision
/// drop). It never promises an observation was written.
- pub fn confirm(&mut self, keys: &[String], now_ms: i64) -> Result<usize> {
+ pub fn confirm(&mut self, keys: &[(String, &str)], now_ms: i64) -> Result<usize> {
if keys.is_empty() {
return Ok(0);
}
@@ -516,7 +532,7 @@ impl Queue {
.conn
.transaction_with_behavior(TransactionBehavior::Immediate)?;
let mut moved = 0;
- for key in keys {
+ for (key, outcome) in keys {
let row: Option<(String, Option<i64>, i64)> = tx
.query_row(
"SELECT body_sha256, first_attempt_ms, first_seen_ms
@@ -529,14 +545,16 @@ impl Queue {
continue;
};
tx.execute(
- "INSERT INTO receipt(ingest_key, body_sha256, first_attempt_ms, delivered_at_ms)
- VALUES(?1, ?2, ?3, ?4)
- ON CONFLICT(ingest_key) DO UPDATE SET delivered_at_ms = excluded.delivered_at_ms",
+ "INSERT INTO receipt(ingest_key, body_sha256, first_attempt_ms, delivered_at_ms, outcome)
+ VALUES(?1, ?2, ?3, ?4, ?5)
+ ON CONFLICT(ingest_key) DO UPDATE SET delivered_at_ms = excluded.delivered_at_ms,
+ outcome = COALESCE(NULLIF(receipt.outcome, 'unknown'), excluded.outcome)",
params![
key,
body_sha256,
first_attempt_ms.unwrap_or(first_seen_ms),
- now_ms
+ now_ms,
+ crate::ack::outcome(outcome)
],
)?;
tx.execute("DELETE FROM pending WHERE ingest_key = ?1", params![key])?;
@@ -612,6 +630,19 @@ impl Queue {
let known_sessions: i64 =
self.conn
.query_row("SELECT COUNT(*) FROM session_agent", [], |r| r.get(0))?;
+ let mut receipt_outcomes = crate::ack::outcome_counts();
+ let mut stmt = self.conn.prepare(
+ "SELECT outcome, COUNT(*) FROM receipt WHERE first_attempt_ms >= ?1 GROUP BY outcome",
+ )?;
+ for row in stmt.query_map(params![cutoff], |r| {
+ Ok((r.get::<_, Option<String>>(0)?, r.get::<_, i64>(1)?))
+ })? {
+ let (value, count) = row?;
+ let key = crate::ack::outcome(value.as_deref().unwrap_or("unknown"));
+ if let Some(total) = receipt_outcomes.get_mut(key) {
+ *total += count;
+ }
+ }
Ok(Stats {
pending_items,
pending_bytes,
@@ -626,6 +657,7 @@ impl Queue {
max_attempts,
receipts,
known_sessions,
+ receipt_outcomes,
})
}
}
@@ -659,6 +691,8 @@ enum DbState {
Fresh,
/// A relay queue of this exact schema version.
Ready,
+ /// Version one is upgraded transactionally.
+ V1,
}
/// Classify an existing file before touching it. Never mutates.
@@ -697,6 +731,7 @@ fn classify(conn: &Connection, path: &Path) -> Result<DbState> {
meta.get("identity").map(String::as_str),
meta.get("schema_version").map(String::as_str),
) {
+ (Some(IDENTITY), Some("1")) => Ok(DbState::V1),
(Some(IDENTITY), Some(SCHEMA_VERSION)) => Ok(DbState::Ready),
(Some(IDENTITY), Some(other)) => Err(refuse(format!(
"schema version {other} but this build speaks {SCHEMA_VERSION}"
diff --git a/companions/ai-memory-relay/src/relay.rs b/companions/ai-memory-relay/src/relay.rs
index c1b7482a..06b562f8 100644
--- a/companions/ai-memory-relay/src/relay.rs
+++ b/companions/ai-memory-relay/src/relay.rs
@@ -228,6 +228,7 @@ pub fn status(dir: &Path) -> Result<Report> {
"max_attempts": stats.max_attempts,
"receipts": stats.receipts,
"known_sessions": stats.known_sessions,
+ "receipt_outcomes": stats.receipt_outcomes,
"limits": {
"pending_items": queue::MAX_PENDING_ITEMS,
"pending_bytes": queue::MAX_PENDING_BYTES,
@@ -281,6 +282,7 @@ fn flush_locked(dir: &Path, options: &FlushOptions) -> Result<Report> {
let started = Instant::now();
let mut deferred: HashSet<(String, String)> = HashSet::new();
let mut delivered = 0usize;
+ let mut outcomes = ack::outcome_counts();
let mut batches = 0usize;
let mut blocked_sessions = 0usize;
let mut failure: Option<String> = None;
@@ -411,12 +413,23 @@ fn flush_locked(dir: &Path, options: &FlushOptions) -> Result<Report> {
// Only now, after the whole response was validated, does anything leave
// the queue.
- let confirmed: Vec<String> = accepted
+ let confirmed: Vec<(String, &str)> = accepted
.iter()
- .filter_map(|idx| batch.items.get(*idx))
- .map(|item| item.ingest_key.clone())
+ .filter_map(|idx| {
+ batch.items.get(*idx).map(|item| {
+ (
+ item.ingest_key.clone(),
+ ack::acknowledged_outcome(&parsed, *idx),
+ )
+ })
+ })
.collect();
delivered += queue.confirm(&confirmed, crate::now_ms())?;
+ for (_, outcome) in &confirmed {
+ if let Some(count) = outcomes.get_mut(*outcome) {
+ *count += 1;
+ }
+ }
if let Some(failed_index) = parsed.failed_index
&& let Some(item) = batch.items.get(failed_index)
@@ -447,6 +460,10 @@ fn flush_locked(dir: &Path, options: &FlushOptions) -> Result<Report> {
"acknowledged {delivered} event(s) in {batches} batch(es); {} still pending across {} session(s)",
stats.pending_items, stats.pending_sessions
)];
+ summary.push(format!(
+ "acknowledged_outcomes: {}",
+ serde_json::to_string(&outcomes)?
+ ));
if backed_off {
summary.push(
"server answered 429: the acknowledged items were applied and the flush stopped. \
diff --git a/companions/ai-memory-relay/tests/relay.rs b/companions/ai-memory-relay/tests/relay.rs
index 3ef35e58..05900db2 100644
--- a/companions/ai-memory-relay/tests/relay.rs
+++ b/companions/ai-memory-relay/tests/relay.rs
@@ -1340,3 +1340,408 @@ fn a_batch_stays_under_the_wire_budget_when_bodies_are_large() {
);
}
}
+
+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 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]
+ .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 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)
+ .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] {
+ 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 --git a/crates/ai-memory-cli/src/commands/status.rs b/crates/ai-memory-cli/src/commands/status.rs
index 7a499e2d..def62ad5 100644
--- a/crates/ai-memory-cli/src/commands/status.rs
+++ b/crates/ai-memory-cli/src/commands/status.rs
@@ -19,6 +19,21 @@ use crate::http_client::{ServerEndpoint, get_json};
#[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)]
+ failed: u64,
+
dropped_by_policy: u64,
shed_saturated: u64,
shed_rate_limited: u64,
@@ -345,6 +360,14 @@ pub async fn run(config: &Config, args: StatusArgs) -> Result<()> {
" 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
+ );
println!(
" shed: {} saturated, {} rate-limited",
ingest.shed_saturated, ingest.shed_rate_limited
@@ -482,6 +505,27 @@ fn error_detail(role: &ProviderRoleHealthSnapshot) -> String {
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",
+ "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 --git a/crates/ai-memory-core/src/ingest_metrics.rs b/crates/ai-memory-core/src/ingest_metrics.rs
index 557ced30..7e4af73a 100644
--- a/crates/ai-memory-core/src/ingest_metrics.rs
+++ b/crates/ai-memory-core/src/ingest_metrics.rs
@@ -45,7 +45,19 @@ pub struct IngestMetrics {
shed_saturated: AtomicU64,
/// Events shed by the per-source rate limiter (429).
shed_rate_limited: AtomicU64,
- /// Unix milliseconds of the last event that reached the writer, or 0
+ /// Completed hook deliveries classified as `stored`.
+ stored: AtomicU64,
+ /// Completed hook deliveries classified as `replayed`.
+ replayed: AtomicU64,
+ /// Completed hook deliveries classified as `resumed`.
+ resumed: AtomicU64,
+ /// Completed hook deliveries classified as `ignored_end`.
+ ignored_end: AtomicU64,
+ /// Completed hook deliveries classified as `dropped_collision`.
+ dropped_collision: AtomicU64,
+ /// Completed hook deliveries classified as `failed`.
+ failed: AtomicU64,
+ /// Unix milliseconds of the last newly persisted observation or effect, or 0
/// when none has since this process started.
last_persisted_ms: AtomicU64,
}
@@ -71,6 +83,30 @@ impl IngestMetrics {
pub fn record_shed_rate_limited(&self) {
self.shed_rate_limited.fetch_add(1, Ordering::Relaxed);
}
+ /// Record one `stored` delivery.
+ pub fn record_stored(&self) {
+ self.stored.fetch_add(1, Ordering::Relaxed);
+ }
+ /// Record one `replayed` delivery.
+ pub fn record_replayed(&self) {
+ self.replayed.fetch_add(1, Ordering::Relaxed);
+ }
+ /// Record one `resumed` delivery.
+ pub fn record_resumed(&self) {
+ self.resumed.fetch_add(1, Ordering::Relaxed);
+ }
+ /// Record one `ignored_end` delivery.
+ pub fn record_ignored_end(&self) {
+ self.ignored_end.fetch_add(1, Ordering::Relaxed);
+ }
+ /// Record one `dropped_collision` delivery.
+ pub fn record_dropped_collision(&self) {
+ self.dropped_collision.fetch_add(1, Ordering::Relaxed);
+ }
+ /// Record one `failed` delivery.
+ pub fn record_failed(&self) {
+ self.failed.fetch_add(1, Ordering::Relaxed);
+ }
/// Stamp the moment an event reached durable storage.
pub fn record_persisted(&self, unix_ms: u64) {
self.last_persisted_ms.store(unix_ms, Ordering::Relaxed);
@@ -81,6 +117,13 @@ 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),
shed_saturated: self.shed_saturated.load(Ordering::Relaxed),
@@ -106,7 +149,19 @@ pub struct IngestMetricsSnapshot {
pub shed_saturated: u64,
/// Events shed by the per-source rate limiter.
pub shed_rate_limited: u64,
- /// Unix ms of the last event that reached the writer, if any.
+ /// Hook deliveries classified as `stored`.
+ pub stored: u64,
+ /// Hook deliveries classified as `replayed`.
+ pub replayed: u64,
+ /// Hook deliveries classified as `resumed`.
+ pub resumed: u64,
+ /// Hook deliveries classified as `ignored_end`.
+ pub ignored_end: u64,
+ /// Hook deliveries classified as `dropped_collision`.
+ pub dropped_collision: u64,
+ /// Hook deliveries classified as `failed`.
+ pub failed: u64,
+ /// Unix ms of the last newly persisted observation or effect, if any.
pub last_persisted_ms: Option<u64>,
}
@@ -146,6 +201,26 @@ mod tests {
assert_eq!(s.last_persisted_ms, Some(1_700_000_000_000));
}
+ #[test]
+ fn additive_outcomes_do_not_change_admission_or_last_write() {
+ let metrics = IngestMetrics::default();
+ metrics.record_stored();
+ metrics.record_replayed();
+ metrics.record_resumed();
+ metrics.record_ignored_end();
+ metrics.record_dropped_collision();
+ metrics.record_failed();
+ let s = metrics.snapshot();
+ assert_eq!(
+ (s.stored, s.replayed, s.resumed, s.ignored_end),
+ (1, 1, 1, 1)
+ );
+ assert_eq!((s.dropped_collision, s.failed), (1, 1));
+ assert_eq!(s.accepted, 0);
+ assert_eq!(s.dropped_by_policy, 0);
+ assert_eq!(s.last_persisted_ms, None);
+ }
+
/// The shape is the privacy contract: counts and one timestamp, nothing
/// that could carry a prompt, path, or tool payload. If a field carrying
/// captured text is ever added, this fails loudly (#428).
@@ -161,10 +236,16 @@ mod tests {
vec![
"accepted",
"dropped_by_policy",
+ "dropped_collision",
"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 --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 7b463fe3..07c8d82b 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -639,7 +639,7 @@ async fn handle_hook(
// Any gate failure leaves an empty Stop with the same 202 "queued" response.
crate::assistant_capture::apply_assistant_backstop(&mut env, state.capture_assistant_enabled);
let Some(env) = inspect_capture_envelope(env) else {
- state.ingest_metrics.record_dropped_by_policy();
+ HookProcessingOutcome::DroppedPolicy.record(&state.ingest_metrics);
return (StatusCode::ACCEPTED, "capture policy dropped");
};
// Accept-but-drop subagent captures (incl. the unmarked tail of tracked
@@ -662,7 +662,7 @@ async fn handle_hook(
let skip_webhooks = admission_skips(level_ext, &headers);
let actor_storage_key = actor.as_ref().map(IdentityKey::storage_key);
if should_drop_subagent(&state, &env, viewer).await {
- state.ingest_metrics.record_dropped_by_policy();
+ HookProcessingOutcome::DroppedSubagent.record(&state.ingest_metrics);
return (StatusCode::ACCEPTED, "subagent capture dropped");
}
let Ok(permit) = state.ingest_semaphore.clone().try_acquire_owned() else {
@@ -684,8 +684,7 @@ async fn handle_hook(
state.ingest_metrics.record_accepted();
tokio::spawn(async move {
let _permit = permit;
- let metrics = state.ingest_metrics.clone();
- let persisted = process_envelope(
+ let _ = process_envelope(
state,
env,
actor,
@@ -694,15 +693,6 @@ async fn handle_hook(
viewer,
)
.await;
- // Stamped only when `process_envelope` actually cleared the writer.
- // This is the signal an operator uses to tell "hooks are arriving but
- // nothing is landing" from "nothing is arriving" — the two look
- // identical from the accepted count alone — so a failed write must
- // NOT advance it, or a store that is rejecting every event still
- // reads as a healthy writer in `ai-memory status`.
- if persisted {
- metrics.record_persisted(now_unix_ms());
- }
});
(StatusCode::ACCEPTED, "queued")
}
@@ -721,15 +711,65 @@ 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,
+}
+
+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::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.
#[derive(Debug, Serialize)]
pub struct HookBatchAck {
- /// Contiguous leading prefix committed, oldest-first. Kept for old spool
+ /// Contiguous leading prefix acknowledged, oldest-first. Kept for old spool
/// drains and as a safe lower bound when `accepted_indices` is absent.
pub accepted: usize,
- /// Non-contiguous item indexes committed by a server new enough to keep
+ /// Results only for acknowledged request indices.
+ pub results: Vec<HookBatchResult>,
+ /// Non-contiguous item indexes acknowledged by a server new enough to keep
/// scanning past per-source rate-limited items. Omitted when it is exactly
/// the legacy accepted prefix so older clients keep working.
#[serde(skip_serializing_if = "Option::is_none")]
@@ -741,9 +781,15 @@ pub struct HookBatchAck {
}
impl HookBatchAck {
+ fn with_results(mut self, results: Vec<HookBatchResult>) -> Self {
+ self.results = results;
+ self
+ }
+
fn prefix(accepted: usize) -> Self {
Self {
accepted,
+ results: Vec::new(),
accepted_indices: None,
failed_index: None,
}
@@ -779,6 +825,7 @@ impl HookBatchAck {
.all(|(pos, idx)| pos == idx);
Self {
accepted: legacy_prefix,
+ results: Vec::new(),
accepted_indices: if contiguous && !(include_empty_indices && indices.is_empty()) {
None
} else {
@@ -826,6 +873,7 @@ async fn handle_hook_batch(
let skip_webhooks = admission_skips(level_ext, &headers);
let actor_storage_key = actor.as_ref().map(IdentityKey::storage_key);
let mut accepted_indices = Vec::new();
+ let mut results = Vec::new();
let total_items = items.len();
for (idx, mut item) in items.into_iter().enumerate() {
// Same unconditional assistant-message backstop as `handle_hook`, applied
@@ -841,7 +889,11 @@ async fn handle_hook_batch(
// A protocol-directed drop is committed from the spool's point of
// view, but intentionally spends neither ingress capacity nor a
// source-rate token.
- state.ingest_metrics.record_dropped_by_policy();
+ HookProcessingOutcome::DroppedPolicy.record(&state.ingest_metrics);
+ results.push(HookBatchResult {
+ index: idx,
+ outcome: HookProcessingOutcome::DroppedPolicy,
+ });
accepted_indices.push(idx);
continue;
};
@@ -849,7 +901,11 @@ async fn handle_hook_batch(
// as committed so the client clears it from its spool, but do not store
// it. Keeps the contiguous-prefix ack contract intact.
if should_drop_subagent(&state, &env, viewer).await {
- state.ingest_metrics.record_dropped_by_policy();
+ HookProcessingOutcome::DroppedSubagent.record(&state.ingest_metrics);
+ results.push(HookBatchResult {
+ index: idx,
+ outcome: HookProcessingOutcome::DroppedSubagent,
+ });
accepted_indices.push(idx);
continue;
}
@@ -867,7 +923,7 @@ async fn handle_hook_batch(
);
return (
StatusCode::TOO_MANY_REQUESTS,
- Json(HookBatchAck::indexed(accepted_indices)),
+ Json(HookBatchAck::indexed(accepted_indices).with_results(results)),
);
};
let rate_key = ingest_rate_key(&env, actor_storage_key.as_deref());
@@ -885,7 +941,7 @@ async fn handle_hook_batch(
let _permit = permit;
state.ingest_metrics.record_accepted();
let (session, agent, event) = (resolve_session_id(&env).ok(), env.agent, env.event);
- if let Err(e) = process_authorized(
+ let outcome = match process_authorized(
&state,
env,
actor.clone(),
@@ -895,44 +951,39 @@ async fn handle_hook_batch(
)
.await
{
- if e.downcast_ref::<CaptureNotAuthorized>().is_some() {
- // Counted as accepted so the client DROPS it. The item can
- // never be stored, so leaving it spooled would retry it until
- // its attempt budget ran out and stall every item behind it.
- // Same treatment a capture-policy drop already gets.
- state.ingest_metrics.record_dropped_unauthorized();
+ Ok(outcome) => outcome,
+ Err(e) if e.downcast_ref::<CaptureNotAuthorized>().is_some() => {
warn!("hook batch capture dropped: author may not write this project");
- accepted_indices.push(idx);
- continue;
+ HookProcessingOutcome::DroppedUnauthorized
}
- if matches!(
- e.downcast_ref::<StoreError>(),
- Some(StoreError::SessionCollision)
- ) {
- warn!(
- session = ?session,
- agent = %agent.as_str(),
- event = ?event,
- reason = SESSION_COLLISION_REASON,
- "hook batch session collision/recovery rejection dropped"
+ Err(e)
+ if matches!(
+ e.downcast_ref::<StoreError>(),
+ Some(StoreError::SessionCollision)
+ ) =>
+ {
+ warn!(session = ?session, agent = %agent.as_str(), event = ?event, reason = SESSION_COLLISION_REASON, "hook batch session collision dropped");
+ HookProcessingOutcome::DroppedCollision
+ }
+ Err(e) => {
+ state.ingest_metrics.record_failed();
+ warn!(error = %e, accepted = accepted_indices.len(), "hook batch item failed; stopping (fail-fast)");
+ return (
+ StatusCode::OK,
+ Json(HookBatchAck::indexed_failed(accepted_indices, idx).with_results(results)),
);
- accepted_indices.push(idx);
- continue;
}
- warn!(error = %e, accepted = accepted_indices.len(), "hook batch item failed; stopping (fail-fast)");
- return (
- StatusCode::OK,
- Json(HookBatchAck::indexed_failed(accepted_indices, idx)),
- );
- }
- // Stamped per item, for the same reason `handle_hook` stamps after
- // `process_envelope`: this is the point the event cleared the writer.
- state.ingest_metrics.record_persisted(now_unix_ms());
+ };
+ outcome.record(&state.ingest_metrics);
+ results.push(HookBatchResult {
+ index: idx,
+ outcome,
+ });
accepted_indices.push(idx);
}
(
StatusCode::OK,
- Json(HookBatchAck::indexed_full_scan(accepted_indices)),
+ Json(HookBatchAck::indexed_full_scan(accepted_indices).with_results(results)),
)
}
@@ -2638,10 +2689,7 @@ fn sticky_cwd_admits(
const SESSION_COLLISION_REASON: &str =
"session id belongs to another owner or agent, or all-owners recovery was refused";
-/// Returns `true` when the event cleared the writer, so the caller can stamp
-/// the ingest "last write" metric. A rejected or failed event returns `false`:
-/// nothing was persisted, and pretending otherwise hides exactly the outage
-/// the metric exists to expose.
+/// Process an asynchronous delivery with the same classification as batch ingress.
async fn process_envelope(
state: Arc<HookState>,
env: HookEnvelope,
@@ -2649,19 +2697,20 @@ async fn process_envelope(
level: ai_memory_core::AuthLevel,
skip_webhooks: Vec<String>,
viewer: Option<ai_memory_core::UserId>,
-) -> bool {
+) -> Option<HookProcessingOutcome> {
let (session, agent, event) = (resolve_session_id(&env).ok(), env.agent, env.event);
- if let Err(e) = process_authorized(&state, env, actor, level, skip_webhooks, viewer).await {
- if e.downcast_ref::<CaptureNotAuthorized>().is_some() {
- // Counted separately from a policy drop so an operator can tell
- // "my configuration is discarding these" from "somebody has been
- // working all day and none of it is being kept".
- state.ingest_metrics.record_dropped_unauthorized();
+ let outcome = match process_authorized(&state, env, actor, level, skip_webhooks, viewer).await {
+ Ok(outcome) => outcome,
+ Err(e) if e.downcast_ref::<CaptureNotAuthorized>().is_some() => {
warn!("capture dropped: author may not write this project");
- } else if matches!(
- e.downcast_ref::<StoreError>(),
- Some(StoreError::SessionCollision)
- ) {
+ HookProcessingOutcome::DroppedUnauthorized
+ }
+ Err(e)
+ if matches!(
+ e.downcast_ref::<StoreError>(),
+ Some(StoreError::SessionCollision)
+ ) =>
+ {
warn!(
session = ?session,
agent = %agent.as_str(),
@@ -2669,12 +2718,16 @@ async fn process_envelope(
reason = SESSION_COLLISION_REASON,
"hook session collision dropped"
);
- } else {
+ HookProcessingOutcome::DroppedCollision
+ }
+ Err(e) => {
+ state.ingest_metrics.record_failed();
warn!(error = %e, "hook processing failed");
+ return None;
}
- return false;
- }
- true
+ };
+ outcome.record(&state.ingest_metrics);
+ Some(outcome)
}
async fn enqueue_session_end_consolidation(
@@ -2682,28 +2735,31 @@ async fn enqueue_session_end_consolidation(
session_id: SessionId,
workspace_id: WorkspaceId,
project_id: ProjectId,
-) -> anyhow::Result<()> {
+) -> anyhow::Result<bool> {
if !state.consolidate_on_session_end || state.consolidator.is_none() {
- return Ok(());
+ return Ok(false);
}
let Some(notify) = state.session_consolidation_notify.as_ref() else {
warn!(
session = %session_id,
"SessionEnd LLM consolidation enabled without a queue worker"
);
- return Ok(());
+ return Ok(false);
};
let inserted = state
.writer
.enqueue_session_consolidation(workspace_id, project_id, session_id)
.await?;
+ if inserted {
+ state.ingest_metrics.record_persisted(now_unix_ms());
+ }
notify.notify_one();
debug!(
session = %session_id,
inserted,
"SessionEnd LLM consolidation queued"
);
- Ok(())
+ Ok(inserted)
}
/// Only events that begin or actively advance work may move the legacy
@@ -2763,7 +2819,7 @@ async fn process(
{
Ok(())
}
- result => result,
+ result => result.map(|_| ()),
}
}
@@ -2776,7 +2832,7 @@ async fn process_authorized(
// Empty for every caller with no HTTP request behind it.
skip_webhooks: Vec<String>,
viewer: Option<ai_memory_core::UserId>,
-) -> anyhow::Result<()> {
+) -> anyhow::Result<HookProcessingOutcome> {
let session_id = resolve_session_id(&env)?;
// An OpenCode `session.moved` relocation, forwarded by the plugin as a
// SessionStart naming the directory the session left. Admission rebinds
@@ -3059,7 +3115,7 @@ async fn process_authorized(
let (admitted, ingest) = match admission {
HookSessionAdmission::InvalidMissingEnd => {
info!(session = %session_id, "ignoring missing SessionEnd");
- return Ok(());
+ return Ok(HookProcessingOutcome::IgnoredEnd);
}
HookSessionAdmission::InvalidScopedEnd => {
info!(
@@ -3067,18 +3123,23 @@ async fn process_authorized(
agent = %env.agent.as_str(),
"ignoring SessionEnd naming a different scope than its session"
);
- return Ok(());
+ return Ok(HookProcessingOutcome::IgnoredEnd);
}
HookSessionAdmission::AlreadyEnded { session } => {
let commit_msg = format!("repair session {}", short_id(&session_id.to_string()));
+ let mut recovered = false;
match state.wiki.commit_all(&commit_msg) {
- Ok(Some(oid)) => debug!(commit = %oid, "wiki recovery auto-commit"),
+ Ok(Some(oid)) => {
+ recovered = true;
+ state.ingest_metrics.record_persisted(now_unix_ms());
+ debug!(commit = %oid, "wiki recovery auto-commit");
+ }
Ok(None) => debug!("wiki clean during SessionEnd recovery"),
Err(e) => warn!(error = %e, "SessionEnd recovery auto-commit failed"),
}
let observations = state.reader.observations_for_session(session_id).await?;
if !is_ephemeral_session(&observations) {
- enqueue_session_end_consolidation(
+ recovered |= enqueue_session_end_consolidation(
state,
session_id,
session.workspace_id(),
@@ -3092,15 +3153,25 @@ async fn process_authorized(
.complete_observation_ingest_if_claimed(session.project_id(), key)
.await?;
}
- return Ok(());
+ return Ok(if recovered {
+ HookProcessingOutcome::Resumed
+ } else {
+ HookProcessingOutcome::IgnoredEnd
+ });
}
HookSessionAdmission::Observation { session, ingest }
| HookSessionAdmission::EndOpen { session, ingest }
| HookSessionAdmission::ReEnd { session, ingest } => (session, ingest),
};
if ingest == IngestObservationOutcome::AlreadyComplete {
- return Ok(());
+ return Ok(HookProcessingOutcome::Replayed);
}
+ let outcome = if matches!(ingest, IngestObservationOutcome::Inserted(_)) {
+ state.ingest_metrics.record_persisted(now_unix_ms());
+ HookProcessingOutcome::Stored
+ } else {
+ HookProcessingOutcome::Resumed
+ };
if ingest == IngestObservationOutcome::ResumePending {
debug!("resuming incomplete keyed hook event");
}
@@ -3174,7 +3245,10 @@ async fn process_authorized(
ws,
proj,
admitted.agent_kind(),
- checkpoint_label,
+ HookCheckpoint {
+ label: checkpoint_label,
+ track_page_write: outcome == HookProcessingOutcome::Resumed,
+ },
session_actor.clone(),
)
.await
@@ -3209,16 +3283,17 @@ async fn process_authorized(
if let Some(key) = ingest_key {
state.writer.complete_observation_ingest(proj, key).await?;
}
- return Ok(());
+ return Ok(outcome);
}
let (page_ws, page_proj) = checkpoint_scope.unwrap_or((ws, proj));
if is_ephemeral_session(&observations) {
- let outcome = state
+ let lifecycle_outcome = state
.writer
.end_admitted_lifecycle_only_session(admitted.clone(), env.occurred_at_micros())
.await?;
- match outcome {
+ match lifecycle_outcome {
ai_memory_store::LifecycleOnlyEndOutcome::Ended { reopened_handoff } => {
+ state.ingest_metrics.record_persisted(now_unix_ms());
let commit_msg = format!(
"lifecycle-only session {}",
short_id(&session_id.to_string()),
@@ -3236,7 +3311,7 @@ async fn process_authorized(
if let Some(key) = ingest_key {
state.writer.complete_observation_ingest(proj, key).await?;
}
- return Ok(());
+ return Ok(outcome);
}
ai_memory_store::LifecycleOnlyEndOutcome::Substantive => {
observations = state.reader.observations_for_session(session_id).await?;
@@ -3257,6 +3332,15 @@ async fn process_authorized(
admitted.agent_kind(),
&observations,
);
+ let track_page_write = turn_checkpoint && outcome == HookProcessingOutcome::Resumed;
+ let previous_page_id = if track_page_write {
+ state
+ .reader
+ .latest_page_id_by_ids(page_ws, page_proj, new_page.path.as_str().to_owned())
+ .await?
+ } else {
+ None
+ };
let page_id = state
.wiki
.write_page(ai_memory_wiki::WritePageRequest {
@@ -3280,6 +3364,9 @@ async fn process_authorized(
evidence: Vec::new(),
})
.await?;
+ if track_page_write && previous_page_id != Some(page_id) {
+ state.ingest_metrics.record_persisted(now_unix_ms());
+ }
// The baton follows the SESSION's owner, so it reaches the person who
// was working, not whoever flushed the event. Run through the ownership
// gate again because even an attributed session remains shared on a
@@ -3382,6 +3469,11 @@ async fn process_authorized(
}
}
};
+ // An admitted open/re-end transition committed even when its summary
+ // page was already present from an interrupted delivery.
+ if !turn_checkpoint {
+ state.ingest_metrics.record_persisted(now_unix_ms());
+ }
if handoff_id.is_some()
&& let Some(ctx) = &admission_ctx
{
@@ -3439,7 +3531,7 @@ async fn process_authorized(
state.writer.complete_observation_ingest(proj, key).await?;
}
- Ok(())
+ Ok(outcome)
}
/// Parse the persisted owner without turning corrupt owned data into shared
@@ -3774,6 +3866,11 @@ fn checkpoint_degrades_to_synth(error: &ConsolidatorError) -> bool {
matches!(error, ConsolidatorError::Llm(_))
}
+struct HookCheckpoint {
+ label: &'static str,
+ track_page_write: bool,
+}
+
/// Write a fresh `sessions/<id>.md` for the current session without
/// ending it. Used by the PreCompact and PostCompaction branches to checkpoint
/// state before/after the agent's working context collapses.
@@ -3783,9 +3880,24 @@ async fn consolidate_or_synth(
workspace_id: WorkspaceId,
project_id: ProjectId,
agent_kind: AgentKind,
- checkpoint_label: &str,
+ checkpoint: HookCheckpoint,
actor: ai_memory_core::ActorContext,
) -> anyhow::Result<()> {
+ let checkpoint_label = checkpoint.label;
+ // First deliveries already stamped their observation write. Only a retry
+ // needs to distinguish a recovered page write from an unchanged checkpoint.
+ let previous_page_id = if checkpoint.track_page_write {
+ state
+ .reader
+ .latest_page_id_by_ids(
+ workspace_id,
+ project_id,
+ format!("sessions/{session_id}.md"),
+ )
+ .await?
+ } else {
+ None
+ };
let fallback_from_llm = state.consolidator.is_some();
if let Some(c) = state.consolidator.as_ref() {
let result = c
@@ -3798,6 +3910,13 @@ async fn consolidate_or_synth(
.await;
match result {
Ok(outcome) => {
+ if checkpoint.track_page_write
+ && outcome.page_id.is_some()
+ && outcome.page_id != previous_page_id
+ {
+ state.ingest_metrics.record_persisted(now_unix_ms());
+ }
+
debug!(
session = %session_id,
path = %outcome.path,
@@ -3846,7 +3965,7 @@ async fn consolidate_or_synth(
agent_kind,
&observations,
);
- state
+ let page_id = state
.wiki
.write_page(ai_memory_wiki::WritePageRequest {
workspace_id: new_page.workspace_id,
@@ -3867,6 +3986,10 @@ async fn consolidate_or_synth(
evidence: Vec::new(),
})
.await?;
+ if checkpoint.track_page_write && previous_page_id != Some(page_id) {
+ state.ingest_metrics.record_persisted(now_unix_ms());
+ }
+
let _ = state
.wiki
.commit_all(&format!(
@@ -4284,6 +4407,7 @@ mod tests {
}),
}];
let before = state.ingest_metrics.snapshot().dropped_unauthorized;
+ state.ingest_metrics.record_persisted(123);
let response = handle_hook_batch(
State(Arc::new(state.clone())),
None,
@@ -4299,6 +4423,11 @@ mod tests {
.await
.unwrap();
let ack: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(
+ ack["results"],
+ serde_json::json!([{ "index": 0, "outcome": "dropped_unauthorized" }])
+ );
+ assert_eq!(state.ingest_metrics.snapshot().last_persisted_ms, Some(123));
assert_eq!(
ack["accepted"], 1,
"the client must be told to drop it, or it will re-send it forever: {ack}"
@@ -4627,6 +4756,7 @@ mod tests {
viewer,
)
.await
+ .map(|_| ())
}
/// A user holding `role` on the capture fixture's repository.
@@ -4770,7 +4900,10 @@ mod tests {
state.workspace_id,
state.project_id,
AgentKind::ClaudeCode,
- "pre-compact",
+ HookCheckpoint {
+ label: "pre-compact",
+ track_page_write: true,
+ },
ai_memory_core::ActorContext::anonymous(),
)
.await
@@ -4853,7 +4986,10 @@ mod tests {
state.workspace_id,
state.project_id,
AgentKind::ClaudeCode,
- "pre-compact",
+ HookCheckpoint {
+ label: "pre-compact",
+ track_page_write: true,
+ },
ai_memory_core::ActorContext::anonymous(),
)
.await
@@ -4890,7 +5026,10 @@ mod tests {
state.workspace_id,
state.project_id,
AgentKind::ClaudeCode,
- "pre-compact",
+ HookCheckpoint {
+ label: "pre-compact",
+ track_page_write: true,
+ },
ai_memory_core::ActorContext::anonymous(),
)
.await
@@ -6035,6 +6174,187 @@ mod tests {
/// Completed replays are skipped, while a claim left pending after the
/// observation commit resumes and completes its downstream processing.
/// Fresh keys and keyless older clients keep landing normally.
+ #[tokio::test]
+ async fn checkpoint_noop_keeps_page_version_and_last_write() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let env = session_envelope("user-prompt-submit", "checkpoint-noop", "/tmp/scratch");
+ let sid = resolve_session_id(&env).unwrap();
+ process(&state, env, None, Vec::new()).await.unwrap();
+ let (ws, proj, _) = state.reader.find_session_scope(sid).await.unwrap().unwrap();
+ consolidate_or_synth(
+ &state,
+ sid,
+ ws,
+ proj,
+ AgentKind::ClaudeCode,
+ HookCheckpoint {
+ label: "test",
+ track_page_write: true,
+ },
+ ai_memory_core::ActorContext::anonymous(),
+ )
+ .await
+ .unwrap();
+ let before = state.reader.status_counts().await.unwrap();
+ assert_eq!(before.pages_all, 1);
+ state.ingest_metrics.record_persisted(123);
+ consolidate_or_synth(
+ &state,
+ sid,
+ ws,
+ proj,
+ AgentKind::ClaudeCode,
+ HookCheckpoint {
+ label: "test",
+ track_page_write: true,
+ },
+ ai_memory_core::ActorContext::anonymous(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ state.reader.status_counts().await.unwrap().pages_all,
+ before.pages_all
+ );
+ assert_eq!(state.ingest_metrics.snapshot().last_persisted_ms, Some(123));
+ }
+
+ #[tokio::test]
+ async fn async_processing_classifies_replay_and_missing_end_without_new_writes() {
+ let tmp = TempDir::new().unwrap();
+ let state = Arc::new(make_state(&tmp).await);
+ let mut env = session_envelope("user-prompt-submit", "async-outcomes", "/tmp/scratch");
+ env.ingest_key = Some("async-prompt".into());
+ assert_eq!(
+ process_envelope(
+ state.clone(),
+ env.clone(),
+ None,
+ ai_memory_core::AuthLevel::Anonymous,
+ Vec::new(),
+ None
+ )
+ .await,
+ Some(HookProcessingOutcome::Stored)
+ );
+ let count = state.reader.status_counts().await.unwrap().observations;
+ state.ingest_metrics.record_persisted(123);
+ assert_eq!(
+ process_envelope(
+ state.clone(),
+ env,
+ None,
+ ai_memory_core::AuthLevel::Anonymous,
+ Vec::new(),
+ None
+ )
+ .await,
+ Some(HookProcessingOutcome::Replayed)
+ );
+ let missing = session_envelope("session-end", "async-missing-end", "/tmp/scratch");
+ assert_eq!(
+ process_envelope(
+ state.clone(),
+ missing,
+ None,
+ ai_memory_core::AuthLevel::Anonymous,
+ Vec::new(),
+ None
+ )
+ .await,
+ Some(HookProcessingOutcome::IgnoredEnd)
+ );
+ assert_eq!(
+ state.reader.status_counts().await.unwrap().observations,
+ count
+ );
+ let metrics = state.ingest_metrics.snapshot();
+ assert_eq!(
+ (metrics.stored, metrics.replayed, metrics.ignored_end),
+ (1, 1, 1)
+ );
+ assert_eq!(metrics.last_persisted_ms, Some(123));
+ }
+
+ #[tokio::test]
+ async fn empty_batch_has_explicit_empty_results_without_effects() {
+ let tmp = TempDir::new().unwrap();
+ let state = Arc::new(make_state(&tmp).await);
+ let response = handle_hook_batch(
+ State(state.clone()),
+ None,
+ None,
+ None,
+ HeaderMap::new(),
+ Json(Vec::new()),
+ )
+ .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["results"], serde_json::json!([]));
+ assert_eq!(ack["accepted"], 0);
+ assert_eq!(state.reader.status_counts().await.unwrap().observations, 0);
+ assert_eq!(state.ingest_metrics.snapshot().last_persisted_ms, None);
+ }
+
+ #[tokio::test]
+ async fn batch_results_preserve_replay_and_end_noop_storage() {
+ let tmp = TempDir::new().unwrap();
+ let state = Arc::new(make_state(&tmp).await);
+ let send = |event: &str, sid: &str, key: &str| {
+ let state = state.clone();
+ let item = HookBatchItem {
+ url: format!("http://h/hook?event={event}&agent=claude-code&ingest_key={key}"),
+ body: serde_json::json!({"session_id": sid, "prompt": "legitimate work"}),
+ };
+ async move {
+ let response = handle_hook_batch(
+ State(state),
+ None,
+ None,
+ None,
+ HeaderMap::new(),
+ Json(vec![item]),
+ )
+ .await
+ .into_response();
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ serde_json::from_slice::<serde_json::Value>(&bytes).unwrap()
+ }
+ };
+ let missing = send("session-end", "absent", "missing-end").await;
+ assert_eq!(missing["results"][0]["outcome"], "ignored_end");
+ assert_eq!(state.reader.status_counts().await.unwrap().observations, 0);
+ assert_eq!(state.ingest_metrics.snapshot().last_persisted_ms, None);
+ let first = send("user-prompt-submit", "results-session", "prompt-1").await;
+ assert_eq!(first["results"][0]["outcome"], "stored");
+ let before = state.reader.status_counts().await.unwrap();
+ state.ingest_metrics.record_persisted(123);
+ let retry = send("user-prompt-submit", "results-session", "prompt-1").await;
+ assert_eq!(retry["results"][0]["outcome"], "replayed");
+ assert_eq!(
+ state.reader.status_counts().await.unwrap().observations,
+ before.observations
+ );
+ assert_eq!(state.ingest_metrics.snapshot().last_persisted_ms, Some(123));
+ let end = send("session-end", "results-session", "end-1").await;
+ assert_eq!(end["results"][0]["outcome"], "stored");
+ let ended = state.reader.status_counts().await.unwrap();
+ state.ingest_metrics.record_persisted(456);
+ let retry = send("session-end", "results-session", "end-1").await;
+ assert_eq!(retry["results"][0]["outcome"], "ignored_end");
+ let after = state.reader.status_counts().await.unwrap();
+ assert_eq!(after.observations, ended.observations);
+ assert_eq!(after.pages_all, ended.pages_all);
+ assert_eq!(state.ingest_metrics.snapshot().last_persisted_ms, Some(456));
+ }
+
#[tokio::test]
async fn replayed_ingest_key_does_not_duplicate_observation() {
let tmp = TempDir::new().unwrap();
@@ -6095,14 +6415,19 @@ mod tests {
.await
.unwrap();
assert!(matches!(pending, IngestObservationOutcome::Inserted(_)));
- process(
+ state.ingest_metrics.record_persisted(123);
+ let outcome = process_authorized(
&state,
fire("user-prompt-submit", Some("entry-pending")),
None,
+ ai_memory_core::AuthLevel::Anonymous,
Vec::new(),
+ None,
)
.await
.unwrap();
+ assert_eq!(outcome, HookProcessingOutcome::Resumed);
+ assert_eq!(state.ingest_metrics.snapshot().last_persisted_ms, Some(123));
let completed = state
.writer
.insert_observation_ingest(pending_obs(), "entry-pending".into())
@@ -6644,6 +6969,7 @@ mod tests {
let snap = metrics.snapshot();
assert_eq!(snap.dropped_by_policy, 2, "accept-but-drop is still a drop");
+ assert_eq!(snap.last_persisted_ms, None);
assert_eq!(
snap.accepted, 0,
"a dropped item spends no ingress capacity"
@@ -7008,6 +7334,10 @@ mod tests {
.await
.unwrap();
let ack: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(
+ ack["results"],
+ serde_json::json!([{ "index": 0, "outcome": "dropped_subagent" }, { "index": 1, "outcome": "stored" }])
+ );
// Accept-but-drop: BOTH are acked so the client clears its spool…
assert_eq!(
ack["accepted"], 2,
@@ -7340,6 +7670,12 @@ mod tests {
.await
.into_response();
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
+ 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["results"], serde_json::json!([]));
+ assert_eq!(ack["accepted"], 0);
}
#[tokio::test]
@@ -7374,6 +7710,10 @@ mod tests {
.await
.unwrap();
let ack: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(
+ ack["results"],
+ serde_json::json!([{ "index": 1, "outcome": "stored" }])
+ );
assert_eq!(ack["accepted"], 0);
assert_eq!(ack["accepted_indices"], serde_json::json!([1]));
}
@@ -7386,8 +7726,9 @@ mod tests {
assert!(limiter.try_take("u:\ns:flooder", std::time::Instant::now()));
state.ingest_rate = Arc::new(tokio::sync::Mutex::new(limiter));
+ let state = Arc::new(state);
let response = handle_hook_batch(
- State(Arc::new(state)),
+ State(state.clone()),
None,
None,
None,
@@ -7397,10 +7738,18 @@ mod tests {
url: "http://h/hook?event=session-start&agent=claude-code".into(),
body: serde_json::json!({ "session_id": "flooder" }),
},
+ HookBatchItem {
+ url: "http://h/hook?event=session-start&agent=claude-code".into(),
+ body: serde_json::json!({ "session_id": "accepted-before-failure" }),
+ },
HookBatchItem {
url: "http://h/hook?event=user-prompt-submit&agent=claude-code".into(),
body: serde_json::json!({ "prompt": "missing session fails" }),
},
+ HookBatchItem {
+ url: "http://h/hook?event=session-start&agent=claude-code".into(),
+ body: serde_json::json!({ "session_id": "unprocessed-after-failure" }),
+ },
]),
)
.await
@@ -7410,9 +7759,24 @@ mod tests {
.await
.unwrap();
let ack: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(
+ ack["results"],
+ serde_json::json!([{ "index": 1, "outcome": "stored" }])
+ );
assert_eq!(ack["accepted"], 0);
- assert_eq!(ack["accepted_indices"], serde_json::json!([]));
- assert_eq!(ack["failed_index"], 1);
+ 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)
+ );
}
#[tokio::test]
@@ -9053,6 +9417,10 @@ mod tests {
.await
.unwrap();
let ack: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(
+ ack["results"],
+ serde_json::json!([{ "index": 0, "outcome": "dropped_collision" }, { "index": 1, "outcome": "stored" }])
+ );
assert_eq!(ack["accepted"], 2, "both contiguous entries are cleared");
assert!(ack.get("accepted_indices").is_none() || ack["accepted_indices"].is_null());
assert!(ack.get("failed_index").is_none() || ack["failed_index"].is_null());
@@ -11656,7 +12024,9 @@ mod tests {
},
serde_json::json!({ "session_id": sid.to_string(), "cwd": "/tmp/target" }),
);
- process(&state, env, None, Vec::new()).await.unwrap();
+ process(&state, env.clone(), None, Vec::new())
+ .await
+ .unwrap();
let pages = state
.reader
@@ -11683,6 +12053,49 @@ mod tests {
.is_none(),
"already-ended synthetic SessionEnd must not create a handoff"
);
+
+ process(
+ &state,
+ session_envelope("user-prompt-submit", "pending-log-write", "/tmp/scratch"),
+ None,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+ state.ingest_metrics.record_persisted(123);
+ let outcome = process_authorized(
+ &state,
+ env.clone(),
+ None,
+ ai_memory_core::AuthLevel::Anonymous,
+ Vec::new(),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(outcome, HookProcessingOutcome::Resumed);
+ assert_ne!(
+ state.ingest_metrics.snapshot().last_persisted_ms,
+ Some(123),
+ "a new recovery commit must advance persistence"
+ );
+ state.ingest_metrics.record_persisted(123);
+ let outcome = process_authorized(
+ &state,
+ env,
+ None,
+ ai_memory_core::AuthLevel::Anonymous,
+ Vec::new(),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(outcome, HookProcessingOutcome::IgnoredEnd);
+ assert_eq!(
+ state.ingest_metrics.snapshot().last_persisted_ms,
+ Some(123),
+ "a clean replay writes nothing"
+ );
}
#[tokio::test]
@@ -11845,14 +12258,36 @@ mod tests {
.await
.unwrap();
- process(
+ state.ingest_metrics.record_persisted(123);
+ let recovered = process_authorized(
+ &state,
+ fire("session-end", Some("entry-recovery")),
+ None,
+ ai_memory_core::AuthLevel::Anonymous,
+ Vec::new(),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(recovered, HookProcessingOutcome::Resumed);
+ assert_ne!(
+ state.ingest_metrics.snapshot().last_persisted_ms,
+ Some(123),
+ "a newly enqueued durable job is a real write"
+ );
+ state.ingest_metrics.record_persisted(456);
+ let repeated = process_authorized(
&state,
fire("session-end", Some("entry-recovery")),
None,
+ ai_memory_core::AuthLevel::Anonymous,
Vec::new(),
+ None,
)
.await
.unwrap();
+ assert_eq!(repeated, HookProcessingOutcome::IgnoredEnd);
+ assert_eq!(state.ingest_metrics.snapshot().last_persisted_ms, Some(456));
let now = Timestamp::now().as_microsecond();
let job = state
.writer
@@ -15048,6 +15483,10 @@ mod tests {
.await
.unwrap();
let ack: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(
+ ack["results"],
+ serde_json::json!([{ "index": 0, "outcome": "stored" }, { "index": 1, "outcome": "dropped_policy" }, { "index": 2, "outcome": "stored" }])
+ );
assert_eq!(ack["accepted"], 3);
let sid = resolve_session_id(&HookEnvelope::from_query_and_body(
HookQuery {
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 05fd1c36..444e6788 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -72,6 +72,11 @@ from hook paths.
wiki commit, durable provider job, and pending key without appending another
observation. `log.md` gets an appended
`## [YYYY-MM-DDTHH:MM:SSZ] <event> | <title>` line.
+ Inline `/hook/batch` ACKs include an outcome per acknowledged index.
+ Process-lifetime counters distinguish stored events, replays, recovery and
+ ignored endings. `last_persisted_ms` advances after a durable write or terminal
+ effect; retries and no-op endings do not advance it. Normal checkpoints reuse
+ the observation write timestamp; only recovery checks for a new page version.
3. On true `SessionEnd` events, the server synthesises a
`sessions/<id>.md` summary page (rule-based, no LLM) and opens a
`Handoff` row for the next agent. One SQLite transaction inserts that
diff --git a/docs/external-lifecycle.md b/docs/external-lifecycle.md
index b085d80b..2c905d6c 100644
--- a/docs/external-lifecycle.md
+++ b/docs/external-lifecycle.md
@@ -141,6 +141,12 @@ Use the tuple recipe when event IDs have narrower scope.
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
+ 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
@@ -178,8 +184,9 @@ not disable native harness transcript files or other vendors' hooks.
Auth, owner checks, admission rules and sanitization still apply. All items in
one batch share one authenticated identity; separate batches by operator when
representing multiple users. `extension` is self-declared provenance and the
-capture variable grants no permissions. ai-memory has a shared single-tenant
-wiki with multi-user attribution, not per-project RBAC or producer isolation.
+capture variable grants no permissions. Project access modes and grants apply
+to DB-user tokens. Pages are shared by authorized project members; session and
+handoff ownership still applies. Producer namespaces provide provenance only.
See [multi-user attribution](users.md).
No framework adapter, workflow engine, generic plugin runtime or OpenTelemetry
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 9027f977..6d90be06 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -51,14 +51,14 @@ 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 |
+| 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 | `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 | 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) | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` |
| 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 |
| 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 |
| 13b | Managed-run lease exclusivity (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and refuses any other `active` run on the workstream inside one transaction (`StoreError::WorkstreamBusy`), regardless of the `lease_owner` label; `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` `wait_out_held_lease` (interactive relaunch) only waits for a reported expiry and retries — it never cancels or claims another run, so the server's busy check stays the sole arbiter | `store/src/lib.rs` `managed_workstream_batches_are_idempotent_and_release_the_lease` (second prepare refused while active); `run.rs` `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over` (renewing holder is reported, never displaced), with controls `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 |
-| 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; 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`; `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; `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 |
diff --git a/tests/e2e/external_relay_smoke.py b/tests/e2e/external_relay_smoke.py
index c06d71f5..f012004d 100755
--- a/tests/e2e/external_relay_smoke.py
+++ b/tests/e2e/external_relay_smoke.py
@@ -188,7 +188,7 @@ def write_json(path: Path, value: Any) -> None:
path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8")
-def parse_status(stdout: str, label: str) -> dict[str, int]:
+def parse_status(stdout: str, label: str) -> dict[str, Any]:
def unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
result: dict[str, Any] = {}
for key, value in pairs:
@@ -209,7 +209,16 @@ def parse_status(stdout: str, label: str) -> dict[str, int]:
raise SmokeFailure(f"{label} status JSON has no integer pending_items")
if type(receipts) is not int:
raise SmokeFailure(f"{label} status JSON has no integer receipts")
- return {"pending_items": pending_items, "receipts": receipts}
+ outcomes = parsed.get("receipt_outcomes")
+ expected = {
+ "stored", "replayed", "resumed", "ignored_end", "dropped_policy",
+ "dropped_subagent", "dropped_unauthorized", "dropped_collision", "unknown",
+ }
+ if not isinstance(outcomes, dict) or set(outcomes) != expected:
+ raise SmokeFailure(f"{label} status JSON has incomplete receipt outcomes")
+ if any(type(count) is not int or count < 0 for count in outcomes.values()):
+ raise SmokeFailure(f"{label} status JSON has invalid receipt counts")
+ return {"pending_items": pending_items, "receipts": receipts, "receipt_outcomes": outcomes}
class Harness:
@@ -582,8 +591,10 @@ def run_smoke(harness: Harness) -> None:
harness.start_server()
harness.flush(main_queue, "flush-after-server-start")
- _, flushed_pending = harness.status(main_queue, "status-after-flush")
+ flushed_status, flushed_pending = harness.status(main_queue, "status-after-flush")
require(flushed_pending == 0, f"successful flush left {flushed_pending} pending")
+ require(flushed_status["receipt_outcomes"]["stored"] == 3, "canonical receipts did not record stored outcomes")
+ require(flushed_status["receipt_outcomes"]["unknown"] == 0, "real-server outcomes became unknown")
main_rows = harness.observations(main_session)
require([row[0] for row in main_rows] == ["session-start", "user-prompt", "session-end"], "canonical lifecycle order differs")
require(all(row[1] == "producer-a" for row in main_rows), "canonical producer extension differs")
@@ -640,6 +651,7 @@ def run_smoke(harness: Harness) -> None:
)
collision_receipts_after = collision_status_after["receipts"]
require(collision_pending == 0, "acknowledged SessionCollision remained pending")
+ require(collision_status_after["receipt_outcomes"]["dropped_collision"] == 1, "collision receipt did not preserve its outcome")
require(
collision_receipts_after == collision_receipts_before + 1,
"SessionCollision acknowledgement did not create one relay receipt",
@@ -730,10 +742,11 @@ def run_smoke(harness: Harness) -> None:
)
proxy.forward_responses()
harness.flush(lost_response_queue, "flush-lost-response-retry")
- _, lost_response_retry_pending = harness.status(
+ lost_response_retry_status, lost_response_retry_pending = harness.status(
lost_response_queue, "status-lost-response-retry"
)
require(lost_response_retry_pending == 0, "lost-response retry remained pending")
+ require(lost_response_retry_status["receipt_outcomes"]["replayed"] == 1, "lost-response retry did not record replayed outcome")
require(
len(harness.observations(lost_response_session)) == 1,
"lost-response retry duplicated the real-server observation",