Skip to content

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

Rust

feat(consolidation): surface session agent origin (#506)

YANGYU6ff3e526322d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e22e40de..05e18336 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- Generated `sessions/<id>.md` pages now surface the originating harness as
+ `agent` frontmatter alongside `session_id`. The value comes from the
+ persisted session row, so LLM rewrites, compaction checkpoints, spool
+ drains, and superseding versions do not mistake the later writer for the
+ origin; manual page writes remain unattributed. (#494)
+
## [1.32.2] - 2026-08-26
### Fixed
diff --git a/crates/ai-memory-consolidate/src/consolidator.rs b/crates/ai-memory-consolidate/src/consolidator.rs
index 1bddcf03..379687f8 100644
--- a/crates/ai-memory-consolidate/src/consolidator.rs
+++ b/crates/ai-memory-consolidate/src/consolidator.rs
@@ -7,7 +7,7 @@
use std::sync::Arc;
-use ai_memory_core::{Observation, PagePath, ProjectId, SessionId, Tier, WorkspaceId};
+use ai_memory_core::{AgentKind, Observation, PagePath, ProjectId, SessionId, Tier, WorkspaceId};
use ai_memory_llm::{ChatMessage, ChatRequest, LlmError, LlmProvider, Role, complete_structured};
use ai_memory_store::{ReaderPool, WriterHandle};
use ai_memory_wiki::{AdmissionContext, AdmissionOp, Wiki, WritePageRequest};
@@ -141,6 +141,7 @@ impl Consolidator {
}
let (ws, proj) = self.resolve_target(session_id).await?;
+ let agent_kind = self.resolve_agent_origin(session_id).await?;
let path = PagePath::new(format!("sessions/{session_id}.md"))?;
// Run the blocking admission chain BEFORE the LLM so a rejected
@@ -188,7 +189,7 @@ impl Consolidator {
);
let page: ConsolidatedPage = complete_structured(&*self.llm, request).await?;
- let frontmatter = build_frontmatter(&page);
+ let frontmatter = build_frontmatter(&page, session_id, agent_kind);
let id = self
.wiki
.write_page(WritePageRequest {
@@ -278,6 +279,16 @@ impl Consolidator {
.unwrap_or((self.workspace_id, self.project_id)))
}
+ /// Resolve the session's creating harness from the persisted session row.
+ /// This is deliberately independent of the actor or client performing the
+ /// consolidation: `agent` in page frontmatter means origin, not writer.
+ async fn resolve_agent_origin(&self, session_id: SessionId) -> ConsolidatorResult<AgentKind> {
+ self.reader
+ .session_agent_kind(session_id)
+ .await?
+ .ok_or(ConsolidatorError::SessionNotFound(session_id))
+ }
+
fn should_skip_high_resistance_slot_update(
&self,
workspace_id: WorkspaceId,
@@ -426,6 +437,7 @@ impl Consolidator {
// Resolve the target from where the observations landed — see
// `resolve_target` / `consolidate_session` for the rationale.
let (ws, proj) = self.resolve_target(session_id).await?;
+ let agent_kind = self.resolve_agent_origin(session_id).await?;
// Preflight admission BEFORE the LLM (see `consolidate_session`). The
// session page is the canonical episodic anchor, so it stands in for
@@ -477,6 +489,9 @@ impl Consolidator {
let mut outcomes_preview = Vec::with_capacity(batch.updates.len());
for upd in &batch.updates {
let (mut req, mut outcome) = build_update(ws, proj, upd, false, &actor, author_id)?;
+ if req.path == anchor {
+ stamp_session_origin(&mut req.frontmatter, session_id, agent_kind);
+ }
// A slot the engine writes belongs to the operator whose session
// produced it, and `build_update` keeps the model's path verbatim
// for every non-Rule kind — so the path here is attacker-reachable
@@ -1221,13 +1236,18 @@ fn usable_summary(raw: Option<&str>, title: &str) -> Option<String> {
Some(text.to_owned())
}
-fn build_frontmatter(page: &ConsolidatedPage) -> serde_json::Value {
+fn build_frontmatter(
+ page: &ConsolidatedPage,
+ session_id: SessionId,
+ agent_kind: AgentKind,
+) -> serde_json::Value {
let mut map = serde_json::Map::new();
map.insert(
"title".into(),
serde_json::Value::String(page.title.clone()),
);
map.insert("tier".into(), serde_json::Value::String("episodic".into()));
+ stamp_session_origin_map(&mut map, session_id, agent_kind);
if !page.tags.is_empty() {
let tags = page
.tags
@@ -1243,6 +1263,31 @@ fn build_frontmatter(page: &ConsolidatedPage) -> serde_json::Value {
serde_json::Value::Object(map)
}
+fn stamp_session_origin(
+ frontmatter: &mut serde_json::Value,
+ session_id: SessionId,
+ agent_kind: AgentKind,
+) {
+ if let Some(map) = frontmatter.as_object_mut() {
+ stamp_session_origin_map(map, session_id, agent_kind);
+ }
+}
+
+fn stamp_session_origin_map(
+ map: &mut serde_json::Map<String, serde_json::Value>,
+ session_id: SessionId,
+ agent_kind: AgentKind,
+) {
+ map.insert(
+ "session_id".into(),
+ serde_json::Value::String(session_id.to_string()),
+ );
+ map.insert(
+ "agent".into(),
+ serde_json::Value::String(agent_kind.as_str().into()),
+ );
+}
+
fn one_line(s: &str) -> String {
s.lines()
.map(str::trim)
@@ -1694,16 +1739,24 @@ mod tests {
tags: Vec::new(),
summary: Some("Bounded the queue so backpressure is testable.".into()),
};
+ let session_id = SessionId::new();
+ let frontmatter = build_frontmatter(&page, session_id, AgentKind::Codex);
assert_eq!(
- build_frontmatter(&page)["summary"],
+ frontmatter["summary"],
"Bounded the queue so backpressure is testable."
);
+ assert_eq!(frontmatter["session_id"], session_id.to_string());
+ assert_eq!(frontmatter["agent"], "codex");
let unusable = ConsolidatedPage {
summary: Some("- **session_id:** `9f2c`".into()),
..page
};
- assert!(build_frontmatter(&unusable).get("summary").is_none());
+ assert!(
+ build_frontmatter(&unusable, SessionId::new(), AgentKind::Codex)
+ .get("summary")
+ .is_none()
+ );
}
#[test]
@@ -2153,6 +2206,103 @@ mod tests {
(store, wiki, session, ws, proj)
}
+ /// Attribution follows the persisted session, not the operator or client
+ /// that happens to request consolidation. Re-running the write supersedes
+ /// the page with the same immutable origin.
+ #[tokio::test]
+ async fn single_page_consolidation_stamps_and_preserves_session_origin() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (store, wiki, session, ws, proj) = batch_fixture(tmp.path()).await;
+ let response = serde_json::json!({
+ "title": "Queue decision",
+ "body_markdown": "The queue is bounded.",
+ "tags": [],
+ });
+ let path = PagePath::new(format!("sessions/{session}.md")).unwrap();
+
+ for actor in [actor_named("alice"), actor_named("bob")] {
+ Consolidator::new(
+ store.reader.clone(),
+ store.writer.clone(),
+ wiki.clone(),
+ Arc::new(ScriptedLlm(response.clone())),
+ ws,
+ proj,
+ )
+ .consolidate_session(session, false, actor, None, None)
+ .await
+ .unwrap();
+
+ let stored = wiki.read_page(ws, proj, &path).unwrap();
+ assert_eq!(stored.frontmatter["session_id"], session.to_string());
+ assert_eq!(
+ stored.frontmatter["agent"], "claude-code",
+ "origin comes from sessions.agent_kind, never the requesting actor"
+ );
+ }
+ }
+
+ /// The multi-page provider path uses the same provenance contract for its
+ /// canonical session anchor, while non-session pages remain outside item 1
+ /// of #494.
+ #[tokio::test]
+ async fn batch_consolidation_stamps_only_the_session_anchor_origin() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (store, wiki, session, ws, proj) = batch_fixture(tmp.path()).await;
+ let session_path = format!("sessions/{session}.md");
+ let response = serde_json::json!({
+ "rationale": "test provenance",
+ "updates": [
+ {
+ "path": session_path,
+ "tier": "episodic",
+ "kind": "fact",
+ "title": "Session narrative",
+ "body_markdown": "Session body.",
+ "tags": []
+ },
+ {
+ "path": "concepts/queue.md",
+ "tier": "semantic",
+ "kind": "fact",
+ "title": "Queue",
+ "body_markdown": "Concept body.",
+ "tags": []
+ }
+ ]
+ });
+
+ Consolidator::new(
+ store.reader.clone(),
+ store.writer.clone(),
+ wiki.clone(),
+ Arc::new(ScriptedLlm(response)),
+ ws,
+ proj,
+ )
+ .consolidate_session_multi(
+ session,
+ false,
+ ai_memory_core::ActorContext::anonymous(),
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+
+ let session_page = wiki
+ .read_page(ws, proj, &PagePath::new(session_path).unwrap())
+ .unwrap();
+ assert_eq!(session_page.frontmatter["session_id"], session.to_string());
+ assert_eq!(session_page.frontmatter["agent"], "claude-code");
+
+ let concept = wiki
+ .read_page(ws, proj, &PagePath::new("concepts/queue.md").unwrap())
+ .unwrap();
+ assert!(concept.frontmatter.get("agent").is_none());
+ assert!(concept.frontmatter.get("session_id").is_none());
+ }
+
/// A batch whose single update targets `path` — the model chooses this
/// string, and `build_update` keeps it verbatim for non-Rule kinds.
fn batch_targeting(path: &str, body: &str) -> serde_json::Value {
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 0db2fb21..38ed071f 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -2630,6 +2630,7 @@ async fn process_authorized(
session_id,
ws,
proj,
+ admitted.agent_kind(),
checkpoint_label,
session_actor.clone(),
)
@@ -2680,7 +2681,8 @@ async fn process_authorized(
}
}
}
- let new_page = synthesize_session_page(ws, proj, session_id, &observations);
+ let new_page =
+ synthesize_session_page(ws, proj, session_id, admitted.agent_kind(), &observations);
let page_id = state
.wiki
.write_page(ai_memory_wiki::WritePageRequest {
@@ -3138,6 +3140,7 @@ async fn consolidate_or_synth(
session_id: SessionId,
workspace_id: WorkspaceId,
project_id: ProjectId,
+ agent_kind: AgentKind,
checkpoint_label: &str,
actor: ai_memory_core::ActorContext,
) -> anyhow::Result<()> {
@@ -3194,7 +3197,13 @@ async fn consolidate_or_synth(
if observations.is_empty() {
return Ok(());
}
- let new_page = synthesize_session_page(workspace_id, project_id, session_id, &observations);
+ let new_page = synthesize_session_page(
+ workspace_id,
+ project_id,
+ session_id,
+ agent_kind,
+ &observations,
+ );
state
.wiki
.write_page(ai_memory_wiki::WritePageRequest {
@@ -3433,6 +3442,7 @@ mod tests {
session_id,
state.workspace_id,
state.project_id,
+ AgentKind::ClaudeCode,
"pre-compact",
ai_memory_core::ActorContext::anonymous(),
)
@@ -3515,6 +3525,7 @@ mod tests {
session_id,
state.workspace_id,
state.project_id,
+ AgentKind::ClaudeCode,
"pre-compact",
ai_memory_core::ActorContext::anonymous(),
)
@@ -3551,6 +3562,7 @@ mod tests {
session_id,
state.workspace_id,
state.project_id,
+ AgentKind::ClaudeCode,
"pre-compact",
ai_memory_core::ActorContext::anonymous(),
)
@@ -9077,7 +9089,13 @@ mod tests {
.observations_for_session(session_id)
.await
.unwrap();
- let page = synthesize_session_page(workspace_id, project_id, session_id, &observations);
+ let page = synthesize_session_page(
+ workspace_id,
+ project_id,
+ session_id,
+ AgentKind::Codex,
+ &observations,
+ );
let page_id = state
.wiki
.write_page(ai_memory_wiki::WritePageRequest {
diff --git a/crates/ai-memory-hooks/src/synth.rs b/crates/ai-memory-hooks/src/synth.rs
index c8b55aca..84b5a19d 100644
--- a/crates/ai-memory-hooks/src/synth.rs
+++ b/crates/ai-memory-hooks/src/synth.rs
@@ -9,8 +9,8 @@
use std::collections::BTreeMap;
use ai_memory_core::{
- NewPage, Observation, ObservationKind, PagePath, ProjectId, SessionId, Tier, WorkspaceId,
- looks_like_scaffolding,
+ AgentKind, NewPage, Observation, ObservationKind, PagePath, ProjectId, SessionId, Tier,
+ WorkspaceId, looks_like_scaffolding,
};
use jiff::tz::TimeZone;
@@ -27,6 +27,7 @@ pub fn synthesize_session_page(
workspace_id: WorkspaceId,
project_id: ProjectId,
session_id: SessionId,
+ agent_kind: AgentKind,
observations: &[Observation],
) -> NewPage {
// One tally for the whole page: the body renderer and the summary builder
@@ -37,6 +38,10 @@ pub fn synthesize_session_page(
let mut frontmatter_json = serde_json::json!({
"title": title,
"session_id": session_id.to_string(),
+ // Origin, not writer: callers pass the immutable value persisted on
+ // the session row, so checkpoints and later superseding versions keep
+ // naming the harness that produced the session.
+ "agent": agent_kind.as_str(),
"tier": "episodic",
});
let summary = session_summary(&tally);
@@ -504,6 +509,7 @@ mod tests {
WorkspaceId::new(),
ProjectId::new(),
SessionId::new(),
+ AgentKind::Codex,
&lifecycle_only,
);
assert!(page.frontmatter_json.get("summary").is_none());
@@ -529,8 +535,10 @@ mod tests {
WorkspaceId::new(),
ProjectId::new(),
SessionId::new(),
+ AgentKind::Codex,
&observations,
);
+ assert_eq!(page.frontmatter_json["agent"], "codex");
assert_eq!(
page.frontmatter_json["summary"],
serde_json::json!("1 prompt, 1 completed tool call across Bash, over 5m.")
@@ -722,6 +730,7 @@ mod tests {
WorkspaceId::new(),
ProjectId::new(),
SessionId::new(),
+ AgentKind::Codex,
&observations,
);
assert!(page.title.contains("build the thing"));
@@ -744,6 +753,7 @@ mod tests {
WorkspaceId::new(),
ProjectId::new(),
SessionId::new(),
+ AgentKind::Codex,
&observations,
);
assert!(page.body.contains("`Bash`: 1"));
@@ -759,6 +769,7 @@ mod tests {
WorkspaceId::new(),
ProjectId::new(),
SessionId::new(),
+ AgentKind::Codex,
&[custom],
);
@@ -775,6 +786,7 @@ mod tests {
WorkspaceId::new(),
ProjectId::new(),
SessionId::new(),
+ AgentKind::Codex,
&observations,
);
@@ -794,6 +806,7 @@ mod tests {
WorkspaceId::new(),
ProjectId::new(),
SessionId::new(),
+ AgentKind::Codex,
&observations,
);
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 4ee6c02e..e2da2143 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -2796,6 +2796,33 @@ impl ReaderPool {
.await
}
+ /// Look up the immutable harness identity stored for a session.
+ ///
+ /// Machine-generated session pages use this as their origin metadata.
+ /// Reading it from the session row, rather than from the request that
+ /// happens to trigger consolidation, keeps spool drains and later
+ /// superseding writes attributed to the harness that created the session.
+ /// Returns `None` when no such session row exists.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn session_agent_kind(
+ &self,
+ session_id: SessionId,
+ ) -> StoreResult<Option<AgentKind>> {
+ self.with_conn(move |conn| {
+ let stored: Option<String> = conn
+ .query_row(
+ "SELECT agent_kind FROM sessions WHERE id = ?1",
+ params![session_id.as_bytes()],
+ |row| row.get(0),
+ )
+ .optional()?;
+ Ok(stored.map(|value| AgentKind::from_wire(&value)))
+ })
+ .await
+ }
+
/// The operator a session belongs to (an
/// [`ai_memory_core::IdentityKey::storage_key`] string), as recorded at
/// session start.
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 660fa050..213c5743 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -85,7 +85,10 @@ from hook paths.
use `ai-memory finalize-session` for Codex, or
`ai-memory finalize-session --agent antigravity-cli` for Antigravity CLI.
The command selects the latest matching open session and enters the same
- canonical SessionEnd path as a native hook.
+ canonical SessionEnd path as a native hook. Generated session-page
+ frontmatter records `session_id` plus the immutable `sessions.agent_kind`
+ as `agent`; it describes the page's harness origin, not the later writer.
+ Manual page writes do not receive inferred agent metadata.
4. When `AI_MEMORY_LLM_PROVIDER` is set, `memory_consolidate` rewrites
that summary into a richer durable page or fans out into a
multi-page batch under `concepts/`, `decisions/`, `gotchas/`. Consolidation
diff --git a/docs/usage.md b/docs/usage.md
index 5c211ca2..0e9ce427 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -68,6 +68,13 @@ When Claude Code or Codex compact their working context, the
compaction, the agent can recover the summary via `memory_recent` even
though its raw chat history was compacted away.
+Generated session pages carry `session_id` and `agent` in frontmatter. The
+`agent` value is the originating harness stored on the session (for example,
+`claude-code` or `codex`), not the client or operator that later requested a
+consolidation. Checkpoints and superseding versions therefore keep the same
+origin. Manual `memory_write_page` and `ai-memory write-page` calls do not
+infer an agent.
+
## Proactive memory queries
Hooks handle capture without prompting. Proactive querying depends on