Skip to content

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

Rust

fix(consolidate): attribute memory_consolidate writes to the request actor

Djalma Júniorc0a855508536
diff --git a/crates/ai-memory-consolidate/src/consolidator.rs b/crates/ai-memory-consolidate/src/consolidator.rs
index c4777005..1eff77b1 100644
--- a/crates/ai-memory-consolidate/src/consolidator.rs
+++ b/crates/ai-memory-consolidate/src/consolidator.rs
@@ -103,6 +103,8 @@ impl Consolidator {
&self,
session_id: SessionId,
dry_run: bool,
+ actor: ai_memory_core::ActorContext,
+ author_id: Option<ai_memory_core::UserId>,
) -> ConsolidatorResult<ConsolidationOutcome> {
let observations = self.reader.observations_for_session(session_id).await?;
if observations.is_empty() {
@@ -160,10 +162,11 @@ impl Consolidator {
title: None,
admission_ctx: Some(AdmissionContext {
op: AdmissionOp::Consolidate,
+ actor: actor.clone(),
..Default::default()
}),
- author_id: None,
- actor: ai_memory_core::ActorContext::anonymous(),
+ author_id,
+ actor,
})
.await?;
// Auto-commit the result so the supersession lands in git.
@@ -268,6 +271,8 @@ impl Consolidator {
&self,
session_id: SessionId,
dry_run: bool,
+ actor: ai_memory_core::ActorContext,
+ author_id: Option<ai_memory_core::UserId>,
) -> ConsolidatorResult<Vec<ConsolidationOutcome>> {
let observations = self.reader.observations_for_session(session_id).await?;
if observations.is_empty() {
@@ -293,7 +298,7 @@ impl Consolidator {
let mut requests = Vec::with_capacity(batch.updates.len());
let mut outcomes_preview = Vec::with_capacity(batch.updates.len());
for upd in &batch.updates {
- let (req, outcome) = build_update(ws, proj, upd, dry_run)?;
+ let (req, outcome) = build_update(ws, proj, upd, dry_run, &actor, author_id)?;
if self.should_skip_high_resistance_slot_update(ws, proj, &req)? {
debug!(
path = %req.path.as_str(),
@@ -346,6 +351,8 @@ fn build_update(
proj: ProjectId,
upd: &crate::types::ConsolidatedPageUpdate,
dry_run: bool,
+ actor: &ai_memory_core::ActorContext,
+ author_id: Option<ai_memory_core::UserId>,
) -> ConsolidatorResult<(WritePageRequest, ConsolidationOutcome)> {
let final_path = if upd.kind == crate::types::PageKind::Rule {
let slug = slugify_for_rule(&upd.title);
@@ -399,10 +406,11 @@ fn build_update(
title: Some(upd.title.clone()),
admission_ctx: Some(AdmissionContext {
op: AdmissionOp::Consolidate,
+ actor: actor.clone(),
..Default::default()
}),
- author_id: None,
- actor: ai_memory_core::ActorContext::anonymous(),
+ author_id,
+ actor: actor.clone(),
};
let outcome = ConsolidationOutcome {
path,
@@ -891,10 +899,54 @@ mod tests {
tags: Vec::new(),
slot_kind: SlotKind::State,
};
- let (req, _) = build_update(WorkspaceId::new(), ProjectId::new(), &update, true).unwrap();
+ let (req, _) = build_update(
+ WorkspaceId::new(),
+ ProjectId::new(),
+ &update,
+ true,
+ &ai_memory_core::ActorContext::anonymous(),
+ None,
+ )
+ .unwrap();
assert_eq!(req.frontmatter["slot_kind"], "state");
}
+ #[test]
+ fn build_update_stamps_request_actor_and_author() {
+ let update = crate::types::ConsolidatedPageUpdate {
+ path: "notes/x.md".into(),
+ tier: Tier::Episodic,
+ kind: crate::types::PageKind::Fact,
+ title: "X".into(),
+ body_markdown: "body".into(),
+ tags: Vec::new(),
+ slot_kind: SlotKind::State,
+ };
+ let actor = ai_memory_core::ActorContext {
+ user: Some("djalmajr".into()),
+ ..Default::default()
+ };
+ let author = ai_memory_core::UserId::new();
+ let (req, _) = build_update(
+ WorkspaceId::new(),
+ ProjectId::new(),
+ &update,
+ false,
+ &actor,
+ Some(author),
+ )
+ .unwrap();
+ // The write is attributed to the real operator (not the old anonymous).
+ assert_eq!(req.actor.user.as_deref(), Some("djalmajr"));
+ assert_eq!(req.author_id, Some(author));
+ // The admission ctx carries the actor too, so an actor-gated webhook
+ // authorizes by user instead of rejecting an empty actor.
+ assert_eq!(
+ req.admission_ctx.expect("ctx").actor.user.as_deref(),
+ Some("djalmajr")
+ );
+ }
+
#[test]
fn slot_update_preserves_explicit_invariant_frontmatter() {
let update = crate::types::ConsolidatedPageUpdate {
@@ -906,7 +958,15 @@ mod tests {
tags: Vec::new(),
slot_kind: SlotKind::Invariant,
};
- let (req, _) = build_update(WorkspaceId::new(), ProjectId::new(), &update, true).unwrap();
+ let (req, _) = build_update(
+ WorkspaceId::new(),
+ ProjectId::new(),
+ &update,
+ true,
+ &ai_memory_core::ActorContext::anonymous(),
+ None,
+ )
+ .unwrap();
assert_eq!(req.frontmatter["slot_kind"], "invariant");
}
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 87602316..b4b1b023 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -1597,7 +1597,15 @@ async fn process(
if state.consolidate_on_session_end
&& let Some(c) = state.consolidator.as_ref()
{
- match c.consolidate_session(session_id, false).await {
+ match c
+ .consolidate_session(
+ session_id,
+ false,
+ ai_memory_core::ActorContext::anonymous(),
+ None,
+ )
+ .await
+ {
Ok(outcome) => info!(
session = %session_id,
path = %outcome.path,
@@ -1744,7 +1752,14 @@ async fn consolidate_or_synth(
project_id: ProjectId,
) -> anyhow::Result<()> {
if let Some(c) = state.consolidator.as_ref() {
- let outcome = c.consolidate_session(session_id, false).await?;
+ let outcome = c
+ .consolidate_session(
+ session_id,
+ false,
+ ai_memory_core::ActorContext::anonymous(),
+ None,
+ )
+ .await?;
debug!(
session = %session_id,
path = %outcome.path,
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 06d27598..e35764a9 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -1432,6 +1432,7 @@ impl AiMemoryServer {
async fn memory_consolidate(
&self,
Parameters(args): Parameters<ConsolidateArgs>,
+ OptionalParts(parts): OptionalParts,
) -> Result<CallToolResult, McpError> {
let Some(consolidator) = self.consolidator.as_ref() else {
return Err(McpError::internal_error(
@@ -1442,15 +1443,21 @@ impl AiMemoryServer {
let session_id = SessionId::from_str(&args.session_id)
.map_err(|e| McpError::internal_error(e.to_string(), 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
+ // admission webhook authorizes by that actor (rather than the previous
+ // hard-coded anonymous, which an actor-gated webhook rejects).
+ let actor = crate::actor::actor_from_parts(&parts);
+ let author_id = crate::actor::author_id_from_parts(&parts);
if args.multi_page.unwrap_or(false) {
let outcomes = consolidator
- .consolidate_session_multi(session_id, dry)
+ .consolidate_session_multi(session_id, dry, actor, author_id)
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
ok_json(&serde_json::json!({ "outcomes": outcomes }))
} else {
let outcome = consolidator
- .consolidate_session(session_id, dry)
+ .consolidate_session(session_id, dry, actor, author_id)
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
ok_json(&outcome)
@@ -6033,11 +6040,14 @@ mod tests {
async fn memory_consolidate_without_provider_errors_cleanly() {
let (_tmp, _store, server, _ws, _pj) = setup_server().await;
let err = server
- .memory_consolidate(Parameters(ConsolidateArgs {
- session_id: "00000000-0000-0000-0000-000000000000".into(),
- dry_run: Some(true),
- multi_page: Some(false),
- }))
+ .memory_consolidate(
+ Parameters(ConsolidateArgs {
+ session_id: "00000000-0000-0000-0000-000000000000".into(),
+ dry_run: Some(true),
+ multi_page: Some(false),
+ }),
+ OptionalParts(test_parts_default()),
+ )
.await
.expect_err("must reject when no consolidator is configured");
let msg = format!("{err:?}");