Skip to content

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

Rust

fix(hooks): re-run the end path when a resumed session re-ends

AkitaOnRails2819d6ea89ec
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7651e9e4..077d2ee6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Fixed
+- A session that is resumed under the same id after an early `SessionEnd`
+ now re-consolidates when it ends again. The end-of-session guard used to
+ drop any `SessionEnd` for a session with `ended_at` set, so a resumed
+ session's page stayed frozen at the first end's content and the resumed
+ work lived only in raw observations. The guard now distinguishes a
+ duplicate/stale end (no observations newer than `ended_at` — still
+ dropped, which keeps `finalize-session` and late spool drains safe) from
+ a genuine re-end with new work behind it, which re-runs the full end
+ path: heuristic page rewrite, `ended_at` bump, auto-handoff refresh, and
+ the opt-in LLM consolidation ([#152]).
- `bin/ai-memory` no longer fails `install-mcp`, `install-hooks`,
`setup-agent`, `install-instructions`, `install-skills`, `uninstall`,
and `backup` under rootless Docker. Rootless Docker maps container UID
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 6bb66a29..acc072d0 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -919,18 +919,34 @@ async fn process(
)
.await?;
- if matches!(env.event, HookEvent::SessionEnd)
- && !state
+ if matches!(env.event, HookEvent::SessionEnd) {
+ match state
.reader
- .session_is_open_for_scope_agent(session_id, ws, proj, env.agent)
+ .session_end_disposition(session_id, ws, proj, env.agent)
.await?
- {
- info!(
- session = %session_id,
- agent = %env.agent.as_str(),
- "ignoring SessionEnd for missing, mismatched, or already-ended session"
- );
- return Ok(());
+ {
+ ai_memory_store::SessionEndDisposition::Open => {}
+ ai_memory_store::SessionEndDisposition::DropStale => {
+ info!(
+ session = %session_id,
+ agent = %env.agent.as_str(),
+ "ignoring SessionEnd for missing, mismatched, or already-ended session"
+ );
+ return Ok(());
+ }
+ // The agent resumed an ended session under the same id and kept
+ // working (issue #152). Run the full end path again — page
+ // rewrite, ended_at bump, handoff, opt-in LLM consolidation — so
+ // the resumed work reaches the compiled session page instead of
+ // living only in raw observations.
+ ai_memory_store::SessionEndDisposition::ReEndWithNewWork => {
+ info!(
+ session = %session_id,
+ agent = %env.agent.as_str(),
+ "SessionEnd re-ends a resumed session with new work; re-running end path"
+ );
+ }
+ }
}
// Hooks are fire-and-forget and may arrive out of order. Begin the
@@ -3290,6 +3306,127 @@ mod tests {
);
}
+ // Issue #152: an agent that resumes an ended session under the same id
+ // and keeps working must get its page re-compiled by the second
+ // SessionEnd instead of that end being dropped as "already-ended".
+ #[tokio::test]
+ async fn resumed_session_second_end_reruns_end_path() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let sid = "33333333-3333-3333-3333-333333333333";
+ let session_id: SessionId = sid.parse().unwrap();
+ let fire = |event: &str, tool: Option<&str>| {
+ let mut body = serde_json::json!({ "session_id": sid });
+ if let Some(tool) = tool {
+ body["tool_name"] = serde_json::Value::String(tool.into());
+ }
+ HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: event.into(),
+ agent: Some("claude-code".into()),
+ ..Default::default()
+ },
+ body,
+ )
+ };
+
+ // First life: one tool call, then a real end.
+ process(&state, fire("post-tool-use", Some("Bash")), None)
+ .await
+ .unwrap();
+ process(&state, fire("session-end", None), None)
+ .await
+ .unwrap();
+ let disposition = state
+ .reader
+ .session_end_disposition(
+ session_id,
+ state.workspace_id,
+ state.project_id,
+ AgentKind::ClaudeCode,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ disposition,
+ ai_memory_store::SessionEndDisposition::DropStale,
+ "a freshly-ended session with no newer work must drop duplicate ends"
+ );
+ let page_after_first_end = state
+ .reader
+ .recent_pages_for_project(state.workspace_id, state.project_id, 20)
+ .await
+ .unwrap()
+ .into_iter()
+ .find(|p| p.path.as_str().starts_with("sessions/"))
+ .expect("first SessionEnd writes the session page");
+
+ // Second life: the agent resumed the same id and did more work.
+ process(&state, fire("post-tool-use", Some("Edit")), None)
+ .await
+ .unwrap();
+ let disposition = state
+ .reader
+ .session_end_disposition(
+ session_id,
+ state.workspace_id,
+ state.project_id,
+ AgentKind::ClaudeCode,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ disposition,
+ ai_memory_store::SessionEndDisposition::ReEndWithNewWork,
+ "observations after ended_at must mark the session re-endable"
+ );
+
+ process(&state, fire("session-end", None), None)
+ .await
+ .unwrap();
+
+ let page_after_second_end = state
+ .reader
+ .recent_pages_for_project(state.workspace_id, state.project_id, 20)
+ .await
+ .unwrap()
+ .into_iter()
+ .find(|p| p.path.as_str().starts_with("sessions/"))
+ .expect("second SessionEnd keeps the session page");
+ // The rewrite supersedes the page, so the latest version carries a
+ // new page id.
+ assert_ne!(
+ page_after_first_end.id, page_after_second_end.id,
+ "the re-end must rewrite the session page with the resumed work"
+ );
+ assert!(
+ state
+ .reader
+ .latest_open_handoff(state.workspace_id, state.project_id, None)
+ .await
+ .unwrap()
+ .is_some(),
+ "the re-end must refresh the auto-handoff"
+ );
+ // ended_at advanced past the resumed work: the next duplicate end is
+ // dropped again (pins the de1cef2 dedupe behaviour post-re-end).
+ let disposition = state
+ .reader
+ .session_end_disposition(
+ session_id,
+ state.workspace_id,
+ state.project_id,
+ AgentKind::ClaudeCode,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ disposition,
+ ai_memory_store::SessionEndDisposition::DropStale,
+ "after the re-end, ended_at must cover the resumed work again"
+ );
+ }
+
#[tokio::test]
async fn process_accepts_prompt_before_session_start() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 86bd0a59..8a24b094 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -40,8 +40,9 @@ pub use reader::{
ContaminationFinding, ContaminationReport, ContaminationSummary, DecayCandidate,
DerivedIndexStatus, EmbeddingTripleCount, HealthDetail, HealthPage, ObservationHit,
OpenSession, PageAuthor, PageHit, PageHitWithMeta, PageLinks, PageMeta, PageSummary,
- ProjectSummary, ReaderPool, ReindexTargetStatus, RelatedPage, ScopeRow, StatusCounts,
- StoredEmbedding, StoredPageBody, WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,
+ ProjectSummary, ReaderPool, ReindexTargetStatus, RelatedPage, ScopeRow, SessionEndDisposition,
+ StatusCounts, StoredEmbedding, StoredPageBody, WorkspaceScopeRow, WorkspaceSummary,
+ f32_vec_to_bytes,
};
pub use scope::{
ResolvedScope, ScopeName, ScopeResolutionError, ScopeResolver, WORKSPACE_PROJECT_PAIR_REQUIRED,
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 03e2f913..8bf2af44 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -67,6 +67,22 @@ pub struct OpenSession {
pub cwd: Option<String>,
}
+/// How a `SessionEnd` event should treat its target session — see
+/// [`ReaderPool::session_end_disposition`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SessionEndDisposition {
+ /// The session is open in the resolved scope/agent: run the normal end
+ /// path.
+ Open,
+ /// Missing, cross-scope, cross-agent, or already ended with no
+ /// observations after `ended_at`: a duplicate or stale end — drop it.
+ DropStale,
+ /// Already ended, but observations arrived after `ended_at`: the agent
+ /// resumed the session under the same id — run the full end path again
+ /// so the resumed work reaches the compiled page (issue #152).
+ ReEndWithNewWork,
+}
+
/// The latest version of a page's stored content, used as a DB-backed
/// fallback when the on-disk markdown read fails (index/disk skew). The
/// markdown file is the source of truth, but the store keeps a faithful copy
@@ -1067,34 +1083,55 @@ impl ReaderPool {
.await
}
- /// True when a session exists, belongs to the resolved scope and agent, and
- /// is still open. Used by SessionEnd ingestion to avoid synthesizing pages
- /// or handoffs for stale, cross-project, or cross-agent synthetic events.
+ /// How a `SessionEnd` should treat its target session (issue #152).
///
- /// # Errors
- /// Propagates any SQL or pool error.
- pub async fn session_is_open_for_scope_agent(
+ /// The old boolean ("is the session open?") conflated two very different
+ /// ended states: a *duplicate/stale* end (nothing happened since
+ /// `ended_at` — drop it, the reason the guard exists) and a *re-end* of a
+ /// resumed session (the agent reused the id and kept working after the
+ /// first end — the end path must run again or the resumed work never
+ /// reaches the compiled session page).
+ pub async fn session_end_disposition(
&self,
session_id: SessionId,
workspace_id: WorkspaceId,
project_id: ProjectId,
agent_kind: AgentKind,
- ) -> StoreResult<bool> {
+ ) -> StoreResult<SessionEndDisposition> {
let agent = agent_kind.as_str().to_string();
self.with_conn(move |conn| {
- let count: u64 = conn.query_row(
- "SELECT COUNT(*) FROM sessions \
- WHERE id = ?1 AND workspace_id = ?2 AND project_id = ?3 \
- AND agent_kind = ?4 AND ended_at IS NULL",
- params![
- session_id.as_bytes(),
- workspace_id.as_bytes(),
- project_id.as_bytes(),
- agent,
- ],
+ let ended_at: Option<Option<i64>> = conn
+ .query_row(
+ "SELECT ended_at FROM sessions \
+ WHERE id = ?1 AND workspace_id = ?2 AND project_id = ?3 \
+ AND agent_kind = ?4",
+ params![
+ session_id.as_bytes(),
+ workspace_id.as_bytes(),
+ project_id.as_bytes(),
+ agent,
+ ],
+ |row| row.get(0),
+ )
+ .optional()?;
+ let Some(ended_at) = ended_at else {
+ // Missing, cross-scope, or cross-agent: never end it.
+ return Ok(SessionEndDisposition::DropStale);
+ };
+ let Some(ended_at) = ended_at else {
+ return Ok(SessionEndDisposition::Open);
+ };
+ let newer: u64 = conn.query_row(
+ "SELECT COUNT(*) FROM observations \
+ WHERE session_id = ?1 AND created_at > ?2",
+ params![session_id.as_bytes(), ended_at],
|row| row.get(0),
)?;
- Ok(count > 0)
+ if newer > 0 {
+ Ok(SessionEndDisposition::ReEndWithNewWork)
+ } else {
+ Ok(SessionEndDisposition::DropStale)
+ }
})
.await
}