Skip to content

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

Rust

fix(hooks): preserve handoffs across empty sessions (#386)

AkitaOnRails78904b82ed6a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6d523afe..c1423f53 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
expose a stable session identifier (#385).
### Fixed
+- Lifecycle-only sessions containing only `SessionStart` / `SessionEnd` now
+ close without generating an empty session page, fallback handoff, or LLM
+ consolidation job. Startup handoff claims are bound to the native receiver
+ session when clients expose one; if that receiver exits without substantive
+ work, the same transaction that ends it returns the accepted handoff to the
+ open pool. Tool-bearing zero-prompt sessions remain substantive. Shipped
+ Claude Code, Codex, OpenCode, Command Code, Kiro, Antigravity, Devin, Cursor,
+ Gemini CLI, and Kimi Code delivery paths forward their available session ids
+ so an empty receiver cannot permanently consume real work (#386).
- The `bin/ai-memory` wrapper now detects rootless mode and SELinux under
podman, so host-file commands stop failing with `Permission denied (os error
13)` on podman-based distros. Both the `-u 0:0` remap and `--security-opt
diff --git a/README.md b/README.md
index 2f8d4571..f3333078 100644
--- a/README.md
+++ b/README.md
@@ -849,7 +849,11 @@ rule-based output. Add an LLM provider
when you want LLM consolidation (on PreCompact, on demand via
`memory_consolidate`, or opt-in at session end with
`AI_MEMORY_CONSOLIDATE_ON_SESSION_END`), richer linting, and bootstrap.
-Session end always writes a rule-based summary page + handoff either way.
+Substantive session ends always write a rule-based summary page + handoff either
+way. A session containing only `SessionStart` / `SessionEnd` boundaries is
+closed without a page, handoff, or provider job. When that empty session had
+accepted startup context, its session-bound handoff is returned to the open
+pool for the next receiver instead of being lost.
When the session-end opt-in is enabled, provider work is durably queued after
those deterministic writes and handled by one bounded server worker, so hook
drain latency does not cancel it. Failed jobs retry with backoff and survive a
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index 1cd9b881..955659d4 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -618,11 +618,10 @@ where
if agent_kind.session_start_injects_handoff() {
let client = build_client();
let bearer = hook_spool::resolve_bearer(&client, &dd, args.auth_token.as_deref()).await;
- let native_session_qs = canonical_session_id
- .as_deref()
- .map_or_else(String::new, |session_id| {
- format!("&session_id={}", url_encode(session_id))
- });
+ let native_session_qs = canonical_session_id.as_deref().map_or_else(
+ || session_qs.clone(),
+ |session_id| format!("&session_id={}", url_encode(session_id)),
+ );
let handoff_url = format!(
"{base}/handoff?agent={}{qs}{managed_qs}{native_session_qs}",
args.agent
@@ -1142,6 +1141,57 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn devin_generated_session_id_reaches_startup_handoff_claim() {
+ let tmp = tempfile::tempdir().unwrap();
+ let data_dir = tmp.path().join("data");
+ let (base, mut requests) = serve_requests("200 OK", "DEVIN-HANDOFF").await;
+ let mut args = devin_hook_args("session-start");
+ args.server_url = base;
+ let mut stdout = Vec::new();
+
+ run_with_payload(
+ Some(data_dir.clone()),
+ args,
+ serde_json::json!({
+ "hook_event_name": "SessionStart",
+ "source": "startup"
+ })
+ .to_string(),
+ &mut stdout,
+ |_| Ok(()),
+ )
+ .await
+ .unwrap();
+
+ let mut recorded = Vec::new();
+ while let Some(request) = first_request(&mut requests).await {
+ recorded.push(request);
+ }
+ assert!(
+ recorded
+ .iter()
+ .any(|request| request.starts_with("POST /hook")),
+ "session start must be posted: {recorded:?}"
+ );
+ let get = recorded
+ .iter()
+ .find(|request| request.starts_with("GET /handoff?"))
+ .expect("startup handoff must be fetched");
+ let request_param = |request: &str| {
+ request
+ .split_whitespace()
+ .nth(1)
+ .and_then(|target| query_param(target, "session_id"))
+ .map(str::to_owned)
+ };
+ assert_eq!(
+ request_param(get).as_deref(),
+ stored_session_id(&data_dir, AgentKind::Devin).as_deref(),
+ "the destructive startup claim must use the generated receiver id: {recorded:?}"
+ );
+ }
+
#[tokio::test]
async fn devin_post_tool_use_real_fixture_without_session_id_or_cwd_is_accepted() {
let tmp = tempfile::tempdir().unwrap();
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 1e3a29b7..597e69cf 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -7483,8 +7483,8 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessio
"Devin session-start.sh must fetch handoff"
);
assert!(
- script_content.contains("$SERVER/handoff?agent=devin${QS}"),
- "Devin session-start.sh must use the registered /handoff endpoint with agent=devin"
+ script_content.contains("$SERVER/handoff?agent=devin${QS}${SID_QS}"),
+ "Devin session-start.sh must bind the handoff claim to its generated session id"
);
assert!(
!script_content.contains("/handoff/latest"),
@@ -7500,6 +7500,27 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessio
);
}
+ #[test]
+ fn startup_handoff_scripts_forward_native_session_ids() {
+ let hooks_root = Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("..")
+ .join("..")
+ .join("hooks");
+ for agent in ["claude-code", "codex", "opencode", "cursor", "gemini-cli"] {
+ let script = fs::read_to_string(hooks_root.join(agent).join("session-start.sh"))
+ .unwrap()
+ .replace("\r\n", "\n");
+ assert!(
+ script.contains("SESSION_ID=$(ai_memory_extract_session_id \"$PAYLOAD\")"),
+ "{agent} must extract the native receiver session id"
+ );
+ assert!(
+ script.contains("${SESSION_QS}"),
+ "{agent} must forward the native receiver session id to /handoff"
+ );
+ }
+ }
+
#[test]
fn grok_placeholder_expansion_resolves_values_and_defaults() {
let expanded = expand_grok_placeholders_with("${HOST}/mcp ${TOKEN:-fallback}", |name| {
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index b1d8d1ff..3af8a431 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -1183,9 +1183,9 @@ async fn fetch_and_accept_handoff(
// session, so resolving it twice was harmless); the handoff is single-use
// and had no second chance.
let managed = fetch_managed_context(state, &query, agent).await?;
- // `/handoff` has no session_id in the request — `per_session` mode
- // therefore falls back to the single slot (graceful degradation),
- // while `per_actor` keys by `user` alone.
+ // Keep the active-project key compatible with MCP transports: the native
+ // session id is carried separately below to bind a destructive handoff
+ // claim to its exact receiver.
let actor_key = ai_memory_core::ActorKey {
user: actor.as_ref().map(IdentityKey::storage_key),
session_id: None,
@@ -1276,6 +1276,26 @@ async fn fetch_and_accept_handoff(
}
None => (None, None),
};
+ let accepting_session = query
+ .session_id
+ .as_deref()
+ .filter(|value| !value.trim().is_empty())
+ .map(resolve_native_session_id);
+ let receiving_session = if handoff.is_some() {
+ match accepting_session {
+ Some(id) => Some(NewSession {
+ id,
+ workspace_id: ws,
+ project_id: proj,
+ agent_kind: agent,
+ cwd: query.cwd.as_deref().map(std::path::PathBuf::from),
+ actor_user: owner_stamp_for_event(state, actor.as_ref()).await,
+ }),
+ None => None,
+ }
+ } else {
+ None
+ };
let acceptance = if handoff.is_some() || managed.is_some() {
state
.writer
@@ -1287,12 +1307,13 @@ async fn fetch_and_accept_handoff(
workspace_id: ws,
project_id: proj,
accepting_agent: agent,
- accepting_session: None,
+ accepting_session,
accepting_user: actor.as_ref().map(IdentityKey::storage_key),
owner_filter,
receiving_cwd: query.cwd.clone(),
}),
managed.as_ref().map(|managed| managed.run_id),
+ receiving_session,
)
.await?
} else {
@@ -2206,7 +2227,10 @@ async fn process(
Ok(None) => debug!("wiki clean during SessionEnd recovery"),
Err(e) => warn!(error = %e, "SessionEnd recovery auto-commit failed"),
}
- enqueue_session_end_consolidation(state, session_id, ws, proj).await?;
+ let observations = state.reader.observations_for_session(session_id).await?;
+ if !is_lifecycle_only_session(&observations) {
+ enqueue_session_end_consolidation(state, session_id, ws, proj).await?;
+ }
if let Some(key) = env.ingest_key {
let completed = state
.writer
@@ -2437,10 +2461,45 @@ async fn process(
warn!(error = %e, "PreCompact/PostCompaction consolidation failed; continuing");
}
- // On SessionEnd, synthesize the summary page, end the session, and
- // auto-create a handoff so the next agent can pick up.
+ // On SessionEnd, close boundary-only sessions without generated artifacts.
+ // Substantive sessions synthesize the summary page and auto-handoff below.
if matches!(env.event, HookEvent::SessionEnd) {
- let observations = state.reader.observations_for_session(session_id).await?;
+ let mut observations = state.reader.observations_for_session(session_id).await?;
+ if is_lifecycle_only_session(&observations) {
+ let outcome = state.writer.end_lifecycle_only_session(session_id).await?;
+ match outcome {
+ ai_memory_store::LifecycleOnlyEndOutcome::Ended { reopened_handoff } => {
+ let commit_msg = format!(
+ "lifecycle-only session {}",
+ short_id(&session_id.to_string()),
+ );
+ match state.wiki.commit_all(&commit_msg) {
+ Ok(Some(oid)) => debug!(commit = %oid, "lifecycle-only log auto-commit"),
+ Ok(None) => debug!("wiki clean after lifecycle-only SessionEnd"),
+ Err(e) => warn!(error = %e, "lifecycle-only log auto-commit failed"),
+ }
+ info!(
+ session = %session_id,
+ reopened_handoff = ?reopened_handoff,
+ "lifecycle-only session ended without summary, handoff, or consolidation",
+ );
+ if let Some(key) = ingest_key {
+ state.writer.complete_observation_ingest(proj, key).await?;
+ }
+ return Ok(());
+ }
+ ai_memory_store::LifecycleOnlyEndOutcome::Substantive => {
+ observations = state.reader.observations_for_session(session_id).await?;
+ debug!(
+ session = %session_id,
+ "substantive work raced lifecycle-only SessionEnd; using normal end path",
+ );
+ // The writer observed substantive work, so the refreshed
+ // set cannot still satisfy the lifecycle-only predicate.
+ debug_assert!(!is_lifecycle_only_session(&observations));
+ }
+ }
+ }
let new_page = synthesize_session_page(ws, proj, session_id, &observations);
let page_id = state
.wiki
@@ -2609,14 +2668,7 @@ fn parse_session_owner(owner: Option<String>) -> anyhow::Result<Option<IdentityK
fn resolve_session_id(env: &HookEnvelope) -> anyhow::Result<SessionId> {
if let Some(raw) = &env.session_id {
- // Accept either a UUID (canonical) or any string, hashing the
- // latter to a deterministic UUID v5 so each agent's session id
- // maps cleanly into our schema.
- if let Ok(id) = SessionId::from_str(raw) {
- return Ok(id);
- }
- let uuid = Uuid::new_v5(&Uuid::NAMESPACE_OID, raw.as_bytes());
- return Ok(SessionId(uuid));
+ return Ok(resolve_native_session_id(raw));
}
if matches!(env.event, HookEvent::SessionStart) {
return Ok(SessionId::new());
@@ -2624,6 +2676,23 @@ fn resolve_session_id(env: &HookEnvelope) -> anyhow::Result<SessionId> {
anyhow::bail!("hook payload missing session_id and event is not session-start")
}
+fn resolve_native_session_id(raw: &str) -> SessionId {
+ // Accept either a UUID (canonical) or any string, hashing the latter to a
+ // deterministic UUID v5 so hook POSTs and startup GETs share one key.
+ SessionId::from_str(raw)
+ .unwrap_or_else(|_| SessionId(Uuid::new_v5(&Uuid::NAMESPACE_OID, raw.as_bytes())))
+}
+
+fn is_lifecycle_only_session(observations: &[ai_memory_core::Observation]) -> bool {
+ !observations.is_empty()
+ && observations.iter().all(|observation| {
+ matches!(
+ observation.kind,
+ ObservationKind::SessionStart | ObservationKind::SessionEnd
+ )
+ })
+}
+
fn build_auto_handoff(
workspace_id: WorkspaceId,
project_id: ProjectId,
@@ -5952,11 +6021,8 @@ mod tests {
);
}
- /// SessionEnd must always write the heuristic `sessions/<id>.md` page,
- /// even with `consolidate_on_session_end` enabled but no LLM provider:
- /// the opt-in LLM pass is additive and guarded by a present
- /// `consolidator`, so flag-on + no-provider degrades to today's
- /// deterministic behavior (issue #40 — no regression).
+ /// A substantive SessionEnd must write the heuristic `sessions/<id>.md`
+ /// page even with `consolidate_on_session_end` enabled but no LLM provider.
#[tokio::test]
async fn session_end_writes_heuristic_page_even_with_consolidate_flag_on() {
let tmp = TempDir::new().unwrap();
@@ -5964,7 +6030,7 @@ mod tests {
state.consolidate_on_session_end = true; // flag on; consolidator stays None
let sid = "11111111-1111-1111-1111-111111111111";
- for event in ["session-start", "session-end"] {
+ for event in ["session-start", "user-prompt-submit", "session-end"] {
let env = HookEnvelope::from_query_and_body(
HookQuery {
event: event.into(),
@@ -5990,6 +6056,154 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn lifecycle_only_session_ends_without_page_handoff_or_consolidation() {
+ let tmp = TempDir::new().unwrap();
+ let mut state = make_state(&tmp).await;
+ let llm = Arc::new(RecordingLlm(Mutex::new(None)));
+ state.consolidator = Some(Arc::new(Consolidator::new(
+ state.reader.clone(),
+ state.writer.clone(),
+ state.wiki.clone(),
+ llm,
+ state.workspace_id,
+ state.project_id,
+ )));
+ state.consolidate_on_session_end = true;
+ state.session_consolidation_notify = Some(Arc::new(tokio::sync::Notify::new()));
+ let sid = "12121212-1212-1212-1212-121212121212";
+ let fire = |event: &str, key: Option<&str>| {
+ HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: event.into(),
+ agent: Some("claude-code".into()),
+ ingest_key: key.map(str::to_string),
+ ..Default::default()
+ },
+ serde_json::json!({ "session_id": sid }),
+ )
+ };
+
+ process(&state, fire("session-start", None), None, Vec::new())
+ .await
+ .unwrap();
+ process(
+ &state,
+ fire("session-end", Some("boundary-end")),
+ None,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+ process(
+ &state,
+ fire("session-end", Some("boundary-end")),
+ None,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+
+ let pages = state
+ .reader
+ .recent_pages_for_project(state.workspace_id, state.project_id, 20)
+ .await
+ .unwrap();
+ assert!(
+ pages
+ .iter()
+ .all(|page| !page.path.as_str().starts_with("sessions/"))
+ );
+ assert!(
+ state
+ .reader
+ .latest_open_handoff(
+ state.workspace_id,
+ state.project_id,
+ None,
+ ai_memory_core::OwnerFilter::Any,
+ )
+ .await
+ .unwrap()
+ .is_none()
+ );
+ assert_eq!(
+ state
+ .reader
+ .latest_completed_session_for_project(state.workspace_id, state.project_id)
+ .await
+ .unwrap(),
+ Some(sid.parse().unwrap())
+ );
+ let now = Timestamp::now().as_microsecond();
+ assert!(
+ state
+ .writer
+ .claim_session_consolidation(now, now - 1)
+ .await
+ .unwrap()
+ .is_none(),
+ "lifecycle-only sessions must not enter provider recovery"
+ );
+ assert_eq!(
+ state
+ .reader
+ .observations_for_session(sid.parse().unwrap())
+ .await
+ .unwrap()
+ .len(),
+ 2,
+ "the completed keyed replay must not append another boundary event"
+ );
+ }
+
+ #[tokio::test]
+ async fn tool_bearing_session_without_prompt_still_writes_page_and_handoff() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let sid = "13131313-1313-1313-1313-131313131313";
+ for event in ["session-start", "pre-tool-use", "session-end"] {
+ let env = HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: event.into(),
+ agent: Some("claude-code".into()),
+ ..Default::default()
+ },
+ serde_json::json!({
+ "session_id": sid,
+ "tool_name": "Read",
+ "tool_input": {"file_path": "README.md"}
+ }),
+ );
+ process(&state, env, None, Vec::new()).await.unwrap();
+ }
+
+ let pages = state
+ .reader
+ .recent_pages_for_project(state.workspace_id, state.project_id, 20)
+ .await
+ .unwrap();
+ assert!(
+ pages
+ .iter()
+ .any(|page| page.path.as_str().starts_with("sessions/"))
+ );
+ assert!(
+ state
+ .reader
+ .latest_open_handoff(
+ state.workspace_id,
+ state.project_id,
+ None,
+ ai_memory_core::OwnerFilter::Any,
+ )
+ .await
+ .unwrap()
+ .is_some(),
+ "tool activity is substantive even without a user prompt"
+ );
+ }
+
#[tokio::test]
async fn stop_does_not_end_session() {
let tmp = TempDir::new().unwrap();
@@ -6212,7 +6426,7 @@ mod tests {
let state = make_state(&tmp).await;
let run_id = ManagedRunId::new().to_string();
let managed_session = SessionId::new();
- for event in ["session-start", "session-end"] {
+ for event in ["session-start", "user-prompt", "session-end"] {
let envelope = HookEnvelope::from_query_and_body(
HookQuery {
event: event.into(),
@@ -6246,7 +6460,7 @@ mod tests {
);
let direct_session = SessionId::new();
- for event in ["session-start", "session-end"] {
+ for event in ["session-start", "user-prompt", "session-end"] {
let envelope = HookEnvelope::from_query_and_body(
HookQuery {
event: event.into(),
@@ -6571,7 +6785,7 @@ mod tests {
.await;
let cwd = tmp.path().to_string_lossy().into_owned();
let session = SessionId::new().to_string();
- for event in ["session-start", "session-end"] {
+ for event in ["session-start", "user-prompt", "session-end"] {
process(
&state,
session_envelope(event, &session, &cwd),
@@ -6605,7 +6819,7 @@ mod tests {
let default_state = make_state(&default_tmp).await;
let default_cwd = default_tmp.path().to_string_lossy().into_owned();
let default_session = SessionId::new().to_string();
- for event in ["session-start", "session-end"] {
+ for event in ["session-start", "user-prompt", "session-end"] {
process(
&default_state,
session_envelope(event, &default_session, &default_cwd),
@@ -6650,7 +6864,7 @@ mod tests {
);
let cwd = tmp.path().to_string_lossy().into_owned();
let session = SessionId::new().to_string();
- for event in ["session-start", "session-end"] {
+ for event in ["session-start", "user-prompt", "session-end"] {
process(
&state,
session_envelope(event, &session, &cwd),
@@ -6694,7 +6908,7 @@ mod tests {
.await;
let cwd = tmp.path().to_string_lossy().into_owned();
let session = SessionId::new().to_string();
- let items = ["session-start", "session-end"]
+ let items = ["session-start", "user-prompt", "session-end"]
.into_iter()
.map(|event| HookBatchItem {
url: format!(
@@ -7852,6 +8066,89 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn lifecycle_only_receiver_returns_its_startup_handoff() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let cwd = tmp.path().to_string_lossy().into_owned();
+ let handoff_id = state
+ .writer
+ .insert_handoff(NewHandoff {
+ workspace_id: state.workspace_id,
+ project_id: state.project_id,
+ from_session_id: None,
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: None,
+ summary: "REAL-WORK-MARKER".into(),
+ open_questions: vec!["what remains?".into()],
+ next_steps: vec!["continue the real work".into()],
+ files_touched: vec!["src/main.rs".into()],
+ owner_user: None,
+ })
+ .await
+ .unwrap();
+ let query = |session_id: &str| HandoffQuery {
+ agent: Some("codex".into()),
+ cwd: Some(cwd.clone()),
+ workspace: Some("default".into()),
+ project: Some("scratch".into()),
+ project_strategy: None,
+ briefing: None,
+ briefing_budget: None,
+ managed_run: None,
+ session_id: Some(session_id.into()),
+ };
+ let empty_sid = "empty-native-session";
+ let rendered = fetch_and_accept_handoff(&state, query(empty_sid), None, Vec::new())
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(rendered.contains("REAL-WORK-MARKER"));
+ let accepted = state
+ .reader
+ .handoff_by_id(handoff_id)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ accepted.accepted_by_session,
+ Some(resolve_native_session_id(empty_sid))
+ );
+
+ for event in ["session-start", "session-end"] {
+ let env = HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: event.into(),
+ agent: Some("codex".into()),
+ cwd: Some(cwd.clone()),
+ workspace: Some("default".into()),
+ project: Some("scratch".into()),
+ ..Default::default()
+ },
+ serde_json::json!({ "session_id": empty_sid, "cwd": cwd }),
+ );
+ process(&state, env, None, Vec::new()).await.unwrap();
+ }
+
+ let reopened = state
+ .reader
+ .handoff_by_id(handoff_id)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(reopened.state, ai_memory_core::HandoffState::Open);
+ assert!(reopened.accepted_by.is_none());
+ assert!(reopened.accepted_at.is_none());
+ assert!(reopened.accepted_by_session.is_none());
+ let next =
+ fetch_and_accept_handoff(&state, query("next-substantive-session"), None, Vec::new())
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(next.contains("REAL-WORK-MARKER"));
+ }
+
#[tokio::test]
async fn managed_session_start_delivers_ledger_and_pending_handoff() {
use ai_memory_core::{NewWorkstreamEvent, WorkstreamEventKind};
diff --git a/crates/ai-memory-store/migrations/V48__handoff_receiver_index.sql b/crates/ai-memory-store/migrations/V48__handoff_receiver_index.sql
new file mode 100644
index 00000000..00b053f9
--- /dev/null
+++ b/crates/ai-memory-store/migrations/V48__handoff_receiver_index.sql
@@ -0,0 +1,6 @@
+-- Session-bound startup claims are released when the exact receiver exits
+-- without substantive work. Both the duplicate-claim guard and release path
+-- look up accepted rows by receiver session.
+CREATE INDEX idx_handoffs_accepted_session
+ ON handoffs (accepted_by_session, accepted_at DESC)
+ WHERE state = 'accepted' AND accepted_by_session IS NOT NULL;
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 54dbf29b..606d4875 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -43,8 +43,8 @@ pub use decay::{
pub use error::{StoreError, StoreResult};
pub use maintenance::MaintenanceJob;
pub use ops::{
- DeleteWorkspaceSummary, EmbeddingWrite, IngestObservationOutcome, MoveSummary, PurgeSummary,
- ReorgSummary,
+ DeleteWorkspaceSummary, EmbeddingWrite, IngestObservationOutcome, LifecycleOnlyEndOutcome,
+ MoveSummary, PurgeSummary, ReorgSummary,
};
pub use reader::{
ActivityWindow, AgentSessionCount, AutoImproveCandidateSession, BriefPageBody, BriefingPage,
@@ -5020,7 +5020,11 @@ mod tests {
let first_handoff = store.writer.insert_handoff(insert_handoff()).await.unwrap();
let accepted = store
.writer
- .accept_startup_context(Some(acceptance(first_handoff, None)), Some(run.run_id))
+ .accept_startup_context(
+ Some(acceptance(first_handoff, None)),
+ Some(run.run_id),
+ None,
+ )
.await
.unwrap();
assert_eq!(
@@ -5042,7 +5046,11 @@ mod tests {
let second_handoff = store.writer.insert_handoff(insert_handoff()).await.unwrap();
let rejected = store
.writer
- .accept_startup_context(Some(acceptance(second_handoff, None)), Some(run.run_id))
+ .accept_startup_context(
+ Some(acceptance(second_handoff, None)),
+ Some(run.run_id),
+ None,
+ )
.await
.unwrap();
assert_eq!(
@@ -5107,6 +5115,7 @@ mod tests {
.accept_startup_context(
Some(acceptance(selected_auto, Some("/repo/api/src".into()))),
Some(run.run_id),
+ None,
)
.await
.unwrap();
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index 12bdfbd2..6eb1f676 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -35,6 +35,19 @@ pub enum IngestObservationOutcome {
AlreadyComplete,
}
+/// Result of conditionally ending a session whose persisted observations are
+/// all lifecycle boundaries.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum LifecycleOnlyEndOutcome {
+ /// The session was still boundary-only inside the writer transaction.
+ Ended {
+ /// Startup handoff returned to the open pool, when one was claimed.
+ reopened_handoff: Option<HandoffId>,
+ },
+ /// Substantive work arrived before the atomic end check.
+ Substantive,
+}
+
/// Summary returned by [`purge_project`] and exposed via
/// [`crate::writer::WriterHandle::purge_project`].
#[derive(Debug, Default, Clone)]
@@ -852,6 +865,38 @@ fn refresh_incoming_links_for_path(
/// Begin (or re-affirm) a session row keyed on the caller-supplied id.
/// Idempotent: a second call with the same id leaves the row untouched.
pub fn begin_session(conn: &mut Connection, session: &NewSession) -> StoreResult<()> {
+ begin_session_row(conn, session)
+}
+
+pub(crate) fn begin_session_in_transaction(
+ tx: &Transaction<'_>,
+ session: &NewSession,
+) -> StoreResult<()> {
+ begin_session_row(tx, session)?;
+ let matches_receiver: bool = tx.query_row(
+ "SELECT EXISTS( \
+ SELECT 1 FROM sessions \
+ WHERE id = ?1 AND workspace_id = ?2 AND project_id = ?3 \
+ AND agent_kind = ?4 AND actor_user IS ?5 \
+ )",
+ params![
+ session.id.as_bytes(),
+ session.workspace_id.as_bytes(),
+ session.project_id.as_bytes(),
+ session.agent_kind.as_str(),
+ session.actor_user.as_deref(),
+ ],
+ |row| row.get(0),
+ )?;
+ if !matches_receiver {
+ return Err(StoreError::InvalidState(
+ "startup receiver id belongs to a different scope, agent, or operator".into(),
+ ));
+ }
+ Ok(())
+}
+
+fn begin_session_row(conn: &Connection, session: &NewSession) -> StoreResult<()> {
validate_identity_storage_key(session.actor_user.as_deref(), "session owner")?;
let now = Timestamp::now().as_microsecond();
let agent = session.agent_kind.as_str();
@@ -887,6 +932,68 @@ pub fn end_session(
end_session_row(conn, session_id, summary_page_id)
}
+/// Atomically end a lifecycle-only session and return its startup handoff to
+/// the open pool.
+///
+/// Only a handoff claimed by this exact receiver session is reopened. The
+/// compare-and-set protects a baton that has moved to any other state, while
+/// clearing all acceptance metadata makes a later claim indistinguishable
+/// from the original open row.
+pub fn end_lifecycle_only_session(
+ conn: &mut Connection,
+ session_id: &SessionId,
+) -> StoreResult<LifecycleOnlyEndOutcome> {
+ let tx = conn.transaction()?;
+ let has_substantive_observation: bool = tx.query_row(
+ "SELECT EXISTS( \
+ SELECT 1 FROM observations \
+ WHERE session_id = ?1 AND kind NOT IN ('session-start', 'session-end') \
+ )",
+ params![session_id.as_bytes()],
+ |row| row.get(0),
+ )?;
+ if has_substantive_observation {
+ return Ok(LifecycleOnlyEndOutcome::Substantive);
+ }
+ end_session_row(&tx, session_id, None)?;
+ let reopened: Option<(Vec<u8>, Vec<u8>, Vec<u8>)> = tx
+ .query_row(
+ "UPDATE handoffs \
+ SET state = 'open', accepted_by = NULL, accepted_at = NULL, \
+ accepted_by_session = NULL, accepted_by_user = NULL \
+ WHERE id = ( \
+ SELECT id FROM handoffs \
+ WHERE state = 'accepted' AND accepted_by_session = ?1 \
+ ORDER BY accepted_at DESC, created_at DESC LIMIT 1 \
+ ) AND state = 'accepted' AND accepted_by_session = ?1 \
+ RETURNING id, workspace_id, project_id",
+ params![session_id.as_bytes()],
+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
+ )
+ .optional()?;
+ let reopened = reopened
+ .map(|(id, workspace_id, project_id)| -> StoreResult<HandoffId> {
+ let handoff_id = HandoffId::from_slice(&id)?;
+ let workspace_id = WorkspaceId::from_slice(&workspace_id)?;
+ let project_id = ProjectId::from_slice(&project_id)?;
+ audit(
+ &tx,
+ "release_lifecycle_only_handoff",
+ Some(workspace_id.as_bytes()),
+ Some(project_id.as_bytes()),
+ None,
+ None,
+ Timestamp::now().as_microsecond(),
+ )?;
+ Ok(handoff_id)
+ })
+ .transpose()?;
+ tx.commit()?;
+ Ok(LifecycleOnlyEndOutcome::Ended {
+ reopened_handoff: reopened,
+ })
+}
+
fn end_session_row(
conn: &Connection,
session_id: &SessionId,
@@ -1712,6 +1819,51 @@ pub(crate) fn accept_handoff_in_transaction(
let now = Timestamp::now().as_microsecond();
let agent = accepting_agent.as_str();
let session: Option<&[u8]> = accepting_session.as_ref().map(|s| &s.as_bytes()[..]);
+ if let Some(accepting_session) = accepting_session {
+ let receiver: Option<(bool, bool)> = tx
+ .query_row(
+ "SELECT workspace_id = ?2 AND project_id = ?3 AND agent_kind = ?4, \
+ ended_at IS NULL \
+ FROM sessions WHERE id = ?1",
+ params![
+ accepting_session.as_bytes(),
+ workspace_id.as_bytes(),
+ project_id.as_bytes(),
+ accepting_agent.as_str(),
+ ],
+ |row| Ok((row.get(0)?, row.get(1)?)),
+ )
+ .optional()?;
+ let Some((matching_scope_and_agent, open)) = receiver else {
+ return Err(StoreError::InvalidState(
+ "handoff receiver session does not exist".into(),
+ ));
+ };
+ if !matching_scope_and_agent {
+ return Err(StoreError::InvalidState(
+ "handoff receiver session does not match the accepting scope and agent".into(),
+ ));
+ }
+ if !open {
+ return Err(StoreError::InvalidState(
+ "an ended session cannot accept a handoff".into(),
+ ));
+ }
+ let already_claimed: bool = tx.query_row(
+ "SELECT EXISTS( \
+ SELECT 1 FROM handoffs \
+ WHERE state = 'accepted' AND accepted_by_session = ?1 \
+ )",
+ params![accepting_session.as_bytes()],
+ |row| row.get(0),
+ )?;
+ if already_claimed {
+ // SessionStart can be retried. One receiver must never consume a
+ // second baton, or an empty end could return only one and strand
+ // the first accepted row.
+ return Ok(false);
+ }
+ }
let metadata = tx
.query_row(
"SELECT from_session_id IS NOT NULL, cwd, created_at, owner_user \
@@ -3516,6 +3668,179 @@ pub(crate) mod tests {
assert!(second.is_ok(), "double-accept must not error");
}
+ #[test]
+ fn lifecycle_only_receiver_releases_its_handoff_and_cannot_reclaim_after_end() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let receiver = SessionId::new();
+ begin_session(
+ &mut conn,
+ &NewSession {
+ id: receiver,
+ workspace_id: ws,
+ project_id: proj,
+ agent_kind: AgentKind::Codex,
+ cwd: Some("/repo".into()),
+ actor_user: None,
+ },
+ )
+ .unwrap();
+ let new_handoff = || NewHandoff {
+ workspace_id: ws,
+ project_id: proj,
+ from_session_id: None,
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: Some("/repo".into()),
+ summary: "real pending work".into(),
+ open_questions: vec![],
+ next_steps: vec![],
+ files_touched: vec![],
+ owner_user: None,
+ };
+ let handoff_id = insert_handoff(&mut conn, &new_handoff()).unwrap();
+ let mut claim = handoff_acceptance(handoff_id, ws, proj);
+ claim.accepting_session = Some(receiver);
+ assert!(accept_handoff(&mut conn, &claim).unwrap());
+ let second_handoff = insert_handoff(&mut conn, &new_handoff()).unwrap();
+ let mut duplicate_start = handoff_acceptance(second_handoff, ws, proj);
+ duplicate_start.accepting_session = Some(receiver);
+ assert!(
+ !accept_handoff(&mut conn, &duplicate_start).unwrap(),
+ "a repeated SessionStart must not consume a second handoff"
+ );
+
+ assert_eq!(
+ end_lifecycle_only_session(&mut conn, &receiver).unwrap(),
+ LifecycleOnlyEndOutcome::Ended {
+ reopened_handoff: Some(handoff_id)
+ }
+ );
+ let (state, accepted_by, accepted_at, accepted_session): (
+ String,
+ Option<String>,
+ Option<i64>,
+ Option<Vec<u8>>,
+ ) = conn
+ .query_row(
+ "SELECT state, accepted_by, accepted_at, accepted_by_session \
+ FROM handoffs WHERE id = ?1",
+ params![handoff_id.as_bytes()],
+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
+ )
+ .unwrap();
+ assert_eq!(state, "open");
+ assert!(accepted_by.is_none());
+ assert!(accepted_at.is_none());
+ assert!(accepted_session.is_none());
+ let (ended_at, summary_page): (Option<i64>, Option<Vec<u8>>) = conn
+ .query_row(
+ "SELECT ended_at, summary_page_id FROM sessions WHERE id = ?1",
+ params![receiver.as_bytes()],
+ |row| Ok((row.get(0)?, row.get(1)?)),
+ )
+ .unwrap();
+ assert!(ended_at.is_some());
+ assert!(summary_page.is_none());
+ assert_eq!(audit_row_for(&conn, "release_lifecycle_only_handoff").0, 1);
+ let second_state: String = conn
+ .query_row(
+ "SELECT state FROM handoffs WHERE id = ?1",
+ params![second_handoff.as_bytes()],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(second_state, "open");
+
+ let next_handoff = insert_handoff(&mut conn, &new_handoff()).unwrap();
+ let mut stale_claim = handoff_acceptance(next_handoff, ws, proj);
+ stale_claim.accepting_session = Some(receiver);
+ let error = accept_handoff(&mut conn, &stale_claim)
+ .expect_err("an out-of-order startup fetch must not bind to an ended session");
+ assert!(matches!(error, StoreError::InvalidState(_)));
+ let state: String = conn
+ .query_row(
+ "SELECT state FROM handoffs WHERE id = ?1",
+ params![next_handoff.as_bytes()],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(state, "open");
+ }
+
+ #[test]
+ fn lifecycle_only_end_compare_and_set_yields_to_substantive_observation() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let receiver = SessionId::new();
+ begin_session(
+ &mut conn,
+ &NewSession {
+ id: receiver,
+ workspace_id: ws,
+ project_id: proj,
+ agent_kind: AgentKind::Codex,
+ cwd: Some("/repo".into()),
+ actor_user: None,
+ },
+ )
+ .unwrap();
+ let handoff_id = insert_handoff(
+ &mut conn,
+ &NewHandoff {
+ workspace_id: ws,
+ project_id: proj,
+ from_session_id: None,
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: None,
+ summary: "continue".into(),
+ open_questions: vec![],
+ next_steps: vec![],
+ files_touched: vec![],
+ owner_user: None,
+ },
+ )
+ .unwrap();
+ let mut claim = handoff_acceptance(handoff_id, ws, proj);
+ claim.accepting_session = Some(receiver);
+ assert!(accept_handoff(&mut conn, &claim).unwrap());
+ insert_observation(
+ &mut conn,
+ &NewObservation {
+ session_id: receiver,
+ workspace_id: ws,
+ project_id: proj,
+ kind: ObservationKind::PreToolUse,
+ extension: None,
+ source_event: None,
+ title: "Read".into(),
+ body: "README.md".into(),
+ importance: 5,
+ },
+ )
+ .unwrap();
+
+ assert_eq!(
+ end_lifecycle_only_session(&mut conn, &receiver).unwrap(),
+ LifecycleOnlyEndOutcome::Substantive
+ );
+ let ended_at: Option<i64> = conn
+ .query_row(
+ "SELECT ended_at FROM sessions WHERE id = ?1",
+ params![receiver.as_bytes()],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert!(ended_at.is_none());
+ let state: String = conn
+ .query_row(
+ "SELECT state FROM handoffs WHERE id = ?1",
+ params![handoff_id.as_bytes()],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(state, "accepted");
+ }
+
#[test]
fn failed_auto_handoff_insert_rolls_back_same_cwd_expiration() {
let (_tmp, mut conn, ws, proj) = fresh_db();
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index 558d5f71..40535672 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -25,8 +25,8 @@ use crate::auto_improve::{
};
use crate::error::{StoreError, StoreResult};
use crate::ops::{
- self, DeleteWorkspaceSummary, EmbeddingWrite, IngestObservationOutcome, MoveSummary,
- PurgeSummary, ReorgSummary,
+ self, DeleteWorkspaceSummary, EmbeddingWrite, IngestObservationOutcome,
+ LifecycleOnlyEndOutcome, MoveSummary, PurgeSummary, ReorgSummary,
};
use crate::session_consolidation::SessionConsolidationJob;
use crate::users::{self, TOKEN_HASH_LEN};
@@ -111,6 +111,10 @@ pub(crate) enum WriteCmd {
handoff: NewHandoff,
reply: oneshot::Sender<StoreResult<HandoffId>>,
},
+ EndLifecycleOnlySession {
+ session_id: SessionId,
+ reply: oneshot::Sender<StoreResult<LifecycleOnlyEndOutcome>>,
+ },
SweepHollowProjects {
min_age_days: u32,
reply: oneshot::Sender<StoreResult<Vec<String>>>,
@@ -378,6 +382,7 @@ pub(crate) enum WriteCmd {
AcceptStartupContext {
handoff: Option<HandoffAcceptance>,
managed_run_id: Option<ManagedRunId>,
+ receiving_session: Option<NewSession>,
reply: oneshot::Sender<StoreResult<StartupContextAcceptance>>,
},
FinishWorkstreamRun {
@@ -574,6 +579,24 @@ impl WriterHandle {
rx.await.map_err(|_| StoreError::WriterClosed)?
}
+ /// Atomically end a lifecycle-only session and reopen the handoff claimed
+ /// by that exact receiver, if one exists.
+ ///
+ /// # Errors
+ /// Returns [`StoreError::WriterClosed`] or propagates SQL/state errors.
+ pub async fn end_lifecycle_only_session(
+ &self,
+ session_id: SessionId,
+ ) -> StoreResult<LifecycleOnlyEndOutcome> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::EndLifecycleOnlySession {
+ session_id,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
/// Delete hollow project rows (no data of any kind) older than
/// `min_age_days`; returns the deleted names. See
/// [`ops::sweep_hollow_projects`].
@@ -1510,11 +1533,13 @@ impl WriterHandle {
&self,
handoff: Option<HandoffAcceptance>,
managed_run_id: Option<ManagedRunId>,
+ receiving_session: Option<NewSession>,
) -> StoreResult<StartupContextAcceptance> {
let (tx, rx) = oneshot::channel();
self.send(WriteCmd::AcceptStartupContext {
handoff,
managed_run_id,
+ receiving_session,
reply: tx,
})
.await?;
@@ -1677,6 +1702,10 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
);
send_or_warn(reply, result, "end_session_with_handoff");
}
+ WriteCmd::EndLifecycleOnlySession { session_id, reply } => {
+ let result = ops::end_lifecycle_only_session(&mut conn, &session_id);
+ send_or_warn(reply, result, "end_lifecycle_only_session");
+ }
WriteCmd::SweepHollowProjects {
min_age_days,
reply,
@@ -2074,10 +2103,25 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
WriteCmd::AcceptStartupContext {
handoff,
managed_run_id,
+ receiving_session,
reply,
} => {
let result = (|| {
let tx = conn.transaction()?;
+ if let Some(session) = &receiving_session {
+ let matching_acceptance = handoff.as_ref().is_some_and(|acceptance| {
+ acceptance.accepting_session == Some(session.id)
+ && acceptance.workspace_id == session.workspace_id
+ && acceptance.project_id == session.project_id
+ && acceptance.accepting_agent == session.agent_kind
+ });
+ if !matching_acceptance {
+ return Err(StoreError::InvalidState(
+ "startup receiver session does not match its handoff claim".into(),
+ ));
+ }
+ ops::begin_session_in_transaction(&tx, session)?;
+ }
let managed_context_accepted = match managed_run_id {
Some(run_id) => {
crate::workstream::claim_context_in_transaction(&tx, run_id)?
diff --git a/docs/design-decisions.md b/docs/design-decisions.md
index b7dd342a..3074e889 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 — session end always writes a rule-based summary page + handoff regardless). 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; 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/mcp-install.md b/docs/mcp-install.md
index ed0c54f3..00ab15ab 100644
--- a/docs/mcp-install.md
+++ b/docs/mcp-install.md
@@ -547,8 +547,9 @@ The rendered hooks config looks like:
- Antigravity CLI does not expose a true session-end hook. `Stop` records a
stop observation only because it marks the end of one execution loop, not
the conversation. After the final turn, run
- `ai-memory finalize-session --agent antigravity-cli` to create the final
- summary and automatic handoff and to queue opt-in SessionEnd consolidation.
+ `ai-memory finalize-session --agent antigravity-cli` to close the session and,
+ when it contains substantive events, create the final summary and automatic
+ handoff and queue opt-in SessionEnd consolidation.
- `memory_handoff_begin` always creates an explicit manual handoff with no
`from_session_id` and `from_agent = other`; it is project-wide for cwd
matching but belongs to the creating operator by default. Pass `shared=true`
diff --git a/docs/prior-art-implementation-findings.md b/docs/prior-art-implementation-findings.md
index 280d372b..3fc296b6 100644
--- a/docs/prior-art-implementation-findings.md
+++ b/docs/prior-art-implementation-findings.md
@@ -315,7 +315,7 @@ These items previously drifted from the code. Their current status is:
| raw archive status | Fixed: docs distinguish reserved `raw/` files from implemented observation-FTS fallback. |
| scheduled maintenance | Fixed: docs describe default scheduled lint/sweep, opt-in embedding backfill, and the independent hollow-project cleanup. |
| procedural tier | Fixed: consolidation can classify procedural memory, auto-improvement can create or patch bounded `procedures/` pages, and retention preserves semantic/procedural tiers. |
-| SessionEnd consolidation | Fixed: SessionEnd always writes a deterministic page and handoff; opt-in LLM work uses a durable retry queue, while PreCompact/manual consolidation remain available. |
+| SessionEnd consolidation | Fixed: substantive SessionEnd processing writes a deterministic page and handoff; lifecycle-only sessions close without generated artifacts or LLM work and release their session-bound startup handoff. Opt-in LLM work uses a durable retry queue, while PreCompact/manual consolidation remain available. |
| batch embeddings | Fixed: code comments and status diagnostics now describe batch vector completeness as backfill-owned. |
## Implemented Roadmap Slice
diff --git a/docs/usage.md b/docs/usage.md
index e921ec83..26cb805d 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -83,7 +83,7 @@ at the managed ai-memory Agent Skills that carry detailed tool routing.
| "Where did we leave off?" | Existing handoff block, or `memory_handoff_accept` if no block exists | Resumes from the latest pending handoff. |
| "Save context for the next session" | `memory_handoff_begin` | Writes a terse session-end handoff with open questions and next steps. Do not use for status or briefing requests. |
| "Discard that handoff" / "I created a handoff by mistake" | `memory_handoff_cancel` | Marks an exact open handoff id expired before the next session can consume it. |
-| "Consolidate this session" | `memory_consolidate` | Manually runs LLM consolidation. 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; session end otherwise writes a rule-based summary page). 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. |
+| "Consolidate this session" | `memory_consolidate` | Manually runs LLM consolidation. 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. |
| "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`. |
diff --git a/hooks/cursor/session-start.sh b/hooks/cursor/session-start.sh
index 518362ad..9652eee6 100755
--- a/hooks/cursor/session-start.sh
+++ b/hooks/cursor/session-start.sh
@@ -14,8 +14,11 @@ SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
PAYLOAD=$(cat)
CWD=$(ai_memory_extract_cwd "$PAYLOAD")
QS=$(ai_memory_marker_qs "$CWD")
+SESSION_ID=$(ai_memory_extract_session_id "$PAYLOAD")
+SESSION_QS=""
+[ -n "$SESSION_ID" ] && SESSION_QS="&session_id=$(ai_memory_url_encode "$SESSION_ID")"
printf '%s' "$PAYLOAD" \
| ai_memory_post_hook "$SERVER/hook?event=session-start&agent=cursor${QS}" >/dev/null 2>&1 || true
-ai_memory_get_handoff "$SERVER/handoff?agent=cursor${QS}" 2>/dev/null || true
+ai_memory_get_handoff "$SERVER/handoff?agent=cursor${QS}${SESSION_QS}" 2>/dev/null || true
exit 0
diff --git a/hooks/devin/session-start.sh b/hooks/devin/session-start.sh
index 3ea0e739..d3d8021c 100644
--- a/hooks/devin/session-start.sh
+++ b/hooks/devin/session-start.sh
@@ -17,7 +17,7 @@ SID_QS=$(ai_memory_session_id_qs devin session-start)
printf '%s' "$PAYLOAD" \
| ai_memory_post_hook "$SERVER/hook?event=session-start&agent=devin${QS}${SID_QS}" >/dev/null 2>&1 || true
-HANDOFF=$(ai_memory_get_handoff "$SERVER/handoff?agent=devin${QS}" 2>/dev/null || true)
+HANDOFF=$(ai_memory_get_handoff "$SERVER/handoff?agent=devin${QS}${SID_QS}" 2>/dev/null || true)
if [ -n "$HANDOFF" ]; then
printf '{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":%s}}\n' \
"$(printf '%s' "$HANDOFF" | ai_memory_json_string)"
diff --git a/hooks/gemini-cli/session-start.sh b/hooks/gemini-cli/session-start.sh
index 7543f319..9520ad06 100755
--- a/hooks/gemini-cli/session-start.sh
+++ b/hooks/gemini-cli/session-start.sh
@@ -14,8 +14,11 @@ SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
PAYLOAD=$(cat)
CWD=$(ai_memory_extract_cwd "$PAYLOAD")
QS=$(ai_memory_marker_qs "$CWD")
+SESSION_ID=$(ai_memory_extract_session_id "$PAYLOAD")
+SESSION_QS=""
+[ -n "$SESSION_ID" ] && SESSION_QS="&session_id=$(ai_memory_url_encode "$SESSION_ID")"
printf '%s' "$PAYLOAD" \
| ai_memory_post_hook "$SERVER/hook?event=session-start&agent=gemini-cli${QS}" >/dev/null 2>&1 || true
-ai_memory_get_handoff "$SERVER/handoff?agent=gemini-cli${QS}" 2>/dev/null || true
+ai_memory_get_handoff "$SERVER/handoff?agent=gemini-cli${QS}${SESSION_QS}" 2>/dev/null || true
exit 0