Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): keep the agent's session page through a compaction checkpoint (#1138)
Felipe Neves Ricardo892a9cfa071c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9544a613..ec33b33b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -51,7 +51,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0never applied, since it read the page after that overwrite and compared anobservation count that the agent's own tool call, the Stop and theSessionEnd always advance. A session page carrying `consolidated_by: agent`- is now kept by both, and the write no longer stamps+ is now kept by both, and by the PreCompact and PostCompaction checkpoints,+ which rewrote it the same way. The write no longer stamps`observation_generation`. (#1138)- Fixed the hook spool charging a spooled event's retry budget while theserver was unreachable: an endpoint-level delivery failure (connectiondiff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex d72ffcc4..be34d29a 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -4469,6 +4469,16 @@ async fn consolidate_or_synth(} else {None};+ // A page the agent wrote itself is kept through a compaction as it is at+ // SessionEnd: the checkpoint would replace it with the server's model or+ // the rule-based summary.+ let path = PagePath::new(format!("sessions/{session_id}.md"))?;+ if agent_session_page_id(state, workspace_id, project_id, session_id, &path)+ .await?+ .is_some()+ {+ return Ok(CheckpointOutcome { fallback_reason });+ }let fallback_from_llm = state.consolidator.is_some();if let Some(c) = state.consolidator.as_ref() {let result = c@@ -11375,8 +11385,8 @@ mod tests {/// Deliver `session-start` and `user-prompt-submit`, write the session/// page with `frontmatter` as `memory_write_page` would, then deliver a/// later prompt (the agent's write is never the session's last event) and- /// `session-end`. Returns the latest session page body.- async fn session_end_over_written_page(frontmatter: serde_json::Value) -> String {+ /// `closing`. Returns the latest session page body.+ async fn written_page_after(frontmatter: serde_json::Value, closing: &'static str) -> String {let tmp = TempDir::new().unwrap();let state = make_state(&tmp).await;let sid = "22222222-2222-2222-2222-222222222222";@@ -11414,7 +11424,7 @@ mod tests {}).await.unwrap();- for event in ["user-prompt-submit", "session-end"] {+ for event in ["user-prompt-submit", closing] {process(&state, deliver(event), None, Vec::new()).await.unwrap();@@ -11433,10 +11443,10 @@ mod tests {/// with the rule-based summary.#[tokio::test]async fn session_end_keeps_a_session_page_the_agent_wrote() {- let body = session_end_over_written_page(serde_json::json!({- "consolidated": true,- "consolidated_by": "agent",- }))+ let body = written_page_after(+ serde_json::json!({ "consolidated": true, "consolidated_by": "agent" }),+ "session-end",+ ).await;assert!(body.contains("Compiled by the agent's own model"), "{body}");}@@ -11445,16 +11455,37 @@ mod tests {/// the rule-based summary, as before.#[tokio::test]async fn session_end_replaces_a_session_page_no_agent_wrote() {- let body = session_end_over_written_page(serde_json::json!({- "consolidated": true,- }))- .await;+ let body =+ written_page_after(serde_json::json!({ "consolidated": true }), "session-end").await;assert!(!body.contains("Compiled by the agent's own model"),"{body}");}+ /// A compaction checkpoint keeps the agent's page as SessionEnd does,+ /// and still replaces a page no agent wrote (control).+ #[tokio::test]+ async fn compaction_checkpoint_keeps_a_session_page_the_agent_wrote() {+ for closing in ["pre-compact", "post-compaction"] {+ let kept = written_page_after(+ serde_json::json!({ "consolidated": true, "consolidated_by": "agent" }),+ closing,+ )+ .await;+ assert!(+ kept.contains("Compiled by the agent's own model"),+ "{closing}: {kept}"+ );+ let replaced =+ written_page_after(serde_json::json!({ "consolidated": true }), closing).await;+ assert!(+ !replaced.contains("Compiled by the agent's own model"),+ "{closing}: {replaced}"+ );+ }+ }+/// A substantive SessionEnd must write the heuristic `sessions/<id>.md`/// page even with `consolidate_on_session_end` enabled but no LLM provider.#[tokio::test]diff --git a/docs/usage.md b/docs/usage.mdindex 0fa4090f..7f052a35 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -149,7 +149,7 @@ at the managed ai-memory Agent Skills that carry detailed tool routing.| "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` (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. |-| "Write this session's page yourself" | `memory_read_session_observations`, then `memory_write_page` with `session_id` and `path: sessions/<id>.md` | The agent compiles the session page with its own model instead of the server's provider. The session must belong to the project the page is written to; the page records it as evidence, gets the same session-page frontmatter (plus `consolidated_by: agent`) and duplicate-title suffix, and the session's queued SessionEnd job is marked completed. The write uses the `write_page` admission op, so a webhook that filters on `consolidate` does not see it. A pinned page is never overwritten this way. SessionEnd keeps the page: neither the rule-based summary nor the opt-in SessionEnd worker replaces it, even when the session went on after the write. |+| "Write this session's page yourself" | `memory_read_session_observations`, then `memory_write_page` with `session_id` and `path: sessions/<id>.md` | The agent compiles the session page with its own model instead of the server's provider. The session must belong to the project the page is written to; the page records it as evidence, gets the same session-page frontmatter (plus `consolidated_by: agent`) and duplicate-title suffix, and the session's queued SessionEnd job is marked completed. The write uses the `write_page` admission op, so a webhook that filters on `consolidate` does not see it. A pinned page is never overwritten this way. SessionEnd keeps the page: neither the rule-based summary nor the opt-in SessionEnd worker replaces it, even when the session went on after the write, and a PreCompact or PostCompaction checkpoint leaves it alone too. || "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`. |