Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(decay): condition cold compaction batches
AkitaOnRails9f319e4ae310
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8176204f..040f2dcf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,10 @@ version in [`docs/changelog/`](docs/changelog/):### Fixed+- Fixed opt-in cold-page compaction replacing a newer user edit with the stale+ episodic body and metadata it had selected earlier. The sweep now writes the+ whole compaction batch only when every selected page version is still latest;+ one changed page leaves the entire batch untouched for the next sweep (#1721).- The OpenCode version probe now waits up to 10 seconds instead of 2, allowingcold-start executable scanning and loaded hosts without treating a workinginstallation as hung (#1718).diff --git a/crates/ai-memory-consolidate/src/sweep.rs b/crates/ai-memory-consolidate/src/sweep.rsindex c671b995..baab71d4 100644--- a/crates/ai-memory-consolidate/src/sweep.rs+++ b/crates/ai-memory-consolidate/src/sweep.rs@@ -48,9 +48,10 @@ use ai_memory_core::{ActorContext, PageEvidence, PageEvidenceKind, PageId, PagePath, ProjectId, Tier, WorkspaceId,};use ai_memory_store::{- DecayCandidate, DecayParams, ReaderPool, WriterHandle, retention_score_with_breadth,+ DecayCandidate, DecayParams, PagePrecondition, ReaderPool, WriterHandle,+ retention_score_with_breadth,};-use ai_memory_wiki::{Wiki, WritePageRequest};+use ai_memory_wiki::{ConditionalBatchWrite, Wiki, WritePageRequest};use jiff::Timestamp;use serde::Serialize;use thiserror::Error;@@ -791,7 +792,7 @@ pub(crate) async fn run_sweep_at(if !compacted.is_empty() {match wiki {Some(wiki) => {- let mut requests: Vec<WritePageRequest> = Vec::new();+ let mut requests: Vec<(WritePageRequest, PagePrecondition)> = Vec::new();let mut request_index: Vec<usize> = Vec::new();for (i, page) in compacted.iter().enumerate() {let path = match PagePath::new(page.path.clone()) {@@ -811,30 +812,40 @@ pub(crate) async fn run_sweep_at(};let (frontmatter, body) =build_compacted_markdown(&markdown.frontmatter, &markdown.body);- requests.push(WritePageRequest {- workspace_id,- project_id,- path,- frontmatter,- body,- tier: Tier::Episodic,- pinned: false,- title: None,- admission_ctx: None,- author_id: None,- actor: ActorContext::anonymous(),- evidence: Vec::new(),- });+ requests.push((+ WritePageRequest {+ workspace_id,+ project_id,+ path,+ frontmatter,+ body,+ tier: Tier::Episodic,+ pinned: false,+ title: None,+ admission_ctx: None,+ author_id: None,+ actor: ActorContext::anonymous(),+ evidence: Vec::new(),+ },+ PagePrecondition::Latest(page.id),+ ));request_index.push(i);}if !requests.is_empty() {- match wiki.apply_batch(requests).await {- Ok(new_ids) => {+ match wiki.apply_batch_if(requests).await {+ Ok(ConditionalBatchWrite::Written(new_ids)) => {for (slot, new_id) in request_index.into_iter().zip(new_ids) {compacted[slot].compacted = true;compacted[slot].new_id = Some(new_id);}}+ Ok(ConditionalBatchWrite::Mismatch { index, current }) => {+ tracing::debug!(+ index,+ ?current,+ "forget sweep: page changed during compaction; retrying batch on next sweep"+ );+ }Err(error) => tracing::warn!(%error,"forget sweep: compaction batch failed; retrying on next sweep"diff --git a/crates/ai-memory-consolidate/tests/suite/compaction_sweep.rs b/crates/ai-memory-consolidate/tests/suite/compaction_sweep.rsindex 1ab250e3..9985f452 100644--- a/crates/ai-memory-consolidate/tests/suite/compaction_sweep.rs+++ b/crates/ai-memory-consolidate/tests/suite/compaction_sweep.rs@@ -150,6 +150,151 @@ fn superseded_bodies(fx: &Fixture, path: &str) -> Vec<String> {const COLD_DAYS: i64 = 400;+#[tokio::test]+async fn compaction_does_not_supersede_a_concurrent_fresh_write() {+ use ai_memory_wiki::{AdmissionChain, AdmissionOp, FailurePolicy, WebhookConfig};+ use std::io::{Read, Write};++ let fx = seed_fixture().await;+ let path = "sessions/concurrent.md";+ write(+ &fx,+ path,+ "Old session",+ Tier::Episodic,+ false,+ "Old session body that the sweep is allowed to compact.",+ )+ .await;+ backdate_latest(&fx, path, COLD_DAYS);++ // Pause admission after A2 derived its replacement but before the batch+ // obtains the page lock. Channels make the interleaving deterministic.+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let url = format!("http://{}", listener.local_addr().unwrap());+ let (started_tx, started_rx) = tokio::sync::oneshot::channel();+ let (release_tx, release_rx) = std::sync::mpsc::channel();+ let server = std::thread::spawn(move || {+ let (mut stream, _) = listener.accept().unwrap();+ stream+ .set_read_timeout(Some(std::time::Duration::from_secs(2)))+ .unwrap();+ let mut bytes = Vec::new();+ let mut buf = [0_u8; 4096];+ let header_end = loop {+ if let Some(pos) = bytes.windows(4).position(|window| window == b"\r\n\r\n") {+ break pos + 4;+ }+ let read = stream.read(&mut buf).unwrap();+ assert!(read > 0);+ bytes.extend_from_slice(&buf[..read]);+ };+ let headers = String::from_utf8_lossy(&bytes[..header_end]).to_lowercase();+ let length = headers+ .lines()+ .find_map(|line| line.strip_prefix("content-length:"))+ .unwrap()+ .trim()+ .parse::<usize>()+ .unwrap();+ while bytes.len() < header_end + length {+ let read = stream.read(&mut buf).unwrap();+ assert!(read > 0);+ bytes.extend_from_slice(&buf[..read]);+ }+ started_tx.send(()).unwrap();+ release_rx+ .recv_timeout(std::time::Duration::from_secs(2))+ .unwrap();+ stream+ .write_all(b"HTTP/1.1 204 No Content\r\ncontent-length: 0\r\nconnection: close\r\n\r\n")+ .unwrap();+ });+ let sweep_wiki = fx.wiki.clone().with_admission_chain(+ AdmissionChain::new(vec![WebhookConfig {+ name: "pause-stale-compaction".into(),+ url,+ timeout_ms: 2_000,+ failure_policy: FailurePolicy::Reject,+ events: vec![AdmissionOp::WritePage],+ blocking: true,+ }])+ .unwrap(),+ );+ let params = DecayParams::default();+ let sweep = run_sweep_with_compaction(+ &fx.store.reader,+ &fx.store.writer,+ Some(&sweep_wiki),+ fx.ws,+ fx.proj,+ ¶ms,+ 0.0,+ ObservationRetention::default(),+ true,+ false,+ );+ let fresh_body = "New user correction: this information is current and must remain latest.";+ let update = async {+ tokio::time::timeout(std::time::Duration::from_secs(2), started_rx)+ .await+ .unwrap()+ .unwrap();+ let fresh_id = write(+ &fx,+ path,+ "Fresh correction",+ Tier::Semantic,+ true,+ fresh_body,+ )+ .await;+ release_tx.send(()).unwrap();+ fresh_id+ };+ let (report, fresh_id) = tokio::join!(sweep, update);+ server.join().unwrap();+ let report = report.unwrap();+ let (marker, latest_body) = latest_marker_and_body(&fx, path);+ let conn = rusqlite::Connection::open(fx.tmp.path().join("db/memory.sqlite")).unwrap();+ let metadata: (String, bool) = conn+ .query_row(+ "SELECT tier, pinned FROM pages WHERE workspace_id = ?1 \+ AND project_id = ?2 AND path = ?3 AND is_latest = 1",+ params![fx.ws.as_bytes(), fx.proj.as_bytes(), path],+ |row| Ok((row.get(0)?, row.get(1)?)),+ )+ .unwrap();+ let disk = fx+ .wiki+ .read_page(fx.ws, fx.proj, &PagePath::new(path).unwrap())+ .unwrap();++ assert_eq!(disk.body, latest_body, "file and DB should still agree");+ assert_eq!(latest_body, fresh_body);+ assert_eq!(metadata, ("semantic".to_string(), true));+ assert!(marker.is_none());+ assert_eq!(+ report.compacted.len(),+ 1,+ "the selected page remains visible as a skipped compaction"+ );+ assert!(!report.compacted[0].compacted);+ assert_eq!(report.compacted[0].new_id, None);+ assert_eq!(+ fx.store+ .reader+ .latest_page_id_by_ids(fx.ws, fx.proj, path.to_string())+ .await+ .unwrap(),+ Some(fresh_id)+ );+ assert_eq!(+ superseded_bodies(&fx, path),+ vec!["Old session body that the sweep is allowed to compact."]+ );+}+/// Test 1: with the flag OFF the sweep evicts a cold episodic page exactly as it/// always has — no compaction, no upgrade surprise.#[tokio::test]diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 80ebf292..30af8705 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -61,16 +61,16 @@ pub use error::{pub use grants::{GrantFilter, GrantListing, GrantOutcome, ProjectGrant};pub use maintenance::MaintenanceJob;pub use ops::{- AdmittedSession, BootstrapChunkRecord, CompactSummary, Compaction, ConditionalUpsert,- DateOnlyTtlPage, DeleteWorkspaceSummary, EmbedOutcome, EmbeddingWrite, EntityBackfillSummary,- HookSessionAdmission, IdentityResolution, IdleEndAction, IdleEndCandidate, IdleEndResult,- IngestObservationOutcome, LifecycleOnlyEndOutcome, MAX_PENDING_INBOX_MESSAGES,- MoveSessionSummary, MoveSummary, ObservationPruneOutcome, OkfMigratedPage,- PAGE_WINDOW_BACKFILL_BATCH, PagePrecondition, PageWindowBackfillSummary, PagesMode,- ProjectAliasWriteResolution, PurgeMode, PurgeSessionSummary, PurgeSummary, ReorgSummary,- RepairSessionTimesSummary, RepairedSessionTimes, SessionTimesCandidate, SessionTimesSkipReason,- SkippedSessionTimes, StaleAfterRepair, backfill_entity_index, backfill_page_windows,- backfill_page_windows_in_batches, purge_session, record_embed_failure,+ AdmittedSession, BootstrapChunkRecord, CompactSummary, Compaction, ConditionalBatchUpsert,+ ConditionalUpsert, DateOnlyTtlPage, DeleteWorkspaceSummary, EmbedOutcome, EmbeddingWrite,+ EntityBackfillSummary, HookSessionAdmission, IdentityResolution, IdleEndAction,+ IdleEndCandidate, IdleEndResult, IngestObservationOutcome, LifecycleOnlyEndOutcome,+ MAX_PENDING_INBOX_MESSAGES, MoveSessionSummary, MoveSummary, ObservationPruneOutcome,+ OkfMigratedPage, PAGE_WINDOW_BACKFILL_BATCH, PagePrecondition, PageWindowBackfillSummary,+ PagesMode, ProjectAliasWriteResolution, PurgeMode, PurgeSessionSummary, PurgeSummary,+ ReorgSummary, RepairSessionTimesSummary, RepairedSessionTimes, SessionTimesCandidate,+ SessionTimesSkipReason, SkippedSessionTimes, StaleAfterRepair, backfill_entity_index,+ backfill_page_windows, backfill_page_windows_in_batches, purge_session, record_embed_failure,};pub use profile::{NewProfileCandidate, PROFILE_CANDIDATES_LIMIT, PROFILE_ENTRIES_LIMIT, PROFILE_HARVEST_BATCH,diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex c1edb3a1..6b361506 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -274,6 +274,20 @@ pub enum ConditionalUpsert {},}+/// The outcome of an atomic conditional page batch.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum ConditionalBatchUpsert {+ /// Every precondition held and all pages were written.+ Upserted(Vec<PageId>),+ /// One precondition did not hold, so no page was written.+ Mismatch {+ /// Index of the refused page in the caller's batch.+ index: usize,+ /// The latest version at that path, if one exists.+ current: Option<PageId>,+ },+}+/// [`upsert_page`] only when `precondition` holds, checked in the same/// transaction as the write so no other writer can land in between.pub fn upsert_page_if(@@ -296,6 +310,32 @@ pub fn upsert_page_if(Ok(ConditionalUpsert::Upserted(id))}+/// Upsert a batch only when every page precondition holds in the batch's+/// transaction. A single mismatch writes nothing.+pub fn upsert_pages_batch_if(+ conn: &mut Connection,+ pages: &[(NewPage, PagePrecondition)],+) -> StoreResult<ConditionalBatchUpsert> {+ let now = Timestamp::now().as_microsecond();+ let tx = conn.transaction()?;+ for (index, (page, precondition)) in pages.iter().enumerate() {+ let current = latest_page_id_in_tx(&tx, page)?;+ let holds = match precondition {+ PagePrecondition::Absent => current.is_none(),+ PagePrecondition::Latest(expected) => current == Some(*expected),+ };+ if !holds {+ return Ok(ConditionalBatchUpsert::Mismatch { index, current });+ }+ }+ let mut ids = Vec::with_capacity(pages.len());+ for (page, _) in pages {+ ids.push(upsert_page_in_tx(&tx, page, now)?);+ }+ tx.commit()?;+ Ok(ConditionalBatchUpsert::Upserted(ids))+}+fn latest_page_id_in_tx(tx: &Transaction<'_>, page: &NewPage) -> StoreResult<Option<PageId>> {let raw: Option<Vec<u8>> = tx.query_row(@@ -11361,6 +11401,64 @@ pub(crate) mod tests {}}+ #[test]+ fn conditional_page_batch_is_all_or_nothing() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let first_path = "notes/first.md";+ let second_path = "notes/second.md";+ let first_id = upsert_page(&mut conn, &page(ws, proj, first_path, "first-v1")).unwrap();+ let second_id = upsert_page(&mut conn, &page(ws, proj, second_path, "second-v1")).unwrap();+ let concurrent = upsert_page(&mut conn, &page(ws, proj, second_path, "second-v2")).unwrap();++ let stale = vec![+ (+ page(ws, proj, first_path, "first-stale-batch"),+ PagePrecondition::Latest(first_id),+ ),+ (+ page(ws, proj, second_path, "second-stale-batch"),+ PagePrecondition::Latest(second_id),+ ),+ ];+ assert_eq!(+ upsert_pages_batch_if(&mut conn, &stale).unwrap(),+ ConditionalBatchUpsert::Mismatch {+ index: 1,+ current: Some(concurrent),+ }+ );+ fn latest_body(conn: &Connection, ws: WorkspaceId, proj: ProjectId, path: &str) -> String {+ conn.query_row(+ "SELECT body FROM pages WHERE workspace_id = ?1 AND project_id = ?2 \+ AND path = ?3 AND is_latest = 1",+ params![ws.as_bytes(), proj.as_bytes(), path],+ |row| row.get(0),+ )+ .unwrap()+ }+ assert_eq!(latest_body(&conn, ws, proj, first_path), "first-v1");+ assert_eq!(latest_body(&conn, ws, proj, second_path), "second-v2");++ let fresh = vec![+ (+ page(ws, proj, first_path, "first-v2"),+ PagePrecondition::Latest(first_id),+ ),+ (+ page(ws, proj, second_path, "second-v3"),+ PagePrecondition::Latest(concurrent),+ ),+ ];+ let ConditionalBatchUpsert::Upserted(ids) =+ upsert_pages_batch_if(&mut conn, &fresh).unwrap()+ else {+ panic!("current preconditions must admit the whole batch");+ };+ assert_eq!(ids.len(), 2);+ assert_eq!(latest_body(&conn, ws, proj, first_path), "first-v2");+ assert_eq!(latest_body(&conn, ws, proj, second_path), "second-v3");+ }+/// The V65 A2 marker is derived from the `compacted: true` frontmatter/// mirror at the single write choke point, in the same transaction as the/// body — a normal write leaves it NULL, so every pre-A2 path is unchanged.diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex ef830121..0558d76a 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -188,6 +188,10 @@ pub(crate) enum WriteCmd {pages: Vec<NewPage>,reply: oneshot::Sender<StoreResult<Vec<PageId>>>,},+ UpsertPageBatchIf {+ pages: Vec<(NewPage, ops::PagePrecondition)>,+ reply: oneshot::Sender<StoreResult<ops::ConditionalBatchUpsert>>,+ },DeletePage {workspace_id: WorkspaceId,project_id: ProjectId,@@ -2831,6 +2835,18 @@ impl WriterHandle {rx.await.map_err(|_| StoreError::WriterClosed)?}+ /// Atomically upsert a batch only when every latest-version precondition+ /// still holds in the write transaction.+ pub async fn upsert_pages_batch_if(+ &self,+ pages: Vec<(NewPage, ops::PagePrecondition)>,+ ) -> StoreResult<ops::ConditionalBatchUpsert> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::UpsertPageBatchIf { pages, reply: tx })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }+/// Upsert a page (creating it or superseding the existing latest/// version when the body has changed).///@@ -3995,6 +4011,10 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {let result = ops::upsert_pages_batch(&mut conn, &pages);send_or_warn(reply, result, "upsert_pages_batch");}+ WriteCmd::UpsertPageBatchIf { pages, reply } => {+ let result = ops::upsert_pages_batch_if(&mut conn, &pages);+ send_or_warn(reply, result, "upsert_pages_batch_if");+ }WriteCmd::BeginSession { session, reply } => {let result = ops::begin_session(&mut conn, &session);send_or_warn(reply, result, "begin_session");diff --git a/crates/ai-memory-wiki/src/lib.rs b/crates/ai-memory-wiki/src/lib.rsindex af1c322d..04d54c45 100644--- a/crates/ai-memory-wiki/src/lib.rs+++ b/crates/ai-memory-wiki/src/lib.rs@@ -36,8 +36,8 @@ pub use migrations::run_pending as run_wiki_migrations;pub use okf_index::okf_directory_listing;pub use watcher::{DEBOUNCE_WINDOW, RECONCILE_INTERVAL, WatcherHandle};pub use wiki::{- ConditionalWrite, EventLedgerFile, MoveSessionOutcome, PAGE_CHECKPOINT_WALK_LIMIT,- PurgeSessionOutcome, SessionPageFile, Wiki, WritePageRequest,+ ConditionalBatchWrite, ConditionalWrite, EventLedgerFile, MoveSessionOutcome,+ PAGE_CHECKPOINT_WALK_LIMIT, PurgeSessionOutcome, SessionPageFile, Wiki, WritePageRequest,};// Integration tests compile into this crate's test harness instead of adiff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rsindex 35de260a..ffef04b9 100644--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@ -11,9 +11,9 @@ use ai_memory_core::{use ai_memory_llm::Embedder;use ai_memory_store::{ApproveAutoImproveProposal, ApproveAutoImproveProposalResult, AutoImproveProposalDetail,- ConditionalUpsert, FailAutoImproveProposal, MoveSessionSummary, MoveSummary, PagePrecondition,- PagesMode, PurgeSessionSummary, ReaderPool, ScopeRow, WriterHandle, artifact_path_for,- f32_vec_to_bytes,+ ConditionalBatchUpsert, ConditionalUpsert, FailAutoImproveProposal, MoveSessionSummary,+ MoveSummary, PagePrecondition, PagesMode, PurgeSessionSummary, ReaderPool, ScopeRow,+ WriterHandle, artifact_path_for, f32_vec_to_bytes,};use tokio::sync::RwLock;@@ -2718,8 +2718,34 @@ impl Wiki {/// Returns [`WikiError`] for any filesystem, parsing, or store/// error.pub async fn apply_batch(&self, requests: Vec<WritePageRequest>) -> WikiResult<Vec<PageId>> {+ match self.apply_batch_inner(requests, None).await? {+ ConditionalBatchWrite::Written(ids) => Ok(ids),+ ConditionalBatchWrite::Mismatch { .. } => Err(ai_memory_wiki_error(+ "an unconditional page batch reported a precondition mismatch",+ )),+ }+ }++ /// Atomically apply a batch only when every page is still at the version+ /// the caller derived its replacement from. One mismatch writes nothing.+ ///+ /// # Errors+ /// As [`Self::apply_batch`].+ pub async fn apply_batch_if(+ &self,+ requests: Vec<(WritePageRequest, PagePrecondition)>,+ ) -> WikiResult<ConditionalBatchWrite> {+ let (requests, preconditions): (Vec<_>, Vec<_>) = requests.into_iter().unzip();+ self.apply_batch_inner(requests, Some(preconditions)).await+ }++ async fn apply_batch_inner(+ &self,+ requests: Vec<WritePageRequest>,+ preconditions: Option<Vec<PagePrecondition>>,+ ) -> WikiResult<ConditionalBatchWrite> {if requests.is_empty() {- return Ok(Vec::new());+ return Ok(ConditionalBatchWrite::Written(Vec::new()));}// Reject any path that cannot be materialised and checkpointed on every// supported platform, before anything is written.@@ -2814,6 +2840,22 @@ impl Wiki {.map(|(req, _, _, _)| (req.workspace_id, req.project_id, req.path.clone())).collect();let _page_guards = self.lock_pages(&batch_keys).await;+ if let (Some(preconditions), Some(reader)) = (&preconditions, &self.store_reader) {+ for (index, ((req, _, _, _), precondition)) in+ staged.iter().zip(preconditions).enumerate()+ {+ let current = reader+ .latest_page_id_by_ids(+ req.workspace_id,+ req.project_id,+ req.path.as_str().to_string(),+ )+ .await?;+ if !precondition_holds(*precondition, current) {+ return Ok(ConditionalBatchWrite::Mismatch { index, current });+ }+ }+ }let mut staged_files: Vec<(WritePageRequest,tempfile::NamedTempFile,@@ -2885,8 +2927,30 @@ impl Wiki {dispatches.push((req.path, req.frontmatter, req.body, ctx));}- let ids = match self.writer.upsert_pages_batch(pages).await {- Ok(ids) => ids,+ let write = match &preconditions {+ Some(preconditions) => {+ let pages = pages+ .into_iter()+ .zip(preconditions.iter().copied())+ .collect();+ self.writer.upsert_pages_batch_if(pages).await+ }+ None => self+ .writer+ .upsert_pages_batch(pages)+ .await+ .map(ConditionalBatchUpsert::Upserted),+ };+ let ids = match write {+ Ok(ConditionalBatchUpsert::Upserted(ids)) => ids,+ Ok(ConditionalBatchUpsert::Mismatch { index, current }) => {+ rollback_or_inconsistent(+ &self.git,+ &installed,+ &ai_memory_wiki_error("conditional page batch changed during write"),+ )?;+ return Ok(ConditionalBatchWrite::Mismatch { index, current });+ }Err(e) => {rollback_or_inconsistent(&self.git, &installed, &e)?;return Err(e.into());@@ -2920,7 +2984,7 @@ impl Wiki {}}- Ok(ids)+ Ok(ConditionalBatchWrite::Written(ids))}/// Acquire the per-path write lock for one page, serializing concurrent@@ -3356,6 +3420,20 @@ pub enum ConditionalWrite {},}+/// Outcome of an atomic conditional page batch.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum ConditionalBatchWrite {+ /// Every precondition held and all page versions were written.+ Written(Vec<PageId>),+ /// One precondition changed, so no page version was written.+ Mismatch {+ /// Index of the refused request in the supplied batch.+ index: usize,+ /// Current latest page version, if the path exists.+ current: Option<PageId>,+ },+}+/// Input bundle for [`Wiki::write_page`]. Carries the full 3-tuple/// identity (`workspace_id`, `project_id`, `path`) plus body & metadata.#[derive(Debug, Clone)]@@ -6618,6 +6696,109 @@ mod tests {assert_eq!(hits.len(), 5);}+ #[tokio::test]+ async fn conditional_batch_rejects_every_page_when_one_version_changed() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone())+ .unwrap()+ .with_store_reader(store.reader.clone());+ let first = PagePath::new("batch/first.md").unwrap();+ let second = PagePath::new("batch/second.md").unwrap();+ let first_id = wiki+ .write_page(req(+ ws,+ proj,+ first.as_str(),+ "first original",+ serde_json::json!({"title": "First"}),+ ))+ .await+ .unwrap();+ let stale_second_id = wiki+ .write_page(req(+ ws,+ proj,+ second.as_str(),+ "second original",+ serde_json::json!({"title": "Second"}),+ ))+ .await+ .unwrap();+ let current_second_id = wiki+ .write_page(req(+ ws,+ proj,+ second.as_str(),+ "second concurrent update",+ serde_json::json!({"title": "Second"}),+ ))+ .await+ .unwrap();++ let outcome = wiki+ .apply_batch_if(vec![+ (+ req(+ ws,+ proj,+ first.as_str(),+ "first stale replacement",+ serde_json::json!({"title": "First"}),+ ),+ PagePrecondition::Latest(first_id),+ ),+ (+ req(+ ws,+ proj,+ second.as_str(),+ "second stale replacement",+ serde_json::json!({"title": "Second"}),+ ),+ PagePrecondition::Latest(stale_second_id),+ ),+ ])+ .await+ .unwrap();++ assert_eq!(+ outcome,+ ConditionalBatchWrite::Mismatch {+ index: 1,+ current: Some(current_second_id),+ }+ );+ assert_eq!(+ wiki.read_page(ws, proj, &first).unwrap().body,+ "first original"+ );+ assert_eq!(+ wiki.read_page(ws, proj, &second).unwrap().body,+ "second concurrent update"+ );+ assert_eq!(+ store+ .reader+ .page_body_by_ids(ws, proj, first.as_str())+ .await+ .unwrap()+ .unwrap()+ .body,+ "first original"+ );+ }+#[tokio::test]async fn apply_batch_rolls_back_files_when_sql_batch_fails() {let tmp = TempDir::new().unwrap();diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 288dbdbd..05437ef1 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -609,7 +609,10 @@ to keep its L0 `abstract:`, an L1 first-paragraph summary, and an L2 regex-minedkeep-token set (paths, URLs, code spans, error codes, identifiers), dropping theprose, instead of being tombstoned. The rewrite supersedes the prior version,so the full body stays reachable (git + supersession chain; `restore-page`-recovers it). The `V65` `pages.compacted_at` marker makes a compacted page+recovers it). The batched rewrite is conditional on every source version still+being latest, checked inside the writer transaction; any concurrent edit rejects+the whole batch without replacing the edit or partially compacting its peers.+The `V65` `pages.compacted_at` marker makes a compacted pageterminal for the decay pass (never re-compacted, never re-evicted, neverre-reported as cold). Zero-LLM, off by default; the R2 recall no-regressionproof gates any future default-on.diff --git a/docs/design-memory-aging.md b/docs/design-memory-aging.mdindex 90b22c45..186c0e94 100644--- a/docs/design-memory-aging.md+++ b/docs/design-memory-aging.md@@ -192,20 +192,26 @@ Everything in A works with no provider and does not require ranking changes.mcp-memory-service ship extractive compression with no LLM. Tier-down beatseviction because the durable facts survive.- *Mechanism:* a new sweep pass, before the decay-eviction pass, that rewrites the- page through `Wiki::write_page`/`apply_batch` (supersession + git preserve the+ page through the wiki's conditional batch write (supersession + git preserve theoriginal, so it is **reversible**: the full body stays in the version chain and git- history). Regex keep-token miner lives beside the sanitizer's patterns. Needs a+ history). Every replacement is conditional on the selected source `PageId`, and+ the writer validates the whole batch in the same SQLite transaction: one page+ changed by a concurrent user leaves every replacement unwritten for the next+ sweep. Regex keep-token miner lives beside the sanitizer's patterns. Needs a**`tier_state`/`compacted` marker** (frontmatter flag + a `pages` column, V65) sothe sweep and `curator.rs` distinguish a *deliberately short* page from a *cold*one and never re-compact or misread it as cold.- *Schema delta:* V65 `pages.compacted_at` (nullable) + frontmatter mirror.- *Invariants:* mutation through the wiki layer only (#16 supersession keeps the- loser reachable); zero-LLM (#13).+ loser reachable); one conditional writer transaction for the batch (#2 and #3);+ zero-LLM (#13).- *R2 bar:* compaction must not drop recall on R2 vs. the pre-compaction corpus(the keep-token set is the hypothesis: facts survive, prose doesn't matter).- *Failure modes:* keep-token miner drops a load-bearing sentence → the original isone supersession-restore away; `restore-page` covers it. Re-compaction loop →- the `compacted_at` marker blocks it.+ the `compacted_at` marker blocks it. Concurrent user correction → the selected+ source id no longer matches and the full batch is retried later rather than+ replacing the correction.**A3. Cold-cluster dedup (DBSCAN, adaptive eps).**- *What:* cluster near-duplicate cold pages by embedding and collapse each clusterdiff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 83acea2d..9da19cd6 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -154,6 +154,7 @@ the legitimate restricted-project control and the failed-query cases.| 27 | Plain-HTTP human authentication stays fail-closed beyond loopback unless the operator supplies the dedicated dangerous override (#1383) | `ai-memory-cli/src/cli.rs` exposes `serve --allow-insecure-human-auth` separately from `--allow-insecure-no-auth`; `serve.rs` `validate_http_exposure` accepts it only when authentication and human mode are both active and the listener is non-loopback with a Non-Secure cookie, while the ordinary unauthenticated guard still runs otherwise. `HttpExposure::InsecureHumanAuthByOverride` gives that path its own unconditional stderr banner and structured warning, naming passwords, API credentials, session cookies, and memory data as plaintext. The default remains refusal, and `secure_cookie=true` or loopback remains the safe path | `serve.rs` `human_auth_non_loopback_requires_secure_cookie_posture` (default refusal, the no-auth override cannot substitute, the dedicated override succeeds, and that override cannot expose a server with no authentication even under inconsistent human-mode input; secure-cookie and loopback controls), `every_unsafe_exposure_produces_an_operator_banner` (the dedicated banner names the flag and session-cookie risk), and `cli.rs` `serve_parses_insecure_transport_overrides` (both dangerous flags remain distinct) | STRONG for the startup boundary. This is an explicit operator acceptance of transport risk, not encryption; authorization, CSRF, rate limits, Host validation, and the unauthenticated exposure refusal are unchanged || 27a | Provider credentials stay on the configured origin | `ai-memory-llm/src/redirect.rs` `same_origin_redirects`, set on every provider and embedder client (`anthropic.rs`, `codex.rs`, `copilot.rs`, `embedding.rs`, `gemini.rs`, `google.rs`, `openai.rs`, `openai_oauth.rs`, `opencode.rs`): a redirect is followed only when scheme, host and port match the previous request, with reqwest's ten-hop limit; any other redirect fails the request. reqwest's own guard strips only `Authorization`, cookies and the proxy headers, so `x-api-key`, `x-goog-api-key` and `llm_headers` values depend on this one. The local model download (`local.rs`) carries no credential and keeps the default policy for its CDN redirects; OIDC and CLI login requests refuse every redirect on clients of their own (`oidc.rs`, `auth.rs` `auth_http_client`) | `ai-memory-llm` `tests/suite/redirect_credentials.rs` `gemini_api_key_does_not_follow_a_cross_origin_redirect`, `anthropic_api_key_does_not_follow_a_cross_origin_redirect`, `operator_headers_do_not_follow_a_cross_origin_redirect` (with `Authorization` stripped as the control), `google_embedder_key_does_not_follow_a_cross_origin_redirect`, `a_refused_redirect_says_where_it_pointed`; legitimate control `a_same_origin_redirect_still_reaches_the_provider` (the key follows a path redirect on one origin); each cross-origin test fails with the policy removed | STRONG for the provider and embedder clients in `ai-memory-llm` || 27b | LLM workload telemetry cannot turn prompts, outputs, scopes, projects, or caller text into status data or unbounded metric labels | `ai-memory-llm/src/types.rs` `LlmWorkload` is a closed enum carried beside, but absent from the display/wire form of, `LlmOperationId`; `health.rs` `LlmWorkloadHealth` uses one fixed array and fixed latency buckets and records only counts/times/coarse estimates/reported usage/redacted error class and status; `ProviderHealth::snapshot` omits the rows when LLM support is disabled; `/admin/status` remains behind the common admin gate | `ai-memory-llm` `workload_snapshot_is_bounded_redacted_and_percentiled` (private prompt, output and upstream body absent; fixed row count, recovery-preserved last error, and percentile controls), `llm_wrapper_forwards_the_callers_operation_id` (label recorded while the same UUID-only id reaches the provider), `types::tests::workload_labels_are_stable_and_do_not_change_the_wire_operation_id`; `ai-memory-mcp` `status_reports_bounded_content_free_llm_workload_telemetry` (private prompt absent from serialized status, one fixed row per label), `status_reports_provider_health_block` (disabled LLM emits no rows) | STRONG for content/cardinality and the existing root-only admin surface |+| 27c | A maintenance compaction cannot replace a newer user page or partly apply a stale batch | `ai-memory-consolidate/src/sweep.rs` carries each selected source `PageId` into `Wiki::apply_batch_if`; `ai-memory-wiki/src/wiki.rs` checks the preconditions after locking every page, installs files with rollback snapshots, and delegates the decisive check to `WriterHandle::upsert_pages_batch_if`; `ai-memory-store/src/ops.rs` validates every latest id and writes every replacement in one SQLite transaction, returning a mismatch before any write | store `conditional_page_batch_is_all_or_nothing`; wiki `conditional_batch_rejects_every_page_when_one_version_changed` (file and DB controls); consolidate `compaction_does_not_supersede_a_concurrent_fresh_write` (an admission barrier lands a semantic pinned correction after A2 reads the old body, then proves the correction remains latest and the selected batch stays uncommitted) | STRONG; all-or-nothing intentionally retries unchanged peers with the next sweep instead of weakening invariant #2 into per-page writes || 28 | An Antigravity hook reads, and uploads as prompts, only the named conversation's own transcript, within bounds | `ai-memory-hooks/src/antigravity.rs` `antigravity_transcript_path` accepts the payload's `transcriptPath` only when it is absolute, has no `..`, names `transcript.jsonl` or `transcript_full.jsonl`, and its canonical directory equals `canonical(<home>/.gemini/<app>/brain)/<conversationId>/.system_generated/logs` for `<app>` `antigravity`, `antigravity-cli` or `antigravity-ide`, with `conversationId` a plain id (`antigravity_conversation_id`); `read_transcript_prompts` opens only a regular, non-symlink file that is still the same file once open (`open_regular_file`, opened with `O_NOFOLLOW | O_NONBLOCK` so a symlink or FIFO swapped in after the check is refused without blocking, and on Linux only when the opened descriptor's `/proc/self/fd` path is the checked one, so a directory swapped for a symlink after the containment check is refused too), reads at most `MAX_TRANSCRIPT_SCAN_BYTES` per hook and parses lines up to `MAX_TRANSCRIPT_LINE_BYTES`, and returns only `USER_INPUT` steps whose `source` is absent or `USER_EXPLICIT`; `ai-memory-cli/src/commands/hook.rs` `antigravity_transcript_prompt_events` runs inside the spool block, so after the capture allowlist, routing, server-profile and external-capture gates, with the home `run_with_payload` resolved once; its path checks, bounded cursor load and transcript read run behind `ANTIGRAVITY_TRANSCRIPT_READ_BUDGET`, and a timeout advances no cursor so a later hook retries; cursor replacement uses the canonical atomic writer; each prompt is capped and scrubbed client-side, keyed by conversation and step, and sanitized again by the server (row 7) | `antigravity.rs` `transcript_path_refuses_anything_outside_the_conversations_own_logs` (another conversation's transcript, the same layout outside the home, another file in the logs directory, an unknown app directory, `..`, a traversal or empty id, a relative path, a missing or non-string path; the conversation's own transcript is the control), `transcript_path_refuses_symlinked_directories_that_leave_the_conversation` (a symlinked `.system_generated` and `brain/<id>` refused; a symlinked `~/.gemini` accepted as the control), `transcript_reader_refuses_symlinks_and_special_files` (a symlinked transcript and a directory refused; the same bytes as a regular file are read), `skips_injected_malformed_empty_and_non_prompt_steps`, `a_line_longer_than_the_scan_budget_is_skipped_across_reads`, `one_read_returns_a_bounded_number_of_prompts`; `hook.rs` `antigravity_transcript_reads_are_confined_to_the_conversations_own_logs` (end to end through the native hook: a forged path outside the home, another conversation's transcript and an arbitrary JSONL file under the home spool no prompt; the conversation's own transcript spools one), `antigravity_transcript_prompts_follow_the_capture_allowlist` (a repository the allowlist leaves out is not read), `antigravity_transcript_read_deadline_does_not_wait_for_blocked_work`, and `antigravity_transcript_cursor_store_is_atomic_and_bounded` (oversized cursor refused) | STRONG on Linux, including the opened descriptor path. Stable symlink escapes and special files are refused on every platform; without Linux `/proc/self/fd`, a same-user process able to replace an ancestor in the narrow interval between canonicalization and open could redirect the read, which still remains size- and time-bounded. The directory-swap bite test is Linux-only; the other symlink cases are `cfg(unix)` |### IBM Bob evidence