Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(mcp): let memory_consolidate default to the latest completed session

Caminhar7d667aa06a81
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 29f2e67d..5d5016c9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Changed
+- `memory_consolidate` accepts an omitted `session_id`. Omitting the field (or
+ sending `null`) no longer fails deserialization with `missing field
+ session_id`; the tool consolidates the latest completed session in the
+ resolved project — the same default `memory_auto_improve` and
+ `memory_read_session_observations` already use. Pass an explicit UUID to
+ target a specific session, and `dry_run=true` for the cheap admission
+ preflight. A project with no completed session now fails as
+ `no completed session in <scope>` instead of a deserialization error.
+
### Fixed
- `ai-memory serve` no longer hard-fails to take its single-instance lock on a
transient error under load. Acquiring the serve lock now retries `open` and
diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-learning-maintenance/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-learning-maintenance/SKILL.md
index a9ba59db..b1f02a26 100644
--- a/crates/ai-memory-core/src/routing_skills/ai-memory-learning-maintenance/SKILL.md
+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-learning-maintenance/SKILL.md
@@ -10,7 +10,7 @@ Use this skill for compilation, learning review, wiki linting, and cleanup of ai
## Tools in this cluster
-- `memory_consolidate` compiles raw session observations into topical wiki pages on demand. The target project's `_prompts/consolidation.md` page supplies standing advisory preferences; `instructions` overrides it for one call.
+- `memory_consolidate` compiles raw session observations into topical wiki pages on demand. Omit `session_id` to consolidate the latest completed session in the resolved project. The target project's `_prompts/consolidation.md` page supplies standing advisory preferences; `instructions` overrides it for one call.
- `memory_auto_improve` reviews a completed session for durable lessons and project-rule proposals.
- `memory_lint` audits the wiki for contradictions, stale guidance, and candidate rule placement.
- `memory_forget_sweep` prunes cold pages and deletes TTL-expired pages when the user asks for memory cleanup.
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 858c9f03..859b928a 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -940,8 +940,11 @@ struct LintArgs {
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct ConsolidateArgs {
- /// UUID of the session to consolidate.
- session_id: String,
+ /// UUID of the session to consolidate. Omit to consolidate the latest
+ /// completed session in the resolved project; pass it to target a
+ /// specific session.
+ #[serde(default)]
+ session_id: Option<String>,
/// If true, preview without writing. Default false.
#[serde(default)]
dry_run: Option<bool>,
@@ -2716,7 +2719,9 @@ impl AiMemoryServer {
(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 \
+ SQL transaction. Omit `session_id` to consolidate the latest \
+ completed session in the resolved project; pass it to target a \
+ specific session. Off by default; requires AI_MEMORY_LLM_PROVIDER \
plus that provider's credentials. AI_MEMORY_LLM_MODEL is optional \
for providers with a built-in default. \
The target project's `_prompts/consolidation.md` page supplies \
@@ -2743,8 +2748,33 @@ impl AiMemoryServer {
None,
));
};
- let session_id = SessionId::from_str(&args.session_id)
- .map_err(|e| McpError::internal_error(e.to_string(), None))?;
+ let session_id = match args.session_id.as_deref() {
+ Some(raw) => SessionId::from_str(raw)
+ .map_err(|e| McpError::internal_error(e.to_string(), None))?,
+ _ => {
+ let aps_actor = Self::actor_key_from_parts(Some(&parts));
+ let (ws, proj) = self
+ .effective_ids_for_read_args_with_actor(None, None, &aps_actor)
+ .await?;
+ let latest = self
+ .reader
+ .latest_completed_session_for_project(ws, proj)
+ .await
+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;
+ match latest {
+ Some(session_id) => session_id,
+ None => {
+ let scope = self.scope_label(ws, proj).await;
+ return Err(McpError::invalid_params(
+ format!(
+ "no completed session in {scope}; pass session_id to consolidate a specific session"
+ ),
+ None,
+ ));
+ }
+ }
+ }
+ };
let dry = args.dry_run.unwrap_or(false);
// Carry the request's authenticated identity into the write so the
// consolidated page is attributed to the real operator and any
@@ -11733,7 +11763,7 @@ mod tests {
let err = server
.memory_consolidate(
Parameters(ConsolidateArgs {
- session_id: "00000000-0000-0000-0000-000000000000".into(),
+ session_id: Some("00000000-0000-0000-0000-000000000000".into()),
dry_run: Some(true),
multi_page: Some(false),
instructions: None,
@@ -11757,6 +11787,106 @@ mod tests {
);
}
+ /// An omitted `session_id` must not fail at the tool boundary: the call
+ /// reaches the consolidator and resolves the latest COMPLETED session of
+ /// the resolved project, skipping an open one — the same default the
+ /// read-only tools use.
+ #[tokio::test]
+ async fn memory_consolidate_defaults_to_latest_completed_session() {
+ 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;
+ let _open = seed_session_observations(
+ &store,
+ ws,
+ proj,
+ false,
+ &[(ObservationKind::UserPrompt, "live", "still running")],
+ )
+ .await;
+
+ let outcome = call_tool_json(
+ server
+ .memory_consolidate(
+ Parameters(ConsolidateArgs {
+ session_id: None,
+ dry_run: Some(true),
+ multi_page: Some(false),
+ instructions: None,
+ }),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap(),
+ );
+ assert_eq!(
+ outcome["path"],
+ format!("sessions/{completed}.md"),
+ "the omitted session_id must resolve the latest completed session",
+ );
+ }
+
+ /// A project with no completed session has no implicit default: the
+ /// omission must fail with the same actionable error the read tools use.
+ #[tokio::test]
+ async fn memory_consolidate_without_completed_session_errors_cleanly() {
+ 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: None,
+ dry_run: Some(true),
+ multi_page: Some(false),
+ instructions: None,
+ }),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .expect_err("an empty project has no completed session");
+ assert_eq!(err.code, rmcp::model::ErrorCode::INVALID_PARAMS);
+ assert!(
+ err.to_string()
+ .contains("no completed session in default/scratch"),
+ "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.md
index c7b43e16..f3cda110 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -391,7 +391,7 @@ content-free (identity, provenance and age, never the summary body). Automatic
expiry deliberately spares manual and sibling-directory handoffs, so a
long-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. 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` 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.md
index 7dbdb73d..455bed5e 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. 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` 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`. |