Skip to content

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

Rust

fix(consolidate): keep the agent's session page at SessionEnd (#1138)

Felipe Neves Ricardo12b1acd6c4b3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fc647f55..9544a613 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -45,6 +45,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
scrubs with the caller's sanitizer before its own 16 KiB bound as
defense in depth. The stored shapes and byte limits are unchanged.
(#1113)
+- Fixed SessionEnd replacing the session page an agent wrote itself through
+ `memory_write_page` with `session_id`: the rule-based summary overwrote it
+ on every substantive session end, and the opt-in SessionEnd worker's skip
+ never applied, since it read the page after that overwrite and compared an
+ observation count that the agent's own tool call, the Stop and the
+ SessionEnd always advance. A session page carrying `consolidated_by: agent`
+ is now kept by both, and the write no longer stamps
+ `observation_generation`. (#1138)
- Fixed the hook spool charging a spooled event's retry budget while the
server was unreachable: an endpoint-level delivery failure (connection
refused, timeout, DNS — the existing `Unreachable` classification) no
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index 1f65ed4b..60e2d1ac 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -903,17 +903,16 @@ async fn run_session_consolidation_worker(
let attempts = job.attempts();
// An agent may have written the session page with its own model
// while the session was still open, before this job existed. Leave
- // that page alone unless observations arrived after it.
- match consolidator
- .agent_page_covers_generation(session_id, generation)
- .await
- {
+ // that page alone: the agent's own tool call, the Stop and the
+ // SessionEnd always land after it, so no observation count can tell
+ // a stale page from a current one.
+ match consolidator.session_page_written_by_agent(session_id).await {
Ok(true) => {
match writer.complete_session_consolidation(job).await {
Ok(()) => info!(
session = %session_id,
generation,
- "SessionEnd: agent-written session page already covers this generation; consolidation skipped",
+ "SessionEnd: session page was written by the agent; consolidation skipped",
),
Err(error) => tracing::warn!(
%error,
@@ -4559,56 +4558,52 @@ mod tests {
.unwrap_or_default()
}
- /// The agent wrote the session page while the session was open, and no
- /// observation arrived after it: the worker completes the job without a
- /// completion (the provider panics if called) and keeps the page.
- #[tokio::test]
- async fn session_consolidation_worker_keeps_a_current_agent_page() {
- let (_tmp, store, wiki, workspace_id, project_id, session_id) =
- session_with_written_page(serde_json::json!({
- "consolidated_by": "agent",
- "observation_generation": 1,
- }))
- .await;
- let body = run_worker_once(
- &store,
- wiki,
- Arc::new(PanicLlm),
- workspace_id,
- project_id,
- session_id,
- )
- .await;
- assert!(body.contains("Written by the agent"), "{body}");
- }
-
- /// Controls: a page the agent wrote before the job's last observation,
- /// and a page with a current generation that no agent wrote, are both
- /// consolidated as before.
+ /// The agent wrote the session page while the session was open: the
+ /// worker completes the job without a completion (the provider panics if
+ /// called) and keeps the page. The page's frontmatter predates the job's
+ /// last observation, as every real in-session write does, and a stale
+ /// `observation_generation` left by an older build changes nothing.
#[tokio::test]
- async fn session_consolidation_worker_replaces_a_stale_or_non_agent_page() {
+ async fn session_consolidation_worker_keeps_an_agent_page() {
for frontmatter in [
+ serde_json::json!({"consolidated_by": "agent"}),
serde_json::json!({"consolidated_by": "agent", "observation_generation": 0}),
- serde_json::json!({"observation_generation": 1}),
] {
let (_tmp, store, wiki, workspace_id, project_id, session_id) =
session_with_written_page(frontmatter.clone()).await;
let body = run_worker_once(
&store,
wiki,
- Arc::new(SuccessfulConsolidationLlm),
+ Arc::new(PanicLlm),
workspace_id,
project_id,
session_id,
)
.await;
assert!(
- body.contains("Durable worker completed"),
+ body.contains("Written by the agent"),
"{frontmatter}: {body}"
);
}
}
+ /// Control: a session page no agent wrote is consolidated as before.
+ #[tokio::test]
+ async fn session_consolidation_worker_replaces_a_non_agent_page() {
+ let (_tmp, store, wiki, workspace_id, project_id, session_id) =
+ session_with_written_page(serde_json::json!({"consolidated": true})).await;
+ let body = run_worker_once(
+ &store,
+ wiki,
+ Arc::new(SuccessfulConsolidationLlm),
+ workspace_id,
+ project_id,
+ session_id,
+ )
+ .await;
+ assert!(body.contains("Durable worker completed"), "{body}");
+ }
+
async fn two_project_wiki() -> (TempDir, Store, Wiki, WorkspaceId, ProjectId, ProjectId) {
let tmp = TempDir::new().unwrap();
let store = Store::open(tmp.path()).unwrap();
diff --git a/crates/ai-memory-consolidate/src/consolidator.rs b/crates/ai-memory-consolidate/src/consolidator.rs
index 7d09099c..3f71d585 100644
--- a/crates/ai-memory-consolidate/src/consolidator.rs
+++ b/crates/ai-memory-consolidate/src/consolidator.rs
@@ -431,41 +431,22 @@ impl Consolidator {
Ok(self.reader.session_project_ids(session_id).await?)
}
- /// Whether the session page was written by the calling agent through
- /// `memory_write_page` and no observation has arrived since: the page's
- /// `observation_generation` reaches the queued job's `generation`. The
+ /// Whether the calling agent wrote the session page through
+ /// `memory_write_page` ([`Wiki::session_page_written_by_agent`]). The
/// SessionEnd worker then leaves the page alone instead of replacing it
- /// with a completion from the server's provider. A page any other writer
- /// produced, or one older than the job's observations, is consolidated
- /// as before.
+ /// with a completion from the server's provider, however many
+ /// observations arrived after it.
///
/// # Errors
/// Propagates store and wiki errors other than a missing page.
- pub async fn agent_page_covers_generation(
+ pub async fn session_page_written_by_agent(
&self,
session_id: SessionId,
- generation: u64,
) -> ConsolidatorResult<bool> {
let (ws, proj) = self.resolve_target(session_id).await?;
- let path = PagePath::new(format!("sessions/{session_id}.md"))?;
- let frontmatter = match self.wiki.read_page(ws, proj, &path) {
- Ok(md) => md.frontmatter,
- Err(ai_memory_wiki::WikiError::Io(err))
- if err.kind() == std::io::ErrorKind::NotFound =>
- {
- return Ok(false);
- }
- Err(err) => return Err(err.into()),
- };
- let by_agent = frontmatter
- .get("consolidated_by")
- .and_then(serde_json::Value::as_str)
- == Some("agent");
- let covered = frontmatter
- .get("observation_generation")
- .and_then(serde_json::Value::as_u64)
- .is_some_and(|written| written >= generation);
- Ok(by_agent && covered)
+ Ok(self
+ .wiki
+ .session_page_written_by_agent(ws, proj, session_id)?)
}
/// Resolve the session's creating harness from the persisted session row.
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 041da2d7..d72ffcc4 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -16,8 +16,8 @@ use ai_memory_consolidate::{Consolidator, ConsolidatorError, redacted_error_summ
use ai_memory_core::{
ActiveProject, ActorKey, AgentKind, DEFAULT_WORKSPACE_NAME, Handoff, IdentityKey,
MANAGED_WORKSTREAM_PACKET_MARKER, ManagedRunId, MidSessionRouting, NewHandoff, NewObservation,
- NewSession, ObservationKind, ProjectId, Sanitized, Sanitizer, SessionId, WorkspaceId,
- WorkstreamEvent, WorkstreamEventKind, truncate_utf8_bytes,
+ NewSession, ObservationKind, PageId, PagePath, ProjectId, Sanitized, Sanitizer, SessionId,
+ WorkspaceId, WorkstreamEvent, WorkstreamEventKind, truncate_utf8_bytes,
};
use ai_memory_store::{
HookSessionAdmission, IngestObservationOutcome, StoreError, WriterHandle,
@@ -3856,29 +3856,37 @@ async fn process_authorized(
} else {
None
};
- let page_id = state
- .wiki
- .write_page(ai_memory_wiki::WritePageRequest {
- workspace_id: new_page.workspace_id,
- project_id: new_page.project_id,
- path: new_page.path.clone(),
- frontmatter: new_page.frontmatter_json.clone(),
- body: new_page.body.clone(),
- tier: new_page.tier,
- pinned: new_page.pinned,
- title: None,
- admission_ctx: None,
- author_id: None,
- // Attribute to the operator who OWNED the session, read back
- // from the session row, not to whoever delivered this
- // SessionEnd — a spool drain, an operator finalizing a stuck
- // session, or a shared hook token can all carry a different
- // identity. NULL stays anonymous/shared, including rows that
- // predate owner recording.
- actor: session_actor.clone(),
- evidence: Vec::new(),
- })
- .await?;
+ let page_id =
+ match agent_session_page_id(state, page_ws, page_proj, session_id, &new_page.path)
+ .await?
+ {
+ Some(page_id) => page_id,
+ None => {
+ state
+ .wiki
+ .write_page(ai_memory_wiki::WritePageRequest {
+ workspace_id: new_page.workspace_id,
+ project_id: new_page.project_id,
+ path: new_page.path.clone(),
+ frontmatter: new_page.frontmatter_json.clone(),
+ body: new_page.body.clone(),
+ tier: new_page.tier,
+ pinned: new_page.pinned,
+ title: None,
+ admission_ctx: None,
+ author_id: None,
+ // Attribute to the operator who OWNED the session, read back
+ // from the session row, not to whoever delivered this
+ // SessionEnd — a spool drain, an operator finalizing a stuck
+ // session, or a shared hook token can all carry a different
+ // identity. NULL stays anonymous/shared, including rows that
+ // predate owner recording.
+ actor: session_actor.clone(),
+ evidence: Vec::new(),
+ })
+ .await?
+ }
+ };
if track_page_write && previous_page_id != Some(page_id) {
state.ingest_metrics.record_persisted(now_unix_ms());
}
@@ -4571,6 +4579,47 @@ async fn consolidate_or_synth(
Ok(CheckpointOutcome { fallback_reason })
}
+/// The id of `sessions/<id>.md` when the agent wrote it itself through
+/// `memory_write_page` with the session's id, which the automatic writers
+/// keep instead of replacing with the rule-based summary. The agent's own
+/// tool call, the Stop and the SessionEnd always land after that write, so
+/// no observation count separates a current page from a stale one. A page
+/// that cannot be read is replaced as before, with a warning.
+async fn agent_session_page_id(
+ state: &HookState,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ session_id: SessionId,
+ path: &PagePath,
+) -> anyhow::Result<Option<PageId>> {
+ match state
+ .wiki
+ .session_page_written_by_agent(workspace_id, project_id, session_id)
+ {
+ Ok(true) => {}
+ Ok(false) => return Ok(None),
+ Err(error) => {
+ warn!(
+ session = %session_id,
+ %error,
+ "could not read the session page; writing the rule-based summary",
+ );
+ return Ok(None);
+ }
+ }
+ let page_id = state
+ .reader
+ .latest_page_id_by_ids(workspace_id, project_id, path.as_str().to_owned())
+ .await?;
+ if page_id.is_some() {
+ info!(
+ session = %session_id,
+ "session page was written by the agent; keeping it over the rule-based summary",
+ );
+ }
+ Ok(page_id)
+}
+
fn short_id(s: &str) -> String {
s.chars().take(8).collect()
}
@@ -11323,6 +11372,89 @@ 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 {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let sid = "22222222-2222-2222-2222-222222222222";
+ let deliver = |event: &'static str| {
+ HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: event.into(),
+ agent: Some("claude-code".into()),
+ ..Default::default()
+ },
+ serde_json::json!({ "session_id": sid, "prompt": "consolidate this session" }),
+ )
+ };
+ for event in ["session-start", "user-prompt-submit"] {
+ process(&state, deliver(event), None, Vec::new())
+ .await
+ .unwrap();
+ }
+ let path = format!("sessions/{sid}.md");
+ state
+ .wiki
+ .write_page(ai_memory_wiki::WritePageRequest {
+ workspace_id: state.workspace_id,
+ project_id: state.project_id,
+ path: ai_memory_core::PagePath::new(path.clone()).unwrap(),
+ frontmatter,
+ body: "# Agent page\n\nCompiled by the agent's own model.".into(),
+ tier: ai_memory_core::Tier::Episodic,
+ pinned: false,
+ title: None,
+ admission_ctx: None,
+ author_id: None,
+ actor: ai_memory_core::ActorContext::anonymous(),
+ evidence: Vec::new(),
+ })
+ .await
+ .unwrap();
+ for event in ["user-prompt-submit", "session-end"] {
+ process(&state, deliver(event), None, Vec::new())
+ .await
+ .unwrap();
+ }
+ state
+ .reader
+ .page_body_by_ids(state.workspace_id, state.project_id, &path)
+ .await
+ .unwrap()
+ .expect("the session page must exist after SessionEnd")
+ .body
+ }
+
+ /// The agent wrote the session page itself, and the session went on after
+ /// the write: SessionEnd keeps the agent's page instead of replacing it
+ /// 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",
+ }))
+ .await;
+ assert!(body.contains("Compiled by the agent's own model"), "{body}");
+ }
+
+ /// Control: the same page without `consolidated_by: agent` is replaced by
+ /// 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;
+ assert!(
+ !body.contains("Compiled by the agent's own model"),
+ "{body}"
+ );
+ }
+
/// 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/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index da039c57..035a4229 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -3905,9 +3905,8 @@ impl AiMemoryServer {
/// The origin keys consolidation stamps on a session page, so a reader
/// cannot tell the two writers apart by shape. `consolidated_by` is the
/// one difference: the server cannot verify which model the agent ran, so
- /// it records the route and no model name. `observation_generation` is
- /// the session's observation count at write time, which the SessionEnd
- /// worker compares to its job's generation before overwriting the page.
+ /// it records the route and no model name, and the automatic SessionEnd
+ /// writers leave a page carrying it alone.
async fn stamp_session_page(
&self,
fm: &mut serde_json::Map<String, serde_json::Value>,
@@ -3934,15 +3933,6 @@ impl AiMemoryServer {
"consolidated_by".into(),
serde_json::Value::String("agent".into()),
);
- let generation = self
- .reader
- .session_observation_count(session_id)
- .await
- .map_err(|e| McpError::internal_error(e.to_string(), None))?;
- fm.insert(
- "observation_generation".into(),
- serde_json::Value::from(generation),
- );
Ok(())
}
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index cce96751..ad5b4c9c 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -4107,24 +4107,6 @@ impl ReaderPool {
.await
}
- /// Number of observations captured for a session, in every scope: the
- /// same count `session_consolidation::enqueue` stores as a job's
- /// generation, so a page stamped with it can be compared to a queued job.
- ///
- /// # Errors
- /// Propagates any SQL or pool error.
- pub async fn session_observation_count(&self, session_id: SessionId) -> StoreResult<u64> {
- self.with_conn(move |conn| {
- let count: i64 = conn.query_row(
- "SELECT COUNT(*) FROM observations WHERE session_id = ?1",
- params![session_id.as_bytes()],
- |row| row.get(0),
- )?;
- Ok(u64::try_from(count).unwrap_or(0))
- })
- .await
- }
-
/// Look up the immutable harness identity stored for a session.
///
/// Machine-generated session pages use this as their origin metadata.
diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rs
index 8f51f464..5ce3a2fe 100644
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@ -754,6 +754,34 @@ impl Wiki {
parse(&raw)
}
+ /// Whether the calling agent wrote `sessions/<session_id>.md` itself,
+ /// through `memory_write_page` with that session's id: the page carries
+ /// `consolidated_by: agent`. The automatic session-page writers leave such
+ /// a page alone, because it was compiled by the model the user was
+ /// working with. A missing page is `false`.
+ ///
+ /// # Errors
+ /// Propagates [`Self::read_page`] errors other than a missing file.
+ pub fn session_page_written_by_agent(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ session_id: SessionId,
+ ) -> WikiResult<bool> {
+ let path = PagePath::new(format!("sessions/{session_id}.md"))?;
+ let frontmatter = match self.read_page(workspace_id, project_id, &path) {
+ Ok(md) => md.frontmatter,
+ Err(WikiError::Io(err)) if err.kind() == std::io::ErrorKind::NotFound => {
+ return Ok(false);
+ }
+ Err(err) => return Err(err),
+ };
+ Ok(frontmatter
+ .get("consolidated_by")
+ .and_then(serde_json::Value::as_str)
+ == Some("agent"))
+ }
+
fn confined_project_root(
&self,
workspace_id: WorkspaceId,
diff --git a/docs/design-decisions.md b/docs/design-decisions.md
index 47baecda..68df96fc 100644
--- a/docs/design-decisions.md
+++ b/docs/design-decisions.md
@@ -96,7 +96,7 @@ Why not LanceDB/Qdrant/Kuzu/CozoDB/SurrealDB?
**LLM for consolidation passes:**
- **Off by default**, behaves like agentmemory after #138's fix. Without a provider, the system still works: synthetic compression (rule-based), no LLM-generated summaries, no `memory_consolidate` page-rewrite.
-- With a provider, LLM consolidation runs on PreCompact, on demand via `memory_consolidate`, and at session end only when `AI_MEMORY_CONSOLIDATE_ON_SESSION_END=true` (off by default). A substantive session end always writes a rule-based summary page + handoff regardless; a session containing only `SessionStart` / `SessionEnd` boundaries closes without either artifact or provider work and releases any startup handoff bound to that receiver. SessionEnd provider work is persisted by observation generation and consumed outside the hook request by one bounded retrying worker, so client drain cancellation cannot lose it. The automatic handoff and completed-end watermark commit in one SQLite transaction; an already-ended keyed replay converges the remaining wiki commit, provider enqueue, and ingest-key completion. The completed end also stores the observation count it covered; a resumed session re-enters the end path only after that count advances, avoiding non-convergent wall-clock comparisons. Optional 6h maintenance timer.
+- With a provider, LLM consolidation runs on PreCompact, on demand via `memory_consolidate`, and at session end only when `AI_MEMORY_CONSOLIDATE_ON_SESSION_END=true` (off by default). A substantive session end always writes a rule-based summary page + handoff regardless, except that a session page the agent wrote itself through `memory_write_page` with the session's id (`consolidated_by: agent`) is kept in place of the summary and skipped by the SessionEnd worker; a session containing only `SessionStart` / `SessionEnd` boundaries closes without either artifact or provider work and releases any startup handoff bound to that receiver. SessionEnd provider work is persisted by observation generation and consumed outside the hook request by one bounded retrying worker, so client drain cancellation cannot lose it. The automatic handoff and completed-end watermark commit in one SQLite transaction; an already-ended keyed replay converges the remaining wiki commit, provider enqueue, and ingest-key completion. The completed end also stores the observation count it covered; a resumed session re-enters the end path only after that count advances, avoiding non-convergent wall-clock comparisons. Optional 6h maintenance timer.
- Providers implement `LlmProvider { complete(...); complete_structured(...) }`. The current provider and authentication matrix lives in [`ARCHITECTURE.md`](ARCHITECTURE.md); this design boundary also covers OpenAI-compatible endpoints such as Ollama, vLLM, and LM Studio.
- **Native HTTP per provider** - no LiteLLM-equivalent. The cognee tracker (#2412/#2430/#2537/#2608/#2749/#2782/#2840/#2842) showed silent-kwarg-drop in a generic gateway is the #1 source of provider bugs. Each provider's typed JSON, errors on unknown fields. Hand-coded but correct.
- **Structured output via JSON schema, not XML, not Instructor-style wrapping.** Use each provider's native JSON-mode where available; for Anthropic, request a tool-use response with a typed schema. Validate with `serde_json` + `schemars`-derived schemas.
diff --git a/docs/usage.md b/docs/usage.md
index 0ca3cb28..0fa4090f 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. The page records the session's observation count, and the opt-in SessionEnd worker keeps it unless observations arrived after it. |
+| "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. |
| "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`. |