Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
consolidator: use session's project_id, not server's startup default
AkitaOnRailsfab51ce80a33
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8a8a9474..6cd6fc7d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -94,6 +94,27 @@ blocking issue:**12. No global singletons / `lazy_static` configs.13. Zero-LLM default path. LLM features opt-in via env.14. Tracing subscribers explicitly filter their own module.+15. **Every command + storage operation is namespaced by the current+ sub-dir as the project id.** The router derives the project from+ `basename(cwd)`; bootstrap / lint / embed / forget-sweep /+ purge-project / rename-project / consolidate ALL resolve through+ the same helper. There is no generic `scratch` fallback in the+ happy path — `scratch` exists only as a defensive default for+ hook events that arrive without a `cwd` (e.g. early startup or+ misconfigured agents). New commands/handlers that bake in a+ `workspace_id`/`project_id` at construction time MUST look up+ the session's actual project (via+ `ReaderPool::session_project_ids` or equivalent) before writing.+16. **The CLI is always a thin HTTP client to the running MCP /+ admin server.** The server is the ground truth and the sole+ writer of wiki + SQLite. CLI commands NEVER call `Store::open`,+ `Wiki::new`, `build_provider`, or `build_embedder`. State+ mutations go through `/admin/*` HTTP routes; reads go through+ MCP tools or `/admin/*` GETs. The two exceptions are+ `init` / `serve` / `generate-auth-token` / `install-*` /+ `setup-agent` — local-only setup commands that don't touch+ server state. Use the shared `crate::http_client::{ServerEndpoint,+ get_json, post_json}` plumbing for every new client subcommand.## Mistakes documented in the research — do NOT repeatdiff --git a/crates/ai-memory-consolidate/src/consolidator.rs b/crates/ai-memory-consolidate/src/consolidator.rsindex 2d53a78e..c24e95ac 100644--- a/crates/ai-memory-consolidate/src/consolidator.rs+++ b/crates/ai-memory-consolidate/src/consolidator.rs@@ -110,6 +110,17 @@ impl Consolidator {return Err(ConsolidatorError::EmptySession(session_id));}+ // Look up the session's actual (workspace, project) IDs — the+ // hook router stamped them per-cwd at session start, so this+ // is the correct target for the resulting wiki page. The+ // server's startup IDs (self.workspace_id / self.project_id)+ // are the fallback for sessions that pre-date per-cwd routing.+ let (ws, proj) = self+ .reader+ .session_project_ids(session_id)+ .await?+ .unwrap_or((self.workspace_id, self.project_id));+let path = PagePath::new(format!("sessions/{session_id}.md"))?;let current_body = self.wiki@@ -140,8 +151,8 @@ impl Consolidator {let id = self.wiki.write_page(WritePageRequest {- workspace_id: self.workspace_id,- project_id: self.project_id,+ workspace_id: ws,+ project_id: proj,path: path.clone(),frontmatter,body: page.body_markdown.clone(),@@ -209,6 +220,13 @@ impl Consolidator {if observations.is_empty() {return Err(ConsolidatorError::EmptySession(session_id));}+ // Resolve the session's actual (workspace, project) IDs from+ // its row — see `consolidate_session` for the rationale.+ let (ws, proj) = self+ .reader+ .session_project_ids(session_id)+ .await?+ .unwrap_or((self.workspace_id, self.project_id));let request = build_batch_request(session_id, &observations);debug!(session = %session_id,@@ -261,8 +279,8 @@ impl Consolidator {}fm.insert("consolidated".into(), serde_json::Value::Bool(true));requests.push(WritePageRequest {- workspace_id: self.workspace_id,- project_id: self.project_id,+ workspace_id: ws,+ project_id: proj,path: path.clone(),frontmatter: serde_json::Value::Object(fm),body: upd.body_markdown.clone(),diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 8b3c269d..e64cc731 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -328,6 +328,39 @@ impl ReaderPool {.await}+ /// Look up the `(workspace_id, project_id)` a session belongs to.+ /// Returns `None` when no such session row exists.+ ///+ /// Used by the consolidator + lint pass to write pages into the+ /// SESSION'S project, not the server's startup defaults — every+ /// session row carries the project_id the hook router resolved+ /// from its per-cwd basename heuristic, which is the correct+ /// target for any wiki page derived from that session.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn session_project_ids(+ &self,+ session_id: SessionId,+ ) -> StoreResult<Option<(WorkspaceId, ProjectId)>> {+ self.with_conn(move |conn| {+ let mut stmt =+ conn.prepare("SELECT workspace_id, project_id FROM sessions WHERE id = ?1")?;+ let mut rows = stmt.query(params![session_id.as_bytes()])?;+ let Some(row) = rows.next()? else {+ return Ok(None);+ };+ let ws_bytes: Vec<u8> = row.get(0)?;+ let proj_bytes: Vec<u8> = row.get(1)?;+ let ws = WorkspaceId::from_slice(&ws_bytes)+ .map_err(|_| rusqlite::Error::IntegralValueOutOfRange(0, 0))?;+ let proj = ProjectId::from_slice(&proj_bytes)+ .map_err(|_| rusqlite::Error::IntegralValueOutOfRange(1, 0))?;+ Ok(Some((ws, proj)))+ })+ .await+ }+/// Load every `is_latest=1` page's embedding for the project, but/// only when the stored `(provider, model, dim)` matches the/// caller's expectation. Mismatched rows are skipped (the