Skip to content

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

Rust

feat(mcp): let memory_write_page cite a session (#1038)

Felipe Neves Ricardod8446a1d0ab8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 762d7fbb..63b15120 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- Added an optional `session_id` to `memory_write_page`, so an agent can
+ write a session's page with its own model and keep it traceable to the
+ session. The session must belong to the project the page is written to, and
+ the page records it as session evidence. A page that cites a session does
+ not overwrite a pinned page. Writing `sessions/<id>.md` also stamps the
+ frontmatter `memory_consolidate` writes there (`session_id`, `agent`,
+ `consolidated`, plus `consolidated_by: agent`), defaults the tier to
+ `episodic`, applies the same duplicate-title suffix, and marks the session's
+ queued SessionEnd consolidation job completed. (#1038)
- Added `install-hooks --agent claude-code --scope project`, which writes the
hook configuration to the checkout's gitignored `.claude/settings.local.json`
(where Claude Code reads it: the git root, or the launch directory on
diff --git a/crates/ai-memory-consolidate/src/consolidator.rs b/crates/ai-memory-consolidate/src/consolidator.rs
index 44231cb6..fec03aea 100644
--- a/crates/ai-memory-consolidate/src/consolidator.rs
+++ b/crates/ai-memory-consolidate/src/consolidator.rs
@@ -516,12 +516,7 @@ impl Consolidator {
}
}
- /// Latest page titles for duplicate-title avoidance on the session
- /// page, seen through the same owner visibility as the slot
- /// snapshots. The session's OWN page is excluded: re-consolidation
- /// refreshing its own previous title is correct, not a collision.
- /// Best-effort — a store hiccup degrades to "no context" rather
- /// than failing consolidation.
+ /// See [`existing_session_page_titles`].
async fn existing_page_titles(
&self,
workspace_id: WorkspaceId,
@@ -529,42 +524,8 @@ impl Consolidator {
actor: &ai_memory_core::ActorContext,
session_id: SessionId,
) -> Vec<String> {
- let own_path = format!("sessions/{session_id}.md");
- match self
- .reader
- .briefing_for_project(
- workspace_id,
- project_id,
- EXISTING_TITLES_QUERY_LIMIT,
- ai_memory_core::OwnerFilter::for_actor_context(actor),
- false,
- )
+ existing_session_page_titles(&self.reader, workspace_id, project_id, actor, session_id)
.await
- {
- Ok(brief) => {
- let from_briefing = brief
- .recent_pages
- .iter()
- .chain(brief.pinned.iter())
- .chain(brief.rules.iter())
- .chain(brief.slots.iter())
- .filter(|p| p.path != own_path)
- .map(|p| p.title.clone());
- let from_settled = brief
- .settled
- .iter()
- .filter(|p| p.path != own_path)
- .map(|p| p.title.clone());
- from_briefing.chain(from_settled).collect()
- }
- Err(err) => {
- warn!(
- error = %err,
- "existing-title query failed; skipping duplicate-title context"
- );
- Vec::new()
- }
- }
}
async fn slot_snapshots(
@@ -1777,11 +1738,64 @@ fn render_title_uniqueness_section(titles: &[String]) -> String {
)
}
-/// Shared collision backstop for both session-page write paths.
+/// Latest page titles for duplicate-title avoidance on the session
+/// page, seen through the same owner visibility as the slot
+/// snapshots. The session's OWN page is excluded: re-consolidation
+/// refreshing its own previous title is correct, not a collision.
+/// Best-effort — a store hiccup degrades to "no context" rather
+/// than failing consolidation. Shared with the MCP `memory_write_page`
+/// session-page path, which writes the same page without a completion.
+pub async fn existing_session_page_titles(
+ reader: &ReaderPool,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ actor: &ai_memory_core::ActorContext,
+ session_id: SessionId,
+) -> Vec<String> {
+ let own_path = format!("sessions/{session_id}.md");
+ match reader
+ .briefing_for_project(
+ workspace_id,
+ project_id,
+ EXISTING_TITLES_QUERY_LIMIT,
+ ai_memory_core::OwnerFilter::for_actor_context(actor),
+ false,
+ )
+ .await
+ {
+ Ok(brief) => {
+ let from_briefing = brief
+ .recent_pages
+ .iter()
+ .chain(brief.pinned.iter())
+ .chain(brief.rules.iter())
+ .chain(brief.slots.iter())
+ .filter(|p| p.path != own_path)
+ .map(|p| p.title.clone());
+ let from_settled = brief
+ .settled
+ .iter()
+ .filter(|p| p.path != own_path)
+ .map(|p| p.title.clone());
+ from_briefing.chain(from_settled).collect()
+ }
+ Err(err) => {
+ warn!(
+ error = %err,
+ "existing-title query failed; skipping duplicate-title context"
+ );
+ Vec::new()
+ }
+ }
+}
+
+/// Shared collision backstop for every session-page write path: the
+/// single-page and batch consolidations, and `memory_write_page` with a
+/// `session_id`.
/// When `title` already names another latest page (case-insensitive,
/// whitespace-collapsed — the M8 grouping), suffix the session short
/// id and retitle a matching leading H1. `None` when the title is free.
-fn disambiguate_colliding_session_title(
+pub fn disambiguate_colliding_session_title(
title: &str,
body: &str,
existing_titles: &[String],
diff --git a/crates/ai-memory-consolidate/src/lib.rs b/crates/ai-memory-consolidate/src/lib.rs
index 91ff06e1..e3a16c02 100644
--- a/crates/ai-memory-consolidate/src/lib.rs
+++ b/crates/ai-memory-consolidate/src/lib.rs
@@ -64,7 +64,8 @@ pub use consolidator::{
BATCH_SYSTEM_PROMPT, Consolidator, ConsolidatorError, ConsolidatorResult,
DEFAULT_CONSOLIDATION_INPUT_TOKEN_SAFETY_MARGIN, DEFAULT_CONSOLIDATION_MAX_INPUT_TOKENS,
DEFAULT_CONSOLIDATION_MAX_OUTPUT_TOKENS, MIN_CONSOLIDATION_MAX_INPUT_TOKENS,
- MIN_CONSOLIDATION_MAX_OUTPUT_TOKENS, build_batch_request,
+ MIN_CONSOLIDATION_MAX_OUTPUT_TOKENS, build_batch_request, disambiguate_colliding_session_title,
+ existing_session_page_titles,
};
pub use curator::{
CuratorFinding, CuratorParams, CuratorReport, render_curator_report_markdown,
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index cb3921da..6ca99b45 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -1606,6 +1606,15 @@ struct WritePageArgs {
/// by the next forget sweep. Omit for pages that never expire.
#[serde(default)]
expires_at: Option<String>,
+ /// Optional session this page was written from. The session must belong
+ /// to the project the page is written to. The page records it as
+ /// evidence, as `memory_consolidate` does, and refuses to overwrite a
+ /// pinned page. Writing `sessions/<session_id>.md` also stamps the
+ /// session-page frontmatter and marks the session's pending
+ /// consolidation job completed, so the agent can write the session page
+ /// with its own model. Not combinable with `scope: "global"`.
+ #[serde(default)]
+ session_id: Option<String>,
}
#[tool_router]
@@ -3530,8 +3539,9 @@ impl AiMemoryServer {
}
/// Reconcile the durable SessionEnd job row after a successful manual
- /// `memory_consolidate` so the operator does not see a `failed` job for a
- /// session that is now consolidated. The automatic worker owns the job's
+ /// `memory_consolidate`, or a `memory_write_page` of the session page, so
+ /// the operator does not see a `failed` job for a session that is now
+ /// consolidated. The automatic worker owns the job's
/// lease, so the reconcile never touches a `running` row; a best-effort
/// failure here must not fail the consolidate that already wrote the page.
async fn reconcile_consolidation_job(&self, session_id: SessionId) {
@@ -3543,11 +3553,118 @@ impl AiMemoryServer {
tracing::warn!(
%session_id,
%error,
- "failed to reconcile session consolidation job after manual consolidate"
+ "failed to reconcile session consolidation job after a manual session-page write"
);
}
}
+ /// A session id names a repository without passing through scope
+ /// resolution (#708), so a page may cite one only when the session lives
+ /// in the project the page is written to, the one the write grant was
+ /// checked against. The project comes from where the session's
+ /// observations landed, as for `memory_consolidate`. Unknown and foreign
+ /// sessions get the same refusal, so the error does not reveal whether a
+ /// foreign id exists.
+ async fn require_session_in_scope(
+ &self,
+ session_id: SessionId,
+ workspace_id: ai_memory_core::WorkspaceId,
+ project_id: ai_memory_core::ProjectId,
+ ) -> Result<(), McpError> {
+ let from_observations = self
+ .reader
+ .session_scope_from_observations(session_id)
+ .await
+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;
+ let scope = match from_observations {
+ Some(scope) => Some(scope),
+ None => self
+ .reader
+ .session_project_ids(session_id)
+ .await
+ .map_err(|e| McpError::internal_error(e.to_string(), None))?,
+ };
+ if scope == Some((workspace_id, project_id)) {
+ Ok(())
+ } else {
+ Err(McpError::invalid_params(
+ format!(
+ "session {session_id} is not a session of the project this page is written to"
+ ),
+ None,
+ ))
+ }
+ }
+
+ /// Pinned pages are immutable to automation, and a write that cites a
+ /// session is a consolidation by another route. `Wiki::write_page` takes
+ /// the pin from the request alone, so without this check the write would
+ /// replace the body and drop the pin. `_slots/` keep their own regime,
+ /// as in the consolidator's batch path.
+ fn refuse_pinned_page_overwrite(
+ wiki: &Wiki,
+ workspace_id: ai_memory_core::WorkspaceId,
+ project_id: ai_memory_core::ProjectId,
+ path: &PagePath,
+ ) -> Result<(), McpError> {
+ if ai_memory_core::is_slot_path(path.as_str()) {
+ return Ok(());
+ }
+ let pinned = match wiki.read_page(workspace_id, project_id, path) {
+ Ok(md) => {
+ md.frontmatter
+ .get("pinned")
+ .and_then(serde_json::Value::as_bool)
+ == Some(true)
+ }
+ Err(WikiError::Io(err)) if err.kind() == std::io::ErrorKind::NotFound => false,
+ Err(err) => return Err(McpError::internal_error(err.to_string(), None)),
+ };
+ if pinned {
+ return Err(McpError::invalid_request(
+ format!(
+ "page '{}' is pinned; a write that cites a session does not overwrite a pinned page",
+ path.as_str()
+ ),
+ None,
+ ));
+ }
+ Ok(())
+ }
+
+ /// 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.
+ async fn stamp_session_page(
+ &self,
+ fm: &mut serde_json::Map<String, serde_json::Value>,
+ session_id: SessionId,
+ ) -> Result<(), McpError> {
+ let agent = self
+ .reader
+ .session_agent_kind(session_id)
+ .await
+ .map_err(|e| McpError::internal_error(e.to_string(), None))?
+ .ok_or_else(|| {
+ McpError::invalid_params(format!("session {session_id} has no session row"), None)
+ })?;
+ fm.insert(
+ "session_id".into(),
+ serde_json::Value::String(session_id.to_string()),
+ );
+ fm.insert(
+ "agent".into(),
+ serde_json::Value::String(agent.as_str().into()),
+ );
+ fm.insert("consolidated".into(), serde_json::Value::Bool(true));
+ fm.insert(
+ "consolidated_by".into(),
+ serde_json::Value::String("agent".into()),
+ );
+ Ok(())
+ }
+
/// Stage durable wiki edit proposals for a completed session.
#[tool(
annotations(
@@ -3855,7 +3972,15 @@ impl AiMemoryServer {
pass the `title` argument; passing it forces correct JSON-escaping \
of the string and is a known source of `JSON parsing` errors when \
the title contains quotes or punctuation (issue #67). Use `title` \
- only when there's no usable H1 in the body."
+ only when there's no usable H1 in the body. \
+ \
+ **Session evidence:** pass `session_id` when the page is compiled \
+ from that session's captured observations. Write the session page \
+ itself at `sessions/<session_id>.md` (tier defaults to `episodic` \
+ there) to replace the server-model consolidation with your own; \
+ `memory_read_session_observations` returns the evidence to write \
+ from. The write goes through the `write_page` admission op, not \
+ `consolidate`."
)]
async fn memory_write_page(
&self,
@@ -3869,15 +3994,38 @@ impl AiMemoryServer {
None,
));
};
- let tier_name = args.tier.as_deref().unwrap_or("semantic");
- let tier: Tier = tier_name
- .parse()
- .map_err(|_| McpError::internal_error(format!("unknown tier '{tier_name}'"), None))?;
+ // Same blank-means-omitted reading as `memory_consolidate`; anything
+ // else that is not a UUID is caller input.
+ let session_id = args
+ .session_id
+ .as_deref()
+ .map(str::trim)
+ .filter(|raw| !raw.is_empty())
+ .map(SessionId::from_str)
+ .transpose()
+ .map_err(|e| McpError::invalid_params(e.to_string(), None))?;
let path = PagePath::new(args.path.clone())
.map_err(|e| McpError::internal_error(format!("invalid path: {e}"), None))?;
path.ensure_portable()
.map_err(|e| McpError::internal_error(format!("invalid path: {e}"), None))?;
let path = self.place_slot_write(path, &parts).await?;
+ let session_page =
+ session_id.is_some_and(|id| path.as_str() == format!("sessions/{id}.md"));
+ // Consolidation writes the session page as episodic; keep that
+ // default so both writers of the page agree.
+ let tier_name =
+ args.tier
+ .as_deref()
+ .unwrap_or(if session_page { "episodic" } else { "semantic" });
+ let tier: Tier = tier_name
+ .parse()
+ .map_err(|_| McpError::internal_error(format!("unknown tier '{tier_name}'"), None))?;
+ if session_id.is_some() && args.scope.as_deref().is_some_and(|s| !s.trim().is_empty()) {
+ return Err(McpError::invalid_params(
+ "session_id cannot be combined with scope: \"global\"; a session belongs to one project",
+ None,
+ ));
+ }
let (ws, proj) = match args.scope.as_deref().map(str::trim) {
None | Some("") => {
self.write_target_ids_with_actor(
@@ -3915,6 +4063,10 @@ impl AiMemoryServer {
));
}
};
+ if let Some(session_id) = session_id {
+ self.require_session_in_scope(session_id, ws, proj).await?;
+ Self::refuse_pinned_page_overwrite(wiki, ws, proj, &path)?;
+ }
let mut fm = serde_json::Map::new();
if let Some(title) = &args.title {
@@ -3948,16 +4100,40 @@ impl AiMemoryServer {
serde_json::Value::String(expires_at.to_string()),
);
}
+ // rmcp exposes the original HTTP `Parts`; trust the auth middleware's
+ // extension, not raw client-controlled actor headers.
+ let actor = crate::actor::actor_from_parts(&parts);
+ let author_id = crate::actor::author_id_from_parts(&parts);
+ let mut body = args.body;
+ let mut title = args.title;
+ if let Some(session_id) = session_id.filter(|_| session_page) {
+ self.stamp_session_page(&mut fm, session_id).await?;
+ let current =
+ ai_memory_wiki::derive_title(&serde_json::Value::Object(fm.clone()), &body, &path);
+ let existing = ai_memory_consolidate::existing_session_page_titles(
+ &self.reader,
+ ws,
+ proj,
+ &actor,
+ session_id,
+ )
+ .await;
+ if let Some((new_title, new_body)) =
+ ai_memory_consolidate::disambiguate_colliding_session_title(
+ &current, &body, &existing, session_id,
+ )
+ {
+ fm.insert("title".into(), serde_json::Value::String(new_title.clone()));
+ title = Some(new_title);
+ body = new_body;
+ }
+ }
let frontmatter = if fm.is_empty() {
serde_json::Value::Null
} else {
serde_json::Value::Object(fm)
};
- // rmcp exposes the original HTTP `Parts`; trust the auth middleware's
- // extension, not raw client-controlled actor headers.
- let actor = crate::actor::actor_from_parts(&parts);
- let author_id = crate::actor::author_id_from_parts(&parts);
// Loop prevention: a webhook that writes back into the engine sets
// `X-Memory-Skip-Admission-Chain` so the chain doesn't re-invoke it
// on the recursive write. Only trusted/root re-entry can honor it.
@@ -3980,18 +4156,29 @@ impl AiMemoryServer {
project_id: proj,
path: path.clone(),
frontmatter,
- body: args.body,
+ body,
tier,
pinned: args.pinned,
- title: args.title,
+ title,
admission_ctx,
author_id,
actor,
- evidence: Vec::new(),
+ evidence: session_id
+ .map(|id| ai_memory_core::PageEvidence {
+ kind: ai_memory_core::PageEvidenceKind::Session,
+ source_id: id.to_string(),
+ })
+ .into_iter()
+ .collect(),
})
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
let checkpoint = checkpoint_or_warn(wiki, format!("memory_write_page: {}", path.as_str()));
+ // Only the session page settles the job: evidence on another page
+ // must not close it while `sessions/<id>.md` is still missing.
+ if let Some(session_id) = session_id.filter(|_| session_page) {
+ self.reconcile_consolidation_job(session_id).await;
+ }
ok_json(&serde_json::json!({
"page_id": page_id.to_string(),
@@ -8742,6 +8929,7 @@ mod tests {
workspace: None,
scope: None,
expires_at: None,
+ session_id: None,
}),
OptionalParts(parts),
)
@@ -9422,6 +9610,7 @@ mod tests {
workspace: None,
scope: scope.map(str::to_string),
expires_at: None,
+ session_id: None,
};
server
@@ -11839,6 +12028,7 @@ mod tests {
workspace: None,
scope: None,
expires_at: None,
+ session_id: None,
}),
OptionalParts(parts),
)
@@ -11875,6 +12065,310 @@ mod tests {
);
}
+ /// Two projects in one workspace, each with one ended session whose
+ /// SessionEnd consolidation job is queued, and a server on the first.
+ async fn session_evidence_fixture() -> (
+ TempDir,
+ Store,
+ AiMemoryServer,
+ WorkspaceId,
+ [(ProjectId, SessionId); 2],
+ ) {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let mut pairs = Vec::new();
+ for name in ["here", "elsewhere"] {
+ let proj = store
+ .writer
+ .get_or_create_project(ws, name, None)
+ .await
+ .unwrap();
+ let session = seed_short_completed_session(&store, ws, proj).await;
+ assert!(
+ store
+ .writer
+ .enqueue_session_consolidation(ws, proj, session)
+ .await
+ .unwrap()
+ );
+ pairs.push((proj, session));
+ }
+ let wiki = Wiki::new(tmp.path(), store.writer.clone())
+ .unwrap()
+ .with_store_reader(store.reader.clone());
+ let server =
+ AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, pairs[0].0)
+ .with_wiki(wiki);
+ (tmp, store, server, ws, [pairs[0], pairs[1]])
+ }
+
+ fn session_write_args(path: String, body: &str, session_id: SessionId) -> WritePageArgs {
+ WritePageArgs {
+ path,
+ body: body.into(),
+ title: None,
+ tier: None,
+ tags: Vec::new(),
+ pinned: false,
+ project: Some("here".into()),
+ workspace: Some("default".into()),
+ scope: None,
+ expires_at: None,
+ session_id: Some(session_id.to_string()),
+ }
+ }
+
+ /// Session ids whose SessionEnd job is still claimable, in claim order.
+ async fn claimable_sessions(store: &Store) -> Vec<SessionId> {
+ let now = jiff::Timestamp::now().as_microsecond();
+ let mut out = Vec::new();
+ while let Some(job) = store
+ .writer
+ .claim_session_consolidation(now, now - 1)
+ .await
+ .unwrap()
+ {
+ out.push(job.session_id());
+ }
+ out
+ }
+
+ fn session_evidence_rows(store: &Store, session_id: SessionId) -> i64 {
+ let conn = rusqlite::Connection::open(store.db_path()).unwrap();
+ conn.query_row(
+ "SELECT COUNT(*) FROM page_evidence WHERE source_kind = 'session' AND source_id = ?1",
+ rusqlite::params![session_id.to_string()],
+ |row| row.get(0),
+ )
+ .unwrap()
+ }
+
+ /// A session id names a repository without passing through scope
+ /// resolution (#708). Citing a session from another project, or one that
+ /// does not exist, is refused before anything is written, and the other
+ /// project's job stays queued. Control: the project's own session is
+ /// accepted.
+ #[tokio::test]
+ async fn write_page_refuses_a_session_from_another_project() {
+ let (_tmp, store, server, _ws, [(_, own), (_, foreign)]) = session_evidence_fixture().await;
+
+ for session in [foreign, SessionId::new()] {
+ let err = server
+ .memory_write_page(
+ Parameters(session_write_args(
+ format!("sessions/{session}.md"),
+ "# Borrowed session\n\nWritten from another project.",
+ session,
+ )),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(err.code, rmcp::model::ErrorCode::INVALID_PARAMS, "{err:?}");
+ assert!(
+ err.message
+ .contains("is not a session of the project this page is written to"),
+ "{err:?}"
+ );
+ }
+ assert_eq!(session_evidence_rows(&store, foreign), 0);
+
+ server
+ .memory_write_page(
+ Parameters(session_write_args(
+ format!("sessions/{own}.md"),
+ "# Own session\n\nWritten from this project.",
+ own,
+ )),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap();
+ assert_eq!(claimable_sessions(&store).await, vec![foreign]);
+ }
+
+ /// Writing the session page settles what `memory_consolidate` would have
+ /// settled: session evidence, the origin frontmatter, the episodic tier,
+ /// and the queued job.
+ #[tokio::test]
+ async fn write_page_of_the_session_page_stamps_cites_and_reconciles() {
+ let (tmp, store, server, ws, [(proj, own), (_, foreign)]) =
+ session_evidence_fixture().await;
+
+ server
+ .memory_write_page(
+ Parameters(session_write_args(
+ format!("sessions/{own}.md"),
+ "# Retry policy settled\n\nThe agent compiled this page.",
+ own,
+ )),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap();
+
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let page = wiki
+ .read_page(
+ ws,
+ proj,
+ &PagePath::new(format!("sessions/{own}.md")).unwrap(),
+ )
+ .unwrap();
+ let fm = &page.frontmatter;
+ assert_eq!(fm["session_id"], serde_json::json!(own.to_string()));
+ assert_eq!(fm["agent"], serde_json::json!(AgentKind::Other.as_str()));
+ assert_eq!(fm["consolidated"], serde_json::json!(true));
+ assert_eq!(fm["consolidated_by"], serde_json::json!("agent"));
+ assert_eq!(fm["tier"], serde_json::json!("episodic"));
+ assert_eq!(session_evidence_rows(&store, own), 1);
+ assert_eq!(claimable_sessions(&store).await, vec![foreign]);
+ }
+
+ /// Evidence may sit on any page, but only the session page closes the
+ /// job: closing it from another path would leave `sessions/<id>.md`
+ /// missing with nothing left to write it.
+ #[tokio::test]
+ async fn session_evidence_on_another_path_leaves_the_job_queued() {
+ let (_tmp, store, server, _ws, [(_, own), (_, foreign)]) = session_evidence_fixture().await;
+
+ server
+ .memory_write_page(
+ Parameters(session_write_args(
+ "decisions/retry-policy.md".into(),
+ "# Retry policy\n\nKeep the event id on retry.",
+ own,
+ )),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(session_evidence_rows(&store, own), 1);
+ let queued = claimable_sessions(&store).await;
+ assert_eq!(queued.len(), 2, "{queued:?}");
+ assert!(
+ queued.contains(&own) && queued.contains(&foreign),
+ "{queued:?}"
+ );
+ }
+
+ /// `Wiki::write_page` takes the pin from the request alone, so a write
+ /// that cites a session would otherwise replace a pinned page and drop
+ /// its pin. Control: the same write without `session_id` is an ordinary
+ /// operator edit and still goes through.
+ #[tokio::test]
+ async fn session_evidence_write_leaves_a_pinned_page_alone() {
+ let (tmp, store, server, ws, [(proj, own), _]) = session_evidence_fixture().await;
+ let path = "notes/curated.md";
+ let mut pinned = session_write_args(path.into(), "# Curated\n\nHand-written.", own);
+ pinned.session_id = None;
+ pinned.pinned = true;
+ server
+ .memory_write_page(Parameters(pinned), OptionalParts(test_parts_default()))
+ .await
+ .unwrap();
+
+ let err = server
+ .memory_write_page(
+ Parameters(session_write_args(
+ path.into(),
+ "# Curated\n\nGenerated over it.",
+ own,
+ )),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(err.code, rmcp::model::ErrorCode::INVALID_REQUEST, "{err:?}");
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let page = wiki
+ .read_page(ws, proj, &PagePath::new(path).unwrap())
+ .unwrap();
+ assert!(page.body.contains("Hand-written."), "{}", page.body);
+ assert_eq!(page.frontmatter["pinned"], serde_json::json!(true));
+ assert_eq!(session_evidence_rows(&store, own), 0);
+
+ let mut edit = session_write_args(path.into(), "# Curated\n\nEdited by hand.", own);
+ edit.session_id = None;
+ edit.pinned = true;
+ server
+ .memory_write_page(Parameters(edit), OptionalParts(test_parts_default()))
+ .await
+ .unwrap();
+ }
+
+ /// The session page gets the same title backstop as consolidation: a
+ /// title another page already carries is suffixed with the session's
+ /// short id, heading included.
+ #[tokio::test]
+ async fn session_page_write_disambiguates_a_taken_title() {
+ let (tmp, store, server, ws, [(proj, own), _]) = session_evidence_fixture().await;
+ let mut other = session_write_args(
+ "notes/release-checklist.md".into(),
+ "# Release checklist\n\nAn earlier page.",
+ own,
+ );
+ other.session_id = None;
+ server
+ .memory_write_page(Parameters(other), OptionalParts(test_parts_default()))
+ .await
+ .unwrap();
+
+ server
+ .memory_write_page(
+ Parameters(session_write_args(
+ format!("sessions/{own}.md"),
+ "# Release checklist\n\nThis session's run.",
+ own,
+ )),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap();
+
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let page = wiki
+ .read_page(
+ ws,
+ proj,
+ &PagePath::new(format!("sessions/{own}.md")).unwrap(),
+ )
+ .unwrap();
+ let title = page.frontmatter["title"].as_str().unwrap().to_string();
+ assert!(title.starts_with("Release checklist (session "), "{title}");
+ assert!(
+ page.body.starts_with(&format!("# {title}")),
+ "{}",
+ page.body
+ );
+ }
+
+ /// Malformed ids are caller input, and a session never belongs to the
+ /// reserved global scope.
+ #[tokio::test]
+ async fn write_page_rejects_a_malformed_or_global_session_id() {
+ let (_tmp, _store, server, _ws, [(_, own), _]) = session_evidence_fixture().await;
+ let mut malformed = session_write_args("notes/x.md".into(), "# X", own);
+ malformed.session_id = Some("not-a-uuid".into());
+ let mut global = session_write_args("notes/x.md".into(), "# X", own);
+ global.project = None;
+ global.workspace = None;
+ global.scope = Some("global".into());
+ for args in [malformed, global] {
+ let err = server
+ .memory_write_page(Parameters(args), OptionalParts(test_parts_default()))
+ .await
+ .unwrap_err();
+ assert_eq!(err.code, rmcp::model::ErrorCode::INVALID_PARAMS, "{err:?}");
+ }
+ }
+
#[tokio::test]
async fn memory_write_page_refuses_git_reserved_and_non_portable_paths() {
let tmp = TempDir::new().unwrap();
@@ -11919,6 +12413,7 @@ mod tests {
workspace: None,
scope: None,
expires_at: None,
+ session_id: None,
}),
OptionalParts(test_parts_default()),
)
@@ -11962,6 +12457,7 @@ mod tests {
workspace: Some("default".into()),
scope: None,
expires_at: None,
+ session_id: None,
}),
OptionalParts(test_parts_default()),
)
@@ -12028,6 +12524,7 @@ mod tests {
workspace: None,
scope: None,
expires_at: None,
+ session_id: None,
}),
OptionalParts(parts),
)
@@ -12135,6 +12632,7 @@ mod tests {
workspace: None,
scope: None,
expires_at: None,
+ session_id: None,
}),
OptionalParts(test_parts_default()),
)
@@ -12292,6 +12790,7 @@ mod tests {
workspace: None,
scope: None,
expires_at: None,
+ session_id: None,
}),
OptionalParts(parts()),
)
@@ -12384,6 +12883,7 @@ mod tests {
workspace: None,
scope: None,
expires_at: None,
+ session_id: None,
}),
OptionalParts(alice_parts),
)
@@ -12785,6 +13285,7 @@ mod tests {
workspace: None,
scope: None,
expires_at: None,
+ session_id: None,
}),
OptionalParts(parts),
)
@@ -12879,6 +13380,7 @@ mod tests {
workspace: None,
scope: None,
expires_at: None,
+ session_id: None,
}),
OptionalParts(parts),
)
@@ -12981,6 +13483,7 @@ mod tests {
workspace: None,
scope: None,
expires_at: None,
+ session_id: None,
}),
OptionalParts(test_parts_default()),
)
@@ -13047,6 +13550,7 @@ mod tests {
workspace: None,
scope: None,
expires_at: None,
+ session_id: None,
}),
OptionalParts(parts()),
)
@@ -13138,6 +13642,7 @@ mod tests {
workspace: None,
scope: None,
expires_at: None,
+ session_id: None,
}),
OptionalParts(test_parts_default()),
)
@@ -13233,6 +13738,7 @@ mod tests {
workspace: Some("alpha".into()),
scope: None,
expires_at: None,
+ session_id: None,
}),
OptionalParts(parts()),
)
@@ -13251,6 +13757,7 @@ mod tests {
workspace: Some("beta".into()),
scope: None,
expires_at: None,
+ session_id: None,
}),
OptionalParts(parts()),
)
@@ -13354,6 +13861,7 @@ mod tests {
workspace: None,
scope: None,
expires_at: None,
+ session_id: None,
}),
OptionalParts(parts()),
)
@@ -15296,6 +15804,7 @@ mod tests {
workspace: None,
scope: None,
expires_at: None,
+ session_id: None,
}),
OptionalParts(parts()),
)
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 645ddcb8..087aed19 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -524,7 +524,7 @@ 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; an update whose path names an existing pinned page is skipped (`_slots/` excepted). 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. |
+| `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; optional `session_id` cites a session of the same project as evidence, and on `sessions/<id>.md` stamps the session-page frontmatter and settles the queued consolidation job. |
| `memory_delete_page` | destructive | Delete a single page by exact `path`. Fires the admission chain (op=delete); idempotent. |
| `memory_forget_sweep` | destructive | Retention pass: evict cold pages through the wiki layer, purge aged tombstone ancestry, and hard-delete TTL-expired pages. `dry_run=true` for preview. |
| `memory_lint` | destructive | Rule-based + LLM contradiction findings → `wiki/_lint/`. Also runs a **zero-LLM contradiction detector** (design-memory-aging.md A5): cold semantic/procedural pages whose already-stored embeddings sit in the `contradiction_band_min`–`contradiction_band_max` cosine-similarity band (default 0.4–0.75; "same topic, not a near-duplicate" — at/above the max is A3 dedup, below the min unrelated) get an advisory `contradiction` finding with newer-wins timestamp advice. Bounded (one embeddings load over the capped cold set, capped findings, deterministic); a clean no-op with no embedder configured; advisory-only — never deletes/edits/supersedes a page and persists no edge (invariants #13, #16, #2), so no migration. On a single-language or single-domain store, background similarity between unrelated pages already sits well above the default floor, so the band measures domain proximity more than conflict and produces noisy findings — raise `contradiction_band_min` (`config.toml` or `AI_MEMORY_CONTRADICTION_BAND_MIN`) for such a store. |
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 53774ace..0a118b26 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -67,6 +67,7 @@ boundary not yet built.
| 14b | Repository identity routing (#708) | `ai-memory-store/src/ops.rs` `resolve_project_by_identity` — one transaction; an identity already on a project is never overwritten; an unclaimed project is claimed only when the capturing user may write it (the choke point's `resolve_project_authz` on the same transaction), otherwise it is returned unclaimed; a different identity under the same name splits into a new project with no shared `repo_path`; `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity too; `ai-memory-core/src/repository_identity.rs` strips credentials from remote URLs client-side, and the server accepts only the routing rungs (`explicit`, `git_remote`) from the wire | `tests/suite/identity_resolution.rs` `an_outsider_cannot_take_an_unclaimed_projects_identity` (control: `an_existing_project_is_claimed_in_place`), `two_unrelated_repositories_with_one_folder_name_stay_apart`, `a_created_or_split_project_admits_its_creator`; `router.rs` `one_path_with_two_remotes_is_two_projects`, `two_api_checkouts_with_different_remotes_get_two_projects` (a manifest rung on the wire is ignored); `repository_identity.rs` credential and normalisation tables — the claim guard and the cache key each proven to fail their test when removed | STRONG — first claimant wins: in a restricted workspace a user who creates a project under a remote identity first holds it until root grants others |
| 14c | Client-supplied event time is bounded and self-scoped (#919) | `ai-memory-hooks/src/payload.rs` `HookEnvelope::occurred_at_micros` — a `/hook` caller's optional `occurred_at` must be `> 0` and `<= now + 5min`; it only sets the caller's *own* admitted session's `started_at`/`ended_at`/`created_at`, never another session/project/user, and the ingest dedup `seen_at`/TTL stays on `now` | `payload.rs` `occurred_at_micros_rejects_a_far_future_timestamp`, `…_rejects_non_positive_values`, `…_rejects_garbage_strings` | MEDIUM — self-scoped numeric bound; no cross-tenant surface (a client already controls its own content) |
| 14d | `include_related` shows and walks only readable projects (#708) | `ai-memory-store/src/reader.rs` `related_walk(.., viewer)` — both the outgoing and incoming hop queries carry `readable_repository_predicate("pg.project_id", viewer)`, the same far-end filter `page_links` applies, so a page in a project the viewer cannot read is neither returned nor expanded; `ai-memory-mcp/src/server.rs` `memory_read_page` passes `viewer_from_parts`, and the access bump only touches the filtered nodes | `related_walk.rs` `the_walk_hides_and_does_not_cross_projects_the_viewer_cannot_read` (an outgoing and an incoming neighbour in an ungranted restricted project are absent, and so is a granted page reachable only through one; control: a granted restricted project is shown, and no viewer walks the whole graph) — fails with the predicate removed; `ai-memory-mcp` `server.rs` `bob_does_not_see_restricted_pages_through_the_related_walk` (an ungranted user's `memory_read_page{include_related}` omits the restricted page; control: no viewer still reaches it) — fails with `memory_read_page` passing `None` instead of `viewer_from_parts` | STRONG |
+| 14e | `memory_write_page` session evidence cites only a session of the target project (#708) | `ai-memory-mcp/src/server.rs` `memory_write_page` — a `session_id` is accepted only when `require_session_in_scope` resolves the session (where its observations landed, else its session row, as `Consolidator::session_target` does) to the same `(workspace_id, project_id)` the write grant was checked against; unknown and foreign ids get one refusal, so the error is no existence oracle; `scope: "global"` with a `session_id` is refused; `refuse_pinned_page_overwrite` keeps a write that cites a session off a pinned page; only a write to `sessions/<id>.md` reconciles the session's queued SessionEnd job | `server.rs` `write_page_refuses_a_session_from_another_project` (a foreign and an unknown session refused, no evidence row written, the foreign job still queued; control: the project's own session accepted), `session_evidence_write_leaves_a_pinned_page_alone` (control: the same write without `session_id` edits the page), `session_evidence_on_another_path_leaves_the_job_queued`, `write_page_rejects_a_malformed_or_global_session_id` — each of the scope check, the pinned check and the session-page-only reconcile proven to fail its test when removed | STRONG |
| 15 | Agent-archive restore path confinement, resource bounds, and consistency | `ai-memory-cli/src/commands/restore_agents.rs` stages only bounded regular UTF-8 entries; requires a one-to-one manifest/body/checksum/target mapping; allowlists destinations by scope; rejects symlinked descendants; writes each file atomically and rolls back earlier writes after a later failure. `backup_agents.rs` skips direct and directory-root source symlinks, bounds individual assets, and atomically replaces a private archive only after gzip completion | `backup_agents.rs` `restore_agents_rejects_path_traversal`, `restore_agents_rejects_unauthorized_destination_path`, `restore_agents_verifies_sha256_integrity`, `restore_agents_requires_a_complete_one_to_one_manifest`, `restore_agents_rejects_oversized_entries_from_the_header`, `restore_agents_rejects_a_symlinked_destination_parent`, `backup_agents_does_not_follow_config_or_asset_root_symlinks`, and `failed_backup_leaves_the_previous_archive_intact`; `backup_and_restore_agents_round_trip` is the valid-path control; `restore_agents::tests::rollback_removes_new_files_and_restores_overwrites` covers recovery | STRONG |
diff --git a/docs/usage.md b/docs/usage.md
index 5069b213..f975f3c4 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -138,6 +138,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. |
| "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`. |