Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(mcp): classify caller-input errors and retry transient LLM failures
Caminharc9041710c7cf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5d5016c9..0674865b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0target a specific session, and `dry_run=true` for the cheap admissionpreflight. A project with no completed session now fails as`no completed session in <scope>` instead of a deserialization error.+- A consolidation LLM call that fails on a transient provider error (`429`, any+ `5xx`, a transport timeout or connect failure) is retried twice, two seconds+ apart, before the failure is reported — the same bounded policy `bootstrap`+ already applies to its chunks. Deterministic failures (auth, schema, a+ malformed-request `4xx`, unparseable or truncated output) are still reported+ on the first attempt, since retrying them only burns another call.### Fixed- `ai-memory serve` no longer hard-fails to take its single-instance lock on a@@ -61,6 +67,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0only `title`/`projectID` on `session.created`, so the marker never reached theserver and the opt-in was a silent no-op for OpenCode. Root sessions (no`parentID`) stay unmarked (#755).+- Scope-resolution failures over MCP now answer with `invalid params`+ (`-32602`) instead of an opaque internal error (`-32603`), the same split the+ web route applies with its 400/404: a malformed scope argument, or a+ workspace/project name that does not resolve, is caller input, while a+ missing writer handle or an underlying store failure stays internal. The+ messages are unchanged.+- `memory_consolidate` treats a blank `session_id` (`""` or whitespace) exactly+ like an omitted one — the resolved project's latest completed session — and a+ malformed id now fails as `invalid params`, the code `memory_auto_improve`+ already uses for the same argument.## [2.3.1] - 2026-09-17diff --git a/crates/ai-memory-consolidate/src/consolidator.rs b/crates/ai-memory-consolidate/src/consolidator.rsindex 21c648b8..61990e8d 100644--- a/crates/ai-memory-consolidate/src/consolidator.rs+++ b/crates/ai-memory-consolidate/src/consolidator.rs@@ -6,6 +6,7 @@//! kicks in automatically.use std::sync::Arc;+use std::time::Duration;use ai_memory_core::{AgentKind, Observation, PagePath, ProjectId, SessionId, Tier, WorkspaceId};use ai_memory_llm::{@@ -63,6 +64,50 @@ impl From<serde_json::Error> for ConsolidatorError {/// Result alias used by the consolidator.pub type ConsolidatorResult<T> = Result<T, ConsolidatorError>;+/// Maximum attempts (initial + retries) for one consolidation LLM call.+const CONSOLIDATION_LLM_MAX_ATTEMPTS: u32 = 3;+/// Fixed, short delay between consolidation retries. Deliberately not+/// tenacity-style escalating backoff — see the cognee #2840 lesson in+/// `ai-memory-llm`; the same policy `bootstrap.rs` applies to its chunks.+const CONSOLIDATION_LLM_RETRY_DELAY: Duration = Duration::from_secs(2);++/// Run one consolidation structured call with a short, bounded retry.+///+/// A provider answering `429`, any `5xx`, or dropping the connection used to+/// end the consolidation after a single attempt: over MCP the operator saw an+/// opaque internal error and had to re-issue the whole call by hand. A couple+/// of seconds apart, one more identical request rides out those windows.+/// Deterministic failures — auth, schema, a malformed-request `4xx`, an+/// unparseable or truncated body — are not retried: the retry would burn+/// another expensive call and hit the same wall.+async fn complete_structured_with_retry<T>(+ llm: &(dyn LlmProvider + 'static),+ request: ChatRequest,+ operation_id: ai_memory_llm::LlmOperationId,+ retry_delay: Duration,+) -> Result<T, LlmError>+where+ T: serde::de::DeserializeOwned + schemars::JsonSchema + Send + 'static,+{+ let mut attempt = 1;+ loop {+ match complete_structured_with_operation_id::<T>(llm, request.clone(), operation_id).await {+ Ok(value) => return Ok(value),+ Err(e) if attempt < CONSOLIDATION_LLM_MAX_ATTEMPTS && e.is_transient() => {+ warn!(+ attempt,+ max = CONSOLIDATION_LLM_MAX_ATTEMPTS,+ error = %e,+ "consolidation hit a transient LLM error; retrying shortly",+ );+ tokio::time::sleep(retry_delay).await;+ attempt += 1;+ }+ Err(e) => return Err(e),+ }+ }+}+/// Karpathy-style single-page consolidator. Holds handles to the/// store, wiki, and LLM provider so it can be reused across many/// `consolidate_session` calls.@@ -191,8 +236,13 @@ impl Consolidator {model = self.llm.model(),"consolidating session");- let page: ConsolidatedPage =- complete_structured_with_operation_id(&*self.llm, request, session_id.into()).await?;+ let page: ConsolidatedPage = complete_structured_with_retry(+ &*self.llm,+ request,+ session_id.into(),+ CONSOLIDATION_LLM_RETRY_DELAY,+ )+ .await?;let frontmatter = build_frontmatter(&page, session_id, agent_kind);let id = self@@ -490,8 +540,13 @@ impl Consolidator {provider = self.llm.name(),"consolidating session (multi-page)",);- let batch: ConsolidatedBatch =- complete_structured_with_operation_id(&*self.llm, request, session_id.into()).await?;+ let batch: ConsolidatedBatch = complete_structured_with_retry(+ &*self.llm,+ request,+ session_id.into(),+ CONSOLIDATION_LLM_RETRY_DELAY,+ )+ .await?;// `dry_run` is always false past the early return above, so every// update here is a real write.@@ -1421,6 +1476,7 @@ mod tests {use super::*;use ai_memory_core::{ObservationId, ObservationKind, ProjectId, SessionId, WorkspaceId};use jiff::Timestamp;+ use std::sync::atomic::{AtomicUsize, Ordering};/// Helper for prompt construction tests.fn obs_of_size(body_len: usize) -> Observation {@@ -2416,6 +2472,163 @@ mod tests {}}+ /// Which failure a [`FlakyLlm`] raises before it starts answering.+ #[derive(Clone, Copy)]+ enum ScriptedFailure {+ /// A provider `503`: transient, so the retry must absorb it.+ Transient,+ /// An expired credential: deterministic, so a retry cannot help.+ Deterministic,+ }++ /// Fails as scripted for its first `failures` structured calls, then+ /// answers `response`, counting every attempt.+ struct FlakyLlm {+ calls: AtomicUsize,+ failures: usize,+ failure: ScriptedFailure,+ response: serde_json::Value,+ }++ #[async_trait::async_trait]+ impl LlmProvider for FlakyLlm {+ fn name(&self) -> &'static str {+ "flaky"+ }+ fn model(&self) -> &str {+ "flaky"+ }+ async fn complete(+ &self,+ _request: ChatRequest,+ ) -> ai_memory_llm::LlmResult<ai_memory_llm::ChatResponse> {+ unreachable!("consolidation only uses structured completion");+ }+ async fn complete_structured_raw(+ &self,+ _request: ChatRequest,+ _schema: serde_json::Value,+ ) -> ai_memory_llm::LlmResult<serde_json::Value> {+ let n = self.calls.fetch_add(1, Ordering::SeqCst);+ if n < self.failures {+ return Err(match self.failure {+ ScriptedFailure::Transient => LlmError::Provider {+ status: 503,+ body: "This model is currently experiencing high demand.".into(),+ },+ ScriptedFailure::Deterministic => LlmError::Auth("expired".into()),+ });+ }+ Ok(self.response.clone())+ }+ }++ fn scripted_page() -> serde_json::Value {+ serde_json::json!({+ "title": "Queue decision",+ "body_markdown": "The queue is bounded.",+ "tags": [],+ })+ }++ /// A briefly overloaded provider must not end the consolidation: the+ /// retry absorbs it and the caller still gets the page.+ #[tokio::test]+ async fn a_transient_provider_failure_is_retried() {+ let llm = FlakyLlm {+ calls: AtomicUsize::new(0),+ failures: 2, // fails twice, answers on the 3rd (= the budget)+ failure: ScriptedFailure::Transient,+ response: scripted_page(),+ };++ let page: ConsolidatedPage = complete_structured_with_retry(+ &llm,+ ChatRequest::user_prompt("consolidate"),+ ai_memory_llm::LlmOperationId::default(),+ Duration::ZERO,+ )+ .await+ .expect("a transient failure that clears within the budget must succeed");++ assert_eq!(page.title, "Queue decision");+ assert_eq!(+ llm.calls.load(Ordering::SeqCst),+ 3,+ "should have retried twice"+ );+ }++ /// An outage that outlasts the budget gives up instead of retrying+ /// forever, and reports the provider error it actually saw.+ #[tokio::test]+ async fn a_transient_provider_failure_gives_up_after_the_budget() {+ let llm = FlakyLlm {+ calls: AtomicUsize::new(0),+ failures: usize::MAX, // never clears+ failure: ScriptedFailure::Transient,+ response: scripted_page(),+ };++ let err = complete_structured_with_retry::<ConsolidatedPage>(+ &llm,+ ChatRequest::user_prompt("consolidate"),+ ai_memory_llm::LlmOperationId::default(),+ Duration::ZERO,+ )+ .await+ .expect_err("a persistently transient failure must eventually give up");++ assert!(err.is_transient());+ assert_eq!(+ llm.calls.load(Ordering::SeqCst),+ CONSOLIDATION_LLM_MAX_ATTEMPTS as usize,+ "must stop at the attempt budget, not retry forever"+ );+ }++ /// A deterministic failure is not retried, and a consolidation whose+ /// completion never arrives writes no page.+ #[tokio::test]+ async fn a_deterministic_provider_failure_is_not_retried_and_writes_no_page() {+ let tmp = tempfile::tempdir().unwrap();+ let (store, wiki, session, ws, proj) = batch_fixture(tmp.path()).await;+ let llm = Arc::new(FlakyLlm {+ calls: AtomicUsize::new(0),+ failures: usize::MAX,+ failure: ScriptedFailure::Deterministic,+ response: scripted_page(),+ });++ Consolidator::new(+ store.reader.clone(),+ store.writer.clone(),+ wiki.clone(),+ llm.clone(),+ ws,+ proj,+ )+ .consolidate_session(+ session,+ false,+ ai_memory_core::ActorContext::anonymous(),+ None,+ None,+ )+ .await+ .expect_err("an auth error must fail the consolidation");++ assert_eq!(+ llm.calls.load(Ordering::SeqCst),+ 1,+ "a deterministic error must fail on the first call, no retries"+ );+ assert!(+ page_missing(&wiki, ws, proj, &format!("sessions/{session}.md")),+ "a failed consolidation must not write a page"+ );+ }+async fn write_slot(wiki: &Wiki, ws: WorkspaceId, proj: ProjectId, path: &str, body: &str) {wiki.write_page(WritePageRequest {workspace_id: ws,diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 859b928a..ec5c5457 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -1416,8 +1416,21 @@ impl AiMemoryServer {.with_active_project(&self.active_project)}+ /// Map a scope-resolution failure to the error the caller can act on.+ ///+ /// A malformed scope argument, or a name that does not resolve to an+ /// existing workspace/project, is caller input rather than a server fault:+ /// it maps to `invalid_params` (`-32602`), the same split the web route+ /// applies with its 400/404 (`ai-memory-web/src/routes/api.rs::+ /// scope_error_response`). Only the remaining classes — a missing writer+ /// handle for a create-on-write resolution, or an underlying store failure+ /// — stay `internal_error` (`-32603`).fn scope_error(err: ai_memory_store::ScopeResolutionError) -> McpError {- McpError::internal_error(err.to_string(), None)+ if err.is_bad_request() || err.is_not_found() {+ McpError::invalid_params(err.to_string(), None)+ } else {+ McpError::internal_error(err.to_string(), None)+ }}/// Construct a server backed by the given reader/writer + 3-tuple@@ -2748,9 +2761,19 @@ impl AiMemoryServer {None,));};- let session_id = match args.session_id.as_deref() {+ // A blank id (`""` or whitespace) means the same thing as an omitted+ // one — the resolved project's latest completed session — exactly as+ // `memory_read_session_observations` already reads it. Anything else+ // that is not a UUID is caller input, so it fails as `invalid_params`,+ // the code `memory_auto_improve` uses for the same argument.+ let session_id = match args+ .session_id+ .as_deref()+ .map(str::trim)+ .filter(|raw| !raw.is_empty())+ {Some(raw) => SessionId::from_str(raw)- .map_err(|e| McpError::internal_error(e.to_string(), None))?,+ .map_err(|e| McpError::invalid_params(e.to_string(), None))?,_ => {let aps_actor = Self::actor_key_from_parts(Some(&parts));let (ws, proj) = self@@ -9579,6 +9602,59 @@ mod tests {assert!(text.contains("\"pages_latest\": 1"));}+ /// A scope that does not resolve is caller input, not a server fault: the+ /// tool must answer with `invalid params` (`-32602`) instead of an opaque+ /// internal error (`-32603`), and keep the message callers already match on.+ #[tokio::test]+ async fn memory_status_reports_an_unknown_project_as_invalid_params() {+ let (_tmp, _store, server, _ws, _pj) = setup_server().await;+ let err = server+ .memory_status(+ Parameters(StatusArgs {+ project: Some("caminhar".into()),+ workspace: Some("default".into()),+ }),+ OptionalParts(test_parts_default()),+ )+ .await+ .expect_err("an unknown project must be rejected");+ assert_eq!(err.code, rmcp::model::ErrorCode::INVALID_PARAMS);+ assert_eq!(+ err.message, "project 'caminhar' not found in workspace 'default'",+ "the scope message must not change"+ );+ }++ /// The classification is by error class, not by tool: a malformed scope+ /// argument is `invalid params` (the not-found half is covered by the tool+ /// test above), while a missing writer handle or an underlying store+ /// failure stay internal errors — the caller cannot fix those by changing+ /// the request.+ #[test]+ fn scope_error_keeps_internal_failures_internal() {+ use ai_memory_store::ScopeResolutionError;++ for err in [+ ScopeResolutionError::WorkspaceProjectPairRequired,+ ScopeResolutionError::ScopeProjectEmpty,+ ] {+ assert_eq!(+ AiMemoryServer::scope_error(err).code,+ rmcp::model::ErrorCode::INVALID_PARAMS,+ );+ }++ for err in [+ ScopeResolutionError::WriterRequired,+ ScopeResolutionError::Store("disk on fire".into()),+ ] {+ assert_eq!(+ AiMemoryServer::scope_error(err).code,+ rmcp::model::ErrorCode::INTERNAL_ERROR,+ );+ }+ }+#[tokio::test]async fn memory_briefing_returns_structured_snapshot() {let (_tmp, _store, server, _ws, _pj) = setup_server().await;@@ -11887,6 +11963,99 @@ mod tests {);}+ /// A blank `session_id` (`""`, or whitespace only) is the same request as+ /// an omitted one: it must resolve the latest completed session of the+ /// resolved project instead of failing as a malformed UUID.+ #[tokio::test]+ async fn memory_consolidate_treats_a_blank_session_id_as_omitted() {+ let (tmp, store, _server, ws, proj) = setup_server().await;+ let wiki = Wiki::new(tmp.path(), store.writer.clone())+ .unwrap()+ .with_store_reader(store.reader.clone());+ let llm: Arc<dyn LlmProvider> = Arc::new(PreflightMustNotCallLlm);+ let consolidator = Arc::new(Consolidator::new(+ store.reader.clone(),+ store.writer.clone(),+ wiki.clone(),+ llm.clone(),+ ws,+ proj,+ ));+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)+ .with_consolidator_arc(wiki, llm, consolidator);++ let completed = seed_session_observations(+ &store,+ ws,+ proj,+ true,+ &[(ObservationKind::UserPrompt, "done", "completed work")],+ )+ .await;++ for session_id in [None, Some(String::new()), Some(" ".to_owned())] {+ let outcome = call_tool_json(+ server+ .memory_consolidate(+ Parameters(ConsolidateArgs {+ session_id,+ dry_run: Some(true),+ multi_page: Some(false),+ instructions: None,+ }),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap(),+ );+ assert_eq!(+ outcome["path"],+ format!("sessions/{completed}.md"),+ "a blank session_id must behave exactly like an omitted one",+ );+ }+ }++ /// A malformed id is caller input rather than a server fault: it must fail+ /// as `invalid params`, the code the sibling tools already answer with for+ /// the same argument.+ #[tokio::test]+ async fn memory_consolidate_rejects_a_malformed_session_id_as_invalid_params() {+ let (tmp, store, _server, ws, proj) = setup_server().await;+ let wiki = Wiki::new(tmp.path(), store.writer.clone())+ .unwrap()+ .with_store_reader(store.reader.clone());+ let llm: Arc<dyn LlmProvider> = Arc::new(PreflightMustNotCallLlm);+ let consolidator = Arc::new(Consolidator::new(+ store.reader.clone(),+ store.writer.clone(),+ wiki.clone(),+ llm.clone(),+ ws,+ proj,+ ));+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)+ .with_consolidator_arc(wiki, llm, consolidator);++ let err = server+ .memory_consolidate(+ Parameters(ConsolidateArgs {+ session_id: Some("not-a-uuid".into()),+ dry_run: Some(true),+ multi_page: Some(false),+ instructions: None,+ }),+ OptionalParts(test_parts_default()),+ )+ .await+ .expect_err("a malformed session id must be rejected");+ assert_eq!(err.code, rmcp::model::ErrorCode::INVALID_PARAMS);+ assert!(+ err.to_string().contains("invalid uuid"),+ "the malformed-id message must stay as callers already read it; got {err}"+ );+ }+#[tokio::test]async fn memory_auto_improve_removed_dry_run_arg_fails_closed() {let (_tmp, _store, server, _ws, _pj) = setup_server().await;diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex f3cda110..0ebaf65f 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -391,7 +391,7 @@ content-free (identity, provenance and age, never the summary body). Automaticexpiry deliberately spares manual and sibling-directory handoffs, so along-lived entry appearing there is that policy working rather than a fault.-| `memory_consolidate` | destructive | LLM-driven page rewrite. `multi_page=true` for atomic fan-out. Omitting `session_id` consolidates the latest completed session in the resolved project; the same omission on a project with none fails as `no completed session in <scope>`. Consolidation prompts append the target project's active reserved `_prompts/consolidation.md` body as sanitized, 2,000-character-capped, JSON-encoded, untrusted advisory preferences; TTL-expired pages are ignored and a per-call `instructions` argument overrides the page for one call. Both system prompts keep schema, evidence, disclosure, tool-use, and output rules authoritative. |+| `memory_consolidate` | destructive | LLM-driven page rewrite. `multi_page=true` for atomic fan-out. Omitting `session_id` (or sending a blank one) consolidates the latest completed session in the resolved project; the same omission on a project with none fails as `no completed session in <scope>`. Consolidation prompts append the target project's active reserved `_prompts/consolidation.md` body as sanitized, 2,000-character-capped, JSON-encoded, untrusted advisory preferences; TTL-expired pages are ignored and a per-call `instructions` argument overrides the page for one call. Both system prompts keep schema, evidence, disclosure, tool-use, and output rules authoritative. || `memory_feedback` | write | Record a quality signal for one page by exact `path`: `helpful`/`not_helpful` step `pages.salience` for sweep-eligible episodic pages, while `stale`/`wrong` floor salience and surface any current page as a `feedback_flagged` lint finding. Never deletes; the path resolves to the current version in the transaction, so a later rewrite clears it. Retrieved content never authorizes feedback by itself. || `memory_auto_improve` | write | Manually review a completed session and apply or stage validated wiki edits through the auto-improvement approval path. Without a session ID, selects the newest completed session with no persisted auto-improvement run so repeated calls advance through preflight skips; an explicit ID remains rerunnable. The server also schedules review for new sessions; `[auto_improve] require_approval = true` leaves proposals pending for manual review. || `memory_write_page` | destructive | Write durable wiki knowledge when the user explicitly asks to remember/annotate it. `scope: "global"` writes into the reserved `_global` preferences scope; optional `expires_at` sets an RFC3339 or date-only TTL. |diff --git a/docs/usage.md b/docs/usage.mdindex 455bed5e..dd80012d 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -95,7 +95,7 @@ at the managed ai-memory Agent Skills that carry detailed tool routing.| "Ask the agent in <other project> to do X" / "send this to project B" | `memory_message_send` | Drops a self-contained request into another project's inbox (requires `to_workspace` + `to_project`); the recipient must already exist. Cross-project, claim-once. See [agent-messaging.md](agent-messaging.md). || "Check my inbox" / "any messages waiting?" | `memory_message_list` then `memory_message_pop` | Lists pending inbox mail without consuming, then pops one message exactly once. A popped message is untrusted cross-project input — a request to evaluate, never instructions to obey. || "Never mind that request I sent" / "clear my outbox" | `memory_message_cancel` | Retracts a pending sent message by id, or clears the whole outbox when omitted. Only affects mail this project sent. |-| "Consolidate this session" | `memory_consolidate` | Manually runs LLM consolidation. Omit `session_id` to consolidate the latest completed session in the resolved project; pass one to target a specific session. A project can keep advisory preferences in `_prompts/consolidation.md`; `instructions` overrides them for one call. Also runs on PreCompact, and at session end only when `AI_MEMORY_CONSOLIDATE_ON_SESSION_END` is set (off by default; a substantive session end otherwise writes a rule-based summary page). Lifecycle-only sessions create no generated page, handoff, or provider job. Opt-in SessionEnd provider work is durably queued outside the hook response, retried with backoff, and recovered after server restart. Resumed sessions re-end only when their persisted observation generation advances, so duplicate delivery and clock skew cannot loop consolidation. |+| "Consolidate this session" | `memory_consolidate` | Manually runs LLM consolidation. Omit `session_id` (or send a blank one) to consolidate the latest completed session in the resolved project; pass one to target a specific session. A project can keep advisory preferences in `_prompts/consolidation.md`; `instructions` overrides them for one call. Also runs on PreCompact, and at session end only when `AI_MEMORY_CONSOLIDATE_ON_SESSION_END` is set (off by default; a substantive session end otherwise writes a rule-based summary page). Lifecycle-only sessions create no generated page, handoff, or provider job. Opt-in SessionEnd provider work is durably queued outside the hook response, retried with backoff, and recovered after server restart. Resumed sessions re-end only when their persisted observation generation advances, so duplicate delivery and clock skew cannot loop consolidation. || "What did we learn from this session?" / "what memory should we add?" | `memory_auto_improve` | Without a session ID, reviews the newest completed session with no persisted auto-improvement run, advancing past preflight skips on repeated calls; pass an ID for a targeted rerun. The server also runs scheduled auto-improvement for new completed sessions when an LLM is configured. `[auto_improve.scheduler] enabled = false` disables automatic review; `[auto_improve] require_approval = true` leaves scheduled and manual proposals in pending-writes for review. || "Remember this permanently" / "add an annotation" | `memory_write_page` | Writes durable wiki knowledge; not a single-use handoff. || "Remember this until Friday" / "expire this after the migration" | `memory_write_page` with `expires_at` | Writes a time-bounded page. Use RFC3339 or `YYYY-MM-DD` (end of day UTC); normal retrieval hides it after expiry and the next forget sweep deletes it. TTL outranks `pinned`. |