Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
M7b: multi-page atomic fan-out (closes v1)
AkitaOnRails714e0a2024fa
diff --git a/crates/ai-memory-cli/src/commands/write_page.rs b/crates/ai-memory-cli/src/commands/write_page.rsindex aba587c8..ee2c1ad0 100644--- a/crates/ai-memory-cli/src/commands/write_page.rs+++ b/crates/ai-memory-cli/src/commands/write_page.rs@@ -73,6 +73,7 @@ pub async fn run(config: &Config, args: WritePageArgs) -> Result<()> {body,tier,pinned: args.pinned,+ title: None,}).await?;diff --git a/crates/ai-memory-consolidate/src/consolidator.rs b/crates/ai-memory-consolidate/src/consolidator.rsindex 10e3adec..397a8ab4 100644--- a/crates/ai-memory-consolidate/src/consolidator.rs+++ b/crates/ai-memory-consolidate/src/consolidator.rs@@ -16,7 +16,7 @@ use ai_memory_wiki::{Wiki, WritePageRequest};use thiserror::Error;use tracing::{debug, info};-use crate::types::{ConsolidatedPage, ConsolidationOutcome};+use crate::types::{ConsolidatedBatch, ConsolidatedPage, ConsolidationOutcome};/// Errors raised by the consolidator.#[derive(Debug, Error)]@@ -147,6 +147,7 @@ impl Consolidator {body: page.body_markdown.clone(),tier: Tier::Episodic,pinned: false,+ title: None,}).await?;// Auto-commit the result so the supersession lands in git.@@ -182,8 +183,150 @@ impl Consolidator {pub fn writer(&self) -> &WriterHandle {&self.writer}++ /// M7b multi-page consolidation: ask the LLM for a batch of page+ /// updates spanning sessions/, concepts/, decisions/, then write+ /// them all atomically (one SQL transaction).+ ///+ /// # Errors+ /// Returns [`ConsolidatorError`] for any store, wiki, or LLM+ /// failure. On error, no pages are written and no files moved.+ pub async fn consolidate_session_multi(+ &self,+ session_id: SessionId,+ dry_run: bool,+ ) -> ConsolidatorResult<Vec<ConsolidationOutcome>> {+ let observations = self.reader.observations_for_session(session_id).await?;+ if observations.is_empty() {+ return Err(ConsolidatorError::EmptySession(session_id));+ }+ let request = build_batch_request(session_id, &observations);+ debug!(+ session = %session_id,+ provider = self.llm.name(),+ "consolidating session (multi-page)",+ );+ let batch: ConsolidatedBatch =+ ai_memory_llm::complete_structured(&*self.llm, request).await?;++ let mut requests = Vec::with_capacity(batch.updates.len());+ let mut outcomes_preview = Vec::with_capacity(batch.updates.len());+ for upd in &batch.updates {+ let path = PagePath::new(upd.path.clone())?;+ let tier = upd.tier.parse::<Tier>().unwrap_or(Tier::Semantic);+ let mut fm = serde_json::Map::new();+ fm.insert("title".into(), serde_json::Value::String(upd.title.clone()));+ fm.insert(+ "tier".into(),+ serde_json::Value::String(tier_as_str(tier).into()),+ );+ if !upd.tags.is_empty() {+ fm.insert(+ "tags".into(),+ serde_json::Value::Array(+ upd.tags+ .iter()+ .map(|t| serde_json::Value::String(t.clone()))+ .collect(),+ ),+ );+ }+ fm.insert("consolidated".into(), serde_json::Value::Bool(true));+ requests.push(WritePageRequest {+ workspace_id: self.workspace_id,+ project_id: self.project_id,+ path: path.clone(),+ frontmatter: serde_json::Value::Object(fm),+ body: upd.body_markdown.clone(),+ tier,+ pinned: false,+ title: Some(upd.title.clone()),+ });+ outcomes_preview.push(ConsolidationOutcome {+ path,+ dry_run,+ new_title: upd.title.clone(),+ new_body_markdown: upd.body_markdown.clone(),+ page_id: None,+ tags: upd.tags.clone(),+ });+ }++ if dry_run {+ return Ok(outcomes_preview);+ }++ let ids = self.wiki.apply_batch(requests).await?;+ let rationale_short = batch.rationale.chars().take(60).collect::<String>();+ let _ = self.wiki.commit_all(&format!(+ "consolidate-batch(session {}): {} page(s) — {}",+ short_id(&session_id.to_string()),+ ids.len(),+ rationale_short,+ ));++ let outcomes = outcomes_preview+ .into_iter()+ .zip(ids)+ .map(|(mut o, id)| {+ o.dry_run = false;+ o.page_id = Some(id);+ o+ })+ .collect();+ Ok(outcomes)+ }+}++const fn tier_as_str(t: Tier) -> &'static str {+ match t {+ Tier::Working => "working",+ Tier::Episodic => "episodic",+ Tier::Semantic => "semantic",+ Tier::Procedural => "procedural",+ }+}++fn build_batch_request(session_id: SessionId, observations: &[Observation]) -> ChatRequest {+ let mut buf = String::new();+ buf.push_str(+ "You are compiling a Karpathy-style multi-page wiki update. Given the \+ session's observation log, produce a ConsolidatedBatch:\n\n",+ );+ buf.push_str("Session id: ");+ buf.push_str(&session_id.to_string());+ buf.push_str("\n\nObservations:\n");+ for o in observations {+ buf.push_str(&format!("- {} | {}\n", o.kind.as_str(), one_line(&o.title)));+ if !o.body.trim().is_empty() {+ buf.push_str(&format!(" body: {}\n", one_line(&o.body)));+ }+ }+ buf.push_str(+ "\nProduce up to 5 page updates. Use these path conventions:\n\+ - sessions/<session_id>.md (episodic, this run's narrative)\n\+ - concepts/<slug>.md (semantic, evergreen concept pages)\n\+ - decisions/<short>.md (semantic, ADR-style records)\n\+ - gotchas/<slug>.md (semantic, failure modes / surprises)\n\+ \nEach update must include a title, markdown body, tier, and tags.\n",+ );+ ChatRequest {+ system: Some(BATCH_SYSTEM_PROMPT.into()),+ messages: vec![ChatMessage {+ role: Role::User,+ content: buf,+ }],+ max_tokens: 4000,+ temperature: Some(0.2),+ }}+const BATCH_SYSTEM_PROMPT: &str = "You are the maintainer of a Karpathy-style LLM wiki \+for a software engineer. Your job is to compile *durable* knowledge -- not just \+restate the session log. Produce a ConsolidatedBatch with 1-5 page updates. Favour \+extracting concept / decision / gotcha pages alongside the session summary when the \+session yields reusable insight; otherwise return only the session page.";+fn build_request(session_id: SessionId,observations: &[Observation],diff --git a/crates/ai-memory-consolidate/src/lib.rs b/crates/ai-memory-consolidate/src/lib.rsindex c2b5280f..8f4d8fd2 100644--- a/crates/ai-memory-consolidate/src/lib.rs+++ b/crates/ai-memory-consolidate/src/lib.rs@@ -12,4 +12,6 @@ pub mod consolidator;pub mod types;pub use consolidator::{Consolidator, ConsolidatorError, ConsolidatorResult};-pub use types::{ConsolidatedPage, ConsolidationOutcome};+pub use types::{+ ConsolidatedBatch, ConsolidatedPage, ConsolidatedPageUpdate, ConsolidationOutcome,+};diff --git a/crates/ai-memory-consolidate/src/types.rs b/crates/ai-memory-consolidate/src/types.rsindex 727de8ce..fa0bf00b 100644--- a/crates/ai-memory-consolidate/src/types.rs+++ b/crates/ai-memory-consolidate/src/types.rs@@ -18,6 +18,33 @@ pub struct ConsolidatedPage {pub tags: Vec<String>,}+/// One update inside a multi-page consolidation batch (M7b).+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]+pub struct ConsolidatedPageUpdate {+ /// Relative wiki path (`concepts/foo.md`, `decisions/0001.md`, …).+ pub path: String,+ /// Tier (`semantic`, `episodic`, `procedural`, `working`).+ pub tier: String,+ /// New page title.+ pub title: String,+ /// New markdown body.+ pub body_markdown: String,+ /// Optional tags surfaced into frontmatter.+ #[serde(default)]+ pub tags: Vec<String>,+}++/// Batch produced by [`ConsolidatorMulti`].+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]+pub struct ConsolidatedBatch {+ /// Pages to create / update.+ pub updates: Vec<ConsolidatedPageUpdate>,+ /// Brief LLM-authored note about *why* this batch was produced.+ /// Surfaced in the auto-commit message.+ #[serde(default)]+ pub rationale: String,+}+/// Outcome of a single consolidation call.#[derive(Debug, Clone, Serialize)]pub struct ConsolidationOutcome {diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex b43057de..a488f8d7 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -138,6 +138,7 @@ async fn process(state: &HookState, env: HookEnvelope) -> anyhow::Result<()> {body: new_page.body.clone(),tier: new_page.tier,pinned: new_page.pinned,+ title: None,}).await?;state.writer.end_session(session_id, Some(page_id)).await?;diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 024a2538..68309d3e 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -75,6 +75,9 @@ struct ConsolidateArgs {/// If true, preview without writing. Default false.#[serde(default)]dry_run: Option<bool>,+ /// If true, M7b multi-page atomic fan-out. Default false (single page).+ #[serde(default)]+ multi_page: Option<bool>,}#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]@@ -179,13 +182,14 @@ impl AiMemoryServer {ok_json(&response)}- /// LLM-driven consolidation of a session into a refreshed- /// `sessions/<id>.md` page (M7a single-page variant).- #[tool(description = "LLM-driven consolidation: rewrite the \- sessions/<id>.md page for the given session_id using the \- observation log + the current heuristic body. Off by default; \- requires AI_MEMORY_LLM_PROVIDER / AI_MEMORY_LLM_MODEL set on \- the server. Pass dry_run=true to preview without writing.")]+ /// LLM-driven consolidation of a session.+ #[tool(description = "LLM-driven consolidation. Default mode \+ (single-page) rewrites sessions/<id>.md from the observation \+ log. multi_page=true fans out into a batch of concept/decision/\+ gotcha pages plus the session page, all written in one atomic \+ SQL transaction. Off by default; requires \+ AI_MEMORY_LLM_PROVIDER + AI_MEMORY_LLM_MODEL set on the server. \+ Pass dry_run=true to preview without writing.")]async fn memory_consolidate(&self,Parameters(args): Parameters<ConsolidateArgs>,@@ -198,11 +202,20 @@ impl AiMemoryServer {};let session_id = SessionId::from_str(&args.session_id).map_err(|e| McpError::internal_error(e.to_string(), None))?;- let outcome = consolidator- .consolidate_session(session_id, args.dry_run.unwrap_or(false))- .await- .map_err(|e| McpError::internal_error(e.to_string(), None))?;- ok_json(&outcome)+ let dry = args.dry_run.unwrap_or(false);+ if args.multi_page.unwrap_or(false) {+ let outcomes = consolidator+ .consolidate_session_multi(session_id, dry)+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;+ ok_json(&serde_json::json!({ "outcomes": outcomes }))+ } else {+ let outcome = consolidator+ .consolidate_session(session_id, dry)+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;+ ok_json(&outcome)+ }}/// Create a handoff snapshot for the next agent CLI.diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 26d70447..36fbb1ee 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -12,7 +12,7 @@ use jiff::Timestamp;use rusqlite::{Connection, OptionalExtension, params};use sha2::{Digest, Sha256};-use crate::error::StoreResult;+use crate::error::{StoreError, StoreResult};/// Upsert a page by path, superseding any existing latest version when the/// content (sha256 of body) has changed.@@ -187,6 +187,124 @@ pub fn get_or_create_project(Ok(id)}+/// Upsert a batch of pages inside one transaction. Either *all* pages+/// land (each becoming the new `is_latest=true` version) or none do.+///+/// This is the M7b atomic-fan-out path: the consolidator can hand a+/// list of {sessions, concepts, decisions} pages and trust that+/// either the whole batch supersedes or the wiki is unchanged.+pub fn upsert_pages_batch(conn: &mut Connection, pages: &[NewPage]) -> StoreResult<Vec<PageId>> {+ let now = Timestamp::now().as_microsecond();+ let tx = conn.transaction()?;+ let mut out = Vec::with_capacity(pages.len());+ for page in pages {+ let id = upsert_page_in_tx(&tx, page, now)?;+ out.push(id);+ }+ tx.commit()?;+ Ok(out)+}++fn upsert_page_in_tx(+ tx: &rusqlite::Transaction<'_>,+ page: &NewPage,+ now: i64,+) -> StoreResult<PageId> {+ let body_sha256: [u8; 32] = {+ let mut hasher = Sha256::new();+ hasher.update(page.body.as_bytes());+ hasher.finalize().into()+ };+ let frontmatter_str = serde_json::to_string(&page.frontmatter_json)?;+ let tier_str = page.tier.as_str();++ let existing: Option<(Vec<u8>, Vec<u8>)> = tx+ .query_row(+ "SELECT id, body_sha256 FROM pages \+ WHERE workspace_id = ?1 AND project_id = ?2 AND path = ?3 AND is_latest = 1",+ params![+ page.workspace_id.as_bytes(),+ page.project_id.as_bytes(),+ page.path.as_str(),+ ],+ |row| Ok((row.get(0)?, row.get(1)?)),+ )+ .optional()?;++ if let Some((existing_id, existing_sha)) = existing {+ if existing_sha == body_sha256 {+ tx.execute(+ "UPDATE pages SET updated_at = ?1 WHERE id = ?2",+ params![now, existing_id],+ )?;+ return PageId::from_slice(&existing_id).map_err(StoreError::from);+ }+ let new_id = PageId::new();+ tx.execute(+ "UPDATE pages SET is_latest = 0 WHERE id = ?1",+ params![existing_id],+ )?;+ tx.execute(+ "INSERT INTO pages \+ (id, workspace_id, project_id, path, title, tier, body, body_sha256, \+ frontmatter_json, is_latest, supersedes, pinned, created_at, updated_at) \+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, 1, ?10, ?11, ?12, ?12)",+ params![+ new_id.as_bytes(),+ page.workspace_id.as_bytes(),+ page.project_id.as_bytes(),+ page.path.as_str(),+ page.title,+ tier_str,+ page.body,+ body_sha256.as_slice(),+ frontmatter_str,+ existing_id,+ i64::from(page.pinned),+ now,+ ],+ )?;+ audit(+ tx,+ "supersede_page",+ Some(page.workspace_id.as_bytes()),+ Some(page.project_id.as_bytes()),+ Some(new_id.as_bytes()),+ now,+ )?;+ return Ok(new_id);+ }+ let new_id = PageId::new();+ tx.execute(+ "INSERT INTO pages \+ (id, workspace_id, project_id, path, title, tier, body, body_sha256, \+ frontmatter_json, is_latest, pinned, created_at, updated_at) \+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, 1, ?10, ?11, ?11)",+ params![+ new_id.as_bytes(),+ page.workspace_id.as_bytes(),+ page.project_id.as_bytes(),+ page.path.as_str(),+ page.title,+ tier_str,+ page.body,+ body_sha256.as_slice(),+ frontmatter_str,+ i64::from(page.pinned),+ now,+ ],+ )?;+ audit(+ tx,+ "create_page",+ Some(page.workspace_id.as_bytes()),+ Some(page.project_id.as_bytes()),+ Some(new_id.as_bytes()),+ now,+ )?;+ Ok(new_id)+}+/// Begin (or re-affirm) a session row keyed on the caller-supplied id./// Idempotent: a second call with the same id leaves the row untouched.pub fn begin_session(conn: &mut Connection, session: &NewSession) -> StoreResult<()> {diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex bb17836a..7f642e7e 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -36,6 +36,10 @@ pub(crate) enum WriteCmd {page: NewPage,reply: oneshot::Sender<StoreResult<PageId>>,},+ UpsertPageBatch {+ pages: Vec<NewPage>,+ reply: oneshot::Sender<StoreResult<Vec<PageId>>>,+ },BeginSession {session: NewSession,reply: oneshot::Sender<StoreResult<()>>,@@ -204,6 +208,18 @@ impl WriterHandle {rx.await.map_err(|_| StoreError::WriterClosed)?}+ /// Upsert a batch of pages atomically (one SQL transaction).+ ///+ /// # Errors+ /// Returns [`StoreError::WriterClosed`] if the actor has shut down,+ /// or propagates the SQL error from [`ops::upsert_pages_batch`].+ pub async fn upsert_pages_batch(&self, pages: Vec<NewPage>) -> StoreResult<Vec<PageId>> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::UpsertPageBatch { 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).///@@ -260,6 +276,10 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {let result = ops::upsert_page(&mut conn, &page);let _ = reply.send(result);}+ WriteCmd::UpsertPageBatch { pages, reply } => {+ let result = ops::upsert_pages_batch(&mut conn, &pages);+ let _ = reply.send(result);+ }WriteCmd::BeginSession { session, reply } => {let result = ops::begin_session(&mut conn, &session);let _ = reply.send(result);diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rsindex 272e5bfd..4a4f4767 100644--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@ -116,6 +116,74 @@ impl Wiki {Ok(id)}+ /// Atomically apply a batch of page writes. Either all pages land+ /// (one SQL transaction) and their files are renamed into place,+ /// or no DB row changes and tempfiles are dropped.+ ///+ /// # Errors+ /// Returns [`WikiError`] for any filesystem, parsing, or store+ /// error.+ pub async fn apply_batch(&self, requests: Vec<WritePageRequest>) -> WikiResult<Vec<PageId>> {+ if requests.is_empty() {+ return Ok(Vec::new());+ }+ // Pre-compute markdown + tempfile for each request.+ let mut staged: Vec<(+ WritePageRequest,+ tempfile::NamedTempFile,+ std::path::PathBuf,+ )> = Vec::with_capacity(requests.len());+ for req in requests {+ let title = derive_title(&req.frontmatter, &req.body, &req.path);+ let markdown = Markdown {+ frontmatter: req.frontmatter.clone(),+ body: req.body.clone(),+ };+ let emitted = emit(&markdown)?;+ let abs = self.abs_path(&req.path);+ let parent = abs.parent().ok_or_else(|| {+ ai_memory_wiki_error("page path has no parent (cannot stage tempfile)")+ })?;+ std::fs::create_dir_all(parent)?;+ let mut tmp = tempfile::Builder::new()+ .prefix(".ai-memory-tmp.")+ .tempfile_in(parent)?;+ use std::io::Write as _;+ tmp.write_all(emitted.as_bytes())?;+ tmp.as_file().sync_data()?;+ let req_with_title = WritePageRequest {+ title: Some(title),+ ..req+ };+ staged.push((req_with_title, tmp, abs));+ }++ // Build NewPage batch with the precomputed titles.+ let pages: Vec<ai_memory_core::NewPage> = staged+ .iter()+ .map(|(req, _, _)| ai_memory_core::NewPage {+ workspace_id: req.workspace_id,+ project_id: req.project_id,+ path: req.path.clone(),+ title: req.title.clone().unwrap_or_default(),+ body: req.body.clone(),+ tier: req.tier,+ frontmatter_json: req.frontmatter.clone(),+ pinned: req.pinned,+ })+ .collect();++ let ids = self.writer.upsert_pages_batch(pages).await?;++ // SQL succeeded; rename tempfiles into place.+ for (_, tmp, abs) in staged {+ let persisted = tmp.persist(&abs)?;+ persisted.sync_data()?;+ }++ Ok(ids)+ }+/// Write `body` (with optional `frontmatter`) atomically to/// `<wiki_root>/<path>` and upsert the matching page row in the store.///@@ -133,9 +201,12 @@ impl Wiki {body,tier,pinned,+ title: explicit_title,} = req;- let title = derive_title(&frontmatter, &body, &path);+ let title = explicit_title+ .clone()+ .unwrap_or_else(|| derive_title(&frontmatter, &body, &path));let markdown = Markdown {frontmatter: frontmatter.clone(),body: body.clone(),@@ -179,6 +250,14 @@ pub struct WritePageRequest {pub tier: Tier,/// `true` if the user has pinned this page.pub pinned: bool,+ /// Optional pre-derived title (used by `apply_batch` to share the+ /// title between the staged markdown file + the store row).+ #[doc(hidden)]+ pub title: Option<String>,+}++fn ai_memory_wiki_error(msg: &str) -> crate::WikiError {+ crate::WikiError::Io(std::io::Error::other(msg.to_string()))}#[cfg(test)]@@ -202,6 +281,7 @@ mod tests {body: body.into(),tier: Tier::Semantic,pinned: false,+ title: None,}}@@ -250,6 +330,47 @@ mod tests {assert!(hits[0].snippet.contains("compile"));}+ #[tokio::test]+ async fn apply_batch_persists_all_pages_in_one_transaction() {+ 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();+ let batch: Vec<_> = (0..5)+ .map(|i| WritePageRequest {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new(format!("batch/{i}.md")).unwrap(),+ frontmatter: serde_json::json!({"title": format!("Page {i}")}),+ body: format!("batch page {i} body line"),+ tier: Tier::Semantic,+ pinned: false,+ title: None,+ })+ .collect();+ let ids = wiki.apply_batch(batch).await.unwrap();+ assert_eq!(ids.len(), 5);+ for i in 0..5 {+ let path = tmp.path().join(format!("wiki/batch/{i}.md"));+ assert!(path.is_file(), "missing file {i}");+ let body = std::fs::read_to_string(&path).unwrap();+ assert!(body.contains(&format!("Page {i}")));+ }+ let counts = store.reader.status_counts().await.unwrap();+ assert_eq!(counts.pages_latest, 5);+ let hits = store.reader.search_pages("batch".into(), 10).await.unwrap();+ assert_eq!(hits.len(), 5);+ }+#[tokio::test]async fn rewriting_same_body_is_idempotent() {let tmp = TempDir::new().unwrap();