Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix: close merge audit regressions
AkitaOnRailsefb39df748b9
diff --git a/crates/ai-memory-consolidate/src/bootstrap.rs b/crates/ai-memory-consolidate/src/bootstrap.rsindex 3f2e3c51..a6c1c453 100644--- a/crates/ai-memory-consolidate/src/bootstrap.rs+++ b/crates/ai-memory-consolidate/src/bootstrap.rs@@ -316,6 +316,9 @@ impl Bootstrap {let incoming = sources.len();let (kept, _prune_internal, est_tokens) =prune_sources_to_budget(sources, cfg.max_input_tokens);+ if kept.is_empty() {+ return Err(BootstrapError::NoSources);+ }let (collected, sources_sent, sources_dropped) =bootstrap_source_counts(incoming, cfg.sources_collected, &kept);info!(@@ -837,7 +840,7 @@ pub fn plan_bootstrap_chunks(if chunk_budget == 0 {return vec![sources];}- let usable = chunk_budget.saturating_sub(1_000);+ let usable = usable_chunk_tokens(chunk_budget);let total: usize = sources.iter().map(BootstrapSource::estimated_tokens).sum();if total <= usable {return vec![sources];@@ -873,6 +876,15 @@ fn chunk_sources_greedy(sources: Vec<BootstrapSource>, usable: usize) -> Vec<Vecchunks}+fn usable_chunk_tokens(chunk_budget: usize) -> usize {+ const PROMPT_RESERVE: usize = 1_000;+ if chunk_budget > PROMPT_RESERVE {+ chunk_budget - PROMPT_RESERVE+ } else {+ chunk_budget+ }+}+fn split_oversized_source(source: BootstrapSource, usable: usize) -> Vec<BootstrapSource> {if usable == 0 || source.estimated_tokens() <= usable {return vec![source];@@ -1265,6 +1277,21 @@ mod tests {);}+ #[test]+ fn plan_chunks_treats_tiny_chunk_budget_as_content_budget() {+ let source = BootstrapSource {+ kind: SourceKind::DocFile,+ label: "docs/huge.md".into(),+ text: "x".repeat(10_000),+ };+ let chunks = plan_bootstrap_chunks(vec![source], 900);+ assert!(chunks.len() > 1, "tiny non-zero budget should still split");+ for chunk in &chunks {+ let t: usize = chunk.iter().map(BootstrapSource::estimated_tokens).sum();+ assert!(t <= 900, "chunk should respect tiny budget; got {t}");+ }+ }+#[test]fn plan_chunks_zero_disables() {let s = BootstrapSource {diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex af4558eb..9cfd475e 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -532,6 +532,14 @@ fn dry_run_outcome(}let incoming = sources.len();let (kept, _dropped, total) = prune_sources_to_budget(sources, max_input_tokens);+ if kept.is_empty() {+ return Err((+ StatusCode::UNPROCESSABLE_ENTITY,+ Json(serde_json::json!({+ "error": BootstrapError::NoSources.to_string()+ })),+ ));+ }let collected = sources_collected.unwrap_or(incoming);let sources_sent = kept.len();let sources_dropped = collected.saturating_sub(sources_sent);diff --git a/crates/ai-memory-mcp/tests/admin_bootstrap.rs b/crates/ai-memory-mcp/tests/admin_bootstrap.rsindex 92679348..6802224e 100644--- a/crates/ai-memory-mcp/tests/admin_bootstrap.rs+++ b/crates/ai-memory-mcp/tests/admin_bootstrap.rs@@ -181,6 +181,25 @@ async fn empty_sources_returns_error() {);}+/// A non-empty request that gets fully pruned by an impossibly small budget is+/// still a validation failure, not a successful no-op bootstrap.+#[tokio::test]+async fn fully_pruned_sources_return_error() {+ let tmp = TempDir::new().unwrap();+ let state = make_admin_state(&tmp).await;++ let body = json!({+ "workspace": "test-ws",+ "project": "test-proj",+ "sources": synthetic_sources(),+ "max_input_tokens": 1,+ "dry_run": true,+ });++ let resp = post_bootstrap(state, body).await;+ assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);+}+/// The workspace + project are auto-created by the handler; posting the/// same workspace/project a second time with `force=true` must not error/// (idempotent upsert).diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 13fe68a3..e5e63c25 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -63,10 +63,14 @@ impl Store {let mut conn = Connection::open(&db_path)?;conn.pragma_update(None, "journal_mode", "WAL")?;conn.pragma_update(None, "synchronous", "NORMAL")?;- conn.pragma_update(None, "foreign_keys", "ON")?;conn.pragma_update(None, "busy_timeout", 5_000)?; // ms+ // SQLite cannot disable FK enforcement inside refinery's per-migration+ // transaction. Keep it off while migrations rebuild tables, then enable+ // it for all runtime reads/writes below.+ conn.pragma_update(None, "foreign_keys", "OFF")?;migrations::run(&mut conn)?;+ conn.pragma_update(None, "foreign_keys", "ON")?;let writer = WriterHandle::spawn(conn);let reader = ReaderPool::new(&db_path, READER_POOL_SOFT_CAP)?;@@ -88,9 +92,10 @@ impl Store {mod tests {use super::*;use ai_memory_core::{- AgentKind, NewObservation, NewPage, NewSession, ObservationKind, PagePath, ProjectId,- SessionId, Tier, WorkspaceId,+ AgentKind, NewObservation, NewPage, NewSession, ObservationId, ObservationKind, PagePath,+ ProjectId, SessionId, Tier, WorkspaceId,};+ use rusqlite::{Connection, params};use tempfile::TempDir;fn sample_page(ws: WorkspaceId, proj: ProjectId, path: &str, body: &str) -> NewPage {@@ -170,6 +175,63 @@ mod tests {assert_eq!(pa, pb);}+ #[tokio::test]+ async fn v09_session_agent_kind_migration_preserves_observations() {+ let tmp = TempDir::new().unwrap();+ let db_dir = tmp.path().join("db");+ std::fs::create_dir_all(&db_dir).unwrap();+ let db_path = db_dir.join(DB_FILENAME);+ let mut conn = Connection::open(&db_path).unwrap();+ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();+ crate::migrations::run_to(&mut conn, 8).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();++ let ws = WorkspaceId::new();+ let proj = ProjectId::new();+ let sid = SessionId::new();+ let oid = ObservationId::new();+ conn.execute(+ "INSERT INTO workspaces (id, name, created_at) VALUES (?1, 'default', 1)",+ params![ws.as_bytes()],+ )+ .unwrap();+ conn.execute(+ "INSERT INTO projects (id, workspace_id, name, created_at) \+ VALUES (?1, ?2, 'scratch', 1)",+ params![proj.as_bytes(), ws.as_bytes()],+ )+ .unwrap();+ conn.execute(+ "INSERT INTO sessions (id, workspace_id, project_id, agent_kind, started_at) \+ VALUES (?1, ?2, ?3, 'open-code', 1)",+ params![sid.as_bytes(), ws.as_bytes(), proj.as_bytes()],+ )+ .unwrap();+ conn.execute(+ "INSERT INTO observations (id, session_id, workspace_id, project_id, kind, title, body, created_at) \+ VALUES (?1, ?2, ?3, ?4, 'user_prompt', 'keep', 'this observation must survive', 1)",+ params![oid.as_bytes(), sid.as_bytes(), ws.as_bytes(), proj.as_bytes()],+ )+ .unwrap();+ drop(conn);++ let store = Store::open(tmp.path()).unwrap();+ let count = store.reader.status_counts().await.unwrap().observations;+ assert_eq!(count, 1, "V09 must not cascade-delete observations");++ store+ .writer+ .begin_session(NewSession {+ id: SessionId::new(),+ workspace_id: ws,+ project_id: proj,+ agent_kind: AgentKind::Cursor,+ cwd: None,+ })+ .await+ .unwrap();+ }+#[tokio::test]async fn serialises_parallel_writes() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-store/src/migrations.rs b/crates/ai-memory-store/src/migrations.rsindex b21c6083..389dd798 100644--- a/crates/ai-memory-store/src/migrations.rs+++ b/crates/ai-memory-store/src/migrations.rs@@ -10,3 +10,11 @@ pub fn run(conn: &mut rusqlite::Connection) -> Result<(), refinery::Error> {migrations::runner().run(conn)?;Ok(())}++#[cfg(test)]+pub(crate) fn run_to(conn: &mut rusqlite::Connection, target: u32) -> Result<(), refinery::Error> {+ migrations::runner()+ .set_target(refinery::Target::Version(target))+ .run(conn)?;+ Ok(())+}